Posts

Showing posts from February, 2012

php - Model from URL/API/JSON CakePHP -

i have new cakephp install , have series of web service endpoints in json, possible populate model json in cakephp? they won't connecting db data comes , submits web service. i have no code cannot find documentation on cakephp models site. rest datasource the storage mechanism model uses datasource. default cake assumes model used database can extends datasource class. there's an example in documentation of simple rest api datasource, , there many more datasources in the community datasources repository . it's not necessary build own rest datasource though, there existing solutions out there such this one make using model rest api rather trivial. examples readme: user::find('all') == http://api.example.com/users.json user::read(null, $id) == http://api.example.com/users/$id.json user::save() == post http://api.example.com/users.json user::save(array('id' => $id)) == put htt

c++ - Can I use a member element as the default argument for a method of the class? -

the method minimum returns minimum element in binary search tree. if no argument passed prints minimum of calling object. if address of node passed prints minimum of subtree root node when compiled shows "invalid use of non static data member tree::root " #include<stdlib.h> #include<iostream> class node { public: node *leftchild; node *rightchild; node *parent; int info; }; class tree { public: node *root; tree() { root=null; } void minimum(node*); }; void tree::minimum(node *curnode=root) { node *parent; while(curnode!=null) { parent=curnode; curnode=curnode->leftchild; } std::cout<<parent->info<<endl; } int main() { tree tree; tree.minimum(); return 0; } no, cannot. for default value can use either value, variable or function accessible in context of function definition is, in class definition, outside of particular object's c

php - CakePHP 1.3 - create() not setting created datetime? -

i'm upgrading system cakephp 1.1 1.3. when using create() (followed save()) in 1.1 system happily add insert entry database created , modified datetime fields set of time created. however, in 1.3 no longer correctly happening. here modified still set current time upon creation , save, created datetime not being set. suggestions why might occurring? thanks! create table code (as requested in comment): create table `units` ( `id` int(10) unsigned not null auto_increment, `id_b36` varchar(4) null default null, `subject_id` int(10) unsigned not null, `gradelevel_id` int(10) unsigned not null, `user_id` int(10) unsigned not null, `school_id` int(10) null default null, `district_id` int(10) null default null, `description` varchar(255) not null, `sort` float(5,1) not null default '0.0', `created` datetime not null default '0000-00-00 00:00:00', `modified` datetime not null default '0000-00-00 00:00:00', prima

Conditional cumulative sum with apply functions in R -

may question addressed , answered in so, couldn't able find out. i'm computing cumulative sum conditions on large data frame. @ below example data=data.frame("catg"=c("a","a","a","a","a","b","b","b","c","c","c","d","d","d","d","d","d","d","d","e","e","f"),"val"=c(67,42,12,32,28,1,11,9,38,61,75,99,22,44,89,99,51,34,82,99,74,42)) res=null uniqcatg=unique(data$catg) for(i in 1:length(uniqcatg)) res=c(res, cumsum(data[data$catg==uniqcatg[i],"val"])) data$res=res data is there smart way without loops? (like apply functions) or plyr::ddply ... require( plyr ) ddply( data , "catg" , transform , res = cumsum(val) ) # catg val res #1 67 67 #2 42 109 #3 12 121 #4 32 153 #5 28 181 #6

jQuery - How do I make sure a user enters text before performing any other operations? -

i'm allowing users create folders in app. once user clicks on "new folder" icon, display folder text box user enter name of folder. how make sure user enters name before clicking on "new folder" icon again or matter before using application else? i tried input change event, offcourse, fires when user attempts enter name. $(".new-folder-name").change(function () { var newfoldername = $(".new-folder-name").val(); if (newfoldername == "") { alert("please enter name new folder."); } else { alert("good, entered name: " + newfoldername); } }); but if user leaves text box blank , goes on doing other things app? how can force user enter text first before doing else? force user input after: alert("please enter name new folder."); add: settimeout(function() {$(".new-folder-name").focus();},10); forces focus on textbox. also, change .cha

jquery - Is there a way to provide a fallback (local) image when the preferred (external/server/remote/cloud) image fails to load? -

i have anchor tags so: <a href=\"http://www.duckbill.com" target=\"_blank\"><img height=\"160\" width=\"160\" src=\"http://images.duckbill.com/platypionvacation.jpg\" alt=\"platypi playing pinochle , eating pizza in panama\" /></a> ...that fail load src image; in such cases i'd to, after sufficient delay (a couple of seconds), replace with: <a href=\"http://www.duckbill.com" target=\"_blank\"><img height=\"160\" width=\"160\" src=\"content/images/platypionvacation.jpg\" alt=\"platypi playing pinochle , eating pizza in panama\" /></a> i know in jquery, how able programmatically determine remote file did not load and, when such case, respond using fallback image? update i brad christie's answer unavailable images, want never show "unavailable" - use local 1 if remote 1 not available @ moment. this: h

php - Simple HTML DOM - traversing html -

