Posts

Showing posts from January, 2014

python - Django: Update exsisting record with form=MyForm(instance=MyID) doesn't work -

i'm try update existing record, had create form, in view call editrecipeform(instance=recipe.objects.get(id=recipe_id) in view don't appear existing fields. here structure of directory rsg ├── src | ├── recipes | | ├── forms | | | ├── __init__.py | | | └── update.py | | ├── __init__.py | | ├── admin.py | | ├── models.py | | ├── test.py | | ├── urls.py | | └── views.py | ├── rsg | | └── ... | ├── signups | | ├── ... | | └── ... | └── magnate.py ├── static ├── media ├── static ├── static-only ├── templates | ├── recipes | | ├── profileview.html | | ├── recipedit.html | | └── recipecreate.html | ├── signups | └── .... ├── ... └── index.hml here recipe models: rsg/src/recpes/models.py class recipe(models.model): name = models.charfield('nome',max_length=200) description = models.textfield('presentazione', null=true, blank=t

java - How can I use an array variable to IF statement? -

i developing simple taxi meter calculator system. have no idea use implement it. have written code got stuck @ if statement had insert array variable. not sure whether correct way implement it. this logic. the first km 50/-. then next 10km charged 45/- per km. eg : if 2km gone , charges 50/- + 45/- = 95/-, if 3km gone 140/-. the next 10km charged 35/- per km 25/- per km charged no matter how many kms gone after above 10km exceed. this code have coded far private void btn_calactionperformed(java.awt.event.actionevent evt) { int kms1 = 50; int kms2 = 45; int kms3 = 35; int kms4 = 25; string[] firstkm={"3,4,5,6,7,8,9,10,11"}; if(txt_km.gettext().equals("1")){ lblout.settext(""+kms1); } if(txt_km.gettext().equals("2")){ lblout.settext(""+(kms1+kms2)); }if(txt_km.gettext().equals(firstkm)){

Remove all the lines in a txt file that start with a string? (Java) -

right, have file format: myfile.txt name nickname; jay epic1; jay epic2; now have string name = jay; . want remove lines start string name so basically, want remove lines in txt file start string. possible? if so, can give me code? (i learn best looking @ code itself.) thanks, jay here 1 possible implementation: string name = "jay "; string source = "/path/to/original/file.txt"; string dest = "/path/to/new/modified/file.txt"; file fin = new file( source ); fileinputstream fis = new fileinputstream( fin ); bufferedreader in = new bufferedreader( new inputstreamreader( fis ) ); filewriter fstream = new filewriter( dest, true ); bufferedwriter out = new bufferedwriter( fstream ); string aline = null; while( ( aline = in.readline() ) != null ) { // check each line string, , write if doesn't have it: if( !aline.startswith(name) ) { out.write( aline );

matlab - Separate connected objects and single objects from an image -

Image
i working on image in matlab shown in link http://lyremjeni.files.wordpress.com/2013/08/tocleanblobs.jpg i want separate connected/grouped cell blobs , single cell blobs image , display them in separate figures. kindly suggest how can achieve separation. here 2 solutions use, 1st 1 using bwconncomp finds connected elements in binary image, , 2nd 1 using imfindcircles , believe or not finds circles! therefore in instances objects detect not circles 1st solution preferred. i prefer first one, discriminates between single circles , clusters of circles, asked, whereas method using imfindcircles rather useful identifying individual circles, not clusters. here code: 1- bwconncomp clear close clc = imread('circles.jpg'); bw = im2bw(a); %// convert binary threshold of 0.5. cc = bwconncomp(bw); %// find connected components. this cc looks like, i.e. structure couple fields: cc = connectivity: 8 imagesize: [256 256] numobjects: 15 pixel

swing - How do you change variable value(s) in Java based on user input in a GUI? -

i designing gui farm. farm consists of 3 actors (weed, bean plant , farmer). upon running farm gui, shows movement of farmer planting , removing weed farm field. have defined probabilities actors ensure field not overpopulated. the following declared in simulator class. probabilities follows: public final double farmer_creation_prob = 0.01; public final double beanplant_creation_prob = 0.01; public final double weed_creation_prob = 0.01; i designing seperate gui allows variables above (and more) changed based on user inputs. example, have jtextfield weed creation probability, if user enters 3, want farmer_creation_prob = 3;. this how have created jtextfields 3 probabilities (declared in farmgui class): weedfield = new jtextfield (); beanfield = new jtextfield (); farmerfield = new jtextfield(); with limited understanding of java, have tried following: public final double weed_creation_prob = weedfield.gettext(); however, states "cannot find symbo

api - Retrieve ASIN from MPN through Amazon -

i operate out of motorcycle dealership , started amazon marketplace store. i've run issue a lot of product not have conventional upc codes uploading product amazon rather cumbersome task. i'm finding when search of part numbers product on amazon. when case product has been assigned asin , therefore can use asin in place of upc when uploading product. the question does amazon provide form of api allows customers myself search products based on mpn , return asin(s) of product? the knowns i know not items have in store on amazon. some mpns may return multiple asins. there individuals have built upc asin converters driven amazon. the unknowns does amazon provide of api this? is api public? free? have sign it? my abilities i have enough experience writing code given api , documentation may able figure out must of myself. i'm confused services amazon offers. i'm looking called aws ? amazon ec2 ? have no idea find resource this. what after

amazon web services - AWS autoscale ELB status checks grace period -

i'm running servers in aws auto scale group. running servers behind load balancer. i'm using elb mange auto scaling groups healthchecks. when servers been started , join auto scale group join load balancer. how time (i.e. healthcheck grace period) need wait until let them join load balancer? should after servers in state of running? should after servers passed system , instance status checks? there 2 types of health check available auto scaling groups: ec2 health check: uses ec2 status check determine whether instance healthy. operates @ hypervisor level , cannot see health of application running on instance. elastic load balancer (elb) health check: causes auto scaling group delegate health check elastic load balancer, capable of checking specific http(s) url. means can check application correctly running on instance. given system using elb health check, auto scaling trust results of elb health check when determining health of each ec2 instance. c

ruby - Making two associations to same model column in Rails -

i'm pretty new rails. i'm trying setup associations model in rails. i have user model columns: id, user_name, email now trying create model expense has associations user model. purpose of model create expense , associate expense 2 different users same model user. association second user split amount between 2 users. this i'm intending while creating model expense: $ rails generate model expense amount:decimal user:references split_with:references now how associate split_with user model, since both references associate same user model's id of 2 users? you can refer same model 2 different ways: class expense < activerecord::base belongs_to :user belongs_to :approving_user, class_name: 'user' end this require columns user_id , approving_user_id present. can adjust generated migration , model code match this. as sure index: true set on these columns.

python - Upload image with an in-memory stream to input using Pillow + WebDriver? -

i'm getting image url pillow, , creating stream (bytesio/stringio). r = requests.get("http://i.imgur.com/sh9lkxu.jpg") stream = image.open(bytesio(r.content)) since want upload image using <input type="file" /> selenium webdriver. can upload file: self.driver.find_element_by_xpath("//input[@type='file']").send_keys("path_to_image") i know if possible upload image stream without having mess files / file paths... i'm trying avoid filesystem read/write. , in-memory or temporary files. i'm wondering if stream encoded base64, , uploaded passing string send_keys function can see above :$ ps: hope image :p you seem asking multiple questions here. first, how convert a jpeg without downloading file? you're doing that, don't know you're asking here. next, "and in-memory or temporary files." don't know means, can temporary files tempfile library in stdlib, , can in-memory t

MySQL: Why is simple query not using index, performing filesort -

i have table defined so: `id` int(10) not null auto_increment, `slug` varchar(150) not null, `title` varchar(150) not null, `description` text not null, `ordinal` int(10) not null default '0' let's call t1 in t1 , have index on ordinal . this table contains few rows, it's definitions table this, definitions in order want them select * t1 1 order ordinal; if perform explain on statement, following: id? select_type? table? partitions? type? possible_keys? key? key_len? ref? rows? extra? 1 simple t1 null null null null null 5 using where; using filesort it doesn't matter row above screwed in alignment. important part it's using filesort , can't figure out why. since it's 5-10 rows in table, can feel it's not important filesort makes open_tables go bit bananas since mysql (according mighty internet) opens 2 tables each filesort query needs perform. so, greatful here. thanks. your t

c++ - How to get the specific output while reading from file -

#include<iostream> #include<fstream> #include<stdlib.h> #include<string.h> using namespace std; class data { public: char name[20]; long long int ph; data() { strcpy(name," "); for(int i=0;i<10;i++) ph=0; } void getdata() { cin>>name; cin>>ph; } }; int main() { int n; fstream file; file.open("test1.txt",ios::app|ios::out); if(!file) { cout<<"file open error"<<endl; return 0;} cout<<"number of data want enter"<<endl; cin>>n; char a[1000]; //data temp; data d[n]; for(int i=0;i<n;i++) { d[i].getdata(); file<<d[i].name<<" "; file<<d[i].ph<<endl; } file.close(); file.open("test1.txt",ios::in); file.seekg(0); file>>a; while(!file.eof()) { cout<<a<<endl; file>>a; //cout<<a<<endl;

java - Error handling by redirection in spring download file controller -

this question nicely explains on how write download file controllers in spring. this question nicely explains post request cannot sent using response.sendredirect() i user redirected same page error caused file download error. here workflow user hits www.abc.com/index [controller has mapping /index.jsp , return modelandview] at page, have file download has url www.abc.com/download?resource_id=123. [controller has mapping /download , returns void] when there error in file download, user should redirected www.abc.com/index error display. when there no error in file download, user stays @ same page , file download dialog appears. following snippet forwarding: @requestmapping(/download) public void execute(@requestparam(value = "resource_id" required = true) final string resource, final httpservletrequest request, final httpservletresponse response) { try { //some processing } catch { requestdispatcher dispatcher = request.getrequestdisp

html - Edit the Sidebar CSS -

Image
i want sidebar occupy whole container, i'll give capture of i'm looking for. this website. here have css code sidebars /* sidebar */ .sidebar { background-color:#fff; padding:13px; margin: 20px; margin-bottom:30px; padding-bottom:20px; color:#000; } .sidebartitle { background-color:#000; margin-left: -13px; margin-right: -13px; margin-top: -16px; padding: 20px; padding-bottom: 20px; margin-bottom:20px; font-family: 'raleway', sans-serif; text-transform:uppercase; font-size:22px; text-align:left; color:#fff; } #sidebar { position: relative; float: left; margin-left:15px; width: 340px; margin-top:20px; } and here have code posts #contentmiddle { margin-left: 370px; padding: 20px 0px 0px 0px; width:650px; } .post { padding:40px; margin-top:60px; background-color:#fff; background-color:#fff; background-repeat: no-repeat; padding-top:0; padding-bottom:0; } this container /* content */ #content {

SQL Server multiple conditions from table -

table1 contains distinct list of members , respective date ranges member_id | date_start | date_end table2 large data set contains large list of entries members, many entries many members member_id | date | value what sql server query need implement retrieve entries table2 meeting conditions table1? want retrieve entries table2 falling between date_start , date_end respective member_id. you need use join : select * `table1` t1 left join `table2` t2 on t1.member_id = t2.member_id t2.date between t1.date_start , t1.date_end if want entry table2 replace * t2.* you can have well: http://dev.mysql.com/doc/refman/5.0/en/join.html

Emacs 24's python.el + ipython cannot complete module names -

i'm using emacs 24.4.1 on osx (installed homebrew), built in python.el , , python 3 (also installed homebrew), along ipython 2.3.0. have in .emacs : (setq python-shell-interpreter "/usr/local/bin/ipython3" python-shell-prompt-regexp "in \\[[0-9]+\\]: " python-shell-prompt-output-regexp "out\\[[0-9]+\\]: " python-shell-completion-setup-code "from ipython.core.completerlib import module_completion" python-shell-completion-module-string-code "';'.join(module_completion('''%s'''))\n" python-shell-completion-string-code "';'.join(get_ipython().completer.all_completions('''%s'''))\n") everything works correctly when invoke m-x run-python , except 1 thing: <tab> -completion of module names doesn't work in repl (it says "no match" in *messages* buffer). i'm pretty sure working emacs 24.3, upgraded recently, i'm not 100%

C++ compiler issue: 3>cl : Command line error D8016: '/clr' and '/arch:SSE2' command-line options are incompatible -

i've been messing around c++ first time, , have been following tutorial on how program simple synth. ive been fine till now, after continuously getting error , failing find solution (yes i've looked here similar posts , none of solutions have worked) can explain error means , how can figure out? thanks! more information: i worked until got particular part of tutorial, having no errors completing section. http://www.martin-finke.de/blog/articles/audio-plugins-011-envelopes/ i disregard drescherjm's suggestion, instead changing project type. you have set project use .net run-time. (/clr = /commonlanguageruntime). given source archive includes macosx folder , more particularly, cbp file (code::blocks project) doesn't use ms compiler (so therefore, can't built using clr), it's entirely safe not intended c++/clr program, instead intended plain c++ one. just re-create project , copy existing files new folder, re-add them project , voila!

Php Json get first element info -

so i'm using php twitter api grab list of tweets hashtag. i'm looking following info returned json; 'screen_name' , 'text'. the screen_name on line 44 , text on line 20. here json output. object(stdclass)#5 (2) { ["statuses"]=> array(15) { [0]=> object(stdclass)#6 (24) { ["metadata"]=> object(stdclass)#7 (2) { ["iso_language_code"]=> string(2) "en" ["result_type"]=> string(6) "recent" } ["created_at"]=> string(30) "fri dec 05 21:22:00 +0000 2014" ["id"]=> float(5.4097942452372e+17) ["id_str"]=> string(18) "540979424523718656" ["text"]=> string(100) "shits getting real. crit happens tonight. #dnd #dungeonsanddragons #nerd #rpg http://t.co/44lnrmmfte" ["source"]=> str

request - how do basic jquery ajax in typo3 flow? -

i trying basic ajax. want onchange event on select call ajax function options select , fill in. not sure how in simple way in typo3 flow. php code action looks this: public function getproductsbycategoryaction( $category='' ) { $postarguments = $this->request->getarguments(); echo __line__; typo3\flow\var_dump($postarguments); die; } and ajax call looks this: jquery('#get_category').change(function(event) { event.preventdefault(); alert('get products'); var category = jquery('#get_category').val(); alert(category); jquery.ajax({ url: "/admin/orders/getproductsbycategory.html", data: { 'category': category }, async: true, datatype: 'html', success: function(data) { alert('hi mom'); ...

php - filter json results based on value with url -

i running mysql query in php file , parsing json follow: $json_response = array(); while ($row = mysql_fetch_array($result, mysql_assoc)) { $row_array['artist'] = $row['artist']; $row_array['song'] = $row['song']; //push values in array array_push($json_response,$row_array); } echo json_encode($json_response); there thousands of entries; there way can filter json results based on value? like: mylink.php/artist1 or mylink.php?artist=1 i appreciate sort of ideas. thanks you can so: // artist info $artist_id = isset($_get['artist']) ? intval($_get['artist']) : 0; $sql = "select * artist"; if($artist_id) $sql .= " artist=$artist_id"; mysql_query($sql);

Xcode - error: pathspec '...' did not match any file(s) known to git -

i using local git repo. when try commit changes core data model file (.xcdatamodel), message: error: pathspec '.../datamodel.xcdatamodeld/datamodel.xcdatamodel/contents' did not match file(s) known git. how fix , commit model other file? the chosen answer specific own question , gives 0 insight on actual cause. problem indeed, mentioned before changing of filename's case. me because of macbook/osx. apparently windows has same 'thing'. cause: git isn't able recognise change 'filename' 'filename'. here's list of solutions stumbling upon this. should run @ project root: the permanent fix work on current , future projects change git case setting. file should committed afterwards git config core.ignorecase false --global the project fix git config core.ignorecase false the just give me line of code can move on fix - credit bruce git commit -a -m "pathspec did not match file(s) known git fix" the i p

Oauth2 Playground exchange authorization code for token: 400 error -

i've been following basic oauth 2.0 tutorial create oauth 2.0 server. whole part worked fine, when tried play around in google oauth2 playground following this page i'm getting errors. i've followed steps in above link except used http://localhost/wordpress/authorize.php?state=xyz authorization endpoint because otherwise error saying state required , didn't want edit code yet. now, seems work fine authorizing apis. i'm directed localhost site , when authorize request returned oauth2 playground. when go on next step , attempt exchange returned authorization code token, given 400 error. the whole request/response follows: post /wordpress/token.php http/1.1 host: localhost content-length: 191 content-type: application/x-www-form-urlencoded user-agent: google-oauth-playground code=6d408c28d468db6586320bff3aacf16492489b67&redirect_uri=https%3a%2f%2fdevelopers.google.com%2foauthplayground&client_id=newclient&scope=& client_secret=newpass&am

c++ - non template function in a template class -

i wondering if there way place non template function within template class. put don't want compiler repeat function each type since function manipulating pointers hence there no type. possible? so if have code this template <typename t> class class{ }; then each function within repeated each type t don't want happen i function static types , there not repeat in memory each individual type. inherit function base class class base_class { public: static void not_a_templated_function(); }; template <typename t> class class: public base_class { };

how to concatenate option in scala -

what's elegant/right way in scala string concatenate option none renders empty string , variables have value don't wrapped in some("xyz") case class foo(bar: option[string], bun: option[string]) println(myfoo.bar+ "," + myfoo.bun) the output want example hello, instead of some(hello),none to value option in safe way use getorelse , provide default argument, used in case option none . in example this: case class foo(bar: option[string], bun: option[string]) println(myfoo.bar.getorelse("") + "," + myfoo.bun.getorelse("")) then you'll required result

python - Parsing model fields in Django REST Framework -

i have simple django model datetime field i'm building django rest framework. django saves datetime fields in format resembles 2014-12-07t17:00:00z . possible parse field in serializer when pull in api response it's in proper format? # serializer class eventserializer(serializers.modelserializer): class meta: model = events depth = 1 # view class eventviewset(viewsets.modelviewset): queryset = events.objects.all() serializer_class = eventserializer # model class events(models.model): title = models.charfield(max_length=250) content = models.textfield(blank=true, null=true) date = models.datetimefield(blank=true, null=true) location = models.foreignkey(locations, related_name='events') def __unicode__(self): return unicode(self.title) class meta: verbose_name_plural = 'events'

c# - Json serialization variable PropertyName -

i use c# , newtonsoft.json library serialization , deserialization of json. i have class this public class animal { [jsonproperty(propertyname = "dog")] public key value {get;set;} } if instantiate as animal = new animal{ key = "bobby" }; and serialize i'll have json like { "dog": "bobby" } can change propertyname of serialization dynamically? instance, if want put "bird" or "cat" instead of "dog"? public class animal { public keyvaluepair<string,string> value {get;set;} } animal = new animal { value = new keyvaluepair("dog","boddy")}; if want bird animal = new animal { value = new keyvaluepair("bird","bird1")};

swift - Expected Declaration error messages on empty lines -

i getting expected declaration error message on 2 empty lines , not know how fix them. don't understand why coming on empty line. here code. var randomvalue = arc4random_uniform(15) + 1 var secondrandomvalue = arc4random_uniform(15) + 1 var firstnumberlabel: uilabel self.firstnumberlabel.text = "\(randomvalue)" any suggestions on how fix problem? try declare firstnumberlabel globally viewcontroller class this: var firstnumberlabel : uilabel = uilabel() after can access anywhere have tried this: import uikit class viewcontroller: uiviewcontroller { var firstnumberlabel : uilabel = uilabel() override func viewdidload() { super.viewdidload() var randomvalue = arc4random_uniform(15) + 1 var secondrandomvalue = arc4random_uniform(15) + 1 self.firstnumberlabel.text = "\(randomvalue)" } } may can you.

bash - Unix Shell Scripts Functions -

i'm learning make little programs in shell , looking how define function uses system calculator (bc -l). show i'm trying do: #!/bin/bash square (){ need here! } cube (){ need here! } rectangle (){ need here! } exit (){ } need here! echo "little program computes following:" echo "a) surface of square" echo "b) volume of cube" echo "c) surface of rectangle" echo "e) exit" echo "choose option want compute" read answer if [ $respuesta == "a" ] echo "what's side of square" read l` after line don't how calll function "eats" user's answer , display computation. things worst because after computation have ask user if wants continue or exit. if me, grateful. sorry english. i'm not native speaker. is looking for?: menu="some items choose from: a) b) else" sample () { a="$1" b="$2" c="$3&

php - Magento Upgrade 1.5.1 to 1.9.1 now Cannot add the item to shopping cart -

i upgraded magento platform , working in admin , front end except shopping cart. here exception log. when try add item cart, cart won't add product. i upgraded on front end using 1.5.1 database columns added salescoupon table 2014-12-06t00:21:16+00:00 debug (7): exception message: sqlstate[42s22]: column not found: 1054 unknown column 'primary_coupon.code' in 'having clause', query was: select `main_table`.*, `rule_coupons`.`code`, group_concat(extra_coupon.code) `extra` `salesrule` `main_table` left join `salesrule_coupon` `rule_coupons` on main_table.rule_id = rule_coupons.rule_id , rule_coupons.is_primary = 1 left join `salesrule_coupon` `extra_coupon` on extra_coupon.rule_id = main_table.rule_id , extra_coupon.is_primary null (is_active=1) , (find_in_set(1, website_ids)) , (find_in_set(0, customer_group_ids)) , (from_date null or from_date<='2014-12-05') , (to_date null or to_date>='2014-12-05') group `main_table`.`rule_id` havi

mysql - GROUP BY and ORDER BY issues -

Image
i have following query: select distinct ( s.styletitle ), count(p.id) `picturecount` `style` s left join `instagram_picture_style` ps on s.id = ps.style_id left join `instagram_shop_picture` p on ps.picture_id = p.id left join `instagram_picture_category` c on c.picture_id = p.id left join `instagram_second_level_category` sl on c.second_level_category_id = sl.id sl.id =25 group p.id order picturecount however query gives me: i wanted list ordered style has pictures in it. did wrong? why giving me 1 on of styles, pretty sure has more pictures style order by doesn't have underscores. equally important, using distinct in way seem think function. not. modifies on select , applies columns. you should group by same column have in distinct. this: select s.styletitle, count(p.id) `picturecount` `style` s left join `instagram_picture_style` ps on s.id = ps.style_id left join `instagram_shop_picture` p on ps.picture_id = p.id left join `instagram_pi

gas - 'Wrong' usage of carry flag in ARM subtract instructions? -

the arm subtraction instructions carry ( sbc , rsc ) interpret carry flag (c) as: 0 means borrow 1 means no borrow why carry flag c inversed make arithmetic? sbc r0, r1, r2 @ r0 = r1 - r2 - !c we know grade school that a = b - c = b + (-c) and elementary programming classes negate number in twos complement invert number , add 1 a = b + (~c) + 1 and works out because when feed adder logic our values invert second operand , invert carry in. (there no subtract logic use adder subtraction) so processor implementations choose invert carry out. inverting stuff subtract, , raw carry out of msbit on normal subtract (without borrow) 1, when there borrow carry out 0, inverting carry out can call "borrow" instead of carry (or instead of /borrow or !borrow or borrow_n) which ever way it, if have subtract borrow, need either invert or not invert carry in depending design choices carry out on subtract (normal without borrow). so subtraction is a = b

ios - Saving User Data (Swift) -

i'm making app, , needs allow user save data, if high score, or if unlock special character , character used when app starts up. , if want go different character, save. should go find resources this? well, there quite few ways persist data in ios. archiving, userdefaults, plists, , of course core data(list not exhaustive); each can piece or of need(in case of core data). if want items remain in cloud, can @ cloud kit or third party solutions parse, or can roll own server. the apple documentation resource, there many books on core data. if you, core data. good luck!

java - Button not working. Keeps on forcing app close -

whenever insert code (button) fragment, app forced close. made xml file , call in fragment java has adapter , in xml use framelayout put button @ bottom of page. try using footer same error got. knows how solve one? :) xml file <?xml version="1.0" encoding="utf-8"?> <framelayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/takequiz" android:orientation="horizontal" android:background="@drawable/bg_linux_commands" android:layout_width="fill_parent" android:layout_height="fill_parent"> <linearlayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:orientation="horizontal"> <listview android:id="@id/android:list" android:layout_width="300dp" android:layout_height="300dp" android:layou

pyqt4 - Set QWebView to mobile dimensions -

i trying crawl pages on site mobile user. set user agent match iphone, , trying set dimensions match 320x568. after that, want take screenshot can see pages like, , make sure correct. however, it's desktop view. how can set qwebview or qwebpage mobile dimensions when load specific page? below self.qweb qwebview . saw this question using qmainwindow , headless crawl, , works great is, except setting width & height of "browser" view. tried variations of it, waiting page load, , resetting size, it's not working. if hasattr(self, 'height') , hasattr(self, 'width'): size = self.qweb.page().mainframe().contentssize() self.qweb.resize(320, 568) self.qweb.setpage(self.page()) self.qweb.loadfinished.connect(self.loaded_page) update tried well, after page loaded, qsize returned 980x568. tried same function calls in loaded_page method after page loads, didn't work either. resets view larger size when action on page performed.

c++ - swap with non-const reference parameters -

i got [error] invalid initialization of non-const reference of type 'float&' rvalue of type 'float' #include <stdio.h> void swap(float &a, float &b){ float temp=a; a=b; b=temp; } main() { int a=10, b=5; swap((float)a, (float)b); printf("%d%d",a,b); } vlad correct, why cast float ? use int values. however, if have reason doing way, must consistent in cast , references : #include <stdio.h> void swap(float *a, float *b){ float temp=*a; *a=*b; *b=temp; } int main() { int a=10, b=5; swap((float*)&a, (float*)&b); printf("\n%d%d\n\n",a,b); return 0; } output: $ ./bin/floatcast 510 when pass address function, must take pointer argument. void swap(float *a,.. when need reference address of variable (to pass pointer ), use address of operator & . when handle values passed pointer , in order operate on values pointed pointer must dereference

Application crashed while Writing data to excel file in android -

i writing application writes data excel file in android...but application crashes please me did mistake here's mainactivity.java package com.example.excel_file; import java.io.file; import java.io.fileinputstream; import java.io.fileoutputstream; import java.io.ioexception; import java.util.iterator; import org.apache.poi.hssf.usermodel.hssfcell; import org.apache.poi.hssf.usermodel.hssfcellstyle; import org.apache.poi.hssf.usermodel.hssfrow; import org.apache.poi.hssf.usermodel.hssfsheet; import org.apache.poi.hssf.usermodel.hssfworkbook; import org.apache.poi.hssf.util.hssfcolor; import org.apache.poi.poifs.filesystem.poifsfilesystem; import org.apache.poi.ss.usermodel.cell; import org.apache.poi.ss.usermodel.cellstyle; import org.apache.poi.ss.usermodel.row; import org.apache.poi.ss.usermodel.sheet; import org.apache.poi.ss.usermodel.workbook; import android.app.activity; import android.content.context; import android.os.bundle; import android.os.environment; import and

python - Using the `.find_next_siblings` function in Beautiful Soup -

i attempting write output of web scraping csv file, here code: import bs4 import requests import csv #get webpage apple inc. september income statement page = requests.get("https://au.finance.yahoo.com/q/is?s=aapl") #put beautiful soup soup = bs4.beautifulsoup(page.content) #select table holds data of interest table = soup.find("table", class_="yfnc_tabledata1") #creates headers table headers = table.find('tr', class_="yfnc_modtitle1") #creates generator holds 4 values yearly revenues company total_revenue = headers.next_sibling cost_of_revenue = total_revenue.next_sibling gross_profit = cost_of_revenue.next_sibling.next_sibling wang = headers.find_next_siblings("tr") #iterates through generator above , writes output csv file open('/home/kwal0203/desktop/apple.csv', 'a') csvfile: writer = csv.writer(csvfile,delimiter="|") writer.writerow([value.get_text(strip=true).en

javascript - How to evaluate Angular expression in child directive and expose it on parent directive? -

i have directive represents group of objects, let's call people . this directive has ng-repeat in template repeats child directive, e.g. person , has expression attribute persongreeting should evaluate on scope. both people , person use isolate scope. how can set these directives such can expose persongreeting on people directive , have evaluated within scope of person directive? here example: angular.module('app', []) .controller('ctrl', function($scope) { $scope.mypeople = [{ id: 1, name: 'bob' }, { id: 2, name: 'steve' }, { id: 3, name: 'joe', }] }) .directive('people', function() { return { scope: { peoplelist: '=', eachpersongreeting: '&' }, template: '<ul><person ng-repeat="currentperson in peoplelist" person-greeting="eachpersongreeting(curren

ios8 - Can't set constraints of UItableView's tableHeaderView height by autolayout in Storyboard -

Image
i want screen shows 1 tableveiwcell headerview.i added uiview header view on top of uitableview "size classes" in storyboard(just drag uiview on top of uitableview), can compatible devices screen size in way. so change header view's height constraints want to. when try that, cant set constraints headerview(xocde doesn't enable me select constrains in storyboard, image 2 below). below. any ideas, thanks! the project code here: https://github.com/williamhqs/autolayouttableviewheaderview eidt: seems still can't set in storyboard. then have change table header view's frame code update constraints. uiview *v = self.tableview.tableheaderview; cgrect fr = v.frame; fr.size.height = [uiscreen mainscreen].bounds.size.height -100; v.frame = fr; [self.tableview updateconstraintsifneeded]; i think uiview doesn't have superview not showing constraints view.

Android Lollipop know if app as Usage Stats access -

since android lollipop, have api accessing apps usage stats. however, app must granted permissions user. i know redirecting user settings using settings.action_usage_access_settings. now, question how know user has granted permissions can stop redirecting him settings. thanks! you can query usagestats daily interval , end time current time , if nothing returned means user hasn’t granted permissions @targetapi(build.version_codes.lollipop) public boolean doihavepermission(){ final usagestatsmanager usagestatsmanager = (usagestatsmanager) context.getsystemservice(context.usage_stats_service); final list<usagestats> queryusagestats = usagestatsmanager.queryusagestats(usagestatsmanager.interval_daily, 0, system.currenttimemillis()); return !queryusagestats.isempty(); } daily interval start date 0 , end date current time must @ least return todays usage.so empty if permissions not granted.

tortoisesvn - Create New user in tortoise SVN installed in windows server -

i installed tortoise svn in windows server. want create different user, please let me know how create users, right able check in check out code adminstrator. please let me know how create users. you haven't set proper subversion server, can't you're attempting do. you need install subversion server such collabnet subversion edge, wandisco's ubersvn, visualsvn server, or put standard subversion distribution , (if want use http) apache. official subversion manual has more details.

google drive sdk - How to get backup file or file conversion -

i had uploaded web design files google drive. files extenstions .html,.css and.js, files had been uploaded google drive. today, trying download files , come know files had been stored extension .docx. don't have other backups of source file. want source code of webdesigns. how can them? in file properties, showing me file type .docx

php - How do I sort elements in a while loop? -

i'm display comments on page, works fine want display comments user first. so, how display user comments user_id first? i'm using while loop display comments. i grateful if me. :) <?php $sql = "select * `comments` `post_id`=$pid , `active`=1 order ups-downs desc"; $result = $mysqli->query($sql); $count = $result->num_rows; if($count == 1){ $counttext = "1 comment"; }else{ $counttext = $count ." comments"; } ?> <div class="media-area media-area-small"> <h3 class="text-center"><?php echo $counttext; ?></h3> <?php while($row = $result->fetch_assoc()){ $uid = (int)$row["user_id"];