Posts

Showing posts from September, 2014

linux - Taking average of decimal number using bash -

how can take average of decimal values written in file: testfile as time write: 0.000118000 sec time write: 0.000119000 sec time write: 0.000122000 sec wrong soln: following prints 0 i.e. 0 awk '{sum+=$7}end{print sum/nr}' testfile edit since having trouble, , seem return 0 try using this grep -op "\d+\.\d+" testfile | awk -vx=0 '{x += $1} end {print x/nr}' this work if file double spaced or not. prints match of file has decimal number. , sends awk. the -p flag perl regular expression. same -e, \d+ matches 1 or more digits, \. matches period. . has special meaning in regular expressions , need escaped , \d+ matches 1 or more digits put together, '\d+\.\d+' , have decimal. lastly, if continue scientific notation may consider printf achieve floating point noation awk -vx=0 '{x += $4} end { printf ("%8.9f", x/nr) } testfile' you can specifiy smaller "%4.3f" print 4 numbers after decimial,...

c - opencvResize() problem -

i trying use opencv2, built on ubuntu 10.04 simple program going reads exisitng image, creates image , resize original image 2(both width , height). below code. upon execution, don't see resized image window. # include "stdio.h" #include "opencv2/highgui/highgui_c.h" #include <opencv2/imgproc/types_c.h> int main( int argc, char** argv ) { iplimage* img = 0; iplimage* dst_img = 0; if( argc < 2 ) { printf( "usage: accepts 1 image argument\n" ); exit( exit_success ); } img = cvloadimage( argv[1],1); if( !img ) { printf( "error loading image file %s\n", argv[1]); exit( exit_success ); } dst_img = cvcreateimage(cvsize(img->width*2,img->height*2),img->depth,img->nchannels); if( !dst_img ) { printf( "error loading output image file \n"); exit( exit_success ); } cvresize(img,dst_img,cv_inter_linear); cvnamedwindow( "original image", cv_window_autos...

sql - Issue with Interop.SQLXMLBULKLOADLib.dll -

i converted old dts package ssis package , trying run windows 2008 server. ssis package runs win32 exe file using interop.sqlxmlbulkloadlib.dll , trying load xml data database. following error when exe gets executed. com exception: retrieving com class factory component clsid {8270cb2f-b0e6-4c37-8a40-d70778f47894} failed due following error: 80040154. i'm trying run .exe file in windows 2000 compatability mode. please let me know if have suggestions. thanks that clsid belongs sqlxml 3.0. can download 3.0 sp3 here . fyi 0x80040154 = regdb_e_classnotreg. as far can tell sqlxml 4 not implement same clsid, think you'll have install 3 if have 4 installed already.

delphi - C# error: cannot use fixed size buffers contained in unfixed expressions -

i'm struggling c# program read binary records database. records created borland delphi. here's example: // delphi record definition tbowler_rec = record public gender : tgender; bowler_num : byte; name : tstring32; initials : string[3]; ... // corresponding c# definition (unmanaged code) [structlayout(layoutkind.sequential, pack=4)] public unsafe struct tbowler_rec { public tgender gender; public byte bowler_num; public fixed byte name[32]; public fixed byte initials[3]; ... i'm able read binary struct out of sql server database , see data in visual studio debugger. yay! i'm able access fields "gender" , "bowler_num" no problem. yay! q: how turn "name" c# string? an example name "ashton". looks in memory: \0x6ashton\0x0\0x0... here's how i'm trying access it: [structlayout(layoutkind.seque...

html - Is there such a thing as meta tagging graphics on a web page? -

i've been doing web work client , they've asked me meta tag images on web page specific data, i've not heard of meta tagging images, @ least not using standard html before , quick search reveals there isn't standard meta tag this. did notice facebook opengraph protocol i'm pretty sure that's not wants. has client been ill informed or missing something? if images jpeg can store meta data using exif . that said, should find out client wants achieve meta data , solve that problem.

python - problem: how to reference to objects/variables created in decorator from injected method? -

i encountered problem availability of objects created within decorator, , needed in test_case method. code presenting below: def execute_results_navigation(test_case): def wrapper(self,*args,**kwargs): result=result() pagination=pagination() results_page_index=1 while results_page_index<=pagination.get_pages_number(): results_object_index in range(results.get_objects_number_per_single_page()): test_case(self,*args,**kwargs) pagination.set_active_page_number(results_page_index) results_page_index+=1 return wrapper in place of test_case method "injected" following code (everything takes place using predefined decorator): @execute_results_navigation def test_check_availability_of_search_results(self): """ test case 2.22 """ offer=offer() result.select_hotel(results_caller["button"],results_object_index) ...

hyperlink - How to link to all publisher apps on Android Amazon Appstore -

i cannot figure amazon appstore equivalent for: market://search?q=pub:smallte.ch this lists apps given developer. note know format specific apps: market://details?id=com.adobe.air becomes either of these : amzn://apps/android?p=com.adobe.air http://www.amazon.com/gp/mas/dl/android?p=com.adobe.air what's equivalent developer's apps list? if want link list of applications on appstore use url http://www.amazon.com/gp/mas/dl/android?p=packagename&showall=1 example http://www.amazon.com/gp/mas/dl/android?p=com.idmobile.horoscope&showall=1 this should work (never tested) amzn://apps/android?p=com.idmobile.horoscope&showall=1 more infos developer.amazon.com/help/faq.html

android - Showing custom dialog instead of "ANR dialog" -

