Posts

Showing posts from April, 2015

c++ - Insufficent Memory -

i new open cv , have been working on project on gesture recognition. implementing pca , while calculating eigen vectors. stumbled upon insufficient memory error. 2d arrays used dynamically allocated. still same error creeps up. here code: void initialization() { long int nrows=15000, ncolumns=20; int i,j; cov = (float**) malloc(nrows * sizeof(float *)); for(i = 0; < nrows; i++) { cov[i] = (float*) malloc(ncolumns * sizeof(float)); } matrix = (int**) malloc(15000 * sizeof(int *)); for(i = 0; < nrows; i++) { matrix[i] = (int*) malloc(20 * sizeof(int)); } matrix1 = (int**) malloc(15000* sizeof(int *)); for(i = 0; < nrows; i++) { matrix1[i] = (int*) malloc(20 * sizeof(int)); } ..... } void cal_eigen() { //mat original matrix cou

python - How to generate reports using HtmlTestRunner for unittests which invlove xml-rpc communication? -

if unittest invlove single xml-rpc requests/response between xmlrpc client/server, works fine , generates report on 1 end if scenario scales more 1 xmlrpc request, report not getting generated. here goes code snippet template: on 1 machine abc have, class abc(): def add(): ....... def subtract(): ....... class machineabctest(unittest.testcase): def test_abc(self): x1 = abc_client.multiply() #method resides in machinexyztest y1 = abc_client.divide() #method resides in machinexyztest suite = unittest.testloader().loadtestsfromtestcase(machineabctest) runner = htmltestrunner.htmltestrunner(stream=fp, verbosity=2) runner.run(suite) class serverthread(threading.thread): def __init__(self): threading.thread.__init__(self) self.abc_server = simplethreadedxmlrpcserver(("xxx.xxx.xxx.1", 8000)) self.abc_server.register_instance(abc()) #methods add & su

playframework - Play framework 2, how to use execution context in Java? -

the official documents describe how use in scala. http://www.playframework.com/documentation/2.1.0/threadpools . future { // blocking or expensive code here }(contexts.myexecutioncontext) i can excutioncontext like: executioncontext myexecutioncontext = akka.system().dispatchers().lookup("my-context"); but how add in code blow? return async( future(new callable<string>() { public string call() { return dosth(); }).map(new f.function<string,result>() { public result apply(string i) { return ok(i); } }) i think answer should be: executioncontext myexecutioncontext = akka.system().dispatchers().lookup("my-context"); return async( akka.aspromise(futures.future(new callable<string>() { public string call() { return dosth(); } }, myexecutioncontext)).map(new f.function<

Reading text files into an array in C -

just got question regards, when read lines of text text file how separate words , store them array. for example if have 2 lines of text in text file looks this: 1005; andycool; andy; anderson; 23; la 1006; johncool; john; anderson; 23; la how split them based on ';' . , store them in 2d array. sorry haven't started coding yet paste here cheers ... use strsep function: char* token; char* line; /* assume line loaded file */; if( line != null ) { while ((token = strsep(&line, ";")) != null) { /* token points current extracted string, use fill array */ } }

android - Custom Seekbar with masking effect with two drawables? -

Image
i using custom seekbar show graph. had done till this. showing graph applying background drawable seekbar. problem is, need set blue 1 progress drawable , need set background of seekbar red graph. when progress happens thumb moves on red area thumb passed should changed blue color masking effect. can 1 tell best possible way this. pictures shown below after reading questions , answers hope should scenario thing done... 1.create 2 graphs per logic. 2.generate 2 drwables particular bitmaps.... drawable g_bg = new bitmapdrawable(red graph bitmap); drawable g_pg = new bitmapdrawable(blue graph bitmap); 3.and customize seek bar using layer list created through java code. clipdrawable c=new clipdrawable(g_pg, gravity.left,clipdrawable.horizontal); layerdrawable ld =new layerdrawable (new drawable[]{g_bg,c}); 4.apply layer list seekbar. graphbar.setprogressdrawable(ld); this should work wanted....thanksss

user interface - Resizeable Legend in Matlab GUI or Legend Scroll Bar -

Image
in matlab have gui analyses , plots data on plot in main figure of gui. have plot lot of different data sets though , have 2 main problems: i cannot set fixed size area legend constructed in i cannot work out how make legend text , box scale when gui full screened one solution thinking scroll bar in legend, possible? image below highlights problem: here solution scale legend whatever scaling factor desire: close all; % generate data n = 10; t = 10; x = rand(t, n); % how scale xlegscale = 0.5; ylegscale = 0.5; % plot data labels = arrayfun(@(n){sprintf('legend entry line %i', n)}, 1:n); plot(x, 'linewidth', 2); hleg = legend(labels); % figure out new legend width / height, including little fudge legpos = get(hleg, 'position'); widthfudgefactor = 0.1; legposnew = legpos; legposnew(3:4) = legposnew(3:4) .* [xlegscale ylegscale]; legposnew(3) = legposnew(3) * (1 + widthfudgefactor); % create new axes matches legend axes , copy legend % c

objective c - [iOS][Background] updating map pins | drawing lines -

hy :) i trying update in background position of device (iphone) , works simulator http://grab.by/melq (the annotations added in background). but when testing iphone not work, have got line between last position (before being in background) , position when becomes active. what coding ? i made test of making list when app in background , when application becomes active again load list of positions recorded. (work simulator) - (void)handleaddlocations { nslog(@"%s | %@", __pretty_function__, self.locationbackgroundlist); if ([self.locationbackgroundlist count] > 0) { (cllocation *backgroundlocation in self.locationbackgroundlist) { if (yes){ locannotation* annotation = [[locannotation alloc] initwithcoordinate:backgroundlocation.coordinate]; nslog(@"%s %@", __pretty_function__, [annotation description]); [self.mapview addannotation:annotation]

