Posts

Showing posts from June, 2012

Python fabric cant be executed from python using subproccess -

in python trying execute fabfile , ,i below error subproccess output. installed fabric using easy install. if run code command line works. python no go. assume there issue how using popen command? /bin/sh: 1: fab: not found below how start fabric python: cmd = """fab -h 111.111.111.111 aws_bootstrap initial_chef_run:aws_server.json,aws-test,development -w """ os.chdir(fab_path) #change dir fabfile located p = subprocess.popen(cmd, shell=true,stderr=subprocess.stdout,stdout=subprocess.pipe) ps added below popen below error: executable="/bin/bash" /bin/bash: fab: command not found from command line below means terminal can find fab. fab fatal error: couldn't find fabfiles! remember -f can used specify fabfile path, , use -h help. aborting. try use whole path fab. path fab on system, can use which fab . however, can't think of reason why calling fab python might better using execute function of fab:

ios - How to check if Safari restricted in Settings? -

when safari restricted, [[uiapplication sharedapplication] canopenurl:url]] return true when call [[uiapplication sharedapplication] openurl:url]] nothing happened. i want check if safari restricted in settings - general - restrictions. this isn't possible in way there hackie way achieve anything. need is, when call safari set global timer before it, schedule few seconds (may 5 seconds), if safari open, app call - (void)applicationdidenterbackground:(uiapplication *)application , should invalidate global timer, in other case timer fire on scheduled time , you'll know safari couldn't open. can invalidate timer , show user appropriate message. p.s. comes mind when read question, not sure other possibilities or ways. there can more elegant way.

opengl - GLSL component-wise equal comparison -

i'm trying check if given pixel in texture white, black, or neither. i've decided use equal function described in opengl 4 reference pages . believe i'm having issue getting syntax correct. i using opengl version 4.0.0 , opengl shading language version 4.00. here relevant part of fragment shader code: //texture 1 vec4 texturecolor1 = texture(texunit1, texturecoord); //texture 2 vec4 texturecolor2 = texture(texunit2, texturecoord); //texture 3 (only contains black , white pixels) vec4 texturecolor3 = texture(texunit3, texturecoord); vec4 finaltexturecolor; vec4 whitecolor = vec4(1.0, 1.0, 1.0, 0.0); //define white vec4 blackcolor = vec4(0.0, 0.0, 0.0, 0.0); //define black if (bvec equal(texturecolor3, whitecolor)){ //if texture 3 pixel white finaltexturecolor = texturecolor1; } else if (bvec equal(texturecolor3, blackcolor)){ //if texture 3 pixel black finaltexturecolor = texturecolor2; } else { //not black or

terminal - png2ico exporting ICO in lower quality than the original PNGs -

Image
i have 6 png files want bundle 1 ico file. i'd use png2ico instead of web app convertico.org's web app . when ico produced using png2ico, quality of ico seems have dropped. below 2 images (100% view , zoomed in) comparing png2ico output (right) original png (left). is limitation of png2ico? can stop png2ico lowering quality? can recommend way of bundling 6 pngs 1 ico using terminal on osx? i emailed developer of png2ico , sounds png2ico supports 256 colors isn't acceptable needed. have since discovered imagemagick can convert , bundle multiple pngs 1 ico rob w's post here .

php - Wordpress, editing blog index link -

Image
im trying edit webisites blog inherited creator have no contact with. have been fiddling site little more week don't know how edit links in blog index. here link site's blog: http://bestdetails.com/blog/ as can see box link whole article, , in article if scroll down can see tags post. i want tags inside box show on blog index page instead. i want put tags red circle is: i know can edit blog in blog.php, don't know code or in html text put code. in order access post tags, have function get_tags() ; it called way: $tags = get_tags(); $html = '<div class="post_tags">'; foreach ( $tags $tag ) { $tag_link = get_tag_link( $tag->term_id ); $html .= "<a href='{$tag_link}' title='{$tag->name} tag' class='{$tag->slug}'>"; $html .= "{$tag->name}</a>"; } $html .= '</div>'; echo $html; the place edit depend on theme, can in index, page.php o

cryptography - 3DES key exchange with RSA in Java -

i'm implementing webservice in java in server needs send 3des key client using rsa algorithm. symmetric generated server. both server , client have own rsa key-pairs, exchanged. in code, server sends symmetric key client. @webmethod public byte[] getsymmetrickey(){ try{ cipher cipher = cipher.getinstance("rsa"); // first, encrypts symmetric key client's public key cipher.init(cipher.encrypt_mode, this.clientkey); byte[] partialcipher = cipher.dofinal(this.key.getbytes()); // finally, encrypts previous result server's private key cipher.init(cipher.encrypt_mode, this.privatekey); byte[] cipherdata = cipher.dofinal(partialcipher); return cipherdata; }catch (exception ex){ ex.printstacktrace(); } } when run encryption server's private key, error of illegalblocksizeexception . why exception if padding activated default? i've tried explicitly activate padding ciphe