i'm using simple html dom parser - http://simplehtmldom.sourceforge.net/manual.htm i'm trying scrape data scoreboard page. below example shows me pulling html of " akron rushing " table. inside $tr->find('td', 0) , first column, there hyperlink. how can extract hyperlink? using $tr->find('td', 0')->find('a') not seem work. also: can write conditions each table (passing, rushing, receiving, etc), there more efficient way this? i'm open ideas on one. include('simple_html_dom.php'); $html = file_get_html('http://espn.go.com/ncf/boxscore?gameid=322432006'); $teama['rushing'] = $html->find('table.mod-data',5); foreach ($teama $type=>$data) { switch ($type) { # rushing table case "rushing": foreach ($data->find('tr') $tr) { echo $tr->find('td', 0); // first td column (player name) echo $tr->find('td

linux - Take commands(password) from string and set as InputStream to Unix servers in Java (JSCH) -

almost similar this topic, here not superuser use --stdin. so found other way round, open "shell" in background , give input shell via string through inputstream i made code below: string s = "cd bin\n"; byte bb[] = s.getbytes(); inputstream intt = new bytearrayinputstream(bb); channel.setinputstream(new filterinputstream(intt) { public int read(byte[] b, int off, int len) throws ioexception { return in.read(b, off, (len > 1024 ? 1024 : len)); } }); now works when want execute 1 command want give multiple commands, facing issue. any suggestions? regards, ishan i found solution question asked, don't know if full proof solution since tested limited period of time , did beast way can. channel = session.openchannel("exec"); ((channelexec) channel).setcommand(command); ((channelexec) channel).setpty(true); in command string string command = "(echo old_password; echo new_password; echo new_passwor

replace an already created instance in spring with the one created at runtime -

i have spring framework related query. could pls me in getting problem resolved. requirement replace created singleton instance 1 created @ runtime programmatically. i have spring context defined in bean follows: <bean name="configuration" class="com.myapp.tests.serviceconfiguration" /> <bean name="anotherbean class="com.myapp.tests.anotherbeanclass"> <property ref="configuration"/> </bean> and loading the context using applicationcontext ctx = classpathxmlapplicationcontext("appconfig.xml"); i need create new instance of com.myapp.tests.serviceconfiguration , replace "configuration" @ runtime , load other beans have dependency on this( kind of refresh.). in our case, anotherbean should see newly created serviceconfiguration instance after re-register singleton. could pls kindly post solution new sort of spring requirements. error if try registersingleton says bea

javascript - template croosdomain with requirejs returns blank page -

i implementing 1 app html5 chaplinjs (can see here https://github.com/andru255/chtw ), paths of htmls runing good, returning blank pages when release request firebug , showin in red error in request, in other tab in browser loads path of template, whats happen in case? fail in request?

c++ - In what case can this if-statement throw an exception? -

apparently, when code reaches if statement, string subscript out of range exception occurs. // int // str std::string while ( true ) { // other stuff if( == str.size() ) // line throws exception break; } in case can such simple if-statement throw exception? don't see it. shouldn't return 0 if reason comparison fails? edit: full function in occurs. reads through file , takes in value of tokens of its. , if of relevancy, i'm using visual studio 2010 express , error says "debug assertion failed". void function(string &str, int start) { int outline; // read attributes int pos, pos2 = start; while( true ) { pos = skipwhitespace(str, pos2); pos2 = findendoftoken(str, pos); string token = str.substr(pos, pos2-pos); pos = skipwhitespace(str, pos2); if( pos == str.size() || str[pos] != '=' ) break; pos = skipwhitespace(str, pos+1); pos2 = findendoftok

java - Build fails when trying to compile spring roo sample heroku app -

i'm trying test out sample app spring/roo/heroku here https://devcenter.heroku.com/articles/spring-mvc-hibernate when run 'mvn package' output: http://pastie.org/8263189 not sure doing wrong. org.apache.maven.buildfailureexception: there test failures. from exception seems test data not correct. if okay skip test please run below command else need fix test failures. mvn package -dmaven.test.skip=true

apache - PHP zipping ends with Internal Server Error -

i have php script on server zips few directories 1 zip file. normally, runs fine. today, it's taking longer , ends page says "internal server error". when check directory zip gets created, seems zip made half way there (as file half size should , corrupted). in logs, see error: mod_fcgid: process 30172 graceful kill fail, sending sigkill any ideas problem is? this code i'm using (and note works fine of time): $zipfolders[] = 'httpdocs/'; $zipfolders[] = 'includes/'; $zip = new ziparchive(); if ($zip->open($sourcefilename, ziparchive::create) !== true) die ("could not open archive"); foreach ($zipfolders $zipfolder) { $iterator = new recursiveiteratoriterator(new recursivedirectoryiterator($zipfolder)); foreach ($iterator $key=>$value) { if ( (substr($key, -1) != '.')&&(substr($key, -2) != '..') ) { $zip->addfile(realpath($key), $key) or die ("e

.net - WCF ChannelFactory with Custom Endpoint Behavior (Json-Rpc) -

i've been working hard on wcf json-rpc service model . i'm new wcf , wcf extensibility i'm able process requests web browser :) summarize it, i've implemented endpoint behavior, operation selector, , message formatter. you can find latest source code on post on msdn forum . i'm trying create wcf client i'm stuck following error: manual addressing enabled on factory, messages sent must pre-addressed. this how i'm creating client: private int communicationtimeout = 10; private int communicationport = 80; private string jsonrpcroot = "/json.rpc"; public void initializeclient() { uri baseaddress = new uribuilder(uri.urischemehttp, environment.machinename, communicationport, jsonrpcroot).uri; endpointaddress address = new endpointaddress(baseaddress.absoluteuri); channelfactory<ijsonservice> channelfactory = new channelfactory<ijsonservice>(new webhttpbinding(), address);

java - In what situation do I need to extend a class? -

i'm learning java , wondering in situation want extend class here suggested: http://5upcodes.blogspot.fi/2013/08/java-inheritance.html thanks! when want create class similar super class(the class being extended), extend , customize it. overwriting of it's functions, and/or add functions.

php - Filling a div with the current time -

in header of page want insert div contains current date. not sure if jquery can handle (perhaps php) better way go. i want populate div in header of page current date in format (example) 20th august 2013. you can use php's built-in date() function purpose: <div id="foo"> <?php echo date('ds f y'); ?> </div> output: 23rd august 2013 documentation: date()

android - How to write a onClick listener for a ListView? -

this arrayadapter: public class listarrayadapter extends arrayadapter<string> { public arraylist<string> links = new arraylist<string>(); public activity activity = new activity(); textview linktext; textview linkdesc; public context c; public listarrayadapter(context context, int textviewresourceid, arraylist<string> fiokilist, object o) { super(context, textviewresourceid, fiokilist); this.links = fiokilist; activity = (activity) (o); c = context; //notifydatasetchanged(); } public view getview(final int position, view convertview, viewgroup parent) { view v = convertview; if (convertview == null) { convertview = layoutinflater.from(getcontext()).inflate( r.layout.list_item, parent, false); convertview.setonclicklistener(new onclicklistener() { @override pu

javascript - Getting correct element from click event -

i have dom tree this: <div class="like-bttn" data-answer-id="{{answer.id}}"> <div class="count>{{ answer.like_score }}</div> <div class="heart>&#10084;</div> </div> i have javascript code make ajax request when like-bttn clicked: $(".like-bttn").click(function(ev) { var id = $(ev.target).attr('data-answer-id'); ... id ... }) but when .heart clicked code not work, becaouse ev.target .heart , not have 'data-answer-id' what correct approach @ stiuation? use $(this) , not event target : $(".like-bttn").click(function(ev) { var id = $(this).attr('data-answer-id'); ... id ... }) and, neal pointed, it's cleaner use data : var id = $(this).data('answerid');

internet explorer - .NET WebBrowser control and "Delete browsing history on exit" setting in IE -

our application includes browser pane, using .net webbrowser control, access local web server serving php pages. users keep running day. if concurrently use ie , close while our application running, , "delete browsing history on exit" settings checked, our webbrowser control loses php session. is there way prevent that?

mysql - INSERT ... SELECT Syntax issue when value(s) from two or more different query -

i have table name shop_balance . has 3 columns ( shop_balance_id (int,pk), shop_balance (double), balance_date (date)). shop_balance (double) column use 2 sub query. 1.get last shop balance amount row shop_balance column in shop_balance table. 2.get purchase amount after 1 purchase product(s). , subtract them , current shop balance my query here insert shop_balance select null, ( (select shop_balance shop_balance shop_balance_id=(select max(shop_balance_id) shop_balance) ) - ( select sum(pr_pur_cost_price*quantity) net product_purchase_item left join product_purchases p on p.product_purchase_item_id=i.product_purchase_item_id p.insert_operation=$id group p.insert_operation ) ),curdate(); it clear 2 sub query different condition , no direct relation them. above insert query work well. idea use many sub query without insert ... select syntax insert 1 value? if

c++ - Why does returning a reference to a automatic variable work? -

i'm reading c++ , , read when using return reference should make sure i'm not returning reference variable go out of scope when function returns. so why in add function object cen returned reference , code works correctly?! here code: #include <iostream> using namespace std; class cents { private: int m_ncents; public: cents(int ncents) { m_ncents = ncents; } int getcents() { return m_ncents; } }; cents& add(cents &c1, cents &c2) { cents cen(c1.getcents() + c2.getcents()); return cen; } int main() { cents ccents1(3); cents ccents2(9); cout << "i have " << add(ccents1, ccents2).getcents() << " cents." << std::endl; return 0; } i using codeblocks ide on win7. this undefined behavior , may seem work can break @ anytime , can not rely on results of program. when function exits, memory used hold automatic variables released , not valid refer memory. the draft c++ st

c# - How do I ensure that all controllers in an asp.net web-api service are configured correctly _in a single test class_? -

dipping toes asp.net , mvc, more web-api (2.0) part of mvc 5, idea of using attributes , creating own attribute classes control how requests handled , responses returned api end-points. the "how test "only roles should have access controller in mvc" article describes how unit test single controller ensure keeps correct attributes , doesn't undesired attributes added. that valid way of unit testing individual controllers. however, prefer have tests of api configuration in single place instead of spread around unit tests of individual controllers. as, using attribute routing , controller can replaced different controller may not have correct attributes , test companion doesn't test them. what envision single test class aspects of api configuration can secured against undesired effects of (inadvertent) changes. struggling how set up. bryan avery's article (mentioned above) shows how list of custom attributes of controller class, but: how hands on li

mysql - Mysqlbug: Could not find a text editor. (tried emacs) -

i want check configurations mysql configured. found mysqlbug can retrieve info, i'm getting following error: mysqlbug finding system information mysql bug report test -x not find text editor. (tried emacs) can change editor setting environment variable visual. if shell bourne shell (sh) visual=your_editors_name; export visual if shell c shell (csh) setenv visual your_editors_name this means can choose use editor whichever want vim, nano etc instead of emacs exporting environment variable. just export visual environment variable. example usage: export visual=vim

regression - R: Error in lars(x = , y = , type = "lasso") -

i trying run lasso (least absolute shrinkage , selection operator) using lars package in r. here dimension of data: dim(y) : 235 50 dim(x) : 235 15 when running following: library(lars) return = as.matrix(ret.ff.zoo) ### "y" data = as.matrix(df) ### "x" lasso <- lars(data, return, type = c("lasso")) i following error: > lasso <- lars(data, return, type = c("lasso")) error in cvec - gamhat * gram[, active, drop = false] %*% w : non-conformable arrays when make response variable "y" vector, follows: lasso <- lars(data, return[,1], type = c("lasso")) it works! however, doing means lasso performed on 1 security out of 3000 panel. how can formula extended analyze panel of data?? doing lasso separately on each of 3000 securities doesn't make sense excludes cross-sectional dynamic. i use can get! thanks!

android - I want to bring my relative layout in bottom -

what changes shall make bring relative layout in bottom? <?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <relativelayout android:layout_width="match_parent" android:layout_height="86dp" android:layout_alignparentbottom="true" android:layout_weight="0.08" android:gravity="bottom" > </relativelayout> </linearlayout> you need change parent layout relativelayout , since attribute android:layout_alignparentbottom nothing linearlayout children: <?xml version="1.0" encoding="utf-8"?> <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="ma

Lift With OpenLayers Timing -

i have simple lift "application" attempts display statically openlayers map in anticipation of having comet dynamically add markers map based on server-side logic. in case, having map show @ proving difficult task. the html follows: <!doctype html> <html> <head> <title>test</title> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge,chrome=1"> <meta name="description" content=""> <meta name="viewport" content="width=device-width"> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/bootstrap-responsive.min.css"> <link rel="stylesheet" href="css/main.css"> <script src="js/vendor/modernizr-2.6.2-respond-1.1.0.min.js"></script> <script src="http://www.openlayers.org/api/openlayers.js&

Change Python version in Maya -

i'm trying change version of python within maya. specifically, want maya (maya 2013) script editor use python2.7 , other packages/modules attached version. want able import pymel , maya eclipse. i've tried following response no luck. maya still points default version. from python, try import pymel import pymel.core pm and error reads file "<stdin>", line 1, in <module> file "/opt/local/library/frameworks/python.framework/versions/2.7/lib/python2.7/site-packages/pymel/core/__init__.py", line 6, in <module> import pymel.versions _versions file "/opt/local/library/frameworks/python.framework/versions/2.7/lib/python2.7/site-packages/pymel/versions.py", line 12, in <module> maya.openmaya import mglobal _mglobal importerror: bad magic number in /opt/local/library/frameworks/python.framework/versions/2.7/lib/python2.7/site-packages/maya/openmaya.pyc thanks in advance. the method described

What is wrong with my if perl statement? -

ok driving me crazy!! looked @ many examples , read on if statements in perl , looks correct me can else spot error? #start of script #!/usr/bin/perl -w ########################## #### define variables #### ########################## echo $pwd; maindirectory=$env{home}"/test/"; file='report.txt'; backupdirectory=$env{home}"/test/backup"; number_to_try=0; ################################## #### check if file exists #### ################################## filename=$maindirectory$file; echo $filename; if (-e $filename) { print "file exists!" } error message is: ./perl.pl: line 18: syntax error near unexpected token `{' ./perl.pl: line 18: `if (-e $filename) {' anyone have ideas?? all of lines above "if" not valid perl; believe wanted do: #!/usr/bin/perl use strict; use warnings; ########################## #### define variables #### ########################## $maindirectory = "$env{home}/test&qu

javascript - Double view render in routers -

var router = backbone.router.extend({ routes:{ 'notes': 'shownotes', "note/:noteid": "opennote" }, shownotes: function() { new app.notesview; }, opennote: function(noteid) { var notescollection = new app.notescollection(); notescollection.fetch(); var view = new app.notesview({ currentmodel : notescollection.get(noteid) }) } }); here problem comes when navigate domain.com/#notes every time navigate there double view occurs, , event get's fired multiple times. i think it's because every time go there, create new view (the old view still exists). instead, can create view once , on shownotes, call render? also, side note, fetch() asynchronous call have wait until data fetched passing in callback (success function) , doing calculations there. something this: var notesview = new app.notesview; var router = backbone.router.ext

c# - XML selectsinglenode how i filter tag? -

i'm starting program in c # , beginner, don't have experience. want 1 day professional , started develop solutions. program save information in xml file , read same information in same xml. xml file has format <dados> <nome>vitor emanuel macedo ferreira</nome> <sexo>m</sexo> <idade>22</idade> <peso>86</peso> <altura>1.87</altura> </dados> and in c# code solution has: openfiledialog ofd = new openfiledialog(); ofd.filter = "xml|*.xml"; ofd.filename = ("c:\\xml\\data.xml"); if (ofd.showdialog() == dialogresult.ok) { xmldocument xdoc = new xmldocument(); xdoc.load(ofd.filename); xdoc.selectsinglenode("dados"); if (ofd.filename == "c:\\xml\\data.xml" && xdoc.selectsinglenode(string.empty) == xdoc.selectsinglenode("dados")) {

youtube - Share a video with Google circles -

i want share private youtube video via google circles. want display video in website, should still seen "friends" in google circles. did following. created 2 different gmail accounts. created circle 1 of them, , added other person (i.e. gmail account) circle. i uploaded private video first gmail account, , then, attempted share circle. did typing in url in share box. unfortunately, "person" appears in circle cannot view video - gets message "private". happens though logged in browser via gmail account. so why can't succeed in sharing 1 video people in circle? thanks it no longer possible share video google circles. refer this thread more details.

internet explorer 8 - BreezeJS's 1.4.1 isolateES5Props causing Out of Stack Space error in IE 8 -

using 1.4.1 of breezejs found new code added isolate es5 properties causing ie 8 have following error: error getting metadata: metadata import failed breeze/breeze/metadata; unable process returned metadata:object doesn't support property or method 'getprototypeof' we tried using both uber proto's getprototypeof ( https://github.com/daffl/uberproto ) , es5-sham ( https://github.com/kriskowal/es5-shim ) both result same issue. we tried removing regular json.parse , using json2's version same results. metadata import failed /breeze/breeze/metadata; unable process returned metadata:out of stack space chrome, firefox, , ie 9+ work without issue, ie 8 support required. can comment out line work: // isolatees5props(proto); but i'm guessing cause issues somewhere down line. this should fixed in breeze v 1.4.2, available now.

ios - Alignment of UILabel and word wrapping with right-to-left language -

i have view has image, , left long block of text may take multiple lines. in english, first line might full, , on second line may take half of left side of screen. when using arabic, should text aligned towards right side, first line full, second line takes half of line , aligned right? i using auto layout. there something, hugging settings, want adjust?

using with-open to initialize unknown number of readers/writers in Clojure -

say have file used n readers , m writers. when know n , m's value, if n==3 , m==1, write code this: (use 'clojure.java.io) (with-open [rdr1 (reader file) rdr2 (reader file) rdr3 (reader file) wtr1 (writer file)] (time-to-work-out-guys)) now case is, app user determines values of n , m, have no idea value n , m have. there way still can use with-open initialize readers/writers , job? because open-with macro instead of function, way build macro generates call open-with , use eval compile @ runtime. while technically answer yes, can't recommend doing so . open-with convenience not fit cases. in case makes more sense write own (try .... (finally ...)) statement.

php - "The Transaction is invalid ...." PayPal when I send user for approval -

i in trouble couple of hours, tried many ways still no luck. have integrated paypal in wordpress theme using paypal framework wordpress plugin. sandbox settings working fine. got success on setexpresscheckout token, when send user paypal approval , payment using https://www.sandbox.paypal.com/webscr?token=ec-2fy692500k5578627&cmd=_express-checkout gives me error... this transaction invalid. please return recipient's website complete transaction using regular checkout flow. please help, can make work... worried... :( updated i sending following params setexpresscheckout $ppparams = array( 'method' => 'setexpresscheckout', 'paymentrequest_0_paymentaction' => 'sale', 'returnurl' => admin_url('admin-ajax.php?action=paypal_handler&step=commit&user_id=' . $user_id), 'cancelurl' => home_url(), 'amt' => $price, 'paymentrequest_0_amt&#

super - python: cooperative supercall of __getattr__ -

i'm working somethign similar code: class baseclass(object): def __getattr__(self, attr): return lambda:'1' class subclass(baseclass): def foo(self): suffix = '2' return super(subclass, self).foo() + suffix class subclass2(subclass): def foo(self): suffix = '3' return super(subclass2, self).foo() + suffix o = subclass2() print o.foo() i'd expect see output of '123', instead error attributeerror: 'super' object has no attribute 'foo' . python isn't attempting use base class's __getattr__ . without modifying base class, , keeping 2 super calls similar, i'm not able output want. there cooperative supercall pattern work me here? i understand super() overrides getattr in way needs do, i'm asking if there's reasonable workaround allows subclass's __getattr__ called when appropriate. ah, great question! in short, what's going on he

How to package django app and make available through pip? -

this question has answer here: how package python application make pip-installable? 1 answer what best way package django app can make available other projects through pip? check out docs , excellent.

qt - How to draw something in a tooltip? -

i trying develop functionality using qt don't know whether possible implement. here requirement: when user hovers on node (an object derived qgraphicsitem), window shown near node, in window there might histograms or buttons can clicked show further information. when mouse leaves window, automatically close. i tried use tooltip, because can pop-up near node , close when mouse leaves it, can show text. so, still cannot work way. wondering if there way this? did lots of google search, there still no answer. thanks helping me this. if you're ok using 3rd party library, qxt provides class provides tooltip qwidget based, let use arbitrary widget tooltip rather text. see: qxt::tooltip

android - Show MapFragment in a DialogFragment -

i'm new android development , i'm working on app need use google map select event position , need show map popup windows , see post : mapfragment in dialogfragment i have same problem listed on post did not understand how her did : xml layout <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".addeventactivity" > <scrollview android:id="@+id/scrollview1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignparentleft="true" > <linearlayout android:layout_width="match_parent" android:layout_height="fill_parent" android:orientation="vertical" android:padding="15dp" >

c# - Force one application to close when a different application has closed, then close itself -

so, i'm writing program, here's start of it! namespace consoleapplication4 { class program { static void main(string[] args) { system.diagnostics.process.start(@"c:\\windows\\ehome\\ehshell.exe"); system.diagnostics.process.start(@"e:\\xpadder\\wmc.xpaddercontroller"); } } } all open 2 files. want wait until detects when ehshell.exe stops running , force program (in case xpadder) end well. i've had code doing this, i'm not best @ c# , not 100% sure i'm looking for! var p1 = new processstartinfo { filename = atomicparsleyfile, arguments = atomicparsleycommands, windowstyle = processwindowstyle.hidden, useshellexecute = false, createnowindow = true, redirectstandardoutput = true }; var proc = new process { startinfo = p1 }; if (!proc.start()) {

c - Sizes of arrays declared with pointers -

char c[] = "hello"; char *p = "hello"; printf("%i", sizeof(c)); \\prints 6 printf("%i", sizeof(p)); \\prints 4 my question is: why these print different results? doesn't c[] declare pointer points first character of array (and therefore should have size 4, since it's pointer)? it sounds you're confused between pointers , arrays. pointers , arrays (in case char * , char [] ) not same thing. an array char a[size] says value @ location of a array of length size a pointer char *a; says value @ location of a pointer char . can combined pointer arithmetic behave array (eg, a[10] 10 entries past wherever a points) in memory, looks (example taken the faq ): char a[] = "hello"; // array +---+---+---+---+---+---+ a: | h | e | l | l | o |\0 | +---+---+---+---+---+---+ char *p = "world"; // pointer +-----+ +---+---+---+---+---+---+ p: | *======> | w | o | r | l | d |\0

c# - How deselect row in grid of devexpress - winforms -

i have 1 grid property multiselected set false, , need clear selection in current grid when user clicks button. read in documentation 2 methods, doesn't work when user can select 1 row. here attempt solve this: gridview1.clearselection(); foreach (var in gridview1.getselectedrows()) gridview1.unselectrow(i); i hope me. in advance! when multiple selection off, grid not allow unfocusing row , contains focused row. see issue additional information. the getselectedrows , clearselection documentation states these nothing if multi-selection disabled. there couple of sample projects in support center regarding row selection: http://www.devexpress.com/support/center/example/details/e13 http://www.devexpress.com/support/center/example/details/e135 the best place ask support devexpress related questions support center . if describe trying achieve, respond , helpfully.

backbone.js - Backbone Collection from JSON file won't pass to the view -

i've been trying figure out hours, can't seem working. json file being loaded in "friends" collection won't populate in view. var friend = backbone.model.extend({ defaults: { "name": "unknown", "job": "unknown" } }); var friend = new friend({ }); var friends = backbone.collection.extend({ model: friend, url: '/friends.json', initialize: function() { this.fetch(); } }); var friends = new friends(); var friendsview = backbone.view.extend({ tagname: "ul", template: _.template('<li><%= name %> <%= job %></li>'), render: function(){ this.$el.html(this.template(this.model.tojson())); } }); var friendsview = new friendsview({ model: friend }); friendsview.render(); $('#here').html(friendsview.el); the json looks this: { "name": "timmy", "job": 'sky

scala - Play! 2 WS library : Detect and Handle Closed Connection in Streaming HTTP response -

in play ws library, using call process streaming http response: def get[a](consumer: responseheaders => iteratee[array[byte], a]): future[iteratee[array[byte], a]] i passing like: _ => (iteratee.foreach(chunk => println(chunk))) everything works fine, @ point connection seems close , don't know how handle this. tried adding .mapdone print out stuff when iteratee done, never happens. on request, how can detect connection has been closed , handle event? it seems not longer problem in play 2.2.3. function passed map defined below should invoked unit when stream closes: val connection = ws.url("http://example.com") .get(_ => iteratee).flatmap(_.run) map { _ => println("closed") }

javascript - load event for iframe does not fire in IE -

i've created iframe in page here it's code: var frame = document.createelement('iframe'); frame.setattribute('src',''); document.body.appendchild(frame); if(document.addeventlistener){ frame.addeventlistener('load', callback, false); } else { frame.attachevent('onload', callback); } function callback(){ alert('test'); } it works fine in ff no thing alerted in ie, why? note use ie10 in win8 you need move document.body.appendchild() after addeventlistener() call var frame = document.createelement('iframe'); frame.setattribute('src',''); if(frame.addeventlistener){ frame.addeventlistener('load', callback, true); } else { frame.attachevent('onload', callback); } document.body.appendchild(frame); function callback(){ alert('test'); }

javascript - jquery ajax asynchronous requests error -

at beginning sorry bad english. jquery v2.0.0 in google chrome, mozilla firefox, opera last versions today had problem timer_multy_update = setinterval( function() { $.get( 'test.php', function (result){ parseandupdatedata(result); }, "json" ); }, 500) the problem if server hangs (i don't know how correctly), i.e. time answer server more 0,5 second, timer not stay , continues send request, before server answer can send 2-4 request, answer return little time and, problem, in firebug request correct, variable result contains 1 answer first answer server. maybe did not express myself clearly, want 2-4 request server return different answer, in result gets 2-4 times first answer server, , big problem. i tried find information on internet, found nothing. i not know why first thought error in jquery, began @ source code, , found mention heder , it's hashes. try chan

c - How will 'fopen' interpret a 'char[]' whose capacity is larger than the string it contains? -

i writing program can encrypt text file. first need ask users file name. did like: char file_name[50]; fgets(file_name, 50, stdin); but didn't work. how can this? i confused if store file name in char array has, say, 50 elements, file name has 10 characters. when pass array or pointer fopen , program going remaining 40 elements of array? storing value? passed fopen ? in c, string \0 terminated sequence of characters. long there \0 within 50 bytes of file_name , file_name contains valid string fopen() . the reason fopen() failed name passed had \n in after reading input. because fgets() stores newline character buffer. have remove before using string file name. char *p = strrchr(file_name, '\n'); if (p) *p = '\0';

javascript - Working with old version of KineticJS -

i had developed complex enough canvas web application using kinetic.js year ago. used kinetic.js 3.10.4. version , i'm surprised application not work anymore on latest browser google chrome , mozilla firefox. example, there error while creating text shapes. here stack trace error google chrome debugger: uncaught typeerror: type error kinetic.shape.kinetic.node.extend.fill config.drawfunc kinetic.shape.kinetic.node.extend._draw kinetic.container.kinetic.node.extend._drawchildren kinetic.layer.kinetic.container.extend._draw kinetic.layer.kinetic.container.extend.draw loadmenu _background.onload i've tried using 4.6.0 version there deprecated functions , features on legacy code. wondering using current 3.10.4 version library (with several effortless fix) rather update 4.6.0 version . still possible that? in advance :) yes, transitions eliminated , have been replaced tweens effective kineticv4.5. tweens coded old transitions. so recoding of transitions

sqlalchemy constraint on a boolean column -

i have table 3 columns a(, b, c) , have 2 constraints a , b should jointly unique have done defining unique constraint. for given value in a, there can 1 true in c. (a, c=true) has unique. need in defining second constraint. e.g data set a : b c a1 : b1 : false a1 : b2 : true a1 : b3 : false a2 : b1 : true a2 : b2 : false a2 : b3 : false i don't think can expressed in database-portable way without changing schema. partial index can this: create unique index one_c_per_a_idx on table(a) c; but available on postgresql , sql server (and simulated functional index on oracle). postgresql back-end can use postgresql_where keyword argument index (see docs ) define partial index in sqlalchemy. a portable way split @ least 2 tables, converting explicit boolean column implicit "prese

ios - How to validate values of UICollectionViewCell from the UICollectionViewController -

i have following design problem, , hope me solve :) i have view controller takes questionnaire model instance , render questionnaire using collectionview. questionnaire model contains array of questions models (each question instance different subclass of base question class depending of answer type, example : date question, boolean question...). each cell in collectionview represent question , contain answer views loaded .xib depending on answer type (1 xib = 1 type of answer). answer view may contain uiswitch, uitextfield or other control allow user answer question. at moment answer view configure control depending on answer validation rules (for example date question may have datepicker minimumdate/maximumdate properties configured depending on in date question model, or correct keyboard textfields etc...). answer view delegate/observer/target of control, , when value change, view set value (using formatter if needed , depending on answer type) in destination object. think

java - NullPointerException on Render -

when try debug this, got nullpointerexception. don't it, must not been initialized correctly can't see what... thanks! @override public void create() { texture.setenforcepotimages(false); camera = new orthographiccamera(virtual_width, virtual_height); camera.settoortho(true,virtual_width,virtual_height); batch = new spritebatch(); labyrinthe = new labyrinthe(2, virtual_width); labyrinthe.generer(); joueur = labyrinthe.getjoueur(); } @override public void dispose() { batch.dispose(); } @override public void render() { camera.position.set(joueur.getx(), joueur.gety(), 0); camera.update(); camera.apply(gdx.gl10); gdx.gl.glviewport((int) viewport.x, (int) viewport.y, (int) viewport.width, (int) viewport.height); gdx.gl.glclearcolor(1, 1, 1, 1); gdx.gl.glclear(gl10.gl_color_buffer_bit); batch.setprojectionmatrix(camera.combined); batch.begin(); dessinerlabyrinthe(); dessinerjoueu

php - How to Print innertext during Parsing with Simple HTML dom parser -

i want print innertext during parsing simple html dom parser html source code: <div id="ctl00_contentplaceholder_middle_ratingsummary1_rating1_ratingpanel"> <img id="ctl00_contentplaceholder_middle_ratingsummary1_rating1_ratingimage" title="(2.5 / 5) : above average" src="../../../../../images/net/common/stars/transparent/2.5.png" alt="(2.5 / 5) : above average" style="border-width:0px;" /> <span id="ctl00_contentplaceholder_middle_ratingsummary1_rating1_ratingtext" class="text med strong">(2.5 / 5) : above average</span> <a id="ctl00_contentplaceholder_middle_ratingsummary1_rating1_ratinghelp" class="help"></a> i want output this: (2.5 / 5) : above average i tried it, not getting it: php code: $ratings = $html->find('div[id=ctl00_contentplaceholder_middle_ratingsummary1_rating1_ratingpanel] span')->outertext; ech

javascript - Why is fusion table style not reflected in google map -

i importing fusion tables google map icon colour used in fusion table not reflected in map. working few days went wrong. please can suggest me reason. layer1 = new google.maps.fusiontableslayer({ query: { select: 'latitude', from: '1f1xftx7j52pzjv3mwnbq3rcipwb6x1li67ca6lg' } }); you must define styleid via options -property when want apply style of map-view in external map: to determine styleid click on arrow on right side of view-tab, choose publish->get html , javascript. give complete code publish map-view on external page, contains styleid . in case styleid 2 layer1 = new google.maps.fusiontableslayer({ query: { select: 'latitude', from: '1f1xftx7j52pzjv3mwnbq3rcipwb6x1li67ca6lg' }, options:{ styleid: 2 } });

Linux shell, get all the matches from a file -

this question has answer here: awk extract multiple groups each line 4 answers i have file following format: line 1 line 2 <% word1 %> text <% word2 %> line 3 <%word3%> i want use linux shell tools awk, sed etc words quoted in <% %> result should like word1 word2 word3 thanks help. i forgot mention: in embedded environment. grep has no -p option using awk: awk -f '<% *| *%>' '{for(i=2; i<=nf; i+=2) print $i}' file word1 word2 word3

android - Custom action bar -

Image
i created layout custom action bar: <?xml version="1.0" encoding="utf-8"?> <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/contacts_action_bar" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:background="#835ca1" android:padding="1dip" > <!-- listrow left side thumbnail image --> <linearlayout android:id="@+id/thumbnail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginright="5dip" android:padding="3dip" android:layout_centervertical="true" > <imageview android:id="@+id/home_image" android:contentdescription="@string/app_name" android:layout_width="wrap_content"

ruby on rails - Stay on the same page after edit -

i'm trying follow railstutorial guide, doing own application instead. have trouble section 7, forms. my controller : def update d = deck.find(params[:id]) d.title = params[:deck][:title] d.slug = params[:deck][:slug] d.category = params[:deck][:category] if d.save redirect_to deck_path(d), notice: "deck saved successfully" else render :edit end end i know it's very, far code, refactor later (if have suggestion i'm ears, use rails 3, guess strong parameters of rails 4 out). the problem when d.save not work (due validation), render :edit . right now, when enter invalid data, tries redirect show action, , crashes because not have data display. if add @deck = d above render , works, url still show action. if validation fail, how can stay on same url , display error messages ? "change url render same page" behavior accepted valid ? thanks ! if you're interested in looking @ rest of cod

asp.net - fetch data from a database server to local application continuously -

i have application collects information customers using asp application in website. application writes information database (sql server) in remote server (web server). want information in database updated local pc in real time i.e. data added web server db same should downloaded local server (offline server). summarize want push notification of data changes web server local pc. there numerous ways accomplish - choose depends on constraints of particular situation. simplest have local application poll server @ regular intervals. crude has advantage work without modification router/firewall settings. alternatively write code on asp application send message local application when change occurs. true push, fail without port forwarding on router; if can configure router, code should straightforward enough. question vague answer here - replies saying 'ok , bit stuck with?', 'what have tried?' etc