rubygems - How will rails 4 affect my current application? -

i new rails , upgrade rails 4. @ same time have been working on small beta rails 3.2 past year.... if upgrade current app affected or mess up. want upgrade don't want current beta encounter problems. how upgrading rails 4 affect current application. breaking news: released new free rails cast upgrading rails4. http://railscasts.com/episodes/415-upgrading-to-rails-4 a tip. can use gem check how compatible environment rails4. https://github.com/alindeman/rails4_upgrade

How can I detect whether or not I am in powershell from a command line? -

i creating standard windows bat/cmd file , want make if statement check whether or not cmd file run powershell. how can that? edit: underlying problem test.cmd "a=b" results in %1==a=b when run cmd %1==a , %2==b when run powershell. script run old windows command line script in both cases, checking get-childitem yield error. one way, see process name is, , check attributes: title=test tasklist /v /fo csv | findstr /i "test" as long use unique name in place of test, there should little room error. you like: "cmd.exe","15144","console","1","3,284 k","running","gncid6101\athomsfere","0:00:00","test" when ran above code bat file, output was: "powershell.exe","7396","console","1","50,972 k","running","gncid6101\athomsfere","0:00:00","

javascript - Dynamically display User Input as tool-tip in Highcharts -

i want take 12 inputs user using multiple areas in popup dialog box.i want these inputs shown tool-tips multiple points of graph http://www.highcharts.com/demo/line-labels whichever examples have come across till don't mention how this.does have idea how implement tooltips using text-area input given user ??? you can use tooltip formatter option of chart render custom tooltip each point of graph. in example every point corresponding value of nth input using eq selector , use value in tooltip. the code this: tooltip: { formatter: function() { var index = datavalues.indexof(this.y); var comment=$("input:eq("+(index)+")").val() return 'the value <b>'+ this.x + '</b> <b>'+ this.y +'</b> -->'+comment; } }, here working fiddle: http://jsfiddle.net/irvindominin/rbenu/1/ obviously can change logic according needs.

jquery - Remove '|' special character from a string -

my question may find simple, not getting right. how remove "|" string far have used following not working <div class="inner"> | abcd || </div> var txt=divvar.html(); 1) txt=txt.remove("|"); 2) txt=txt.replace (/|/g, ''); you have escape '|' character: txt=txt.replace (/\|/g, '');

ComboBox in Telerik.UI.Xaml.Controls.Grid.RadDataGrid -

windows 8 visual studio 2012 express simple xaml: <telerik:raddatagrid itemssource="{binding productssource}" autogeneratecolumns="false"> <telerik:raddatagrid.columns> <telerik:datagridtemplatecolumn header="whatever"> <telerik:datagridtemplatecolumn.cellcontenttemplate> <datatemplate> <combobox> <comboboxitem>one</comboboxitem> <comboboxitem>two</comboboxitem> <comboboxitem>three</comboboxitem> </combobox> </datatemplate> </telerik:datagridtemplatecolumn.cellcontenttemplate> </telerik:datagridtemplatecolumn> </telerik:raddatagrid.columns> </telerik:raddatagrid> the binding source there populate grid something. in real app use it. problem: whenever s