get - TYPO3 getting image from page content -

i'm working on first typo3 project , i'm done template, can't figure out how make work: my page content 1 column header, text , title in every field. don't have problems showing header , text on website, image won't work. image-path fileadmin/user_upload/ , can show setting filename in code, thats not want. content object array, code image 1 of versions found when searching, none of them worked: page.20 = content page.20.table = tt_content page.20.wrap = <div id="content">|</div> page.20.renderobj = coa page.20.renderobj.wrap = <div id="news">|</div> page.20.renderobj { 10 = text 10.stdwrap.field = header 10.stdwrap.wrap = <div id="newstitle"><span>|</span></div> 20 = image 20.stdwrap.field = image 20.stdwrap.wrap = <div id="newsimage><img src="fileadmin/user_upload/|"</img></div> 30 = text 30.stdwrap.field = bodytext 30

javascript - How to change an attribute value in a validation form -

i have created validation form, 1 of fields have compile: <input type="number" name="height" min="160" max="200"/> but, want modify minimum number if clicks on radio button. <input type="radio" name="gender" value="male"> if clicks here want set minimum number of height 170 <input type="radio" name="gender" value="female"> if clicks here want set minimum number of height 160 can me? :) try this: <input id='height_input' type="number" name="height" min="160" max="200"/> <input type="radio" name="gender" value="male" onclick="setmin(170)"> <input type="radio" name="gender" value="female" onclick="setmin(160)"> then in javascript: function setmin(n) { document.getelementbyid('height_input&

C++ MovieList array and pointer -

i'm still bit stuck on part on assignment. here prompt asking: now can modify loadmovies function create movielist object , add each of movie objects it. function loadmovies should return pointer movielist object. means need create movielist object dynamically , on heap. change main function , store returned movielist pointer in variable. test if works expected, can use printall function of movielist object. here code far: class movielist { public: movie* movies; int last_movie_index; int movies_size; int movie_count = 0; movielist(int size) { movies_size = size; movies = new movie[movies_size]; last_movie_index = -1; } ~movielist() { delete [] movies; } int length() { return movie_count; } bool isfull() { return movie_count == movies_size; } void add(movie const& m) { if (isfull()) { cout << "cannot add movie, list full" << endl; return; } ++last

c# 4.0 - how to work with pagination using since_id and max_id in linqtotwitter v2.1? -

i had used linqtotwitter fetching tweets twitter. can pull tweets 1 shot @ time if try pull tweets using sinceid , maxid returning empty , i'm executing range dates in query. below code i'm able 100 tweets.what i'm doing wrong thanks my code var auth = new singleuserauthorizer { credentials = new inmemorycredentials { consumerkey = "xxxxx", consumersecret = "xxxxx", oauthtoken = "xxxxx", accesstoken = "xxxxxxx" } }; var twitterctx = new twittercontext(auth); var owntweets = new list<status>(); ulong sinceid = 0; ulong maxid = 0; int laststatuscount = 0; var datefrom = datetime.now.adddays(-20); bool flag = true; var statusresponse = new list<status>(); statusresponse = (from tweet in twitterctx.status

c++ - Unable to reduce the code (combine cout with exit) -

i'm allowed insert 10 lines (strict) of codes program. have optimized program concise one. have posted code below. if (std::find(outvar.begin(), outvar.end(), line[x].tokens[0]) == outvar.end() || (std::find(inputs.begin(), inputs.end(), line[x].tokens[4]) == inputs.end()) { cerr << "undefined variable " << endl; exit(1); } if (opr[x].type == "mul" && opr[x1].asap_value == my_cycle + 1) { opr[x1].asap_value = my_cycle + 2; update_slack(); update_matrix(opr[x1].opid, 0); } if (latency < (opr[p2].asap_value + opr[p2].latency_op - 1) || opr[p2].asap_value == 0) { cerr << "latency value less circuit \n"; return -1; } this alone takes 10 lines , have 2 more compulsory lines of codes has added. i'n unable further reduce it. i'm looking combine err(cout) statement along exit (return) statement single statement. any appreciated. thank you make 1 line using commas: opr[x1].a

mysqli - Display MySql database errors in php -

this question exact duplicate of: php.ini causes warning: mysqli_error() expects parameter 1 mysqli, null given in/sys/index.php on line 19 2 answers how can mysql database errors 'trying insert duplicate record' captured , displayed in php? get error when inserting -- warning: mysqli_error() expects parameter 1 mysqli, boolean. in case know i'm getting because i'm trying insert duplicate record. php/mysql not give specific errors? display on screen end user understand . function querydb($sql){ $con=mysqli_connect("localhost","my_user","my_password","my_db"); // check connection if (mysqli_connect_errno()) { echo "failed connect database: " . mysqli_connect_error(); return 0; } $result = mysqli_query($con,$sql

c++ - Creating a Makefile that includes a header only library -

this first c++ program, , first time creating makefile im unfamiliar all. i have main file raytracer.cpp includes glm library this: #include "glm/glm.hpp" raytracer.cpp , glm directory in the same directory. how can create makefile project? the glm library header library. have compile files in glm directory? or glm.hpp? if, , if, code in header , nothing defined in corresponding source, don't have specify in makefile, rule raytracer.cpp. header code automatically inserted include statement is. have specify if need other objects or shared objects (libraries in .so .a etc.) included) for more information how create simple makefiles see here: how make simple c++ makefile?

javascript - How to make animations run smoothly on long pages? -

with javascript , php end created small website personal use. fetches images specific tumblr. idea behind can click on images save them desktop. when site has fetched have page-height of @ least 120,000px , huge dom. noticed transitions worked fine 4 images on page not work smoothly anymore. stutter. how can fix this? (i thought has page rendering) im on windows 8 using newest version of google chrome you're going want have lazy load (e.g. scroll load) if have page tall, that's consuming huge amount of memory.

matlab - Indexing a vector by an array in R -

in matlab , numpy, can index vector array of indices , result of same shape out, e.g. a = [1 1 2 3 5 8 13]; b = [1 2; 2 6; 7 1; 4 4]; a(b) ## ans = ## ## 1 1 ## 1 8 ## 13 1 ## 3 3 or import numpy np = np.array([1, 1, 2, 3, 5, 8, 13]) b = np.reshape(np.array([0, 1, 1, 5, 6, 0, 3, 3]), (4, 2)) a[b] ## array([[ 1, 1], ## [ 1, 8], ## [13, 1], ## [ 3, 3]]) however, in r, indexing vector array of indices returns vector: a <- c(1, 1, 2, 3, 5, 8, 13) b <- matrix(c(1, 2, 7, 4, 2, 6, 1, 4), nrow = 4) a[b] ## [1] 1 1 13 3 1 8 1 3 is there idiomatic way in r perform vectorized lookup preserves array shape? you can't specify dimensions through subsetting alone in r (afaik). here workaround: `dim<-`(a[b], dim(b)) produces: [,1] [,2] [1,] 1 1 [2,] 1 8 [3,] 13 1 [4,] 3 3 dim<-(...) allows use dimension setting function dim<- result rather side effect case.

sql server - Prevent INSERT of NULL values for Stored Procedure -

i'm working on stored procedure supposed update table order_truckdelivery info table basket_truckdelivery if second table has data. there 2 columns in each of tables: int id , datetime column called truckdeliverydate . if basket_truckdelivery has date stored current basket id, insert date order_truckdelivery table. right now, insert execute regardless if there in basket_truckdelivery table, , results in null value truckdelverydate column in order_truckdelivery column. want prevent happening not entirely sure how. basically, want perform , insert order_truckdelivery table if value of truckdeliverydate in basket_truckdelivery not empty or null. this have far...i have not done work stored procedures, not sure i've missed.... alter procedure [dbo].[savetruckintoorder] @basketid int, @orderid int begin -- set nocount on added prevent result sets -- interfering select statements. set nocount on; -- insert statements procedure here dec

java - Array is out of bounds while counting [CORRECT] -

i need print array contains duplicate words. have array working cannot figure out how count words properly. know when index counter (i) @ 49, , when (i) wants count 50, error don't know other way adjust method work. can please me? appreciated! this array: blue blue blue blue blue blue blue blue blue blue blue blue blue brown green green green green green green green green lemon lemon lemon lemon lemon lemon lilac lilac orange orange red red red red red red red red red red white white white white white yellow yellow yellow corrected code public static void printwordcount(string[] z) { system.out.println("there " + wordtotal + " words in file"); system.out.println("word w/ count:"); int = 0; int count = 0; while(i < z.length - 1) { if (z[i].equalsignorecase(z[i+1])) { i++; count++; } else if (!z[i].equalsignorecase(z[i+1]) || == z.length - 1) { count++;

vb6 - Best Way To Update Databse String Without Recompiling Code -

i have application references 2 databases. issue is, every time database changes, have change database string in source code , recompile exe. there better way this? thinking save strings file , have application read file. approach? yes, common way handle config file.

url - Website produces 404 error unless a valid path is specified after it -

i'm not quite sure how google problem, here am. purchased domain, set up, got free host, etc. however, whenever access url on own, without path, i'm brought webhost's 404 page. when access url valid path specified, page looking for. meaning, www.example.com -> 404. www.example.com/index.html -> page i'm trying go to. i've been digging on cpanel (my host 000webhost lack of funds) , couldn't find out of ordinary. advice appreciated. you have change directory indexes because index.php defualt 1. mmber area of 000webhost 2. file manager -> log in 3. open public_html 4. edit .htaccess 5.let .htacces that: # not remove line, otherwise mod_rewrite rules stop working rewritebase / directoryindex index.php index.html so when open directory(what http://example.com/ is) search first index.php, index.html , open if found.

jsp - AJAX validation fails for all form data -

Image
i using ajax jquery validation. https://code.google.com/p/struts2-jquery/wiki/validation in struts.xml, have <action name="createchannel" class="channel.channelaction" method="createchannel"> <interceptor-ref name="jsonvalidationworkflowstack"/> <result name="success">createsuccess.jsp</result> <result name="input">createchannel.jsp</result> </action> in jsp page have: <s:form method="get" action="createchannel" > <s:textfield name="channelname" label="channel name" /> <s:textfield name="channelband" label="channel band"/> <s:textfield name="vcfrequency" label="video carrier frequency"/> <s:textfield name="acfrequency" label="audio carrier frequency"/> <s:select name="chargetype" label="charge type" list="{'p

ios - How to properly sort an NSDictonary by key values that contain strings of time? -

i'm not understanding why it's not sorting properly. have nsdictionary contains key values of times in day. when try sort it, it's not ordered. events = @{@"12:00 pm" : @[@"1"], @"12:30 pm" : @[@"2"], @"1:00 pm" : @[@"3", @"4"], @"1:30 pm" : @[@"5", @"11"], @"2:00 pm" : @[@"6"], @"3:00 pm" : @[@"7"], @"3:30 pm" : @[@"8"], @"4:00 pm" : @[@"9"], @"4:30 pm" : @[@"10", @"11"], @"5:00 pm" : @[@"12", @"13", @"14"]}; eventtimes = [ [events allkeys] sortedarrayusingselector:@selector(localizedcaseinsensitivecompare:)]; when nslog eventtimes, produces output: ( "1:00 pm", "1:30 pm", &quo

loops - Computing the frequency of 5 in an array -

very basic query here beginner... i'm looking find frequency of number within array... in (mangled) code below have tried calculate occurances of number 5 in array i'm running problem in formulating loop heres code attempt: //compute frequency of 5 in array named numbers public class find //begin class { public static void main (string []args) //begin main { double numbers[] = {6,7,12,5,4,2,4,6,9,5,7,11,1,23,32,45,5}; //initialise , populate array int total = 0; int counter = 0; (int x : numbers) { if (numbers[] == 5; counter ++) {system.out.println( numbers[i] + " "); } } // end code // ***************** int numbers[] = {6,7,12,5,4,2,4,6,9,5,7,11,1,23,32,45,5}; for(int x : numbers) { if(x == 5) counter++; } system.out.println(counter); i can see trying use for each loop in implementation. @code whisperer provides alternative that, if want use for each loop have make sure loop type , array type match. in ca

c++ - While loop with pointers does not work -

i have problem, trying create list deletes highest value holding number, or numbers same value if value highest in list. thank kind of tips. // n,n1,head,next - pointers int j = 0; //this number helps put pointer forward 1 place while(n!=0){//should go through every digit of list if(head == 0){ cout << "list empty" << endl; } else{ n = head; n1=0; // n1 , n pointers while(n!=0){ if(n->sk == maxx){//searches maximum digit in list break; } else{ n1=n; n=n->next; } } if(head == n){ head = head->next; } else{ n1->next = n->next; } delete n; // deletes pointer holding highest value } n = head; //problem here or somewhere below j++; for(int i=0; i<j;i++){ // loop should make pointer point first n = n->next;

c# - Why OneDrive Upload fails? -

i have function upload serialized data (mydata) onedrive. private async void upload_click( object sender, system.eventargs e ) { if ( livehelper.session == null ) { var livestatus = await livehelper.initauth( app.clientid ); await livehelper.loadliveprofile(); } const string mydatafoldr = "mydata"; string folderid = await livehelper.getfolderid( mydatafoldr ); folderid = ( string.isnullorempty( folderid ) ? await livehelper.createfolder( livehelper.rootfolder, mydatafoldr ) : folderid ); string fileid = await livehelper.backgrounduploadfile( folderid, _app.mydata, app.skydrivefilename ); } public static async task<string> backgrounduploadfile<t>( string skydrivefolderid, t objecttoserialize,

c++ - When do I call boost::asio::streambuf::consume() and boost::asio::streambuf::commit()? -

i'm trying understand boost::asio::streambuf::consume() , boost::asio::streambuf::commit() calls. in docs, have examples, boost::asio::streambuf b; std::ostream os(&b); os << "hello, world!\n"; // try sending data in input sequence size_t n = sock.send(b.data()); b.consume(n); // sent data removed input sequence and boost::asio::streambuf b; // reserve 512 bytes in output sequence boost::asio::streambuf::mutable_buffers_type bufs = b.prepare(512); size_t n = sock.receive(bufs); // received data "committed" output sequence input sequence b.commit(n); std::istream is(&b); std::string s; >> s; i understand these 2 calls as understand documentation says them - call consume() remove characters input sequence inside boost::asio::streambuf , , call commit() move characters boost::asio::streambuf 's output sequence input sequence. fair enough. when actually call these? looking @ boost::asio::read_until() source, have t

paw app - Paste in pre-formatted JSON block -

i have lengthy block of json paste body. see can import file or paste text area. possible convert pasted text json can use nice json editor? when paste text area , switch json overwrites body (with warning). i guess ultimate question here is, how can pre-built piece of json json editor in paw? a sample of text paste is: { "type": "user", "id": "530370b477ad7120001d", "user_id": "25", "email": "wash@serenity.io", "name": "hoban washburne", "remote_created_at": 1392731331, "updated_at": 1392734388, "session_count": 0, "last_seen_ip" : "1.2.3.4", "unsubscribed_from_emails": false, "last_request_at": 1397574667, "remote_created_at": 1392734387, "created_at": 1392734388, "updated_at": 1398269574, "session_count": 179, "user_agent_d

performance - arrayfun 2d matrix input -

i have 3d matrix (8x5x100) containing numerical data. need pass 2d matrix (8x5) taken 3d matrix function , repeat process 100 times(length of 3d matrix). goal speed process as possible. sorry, cannot post actual code. current code: 3dmatrix=ones(8,5,100); i=1:100 output(i)=subfunction(3dmatrix(:,:,i)); end i read using arrayfun may faster looping. correct implementation? 3dmatrix=ones(8,5,100); i=1:100 output(i)=arrayfun(@(x) subfunction(x),3dmatrix(:,:,i)); end when try execute code using new method, keep getting errors in "subfunction" code. in "subfunction", uses size of 2d matrix calculations. however, when use arrayfun method, keeps reading size 1x1 instead of 8x5, causing rest of code crash, complaining not being able access parts of vectors since not calculated due size discrepancy. passing in matrix correctly? what correct way of going speed being imperative? thanks! did @ arrayfun documentation ? don't think need use lo

android - GCM message sending successfully on server but not received on Device -

maybe second set of eyes can me here. can't seem in receiver, though i'm getting successful sends when posting gcm send url server. manifest: <uses-permission android:name="com.google.android.c2dm.permission.receive" /> <permission android:name="<pkgname>.permission.c2d_message" android:protectionlevel="signature" /> <uses-permission android:name="<pkgname>.permission.c2d_message" /> <receiver android:name="<pkgname>.gcmbroadcastreceiver" android:exported="true" android:permission="com.google.android.gcm.c2dm.permission.send" > <intent-filter> <action android:name="com.google.android.c2dm.intent.receive" /> <category android:name="<pkgname>" /> </intent-filter> </receiver> <service a

uiviewcontroller - Pass variables with PresentViewController in Swift -

i'm working on swift application , have created links other views using presentviewcontroller can't figure out how pass variables. how pass variables new view? @ibaction func workoutpressed(sender: anyobject) { let storyboard = uistoryboard(name: "main", bundle:nil) let workoutview = storyboard.instantiateviewcontrollerwithidentifier("workoutview") workoutviewcontroller self.presentviewcontroller(workoutview, animated: false, completion: nil) //self.navigationcontroller?.pushviewcontroller(workoutview, animated: true) } thanks this easier think: don't need pass parameters because can access class variables of next view controller directly. that is, can this: workoutview.myvar = myval and, when view loads, myvar have value myval . (don't forget declare in workoutviewcontroller , though).

apache - index.php not working as default file in new directory -

i have looked @ several other answers of same question, yet none of answers have worked. what happening, when try create new directory, , create new file (index.php/index.html) visit directory (mydomain.com/newdirectory), loads 404 page not found error. this doesn't happen other directories. other ones load fine. i have tried using .htaccess file directoryindex index.php no luck. sorry if 1 of hundreds of same question.. couldn't find worked. thanks.

verilog - Which region are continuous assignments and primitive instantiations with #0 scheduled -

all #0 related code examples have found related procedural code (ie code inside begin - end ). continuous assignments , primitive instantiations? ieee 1364 & ieee 1800 (verilog & systemverilog respectively) give 1 line description can find (quoting version of ieee 1364 under section name " the stratified event queue "): an explicit 0 delay ( #0 ) requires process suspended , added inactive event current time process resumed in next simulation cycle in current time. i read documents , talked few engineers have been working verilog long before ieee std 1364-1995. in summary, inactive region failed solution synchronizing flip-flops verilog's indeterminate processing order. later verilog created non-blocking assignments ( <= ) , resolved synchronizing indeterminate order. inactive region left in scheduler not break legacy code , few obscure corner cases. modern guidelines avoid using #0 because creates race conditions , may hinder simulation performan

c# - Unity3D - Error - Cannot implicitly convert type 'int' to 'string' -

my code listed here, coding rpg game, should not matter when comes helping me fix this. problem console keeps giving me: assets/standard assets/scripts/base player/baseplayer.cs(20,21): error cs0029: cannot implicitly convert type 'int' 'string' code: using unityengine; using system.collections; public class baseplayer { private string playername; private int playerlevel; private basecharacterclass playerclass; private int speed; private int endurance; private int strength; private int health; public string playername{ get{return playername;} set{playername = value;} } public int playerlevel{ get{return playerlevel;} set{playername = value;} } public basecharacterclass playerclass{ get{return playerclass;} set{playerclass = value;} } public int speed{ get{return speed;} set{speed = value;} } public int endurance{ get{re

c# - Dropdown Remove Selected Item On Post Back -

i have place order form , have drop down list contains list of items binding from sharepoint list dynamically. whenever add item (for example item1) place order , click add another item button,i need remove (item1 ) drop down list avoid duplicate insert in sharepoint list or maybe need fill drop down without (item1) cause selected it. please give me solution. thanks in advance. kumar.

protocols - How does Swift memory management work? -

specifically, how swift memory management work optionals using delegate pattern? being accustomed writing delegate pattern in objective-c, instinct make delegate weak . example, in objective-c: @property (weak) id<foodelegate> delegate; however, doing in swift isn't straight-forward. if have normal looking protocol: protocol foodelegate { func dostuff() } we cannot declare variables of type weak: weak var delegate: foodelegate? produces error: 'weak' cannot applied non-class type 'foodelegate' so either don't use keyword weak , allows use structs , enums delegates, or change our protocol following: protocol foodelegate: class { func dostuff() } which allows use weak , not allow use structs or enums . if don't make protocol class protocol, , therefore not use weak variable, i'm creating retain cycle, correct? is there imaginable reason why protocol intended used delegate protocol shouldn't class p

arrays - In Ember pushObject calls supposed callbacks but removeObject does not -

i got following workspec item controller, controls checkboxes state: contractorapp.workspeccontroller = em.objectcontroller.extend needs: ['account'] selected: (-> work_spec = @get 'content' work_specializations = @get 'controllers.account.work_specializations' work_specializations.contains work_spec ).property() selection_changed: (-> work_spec = @get 'content' work_specializations = @get 'controllers.account.work_specializations' limit = @get 'controllers.account.specialization_limit' if @get( 'selected' ) && work_specializations.get('length') < limit work_specializations.pushobject work_spec else work_specializations.removeobject work_spec ).observes('selected') as see work_specializations parent's set of work specializations: want control (work_specializations.get('length') < limit) addition of element array.

java ee - strange illegalArgumentException rooted from JBoss 5.0.1 GA -

we have java web application deployed jboss 5.0.1 ga. sometimes, observe such exceptions our server log java.lang.illegalargumentexception @ java.nio.buffer.position(buffer.java:216) @ org.apache.tomcat.util.buf.b2cconverter.convert(b2cconverter.java:84) @ org.apache.catalina.connector.inputbuffer.realreadchars(inputbuffer.java:403) @ org.apache.tomcat.util.buf.charchunk.substract(charchunk.java:416) @ org.apache.catalina.connector.inputbuffer.read(inputbuffer.java:432) @ org.apache.catalina.connector.coyotereader.read(coyotereader.java:105) @ org.apache.catalina.connector.coyotereader.readline(coyotereader.java:158) .... the code our part triggered exception is public static string getstringfromrequest(httpservletrequest request) { string data = ""; try { bufferedreader reader = request.getreader(); stringbuilder sb = new stringbuilder(); // line below the line blows exception string line = reader.readline(); whil

css - box shadow left position using percent value -

how can use percent value in box-shadow property? for example one box-shadow: -25% 0 0 #000; chrome log said invalid value. possible so? or should use javascript? the box-shadow property not support percentages, can achieve similar effect using pseudo-element. there limitations technique, see comments. example: .shadow { background: #dddddd; padding: 1em; width: 100px; border: solid 1px #999999; position: relative;/*positioning required.*/ } .shadow:before { content: ''; display: block; position: absolute; width: 100%; height: 100%; left: 50%; top: 50%; z-index: -1;/*put shadow behind.*/ background: rgba(0, 0, 0, 0.25);/*give shadow fill.*/ box-shadow: 0 0 10px 10px rgba(0, 0, 0, 0.25);/*the spread value must greater or equal blur.*/ } <div class="shadow">shadow 50% off center.</div>

java - Android 2.2 front camera -

android 2.2 want open front camera , take picture. use code: private camera getfrontcamera() { camera camera = camera.open(); if (camera == null) { return null; } packagemanager pm = context.getpackagemanager(); if (pm.hassystemfeature("android.hardware.camera.front")) { parameters params = camera.getparameters(); params.set("camera-id", 2); camera.setparameters(params); } return camera; } but since have not worked. how enable front camera on android 2.2? there no android 2.2 phones shipped front facing camera - first android phones did have front facing camera started android 2.3 - gingerbread per new features of android 2.3 .

apache - PHP URL Error Handing -

i'm trying find way handle 4xx , 5xx error status codes throw url apache 404 error. i'd execute contents of if statement if there no error status codes thrown server. using following if statement seems hosted content not being found , throwing apache 404 error still running contents of if statement. if (@fopen('http://example','r')){ use resource } else{ use other resources } is there better way ensure url available before running it? edit: can't use curl in instance. thanks $headers = get_headers($url, 1); if ($headers[0] == 'http/1.1 200 ok') {//no error status codes thrown server $data = file_get_contents($url); //do }

javascript - Append DIV content using AJAX - Previous/Next -

so i'm trying append content html document div i've loaded content (from same file) using ajax. i'm trying have when click "previous" , "next" buttons loads previous or next project. here's have code. html (i'm loading content #ajax) <div class="p-modal"> <div id="p-controls"> <a id="p-close" href="javascript:;">close</a> </div> <div id="ajax"></div> </div> jquery $(document).ready(function() { $('.p-load').on('click', function(e) { e.preventdefault(); var href = $(this).attr('href'); if ($('#ajax').is(':visible')) { $('#ajax').css({ display:'block' }).animate({ height:'auto' }).empty(); } $('#ajax').css({ display:'block' }).animate({ height:'auto' },function() { $('#ajax').html('&l

mysql - How to simplify this subquery? -

i saw subquery http://www.programmerinterview.com/index.php/database-sql/derived-table-vs-subquery/ , has following subquery example, says written more simply. tell me how that? thank you! a table called employee columns employee_name, last_name, employee_salary, , employee_number. want find employees have salary above average. select employee_name employee employee_salary > (select avg(employee_salary) employee) you can use over clause calculate average salary , if current employee's salary bigger it. unfortunatelly, window functions can not used in clause, should use comman table expression, too. declare @employee table ( [employee_name] varchar(12) ,[employee_salary] int ) insert @employee ([employee_name], [employee_salary]) values ('empl1', 100) ,('empl2', 200) ,('empl3', 300) ,('empl4', 400) ,('empl5', 500) ,('empl6', 600) ,('

palindrome - Best algo for finding no. of steps required to convert a sequence to a palindromic sequence -

[my first question of stackoverflow, so, hi!] i'm not sure of rules around place, have straightforward question follows... the sequences 23, 45, 23 , 23, 45, 56, 23, 23, 56, 45, 23 examples of palindromes. sequence 23, 45, 56 not palindrome. sequence 23, 32 not palindrome either. sequence of length 1 palindrome. given sequence of integers can broken parts such each of them palindrome. consider sequence 34,45,34,56,34. can broken 3 palindrome sequences 34, 45, 34 constituting first, 56 constituting second , 34 constituting third. can broken in 5 palindrome sequences each containing single number. we want determine smallest number k such given sequence can broken k palindrome sequences. #include<iostream> using namespace std; int main() { int n; cin>>n; int num[n]; for(int i=0;i<n;i++) cin>>num[i]; int c[n]; int co=0; for(int i=0;i<n;i++){ if(num[i]!=-1){ for(int

java - Update JLabel Display with Jtextfield, Jcombobox, Jradiobutton and JCheckbox input (ALL OF THEM TOGETHER) -

i trying update jlabel based on of inputs listed in title. can update jradiobuttons, , jcheckboxes, not else. doing wrong? here code: write code proper indentation. see 1 example code if(select == itemevent.selected) { totalamountowed += breakfast; //set total amount owed, , format money format. lblamountowed.settext("$" + moneyformat.format(totalamountowed)); } else totalamountowed -= breakfast; lblamountowed.settext("$" + moneyformat.format(totalamountowed)); in case lblamountowed.settext("$" + moneyformat.format(totalamountowed)) getting executed twice if enters in if loop. have add open , closing braces else part also. basically want execute both lines code in else part . beacuse did not add opening , closing braces in else logic , second lin

java - Is it okay to have duplicates in a array? -

i'm working on self project. project let input day , program gives day of given date. here's array: string []days = {"sunday","monday","tuesday","wednesday","thursday","friday","saturday", "sunday", "monday"}; my condition: if(inputdate <= 6){ firstcase = yearscode[0] + inputdate + 3 - 7; system.out.println("january " + inputdate + " " + days[firstcase]);} i put day sunday , monday again because if input date 5<7 gives me arrayoutofboundsexception. i got algorithm here #6 : arrays don't care put in them, can have several copies of object in array if desire. however, solve problem more elegantly, can ensure index calculate never exceeds number of elements in array. this, can use modulo operator % firstcase = yearscode[0] + inputdate + 3 - 7; firstcase = firstcase % 7;

Python for loop print error -

this question has answer here: what “syntaxerror: missing parentheses in call 'print'” mean in python? 3 answers for in range(10): x = 0.1*i print x print x/(1-x*x) i'm trying print results out using loop, says syntax error: missing parentheses in call 'print' . i'm using python 3.4 , i'm new python. the error message crystal clear, isn't it? print function missing parentheses needed function call: print(x) python 2 had print statement syntax print x correct; python 3 has changed this. should learning python python 3 specific resource, example python tutorial .

ios - UItextfield shouldChangeCharactersInRange method backSpace not working -

i implement code backspace not working until press delete button in uitextfield want backspace delete. - (bool)textfield:(uitextfield *)textfield shouldchangecharactersinrange:(nsrange)range replacementstring:(nsstring *)string { nscharacterset *mycharset = [nscharacterset charactersetwithcharactersinstring:_demo_str]; (int = 0; < [string length]; i++) { unichar c = [string characteratindex:i]; if ([mycharset characterismember:c]) { return yes; } } return no; } try code. working me - (bool)textfield:(uitextfield *)textfield shouldchangecharactersinrange:(nsrange)range replacementstring:(nsstring *)string { nscharacterset *mycharset = [nscharacterset charactersetwithcharactersinstring:_demo_str]; (int = 0; < [string length]; i++) { unichar c = [string characteratindex:i]; if ([mycharset characterismember:c]) { return yes; } else { return no; } } return

java - How set priority to intellij idea process? -

i want set priority "below normal" idea64.exe process , descendants. want setting retained permanently , not want set every time run idea. there intellij idea settings doing this? you can creating shortcut below command: c:\windows\system32\cmd.exe /c "start /belownormal notepad.exe" for idea this: c:\windows\system32\cmd.exe /c "start /belownormal c:\"program files (x86)"\jetbrains\"intellij idea 13.1.1"\bin\idea64.exe" other options: /low /belownormal /normal /abovenormal /high /realtime

python - Is there a way to convert a Lucene index into Whoosh or MongoDB? -

lucene popular text indexing tool ( http://lucene.apache.org/ ). installing lucene pythonic usage heck of work ( building pylucene on ubuntu 14.04(trusty tahr) ). whoosh python based indexing library ( https://pythonhosted.org/whoosh/quickstart.html ) supports full text search of lucene. for sake of users don't want hassle of installing pylucene use index i've built. is there way port lucene index whoosh? if so, how? other whoosh, lucene mongodb's gridfs , try replicate full text search in mongodb. but how port lucene index mongodb? possible? humanly, 1 can use luke ( https://code.google.com/p/luke/ ) or clue ( https://github.com/javasoze/clue ) read files is there other way export lucene index pythonically readable format? (without using pylucene)?