Posts

Showing posts from 2014

BASH - quickly determine the number of lines in a file that start with a Uppercase -

how can determine number of lines in file start uppercase? i think regex [a-z]*), don't want "read line" ... more faster. your best option if don't want use read loop use grep , -c switch counts matching lines, this: grep -c ^[a-z] the_file.txt

Is there any XAML Grid element equivalent in HTML/CSS? -

i have deep experience wpf, xaml, etc. however, i'd need create in html/css/js. in wpf, in silverlight, there versatile element "grid". it's list hosting kind of visual object, arranged accordingly row/column collection definitions. here (simple imho) example non-xaml addicted: http://wpftutorial.net/gridlayout.html i believe it's important control managing layout of visual. now, i'm wondering whether there equivalent "component" web world, possibly simple , clean: not tons of code such simple problem. in other words, don't want rely on frameworks such asp.net, extjs or else. guideline, minimal html/css/js section. it's fine relying on recent browsers. many in advance. well, found 1 myself, although it's still under development: @ moment seems ie10 implements it. http://ie.microsoft.com/testdrive/graphics/hands-on-css3/hands-on_grid.htm i hope feature won't trashed in short.

php - Unable to upload camera pictures -

firstly, new so, html & php, english isn't main language sorry if i'm offending in way or asking stupid questions. i have a(n almost) functional upload function. uploading photo works in every way except when directly make picture phone. i have samsung galaxy s2. (it seem work on iphone, haven't tested on other phones) my form: <form action='m.dier_plaatsen.php' method='post' enctype='multipart/form-data'> <table> <tr> <td> kies een bestand: </td> <td> <input type='file' name='img1' value='choose file' /> </td> </tr> <tr> <td> kies een bestand: </td> <td> <input type='file' name='img2' value='choose file' /> </td> ...

android - How to insert an object from canvas? -

is possible point image through canvas?. able draw rect or draw line using canvas bitmap. thing insert image drawable folder instead of pointing out rect or circle. possible do. new topic, if wrong kindly let me know. you can use below in ondraw() bitmap bmp = bitmapfactory.decoderesource(getresources(), r.drawable.yourimage); // bitmap drawable folder canvas.drawbitmap(bmp, 100, 100, paint); // draw bitmap canvas 1st argument bitmap, 2nd argument position left, 3rd argument position top , 4th argument paint object. for more info check doc http://developer.android.com/reference/android/graphics/canvas.html

php - Simplexml count inside a do-while loop -

i trying simplexml count inside do-while loop, yes simple count not correct inside 2 loops. there easier way count? $query_fl = "select * table"; $fl = mysql_query($query_fl, $rf) or die(mysql_error()); $row_fl = mysql_fetch_assoc($fl); { $xml = $row_fl['fu']; $xmldoc = new domdocument(); $xmldoc->load($xml); $rss = simplexml_load_file($xml); $items = $rss->channel->item; foreach($items $item){ echo $rss->channel->title; echo $feed_count."<br>"; $feed_count++; } $feed_count=1; } while ($row_fl = mysql_fetch_assoc($fl)); ------------- the output this feed 1 - count-1 feed 1 - count-2 feed 1 - count-3 feed 1 - count-4 feed 1 - count-5 feed 2 - count- 1 feed 2 - count- 2 feed 2 - count- 3 ... .. --------------- i want output as feed 1 - count-5 feed 2 - count-3 you should using mysqli instead of mysql_* depricated, moving on... have couple of optio...

bash how to pass array as an argument to a function -

as know, in bash programming way pass arguments is $1 , ..., $n . however, found not easy pass array argument function receives more 1 argument. here 1 example: f(){ x=($1) y=$2 in "${x[@]}" echo $i done .... } a=(“jfaldsj jflajds" "last") b=noefldjf f "${a[@]}" $b f "${a[*]}" $b as described, function f receives 2 arguments: first assigned x array, second y. f can called in 2 ways. first way use "${a[@]}" first argument, , result is: jfaldsj jflajds the second way use "${a[*]}" first argument, , result is: jfaldsj jflajds last neither result wished. so, there having idea how pass array between functions correctly. you cannot pass array, can pass elements (i.e. expanded array). #! /bin/bash function f() { a=("$@") ((last_idx=${#a[@]} - 1)) b=${a[last_idx]} unset a[last_idx] in "${a[@]}" ; echo "$i" done echo ...

javascript - Stick whole table to its original position while scrolling -

i'm trying make sticky table while scrolling page. i'm having 2 tables 1 after another, when i'm scrolling page, first table moves 10px; , stops. here jsfiddle , tables don't move @ all. anyone, can advice me, i'm doing wrong? html: <div id="header"> header </div> <table class="table_filter_data filter_table" cellpadding='0' cellspacing='0' width='100%'> <tr> <td> table_1 </td> </tr> </table> <table class="table_filter_data filter_table" cellpadding='0' cellspacing='0' width='100%'> <tr> <td> table_2 </td> </tr> </table> jquery: <script type="text/javascript"> function updatefilterheaders() { $("div.div_filter_table").each(function() { ...

My HTML file isn't connecting to my CSS file. Why? -

i not being able connect css html file. put code below in head @ top of html file. used code on website connect css html: http://w3schools.com/tags/tag_link.asp this html file far: <!doctype html> <html> <head> <link rel="stylesheet" type="text/css" href="theme.css"> </head> <body id="whole-background"> <h1>akhil sharma</h1> <p>official website</p> </body> </html> and css: #whole-background { background-color: #0099ff; } someone please tell how can fix problem. save file called theme.css in same directory of html page, css rules #whole-background { background-color: #0099ff; }

SSIS Derived column trailing zeros -

im having issue derived column. have flat file source contains delimited data. some of columns currencies , data saved in strange format (older systems tend way). anyways, data saved such: 00030.200, 0123.410,0002231.210 i need convert these strings currency dt_cy. i've tried direct casts using difference numerical types fail (not sure if leading or trailing zeros causing it) so question simple. expression can use in derived column remove leading , trailing zeros. note data not same length time can't left/right substring options. any help? tx you have done way, using derived column: replace(ltrim(replace(datatoconvert, "0", " ")), " ", "0") basically, convert zeros white spaces take benefits of ltrim function. i founded solution here . here example of how proceed: (let's want convert 0040.300. purpose, can display number as: |0|0|4|0|.|3|0|0| see how replace statement affects our data) basically, c...

windows - Threading in C with CreateThread() -

i novice c, , trying make program run midi sequences, , basically, have 2 functions, both running different midi pattern, , need them run in parallel. due nature of functions (one running sequence , other playing random notes), 100% sure can't have running in same function. i've been scouring internet clue on how pthreads (which apparently don't work on windows?) , createthread(), can't seem work. trying use createthread() , trying bring in integers required random midi sequence , getting error concerning 'lpthread_start_routine' reads: 'expected 'lpthread_start_routine' argument of type 'dword (*)(int, int, int)'. a sort of pseudocode of i'm working on here: dword winapi solo_thread(int key, int tempo, int scale) { ///// contains random midi notes } int backing(int key, int tempo, int backing) { handle thread = createthread(null, 0, solo_thread, null, 0, null); if (thread) { ////// con...

Django Sorl Thumbnail Resizing error -

Image
i"m been using django sorl thumbnail , encountered problem. i set settings on template scale image larger 500 width , height resize around 500 width , height. problem , happen if image lower fixed settings height , width 500.the image scaled 500 width , height . how can fix problem image lower 500 width , height not need resize. { % thumbnail item.image "x500" im %} <img src="{{ im.url }}"> {% endthumbnail %} i got solved it, have set upscale=false . upscale boolean , controls if image can upscaled or not, default value true . {% thumbnail item.image "x500" upscale=false im %} <img src="{{ im.url }}"> {% endthumbnail %} then images lower 500px not upscaled.

android - Unable to copy sqlite database from assets to internal memory -

we trying copy sqlite database stored in assets folder local directory on actual phone unable so. checkdatabase tails database exists code fails when try read data phone. ( tried view database through ddms doesn't show there) phone have os 2.3.4 saw various folks have complained on stackoverflow did not find solution. is related https://code.google.com/p/android/issues/detail?id=949 also tried below library https://github.com/jgilfelt/android-sqlite-asset-helper sample code provided in fails while copying database , gives below error sqlite3_open_v2("/mnt/sdcard/android/data/com.sqliteassethelper.example/files/northwind", &handle, 2, null) failed consider using library , magic https://github.com/jgilfelt/android-sqlite-asset-helper hope you

r - Looping a function for each row in csv -

i have .csv file containing 22.388 rows comma seperated numbers. want find possible combinations of pairs of numbers each row seperately , list them pair pair, i'll able make visual representation of them clusters. an example of 2 rows file "2, 13" "2, 8, 6" when use str() function r says file contains factors. guess needs integers, need rows seperate, therefore i've wrapped each row in " ". i want possible combinations of pairs each row this. 2, 13 2, 8 2, 6 8, 6 i've gotten answer @flodel saying sample input - replace textconnection(...) csv filename. csv <- textconnection("2,13 2,8,6") this reads input list of values: input.lines <- readlines(csv) input.values <- strsplit(input.lines, ',') this creates nested list of pairs: pairs <- lapply(input.values, combn, 2, simplify = false) puts in nice matrix of integers: pairs.mat <- matrix(as.integer(unlist(pairs)), ncol = 2, byrow = ...

compiler errors - when use cygwin g++ to build a project , can't find the include head file even if I have indicated path with -I -

i knew there punch of kind problem bother . it's weird me . please patient let me finish problem statement . background : windows vista , cygwin latest version , opencv 2.4.3 my project make file opencv installed in d:\application\opencv2.4.3\opencv : opencv=/cygdrive/d/application/opencv2.4.3/opencv/build custom_includes+=-i${opencv}/include -i${opencv}/include/opencv -i${opencv}/include/opencv2/ml -i${opencv}/include/opencv2/highgui -i${src_dir} custom_libraries+= -l${opencv}/x86/mingw/lib -lopencv_core -lopencv_highgui -lopencv_imgproc -lopencv_objdetect and head file need build : #include <iostream> #include <string> #include <opencv2/core/core.hpp> #include <opencv2/core/core_c.h> blablabla... when execute : g++ -c src/objectdetector.cpp -wall -o3 -ffast-math -funroll-loops -i/cygdrive/d/application/opencv2.4.3/opencv/build/include -i/cygdrive/d/application/opencv2.4.3/opencv/build/include/opencv -i/cygdrive/d/application/opencv2.4...

wpf - Programmatically enter edit mode on datagrid row -

i have following request: items added , removed datagrid (wpf) button click. when user adds new row (new item) in datagrid, want automatically enter edit mode on new item. work if selectionunit cell, fullrow. tried change selectionunit cell before calling datagrig.beginedit() doesn't work. here's code: <datagrid name="dgdatagrid" margin="20,20,3,3" canusersortcolumns="true" itemssource="{binding allitems}" autogeneratecolumns="false" selectionunit="fullrow" selectionmode="single" canuseraddrows="false" canuserdeleterows="false" canuserresizerows="true" canuserreordercolumns="false"> <datagrid.columns> <datagridtextcolumn header="first column name" minwidth="160" binding="{binding path=firstcolumn}"/> <datagridcheckboxcolumn header="second column name" minwidth="100...

iphone - how to check which view in storyboard are showing -

i know storyboard view being showed. [self setleftpanel:[self.storyboard instantiateviewcontrollerwithidentifier:@"menulistviewcontroller"]]; [self setcenterpanel:[self.storyboard instantiateviewcontrollerwithidentifier:@"navcentercontroller"]]; [self setrightpanel:[self.storyboard instantiateviewcontrollerwithidentifier:@"designview"]]; i check if "navcentercontroller" shown, disable something any comments appreciated. if understand you're asking, in order check whether view being shown, should check window property. view controller following: if(self.view.window) // view controller being shown, else // view controller not being shown

memory - actionscript 3.0 how to clear RAM -

i'm using actionscript p2p application transfer files between peers. received files bytearrays stored in 1 array one: recvfiles[peerid][fileid].data:bytearray = filereference.data now i'm stuck in such situation - if decided transfer files size greater 1gb. means receiver memory gonna clogged. how can delete saved file bytearray after user save on pc? i thought this: recvfiles[peerid][fileid] = null; but i'm newbie in actionscript , don't how interracts memory... so question best way clear memory? thanks help! yes, should it. can try force garbage collection immediately, although not officially supported. can making localconnection. there more here on grant skinner's blog: http://gskinner.com/blog/archives/2006/08/as3_resource_ma_2.html try { new localconnection().connect('foo'); new localconnection().connect('foo'); } catch (e:*) {} // gc perform full mark/sweep on second call. if testing using debug versio...

Auto fill input in the html form - spring-security -

is there cross-browser mechanism automatically fill value of html form, if been filled previous time when user opened page? for example, have authentication page login form (username & password) used spring-security. in case of authentication failure user redirected login page. there way username input filled username entered first time (except of manually on server side)? there html tags or css properties?

c++ - Reading and writing double precision from/to files -

i trying write double arrays files , read them again. below code, there missing. sounds silly cannot right. #include <stdio.h> #include <stdlib.h> int main(){ int i,j,k; int n = 10; double* readin = new double[n]; double* ref = new double[n]; file* ptr1, *ptr2; ptr1 = fopen("output.txt","w"); //write out (i = 0; < n;i++){ ref[i] = (double)i; fprintf(ptr1,"%g\n",(double)i); } fclose(ptr1); //read file ptr2 = fopen("output.txt","r+"); //read in for(i = 0;i < n;i++) fscanf(ptr2, "%g", &readin[i]); fclose(ptr2); for(i = 0;i<n;i++) if(ref[i] != readin[i]){ printf("error: %g %g\n",ref[i], readin[i]); } return 0; } your fscanf using wrong format string (which gcc tell if enable sufficient warnings). so double filled float value, of course leads rather "random" errors. if change "%g" ...

mono - Searching for the best PCL profile for cross-platform development -

i working on extending number of supported platforms app, used support .net4/windows store/windows phone, hope cover mono android , ios. i've put business logic, models , view models portable class libraries (pcl) it's big dilemma subset of platforms should target. each combination causes fail. here results 4 platforms might use: profile 78 (net45+wp8+store): no problem tpl,await/async , support callermembername attribute (used in bindablebase view model base class). mono.android project refers such library fails build complaining non-present system.runtime.dll should referenced. profile 104 (net45+sl4+wp75+store): await/async don't work, callermember name not found, if remove references them, android project builds fine. profile 147 (net403+sl5+wp8+store): await/async don't work, callermember name not found, if remove references them, android project builds fine. profile 158 (net45+sl5+wp8+store): await/async don't work, callermember name not found, if ...

c# - Check radio button in RadioButtonList based on value read from database -

i have radiobuttonlist , select radio button in list based on value read database. once read value database, how make radio button in list become selected? you can assign value via radiobuttonlist.selectedvalue = reader.value; long know value in list (if it's not in list, exception when line executes). since sounds not know sure reader.value 1 of options in radiobuttonlist , need check first. if(radiobuttonlist.items.findbyvalue(reader.value) != null) { radiobuttonlist.selectedvalue = reader.value; } alternatively, handle exception via try/catch.

.net - Convert IObservable<Timestamped<T>> to IObservable<TimeInterval<T>> -

how can convert observable sequence of timestamped<t> sequence of timeinterval<t> where interval time between timestamps on original sequence? given input sequence.. new timestamped<int>(1, datetime.parse("2000-01-01 00:00:01")) new timestamped<int>(2, datetime.parse("2000-01-01 00:00:05")) new timestamped<int>(3, datetime.parse("2000-01-01 00:01:04")) .. output be: new timeinterval<int>(1, timespan.parse("00:00:00")) new timeinterval<int>(2, timespan.parse("00:00:04")) new timeinterval<int>(3, timespan.parse("00:00:59")) i think it. var s = source.publish().refcount(); var sprev = s.take(1).concat(s); var scurrent = s; var converted = observable.zip(sprev, scurrent, (prev, current) => new timeinterval<int>(current.value, current.timestamp - prev.timestamp)); the thing i'm not sure of if zip ends when either sequence ends. assume does...

storekit - Restore transaction doesn't download the content IAP IOS -

i have been struggling issue since 2 days. have implemented in app purchase downloadable content . whenever delete app , restore purchase , restore doesn't download content. if add download code in restoretransaction never calls finish transaction cause app behave weirdly(which resonable) , every time delete app , reinstall it. appreciated!! please let me know if needs further explanation. thanks!! - (void)paymentqueue:(skpaymentqueue *)queue updatedtransactions:(nsarray *)transactions { (skpaymenttransaction * transaction in transactions) { switch (transaction.transactionstate) { case skpaymenttransactionstatepurchased: if(transaction.downloads) [self download:transaction]; else [self completetransaction:transaction]; break; case skpaymenttransactionstatefailed: [self failedtransaction:transaction]; break; case skpaymenttransactionstateres...

sql - Is it possible to use a PG sequence on a per record label? -

does postgresql 9.2+ provide functionality make possible generate sequence namespaced particular value? example: .. | user_id | seq_id | body | ... ---------------------------------- - | 4 | 1 | "abc...." - | 4 | 2 | "def...." - | 5 | 1 | "ghi...." - | 5 | 2 | "xyz...." - | 5 | 3 | "123...." this useful generate custom urls user: domain.me/username_4/posts/1 domain.me/username_4/posts/2 domain.me/username_5/posts/1 domain.me/username_5/posts/2 domain.me/username_5/posts/3 i did not find in pg docs (regarding sequence , sequence functions) this. sub-queries in insert statement or custom pg functions other options? maybe answer little off-piste, consider partitioning data , giving each user own partitioned table posts . there's bit of overhead setup need triggers managing ddl statements partitions, result in each user having own tab...

c# - Is there a code-behind equivalent for TextBlock ScrollViewer.CanContentScroll="True" for DataGridTemplateColumn? -

for textblock in xaml, can following inside datatemplate: <textblock text="mytextblock text" verticalalignment="center" margin="0,0,5,0" scrollviewer.cancontentscroll="true" scrollviewer.horizontalscrollbarvisibility="visible"/> but when try set scrollviewer.horizonalscrollbarvisibility, doesn't seem anything. datatemplate textblocktemplate = new datatemplate(); frameworkelementfactory textblockelement = new frameworkelementfactory(typeof(textblock)); binding c1binding = new binding("mybindingvalue") { mode = bindingmode.twoway, updatesourcetrigger = updatesourcetrigger.propertychanged }; textblockelement.setbinding(textblock.textproperty, c1binding); textblockelement.setvalue(textblock.textwrappingproperty, textwrapping.wrap); textblockelement.setvalue(textblock.heightproperty, system.convert.todouble(23)); textblockelement.setvalue(scrollviewer.cancontentscrollproperty, true); textblockelement.setvalue(...

sql - View a message as it works through a BizTalk orchestration? -

i trying find out value getting dropped biztalk 2006 r2 progresses through orchestration. have been using health , testing utility , can see message ids move through, have hard time figuring out how them see values? i tried going sql , executing readmessage proc, returned empty values. any ideas how find specific message? you want use orchestration debugger tool , put break point in orchestration, run message through , find suspended orcherstration, , debug it.

sql - Select Statement based on user defined variable -

i trying simple select statement based on input of user (ssrs). help! select * table1 case when @x = 'yes' (select * table1 [column1] < 0) end; case when @x = 'no' (select * table1 [column1] > 0) end; thank in advance kj it should simple as select * table1 (@x = 'yes' , [column1] < 0) or (@x = 'no' , [column1] > 0); by way, select * bad coding, should specify each column returning.

java - Open Session in View vs @Transactional -

i had been using @transactional annotations in service layer. resolve error due lazy loading in view had use open session in view filter . after this, without use of @transaction session gets opened , transaction starts. mean @transactions not required? how transactions , roll-backs handled, in service layers? the javadoc explains it: this filter makes hibernate sessions available via current thread, autodetected transaction managers. suitable service layer transactions via hibernatetransactionmanager or jtatransactionmanager non-transactional execution (if configured appropriately). note: filter default not flush hibernate session, flush mode set flushmode.never. assumes used in combination service layer transactions care flushing: active transaction manager temporarily change flush mode flushmode.auto during read-write transaction, flush mode reset flushmode.never @ end of each transaction. if intend use filter without transactions, consider changing default...

Drag treeview item to canvas in silverlight -

in application, allow user drag item treeview canvas generate control dragged item. have tried use paneldragdroptarget that, canvas couldn't listen drop event. in xaml file: <toolkit:paneldragdroptarget allowdrop="true" drop="drop_event"> <canvas name="mycanvas" /> </toolkit:paneldragdroptarget> in xaml.cs file: void drop_event(object sender, dropeventargs e) { messagebox.show("dropped"); } what correct way that? many thanks. problem solved. i created class inherit dragdroptarget , wrap canvas in it. public class canvasdragdrop : dragdroptarget<panel, uielement> { //override methods if needed } in xaml file <canvasdragdrop allowdrop="true"> <canvas x:name="mycanvas" /> </canvasdragdrop>

c# - DbSet Object reference not set to an instance of an object -

i'm trying make universal 3-tier application generic repositories data provider/orm. rewrote code , got stuck on error of object reference not set instance of object while trying make action in dbset. i'm confused.. @ least nudge me in right direction. repository.cs public class repository<t> : irepository<t> t : class { public iunitofwork unitofwork { get; set; } private idbset<t> _objectset; private idbset<t> dbset { { return _objectset ?? (_objectset = unitofwork.context.set<t>()); } } public list<t> getall() { try { return dbset.tolist(); } catch (exception) { throw new exception("error in repository while attempts elements"); } } } efunitofwork.cs public class efunitofwork : iunitofwork { public efunitofwork() { context = new appcontext(); } public dbcontext context { get; set; } ...

search - Integrating Solr using PHP -

i wanted use solr in order enable learning management service package have search features. read , tried out official tutorial here: http://lucene.apache.org/solr/4_3_0/tutorial.html . , here: http://wiki.apache.org/solr/integratingsolr what should use: solphp or kophp however, couldn't think how integrate solr php package. what files have include in package , modifications need enable solr indexing , search? any help/post/relevant tutorial helpful. integration solarium php 1.download , install php web server(xampp) 2.set php path in envirement varibale(c:\xampp\php) 3.downlaod , install composer (change compatibilty if program crasshed ) 4.open file "c:\xampp\php\php.ini" , uncomment extension=php_curl.dll , extension=php_openssl.dll 5.when composer install succesfully(c:\programdata\composer\bin) there composer.phar file available or download composar.phar file 6.open command prompt , goto composer.phar file path ,create file name co...

Oracle ORDImage and EclipseLink || Hibernate -

i'm trying create orm eclipselink in java ee + oracledb application. problem don't know how map ordimage type database. tried use @struct without success. i created 2 @struct structures: @embeddable @struct(name = "ordsource", fields = {"localdata", "srctype", "srclocation", "srcname", "updatetime", "local"}) public class ordsourcestruct implements serializable { private static final long serialversionuid = 1l; @lob @basic @column(name = "localdata") private byte[] localdata; @column(name = "srctype") private string srctype; @column(name = "srclocation") private string srclocation; @column(name = "srcname") private string srcname; @column(name = "updatetime") @temporal(temporaltype.date) private date updatetime; @column(name = "local") private short slocal; //getters , sett...

sdk - Cognos connection pool -

i'm working java code creates custom connection pool of cognos connections. these connections time out. i've used jmeter script keep them timing out. best way this? thinking of adding spring task performs cognos contentmanagerservice_port in each connection in pool every 10 minutes or so, wasn't sure if that's best way this, or way this.

php - Creating nusoap object inside Magento Event Listener throws exception -

in magento 1.7.0.2, have created event listener triggers every time application checks final price of product (the final code not trigger on event, testing convenience, trying here). the event triggers fine , changes price accordingly, when try create nusoap object make non-wsdl calls external webservice, raises warning , not create client object. the code is: $endpoint = 'http://[ip]:155/[client_name]/[client_name].soap2'; try { $client = new nusoap_client($endpoint); } catch (exception $e) { echo $e->getmessage(); } and warning raised: warning: include(nusoap/client.php) [<a href="function.include">function.include</a>]: failed open stream: no such file or directory in /var/www/clients/client3/magento/lib/varien/autoload.php on line 93 the same code works fine if executed on magento root directory, able call correct webservice , parse response. i have included nusoap libraries (v. 0.9.5) in magent...

node.js - ExpressJS/Request - Make a POST request after GET -

i new node.js, bear me here. trying make post request after get. idea once user hits homepage, want redirect user salesforce , oauth dance. using expressjs , mikeal's request. code have far server.get('/', function(req, res){ var client_id = "xxx"; var client_secret = "xxx"; var redirect_uri = "https://192.168.233.105:8000/callback"; var grant_type = "authorization_code"; var remotereq = request.post('https://na1.salesforce.com/services/oauth2/token').form( {"client_id":client_id, "client_secret":client_secret, "redirect_uri":redirect_uri, "grant_type":grant_type, "immediate":'true' } ); //how expressjs res object use remotereq object? }); when hit home page, request hangs. thinking have somehow expressjs response object play nice mikeal/request object. how connect 2 together? you can pipe result of request.post directly res : remotereq.pipe...

c# - Event when user navigates away from a page asp.net -

this question has answer here: best way detect when user leaves web page? 6 answers when page loaded use page_load event set value 1. in asp.net using c# want set value null whenever user navigates away page. page_unload not because runs when page loaded itself. event should use? leaving page not require hit server there no way guarantee execution of c# code when user closes browser instance. you can use javascript onbeforeunload flash warning message user. how can customize message depends on browser using (spoiler alert: firefox won't let customize message). require user has javascript enabled. you might able rig javascript posts server onbeforeunload event, have play see if can working purposes.

c++ - How to declare and link to RoInitialize,RoUninitialize,RoGetActivationFactory and HSTRING Functions in Mingw Gcc -

updated: added roinitialize looks in roapi.h i in process of writing pure c++11 winrt library. not use wrl or c++/cx(obviously if want pure c++11). i got code compile , run on msvc, want see if can code compile , run on mingw gcc. using gcc 4.7.2 obtained nuwen.net. what need @ point way call windows api functions roinitialize rounitialize rogetactivationfactory , hstring functions windowscreatestring, windowsduplicatestring, windowsdeletestring. i tried compiling program in g++ got error extern "c"{ __declspec(dllimport)int __stdcall roinitialize(int); } int main(){ roinitialize(1); } i tried compile, got c:\users\jrb\desktop>g++ gccwinrt.cpp c:\users\jrb\appdata\local\temp\ccy7y1v9.o:gccwinrt.cpp:(.text+0x1e): undefined reference `_imp__roinitialize@4' collect2.exe: error: ld returned 1 exit status if can point me in right direction on how declare these functions , libraries need link to, appreciate it. if required loadlibrary/getprocaddress s...

android - GCM notification received but not displaying -

my android app , server have been configured receive , send push notifications. app receives notification , shows in logcat whether app open, in background or not running should. however, i'm having problem getting display. no matter do, can't show in notification center or come in alert vibrates phone or makes sound. what missing? i'm using gcm plugin here: https://github.com/marknutter/gcm-cordova i've tried getting send notification using notificationcompat, i've been unsuccessful. -->json gcm passed function... @override protected void onmessage(context context, intent intent) { log.d(tag, "onmessage - context: " + context); // extract payload message bundle extras = intent.getextras(); if (extras != null) { try { log.v(me + ":onmessage extras ", extras.getstring("message")); jsonobject json; json = new jsonobject().put("event", "mes...

PHP image output suddenly stopped working -

i have file manipulates images before output browser. here code: <?php require_once($_server["document_root"].'/_content/_constants.php'); require_once($_server["document_root"].'/_content/_functions.php'); function hex2rgb($hex) { $hex = str_replace("#", "", $hex); if(strlen($hex) == 3) { $r = hexdec(substr($hex,0,1).substr($hex,0,1)); $g = hexdec(substr($hex,1,1).substr($hex,1,1)); $b = hexdec(substr($hex,2,1).substr($hex,2,1)); } else { $r = hexdec(substr($hex,0,2)); $g = hexdec(substr($hex,2,2)); $b = hexdec(substr($hex,4,2)); } $rgb = array($r, $g, $b); //return implode(",", $rgb); // returns rgb values separated commas return $rgb; // returns array rgb values } /*-- hex color code url query --*/ $rgb = hex2rgb((isset($_get["color1"]) && $_get["color1"]...

java - How to Handle ArrayIndexOutOfBoundsException -

i getting -1 response . exception, how handle exception can avoid integer not match array . constants.friends[integer.parseint(custom.getfriendslist())] for instance if array holds 4 items. string[] mylist = {"one","two","three","four"}; if getting either -1 or value greater 3, how can handle them. arrayindexoutofboundsexception unchecked exception, meaning signals programming errors, opposed conditions outside program's control. these exceptions should prevented , rather handled. in specific instance, should check value before passing index array, this: int pos = integer.parseint(custom.getfriendslist()); if (pos < 0 || pos >= constants.friends.length) { // handle error , exit or re-read pos } // accessing friends[pos] safe now: string friend = constants.friends[pos];

javascript - jQuery Mobile data-role="header" click event not firing -

i have refresh button in header of jquery mobile app , click event not fire in browser (chrome). here code: html <div data-role="header" data-position="fixed"> <a id="#refresh_deals" data-role="button" data-inline="true" data-iconpos="notext" data-mini="true" data-icon="refresh"></a> <div data-role="fieldcontain" class="ui-title" data-inline="true"><input id="main_search" data-mini="true" type="search" /></div> <a id="map_btn" data-inline="true" data-mini="true" data-transition="slide" href="#gps_map">map</a> </div><!-- header --> javascript $(document).bind('pageinit', function() { $('#refresh_deals').on('click', function(){ console.log('refresh clicked') }); }); it...

oop - Using an object oriented approach in Ruby -

i have 2 classes, class a , class b . i've noticed share lot of same code. example: def viewable_by?(user) super || clinic.has_staff_member?(user) || user.system_admin? || self.person == user.person end i want minimize code duplicated between classes. in refactoring, i've found of doesn't fit neatly 1 class falls cleanly in single responsibility principle. want put single module, methods have time formatting, viewing permissions, , few other things. as see it, have few choices. (and bet can suggest others.) object oriented point of view, approach should go , why? use 1 single module shared between both of classes. may not have specific single responsibility, clean code significantly, , keeps in 1 place. make tiny classes , mix in both classes modules. have single responsibility, there many of them, of may have 1 method. seems waste. perhaps use presenter things time formatting, , permissions module shared between both classes. perhaps "cleaner,...

c - Why can I still access a member of a struct after the pointer to it is freed? -

if define structure... struct linknode { int node_val; struct linknode *next_node; }; and create pointer it... struct linknode *mynode = malloc(sizeof(struct linknode)); ...and free() it... free(mynode); ...i can still access 'next_node' member of structure. mynode->next_node my question this: which piece of underlying mechanics keeps track of fact block of memory supposed represent struct linknode? i'm newbie c, , expected after used free() on pointer linknode, no longer able access members of struct. expected sort of 'no longer available' warning. i love know more how underlying process works. the compiled program no longer has knowledge struct linkednode or field named next_node , or that. names gone compiled program. compiled program operates in terms of numerical values, can play roles of memory addresses, offsets, indices , on. in example, when read mynode->next_node in source code of program, compiled machine co...

.htaccess - What is L in [QSA, L] in htaccess -

qsa means if there's query string passed original url, appended rewrite (olle?p=1 rewritten index.php?url=olle&p=1. l means if rule matches, don't process more rewriterules below one. hi, easy examples explain use of l? can't seem grasp explanation above. highly appreciated. thanks. the qsa flag means append existing query string after uri has been rewritten. example: url= http://example.com/foo/bar?q=blah rule: rewriterule ^foo/(.*)$ /index.php?b=$1 result= /index.php?b=bar notice how q=blah gone. because existing query string dropped in favor of 1 in rule's target, (b=$1). if include qsa flag: rewriterule ^foo/(.*)$ /index.php?b=$1 [qsa] the result becomes= /index.php?b=bar&q=blah the l flag means stop applying rules follow. given same url, http://example.com/foo/bar?q=blah , , given rules: rewriterule ^foo - rewritecond %{request_uri} !^/bar.php rewriterule ^(.*)$ /bar.php?z=$1 the first rule gets a...

installation - Trying to run Code::Blocks on Ubuntu with wxWidgets -

i've installed cb (code::blocks) 10,05 , installed wxwidgets repos. trying compile , run blank form. not seem work. error: /usr/include/wx-2.8/wx/cursor.h error: ‘wxisbusy’ not declared in scope what i've tried far: installed libwxbase 2.8 lib , dev files restarted cb installed codeblocks-contrib i've tried solutions forums nothing seems work. error mentioned above. can please direct me towards fix? thanks! after trying many forums (on different sites), did 1 desperate install. went on software center , searched wxsmith. checked not installed. i believe trick in package: "dummy transitional package wxsmith development files" (libwxsmithlib0-dev). along package got installed. so, did not reinstall one(s) mentioned above in answer. restarted cb , compiled , run breeze!

sql server - IF function in Crystal Report -

is possible have substring/left , if function in crystal report? mean want first 2 characters of name_column if substring of name_column 'xo' new field in formula 1000 or if 'xd' 2000.. appreciated.. thank before nb: use vb.net , sqlserver // {@foobar} select left({table.name_column},2) case "xo": 1000 case "xd": 2000 default : -1

MySQL Arbitrary Ordering Of Group By -

i have sql query looks like select fruit, count(*) table1 group fruit it returns grape 8 apple 2 peach 9 orange 6 banana 5 i not wish sort alphabetically. i want in order banana apple orange peach grape i cant seem syntax right on case stamens.....help! you use field() function: select fruit, count(*) table1 group fruit order field(fruit, 'banana','apple','orange','peach','grape')

x86 - Hooking a _userpurge function c++ -

i want hook function x86 executeable. that's functions prototype decompiled hex-rays plugin ida: int __userpurge sub_43ce70<eax>(int a1<eax>, int a2, char a3, int a4, int a5, int a6) so function acception eax first parameter , returns same register. i tried following function wrapper: int the_wrapper(int a2, unsigned a3, int a4, int a5, int a6) { int a1; _asm { mov [a1], eax }; char bstring[50]; sprintf(bstring,"a1: %u, a2: %u, a3: %d, a4: %d, a5: %d, a6: %d",a1,a2,a3,a4,a5,a6); logs(bstring); int rtn; _asm{ push a6 push a5 push a4 push a3 push a2 mov eax, [a1] call the_function mov [rtn], eax }; return rtn; } for reason it's not working , crashed everytime function gets called. you need declare wrapper same calling convention function trying wrap. depending on convention (the common being cdecl , stdcall depends o...

ssms - How can I modify the default file name format for auto generated script files in SQL Server Management Studio? -

our database contains 600 stored procedures , functions. trying better manage changes database scripts without having purchase additional software. we use > tasks > generate scripts function in sql server management studio automatically generate individual files every stored procedure , function in database. this article pretty sums steps take achieve this: http://earljon.wordpress.com/2008/04/10/sql-server-2005-scripting-each-objects-to-a-separate-file/ the issue having default naming convention management studio uses file name. suffixes type of script end of file name dbo.name.storedprocedure.sql or dbo.name.userdefinedfunction.sql . want change file name sp_name.sql , fn_name.sql . is possible customize output file name format within sql server management studio? prefer wizard output file name convention, rather having use separate piece of software batch rename them. thanks, nick there's no setting control in ssms, options are: write script re...

mysql - ON DELETE CASCADE in this case? -

i need advice on whether on delete cascade suitable use in following table create table category ( id int not null auto_increment primary key, name varchar(255) not null, maincategory int default null, foreign key(maincategory) references category(id) on delete cascade on update cascade ) engine = innodb default charset = utf8; in case, on delete cascade delete sub categories if main category gets deleted.is recommended approach ? you trying create tabular representation of tree structure. using adjacency model, storing id of parent in maincategory field (usually called parent_id). yes, approach totally valid. using on delete cascade securing delete anomalies. i recommend read nested sets - efficient technique representing trees in sql: http://www.evanpetersen.com/item/nested-sets.html how represent data tree in sql? http://en.wikipedia.org/wiki/nested_set_model and book: joe celko "trees , hierarchies in sql smarties"

java - Dynamically add kendo grid inside panel of kendo panelbar in JSP -

i using kendo ui in java jsp application. i able load panel bar dynamically want insert grid 1 of panels when user clicks panel. got select/expand event catch action not sure how insert grid there. any suggestions or pointers appreciated. thanks! function createattendancepanel(){ $("#attendance-details").kendopanelbar({ expandmode: "multiple", select: selectattndpanel }); var attendancepanelbar = $("#attendance-details").kendopanelbar().data("kendopanelbar"); attendancepanelbar.append({text: "absence year", id:"item1"}, attendancepanelbar.select()); }; this function called when select particular element after page loaded. now when panel text "absence year" expanded or selected want add grid panel. thanks, here solution, in case 1 looking it: first append panel "content" has div element panelbar.append( { text: "<b>item 2...

sockets - Android - ObjectInputStream keeps on reading the previous value even with .reset() -

i'm building application sending files between 2 android phones, have listactivity retrieves sdcard , lists files, when listactivity first starts on 2 devices serversocket set , listening .accept() ... this thread starts when listactivity starts : receivefilesendrequestthread receivefilesendrequestthread = new receivefilesendrequestthread(); receivefilesendrequestthread.start(); and here full thread class: static public class receivefilesendrequestthread extends thread { public void run() { serversocket serversocket; try { serversocket = new serversocket(6789, 200); connectionserv = serversocket.accept(); requestfileinserver = new objectinputstream( connectionserv.getinputstream()); requestfilestring = (string) requestfileinserver.readobject(); handler.post(new acceptfilesendalertdialogrunnable()); while (oktosend == null) { } if (...

how to write ant script to check a given string is a file or directory -

how use write ant script check file file or directory??? given string "c:\test\application\services\test" i need know string "c:\test\application\services\test" is file or directory, i use following script check, looks cannot decide s file or directory <if> <available file="${sourcefile}" /> <then> <echo> file ${sourcefile}</echo> <copyfile src="${sourcefile}" dest="${targetfile}" /> <echo> single file copied: sourcefile = ${sourcefile}</echo> </then> <else> <if> <available file="${dir}" type="dir" /> <then> <echo> directory: ${sourcefile}</echo> <copy todir="${targetfile}"> <fileset dir="${sourcefile}" /> </copy> ...

c# - Exposing domain logic in webapi -

so in rest have product resource... http://api/product question if i've got domain logic? in object oriented world, might have public class product { int id; public product(){} public int calc(int first, int second) { return first + second; } } how represent business logic? assume can do... public int getcalc(int id, int first, int second) { localproduct = products[id]; return localproduct(first + second); } hence url of service become http://api/product/calc?id=1&first=1&second=2 or (alternatively) http://api/product/1/calc?first=1&second=2 this returns correct result.... i'm wondering if how should represent business business logic? or should doing different way or trying avoid altogether? i'd welcome ideas on how improve this... this depends on system build. take time think how evolve on time, quite hard refactor. general direction heading looks good. this api call ...

sql - Query to get a city by a truckload of possible parameters -

while testing search engine, realised not pretty awfull, didn't work lot of combinations user input. i have search field user can input wants. region, city name, zipcode or country or combinations of in no predetermined order or predetermined separator. this quite difficult find cities correspond user wants because of big number of possible combinations user enter in field. what more difficult lot of cities have article in name or composed name, article or words user or couldn't enter. example, since i'm french, i'll use example of city called: la rochelle. the user search la rochelle, rochelle or la-rochelle city's name. if wants more precise, add zip-code after, or before, or country or both... i can't find how optimize search city random user input. there conventional ways ? the table containing cities follow: create table cities ( id int primary key, article text, - contain article if there's one, or null if not city_name te...