c++ - In-class initialization of static data members -

in c++, static members may not initialized in class body these exceptions: static members of const integral type can be static members of constexpr literal type must be can explain why these exceptions? also, holds: even if const static data member initialized in class body, member ordinarily should defined outside class definition. this never understood @ all. what's point of definition? just trying intuitions here. why can there initializer in class definition? concerning 2 exceptions const , constexpr static data members: [class.static.data]/3 [ note: in both these cases, member may appear in constant expressions. — end note ] i.e. initializer, may use them in constant expressions, e.g. struct s { static std::size_t const len = 10; int arr[len]; }; std::size_t const s::len; if len wasn't initialized in class definition, compiler couldn't know value in next line define length of arr . one argue allowing

java - Calling Soap webservice from android -

i using below process, 1)create string template soap request , substitute user-supplied values @ runtime in template create valid request. 2) wrap string in stringentity , set content type text/xml 3) set entity in soap request. and of httppost posting request, i using demo webservice w3schools.com url---> http://www.w3schools.com/webservices/tempconvert.asmx what have tried is, httppost httppost = new httppost("http://www.w3schools.com/webservices/tempconvert.asmx"); stringentity se; try { soaprequestxml="<soapenv:envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\"><soapenv:header/><soapenv:body><tem:celsiustofahrenheit><!--optional:--><tem:celsius>30</tem:celsius></tem:celsiustofahrenheit></soapenv:body></soapenv:envelope>"; log.d("request ", soa

android - Extract Notification Pending Intent Content for Accessibility -

i'm working on accessibility features android application, 1 of announce user notifications. using following standard code, can access notification information: @override public void onaccessibilityevent(final accessibilityevent event) { final notification not = (notification) event.getparcelabledata(); final charsequence tick = not.tickertext; final pendingintent pi = not.contentintent; but here i'm stuck @ how can extract information pendingintent establish, example, activity (if any) points at. i can establish originator, using further standard code of: final string packagename = event.getpackagename().tostring() this fine in cases, many notifications google services framework or android system , therefore pendingintent information give further clues - example of gtalk, under generic package name of google services framework. i've read many related posts , including how action pending intent , can't work out how access info

Open Facebook Place's Page from Android App -