i want show customize dialog instead of anr dialog. know avoiding anr nowadays working on big code base , instead of re vamping code want know there way override anr dialog? thanks no, cannot "override anr dialog".

ruby - Multiple Level Nested Layout in Rails 3 -

i have application global application layout file application.html.haml . have multiple "controller stacks": our main site, our admin portal, , our business site. each of these, controllers within module , inherit same basecontroller . each stack has it's own layout file. within stack, controllers have layout files well. i views (unless otherwise specified) render inside multiple levels of nested layouts : application, "stack", "controller". for example, site::blogcontroller#show action, i'd rails render: /site/blog/show.html.haml inside /layouts/site/blog.html.haml inside /layouts/site.html.haml inside /layouts/application.html.haml i having difficulty understanding how insert /layouts/site.html.haml stack. appears though automatically, rails render action inside controller layout inside application layout, however, can't see how "insert" layouts render stack. any appreciated, however, have read rails guides no ava...

io - Using inp() on 16Bit Dos 5with Turbo C++ 3.0 -

first off i'd know outdated question. that,s why can't find information through google. (or i'm worse @ searching i'd admit! haha.) results pretty tell me inp() & outp() useless on modern systems because kernel handles input , output rather program. i'm running 16 bit dos 486 machine , i've been able use outp() parallel port perfectly. 16 bit dos, , i'm not interested in learning "new , improved" way of doing on nt era systems , higher (at least not right now). with cleared -- my question in regards inp() . have old hardcopy manual says pass single variable, port address, inp() . in case assume since use 0x378 port outp() , i'd use inp() well. since haven't programmed accept external input before, wasn't sure type of value i'd simple on/off switch wrote quick code grab new values- #include <iostream.h> #include <stdio.h> #include <conio.h> #include <time.h> #include <dos.h> i...

Assign JavaScript value to Django template tag argument -

how assign argument value django template tag, using javascript? {% url path.to.some_view arg=v %} this doesn't work: <script> var v = 5; </script> {% url path.to.some_view arg=v %} this should work: <script> var v = 5; var url = '{% url path.to.some_view 999 %}'.replace (999, v); </script>

asp.net - white label design strategy -

i have data driven web site written in asp.net. i've had 3rd parties contact me , ask if provide branded access own users. think direction want take site, i'm unsure of best way done. i'm looking input on various ways implement this, , pros , cons of each method. i'm looking put little technical burden on 3rd party possible. can provide them html snippet, , takes integration. here few ways i've come make happen. please comment on wisdom of each, , provide alternatives if think viable: create subdomain 3rd party. read server variables , set theme , data accordingly. provide link 3rd party web master. create redirecting page i.e. http://mywebapp.com/landingpage?clientid=xxxx . page takes xxxx , writes session, used set themes , data. similar above work within iframe in 3rd parties site. provider javascript code 3rd party's web master dynamically generate content on website, originating our servers. i'm not sure how this, see providers disqus , f...

c# - Html Agility Pack is truncating a meta tag's value -

i using html agility pack parse html , having issue poorly formatted meta tag. given meta tag: "<meta name=\"productattributes\" value=\"shop: baby|category: category|category: babies\" r\"us=\"\" exclusives|family:=\"\" strollers|name:=\"\" baby=\"\" trend=\"\" expedition=\"\" elx=\"\" travel=\"\" system=\"\" stroller=\"\" -=\"\" everglade|price:=\"\" 239.99\"=\"\">" when call: htmlnode productattributes = hap.documentnode.selectsinglenode("//meta[@name='productattributes']"); var productattributesstr = productattributes.getattributevalue("value", ""); the resulting productattributesstr ending value truncated @ \”r”: "shop: baby|category: category|category: babies" what doing wrong? you using " data inside attribute value delimite...

c# - Selecting on Sub Queries in NHibernate with Critieria API -

