Posts

Showing posts from May, 2015

javascript - Hide Confirm Form Resubmission PHP -

after submit form, , click button, page displays confirm form resubmission page. instead of that, want browser display form itself. there way that? here part of code below, , works except not stop refreshing. want refresh once when click button. <meta http-equiv="refresh" content="0"> <form method = 'post' action = 'submitpost.php?section=$section'> <textarea rows='10' cols='100' name = 'post'></textarea> </br> <input type = 'submit' value = 'submit'> </form> this browser security policy - when want go page loaded using post http verb ask confirmation.

C++ Converting a text file list with numbers and words into an integer 2D array -

i have basic text file has 1 entry per line, entries are numerical, there few lines word , (evenly spaced) in them. here example of 1 such spacing between , : <event> 4 0 0.1005960e+03 0.2722592e+03 0.7546771e-02 0.1099994e+00 21 -1 0 0 501 502 0.00000000000e+00 0.00000000000e+00 0.17700026409e+03 0.17700026409e+03 0.00000000000e+00 0. -1. 21 -1 0 0 502 503 0.00000000000e+00 0.00000000000e+00 -0.45779372796e+03 0.45779372796e+03 0.00000000000e+00 0. 1. 6 1 1 2 501 0 -0.13244216743e+03 -0.16326397666e+03 -0.47746002227e+02 0.27641406353e+03 0.17300000000e+03 0. -1. -6 1 1 2 0 503 0.13244216743e+03 0.16326397666e+03 -0.23304746164e+03 0.35837992852e+03 0.17300000000e+03 0. 1. </event> what need create numerical matrix (using numerical values) each column holds data values between each separate instance of , . this have far: using namespace std; int main() { vector <string> data; string str; ifstream fin("final_small.txt"); while

sql - Concatrelated with two parameters -

i trying use allen browne's concatrelated function in database city council ordinances. have 1 working properly, 1 in unbound field should produce string of councilor names of voted yes. has 2 parameters , keeps returning 3601 error, few parameters. votes tallied 'y' or 'n'. need sister string 'n' =concatrelated("[lname]","[qryvotetally2]","co2_idfk =" & [co2_id] & " , " & "vote = 'y'") the underlying sql is select mmvotes.co_id2fk, mmvotes.vote, tblsponsors.lname mmvotes left join tblsponsors on mmvotes.counc_id = tblsponsors.spon_id the query works on own. why?

javascript - Can I catch an error from async without using await? -

Image
can errors non-awaited async call caught, sent original encapsulating try/catch, or raise uncaught exception? here's example of mean: async function fn1() { console.log('executing fn1'); } async function fn2() { console.log('executing fn2'); throw new error('from fn2'); } async function test() { try { await fn1(); fn2(); } catch(e) { console.log('caught error inside test:', e); } } test(); in scenario, error thrown fn2 swallowed silently, , not caught original try/catch . believe expected behavior, since fn2 being shoved off event loop finish @ point in future, , test doesn't care when finishes (which intentional). is there way ensure errors not accidentally swallowed structure this, short of putting try/catch internal fn2 , doing emitting error? settle uncaught error without knowing how catch it, think -- don't expect thrown errors typical program flow writing, swallowin

php - Add data attribute to wp_nav_menu -

i have following code: $nav_menu_args = array('fallback_cb' => '','menu' => 'menu', 'menu_class' => 'menu_class'); $x = wp_nav_menu( apply_filters( 'widget_nav_menu_args', $nav_menu_args, 'menu', $args ) ); $pattern = '#<ul([^>]*)>#i'; $replacement = '<ul$1 data-attr="abc">'; // wrong echo preg_replace( $pattern, $replacement, $x ); i trying add data-attr ul altering pattern, , without making changes through walker_nav_menu . what want have list this: <ul class="menu_class" data-attr="abc"> <li><li> <li> <ul> <li></li> </ul> <li> </ul> but data-attr on inner ul this. <ul class="menu_class" data-attr="abc"> <li><li> <li> <ul data-attr="abc"> <li></li> </ul>

Run time error 462 Access VBA using Excel -

i run time error when trying open/manipulate excel files using access vba. error "run-time error '462': remote server machine not exist or unavailable what frustrating error occurs files , not others , in different instances. here code, error occurs @ workbooks.open(spath) line: docmd.setwarnings false dim oexcel new excel.application dim owb workbook dim ows worksheet set oexcel = excel.application set owb = oexcel.workbooks.open(spath) set ows = owb.sheets(1) oexcel.visible = false if fgetfilename(spath) = "file_name1.xlsx" 'oexcel.visible = false ows.range("aw1").value = "text1" ows.range("ax1").value = "text2" ows.range("ay1").value = "text3" end if owb.save debug.print "amended " & spath owb.close false set owb = nothing oexcel.quit set oexcel = nothing docmd.setwarnings true after bit of research online, i'

mysql - Can't see PHPMYADMIN Control Panel -

i have problem phpmyadmin. i'm trying create database on local mac see when i'm inside phpmyadmin: http://i.imgur.com/u7hhgwh.png . as can see there no control panel. seems i'm not admin of phpmyadmin or maybe i'm guest.. this config file of database: <?php /* * generated configuration file * generated by: phpmyadmin 4.4.8 setup script * date: thu, 04 jun 2015 15:01:24 +0000 */ /* servers configuration */ $i = 1; /* server: localhost [1] */ $i++; $cfg['servers'][$i]['verbose'] = ''; $cfg['servers'][$i]['host'] = 'localhost'; $cfg['servers'][$i]['port'] = ''; $cfg['servers'][$i]['socket'] = ''; $cfg['servers'][$i]['connect_type'] = 'tcp'; $cfg['servers'][$i]['auth_type'] = 'cookie'; $cfg['servers'][$i]['user'] = 'root'; $cfg['servers'][$i]['password'] = ''; /* en

php - CakePHP Model::create and Model::save() performance in loop -

i @ cakephp 2.3.4 , php 5.5 mysql running on ubuntu server. have loop this: foreach($notification_group['user'] $notification_user) { // $this->set($notification); $this->notification->create(); $this->notification->save($notification); // 0.4 seconds per iteration } // same $this->set($notification); $this->notification->create(); $this->notification->save($notification); // less 0.1 seconds in loop, each iteration take 0.4 seconds complete. create , save method outside loop take (way) less 0.1 seconds finish. loop overhead should not problem. why takes longer basic insert in loop? how improve it? thanks! update 1: have tried comment out create , save methods in loop , turns out loop doesn't have overhead @ all. know why performance hit happening before try savemany() or other methods. update 2: have tried savemany() save array of notification in single shot. here code snippet: $notification_array = array();

Google Universal Analytics - track multiple events on a single link click -

google suggests track outbound links : ga('send', 'event', 'outbound', 'click', url, { 'hitcallback': function () { document.location = url; } }); it uses "hitcallback" redirect user page once event has been tracked. what syntax tracking multiple events per click? i'd prefer not write code this: ga('send', 'event', 'outbound', 'click', url, { 'hitcallback': function () { ga('send', 'event', 'foo', 'click', url, { 'hitcallback': function () { ga('send', 'event', 'bar', 'click', url, { 'hitcallback': function () { document.location = url; } }); } }); } }); any solution needs support ie7+ , have no library dependencies. i think there

Prompt download of external url from php script -

so right use below code , if external file 100mb takes forever download prompted.how can prompt download , start streaming download users. <?php header( 'content-type: application/x-bittorrent' ); header( 'content-disposition: attachment; filename="torrent' ); echo file_get_contents("http://externallink.com/sizemorethan100mb"); ?> edit : not duplicate , duplicated question not provide solution external url.

inheritance - Why can't class be destructed in polymorphism C++ -

i have problem using polymorphism. code here: class { public: a() {cout << "construct a" << endl;} virtual ~a() {cout << "destroy a" << endl;} }; class b : public a{ public: b() {cout << "construct b" << endl;} ~b() {cout << "destroy b" << endl;} }; void main() { *p = new b; } the result is: construct construct b why 'p' can not destroyed or may wrong somewhere. thanks. you need invoke delete p; to delete pointer , call destructor. dynamically allocated objects not have destructor called automatically, that's why need invoke delete operator, first invokes destructor calls operator delete release memory.

excel - Access the interior color of a cell style from VBA? -

my workbook has cell style called "normal formula". possible access interior color of cell style vba? i've tried: rcell.interior.color = activedocument.styles("normal formula").interior.color but vbe gives me object required error. the code found msdn word. when replaced activedocument thisworkbook, code worked. rcell.interior.color = thisworkbook.styles("normal formula").interior.color

c# - Flow context/state through generated continuations -

first, context (pardon pun). consider following 2 async methods: public async task async1() { prework(); await async2(); postwork(); } public async task async2() { await async3(); } thanks async , await keywords, creates illusion of nice simple call stack: async1 prework async2 async3 postwork but, if understand correctly, in generated code call postwork tacked on continuation async2 task, @ runtime flow of execution more this: async1 prework async2 async3 postwork (and it's more complicated that, because in reality use of async , await causes compiler generate state machines each async method, might able ignore detail question) now, my question : there way flow sort of context through these auto-generated continuations, such time hit postwork , have accumulated state async1 , async2 ? i can similar want tools asynclocal , callcontext.logicalsetdata , aren't quite need because contexts "rolled back" work w

PHP Sort Array (Chatlog) by date (keep order of equivalent dates) -

i have chatlog composed of date , actual entry after 2 spaces. need sort time of entry, keep order of entries same when dates equivalent. array ( [0] => '6/4 17:01:30.001 x' [1] => '6/4 17:01:30.003 b' [2] => '6/4 17:01:30.003 c' [3] => '6/4 17:01:30.003 a' [4] => '6/4 17:01:30.002 y' ) i tried couple of things, creating multidimensional array splitted in dates values sorting couple of different algorithms i'm pretty sure there must easy, , obvious way without multiple loops. the result should this: array ( [0] => '6/4 17:01:30.001 x' [4] => '6/4 17:01:30.002 y' [1] => '6/4 17:01:30.003 b' [2] => '6/4 17:01:30.003 c' [3] => '6/4 17:01:30.003 a' ) we can take advantage of fact date string sort in correct order. use key , ksort: // starting array $aarray = array( '6/4 17:01:30.001 x', &#

How to Import Github non Android Studio Project as library into Android Studio? -

Image
i trying import standout library github project library in project.what tried below: created folder in root project directory named 'libs' copied complete folder 'library' of standout project on git 'libs' renamed folder 'library' copied e.g. "standout" (just avoid confusion) now added library in settings.gradle following command: include ':libs:standout' going build.gradle file of appproject , added following line 'dependencies': compile project(':libs:standout') but got error , added compile filetree(dir: 'libs', include: ['standout']) gradle sync successful there red mark on src files of library project. . i couldn't access library src files mainactivity of project.as github project wasn't android studio project need that? i have tried below way suggested wesley: download or clone git repository, copy library folder project root folder. then in proj

How to open and read "/proc/cpuinfo" on Android device in Delphi -

could advise me how open , read " /proc/cpuinfo " on android device in delphi ? original code: var i: integer; fs: tfilestream; lbuffer: tbytes; begin if fileexists('/proc/cpuinfo') begin fs:= tfilestream.create('/proc/cpuinfo', fmopenread); try setlength(lbuffer, fs.size); fs.readbuffer(pointer(lbuffer)^, length(lbuffer)); i:= 0 length(lbuffer) - 1 memo1.lines.add(lbuffer[i]); fs.free; end; end; end; the problem size of fs -1 , therefore not read ... the answer simple (tested): var fs: tfilestream; ch: char; rawline: system.unicodestring; begin if fileexists('/proc/cpuinfo') begin try rawline:= ''; ch := #0; fs:= tfilestream.create('/proc/cpuinfo', fmopenread); while (fs.read( ch, 1) = 1) , (ch <> #13) begin rawline := rawline + ch end; m

android - TransitionDrawable not working inside custom view's onDraw -

i trying start transitiondrawable starttransition() method inside ontouchevent() of custom view. shows first image in xml file. works on imageview 's setdrawable() method. combining these 2 possible or there other alternative show similar transition in custom view. transition.xml: <?xml version="1.0" encoding="utf-8"?> <transition xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/ic_icon_lock"/> // image shown <item android:drawable="@drawable/ic_icon_unlock"/> </transition> initializer: mlocktransitionaldrawable = (transitiondrawable) resourcescompat.getdrawable(mresources, r.drawable.transition, mcontext.gettheme()); ondraw() custom view: mlocktransitionaldrawable.setbounds(mlockrect); mlocktransitionaldrawable.draw(canvas); fired when action down happens inside rectangle(mlockrect) containing drawable: mlocktra

go - Does runtime.LockOSThread allow child goroutines to run in same OS thread? -

i understand in go, runtime.lockosthread() bind goroutine 1 os thread , not allow other goroutines execute in thread. true child goroutines? for example: runtime.lockosthread() go func() { go func() { // }() // }() do both of these goroutines execute in single , exclusive os thread or first one? the documentation runtime.lockosthread says: lockosthread wires the calling goroutine current operating system thread. until calling goroutine exits or calls unlockosthread, execute in thread, and no other goroutine can . (emphasis mine) this means if implementation of go did you're asking, faulty. to clarify: if goroutine had reserved thread , goroutine executed on same thread; that's wrong.

jsf - How can I selectall visible rows in an icefaces ace:datatable? -

it doesn't ace:datatable component has selectall/deselectall functionality...unless shift+click on table directly. i don't want perform ajax submit , modify rowstatemap because: a) i'd rather not submits until form submission b) rowstatemap.setallselected() selects rows in table regardless of visibility. any ideas? perhaps can help. datatable.js file icefaces has method: ice.ace.datatable.prototype.domultirowselectionevent = function (lastindex, current) i tried running directly: <h:commandbutton value="select all" onclick="ice.ace.datatable.prototype.domultirowselectionevent(0, ice.ace.jq('.ui-datatable-data').children().last()); return false;"/> but didn't seem work. so created function "doselectallrows" copy of "domultirowselectionevent" has following changes: ice.ace.datatable.prototype.doselectallrows = function () { var self = this,

html - "linear-gradient" not working in IE9 and Safari -

i try apply style button style displays on mozilla , chrome not case safari , ie9. here css class: #bt_d{ width:130px; height:30px; box-shadow:1px 2px 4px rgba(0,0,0,0.60); font-size:12px; background-image:linear-gradient(60deg, rgb(231,110,49), rgb(231,171,49)); border:1px solid rgb(180,180,180); border-radius:5px; float:right; text-align:center; vertical-align:middle; } but when inspect button , find in quoted of property linear-gradient yellow exclamation mark indicates property not recognized browser (safari or ie9) any idea solve issue? for safari, have put additional, so-called "vendor-prefixed" version of definition: background-image: -webkit-linear-gradient(60deg, rgb(231,110,49), rgb(231,171,49)); for ie9 (which has no support css gradients) must use image fallback, either png/gif/jpg, or better svg. here 1 of many gradient generators creates svg want: http://www.colorzilla.com/gradient-editor/

multithreading - Object vs Thread object Python -

i coding gui in python , pyqt , parts of logic needs executed in specific time intervals measured in ms. think running parts threads , keep track of time best please correct me if wrong. second question, can use threads classic objects , use them in same way? call methods or use them specific task , keep them simple possible? because thread nature tempted write run() method procedure , somehow lacking oop approach. thanks 1st part: if timed part of code rather computation heavy in qthread - if not there no need make things complicated. as said x3al in comment, there no obvious reason why should not able timing using qtimer. if need repeating signal can use setinterval . if single signal after x ms can use singleshot ( pyqt4-doc ). 2nd part: if part correctly asking advice on how use threads - depends on implementation (movetothread vs subclassing), have @ answers background thread qthread in pyqt allow me recycle example used before on matter: class thr

javascript - How do I properly restrict a .on('click tap') event from triggering more than once per click? -

i'm developing application on phonegap screen has cancel button. the cancel button needs have click/tap event listener cancels form submission , returns previous page on application. the application needs compatible both mobile devices (such tablets) , modern day browsers. why listen both click events tap events. this how have event listener defined... $(cancel_button).on('click tap', function(event) { // assumed following line fix issue, doesn't. event.stopimmediatepropagation(); goback(); alert("your submission has been cancelled."); }); so when click cancel button on browser runs code inside listener 6 times. have idea on how solve this? maybe try $(cancel_button).on('click touchend', function(event) { event.preventdefault(); goback(); alert("your submission has been cancelled."); });

visual studio - C++ Get country code -

i'm trying country code (example: "uk" or "si" or "ger") via getgeoinfo(). geoid getusergeoid(geoclass_nation); currently getting value 16 above function ^ looking in table there's no number 16. https://msdn.microsoft.com/en-us/library/windows/desktop/dd374073(v=vs.85).aspx i know it's 3-4 lines of code can't seem figure out on own. appriciated. edit: geoid mygeo = getusergeoid(geoclass_nation); int sizeofbuffer = getgeoinfo(mygeo, geo_iso2, null, 0, 0); wchar *buffer = new wchar[sizeofbuffer]; int result = getgeoinfo(mygeo, geo_iso2, buffer, sizeofbuffer, 0); got display country number don't know how i'd transform iso code. to country iso: geoid mygeo = getusergeoid(geoclass_nation); int sizeofbuffer = getgeoinfo(mygeo, geo_iso2, null, 0, 0); wchar *buffer = new wchar[sizeofbuffer]; int result = getgeoinfo(mygeo, geo_iso2, buffer, sizeofbuffer, 0); wcout<<buffer; thanks @christophe , @thomas

javascript - show validation message after user enters invalid value and focused out and then on keyup,using knockout validation -

i using knockout validation validate data before updating in db. not familiar knockout validation. "valueupdate" in data-bind input box "afterkeydown", which, each time giving invalid value message coming up. want show message after user first time focused out input box. after want show message on key up. if can set valueupdate after focus out view model, may help. since having other bindings in data-bind, can't add data-bind attribute vm. checked this link . any idea how this? your fiddle example using knockout 2.3. if use knockout 3+ can use textinput binding. the textinput binding links text box () or text area () viewmodel property, providing two-way updates between viewmodel property , element’s value. unlike value binding, textinput provides instant updates dom types of user input, including autocomplete, drag-and-drop, , clipboard events. so instead of: <input data-bind='value: emailaddress,valueupdate:"keyup"&#

c# - ImmutableHashSet .Contains returns false -

i have list (to precise immutablehashset<listitem> system.collections.immutable) of base items , try call following code _baselist.contains(deriveditem) but returns false . even though following code lines return true object.referenceequals(_baselist.first(), deriveditem) object.equals(_baselist.first(), deriveditem) _baselist.first().gethashcode() == deriveditem.gethashcode() i can write following , returns true: _baselist.oftype<derivedclass>().contains(deriveditem) what doing wrong, avoid writing .oftype stuff. edit: private immutablehashset<baseclass> _baselist; public class baseclass { } public class derivedclass : baseclass { } public void dostuff() { var items = _baselist.oftype<derivedclass>().tolist(); foreach (var deriveditem in items) { removeitem(deriveditem); } } public void removeitem(baseclass deriveditem) { if (_baselist.contains(deriveditem)) { //doesn't reach place, since

shell - Jenkins job setup automation with SVN credentials -

Image
i created deploy script virtual machine (ubuntu). script installs svn, jenkins, etc, created job in jenkins using curl post request , uploaded config.xml (this file contains job details). couldn't set svn credentials script. succeeded using web interface, manually. tell me how it? have url, username , password svn server. on existing jenkins server, create credentials svn server: these credentials stored in $jenkins_home/credentials.xml file. you can copy file on vm script. regarding job, have use relevant credentials in svn section:

swift - Applying two consecutive transformations on a UIView -

how can apply scale , rotation transformation view? when use code below, last transformation applied. testv.transform = cgaffinetransformrotate(view.transform, keeprotation) testv.transform = cgaffinetransformscale(view.transform, keepscale, keepscale) got work this: var transformation1 = cgaffinetransformrotate(view.transform, keeprotation) var transformation2 = cgaffinetransformscale(view.transform, keepscale, keepscale) testv.transform = cgaffinetransformconcat(transformation1, transformation2)

OOP class design in C++ -

i have simple question class design in c++. lets assume have following class: class database { public: database(); void addentry(const std::string& key, double value); double getentry(const std::string& key); protected: std::map<std::string, double> table; }; there class holds pointer instance of database class: class someclass { protected: database *somedatabase; }; here confused, 2 options come mind: each instance of someclass have database of own. in sense data added instance present in database (dedicated databases). each instance of someclass referring central database. data added of instances of someclass in 1 single database (a global database). question: what name of aforementioned concepts in oop? how each of aforementioned approaches can achieved in c++ what looking topic of ownership in c++. when ownership, mean responsible managing memory holds object. in first exam

ios - Getting images from the XML Links -

http://www.cinejosh.com/news/3/40889/high-court-dismisses-andhra-poris-case.html in above link have tag <img src="/newsimg/newsmainimg/1433410900_andhra-pori.jpg" alt="high court dismisses 'andhra pori's case" class="img-responsive center-block visible-xs"> i have above tag , need image on imageview. my code this nsstring *gossipsxpathquerystring = @"//td//img"; //imagegossipsnodes array data imagegossipsnodes = [gossipsparser searchwithxpathquery:gossipsxpathquerystring]; (tfhppleelement *element in imagegossipsnodes) { nsstring *imageurlstring = [nsstring stringwithformat:@"http://www.cinejosh.com%@", [element objectforkey:@"src"]]; } now want pass string getting images.how achieve this?please me. thanks you have 2 options synchronous , asynchronous options. try use async methods. uiimage *image = [uiimage imagewithcontentsofurl:[nsurl urlwithstring:imageurlstring]

Best practices of deploying Spring Extjs webapp -

i'm working on project involving spring boot creating rest webservice , extjs 5 front end, frontend , backend developped independentely, i've managed avoid cors problems, know best practices concerning deployment in case. keep backend independent of frontend packaging frontend in own .war , backend, there problems in following practice. you can avoid cors problem if deploy front-end , back-end same domain different context (domain.com/front, domain.com/back). in other case need cors, please take @ last release spring boot 1.3.m1: https://spring.io/blog/2015/06/12/spring-boot-1-3-0-m1-available-now the released spring framework 4.2 rc1 provides first class support cors out-of-the-box, giving easier , more powerful way configure typical filter based solutions. source post: https://spring.io/blog/2015/06/08/cors-support-in-spring-framework

No output in word count program in C -

i new learner of c language. got know getchar() function. wrote program count number of words in input. program goes follows: (i using codeblocks): #include <stdio.h> main(){ int c, nw; /*nw stands number of words*/ while((c=getchar())!=eof){ if (c==' '||c=='\t'||c=='\n') ++nw; } printf("number of words are:%d",nw); } when run program, takes input, there no output. keeps on taking input no matter how many times press enter. i tried search million times couldn't find answer. however, told me include ctrl+d break in while loop. tried same result. please if has solution me. past 2 weeks trying figure out problem. thanks! your loop end when encounters eof (-1). it keeps on taking input no matter how many times press enter. because '\n' != eof . to stimulate eof , press ctrl+z if using windows/dos. must followed enter press ctrl+d if on unix/linux/osx. flushes stdin there cha

php - Restrict route access to non-admin users -

goal i'm trying create admin route restriction log-in users. i've tried check see if user log-in , , if user type admin , , if are, want allow them access admin route, otherwise, respond 404. routes.php <!-- route group --> $router->group(['middleware' => 'auth'], function() { <!-- no restriction --> route::get('dashboard','welcomecontroller@index'); <!-- admin --> if(auth::check()){ if ( auth::user()->type == "admin" ){ //report route::get('report','reportcontroller@index'); route::get('report/create', array('as'=>'report.create', 'uses'=>'reportcontroller@create')); route::post('report/store','reportcontroller@store'); route::get('report/{id}', array('before' =>'profile', 'uses'=>'reportcontr

javascript - Why does $.each show only one of my Mustache templates? -

i'm using $.get inside $.each call external mustache template use on each photo object in array. here code: $.when.apply($, requests).then(function(dataone, datatwo) { $.each(dataone, function(idx, obj) { $.get("mytemplate.mst", function(template) { var rendered = mustache.render(template, obj); $photoelem.html(rendered); }); }); }); my problem once refresh screen, 1 of array objects shows up. i'm aware of {{#item}} iterate through array i'm using $.each specific reason. can tell me i'm doing wrong? try one $.when.apply($, requests).then(function(dataone, datatwo) { $.get("mytemplate.mst", function(template) { $.each(dataone, function(idx, obj) { var rendered = mustache.render(template, obj); $photoelem.append(rendered); }); }); }); suppose problem causes replace content of $photoelem ( using .html() ) instead of ap

c# - jpeg to byte array, while conversion logic is inside if statement -

i'm sure simple issue inexperienced developers able do, i'm starting out. i've put if statement round logic convert jpeg byte array conversion doesn't happen unless there file selected. makes variable logobytes invisible data parameter. colleague told me have put logic conversion method, , reference method somewhere, i'm still rather confused. protected void btnsubmit_click(object sender, eventargs e) { div1.visible = true; if (logoprvw.value != null) { system.drawing.image img = system.drawing.image.fromfile(logoprvw.value); byte[] logobytes; using (memorystream ms = new memorystream()) { img.save(ms, system.drawing.imaging.imageformat.jpeg); logobytes = ms.toarray(); } } templatedata data = new templatedata(txtschemecode.text, txtversion.text, txtcomment.text, txttemplateid.text, logobytes); if (ddschemecode.selectedindex == 0) { lblcreated.visi

git - Capistrano unable to pull a Stash repository using SSH -

i followed following procedure: created ssh key; enabled ssh in atlassian stash; added ssh key stash account called capistrano (already used capistrano connect using username , password stash) tested ssh connection using command git clone ssh://git@stash.domain.com:7999/project/repository.git , repository cloned; changed following line config/deploy.rb in capistrano project directory: set :repo_url, 'ssh://git@stash.domain.com:7999/project/repository.git' the problem executing command cap production git:check following error lines , deployment cancelled: info [8b21e06e] running /usr/bin/env mkdir -p /tmp/capistrano_project_name/ deploy@host.domain.com debug [8b21e06e] command: /usr/bin/env mkdir -p /tmp/capistrano_project_name/ info [8b21e06e] finished in 0.292 seconds exit status 0 (successful). debug uploading /tmp/capistrano_project_name/git-ssh.sh 0.0% info uploading /tmp/capistrano_project_name/git-ssh.sh 100.0% info [376577ce] running /usr/bin/env chmod

Difference between MATLAB hough and my implementation -

i trying recreate matlab's hough function mine. code follows function [h,t,r] = my_hough(x,dr,dtheta) rows = size(x,1); cols = size(x,2); d = sqrt((rows - 1)^2 + (cols - 1)^2); nr = 2*(ceil(d/dr)) + 1; diagonal = dr*ceil(d/dr); r = -diagonal:dr:diagonal; t = -90:dtheta:90-dtheta; ntheta = length(t); h = zeros(nr,ntheta); = 1:ntheta n1 = 1:rows n2 = 1:cols if x(n1,n2)==1 r = n2*cos(t(i)*pi/180) + n1*sin(t(i)*pi/180); [~,j] = min(abs(r-ones(1,nr)*r)); h(j,i) = h(j,i) + 1; end end end end end where dr , dtheta distance , angle resolution. printing difference between hough table , matlab's there many zeros, there non-zero elements. idea why happening? well, silly mistake... r = n2*cos(t(i)*pi/180) + n1*sin(t(i)*pi/180); must be r = (n2-1)*cos(t(i)*pi/180) + (n1-1)*sin(t(i)*pi/180)

Understand EXPLAIN in a mysql query -

i trying interpret explain of mysql in query(written in 2 different ways),this table: create table text_mess( datamess timestamp(3) default 0, sender bigint , recipient bigint , roger boolean, msg char(255), foreign key(recipient) references users (tel) on delete cascade on update cascade, primary key(datamess,sender) ) engine = innodb this first type of query : explain select /*!straight_join*/datamess, sender,recipient,roger,msg text_mess join (select max(datamess)as dmess text_mess roger = true group sender,recipient) max on text_mess.datamess=max.dmess ; and second: explain select /*!straight_join*/datamess, sender,recipient,roger,msg (select max(datamess)as dmess text_mess roger = true group sender,recipient) max

rest - Why is my spring boot stateless filter being called twice? -

i'm trying implement stateless token-based authentication on rest api i've developed using spring boot. idea client includes jwt token request, , filter extracts request, , sets securitycontext relevant authentication object based on contents of token. request routed normal, , secured using @preauthorize on mapped method. my security config follows : @configuration @enablewebsecurity @enableglobalmethodsecurity(prepostenabled = true) public class securityconfig extends websecurityconfigureradapter { @autowired private jwttokenauthenticationservice authenticationservice; @override protected void configure(httpsecurity http) throws exception { http .csrf().disable() .headers().addheaderwriter(new xframeoptionsheaderwriter(xframeoptionsmode.sameorigin)) .and() .authorizerequests() .antmatchers("/auth/**").permitall() .antmatchers("/api/**").authenticated() .and() .addfilte

scala - Akka router's routees sends Terminate message to itself -

i have actor creates router. when work done want stop current actor, stop router , routees. this code stop hierarchy: // stopping children context.children foreach context.stop // stopping current actor context.stop(self) but in log i'm getting messages this: message [akka.dispatch.sysmsg.terminate] ... ... not delivered. [5] dead letters encountered. i.e. routees sends terminate message itslef. i think problem related code stopping actors (above). how can fix it? when stop self, children stopped automatically. use context stop self .

java - Calculate variable String(010) with integer(1) where outcome is string(011) -

the user can insert random string can contains numbers. must been possible calculate integer. the problem user insert string 010 + integer(1) result in 11; but want return string 011 but user can enter numbers 001, 0001, etc what best approach here? have try use string.format("%05d", yournumber); not work variable strings i came across string str = "abcd1234"; string[] part = str.split("(?<=\\d)(?=\\d)"); system.out.println(part[0]); system.out.println(part[1]); if use got new problem. how split number in right way. any idea i'm missing considering handling integer number (not binary ) try this: string input ="001";//your user input /** * check here if input number */ int len=input.length(); int inputinteger=integer.parseint(input); inputinteger+=1; string output=string.format("%0"+len+"d", inputinteger); system.out.println(output);

sql - how to insert records from one table to another selecting only the common columns -

i want insert records 1 table common columns desc fp_mast null? type emp_id not null varchar2(4) emp_nm not null varchar2(35) typ not null varchar2(1) flag not null varchar2(1) st_dt not null date end_dt date wk_dt not null date desc emp_mast null? type emp_id not null varchar2(4) emp_nm not null varchar2(35) grd_cd not null varchar2(3) desg_cd not null varchar2(2) cost_sl not null varchar2(2) flag not null varchar2(1) join_dt not null date resig_dt date wk_dt not null date i tried query insert records did not work insert fp_mast(emp_id,emp_nm,st_dt,end_dt,wk_dt) select(emp_no,emp_nm,join_dt,resig_dt,wk_dt) emp_mast emp_id in ('7996','7942','5251','

ios - Get touch location on map -

Image
i using following code find latitude , longitude of touch location on map- -(void)handlepressrecognizer:(uigesturerecognizer *)gesturerecognizer { (pointannotation *ann in [mmapview annotations]) { if ([ann iskindofclass:[pointannotation class]]) { [mmapview removeannotation:ann]; } } [mmapview removeannotations:[mmapview annotations]]; cgpoint touchpoint = [gesturerecognizer locationinview:mmapview]; cllocationcoordinate2d touchmapcoordinate = [mmapview convertpoint:touchpoint tocoordinatefromview:gesturerecognizer.view]; if (gpslocation != nil) { gpslocation = nil; } gpslocation = [[cllocation alloc]initwithlatitude:touchmapcoordinate.latitude longitude:touchmapcoordinate.longitude]; [self performselector:@selector(showloadingview) withobject:nil afterdelay:0.001]; [self performselector:@selector(getgoogleaddressfromlocation:) withobject:gpslocation afterdelay:0.1]; } and passing these lat/long

javascript - Get elements 'tag name' by searching Class name -

i'm trying element tag name associated element class name. i know can these 2 lines of code class name , tag name. document.getelementsbytagname("regeneratepostnatal"); document.getelementsbyclassname(returnedpatientid); i'm asking if there way of doing below tag name belongs element class name? document.getelementsbyclassname(returnedpatientid).tagname example var element = document.getelementsbyclassname("oneid")[0].tagname; document.getelementbyid("returnedvalue").innerhtml = element; var element2 = document.getelementsbyclassname("oneid")[0].nodename; document.getelementbyid("returned2value").innerhtml = element2; <a class="oneid" name='regeneratepostnatal'>click</a> <div id="returnedvalue"></div> <div id="returned2value"></div> i'm trying name attribute value it'll show "regeneratepostnatal"

pdo - Equal in select does not work as expected -

i found funny behaviour using equal pdo. checked several select-statements in phpmyadmin , pdo , results vary. has idea whats wrong? $sql = "select * fenster fenster > 'news'"; //works ok $sql = "select * fenster fenster < 'news'"; //works ok $sql = "select * fenster fenster <= 'news'"; //works ok $sql = "select * fenster fenster >= 'news'"; // news not in result $sql = "select * fenster fenster = 'news'"; // news not in result $stmt = $db->prepare($sql); $stmt->execute(); $feldname = array_keys($stmt->fetch(pdo::fetch_assoc)); while($data = $stmt->fetch()) { var_dump($data); } i found reason myself. $feldname = array_keys($stmt->fetch(pdo::fetch_assoc)); did read missing row, did not show afterwards. have find workaround.

MySQL Procedure IN variable don't work properly -

i'm learning functions, procedures , triggers , wanted easy procedure count rows in table parameters. create procedure countrows(in v varchar(30)) select count(*) v; can tell me why if do: call countrows('sometable'); call countrows(sometable); //i tried both it don't work sorry newbie question. you need dynamic sql. solution returning count of table passed parameter sp delimiter $$ create procedure `countrows`(in v varchar(30)) begin set @t1 =concat("select count(*) ",v); prepare stmt3 @t1; execute stmt3; deallocate prepare stmt3; end$$ delimiter ; execution call countrows('sometable'); update: solution returning "table x contain n row(s)" table passed parameter sp delimiter $$ create procedure `countrowsex`(in v varchar(30)) begin -- set @t1 =concat("select count(*) ",v); set @t1 =concat('set @totalrows=(select count(*) ',v, ' );');

javascript - Generate React components in PHP and then render in client -

i'm trying use react simplify way build ui app i'm writing. i've got proof of concept working in single html page, need split out js individual modules make easier maintain. i know how structure app if every piece of puzzle known @ build time. this: https://github.com/jordwalke/reactapp . however, ui built dynamically in php, nesting various components want pass app. my initial thought of dumping generated code script tag , having javascript find has led me horrible dependencies hell. my primary question is: how pass <panel><group><field /></group></panel> app can call react.render() on it? as @llernestal , @mikedriver suggested in comments, used php build json representation of ui , had react build components needed render ui.

android - What exactly returns EntityUtils.toString(response)? -

i'm doing api rest , saw in lot of examples people use entityutils.tostring(response) response string get , post , put , delete methods. similar this: httpget method = new httpget(url); method.setheader("content-type", "application/json"); httpresponse response = httpclient.execute(method); string responsestring = entityutils.tostring(response.getentity()); please avoid answers said me gives me string i know returns me string content of entity (in case response) here doubts come, because i'm not secure string returns. saw official documentation. read contents of entity , return string. https://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/util/entityutils.html#tostring(org.apache.http.httpentity,java.lang.string) it content-type returned in string ? on contrary, values i'm getting method returned in string ? i think second 1 question i'm not secure that. and, in case true, how values stored stri

Generating ANTLR4 grammar files with package declaration in gradle -

i try use gradle antlr plugin, run several problems. i have grammar file called wls.g4 : grammar wlsscript; @header { package hu.pmi.wls.antlr.ws; } program : 'statementlist'? eof ; // several more grammar , lexer rules ( note: made statementlist keyword make correct grammer without including whole grammar. ;-) ) this file located in /src/main/antlr (as default source folder of antlr production grammar files). here snippet build.gradle : project('common') { apply plugin: 'antlr' dependencies { // dependencies antlr "org.antlr:antlr4:4.5" } } when use generategrammarsource gradle task (comming antlr plugin) generate source files generates files in build/generated-src/antlr/main folder default. what goes wrong, doesn't create folders of java package ( hu/pmi/wls/antlr/ws in our case) source incorrectly located in eclipse. my primary question how force task generate source files in pac

c++ - most elegant way to hardcode pair, triplet ... values -

i have enum. and each value in enum, need associate data (actually in case, it's integer, know more generally, instance 2 integer values, or 2 strings etc). those values can't accessible user. in case of reverse engineering, well, can't much, should ask user effort modify it. can't in config file or in db etc. so thinking about: hardcode them in case, what's elegant (least horrible) method? hardcode pair, triplet in namespace store in hash [enumvalue]->[struct]? store in file compiled resource file (although accessible tools, ask bit more effort user). checksum make sure wasn't modified if necessary guess? what thoughts? to summarize, have enum containing val1, val2 ... and associate like: val1 has length 5 , name "foo" val2 has length 8 , name "bar" i might missing other easy solution though this code adapted solution found while ago on stackoverflow post - if can find original link again i'll include

wix3.9 - unable to get Wix heat.exe working -

i working wix in combination visual studio 2013. bud there dont seem working. building installer (.msi) means need add files it, of course dont want al hand trying use heat.exe bud not succesful moment. i have tried following: made system variable points location of files. put system variable in command described in wix documentation: heat dir ".\mysystemvariablename" -gg -sfrag -template:fragment -out directory.wxs i inserted command in pre-build command line, selected suppress ice validation. when build project returns error 9009, couldnt figure out why or problem followed tutorial on youtube. in tutorial command used: “$(wix)bin\heat.exe” dir “$(superformfilesdir)” -cg superformfiles -gg -scom -sreg -sfrag -srd -dr installlocation -var env.superformfilesdir -out “$(projectdir)fragments\filesfragment.wxs” in video stripped down this: “$(wix)bin\heat.exe” dir “$(mysystemvariablename)” -cg mysystemvariablename -gg -scom -sreg -sfrag -srd -out “$(projectdir)