Posts

Showing posts from September, 2012

algorithm - Loop through two arrays deleting overlaps in perl -

i have 2 sets of ranges, represented [ start, stop ] values. of ranges overlap, meaning start of 1 range in between [ start, stop ] of other range. i'd make new set of ranges has no such overlap, , doesn't include new values in range. the ranges this: @starts @ends 5 108 5 187 44 187 44 229 44 236 64 236 104 236 580 644 632 770 the output expect this: @starts @ends 5 236 580 770 this because first 7 ranges overlap interval 5 => 236, , last 2 overlap interval 632 => 770. here's code tried: $fix = 0; foreach (@ends) { if ($starts[$fix + 1] < $ends[$fix]) { splice(@ends, $fix, $fix); splice(@starts, $fix + 1, $fix + 1); } else { $fix += 1; } } i can print out values myself, need algorithm merging. this edits arrays in-place, collapsing boundaries when overlap. # since they're sorted @starts, accept 0th in...

Bing maps, how to make geocode request without call back in 7 version? -

i know how make bing geocode request callback function, this: function makegeocoderequest(credentials) { var geocoderequest = "http://dev.virtualearth.net/rest/v1/locations/" + document.getelementbyid('txtquery').value + "?output=json&jsonp=geocodecallback&key=" + credentials; callrestservice(geocoderequest); } function callrestservice(request) { var script = document.createelement("script"); script.setattribute("type", "text/javascript"); script.setattribute("src", request); document.body.appendchild(script); } function geocodecallback(result) { // result } (copied msdn maps ajax control 7.0 isdk) in bing map 6.2 version opportunity make such request using next code: map.find(null, tempdest, null, null, null, null, null, null, null, null,...

aptana - Project connection to CVS lost on reboot -

in aptana studio 1.5.1, if aptana open when reboot occurs, when reopen aptana, project folders changed folder+orange cylinder icon folder icon, meaning projects no longer connected cvs. if re-checkout projects, of files i've edited didn't commit overwritten repository copy. can save copy of edited files, re-checkout project, , copy edited files over, aptana tells me each file out-of-synch repository, , have fix file-by-file. there easy way reattach project on local hard drive existing project in repository , have go state in before reboot messed workspace info? after couple of days' research, can answer own question. easiest way have found restore link cvs when has been lost (i.e. orange "disk" icon no longer appears on project folder) due reboot aptana open or other catastrophe seems following: in local file system, make backup copy of project folder want reconnect exists, uncommitted changes. in aptana perspective, right click on folder , choose...

sql - Merge two queries into one -

i'm not sure if can in 1 query to. i need records this: select a.field_1, a.field_2, b.field_3, b.field_4 tbl_a a, tbl_b b a.field_1 = b.field_3 and exclude these records fall condition: if a.field_1 in (1,2,3,4) , a.field_date < now() update: (sorry confusion) so if field_1 equals 1,2,3 or 4 , has date timestamp today need display record (add results) and if field_1 equals 1,2,3 or 4 , has date timestamp less today (remove results). any ideas both results 1 query notes (if makes difference): field_a can have value a-z, 1-99 (two characters only) something this? select a.field_1, a.field_2, b.field_3, b.field_4 tbl_a a, tbl_b b a.field_1 = b.field_3 , ( case when a.field_1 in (1,2,3,4) case when a.field_date = now() 1 else 0 end else 1 end) = 1

java - Retrieving Youtube Thumbnail URLs using gdata? -

ive been researching information on how data youtube. want information on videos (titles, descritions, , thumbnail urls) playlist (ex: http://gdata.youtube.com/feeds/api/playlists/6a40ab04892e2a1f ). able retrieve titles using code snippet (which borrowed question): string featuredfeed = "http://gdata.youtube.com/feeds/api/playlists/6a40ab04892e2a1f"; url = new url(featuredfeed); urlconnection connection; connection = url.openconnection(); httpurlconnection httpconnection = (httpurlconnection) connection; int responsecode = httpconnection.getresponsecode(); if (responsecode == httpurlconnection.http_ok) { inputstream in = httpconnection.getinputstream(); documentbuilderfactory dbf = documentbuilderfactory.newinstance(); dbf.setnamespaceaware(true); documentbuilder db = dbf.newdocumentbuilder(); document dom = db.parse(in); element docele = dom.getdocumentelement(); nodelist nl = docele.getelementsbytagname("entry"); // n...

Cannot start Informatica services error in Windows 7 and Oracle 11g -

Image
i trying install informatica 8.6 server on windows 7 home edition laptop oracle 11g. getting error message: "cannot start informatica services" exitcode: s. there long description says: "use error below , catalina.out , node.log in server/tomcat/logs directory on the current machine more information." . when checked catalina.out, file empty , node.log didn't exist in server/tomcat/logs. could please let me know how rid of error if have happened come across , resolved or know how resolve error? it looks have downloaded incorrect file in x32 laptop., advice delete it., , make again reconstruction in 32-bits machine: download: from here first: then 2 files: repository accounts: follow link ., posted few weeks ago. server run file1 pc861_win32_x86\install.bat , select language , option install powercenter 8.6.1 you must select license key text file in file2>oracle_all_os_prod.key configuration domain nam...

objective c - more specific about sending json with utf8 to iphone from php server -

we have php server sends json string in utf-8 encoding. im responsible iphone app data. i want sure on side correct : //after downlad data stream : nsstring* content = [[nsstring alloc] initwithdata:self.m_datatoparse encoding:nsutf8stringencoding]; //here data shown correctly in console nslog(@"%@",content); sbjsonparser *_parser = [[sbjsonparser alloc]init]; nsdictionary *jsoncontentdictionary = [_parser objectwithdata:self.m_datatoparse]; //here, when printer values of array in array, see \u454 u\545 \4545 format. ideas why ? for(id key in jsoncontentdictionary) { nslog(@"key:%@, value:%@,key, [ jsoncontentdictionary objectforkey:key]); } im using latest version of json library : https://github.com/stig/json-framework/ there problem iphone side ? (json parser ? ) or in php server ? just clear again : 1.on console, before json, string looks o.k 2.after doing json, array in array values in format of \u545 \u453 \u545 thanks in advance. ...

Windows Live Contacts API Error on Getting E-Mail hashes - JavaScript -

the following codes window live contacts api email address from. works fine in login, log-out, , other authentications. can collect user information of logged in user get data function call, getting email hashes of users, rest of email hashes blank. have 10 email address in contact book. how email addresses of contacts using api? <html> <head> <script src="https://js.live.net/v5.0/wl.js" type="text/javascript"></script> </head> <body> <a href='javascript:void(0);' onclick='signuserin();'>signuserin</a> <br> <a href='javascript:void(0);' onclick='signuserout()'>signuserout</a><br> <a href='javascript:void(0);' onclick='loginstatus()'>check user status</a> <a href='javascript:void(0);' onclick='getdata()'>get data</a> <script type="text/javascript...

tfs2010 - TFS 2010 Missing Process Templates -

Image
i trying set continuous integration using visual studio 2010 , tfs 2010 , when try create new build definition, , go process tab, dont see templates under build process file(windows workflow xaml) drop-down. i have setup build controller points our team project collection , build agent, in our tfs server.i trying setup new build definition local machine visual studio , cant see default templates under build process file(windows workflow xaml) drop-down. is there settings missing ?please let me know. need install visual studio in tfs server ? all need whenever checks in file, should kick off build , see status if build broken or not ! make sure have folder inside team project source control called: buildprocesstemplates inside of there should following files: defaulttemplate.xaml upgradetemplate.xaml there additional ones in example, should have 2 install. if have folder , still cannot see in dropdown let me know , can take there. happened or on tea...

Android, how do can I get a list of all files in a folder? -

i need name (string) of files in res/raw/ i tried: file f = new file("/"); string[] somefiles = f.list(); it looks root directory root of android emulator...and not computers root directory. makes enough sense, doesn't me find out raw folder exists. thanks! update: great replies. appears of these working, getting me half way. perhaps more detailed description aid... i want mp3 files in raw folder can names, add them uri play random mp3 in following way... string uristr = "android.resource://"+ "com.example.phone"+ "/" + "raw/dennis"; uri uri = uri.parse(uristr); singletonmediaplayer = mediaplayer.create(c, uri); when put "dennis.mp3" assets folder, show expected...however, using above code, can't access mp3 anymore...unless there along line of: string uristr = "android.assets://"+ "com.example.phone"+ "/" + "dennis"; uri uri = uri.parse(uristr); thanks ag...

Private messaging in a asp.net mvc app with email reply -

we implementing private messaging in our asp.net mvc app , have come conclusion make work github does... meaning user receive message both through our site , email inbox(this easy achieve mvcmailer nuget).. option have user reply email (through email client) , have email sent our app (if have used guthubs private messaging should know mean)..... common approach implementing feature? see comment regarding how read emails mailbox. i use message bus not limited internal , email notifications, example may wish add sms notifications in future. you may want check out masstransit or nservicebus although may easier create own. public class message { public string title {get;set;} public string body {get;set;} } public interface imessagebus { void send(message message); } public interface imessagehandler { void handle(message message); } public class internalmessagehander : imessagehandler { public void handle(message message) { // send intern...

ruby on rails - My app cannot load some images from the server -

i'm using ruby on rails on local webrick server. i'm generating images of websites urls, writing them local filesystem, , displaying them. name images url replace \ - . images seem not loading because cannot find images on filesystem, , broken image icon. however, see images there when check filesystem. this error in logs: started "/images/image_site/http:--www.urbandictionary.com-define.php?term=slim%20shady.jpg?1309465379" 127.0.0.1 @ thu jun 30 13:23:06 -0700 2011 actioncontroller::routingerror (no route matches "/images/image_site/http:--www.urbandictionary.com-define.php"): this html code: <img alt="http:--www.urbandictionary.com-define.php?term=slim%20shady" class="site_image" src="/images/image_site/http:--www.urbandictionary.com-define.php?term=slim%20shady.jpg?1309465379"> what going on , how can fix this? please let me know if need provide more information. looks you're not encoding...

What do we need both the rails and the rake commands? -

why commands (e.g., generating new controller or model) executed rails command? while others (e.g., migrating databases , running specs) executed rake command? there reason these weren't included under rails? also, if can't remember whether command associated rails or rake, there simple conceptual principle allow me figure out? there's conceptual difference between rails commands , rake commands. rails commands add application. rake commands building/testing/deploying application. those differences should explain both why there 2 different commands figure out 1 use tasks.

In C, how come function may have several declarations but only one definition? -

in c, how come function may have several declarations 1 definition? can elaborate on please! in order allow multiple definitions, must require definition functionally identical - otherwise must have way decide run, @ point might give them different names. proving 2 function definitions identical non-trivial problem. since functions may declared in multiple translation units, need compare them @ link stage in order prove identical. problem when start dealing compiler optimizations may take account other contents of these translation units. example, consider: const char *foo() { return "world"; } simple enough, right? compile 2 files. a.c contains foo . b.c contains well: const char *bar() { return "hello world"; } the compiler may choose make foo() 's "world" point middle of bar() 's "hello world". linker must somehow determine 2 foo() s identical, though point non-identical constant data. a bigger issue com...

asp.net mvc - Asp/Razor CreateUser method -

okay, here's issue in general. using system.web.security.sqlmembershipprovider log in , registration website. , using razor syntax (.cshtml files) view pages. 1 of these pages "forgot password" page. in page, want use code supported by webmatrix.webdata.websecurity . i've added necessary code web.config , that, that's not problem. my problem register code doesn't work. specifically, createuser method. happening that, though visualstudio shows createuser method membershipprovider.createuser , when function called (i've looked @ stack call, i'm sure of this) webmatrix.webdata.simplemembershipprovider.createuser . function not supported system (according exception statement). apparently, createuser methods both membershipprovider , webmatrix have exact same signatures, appears problem. here's method code, worth, but, code created automatically, when create website in visualstudio. and, way, cannot change parameters: _provider.createuser(usern...

ios - SKProductsRequest - how to handle timeouts / connection errors? -

cheers, it appears me skproductsrequest not handle timeouts or connection errors in way. either calls -(void)productsrequest:(skproductsrequest *)request didreceiveresponse:(skproductsresponse *)response on delegate in case of success, or doesn't. i'd present users kind of activity indicator while products being retrieved, or maybe pop alert if appstore can't reached. since (in case of failure) there's no feedback skproductsrequest however, wonder event should tie presentation of feedback - other waiting arbitrary amount of time. so, question is: there known amount of time after safe assume request has failed? or there way check upon status of pending request failed see? i run in project whenever skrequest fails (which includes skproductrequest): - (void)request:(skrequest *)request didfailwitherror:(nserror *)error { alert = [[uialertview alloc] initwithtitle:@"in-app store unavailable" message:@"the in-app store unavailable, p...

tsql - Why does newid() materialize at the very end of a query? -

if run following sample code in sql server, you'll notice newid() materializes after join whereas row_number() materializes before join. understand , if there's way work around it? declare @a table ( num varchar(10) ) insert @a values ('dan') insert @a values ('dan') insert @a values ('fran') insert @a values ('fran') select * @a t inner join (select num, newid() id @a group num) t1 on t1.num = t.num select * @a t inner join (select num, row_number() on (order num) id @a group num) t1 on t1.num = t.num not sure see problem here. materialize subquery t1 first: select num, row_number() on (order num) @a group num; you 2 rows: dan 1 fran 2 now join against on num = num, 4 rows, 2 each distinct value. actual goal here? perhaps should applying row_number() outside? the order of materialization optimizer...

android - Draw text on canvas and make it visible on screen -

this code supposed convert text image public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); paint paint = new paint(); paint.setstyle(paint.style.fill); paint.setcolor(color.red); paint.settextsize(16); paint.setantialias(true); paint.settypeface(typeface.monospace); bitmap bm = bitmap.createbitmap(16, 16, bitmap.config.alpha_8); float x = bm.getwidth(); float y = bm.getheight(); canvas c = new canvas(bm); c.drawtext("test", x, y, paint); } is code ok? if yes, how can make new bitmap visible on screen? tried code produced error setcontentview(c); //<- error! i confused element canvas there not such element in xml can use in code. setcontentview(view) takes view , canvas not view . i not sure want create canvas on own. there ways canvas passed android framework though. 1 way can creating custom view . this, need cr...

php - custom logarithmic scale for line-graph -

i kinda stuck problem in jpgraph: need create diagram (line) shows users progress in online-game 6000 other players. y-axis shows users position in ranking , goes 6000 1 (last position first position). x-axis timeline. so first, x-axis-scale needs inverted - no problem got 1 documentation. but, have scale "kind of" logarithmic - means want values on x-axis this: 6000, 5000, 4000, 3000, 2000, 1500, 1000, 900, 800, 700, 600, 500, 400, 300, 200, 100, 50, 40, 30, 20, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 i managed scale this, smaller values get, smaller distances between labels. - want have equal distances between every label. - in diagram step 6000-5000 should take space step 50 40 or step 2 1. hope explain more or less clear. if not add drawing (i suck @ drawing) , sure mean. if values represented going positive, can make scale negative displays values backwards, jpgraph built display scale on incremental way in case decrease value , make negative values positive. ...

Ordering Choices in ModelForm ManytoManyField DJANGO -

i have in models.py class business(models.model): industry = models.models.manytomanyfield(industry) in forms.py class businessform(forms.modelform): class meta: model = business when render form, industry names appear in multiple select box. do make industry names in alphabetical order? there several ways: you can override queryset ordering on per-form basis, set ordering meta class option, or override model manager queryset ordering method. override global model manager queryset class industrymanager(models.manager): def get_query_set(self): return ( super(industrymanager, self) .get_query_set() .order_by('name') ) class industry(models.model): name = models.charfield(max_length=128) objects = industrymanager() specify global meta option ordering class industry(models.model): name = models.charfield(max_length=128) class meta: ordering = ['name...

iphone - Issues in setting UIButton title in its click event -

i'm trying change title of button when user press on following code: - (ibaction) hidekb: (uibutton *) sender { sender.titlelabel.text = @"↓"; } but when click app crashes , can't understand why. removing sender stuff, button works no problems. the correct method signature action is - (ibaction)action:(id)sender your app crashing because object being sent message doesn't understand. try replacing code along lines of: - (ibaction)hidekb:(id)sender { uibutton *button = (uibutton *)sender; [button settitle:@"↓" forstate:uicontrolstatenormal]; } as may notice i've changed line sets button title. because should never manipulate uibutton 's titlelabel property directly, rather should using appropriate setter method shown above. edit: clarify, controls allow use dot notation edit text property of titlelabel . however, uibutton instances support different titles (as images , background images) depending on ...

java - Steganography program giving weird results -

i developing steganography program computer programming class. appears gives random ascii symbols. output supposed binary. encode message method given teacher. have program decode part. import java.awt.*; class hidemessage { public void encodemessage(picture stegoobject, int[] binaryarray) { pixel pixeltarget = new pixel(stegoobject, 0, 0); pixel[] pixelarray = stegoobject.getpixels(); color pixelcolor = null; int redvalue = 0; (int x = 0; x < binaryarray.length; x++) { redvalue = binaryarray[x]; pixeltarget = pixelarray[x]; pixeltarget.setred(redvalue); } pixeltarget = pixelarray[binaryarray.length]; pixeltarget.setred(255); system.out.println("finishedpic"); stegoobject.write("secretmessage.bmp"); stegoobject.explore(); } public void decodemessage(picture decodepic) { int redvalue = 0; pixel targetpi...

Dynamic array of an object -

maybe solution simple. must be, maybe overlooking something i have: public class object { public int pos_x; public int pos_y; } object testobject[] = new object[10] and somewhere in function testobject[1].pos_x = 1; it force closes app.. how? , why? can cause of this. furthermore. ideally need this testobject[].add_new_object(); testobject[].remove_item(3); can done? thank helping you have allocated array can hold 10 objects. you need allocate objects.

ruby - Rails Active:Record helpers broken with large database -

i imported 850,000 row csv file sqlite database , of sudden find_by_field methods don't work. on rails 3.1 btw. for instance, model name zip , 1 of fields zipcode , string. if zip.find_by_zipcode(zip.first.zipcode) returns nil . methods work ones aren't on string fields find(:id) , find_by_created_at , find_by_latitude , integer. tried indexing fields didn't help. here's snippet: ruby-1.9.2-p180 :029 > zip.find_by_zipcode(zip.first.zipcode) zip load (0.2ms) select "zips".* "zips" limit 1 zip load (0.2ms) select "zips".* "zips" "zips"."zipcode" = 'a0a 1a0' limit 1 => nil anyone have suggestion? also if zip.where('zipcode ?', zip.first.zipcode) works.

javascript - Parsing city/state from Google Maps request -

var geocoder = new google.maps.geocoder(); geocoder.geocode({'latlng': foundloc}, function(results, status) { if (status == google.maps.geocoderstatus.ok) { if (results[1]) { var loc = getcitystate(results); } } }); function getcitystate(results) { var citystatearray = results[1].formatted_address.split(",",2); var city = citystatearray[0]; var state = citystatearray[1].substring(1, 3); return (city + ', ' + state) } this use now, , works 90% of time. other times, formatted_address contains town , city along state, other times town , city, other times can dream of. i haven't yet found consistent way of getting city/state google maps api result. of guys have one? thanks. example of 1 response google uses example on page: { "status": "ok", ...

python - Check to ensure a string does not contain multiple values -

**note- not testing @ end of string-- need locate particular substrings anywhere in string what fastest way check make sure string not contain multiple values. current method inefficient , unpythonic: if string.find('png') ==-1 , sring.find('jpg') ==-1 , string.find('gif') == -1 , string.find('youtube') == -1: if you're testing end of string, remember str.endswith can accept tuple. >>> "test.png".endswith(('jpg', 'png', 'gif')) true otherwise: >>> import re >>> re.compile('jpg|png|gif').search('testpng.txt') <_sre.sre_match object @ 0xb74a46e8> >>> re.compile('jpg|png|gif').search('testpg.txt')

data between two php files -

i have php script: <?php include("simple_html_dom.php"); $url = "http://en.wikipedia.org/wiki/thailand"; echo file_get_html($url); ?> how can send $url variable tosql.php script ? i apologize not including more im doing. im sending url jquery script sends php script titled tosql.php (which stores processed data mysql jquery script) this should want. <?php $url = "http://en.wikipedia.org/wiki/thailand"; include("simple_html_dom.php"); echo file_get_html($url); ?> by declaring $url before include, it's same declaring $url @ top of simple_html_dom.php .

php - split switch cases in different files -

i have php file in using long switch case. want split cases in different files (keep logically connected cases in 1 file). edit: sorry code causing problem. switch case working expected. file -> a.php echo "<br>res = ".test(1); function test($value) { switch($value) { case (1 || 2): include("b.php"); **return $temp;** break; default: echo "error"; return 3; break; } } file -> b.php switch($value) { case 1: echo "value 1"; **$temp = 1;** return 1; break; case 2: echo "value 2"; **$temp = 2;** return 2; break; } how proper result? if switch case of b.php in a.php file works fine.any idea/suggestion on how this? if add $temp (bold lines) works... thanks in advance. regards ...

ruby - How to list active records using Active scaffold with association in rails 2.3.8? -

i want list records db, active(true) in index page. i'm using active scaffold plugin rails 2.3.8. suggestion how add active condition in controller? here admin controller class admin::accountscontroller < applicationcontroller active_scaffold :accounts |config| config.list.sorting = {:id => :asc} config.list.columns = [:description,:year] config.actions = [:create, :update,:list,:search,:delete] end end models class account < activerecord::base has_many :customer_accounts end class customeraccount < activerecord::base belongs_to :account end table structure create_table :customer_accounts |t| t.integer :account_id t.active :boolean, :default=>true t.timestamps end you can add following method controller apply conditions on active scaffold collection: def conditions_for_collection unless has_role?(:admin) # if want limit records non admin users [...

What's the best way to remove first div inside a parent div using jQuery? -

i have following markup: <div id="parent"> <div id="divtoremove"> </div> </div> and have following jquery remove first div works fine: $('#parent').find('div').remove(); is best way remove first component? or more efficient use selectors? example great! please note , know can use: $('#divtoremove').remove(); however i'd able use selectors in instance (reasons outside of scope of question). thanks, norm. this should fastest , safest: $('#parent').find('div').first().remove();

iphone - How can a method tell which view controller called it -

i want current view controller in own method. mean have 2 view controllers calling same method. in want diffentiate view controller class calling method. please me out lets mycommonmethod: common function called both view controller , check viewcontroller whether it's member of class or not using ismemberofclass: method of nsobject . -(void) mycommonmethod:(uiviewcontroller*) aviewcontroller { if([aviewcontroller ismemberofclass:nsclassfromstring(@"myfirstcontroller")]) { } else if([aviewcontroller ismemberofclass:nsclassfromstring(@"mysecondcontroller")]) { } }

join - MYSQL : Problem in writing where clause according to scenario -

i have db (user_interests) set 3 fields: i_id (unique), interest_id, uid. then second db (interests) set interests: interest_id (unique), interest_name i'd sql query return list of interests 2 users have in common: user (owner of profile) , user b (you/viewer of profile). guess need query user_interests, join interests name of interest. select user_interests.i_id, user_interests.uid, interests.interest_name databases.user_interests left join databases.interests on interest.interest_id = user_interest.interest_id _______________ i'm confused clause (if correct way @ all). goal interest_id user_interests.interests user_interests.uid both , b (in separate rows). i saw link, couldn't figure out missing: group x y = , b , c i don't think need clause in case remove , set of data looking for: select user_interests.i_id, user_interests.uid, interests.interest_name databases.user_interests left join databases.interests on interest.interest_id = us...

replace - R: How to do fastest replacement in R? -

i have input dataframe (the real 1 large, want faster): df1 <- data.frame(a=c(1:5), b=c(5:9), c=c(9:13)) b c 1 1 5 9 2 2 6 10 3 3 7 11 4 4 8 12 5 5 9 13 i have dataframe replacement code (the entries here maybe more df1): df2 <- data.frame(x=c(1:15), y=c(101:115)) x y 1 1 101 2 2 102 3 3 103 4 4 104 5 5 105 6 6 106 7 7 107 8 8 108 9 9 109 10 10 110 11 11 111 12 12 112 13 13 113 14 14 114 15 15 115 by matching df2$x value in df1$a , df1$b, want new_df1 replace df1$a , df1$b corresponding values in df2$y, i.e. resulting new_df1 b c 1 101 105 9 2 102 106 10 3 103 107 11 4 104 108 12 5 105 109 13 could mind give me guidance how faster in r, dataframe large? many thanks. it's supereasy! need proper offsets in array. so instance, y column of df2 corresponding values in column of df1 you'll write df2$y[df1$a] hence, code be: df_new <- data.frame("a" = df2$y[df1$a], "b" = df2$y[df...

PHP cli getting input from user and then dumping into variable possible? -

is possible input user using php cli , dump input variable , script goes ahead. just c++ cin function ? is possible if yes how ? maybe not php maybe linux commands ? thanks have @ php manual page http://php.net/manual/en/features.commandline.php in particular <?php echo "are sure want this? type 'yes' continue: "; $handle = fopen ("php://stdin","r"); $line = fgets($handle); if(trim($line) != 'yes'){ echo "aborting!\n"; exit; } echo "\n"; echo "thank you, continuing...\n"; ?>

Struts 2 jquery autocompleter with JSON -

i'm using atocompleter in form json. this part of struts.xml <package name="json" namespace="/" extends="json-default"> <result-types> <result-type name="json" class="com.googlecode.jsonplugin.jsonresult" /> </result-types> <action name="test" class="testclass" method="populate"> <result type="json" name="success"> <param name="root">itemlist</param> <param name="contenttype">text/html</param> </result> </action> </package> this jsp <s:form id="frm_demo" name="frm_demo" theme="simple" action="test2"> <s:url id="remoteurl" action="test" /> <sj:autocompleter id="lst"...

javascript - preview of text using jquery -

i have following html <img src="a.jpg" /><p> random text , test example. random text , test example. random text , test example<p> <br><p>this random text , test example random text , test example</p> <img src="a.jpg" /> <br><p>this random text , test example random text , test example</p> my question if have give preview of text using jquery suppose have in variable named html how display few parts of text ignoring images <div id="preview"></div> $("#preview").val("//display text in variable named html") you filter images html: var somehtml = '....'; $('#preview').html($(somehtml).filter(':not("img")'));

haskell - UI input with reactive-banana-wx -

how content of ui elements when using reactive-banana? event0 returns event of type event () , has unit type instead of type of control. event1 takes event of type event w (a -> io ()) , command of type event w (io ()) . mapaccume , mapaccumb takes pure functions parameters, get text foo can't used them. basically, want work functions instead of data. if you're thinking "how create behavior has current text in box", don't. instead write functions take current text parameter, , pass in when necessary. suppose want print contents of textbox when button pressed. this: ebutton :: networkdescription (event ()) ebutton = event0 button command network = pressbutton <- ebutton reactimate $ (\() -> text foo >>= print) <$> pressbutton if need input behavior, can use function type behavior (string -> a) (or whatever type need), , pass string in @ point of reactimate call.

MySQL Connect via proxy in Java -

i developing client-server software, client connects database server follows. ... try { class.forname("com.mysql.jdbc.driver"); connection conexion = drivermanager.getconnection("jdbc:mysql://localhost/agenda", "root", "la_password"); }catch.... ... both applications on same local network. problem have when local network uses proxy, in case mysql connection fails. how can make connection java programming language, mysql database when proxy on local network?. thanks help. greetings! try using socksproxyhost , socksproxyport system properties. here @ chapter "2.4) socks" , here . (the http.proxyhost not work jdbc.) here description of use proxy jdbc (oracle example): connect outside internet oracle database inside intranet through jdbc . may want use properties: socksproxyset, socksproxyport, socksproxyhost, java.net.socks.username, java.net.socks.password . here description how set version, username , passwo...

unicode - C++ bit manipulation -

i trying extract character value utf-8 format. suppose have 2 characters, , extract 5 bits first character => 10111 , 6 bits character => 010000 so ch1 = 10111; ch2 = 010000; how combine them form 10111010000 , output hex 0x5d0? need shift or there easier way this, because checking documentation write appear able read characters sequentially, there similar function this? also, appears need char buffer since 10111010000 11 bits long. know how go this? you need use shifting, plus | or |= operator. unsigned int ch3 = (ch1 << 6) | ch2; // ch3 = 0000010111010000 i'm assuming here unsigned int 16 bits. mileage may vary.

.net - Access to parent's private properties through nested types in C# -

nested types in c# have ability access parent's private properties. there specific reason having language feature ? in opinion breaks encapsulation. if make nested type public, able expose private properties of parent class through it. you would able - can nest class if you've got in same source file outer class in first place. effectively nested class "owned" outer class, , trusted same extent other member of outer class. method in outer class expose private property - trust not to, because own code. likewise (the author of outer class) own code of nested class. if don't want break encapsulation in nested class, avoid writing code break encapsulation :)

iphone - Image bounds not rect but custom -

i want add image onto image. know imageview has rectangular frame. there way can add image without rect farme? say, want add pin onto imageview. rectangular shaped imageview or can add image frame shape of pin. it rectangular can not add imgeview other shape. what need transparent png pin , added original image view sub view.

java - How to solve "Symbol lookup error" by using JPL on Ubuntu11.04? -

Image
i'm coding program in java , connect prolog. thus, decided use jpl. use jpl on windows vista. later, have change os platform ubuntu 11.04. unfortunately, there error: symbol lookup error: /usr/lib/swi-prolog/lib/i386/libjpl.so: undefined symbol: pl_is_initialised environment: ubuntu 11.04 java version 1.6.0_24 eclipse galileo version: 3.5.2 swi-prolog version 5.10.1 i386 jpl (apt-get install swi-prolog-java) family.java + family.pl i explain steps of working , problems follows. step1: install swi-prolog + jpl using synaptic package manager step2: run family.java , found error step3: configure library path @ vmarguments step4: run again, there error /usr/lib/jvm/java-6-sun-1.6.0.24/bin/java: symbol lookup error: /usr/lib/swi-prolog/lib/i386/libjpl.so: undefined symbol: pl_is_initialised step5: config environment error still same. the method used solve problem in step 3 , 5 searched internet. can not find other solutions try. have idea? in adv...

c# - protobuf-net exception: No serializer defined for type: System.Xml.XmlDocument -

how serialize object contains property of xmldocument type?: [protocontract] public class foo { [protomember(1)] public xmldocument bar { get; set; } } as string; example: [protocontract] public class foo { public xmldocument bar { get; set; } [protomember(1)] private string barserialized { { return bar == null ? null : bar.outerxml; } set { if (value == null) { bar = null; } else { var tmp = new xmldocument(); tmp.loadxml(value); bar = tmp; } } } } i guess could handled automatically, but... packing xml inside protobuf seems smell bit of redundancy / inner-platform-effect. such, i'm not sure want encourage adding direct library support ;p if have lots of xml-documents in model, - well, firstly protobuf isn't going gain much, secondly : possible hook "surrogate" xmldocument in v2; add 2 bytes overhead per doc, i...

Youtube embedded video - remove final info screen -

is there way can remove final screen of embedded youtube video, has "replay" button, listing other videos, url , embed options etc? i want video end, , not see else? thanks edit: solved it!! rel=0 in video url! i have following params in video url, made title go, , end info window go: showsearch=0&showinfo=0&playlist=&modestbranding=1&egm=0&rel=0 let's have video: http://www.youtube.com/embed/geydf4oopdo you need add option rel ( ?rel=0 ) end, parameter. like this: http://www.youtube.com/embed/geydf4oopdo?rel=0 here can find parameters: youtube parameters , , tricks: tricks

running around 220 insert into mysql and php -

i have 20 files have mysql queries run, example of file1.php,file2.php,file3.php <?php $s = array(); foreach($j $y) { //codes $s[] = "($link, $img)"; } mysql_query("insert xyz values ".implode(',',$s)); ?> file1.php,file2.php,file3.php more same , requires insert queries run. //insert varies on each file , dynamic based on input i have run.php which <?php require 'file1.php'; require 'file2.php'; require 'file3.php'; ?> so execution of file1, file2 , file3 depends on run.php is safe way it? or should move mysql insert @ run.php (run queries together) instead of leaving in individual files (file1,file2,file3). what best way send data file1.php run.php? method, echo? there no problem in doing this. maters initiate transaction before starting queries , commit in end or rollback in case of exception.

php - Boolean OR in condition - what's wrong? -

here's condition - if ($file !== "." || $file !== "..") not working. if (($file !== ".") || ($file !== "..")) not working either. if ($file !== ".") works fine. ' drives me edgy. i've read php.net has offer on logical operators ( http://php.net/manual/en/language.operators.logical.php ), bunch of crappy tutorials googled up, , triple-checked operator precedence. points, either of ways should work. what reason? $file should not . , should not .. if ($file !== "." && $file !== "..")

iphone - How to set high resolution images for iphone4 using css -

in iphone4 images not showing in high resolution shows low resolution images. how change high resolution images iphone4 using css? to clarify, developing in phonegap using html , jquery high-res images end pixelated in application. .png images have designation of @2x.png , raw files match png files. we have utilized practices in http://aralbalkan.com/3331 , http://davidehlers.com/2011/03/iphone ... the images appear smaller raw images are, , pixelated. have attached overlay of issue venky referring to. buttonsml@2x.png on right, placed on top of screenshot of app iphone4. not sure css in normal way can append "@2x" normal image name , goes retina display. may don't need mention in css , put @2x in image , add in project. example icon.png icon@2x.png. hope help.

login - Android: Can I use google ClientLogin for user registration? -

we developing app has option of user registration. want make process easy possible user (to encourage registration), want user login google account , our server store google username (not password). not accessing google services app, want give easy option register , login. other apps doing? google have problem that? i recommend use accountmanager android don't have problems storing password on severs if use auth token. , biggest benefit is, user don't have enter email or password http://developer.android.com/reference/android/accounts/accountmanager.html look @ steps in documentation get available accounts view them in list request auth token

manytomanyfield - django-reversion revert ManyToMany fields outside admin -

i using django-reversion in project. , works except 1 thing: can't previous versions of manytomany fields. in django admin works, not in code. previous version use following code: vprod = version.objects.get_for_date(product, ondate).get_object_version().object and works except m2m field 'product' object of product class, class product(models.model): name = models.charfield(max_length=255) elements = models.manytomanyfield(sku) class sku(models.model): name = models.charfield(max_length=255, verbose_name="sku name") i can vprod.name , returns need, when try vprod.elements.all() returns list current (last) version, if number of elements changed. if understand correctly, think should revision version; version contains data of object, revision contains versions multiple objects. have at: some_version.revision.version_set.all() concretely, think should use (untested): [ v v in version.objects.get_for_date(p...

asp.net mvc - asp .net mvc routing url with custom literal -

is possible make url custom literal separator can have default parameters ? context.maproute( "forums_links", "forum/{forumid}-{name}", new { area = "forums", action = "index", controller = "forum" }, new[] { "jami.web.areas.forums.controllers" } ); i have see im using dash separate id name can have url like: /forum/1-forum-name instead of: /forum/1/forum-name i see problem i'm using multiple dashes. , routing engine don't know 1 separate. overalll doesn't change question because want use multiple dashes anyway. very interesting question. the way come daniel's, 1 feature. context.maproute( "forums_links", "forum/{forumidandname}", new { area = "forums", action = "index", controller = "forum" }, new { item = @"^\d+-(([a-za-z0-9]+)-)*([a-za-z0-9]+)$" } //...

c++ - Qt window resize problem -

Image
i having problem redrawing qwidget window after size has been adjusted. have tried update() , repaint() , adjustsize() , seem suffer same thing: part of window redrawn, resulting in window frame on bottom , right sides not show. window not resized entirely. just in case makes difference, window in qmdiarea . thanks. // ... subwidget resizing , moving. calibrationwindowuis[activewindow].layoutwidget2->move(qpoint(oldxleft, 30 + height + 21)); calibrationwindowuis[activewindow].layoutwidget1->move(qpoint(oldxright, 30 + height + 21)); // set window size. calibrationwindows[activewindow]->setminimumsize(calibrationwindowuis[activewindow].tabwidget->geometry().width() + 40, calibrationwindowuis[activewindow].tabwidget->geometry().height() + 40); calibrationwindows[activewindow]->update(); note: i'm new qt; perhaps i'm doing wrong layouts? edit: may have not given enough information. alright, quite h...

jsf - Using PrimeFaces Global Filter? -

as mentioned in primefaces showcase trying create global filter datatable . there unable understand carstable means, in code fragment <h:form> <p:datatable var="car" value="#{tablebean.carssmall}" emptymessage="no cars found given criteria"> <f:facet name="header"> <p:outputpanel> <h:outputtext value="search fields:" /> <p:inputtext id="globalfilter" onkeyup="carstable.filter()" style="width:150px"/> </p:outputpanel> </f:facet> when use my datatableid inplace of carstable iam getting javascript error undefined id. this looks typo in showcase code display. missing attribute on <p:datatable> component called widgetvar . attribute declares unique javascript identifier client side component. code should show this: ...

c# - Drag and drop custom object -

i have 2 controls 1 one form: list , tree (specific type names irrelevant). in list control execute dodragdrop method. first argument pass object data bound row. object implements specific interface , marked serializable attribute. what want retreive object in dragenter/dragdrop event handler of tree control. i'm using following code: void treecontroldragenter(object sender, drageventargs e) { var formats = e.data.getformats(); var data = e.data.getdata(typeof (ifoo)); } unfortunately, in result data null , formats one-element array holds name of specific type (implementing ifoo). assume have pass exact type name getdata retreve object, it's not possible private class. is there way object interface? you have provide same type class serialized in first place. cannot use interface or base class of serialized class because more 1 of formats might match , not know 1 deserialize. if have several classes implement ifoo , there instance of each inside da...

Django MPTT - absolute url for category -

i have following tree structure: cat 1 --sub cat 1 --sub cat 2 cat 2 --sub cat 1 --sub cat 2 ----subsub cat 1 using django-mptt i'm able display information using 1 query great, when trying create url like: http://www.somesite.com/categories/cat1/subcat1/subsubcat1/ it doing sql lookup each of categories in tree parent nodes slug (which understandable.) here code: @models.permalink def get_absolute_url(self): if not getattr(self, '_slug', none): url = self.slug ancestor in self.get_ancestors(ascending=true): url = url + ancestor.slug + u'/' self._slug = url return ('catalogue_category', [str(self._slug)]) is there functionality of mptt allow me create url slug without going crazy on sql? i think answer question no. daniel points out in comment should able ancestors 1 query, agree eg. have list of categories need hit database each item once. if that's prob...

connection refused when trying to connect to my REST server from android emulator -

consider following android code , please solve problem: there rest server running on laptop..i can access server browser , proper resuts...but want use android emulator running on laptop using following code.. // string url = "http://localhost:8080/server/rest/user/1"; string url = "http://www.google.com"; httpclient httpclient = new defaulthttpclient(); httpget request = new httpget(url); httpresponse result = httpclient.execute(request); in emulator when pass url http://www.google.com , got proper response in result when use localhost url(the commented 1 above) got connection refused.... warn/system.err(901): org.apache.http.conn.httphostconnectexception: connection http://localhost:8080 refused warn/system.err(901): caused by: java.net.connectexception: /127.0.0.1:8080 - connection refused if run same url on browser works. can tell me why localhost url not working in emulator..? ankur, had same problem replacing localhost 10.0.2.2 worked...

javascript - Strict validation of text field -

on form there 2 fields days , month. i want simple validation that. once user enter month , i.e., 12 alllow go next field. if user enters invalid month should focus again on month field , entered text should selected. i trying use .focus() , .select() jquery function not working this fiction validation test , can number or label. here jsfiddle link . <input type="text" id="days" /> <input type="text" id="month" /> jquery("#days").blur(function(){ if(jquery(this).val() == "12"){ alert("valid"); } else { alert("invalid"); jquery(this).focus().select(); } }); $(function({ $('#days').attr("disabled", true); }); $("#months").blur(function(){ if($(this).val()<1 || $(this).val()>12){ $(this).val() = "error, invalid month"; $(this).css('color', 'red'...

c++ - Is an empty function called at all in optimised code? -

if test macro not defined, know whether there performance difference in these 2 pieces of code: void func1(int a) { ... } #ifdef test func1(123); #endif and: void func2(int a) { #ifdef test ... #endif } func2(123); with test not defined, func2 become , empty function complier should not call @ all, isn't it? thank you. it pretty comes down whether particular call func2 inlined or not. if is, optimizing compiler ought able make inlined call empty function same not calling @ all. if isn't inlined, it's called , returns immediately. as long function definition available in tu containing call func2 , there's no obvious reason won't inlined. this relies on fact 123 literal, evaluating arguments of call has no side-effects. args have evaluated if function call has no effect, so: int = 0; /* 'i' incremented, if call optimized out */ func2(++i); /* 'i' not incremented when 'test' undefined */ #ifdef test fun...

c# - Join between in memory collection and EntityFramework -

is there mechanism doing join between in-memory collection , entity framework while preserving order. what trying var itemstoadd = myinmemorylist.join(efrepo.all(), listitem => listitem.record_number, efrepoitem => efrepoitem.record_number, (left, right) => right); which gives me rather curiously titled "this method supports linq entities infrastructure , not intended used directly code." error. now of course can iteratively like foreach (var item in myinmemorylist) { var ho = efrepo.where(h => h.record_number == item.record_number).firstordefault(); tmp.add(ho); } but n+1 query. nasty myinmemorylist might quite large! resharper can refactor me tmp = (from typeofiteminthelist item in myinmemorylist select efrepo.where(h => h.record_number == item.record_number) .firstordefault()); which suspect still doing n+1 queries. ideas better approach getting ef entit...

stl - A question about for_each in vector of c++ -

i have question for_each in vector, code following: #include <iostream> #include <algorithm> #include <vector> using namespace std; struct myclass { void operator() (int i) {cout << " " << i;} } myobject; int main () { vector<int> myvector(3,4); cout << "\nmyvector contains:"; for_each (myvector.begin(), myvector.end(), myobject); cout << endl; return 0; } should third argument of for_each() function name? if pass name of struct, how works? this functor . std::for_each function template expands this: for (iter = myvector.begin(); iter != myvector.end(); ++iter) { myobject(*iter); } so myobject can either function pointer, or can object overload operator() .