so have sql query following structure: select p.* ( select max([price]) max_price, [childid] childnodeid [items] group [childid] ) q inner join [items] p on p.[price] = q.[max_price] , p.[childid] = q.[childnodeid] i need recreate query in nhibernate, using criteria api. tried using subqueries api, seems require inner query returns single column check equality property in outer query. however, return two. i've read can accomplished via hql api, need criteria api, we're going dynamically generating queries on fly. can steer me in correct direction here? i've managed resolve similar problem adapting original sql query. i've ended (pseudo sql code): select p.* [items] p exists ( select [childid] childnodeid [items] q p.[childid] = q.[childnodeid] group q.[childid] having p.[price] = max(q.[price]) ) and queryover implementation: var subquery = queryover.of(() => q) .selectlist(list => list.selectgroup(() =>...

iphone - Whats the point in UrbanAirship? -

i'm looking push notifications app i'm creating. i've heard lots urbanairship can't seem find definitive reason why should use it? far understand ua middle man? this page shows free version doesn't have push composer, developer still need server create notification, if own server needed might go directly apns? what point , advantage of ua? , if use how send notifications without own server? a working implementation of push notifications involves many things, such as: keeping track of device ids (web service device contact, database store ids) storing metadata associated each device id (ie. can refer device username or group of devices tag) keeping track of devices have been deactivated (which happens if user turns of notifications) clearing out bad device ids actually forming raw request send message apple's servers some sort of service/program know when need send notifications urban airship takes care of 1-5 you, simplifies whole proc...

ios - Simulator not getting location -

i'm following this tutorial learn core data. i'm on section 4, adding events. in section 2 tutorial says add button become active seconds after prompted simulator location, never becomes active, idea might happening? ps: if hardcode button active before getting location following error: *** terminating app due uncaught exception 'nsrangeexception', reason: '*** -[nsmutablearray objectatindex:]: index 0 beyond bounds empty array' on following line: [self.tableview insertrowsatindexpaths:[nsarray arraywithobject:indexpath] withrowanimation:uitableviewrowanimationfade]; edit: posting more code bigger picture - (void)viewdidload { [super viewdidload]; self.title = @"locations"; self.navigationitem.leftbarbuttonitem = self.editbuttonitem; addbutton = [[uibarbuttonitem alloc] initwithbarbuttonsystemitem:uibarbuttonsystemitemadd target:self action:@selector(addevent)]; addbutton.enabled = no; ...

c# - Cross-thread operation not valid - listbox Clear statement -

i getting error because trying update listbox thread not created on: cross-thread operation not valid: control 'tbhistory' accessed thread other thread t = new thread(updatehistory); // kick off new thread t.start(); private void updatehistory() { //tbhistory listbox tbhistory.items.clear(); } can please give me code fix problem? know supposed use invoke examples found on google don't seen me. examples seem show how change label text, not clear listbox. you need use ui thread. accomplish this, use: private void updatehistory() { //tbhistory listbox myform.invoke ((action) (() =>tbhistory.items.clear())); } edit: added missing bracket code wouldn't compile.

c# - WCF Service References : Managing App.Config -

my solution composed of several class library projects. 1 of these include service reference. functionality exposed particular assembly need called several other assemblies. how can manage configuration file(s) solution, don't have repeat <system.servicemodel> contents on every single assembly making use of web service? that approach (repeating in every app's config) default , recommended way go - cannot have config files class-library assemblies (you can, it's fair bit of work them work - not worth trouble). if can't live this, create wcf client proxy in code, bindings, options, endpoints , all. gain bit of ease-of-use (no more config needing put every app calling class library), loose bit of flexibitlity (endpoint addresses , binding options hard-coded).

javascript - Match each address from the address number to the 'street type' -

i have paragraph of text contains following addresses: at 900 greenwood st. in 500 block of main street at 670 w. townline ave. before 1234 river avenue of 1125 main ave. i want match each address address number 'street type' (ave., street, lane, road, rd., etc.) except for addresses begin word of. so of addresses above, statement match: 900 greenwood st. 500 block of main street 670 w. townline ave. 1234 river avenue and not match: 1125 main ave. as far know, there isn't 1 simple regex pattern kind of complicated task. there many variables cover 1 pattern work reliably. first guess "street", "ave", etc., if street name doesn't have suffix (i.e. 999 la canada)? phrase between "at", "in" or "before", if 1 of phrases isn't address? see mean? my suggestion take @ lingua::en::addressparse perl.

Is it possible to make Java ME application applying phone cell tower location to get a fingerprint to the location -

i know quite difficult know location cell tower because have know exact location of cell tower black box network operator. question fingerprint of location. , if @ location , store position x. have been @ location again , phone detect position x . question : is possible . how accuracy . can program run on java mobile application . are there recommendations start new java me . want know langauge use , netbeans , eclipse or other , .... do have resource make life easier me thank in advance support. you can current cellid criteria cr= new criteria(); cr.sethorizontalaccuracy(500); // instance of provider locationprovider lp= locationprovider.getinstance(cr); // request location, setting one-minute timeout location l = lp.getlocation(60); coordinates c = l.getqualifiedcoordinates(); if(c != null ) { // use coordinate information double lat = c.getlatitude(); double lon = c.getlongitude(); } using xellid can coordinated opencelid database accuracy may...

How to get the set of nodes based on a given CSS selector in jQuery? -

i want retrieve set of nodes based on given css selector in jquery. done in yui yahoo.util.selector.query(abc,root), abc given css. have convert jquery. var nodes = $('.somecssselector'); to make array of dom elements instead of jquery object dom elements: var nodes = $('.somecssselector').toarray(); the default root document . above selector find .somecssselector elements in document. css selectors can of course establish own root. var nodes = $('#somecontainer .somecssselector'); this give exist descendant of element id somecontainer . if selected somecontainer , can use 1 of jquery's traversal methods [docs] find() [docs] method locates elements selected element. var container = $('#somecontainer'); var nodes = container.find( '.somecssselector' ); jquery has helpful documentation . search jquery field @ top filter actively narrow api you.

Undoing accidental git stash pop -

i stashed local changes before doing complicated merge, did merge, stupidly forgot commit before running git stash pop . pop created problems (bad method calls in big codebase) proving hard track down. ran git stash show , @ least know files changed. if nothing else, guess lesson commit more. my question: possible undo stash pop without undoing merge? try using how recover dropped stash in git? find stash popped. think there 2 commits stash, since preserves index , working copy (so index commit empty). git show them see diff , use patch -r unapply them.

iphone - ALAsset timestamp returns wrong date -

i trying timestamp of images, can correct latitude , longitude values, timestamp returns current time, not exif time of image. alassetslibraryassetforurlresultblock resultsblock = ^(alasset *asset) { cllocation *imageloc = [asset valueforproperty:alassetpropertylocation]; nsdateformatter *formatter = [[nsdateformatter alloc] init]; [formatter setdateformat:@"dd/mm/yy hh:mm:ss"]; nsstring *trailtime = [formatter stringfromdate:imageloc.timestamp]; nslog(@"---+++ image timestamp: %@", trailtime); [formatter release]; any appreciated, thanks you need date using alassetpropertydate key. nsdate * date = [asset valueforproperty:alassetpropertydate]; /* use `nsdateformatter` instance print date */

gwt - CellWidget not getting displayed -

i trying make basic cellbrowser widget work in app. structure can replace later meaningfull. looked samples , implemented 1 when try integarting in application, wont work! here part of code. problem? why cant see widget? public class listviewimpl extends composite implements listview { private static listviewimpluibinder uibinder = gwt .create(listviewimpluibinder.class); interface listviewimpluibinder extends uibinder<widget, listviewimpl> { } private presenter presenter; @uifield(provided=true) cellbrowser cellbrowser; public listviewimpl() { treeviewmodel model = new listtreeviewmodel(); cellbrowser=new cellbrowser(model,null); cellbrowser.setkeyboardselectionpolicy(keyboardselectionpolicy.enabled); cellbrowser.setanimationenabled(true); initwidget(uibinder.createandbindui(this)); } @override public void setpresenter(presenter presenter) { this.presenter=presenter; } @override public widget aswidget() { return this; } } ...

mysql last url id always comes out to 0 -

$urlid = mysql_query("select url_id url order url_id desc limit 1"); foreach($textnode $key => $value) { $value = stripslashes($value); $value = mysql_real_escape_string($value, $con); mysql_query("insert paragraphs (paragraphs, url_id) values ('$value', '$urlid')"); } has been returning 0 url_id column. suggestions ? should returning 1. mysql_query function retrieving resource object. need go looping , retrieve actual data mysql_fetch_array() function. i.e: while($rowfeach = mysql_fetch_array($urlid)); print_r($rowfeach); try this. thanks.

ruby - Search by conten_type in rails? -

i want provide search functionality on basis of spreadsheets, presentations, documents, images, videos etc .. are there plugins or gems available type of functionality ? suggestions provide functionality ? you can use paperclip gem upload , store files. stores content_type automatically, you`ll have possibility search/filter content type etc.

sql - how To select fields from two tables -

i need select these fields----- user_id, sales_vertical, partner_id, category, sub_category, stage_id, exp_revenue, action, action_date, title_action, date_action, details opportunity_history table and tri_title, tri_subtitle res_partner table res_partner.partner_id = opportunity_history.partner_id in single query. how can that? thanks adil why many downvotes , no comments? try with: select oh.ser_id, oh.sales_vertical, oh.partner_id, oh.category, oh.sub_category, oh.stage_id, oh.exp_revenue, oh.action, oh.action_date, oh.title_action, oh.date_action, oh.details, rp.tri_title, rp.tri_subtitle opportunity_history oh inner join res_partner rp on rp.partner_id = oh.partner_id

asp.net - Button created in RowDatabound doesn't fire click event -

i adding linkbutton in gridview rowdatabound event , here firing click event on protected void cgvprojectpropertylist_rowdatabound(object sender, gridviewroweventargs e) { if (e.row.rowtype == datacontrolrowtype.datarow) { linkbutton lnkdelete = new linkbutton(); lnkdelete.text = "delete"; e.row.cells[col_index_delete].controls.add(lnkdelete); lnkdelete.commandname = "delete"; lnkdelete.click += new eventhandler(lnkdelete_click); } } void lnkdelete_click(object sender, eventargs e) { } lnkdelete_click event not working. thanks. the problem caused fact adding linkbutton control dynamically, pretty painful approach in asp.net webforms. in order events in asp.net work control has there after load event, because that's when control events fired. otherwise there isn't linkbutton bind click event to. my suggestion try add linkbutton in markup instead. save lot of pain. can u...

php - How to prevent adding same product to cart more then one time in magento -

i new in magento development. dont want user add product more once cart.if he/she need change qty of product he/she need change mycart page add cart button allow once add product, after when he/she clicks on add cart button must "it added cart if want change quantity please go mycart". for example can see www.flipkart.com. have at: product -> inventory -> maximum qty allowed in shopping cart system -> configuration -> inventory -> maximum qty allowed in shopping cart have @ customize magento using event/observer . events use, example: checkout_cart_update_items_before , checkout_cart_product_add_after also i'd suggest looking atthe: /app/code/core/mage/checkout/model/cart.php other events might helpful. in file also, you'll find code like: $this->getcheckoutsession()->adderror( mage::helper('checkout')->__('some of requested products unavailable.') ); which use displaying the error message cu...

android - How to Stream Audio from PC through Bluetooth -

here's trying do. capture audio being played on pc , stream through bluetooth , play through android device paired pc. have worked bluetooth little basic stuffs. , have less idea on how go on this. target device android 2.2 (and above). guess have use bluetooth profiles, not sure. also, not aware of other caveats may have face. would point me @ correct direction. tips, links help. thank you. it depends on capability / profile android device supports, streaming use a2dp profile , android device need support a2dp sink role. typically role supported stereo headsets , speakers etc. android phones not support sink - phones a2dp source (or initiator of streaming)

windows - how to rewrite history to remove executable bit in git -

i have imported rather large repository scm git. unfortunately migration done (had be) on windows , every file got committed git execute bit set. avoid having migration again (it long , hang-prone process) trying figure out if can clean out executable bit server side. thought using git filter-branch somehow combined git update-index, take hints how proceed. doing huge commit @ end clearing executable bits not solution -- don't want every file have bump in history. this seems trick: git filter-branch --index-filter 'git ls-files -s | sed s/^100755/10644/ | git update-index --index-info' -- --all

preloader - Best way to preload all images and background images using jQuery -

i have website consists of 2 pages: index.php , content.php. both pages pretty long , contain lots of graphics (both inline images , background images via css). graphics located in 1 folder (/img). my idea include preloader on index.php. should display progress bar / spinner or , display "real" content of index.php once graphics loaded. what best way achieve using jquery? thanks in advance

java - Class methods vs instance methods -

hi class methods measured faster instance methods since doesn't require loading instance? if so, should use class methods when possible? thanks i don't know generally, remember measuring application time ago, , static methods indeed faster. from design standpoint argue method can sensibly static (meaning without explicitly passing instance parameter or that), should be.

Git Pushing from a local branch to a remote tracking branch -

i have master branch , branched out build branch. i cloned repository different machine. created branch my_build track remote build branch. have few commits made in my_build branch. want push these changes remote build branch. i tried pulling remote build branch , worked. but there way can push commits in my_build branch remotes build branch? i have master , 2 branches branch , branch b branched master @ same point. i in branch , want push commits branch b how can this? i have master , branch a. cloned machine. created branch b made commits in b. b not tracking a. how can push changes b a. how can pull a's changes branch b. and above cases master , repos non-bare repos. have @ refspec format of git pull git push origin branch_from:branch_to

php - How to get array of row objects from my result in mysqli prepared query -

i return results prepared query (mysqli) objects in array cant find fetchall method or similar. how go this? public function getimageresults ($search_term) { if (empty($search_term)) return false; $image_query = $this->db_connection->stmt_init(); $image_query_sql = " select images.url url images, imagesearch, imagesearchresults imagesearch.search_string = ? , imagesearchresults.search_id = imagesearch.id , imagesearchresults.image_id = images.id , images.deleted = 0 , imagesearch.deleted = 0 , imagesearchresults.deleted = 0 "; if ($image_query->prepare($image_query_sql)) { $image_query->bind_param('s', $search_term); $image_query->execute(); $image_query->store_result(); ...

jquery - Validate phone number by custom validator and javascript -

i have phonetextbox control, contains 4 textboxes: country code (1-3 digits), city code (1-7 digits), local number (1-7 digits) , phone number (1-5 digits). the phone number not required. the code below doesn't work. <script type="text/javascript"> function validatephonenumber(source, args) { if ( $('#<%=txtcountrycode.clientid %>').val().match(/^\d{1,3}$) || $('#<%=txtcitycode.clientid %>').val().match(/^\d{1,7}$) || $('#<%=txtmainphonenumber.clientid %>').val().match(/^\d{1,7}$) ) { if ($('#<%=txtextraphonenumber.clientid %>').val().length<=0) { args.isvalid = true; return; } else { if ($('#<%=txtextraphonenumber.clientid %>').val().match(/^\d{1,5}$) { args....

vba - Editing Word 2003 template with custom toolbar in Word 2007 -

i have word 2007 , word 2003 template (.dot file). when open it, can see has macro's in it, stored in modules. can see template adds buttons add-ins tab in ribbon. how can modify these buttons? text or macro each button triggers? as test deleted macros in template, saved it, restared it, , still gave me custom buttons in add-in tab. of course if press buttons, gives me error macro not there. fune. then, if view template's code (alt-f11), there no code @ all. no add-in loaded (as seen in word options > add ins window). how word 2003 template know buttons load? custom toolbar info stored in word 2003 template? i not sure understood question. yet, here few elements. modify buttons generated macro you have change vba code. see : this link word 2003 : http://www.ozgrid.com/vba/custom-menus.htm this link word 2007+ : http://www.rondebruin.nl/ribbon.htm buttons loaded if custom buttons still appear after deleted code : i'd think missed part of...

php - Assigning and Passing Sessions Variables Between Subdomains -

i going create site have have multiple subdomains. example: shop.domain.com blog.domain.com news.domain.com account.domain.com i know if session variables can passed between subdomains. example $_session['variable'] accessible on of subdomains listed above. you first have make sure store session data in way hosts can access them; if hosted on same machine fine, otherwise might want use session handler e.g. uses database, memcache, ... store session data. have make sure session id available on subdomains; can achieved setting ini.session.cookie-domain . for more information on sessions should read appropriate chapter in fine php manual.

c# - Fading the background while modal dialog is shown -

when shutting down windows xp system, displays modal dialog box while background fades grayscale. achieve same effect in of programming languages in tag list. can help? this pretty easy winforms. need borderless maximized window gray background opacity change timer. when fade done, can display dialog borderless , uses transparencykey make background transparent. here's sample main form implements this: public partial class form1 : form { public form1() { initializecomponent(); this.formborderstyle = formborderstyle.none; this.windowstate = formwindowstate.maximized; this.backcolor = color.fromargb(50, 50, 50); this.opacity = 0; fadetimer = new timer { interval = 15, enabled = true }; fadetimer.tick += new eventhandler(fadetimer_tick); } void fadetimer_tick(object sender, eventargs e) { this.opacity += 0.02; if (this.opacity >= 0.70) { fadetimer.enabled = false; ...

c++ - Why am I getting a g++ error about discarding qualifiers in my code when compiling? -

just little warning: i've been doing c++ 2 weeks now, expect see stupid beginner errors. i writing (useless) code familiar classes in c++ (it's wrapper around string), , added copy constructor, keep on getting error: pelsen@remus:~/dropbox/code/c++/class-exploration> make val g++ -o val.o val.cpp val.cpp: in copy constructor ‘cvalue::cvalue(const cvalue&)’: val.cpp:27: error: passing ‘const cvalue’ ‘this’ argument of ‘const std::string cvalue::getdata()’ discards qualifiers make: *** [val] error 1 i have done research, apparently error caused copy constructor doing non-const operations. much. in response, made cvalue::getdata() const member. apart accessing getdata(), copy constructor doesn't anything, don't see why still getting error. here (some of) buggy code: 7 class cvalue { 8 string *value; 9 public: 10 cvalue(); 11 cvalue(string); 12 cvalue(const cvalue& other); 13 ~cvalue(); 14 void setdata(string); 15 const strin...

c# - Entity Framework Error - The version of SQL Server in use does not support datatype 'datetime2' -

i using entity framework 4.0 in asp.net 4.0 web form. all fine on development server. when production server, elmah logs error system.argumentexception version of sql server in use not support datatype 'datetime2'. i did quick research , found out datetime2 aka datetime2(7) problem , setting providermanifesttoken="2005" solve issue. my problem this. development server has sql server 2008 r2 , production server has sql server 2008 express . so, changing manifest 2005 doesn't seem right. my questions are will setting providermanifesttoken="2005" work? why has entity framework generated datetime2 when haven't used @ in of table? is there better work around? i dont see workaround till date. if using sql server 2008 express , please right click on edmx, open xml (text) editor , set providermanifesttoken="2005" . doesn't sound good. have got of now.

c# - How to append text to RichTextBox without scrolling and losing selection? -

i need append text richtextbox, , need perform without making text box scroll or lose current text selection, possible? the richtextbox in winforms quite flicker happy when play around text , select-text methods. i have standard replacement turn off painting , scrolling following code: class richtextboxex: richtextbox { [dllimport("user32.dll")] static extern intptr sendmessage(intptr hwnd, int32 wmsg, int32 wparam, ref point lparam); [dllimport("user32.dll")] static extern intptr sendmessage(intptr hwnd, int32 wmsg, int32 wparam, intptr lparam); const int wm_user = 0x400; const int wm_setredraw = 0x000b; const int em_geteventmask = wm_user + 59; const int em_seteventmask = wm_user + 69; const int em_getscrollpos = wm_user + 221; const int em_setscrollpos = wm_user + 222; point _scrollpoint; bool _painting = true; intptr _eventmask; int _suspendindex = 0; int _suspendlength = 0; public void suspendpainting() { ...

php - Java decrypt error: data not block size aligned -

i'm trying encrypt data between android application , php webservice. i found next piece of code in website: http://schneimi.wordpress.com/2008/11/25/aes-128bit-encryption-between-java-and-php/ but when try decrypt exception of title "data not block size aligned" this method in mcrypt class public string encrypt(string text) throws exception { if(text == null || text.length() == 0) throw new exception("empty string"); cipher cipher; byte[] encrypted = null; try { cipher = cipher.getinstance("aes/cbc/nopadding"); cipher.init(cipher.encrypt_mode, keyspec, ivspec); encrypted = cipher.dofinal(padstring(text).getbytes()); } catch (exception e) { throw new exception("[encrypt] " + e.getmessage()); } return new string( encrypted ); } public string decrypt(string code) throws exception { if(code == null || code.length() == 0) throw new exce...

silverlight - RIA/EF4 Entity property mapped to NOT NULL nvarchar - empty string -

background: entity framework 4 silverlight 4 ria services mssql server 2008 i have entity has string property named description. in database maps not null nvarchar(200) . problem: when try insert new row of entity, do: myexampleentity entity = new myexampleentity() { name = "example", description = "" // note line! }; databasecontext db = new databasecontext(); db.myexampleentities.add(entity); db.submitchanges(); this, however, causes exception saying "the description field required." question: should not "empty string" - a string 0 characters ? i believe description = null should treated providing no value . why string, has value (although length 0), considered if have omitted value? on level conversion happen? on ria, on ef or in mssql? is there way make description have zero-length value when set description "" , cause exception when description = null (having no value)? ...

redirect - JSP - sendRedirect is not working -

i have simple jsp file: string url =""; if(acontroller.find(integer.parseint(request.getparameter("id"))) != (null)) { url += request.getparameter("name") + "&id="+request.getparameter("id") + "&__locale=" + localeutil.setlocalestringmail(request, response); url += "&__overwrite=true"; system.out.println("this report has not been deleted"); response.sendredirect(url); } else{ url += "error.rptdesign&__locale=" + localeutil.setlocalestringmail(request, response) + "&user="+report.getcreatorname(); system.out.println("this report has been deleted"); response.sendredirect(url); } it goes first condition, system out , send redirect. doesn't go else , throws following exception: [#|2011-07-01t16:29:08.595+0300|warning|glassfishv3.0|javax.enterprise.system.container.web.com.s...

asp.net - Dynamic link issue in an MVC 3 website -

i'm creating first asp.net mvc 3 website company's intranet. it's pretty cool, play audio recorded our phone system , saved in our db. that's working good, i'm having hard time figuring out how should simple. please forgive syntax errors have, rough draft. i have table in index view /apps list appname's, , next each appname want display link view, text of link being count() of calldetails associated app. i have 2 classes: public class apps { public int appid { get; set; } public string appname { get; set; } } public class calldetail { public int id { get; set; } public int appid { get; set; } public byte[] firstname { get; set; } public byte[] lastname { get; set; } ....etc } a context each: public class appscontext : dbcontext { public dbset<apps> apps { get; set; } } public class callcontext : dbcontext { public dbset<calldetail> calldetails { get; set; } } a controller method each: // appscon...

asp.net mvc 2 - The best way for mapping 2 table? -

i have 1 table name activity type there filed id (auto number) , field type name. , other table name activity there field id (auto number) ,field name , field activitytypeid (id table activitytype ) . want display in page show activitytype (name , id) in dropdownlist , name(activity) in textbox.what best way ?

Need a python script to search specific keywords in a collection of sql files returning the index of where each keyword was found -

i'm extremely new python , wondering how take collection of files (sql), , using specific keywords, find line of code matched throughout files. notions, ideas or suggestions life savingly helpful. kind regards tiago m solution s = 'somestring' names = ['file1.sql', 'file2.sql'] n in names: f = open(n) lines = f.readlines() i, l in enumerate(lines): if s in l: print 'line %d' % (i)

c# - Should I dispose() the Matrix returned by Graphics.Transform? -

i need draw primitives graphics object different transformation matrix. wonder should dispose matrix or graphics me: using (var g = graphics.fromimage(...)) { ... code ... var tmp = g.transform; g.translatetransform(...); ... code ... g.transform = tmp; // should call tmp.dispose() here? tmp.dispose(); ... code use g .... } http://msdn.microsoft.com/en-us/library/system.drawing.graphics.transform.aspx says: because matrix returned , transform property copy of geometric transform, should dispose of matrix when no longer need it. i not need after g.transform = tmp; , should dispose it? quoting msdn , graphics.transform... gets or sets a copy of geometric world transformation graphics. (emphasis mine.) when call transform , you're making copy of matrix, , should dispose yourself. long own them, it's idea dispose objects implement idisposable , , preferably using using(...) syntax.

objective c - bring data to new view through UITableViewCell -

i want populate uitableview data database and, when tap cell, in didselectrowatindexpath , sending selected cell new view. accomplished standard way. want when cell tapped, data of cell brought other view. doing not working mycoredataclassname *object = [fetchedobjecs objectatindex:indexpath.row]; this same way read on other forum posts not helpfull me. whenever use line , run app, when tap cell hangs second , exits app. doing wrong? kindly guide me. p.s: using core data fill in table. regards. so objective pass data fid view next view. can in many ways. let me post 1 way - using nsuserdefaults consider example code. in first view: nsinteger row = [indexpath row]; nsuserdefaults *rowselect = [nsuserdefaults standarduserdefaults]; if (row ==0){ [rowselect setinteger:0 forkey:@"thechosenrow"]; } if (row ==1){ [rowselect setinteger:1 forkey:@"thechosenrow"]; } if (row ==2){ [rowselect setinteger:2 forkey:@"thechosenrow...

c# - ASP.NET MVC 3 Html helper not recognized -

for reason html helper not recognized. @using system.data.sqlclient @using system.data <!doctype html> <html> <head> <title>site visits</title> </head> <body> <div> @{ public string getsitevisits() { datatable dt = new datatable(); sqldataadapter sda = new sqldataadapter( "select numvisits tblsitevisits ipaddress='" + request.userhostaddress + "'", new sqlconnection("data source=*****;initial catalog=*****;persist security info=true;user id=*****;password=*****;multipleactiveresultsets=true")); sda.fill(dt); string table = "<table><tr>"; foreach (datacolumn dc in dt.columns) { table += "<th>" + dc.columnname + "</th>"; } ...

jquery - select an option without reload page -

i know, code not well, tryed best. here code: function submitform() { document.getelementbyid("formelement").submit(); } jquery(document).ready(function($) { var img = new image(); $(img).load(function () { $(this).hide(); $('#loader').removeclass('loading').append(this); $(this).fadein(800); }).attr('src', '.chart.php?id=<? echo $sid; ?>&date=<? echo $order; ?>'); }); <div id="loader" class="loading"></div> <select name="order" class="dropdown" onchange="submitform()"> <option disabled selected> <? echo(choose); ?> </option> <option value="./chart.php?id=<? echo $sid; ?>&date=d"> <? echo(choose_day); ?> </option> <option value="./chart.php?id=<? echo $sid; ?>&date=m"> <? echo(choose_month); ?> </option> <option value="./chart.php?...

iphone - Is there a delegate in the parent view controller that gets called after a modal view gets dismissed? -

after modal view controller dismissed, there delegate method called bring parent view controller front? i ended using delegation apple's view controller programming guide ios : http://developer.apple.com/library/ios/#featuredarticles/viewcontrollerpgforiphoneos/modalviewcontrollers/modalviewcontrollers.html#//apple_ref/doc/uid/tp40007457-ch111-sw14 when comes time dismiss modal view controller, preferred approach let parent view controller dismissing. in other words, same view controller presented modal view controller should take responsibility dismissing whenever possible. although there several techniques notifying parent view controller should dismiss modally presented child, preferred technique delegation. there example in coredatarecepies sample code when adding recipe fit trying do.

wifi - Multicast Support on Android in Hotspot/Tethering mode -

i have prototype android app listening multicast packets 'discover' clients communicate with. socket set similar this: inetaddress group = inetaddress.getbyname("228.1.2.3"); multicastsocket s = new multicastsocket(4000); s.joingroup(group); this works when devices connected via wifi. support phone acting portable hotspot. however, while devices appear connect hotspot correctly no longer receive multicast data. i'm wondering if there restrictions disallow type of communication in hotspot mode, or if there additional network configuration required enable this? i've tried on couple different devices running gingerbread , froyo no luck. as article show: https://plus.google.com/+chainfire/posts/9nmemrkyncd multicastsocket::setnetworkinterface() would answer you can find wlan0 eth : public static networkinterface getwlaneth() { enumeration<networkinterface> enumeration = null; try { enumeration = networkinterface....

iphone - Error: Variable-sized object may not be initialized. But why? -

enter code hereint quantity = [array count]; int i; (i=0; i<quantity; i++) { nsstring *imagename = [nsstring stringwithformat:@"car_%@.jpg", [[array objectatindex:i] objectforkey:@"carname"]] ]; uiimage *img[i] = [uiimage imagenamed:imagename]; uiimageview *imgview[i] = [[uiimageview alloc] initwithimage:img[i]]; imgview[i].frame = cgrectmake(i*kwidth, 0, kwidth, kheight); [scrollview addsubview:imgview[i]]; [imgview[i] release]; }`enter code here` error: variable-sized object may not initialized. why? you may want try this: int i; (i=0; i<quantity; i++) { nsstring *imagename = [nsstring stringwithformat:@"car_%@.jpg", [[array objectatindex:i] objectforkey:@"carname"]] ]; uiimage *img = [uiimage imagenamed:imagename]; uiimageview *imgview = [[uiimageview alloc] initwithimage:img]; imgview.frame = cgrectmake(i*kwidth, 0, kwidth, kheight); [scrollview addsubview:imgview]; ...

python - Appending strings to a list -

novice question here. i'm working on finding every single combination of various string elements, , want place them list. import itertools mydata = [ ] main = [["car insurance", "auto insurance"], ["insurance"], ["cheap", "budget"], ["low cost"], ["quote", "quotes"], ["rate", "rates"], ["comparison"]] def twofunc(one, two): a, b in itertools.product(main[one], main[two]): print a, b def threefunc(one, two, three): a, b, c in itertools.product(main[one], main[two], main[three]): print a, b, c twofunc(2, 0) #extremely inefficient run these functions on , over. alternative? twofunc(3, 0) twofunc(0, 4) twofunc(0, 5) twofunc(0, 6) threefunc(2, 0, 4) threefunc(3, 0, 4) threefunc(2, 0, 5) threefunc(3, 0, 5) threefunc(2, 0, 6) threefunc(3, 0, 6) the above code prints out each permutation, doesn't append values list. i've tried ...

Java Scanner loop? -

i making maze solver. reason everytime line marked '-->' reached, "enter height: " outputted. line (which not run when reached) somehow makes method loop. private void makemap() { map map; //used convert char array graph int height; //the height of map user input char[][] array; //used store char map system.err.println("enter height: "); height = scanner.nextint(); //gets , stores height user array = new char[height][]; //initializes map input height for(int i=0; i<height; i++) { //adds row row map array system.err.print("enter next line of map: "); array[i] = scanner.next().tochararray(); } --> map = new map(array); //initializes map passing char array graph = map.makegraph(); //creates graph char array } i labelled '-->' believe problem lays. code put before marked line execute, line reached loops top of method. below map constructor: public map(char[][] p...

Perl tail logs in between servers -

i want able send apache log file line line (tail) in between 2 servers (unidirectionally, 1 2 one), want use perl. any idea?, able things each line of apache log in real time in server. thanks you! not sure perl (you can wrap in bit of perl can manipulate data), netcat (or nc short) (should available on systems). on 1 server tail -f filename | nc -l 12345 on other server nc hostname 12345 of course can use different port number. guess in perl exec these commands (ssh remote server etc.). has given ideas! nc has loads of options should able find something. if want write netcat in perl that's different story.

How to make nginx work with dyndns? -

i trying make local site work on web dyndns. using nginx server. here have in file located in 'sites-available': server { listen 80 default; server_name mydyndnshost; ... if add "mydyndnshost" listen, nginx fail start. if leave this, work, localy, if access "mydyndnshost" in browser, won't show site. show router login screen. lol sounds need open inbound tunnel in router/firewall. mydyndnshost name pointing public ip, router/firewall answers. you'll need configure rule "when receiving hits on port 80, forward them port 80 of (my server)" or similar. edit: oh, , turn off public login ability on router. should (normally) accessible inside only.

performance - Is it possible to have an Array which evaluates its elements lazily? -

consider bigint class, should cache common values in smallvalues : object bigint { lazy val smallvalues = array(zero, one, two) lazy val 0 = new bigint(0, array[long]()) lazy val 1 = new bigint(1, array[long](1)) lazy val 2 = new bigint(1, array[long](2)) private lazy val cachesize = smallvalues.length def apply(num: long): bigint = { // number cached? if (0 <= num && num < cachesize) smallvalues(num.toint) // figure out sign , make number positive after else { val (sign, value) = if (num < 0) (-1, num * -1) else (1, num) new bigint(sign, array(value)) } } } class bigint private(val sign: int, val num: array[long]) extends ordered[bigint] { println("constructing bigint") ... } the problem here accessing 1 element of array forces evaluation of elements: scala> bigint.smallvalues(0) constructing bigint constructing bigint constructing bigint res0: bigint = bigint@2c176570 how solve that? ed...