i'm trying open app page on facebook users can it i followed this solution, can't seem find way access pages through facebook's scheme mechanism, using solution code, page id open page in facebook's android app, button missing, , subscribing page fails. found answer: public static intent getopenfacebookintent(context context) { try { //context.getpackagemanager().getpackageinfo("com.facebook.katana", 0); return new intent(intent.action_view, uri.parse("fb://page/576525422362966")); } catch (exception e) { return new intent(intent.action_view, uri.parse("https://www.facebook.com/576525422362966")); } }

servlets - Google Chart - Populate with JSON -

i have been trying fill google chart dynamicly, example: https://developers.google.com/chart/interactive/docs/php_example i'm using dependency datatable class , others: <dependency> <groupid>com.google.visualization</groupid> <artifactid>visualization-datasource</artifactid> <version>1.1.1</version> </dependency> this api datatable class: https://developers.google.com/chart/interactive/docs/dev/dsl_javadocs/com/google/visualization/datasource/datatable/datatable i'm using java httpservlet contains code (example) populate datatable: datatable datatable = new datatable(); datatable.addcolumn(new columndescription("uur", valuetype.text, "uur")); datatable.addcolumn(new columndescription("aantal", valuetype.number, "aantal spellen")); try { datatable.addrowfromvalues("1", 5, true); datatable.addrowfromvalues("2", 9, true); datatab

ios - NSInputStream send NSStreamEventEndEncountered after Facebook connexion -

i use socketio project on ios app connect node.js server , works great until choose connect facebook. when connect facebook send data server , answer data "user connected, user created in database" etc. , after that, nsinputstream seems @ 0 , connexion closed. don't know do, spent 14 hours on , still issue... can me ? edit: looks problem in srwebsocket.m line 1462 for more details added log : case nsstreameventhasbytesavailable: { srfastlog(@"nsstreameventhasbytesavailable %@", astream); const int buffersize = 2048; uint8_t buffer[buffersize]; while (_inputstream.hasbytesavailable) { int bytes_read = [_inputstream read:buffer maxlength:buffersize]; dispatch_async(dispatch_get_main_queue(), ^{ nslog(@"bytes_read = %i", bytes_read); }); if (bytes_read > 0) { [_readbuffer appe

c# - JQuery MVC collection name attributes -

i have table, , i've dynamically added / removed rows it. table contains fields posted collection mvc. in scenario updating table jquery means collections contain incomplete collections example ... function add() { $.ajax({ url: "getrow", type: 'post', datatype: 'html', timeout: 30000, data: { rowindex: otherrows.length, "item.property1": $("option:selected", dropdown).text(), "item.property2": $("option:selected", dropdown).val() }, success: function (result) { var newrow = $(result); tablebody.append(newrow); } }); } this function makes ajax call go mvc action result returns result of row @ given index , additionally sets default values drop down on page. now lets assume have similar function called "delete" i

Using Icon Fonts as Markers in Google Maps V3 -

i wondering whether possible use icon font icons (e.g. font awesome) markers in google maps v3 replace default marker. show/insert them in html or php document code marker be: <i class="icon-map-marker"></i> here's attempt @ same thing (using "markerwithlabel" utility library) before realised nathan did same more elegantly above: http://jsfiddle.net/f3xchecf/ function initialize() { var mylatlng = new google.maps.latlng( 50, 50 ), myoptions = { zoom: 4, center: mylatlng, maptypeid: google.maps.maptypeid.roadmap }, map = new google.maps.map( document.getelementbyid( 'map-canvas' ), myoptions ), marker = new markerwithlabel({ position: mylatlng, draggable: true, raiseondrag: true, icon: ' ', map: map, labelcontent: '<i class="fa fa-send fa-3x" style="color:rgba(153,102,102,0.8);&q

io - C: Logical error in scanning input -

i have following implementation of reading character matrix , printing back. works fine, when give matrix it, waits character , outputs matrix properly. how can fix not need input character? sample input 3 4 0001 0110 1110 sample output 0001 0110 1110 my code #include <stdio.h> #include <stdlib.h> int main() { int n, m; /* n, m - dimensions of matrix */ int i, j; /* i, j - iterators */ char **matrix; /* matrix - matrix input */ scanf ("%d %d\n", &n, &m); matrix = (char **) malloc (sizeof (char *) * n); (i = 0; < n; ++i) { matrix[i] = (char *) malloc (sizeof (char) * m); } (i = 0; < n; ++i) { (j = 0; j < m; ++j) { scanf ("%c ", &matrix[i][j]); } } (i = 0; < n; ++i) { (j = 0; j < m; ++j) { printf ("%c", matrix[i][j]); } printf ("\n"); } } thanks in a

c++ - Linux, share a buffer with another program in fork() -

Image
i have client/server model each client can send task server - called task requesting. this base simple distributed-computing library after. " in other words, if ordinary application processes array of independent elements, in data-parallel model, each processor assigned process part of array. support data-parallel computing, core library should divide tasks parts, transfer task data local memory of particular cpu, run task on cpu, transfer results caller, , provide ability request global data caller. " a task binary (std::vector uint8_t) , payload (std::vector uint8_t). a binary compiled task / application. a payload optional data serialized uint8_t. so simply: class cgridtask { public: ... bool run (); private: std::vector<uint8_t> m_vbinary; std::vector<uint8_t> m_vpayload; uint32_t m_uiuniqueid; ... } the pseudo-diagram sh

installation - Unable to create a new android project -

Image
i used install existing ide , adding sdk location it. wanna set on different pc. have seen this post, seemed quite easy me set environment. downloaded adt bundle here , followed these 2 steps: unpack zip file (named adt-bundle-.zip) , save appropriate location, such “development” directory in home directory. open adt-bundle-/eclipse/ directory , launch eclipse. so did these 2 steps. when launch eclipse , clicked on new android project, gives me following error message shown in below picture. so, referred this post , still problem persists , error window opens. can 1 please tell me why happens , suggest me avoid error? when check in preferences--> android , result below image.

android - how to transfer the curl command to http post request -

i using facebook object api upload images facebook staging service. api document here http://developers.facebook.com/docs/opengraph/using-object-api/ in doucement, uses curl upload image: curl -x post https://graph.facebook.com/me/staging_resources -f file=@images/prawn-curry-1.jpg -f access_token=$user_access_token how can achieve same function using http post request in android app? thanks lot! string uri = "https://graph.facebook.com/me/staging_resources"; httpresponse response = null; try { httpclient client = new defaulthttpclient(); httppost post = new httppost(uri); multipartentity postentity = new multipartentity(); string picpath = (uri.parse(picuristr)).getpath(); file file = new file("/data/local/tmp/images.jpg"); postentity.addpart("file", new filebody(file, "image/jpeg")); postentity.addpart("access_token", new stringbody("your access token string here"));

php form validation using prerequisite -

i trying validate fields in form. working 2 fields, "address" , "state", "address" , "state" field not compulsory if value entered "address" field "state" field (which selection list) automatically becomes compulsory. unsure on how code right if condition. here have started on: <?php if (isset($_post["submit"])) { $address = $_post["address"]; $address = trim($address); $lengtha = strlen($address); $post = $_post["post"]; $state = $_post["state"]; if ($lengtha > 1) { ?> <form method="post" action="<?php echo $_server["php_self"];?>" id="custinfo" > <table> <tr> <td><label for="custid">customer id (integer value): </label></td> <td><input type="text" id="custid" name="custid" value="<?php echo $temp ?>" size=

timezone - Problems with PHP time zone wrongly set -

i have problem php not reflecting correctly actual time, result server's scripts 5 hours in future. if run in thecommand line got. (centos5) .. [root@server ~]# date sat may 4 11:20:17 cdt 2013 which correct (im mexico , server has correct time zone , time set), how ever doing in php get... [root@server ~]# php -r 'echo gmdate("d, d m y h:i:s e")."\n";' sat, 04 may 2013 16:18:45 utc as can see time hours in future, , php.ini supposed have correct time zone defined. [date] ; defines default timezone used date functions date.timezone = america/mexico_city so can problem here? gmdate() returns time according gmt (greenwich mean time) (although not same) used interchangeably utc. said right you're in cdt 5 hours behind utc (because daylight savings time in effect). if want scripts generate datetime strings reflect time zone set in php.ini file should use date() function. better yet, start using datetime library.

windows - How to setup SAPI with Visual C++ 2010 express? -

i need know how can setup sapi (windows speech api) visual c++ 2010 express. got know windows 7 comes built in sapi libs, , using windows 7. however, downloaded sapi 5.1 in case needed. ms instructions setting sapi vs pretty old, didn't work me. if browse previous questions, may notice how have struggled. please kind enough teach me how setup vs 2010 express, because need apply settings qt , proceed final year project. please help! well know. took code previous question, , removed atl stuff (atl not supported on visual studio express 2010). left this #include <windows.h> #include <sapi.h> #include <iostream> using namespace std; int main(int argc, char* argv[]) { cout << "hello" << endl; ispvoice * pvoice = null; if (failed(::coinitialize(null))) return false; hresult hr = cocreateinstance(clsid_spvoice, null, clsctx_all, iid_ispvoice, (void **)&pvoice); if( succeeded( hr ) ) {

c++ - rvalue or lvalue (const) reference parameter -

i want pass parameter(s) (of concrete type, int ) member function r- or l- value (const) reference. solution is: #include <type_traits> #include <utility> struct f { using desired_parameter_type = int; template< typename x, typename = typename std::enable_if< std::is_same< typename std::decay< x >::type, desired_parameter_type >::value >::type > void operator () (x && x) const { // or static_assert(std::is_same< typename std::decay< x >::type, desired_parameter_type >::value, ""); std::forward< x >(x); // useful } }; another exaple here http://pastebin.com/9kghmsvc . but verbose. how in simpler way? maybe should use superposition of std::remove_reference , std::remove_const instead of std::decay , there simplification here. if understand question correctly, wish have single function parameter either rvalue reference (in case rvalue provided) or lvalue ref

php - make curl get the final url and use it for another function -

i have url variables example : http:// remotesite.com/index1.php?option=com_lsh&view=lsh&event_id=149274&tid=372536&channel=0 this url redirect http://remotesite.com/static/popups/xxxxxxxxxxx.html xxxxxxxxxxx variables 1st link, event_id=149274, tid=372536, channel=0 then xxxxxxxxxxx = 1492743725360 , link : http://remotesite.com/static/popups/1492743725360.html how link automatically in php link http:// remotesite.com/index1.php?option=com_lsh&view=lsh&event_id=149274&tid=372536&channel=0 then use curl function source code of 1492743725360.html using : <?php //get url $url = "http:// remotesite.com/static/popups/1492743725360.html"; //get html of url function get_data($url) { $ch = curl_init(); $timeout = 5; //$useragent = "mozilla/5.0 (windows; u; windows nt 5.1; en-us)applewebkit/525.13 (khtml, gecko) chrome/0.x.y.z safari/525.13."; $useragent = "ie 7 –

arm - Raspberry Pi: Embedded Programming Exercise, Getting Started -

first, following tutorial here ( http://www.cl.cam.ac.uk/projects/raspberrypi/tutorials/os/ ). in first exercise learn addressing gpio pin responsible turning on green okay led. have rev c of raspberry pi knowledge uses broadcom (bcm2835) micro processor has following datasheet peripherals: ( http://www.cl.cam.ac.uk/projects/raspberrypi/tutorials/os/downloads/soc-peripherals.pdf ). i have read pages 89 through 104 of data sheet still lost. program provided author not seem run cross compiler build chain provided. striping comments out of source provided author have: .section .init .global _start _start: ldr r0, =0x20200000 /* enable output on 16th pin */ mov r1, #1 lsl r1, #18 str r1, [r0, #4] /* turn pin off turn led light on */ mov r1,#1 lsl r1,#16 str r1, [r0, #40] loop$: /* keep system running */ b loop$ where stuck is, in data sheet see nothing address 0x20200000. starting on page 91 in table 6-2 see tables describe first 32 bits. , in table 6-1

iphone - Can't quit (ending match) in Game Center -

i'm working on turn based ios game using game center , right have test account participating in 6 games in game center, every time try quit 1 swiping on (which should end game because test account 1 in it) removes game table split second , replaces , doesn't quit. here playerquitformatch function: // handle players leaving match in , out of turn. - (void)turnbasedmatchmakerviewcontroller:(gkturnbasedmatchmakerviewcontroller *)viewcontroller playerquitformatch:(gkturnbasedmatch *)match { // if player current participant, remove them next participants array. if ([match.currentparticipant.playerid isequaltostring:gklocalplayer.localplayer.playerid]) { nsmutablearray* nextparticipants = [nsmutablearray arraywitharray:[match participants]]; [nextparticipants removeobjectidenticalto:[match currentparticipant]]; // if last player, end match because empty. if ([nextparticipants count] == 0) {

javascript - jQuery Ajax PUT not firing -

the following ajax works advertised in chrome. http put used trigger insertion of object restful api. $.ajax({ type: "put", url: "/ajax/rest/team/create/", datatype: "json", processdata: false, data: json.stringify(teamobject), success: function (response) { teamobject = response.object; } }); i note jquery api docs helpfully tell me put , delete may work not guaranteed in browsers. such problem. how restful api supposed implemented on client side problem this? edit: firebug tells me ff indeed issuing put, unknown reason it's dying before getting server. repeat, works fine in chrome. edit: fiddler doesn't see ff attempt @ all. :( i got following work. var payload = json.stringify(teamobject) synchttp('/ajax/rest/team/create/', 'put', payload); function synchttp(url,method,payload) {

java - New to HashMap : how can I sort it? -

so have hashmap looking : hashmap<movie, float> movies; it contains movies global ratings floats , , want sort movies best worst. i had in collections.sort() have no idea if can it... it not possible sort hashmap. if need sorted map take @ treemap . what adding rating value movie class , let implement comparable ? public class movie implements comparable<movie> { private float rating; public movie(float rating) { this.rating = rating; } public float getrating() { return rating; } public int compareto(movie param) { return param.getrating().compareto(rating); } @override public string tostring() { return string.valueof(rating); } } then can use movie class this: public static void main(string[] args) { set<movie> movies = new hashset<movie>(); movies.add(new movie(0.6f)); movies.add(new movie(0.5f)); movies.add(new movie(0.7f)); movies.a

Creating a vector of strings : C++ -

i trying create vector should input strings (white space included) until user enters '!' . below code : #include <iostream> #include <vector> #include <string> #include <iterator> using namespace std; int main() { char buffer[100]; string temp; vector <string> vec; while(1)//shows segmentation fault error while running, //compiles succesfully { cout << "enter string : "; cin.get(buffer,100,'\n');//to ensure whitespaces input cout << "@@@@ " << buffer << endl ;//shows correct input cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); //clearing cin stream residual characters temp.assign(buffer);//assigning string input "phrase" cout << "###" << temp << endl;//shows correct output if (temp == "!") //if input '!' character not push on vector //come o

pointers,deallocation and vector in c++ -

i want know should explicitly deallocate pointers erase vector myvector.erase(); . for example; class sample1{ public: removesample2(sample2 * a) { if(// if find in samplelist1 vector index ){ // should call here delete or pointer ? samplelist1.erase(samplelist1.begin()+i); } } private: vector<int *> samplelist1; } class sample2{ public: // not important areas private: sample1 * example; } there's no way possibly know, since don't know you're trying do. basic answer is: if collection logically owns things in it, doing wrong. never use ordinary collections of ordinary pointers purpose. things go horribly wrong if you, example, copy collection. (either use ordinary collections of smart pointers or collections designed hold pointers , manage lifetimes of objects in them.) if collection no

php - Merge multiple Array() depending loop and number -

this question has answer here: merging 2 set of array values 1 multidimesional array 2 answers finding cartesian product php associative arrays 10 answers i want merge 3 arrays. my first 1 is: array ( [0] => leaves-19 [1] => shifts-1 [2] => shifts-1 [3] => shifts-1 [4] => shifts-1 [5] => shifts-1 [6] => leaves-19 [7] => leaves-19 [8] => shifts-1 [9] => shifts-1 [10] => shifts-1 [11] => shifts-1 [12] => shifts-1 [13] => leaves-19 [14] => leaves-19 [15] => shifts-1 [16] => shifts-1 [17] => shifts-1 [18] => shifts-1 [19] => shifts-1 [20] => leaves-19 [21] => leaves-19 [22] => shifts-1 [23] => shifts-1 [24] => shifts-1 [25] => shifts-1 [26] => shifts-1 [27] => leaves-19 [28] => leaves-19 [29]

android start Dropbox activity -

i need access dropbox folders android app, select file , open in app. after having thought on integrating dropbox library android app, decided make easier. idea have "launch dropbox" button launch normal dropbox application. , then, using intent-filters, catch file selected , open in app. the question is: how launch dropbox app? guess have construct intent: intent intent = new intent(); intent.setcomponent(new componentname("com.dropbox???", ????)); startactivity(intent); what should there instead of '???'? i've looked package name of dropbox application phone. use these kind of operations. packagemanager manager = getpackagemanager(); intent = manager.getlaunchintentforpackage("com.dropbox.android"); i.addcategory(intent.category_launcher); startactivity(i);

java - Second record doesnt get stored in arraylist -

i have arraylist records stored objects. in different form allow user enter id , retrieve data of record corresponding id. my problem , can retrieve 1 record , meaning first record store in arraylist. if type in second record , if try search record using id , message "invalid id", message assigned make sure users won't enter invalid ids. here code used store object in arraylist:- patient_class patients=new patient_class(firstname,lastname,initials,gender,birthday,birthmonth,birthyear,contactnumber,address,bloodgroup,patientid); patientlist.add(patients); here code check whether if arraylist contains id. public boolean checkrecord(arraylist<patient_class>patients,string search) { for(patient_class patient : patients) { if(patient.getid().contains(search)) { return true; } } return false; } if true have created separate constructor find record give id. here c

JNA: get all windows processes command line -

looking way using jna list of running windows programs , command lines. there few tutorials on site ( get list of processes on windows in charset-safe way ) show how list of running program names i'm looking full command line. i've seen posts mention use of module32first functions can't seem find documentation on how use through jna. ideas? edit: i've tried below aforementioned post. idea want in-process way of iterating on running processes on windows , command lines. don't want use wmic. kernel32 kernel32 = (kernel32) native.loadlibrary(kernel32.class, w32apioptions.unicode_options); tlhelp32.processentry32.byreference processentry = new tlhelp32.processentry32.byreference(); winnt.handle snapshot = kernel32.createtoolhelp32snapshot(tlhelp32.th32cs_snapprocess, new windef.dword(0)); try { while (kernel32.process32next(snapshot, processentry)) { system.out.println(processentry.th32processid + &qu

php - Manage multiple tables relationed in CakePHP -

so, have 3 tables table: users _________________ | id | user | ------------------- | 1 | roy | | 2 | ben | |________|________| table: hability_lists // set list habilities available ___________________________________ | id | category | subcategory | ------------------------------------ | 1 | programmer | php | | 2 | programmer | asp | |________|____________|_____________| table: habilities // set habilities users ________________________________________ | id | user_id | hability_list_id | ----------------------------------------- | 1 | 2 | 1 | | 2 | 1 | 2 | |________|____________|__________________| by this, can see that: roy asp programmer , ben php programmer but, how set relative models using cakephp? know how using 2 models not using 3 models. there way this? or maybe better way do? thanks in advance. when working mvc

ipad - How to support Flash images and flash video's in ios programatically -

for ex : loading url contains flash image ,which not loading in ios . another 1 loading video of .flv format , how support in ios ? the web view not support .swf files, there libraries render .swf files ios: swiffcore swiffcore wasn't 1 thinking of. there's c library also. popular game clash of clans renders .swf assets in game.

Python Nose tests from generator not running concurrently -

given following: from time import sleep def runtest(a): sleep(1) assert >= 0 def test_all(): in range(5): yield (runtest, i) i expect 5 tests run in parallel running nosetests --processes=8 , run in approximately 1 second — however, takes on 5 seconds run: appear running sequentially , not concurrently. according nose documentation, multiprocess plugin has supported test generators (as nose documentation calls them) since 1.1: i'm using nose 1.3.0 should supported. adding _multiprocess_can_split_ = true make difference, 1 expect, fixtures not used. how these 5 tests run concurrently? according nose's author, on mailing list , multiprocess plugin not work generators in 1.3 ( a known bug ), , recommends sticking 1.1 if 1 needs work.

Password Input in django form hosted on google app engine not working -

i using django form google app engine. django form code : class changepasswordform(forms.form): password = forms.passwordinput() confirmpassword = forms.passwordinput() test = forms.charfield() only "test" text field shown in ui. missing something. using python 2.7 , gae 1.7.3 passwordinput widget , not field: password = forms.charfield(widget=forms.passwordinput)

mongodb - Is there a pymongo (or another Python library) bulk-save? -

i'm trying write function bulk-save mongodb using pymongo, there way of doing it? i've tried using insert , works new records fails on duplicates. need same functionality using save collection of documents (it replaces added document same _id instead of failing). thanks in advance! you can use bulk insert option w=0 (ex safe=false), should check see if documents inserted if important you

Strong parameters with Rails and Devise -

i using rails 4.0 branch of devise along ruby 2.0.0p0 , rails 4.0.0.beta1. this kind of question checking if i'm doing right way, or if there other things should doing. i'm sure lot of people moving rails 4.0 facing same problems (after googling similar things). i have read following links: devise , strong parameters https://gist.github.com/kazpsp/3350730 https://github.com/plataformatec/devise/tree/rails4#strong-parameters now using devise created user model, created following controller using above gists (and made sure include in routes file). parameters first_name , last_name. class users::registrationscontroller < devise::registrationscontroller def sign_up_params params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation) end def account_update_params params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation, :current_password) end private :sign_up_params pri

scheme - Recursive range in Lisp adds a period? -

(define .. (lambda (start stop) (cond ((> (add1 start) stop) (quote ())) ((eq? (add1 start) stop) (sub1 stop)) (else (cons start (.. (add1 start) stop)))))) i have defined simple range function. intent for (.. 1 5) --> (1 2 3 4) instead, bizarre period being added tuple , have no idea why: (.. 1 5) --> (1 2 3 . 4) i don't understand why happening. appreciated a list in scheme either empty list () (also known nil in lisps), or cons cell car (also known first ) element of list , cdr (also known rest ) either rest of list (i.e., list), or atom terminates list. conventional terminator empty list () ; lists terminated () said "proper lists". lists terminated other atom called "improper lists". list (1 2 3 4 5) contains elements 1, 2, 3, 4, , 5, , terminated () . construct (cons 1 (cons 2 (cons 3 (cons 4 (cons 5 ()))))) now, when system prints cons cell, general case print (car . cdr) f

jquery - Add new <option> to all dropdown <select> tags using javascript -

im trying add drop down menu option "please select" top of each drop-down list on page selected default, using similar this: window.onload = function() { $('select option[value="psc"]').attr("selected",true); }; and im using drop-down: window.onload = function additem(text,value) { // create option object var opt = document.createelement("option"); // add option object drop down/list box document.getelementsbytagname("option").options.add(opt); // assign text , value option object opt.text = 'please select...'; opt.value = 'please select'; } i'm new @ javascript, can point me in right direction compiling when page loads every drop-down list gets default selected option called "please select" thanks in advance modified pure javascript function function (this not affect selected option) demo jsfiddle window.onload = function additem(text,