Thursday, 15 April 2010

javascript - Use Offcanvas with Bootstrap 3 Navbar Fixed Top -



javascript - Use Offcanvas with Bootstrap 3 Navbar Fixed Top -

i building site rather big menu, , don't collapsed menu ships bs3. want utilize drawer/off canvas menu, such 1 in bs3's offcanvas js illustration (or other plugin trick - must include back upwards dropdowns), illustration on sidebar menu/nav. how can create work current nav?

here example: http://getbootstrap.com/examples/offcanvas/

i need functionality, applied top menu rather sidebar.

html

<nav id="navbar-main" class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" id="menu-trigger" class="navbar-toggle"> <span class="sr-only">toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">brand</a> </div> <div id="main-menu" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="#">link</a></li> <li><a href="#">link</a></li> <li><a href="#">link</a></li> </ul> </div> </div> </nav>

ok, has issue figured out using jasny bootstrap's offcanvas feature.

working example: http://jasny.github.io/bootstrap/examples/navbar-offcanvas/

javascript jquery html css twitter-bootstrap

Android fragment -- OnDestroy being called when switching to a different tab followed by OnCreate when returning to the tab? -



Android fragment -- OnDestroy being called when switching to a different tab followed by OnCreate when returning to the tab? -

i have tabbed android app. when switch away tab, seeing ondestroy called corresponding fragment. when come tab, seeing oncreate called same fragment object. same object, not instance of same class. if switch away tab, ondestroy called again, followed 3rd phone call oncreate if homecoming tab, , on.

android docs appear state should not happen.

does indicate architectural problem app? if it's relevant, using mono, , setting retaininstance true in onactivitycreated.

edit: code below activity wraps tabs.

protected override void oncreate(bundle bundle) { base.oncreate(bundle); maincontext maincontext = maincontext; tabcontext tabcontext = maincontext.tabcontext; // tab custom model object; not related android tabs. list<tab> tabs = tabcontext.tabs; foreach (tab tab in tabs) { string displaystring = tab.displaystring; string withunderscores = displaystring.replace(' ', '_'); type fragmenttype = type.gettype(assembly.getexecutingassembly().getname().name + "." + withunderscores + "fragment"); this.addtab(tab, (fragment) activator.createinstance(fragmenttype)); } actionbar bar = this.actionbar; bar.navigationmode = actionbarnavigationmode.tabs; bar.setdisplayshowtitleenabled(false); bar.setdisplayshowhomeenabled(false); setcontentview(resource.layout.maintabactivitylayout); if (bundle != null) { int index = bundle.getint("index"); actionbar.setselectednavigationitem(index); } } private void addtab(tab tab, fragment fragment) { actionbar bar = this.actionbar; android.app.actionbar.tab droidtab = bar.newtab(); droidtab.settag(tab.tostring()); // omitting code sets icon , display text. droidtab.tabselected += (sender, e) => { e.fragmenttransaction.replace(resource.id.fragmentcontainer, fragment, tab.tostring()); }; this.actionbar.addtab(droidtab); }

it calling ondestroy because replacing fragment each time alter tab

e.fragmenttransaction.replace(resource.id.fragmentcontainer, fragment, tab.tostring());

as see using 1 layout(resource.id.fragmentcontainer) replacing fragment hence reusing after alter tab , releasing memory of replaced fragment calling ondestroy.

android android-fragments tabs mono monodroid

javascript - YouTube API: Multiple Embeds on the Same Page? -



javascript - YouTube API: Multiple Embeds on the Same Page? -

how can embed different youtube videos @ different places on page using youtube api? (this means can not share same <div> "player".) start @ different times based on different onclick events. code works fine when 1 video on page, life of me cannot figure out code allow work 2 or more!

at first trying add together multiple instances of code wanted each 1 be, wasn't working. read players need added 1 <script>, tried this:

(also, matter on page <script> , <div>s are? can <script> write <div> no matter on page?)

anyway, here's code i'm using:

// within other containers with relative , absolute positioning // fadein , fadeout using jquery <div id="video1"></div> // within other containers with relative , absolute positioning // fadein , fadeout using jquery <div id="video2"></div> <script> var tag = document.createelement('script'); tag.src = "//www.youtube.com/iframe_api"; var firstscripttag = document.getelementsbytagname('script')[0]; firstscripttag.parentnode.insertbefore(tag, firstscripttag); var player1; var player2; function onyoutubeiframeapiready() { player1 = new yt.player('video1',{ width: '320', height: '216', videoid: 'video_id_1', playervars: {rel: 0, controls: 0, autohide: 1, disablekb: 1, enablejsapi: 1, modestbranding: 1, showinfo: 0 }, events: { 'onstatechange': onplayerstatechange1 } });; player2 = new yt.player('video2',{ width: '320', height: '216', videoid: 'video_id_2', playervars: {rel: 0, controls: 0, autohide: 1, disablekb: 1, enablejsapi: 1, modestbranding: 1, showinfo: 0 }, events: { 'onstatechange': onplayerstatechange2 } });; } function startvideo1() { player1.playvideo(); $('#video_box_b1').delay(1000).fadein(); $("#video_box_b1").delay(20000).hide(); }; function onplayerstatechange1(event) { if(event.data === 2) { $("#video_box_b1").hide(); } } function startvideo2() { player2.playvideo(); $('#video_box_e5').delay(1000).fadein(); $("#video_box_e5").delay(20000).hide(); }; function onplayerstatechange2(event) { if(event.data === 2) { $("#video_box_e5").hide(); } } </script> // onclick triggers @ various places on page <img src="image_1.jpg" onclick="startvideo1()" /> <img src="image_2.jpg" onclick="startvideo2()" />

is there can tell i'm doing wrong? btw, containers fading in , out works if i'm using still image, text-only, or 1 video on page, it's not fading containers causing this. it's got youtube script. can help?

seems working in jsbin:

http://jsbin.com/catuhimo/3/edit

what browser trying out in? if you're using safari bleeding border version 8.0 (10538.39.41) on yosemite, jsfiddle , jsbin had problem rendering things. tried out code on chrome latest , replaced placeholders actual video ids , worked.

does help? missing point of question? based on asked, seems work ok me.

javascript jquery html youtube-api

database - MySQL Delete Rows Based Upon Max Value of Column -



database - MySQL Delete Rows Based Upon Max Value of Column -

i have table ('conditions') contains column titled "date" delete of rows not equal current date (as determined max value of date(max(date)). partial table result:

| date | time | observed | temp | heatindex | windchill | relhumidity | wind | 14-06-21 | 19:30 | scattered clouds | 85.9 | 91 | na | 61% | 2 | | 14-06-21 | 20:30 | clear | 83.2 | 88 | na | 67% | 3 | | 14-06-21 | 21:30 | clear | 80.7 | 85 | na | 74% | 5 | | 14-06-21 | 22:30 | clear | 79.5 | 83 | na | 76% | 4 | | 14-06-21 | 23:30 | clear | 78.4 | 81 | na | 79% | 4 | | 14-06-22 | 00:30 | clear | 77.6 | na | na | 82% | 3 | | 14-06-22 | 01:30 | clear | 77.1 | na | na | 83% | 3 | | 14-06-22 | 02:30 | scattered clouds | 77.3 | na | na | 84% | 2 | | 14-06-22 | 03:30 | clear | 77.1 | na | na | 83% | 2 | | 14-06-22 | 04:30 | clear | 76.6 | na | na | 86% | 4 |

so after command, see next only:

| 14-06-22 | 00:30 | clear | 77.6 | na | na | 82% | 3 | | 14-06-22 | 01:30 | clear | 77.1 | na | na | 83% | 3 | | 14-06-22 | 02:30 | scattered clouds | 77.3 | na | na | 84% | 2 | | 14-06-22 | 03:30 | clear | 77.1 | na | na | 83% | 2 | | 14-06-22 | 04:30 | clear | 76.6 | na | na | 86% | 4 |

i tried:

delete conditions date <> max(date);

but received:

error 1111 (hy000): invalid utilize of grouping function

the lastly row current date. have considered adding id column , sorting desc, want lastly row recent entry. every time insert info (python) database, script containing delete executed.

pretty sure can't utilize max same reason can't sub-query current table on delete.

what can utilize curdate()

http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_curdate

delete conditions date <> curdate();

mysql database sql-delete

python - Confusion found with and operator -



python - Confusion found with and operator -

this question has reply here:

does python back upwards short-circuiting? 3 answers

i next output and operator

code

>>>0 , [] 0 >>>[] , 0 [] >>> 0 , '' 0 >>>'' , 0 ''

i not figure out on basis m getting different result on basis of placing of elements..

from the docs on and:

the look x , y first evaluates x; if x false, value returned; otherwise, y evaluated , resulting value returned.

in case, because 0, '', , [] evaluate false, first value in each of expressions beingness returned.

python operator-keyword

adobe - Evenly distribute objects within another object -



adobe - Evenly distribute objects within another object -

is there simpler way distribute multiple objects within bounds of object?

i've included image help illustrate want done.

the greenish portion artboard, grayness portion main body , item1-6 distributed within bounds of white box. typically accomplish desired result have create additional objects (represented reddish lines) , place 1 @ left end of box, 1 @ right end, , 1 between each item, , utilize distribute evenly button , remove reddish lines afterwards.

i imagine there faster way can't seem find it. ideas appreciated.

okay, fiddly, seem quite inuitive 1 time you've done 1 time or twice.

short version;

find width of container. select container , objects - set container key object. enter width of container align window: distribute spacing, split figure number of objects, click horizontal distribute center. group objects , center them container. ungroup them again, if desired.

long version;

1. work out width of containing box (or artboard, if distributing items that). if, example, have rectangle can select , @ 'w' (width) value @ top of window (click on transform reveal info if you're working on smaller screen). remember number - nil else.

2. select of items , container. click on container 1 time again create 'key object' (you should see selection border becomes distinctly fatter).

3. if necessary, open align window (window > align). window visible, should see 3 rows or sections take - 'align objects', 'distribute objects' , 'distribute spacing'. if latter missing, may need click on little up/down arrow symbol next 'align' tab title few times in order expand of options.

4. ensuring still have of items selected , container set key object (the 'align to' box should automatically set 'align key object' in recognition of this), come in container width took note of before 'distribute spacing' box - , append /x x = number of items have. so, if box 200 pts wide, , have 5 items, come in 200/5 - save having maths. illustrator automatically split starting figure , (in case of example), alter 40 pt (200 divided 5).

5. click on horizontal distribute center button , of items set right spacing. won't aligned container, though, ...

6. in order prevent nicely spaced items beingness messed next step, de-select container (so items selected), grouping them - either keyboard shortcut ctrl+g (or command+g on mac), or going object > group.

7. items grouped, re-select container (so container , grouping of objects selected), create container key object 1 time again - if don't want see move) , click on horizontal align center. items centered in container , can safely ungrouped if wish (ctrl+shift+g / command+shift+g).

adobe adobe-illustrator

jquery - data-ajax="false" for for all web pages -



jquery - data-ajax="false" for for all web pages -

i using j query mobile web site . website dont need ajax functionality . want native page links. in j query mobile page transfers in ajax mode. if want turn off need utilize syntax data-ajax="false" don't need ajax.

can turn off ajax whole website

note : utilize include pages php mutual code work pages

on mobileinit event, pass $.mobile.ajaxenabled = false; disable ajax mobile page navigation:

$(document).bind("mobileinit", function () { $.mobile.ajaxenabled = false; });

proper format binding mobileinit event:

<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0rc3/jquery.mobile-1.0rc3.min.css" /> <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script> <script type="text/javascript"> $(document).bind("mobileinit", function () { $.mobile.ajaxenabled = false; }); </script> <script src="http://code.jquery.com/mobile/1.0rc3/jquery.mobile-1.0rc3.min.js"></script> jquery core specific mobileinit event handler the jquery mobile js file

jquery mobile js file lastly event handler mobileinit set before event fired.

reference: http://demos.jquerymobile.com/1.0/docs/api/globalconfig.html

jquery ajax jquery-mobile

loops - In powerpoint how do I go about having looping animations? -



loops - In powerpoint how do I go about having looping animations? -

i'm trying animate button if clicked, image appear, when clicked again, image disappear- want go on happen indefinitely- sense can written macro, want avoid unnecessary over-complicating of things. tried add together in click animations appear , disappear

instead of using animations, can toggle transparency of image between 0 (totally transparent) , 1 (totally solid) when click happens accomplish disappearing , appearing.

loops button click jquery-animate powerpoint

PHP SESSION works only over HTTPS + PHPSESSID cookie is not sent -



PHP SESSION works only over HTTPS + PHPSESSID cookie is not sent -

i have sample page content of next code:

<?php session_start(); if (isset($_session['test'])){ echo 'session variable set '; echo $_session['test']; }else{ echo 'session variable not set'; $_session['test'] = 'test'; }

when access page through https (ex: https://www.example.com/page.php) works well, first time sets $_session variable , after retrievs normally.

however, when access page through normal http, every time "session variable not set". when checked request/response cookies in both situations, found when using https phpsessid cookie retrieved first request of page, , sec request on same phpsessid sent request cookie. however, on normal http every time load page, loads without sending cookies, gets different phpsessid cookie doesn't save , utilize next requests of page.

i want know causes , solutions problem.

thank you.

session cookies may sets secured

try using session_set_cookie_params disable secure session cookies

$oldparams = session_get_cookie_params(); session_set_cookie_params($oldparams["lifetime"], $oldparams["path"], $oldparams["domain"], false, true); session_start();

php session cookies

swift - How to pass a class and method to create an instance of a class? -



swift - How to pass a class and method to create an instance of a class? -

this question has reply here:

swift class introspection & generics 6 answers

i started learning apple swift can not deal problem, have methods help objective-c please rewrite on apple swift

- (void)setclass:(class)aclass { nsobject *object = [[aclass alloc] init]; }

call method (user inherited nsobject):

[self setclass:[user class]];

how repeat such actions on apple swift? give thanks you!

here article instantiating classes name in swift. problem solved creating objective-c class method

+ (id)create:(nsstring *)classname { homecoming [nsclassfromstring(classname) new]; }

and calling swift. source code on github: https://github.com/ijoshsmith/swift-factory

update:

here simpler solution:

var clazz: nsobject.type = testobject.self var instance : nsobject = clazz() if allow testobject = instance as? testobject { println("yes!") }

of course, class must subclass of nsobject.

your function be:

func setclass (myclass: nsobject.type){ var object = myclass() }

swift

php - Laravel routes error -



php - Laravel routes error -

here 2 routes have:

route::resource('tournament/{tourid}/phase/{phaseid}/bets', 'phasecontroller@getphasebets'); route::resource('tournament/{tourid}/phase/{phaseid}', 'phasecontroller@getphaseinfo');

but getting exception when trying run api:

route pattern "/api/tournament/{tourid}/phase/{phaseid}/{{phaseid}}" cannot reference variable name "phaseid" more once.

from did {{phaseid}} ? why getting error?!

tl;dr:

since defining routes straight pointing controller actions, should using:

route::get('tournament/{tourid}/phase/{phaseid}/bets', 'phasecontroller@getphasebets'); route::get('tournament/{tourid}/phase/{phaseid}', 'phasecontroller@getphaseinfo');

longer version:

to utilize route::resource() should next docs in resource controllers. e.g:

route::resource('phase', 'phasecontroller');

which generate route urls like:

/tournament/{tourid}/phase/{phaseid}/bets /tournament/{tourid}/phase/{phaseid}/bets/{resource_id} /tournament/{tourid}/phase/{phaseid}/bets/{resource_id}/edit /tournament/{tourid}/phase/{phaseid}/bets/create

you see instead of having 1 parameter resource id, routes have 3 parameters. confuses laravel on 1 should utilize resource id.

since defining routes straight pointing controller actions, should using:

route::get('tournament/{tourid}/phase/{phaseid}/bets', 'phasecontroller@getphasebets'); route::get('tournament/{tourid}/phase/{phaseid}', 'phasecontroller@getphaseinfo');

if you'd still utilize resource controllers you'll need alter code this.

route::resource('phase', 'phasecontroller'); route::resource('bet', 'betcontroller');

and in controller files:

phasecontroller.php:

class phasecontroller extends basecontroller { public function show($id) { // original phasecontroller@getphaseinfo() here } }

betcontroller.php:

class betcontroller extends basecontroller { public function show($id) { // original phasecontroller@getphasebets() here } }

and reference urls this:

/phase/your_phase_id /bet/your_bet_id

obviously might not totally suit requirements. if explain little bit of relationships between tournaments, phases, bets, , you're trying achieve, maybe can suggest improve way.

php laravel laravel-4 laravel-routing

java - View and SurfaceView alternative? -



java - View and SurfaceView alternative? -

help! making simple android game involves dragging player sprite avoid enemy sprites, i'm running problems both view , surfaceview.

view - ondraw() , ontouchevent() methods on ui thread , cause framerate drop (or speed on devices) when screen touched.

surfaceview - there no hardware acceleration on this, causes high resolution .png bitmaps drawn badly without antialiasing.

glsurfaceview - not prefer larn opengl such basic game, , don't have plenty time game must done soon.

do have alternative here? if handle touch events in thread using view might work, don't know if it's possible.

java android multithreading surfaceview

objective c - Set delegate:self.delegate in an alertView where self.delegate implements UIAlertViewDelegate protocol -



objective c - Set delegate:self.delegate in an alertView where self.delegate implements UIAlertViewDelegate protocol -

in viewcontroller have implemented uialertviewdelegate , in model have method creates uialertview delegate set self.delegate instance of viewcontroller. seek phone call willpresentalertview (in model):

uialertview *alert = [[uialertview alloc] initwithtitle:@"invalid operation" message:@"cannot split 0!" delegate:self.delegate cancelbuttontitle:@"cancel" otherbuttontitles:@"undo division",nil]; [self.delegate willpresentalertview:alert];

the willpresentalertview implemented in viewcontroller this:

- (void)willpresentalertview:(uialertview *)alertview { [alertview show]; }

i error thread 1:exc_bad_access (code=2,adress=0xbf7fff6c) when calling [alert show].

if set delegate nil or self works fine, want phone call alertview:alertview clickedbuttonatindex:buttonindex when press button on alert, doesn't work delegate set nil or self. viewcontroller implements these methods, why should self.delegate, or?

i want model invoke alert, want viewcontroller handle alert methods such alertview:alertview clickedbuttonatindex:buttonindex.

how can done?

it should self [self willpresentalertview:alert]

uialertview *alert = [[uialertview alloc] initwithtitle:@"invalid operation" message:@"cannot split 0!" delegate:self //self cancelbuttontitle:@"cancel" otherbuttontitles:@"undo division",nil]; [self willpresentalertview:alert];//self 1 time again

objective-c xcode delegates uialertview uialertviewdelegate

Balanced payment integration with PHP Curl -



Balanced payment integration with PHP Curl -

i using balanced payment transferring payment site having problem , using php curl code in programming language, have not received type oh hopeful response of problem.

my curl code written below.

$url = "https://api.balancedpayments.com/v1/marketplaces/test-mp1k1dzwdlvf3nifthuparof/"; $ch = curl_init(); curl_setopt($ch, curlopt_ssl_verifypeer, false); curl_setopt($ch, curlopt_url,$url); curl_setopt($ch, curlopt_post, 1); curl_setopt($ch, curlopt_postfields,'key=xxxxxxxxxxxxxxxxxxxxxx&amount=5000&description=some descriptive text debit in dashboard'); curl_setopt($ch, curlopt_returntransfer, true); $output = curl_exec($ch);

this "key" hidden purchase security reason.

if has solution problem please contact me email ishansourabhjain@hotmail.com.

thanks & regards, ishan s. jain

i suspect issue has trying post key instead of supplying in basic auth format.

also, note you're building code against old api version (1.0). 1.1 recommended.

why not utilize existing balanced client library php? https://github.com/balanced/balanced-php

php curl balanced-payments

javascript - Delete textarea text on submit in new tab? -



javascript - Delete textarea text on submit in new tab? -

so i'm working on chat scheme , though know works in pretty lame way - submitting messages in new window () - i'm interested if there's way reset textarea's content after sending message.

now, problem is, i've found ways via javascript (editing textarea's value), don't know how "launch" javascript after submitting form.

obviously, can utilize onsubmit(), delete's value before sending data. works, sends empty text.

any ideas? thanks!

a mutual solution re-create values of <form> object can convert json. way, have re-create of values doesn't alter when reset fields of form. jquery create simple. see also: serializing , submitting form jquery post , php

the sec solution submit form , lastly thing, add together timeout resets form. there little gap , user might able type while handler clearing form.

javascript jquery html textarea chat

mysql - Writing PHP with SQL queries in Emacs -



mysql - Writing PHP with SQL queries in Emacs -

what should utilize in emacs developing php files sql queries?

when indenting buffer code should this:

<?php $query = " select id, name products id > 12" ?>

in web-mode , php-mode looks this:

<?php $query = " select id, name products id > 12" ?>

if isn't possible, 1 alternative have enable manual indentation (using tab , shifttab, in sublime , other editors) when @ multi-line strings in php code. how that?

the lastly version (9.0.84) of web-mode (available on github) provides native sql indentation in block strings.

php mysql emacs

sql - Creating Integer Primary key value using the following query -



sql - Creating Integer Primary key value using the following query -

discuss next sql query respect performance in application involving more number of concurrent users creating , deleting records. objective create continuous primary key integer values.

table name: sitepage column datatype --------- ----------- pageid bigint pagename nchar(10)

query insert new record

declare @intflag int set @intflag = 0 while (@intflag =0) begin begin seek insert sitepage (pageid, pagename) values ((select max(pageid)+1 sitepage), concat('page id : ', (select max(pageid)+1 sitepage))); set @intflag = @@rowcount end seek begin grab set @intflag=0 end grab end go we don't want utilize auto increment integer value primary key because of next reason we don't want utilize sequence we can't trace flag 272

you should never utilize "select max()+1" unique id. number 1 reason concurrent users, value has absolutely no guarantee of beingness unique - 2 users running anywhere close simultaneously can end same value. don't it. ever. that's why things auto-number , sequences exist.

sql sql-server

ios - UICollectionView with Paging Enable -



ios - UICollectionView with Paging Enable -

i have create grid view appstore ios app. want uicollectionview paging. have implemented code not able scroll that.

what want there 1 image in center , @ both sides(left , right), should show portion of previous , next image. have set frame uicollectionview 320*320. cell size 290*320.(cell min spacing 10)1

below 2 links depicts requirement. in advance.

(this want) 2

have tried setting scroll direction of uicollectionviewflowlayout horizontal?

[yourflowlayout setscrolldirection:uicollectionviewscrolldirectionhorizontal];

you'll need enable paging on collection view so:

[yourcollectionview setpagingenabled:yes];

ios objective-c uiscrollview uicollectionview paging

android - NFC - How to check if device still has contact to chip -



android - NFC - How to check if device still has contact to chip -

i'm using nfc chip open app. when device still has contact nfc chip , press home button want reopen app. how can manually check contact?

in short: can't. home button handled android os. unless want modify android os, not possible.

android nfc

Moving and Hiding data in SSRS 2008 and 2012 -



Moving and Hiding data in SSRS 2008 and 2012 -

i have created matrix ssrs first column beingness todays date , sec column beingness same date lastly year. have provided sample below. see june 1 2014 , next june 2013. hide june 2 2013 , slide info left fill empty space under june 1 2013 have 4 rows of data. did not past on row of 3 2014 , row of 1 2013 . suggestions? have not found samples of such. ahead of time.

jun 1 2014 jun 2 2013 jun 2 2014 jun 3 2013 3,465 12,575 3,465 12,575 1,480 10,396 1,287 11,208 6,514 23,642 6,514 23,642 6,893 21,617 6,702 19,716 5,086 18,460 5,086 18,460 4,353 16,299 3,543 11,723 1,067 3,874 1,067 3,874 559 2,562 94 216 933 3,388 933 3,388 764 3,425 71 159

you need set column visibility column want hide hidden=true. if question more complex reply above might want using column grouping on days in info , hiding specific days in data.

ssrs-2008

html - Upload Image not using erb (form) rails -



html - Upload Image not using erb (form) rails -

i wondering if there way upload images in rails 4 not using erb. have html code in quotations in model (so can utilize default when creating page). cant set erb in quotes, cuz if it'll come out erb code , not actual view. (i.e. upload image form. itll come out actual f.image_tag instead of actual upload button).

so seeing if there way implement image uploading quotations wont require erb. but, uses rails 4.

if have plain html code within string, , want displayed, need phone call .html_safe in view, like:

'<div id="foo">bar</div>'.html_safe()

note bad practice: doesn't mean bad, means attending point create sure best way it.

if want image upload without using form.image_tag, can set in view , see generated code (ctrl+u in chrome), that, in case, like:

<input type="file" id="something" />

and add together string. finer validation , options added via js, pain add together way - 1 way to add together script tag html code.

if, however, string contains code this, , asking way not working, need add together eval caller, e.g.:

eval('form.image_tag :image')

not worse smell, , should avoided @ costs.

maybe improve add together flags in section.rb model, , utilize in helper or in view render html; example, has_upload? field, , can this:

if @section.has_upload? form.image_tag :imagem end

html ruby-on-rails ruby

android - How to add multiple TextViews programmatically to a RelativeLayout -



android - How to add multiple TextViews programmatically to a RelativeLayout -

how 1 programmatically, via 1 button click @ time, add together multiple textviews existing relativelayout without textviews overlapping onto 1 another.

i trying - next code exists within oncreate() method:

textview textviewtoseefirst = (textview) findviewbyid(r.id.textview1); relativelayout rlayout1 = (relativelayout) findviewbyid(r.id.relativelayout1); button button1 = (button) findviewbyid(r.id.button1); button1.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { relativelayout.layoutparams lparams = new relativelayout.layoutparams (layoutparams.match_parent, layoutparams.wrap_content); textview newtextview = new textview(theactivityyouareusingactivity.this); newtextview.settext("text want"); rlayout1.addview(newtextview, lparams); }

the textviews beingness added relativelayout, on top of 1 another, how 1 prepare this?

why dont add together text views in xml file (as much want) before running app. set visibilities textviews dont want show "gone" , in button click listener maintain changing visibility of textview "view.visible" . if want new textview appear each time press button set counter button , each time counter increments alter want textview's visibility view.visible. if understood saying able create code on own.

android relativelayout overlapping

c# - "Fatal error encountered during command execution." mysql-connector .net -



c# - "Fatal error encountered during command execution." mysql-connector .net -

i using next code:

mysqltransaction trndata = pcondb.begintransaction(); mysqlcommand cmddata = new mysqlcommand(); cmddata.connection = pcondb; cmddata.commandtimeout = plngquerytimeout; cmddata.commandtype = commandtype.text; cmddata.commandtext = "call spsome( 4, 'data', 389552022,@intoutreturn);"; cmddata.transaction = trndata; plngrecordscount = cmddata.executenonquery();

isn't call statement possible straight .net library? same query working on workbench.

change 2 lines this:

cmddata.commandtype = commandtype.storedprocedure; cmddata.commandtext = "spsome( 4, 'data', 389552022,@intoutreturn);";

you need add together parameter parameters collection of cmdata @intoutreturn parameter. won't give illustration of syntax varies databases , don't know mysql's looks like.

also, line:

cmddata.transaction = trndata;

..is necessary if doing other db operations should in same transaction. if you're not, i'd leave line out.

c# mysql .net mysql-connector

jquery - Trying to get the date from the bootstrap datepicker to working right -



jquery - Trying to get the date from the bootstrap datepicker to working right -

basically, date take goto textbox. since it's not putting date straight startdatetextbox.value, can't access date on startdatetextbox. there way prepare this?

<script> $(function () { $("#startdatetextbox").datepicker({ showon: "button", buttonimage: "./calendarfull.png", buttonimageonly: true }); document.getelementbyid('startdatetextbox').value = $("startdatetextbox").valueof(); var sdf = 234; } ); </script> <script> $("startdatetextbox").click(function (event) { alert($(this).attr("data-my-custom-data")); alert($(this).attr("data-row-id")); alert($(this).attr("href")); event.preventdefault(); // avoid browsing href... }); document.getelementbyid('startdatetextbox').value = " 234 "; </script>

i'm going effort reply before reply comments on question:

when encounter problem (and posted code i'm guessing you've been doing try-and-see-what-happens approach solving problem), go basics. start fresh page has want on it: references jquery, bootstrap, , date-picker library, plus bare minimum test ui , script.

try this: add together text box t o page: <input type="text" value="" id="startdatetextbox" />, next code: <script type="text/javascript"> $(document).ready(function () { $("#startdatetextbox").datepicker({ showon: "button", buttonimage: "./calendarfull.png", buttonimageonly: true }); }); </script>

i've tested code , know works. generates pop-up date picker when focus on text box, , adds date select text box. , notice i've used $(document).ready()? help ensure libraries have loaded first before initialise date-picker.

i see you're mixing both native javascript selectors , jquery. pick 1 , stick save confusion in switching between styles. jquery works well, suggest utilize that.

now, want access selected date in textbox? seek this: function showdatevalue() { alert($("#startdatetextbox").val()); } should display day textbox in alert dialog.

what need next? see you're referencing hrefs , talking stopping browsing links, suspect there more problem. step me through , can help.

jquery asp.net twitter-bootstrap datepicker bootstrap-datepicker

PHP MongoDb driver: How to set timeout for executing a code -



PHP MongoDb driver: How to set timeout for executing a code -

i have next code executes piece of code on mongodb's side:

$mongocode = new mongocode('/* js code */'); $db->execute($mongocode, array( 'sockettimeoutms' => 1000000, ));

as see have tried set timeout code's execution setting sockettimeoutms value in sec parameter of execute() function. not work. documentations in php website indicate sec parameter of execute() command sent code arguments. how can set timeout mongodb::execute()? please note using version 1.5 of mongodb driver php , mongocursor::$timeout deprecated , not work anymore.

you can set sockettimeoutms on mongoclient:

$mongo = new mongoclient("mongodb://localhost:27017", array( "sockettimeoutms" => 100000 ) );

the args parameters execute method passed code (your javascript function) not driver.

alternatively, can set timeout on cursor this:

$cursor = $collection->find(array()); $cursor->timeout(10000);

but not work on execute command, because command doesn't homecoming cursor.

php mongodb

jsf - Could not find backup for factory javax.faces.context.FacesContextFactory Weblogic -



jsf - Could not find backup for factory javax.faces.context.FacesContextFactory Weblogic -

i'm using jsf2.1 mojarra on weblogic 12c servlet 3.0. jsf-api , jsf-impl not in /web-inf/lib after build/deploy. i've tried checking classpath pollution, don't see anything. error:

java.lang.illegalstateexception: not find backup mill javax.faces.context.facescontextfactory. @ javax.faces.factoryfinder$factorymanager.getfactory(factoryfinder.java:1010) @ javax.faces.factoryfinder.getfactory(factoryfinder.java:342) @ javax.faces.webapp.facesservlet.init(facesservlet.java:302) @ weblogic.servlet.internal.stubsecurityhelper$servletinitaction .run(stubsecurityhelper.java:337) @ weblogic.servlet.internal.stubsecurityhelper$servletinitaction .run(stubsecurityhelper.java:288) truncated. see log file finish stacktrace

here's found in classpath relates jsf:

com.oracle.adf.library:jsf:pom:12.1.2-0-0 com.sun.faces:jsf-api:jar:2.1.7-01 com.sun.faces:jsf-impl:jar:2.1.7-01

here's in classpath:

com.bea.core.antlr:runtime:jar:1.0.0.0_3-2 com.oracle.adf.library:contexts-and-dependency-injection:pom:12.1.2-0-0 com.oracle.adf.library:java-ee:pom:12.1.2-0-0 com.oracle.adf.library:jsf:pom:12.1.2-0-0 com.oracle.adf.library:jsp-runtime:pom:12.1.2-0-0 com.oracle.adf.library:jstl:pom:12.1.2-0-0 com.oracle.adf.library:toplink:pom:12.1.2-0-0 com.oracle.adf:eclipselink:jar:12.1.2-0-0 com.sun.faces:jsf-api:jar:2.1.7-01 com.sun.faces:jsf-impl:jar:2.1.7-01 com.sun.mail:javax.mail:jar:1.4.4 glassfish:el:jar:1.1.0.0_2-2 glassfish:jstl:jar:1.2.2.0 javax.enterprise:deploy:jar:1.3 javax.enterprise:inject:jar:1.1 javax.management:j2ee:jar:1.1.0.0 javax.security:jacc:jar:1.1.0.0_1-1 javax.servlet:jstl:jar:1.2 javax.servlet:servlet-api:jar:2.5 javax.xml:registry:jar:1.1.0.0_1-0-4 javax.xml:rpc:jar:1.2.3 javax.xml:stream:jar:1.1.1.0 javax.xml:ws:jar:2.3.0 javax:ejb:jar:3.2.0 javax:inject:jar:1.1 javax:interceptor:jar:1.2 javax:jms:jar:1.1.3 javax:jsp:jar:3.0.0.0_2-2 javax:resource:jar:1.6.1 javax:servlet:jar:2.1.0.0_3-0 javax:transaction:jar:2.1.0.0_1-1 javax:validation:jar:1.1.0 junit:junit:jar:4.4:test log4j:log4j:jar:1.2.16 org.eclipse.persistence:javax.persistence:jar:2.0.5-snapshot org.eclipse.persistence:nosql:jar:2.4.2.v20130514-5956486 org.eclipse.persistence:org.eclipse.persistence.oracle.nosql:jar:2.4.2-snapshot org.glassfish:javax.annotation:jar:3.0.1

i found issue. in web-inf/faces-config.xml, had navigation-handler pointing class didn't exist. correcting resolved issue.

jsf weblogic

Putting a JSONArray into a list(Android) -



Putting a JSONArray into a list(Android) -

i have project can take jsonobject , set edittext i'm trying figure out how alter takes jsonarray , puts listview.

here current code:

public class js extends activity { private string url1 = "http://api.openweathermap.org/data/2.5/weather?q=chicago"; //private string url1 = "http://bisonsoftware.us/hhs/messages.json"; private textview temperature;//,country,temperature,humidity,pressure; private handlejson obj; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_js); //location = (edittext)findviewbyid(r.id.edittext1); //country = (textview)findviewbyid(r.id.edittext2); temperature = (textview)findviewbyid(r.id.edittext3); //humidity = (edittext)findviewbyid(r.id.edittext4); //pressure = (edittext)findviewbyid(r.id.edittext5); } @override public boolean oncreateoptionsmenu(menu menu) { // inflate menu; adds items //to action bar if present. getmenuinflater().inflate(r.menu.js, menu); homecoming true; } public void open(view view){ //string url = location.gettext().tostring(); //string finalurl = url1 + url; //country.settext(url1); obj = new handlejson(url1); obj.fetchjson(); while(obj.parsingcomplete); //country.settext(obj.getcountry()); temperature.settext(obj.gettemperature()); //humidity.settext(obj.gethumidity()); //pressure.settext(obj.getpressure()); } } public class handlejson { //private string country = "temperature"; private string temperature = "clouds"; //private string humidity = "humidity"; //private string pressure level = "pressure"; private string urlstring = null; public volatile boolean parsingcomplete = true; public handlejson(string url){ this.urlstring = url; } /*public string getcountry(){ homecoming country; }*/ public string gettemperature(){ homecoming temperature; } /*public string gethumidity(){ homecoming humidity; } public string getpressure(){ homecoming pressure; }*/ @suppresslint("newapi") public void readandparsejson(string in) { seek { jsonobject reader = new jsonobject(in); //jsonobject sys = reader.getjsonobject("main"); //country = sys.getstring("temp"); jsonobject main = reader.getjsonobject("clouds"); temperature = main.getstring("all"); //pressure = main.getstring("pressure"); //humidity = main.getstring("humidity"); parsingcomplete = false; } grab (exception e) { // todo auto-generated grab block e.printstacktrace(); } } public void fetchjson(){ thread thread = new thread(new runnable(){ @override public void run() { seek { url url = new url(urlstring); httpurlconnection conn = (httpurlconnection) url.openconnection(); conn.setreadtimeout(10000 /* milliseconds */); conn.setconnecttimeout(15000 /* milliseconds */); conn.setrequestmethod("get"); conn.setdoinput(true); // starts query conn.connect(); inputstream stream = conn.getinputstream(); string info = convertstreamtostring(stream); readandparsejson(data); stream.close(); } grab (exception e) { e.printstacktrace(); } } }); thread.start(); } static string convertstreamtostring(java.io.inputstream is) { java.util.scanner s = new java.util.scanner(is).usedelimiter("\\a"); homecoming s.hasnext() ? s.next() : ""; } }

i have been trying figure out while can't find way implement through way i'm parsing data. in advance help given.

here json:

"messages":["this demo message. enjoy!","another demonstration message stored in json format.","json stands javascript object notation (i think)"]

what you're asking several questions. break downwards yourself, , think you'll have much easier time.

create functionality executes net service request , returns response, handling error cases, etc.

create "weather" class reflects contents of json (e.g. yours, class temperature, pressure, humidity, etc.)

create functionality checks response validity , constructs weather object it.

create collection of these weather objects (list, set, etc.) response

create custom listadapter takes instance of weather object , translates ui.

???

profit

taken individually, you'll have much easier time tackling this. custom adapter simple implement. so, have simple weather class this:

public final class weather { public final string temperature; public final string pressure; public final string humidity; public weather(string temperature, string pressure, string humidity) { this.temperature = temperature; this.pressure = pressure; this.humidity = humidity; } public static weather valueof(jsonobject json) throws jsonexception { string temperature = json.getstring("temp"); string pressure level = json.getstring("pressure"); string humidity = json.getstring("humidity"); } }

make simple subclass of baseadapter takes weather , adapts custom layout you've created:

public final class weatheradapter extends baseadapter { private final list<weather> mweatherlist; private final layoutinflater minflater; public weatheradapter(context ctx, collection<weather> weather) { minflater = layoutinflater.from(ctx); mweatherlist = new arraylist<>(); mweatherlist.addall(weather); } @override public int getcount() { // homecoming size of info set homecoming mweatherlist.size(); } @override public weather getitem(int position) { // homecoming item in our info set @ given position homecoming mweatherlist.get(position); } @override public long getitemid(int position) { // not useful in our case; homecoming position homecoming position; } @override public view getview(int position, view convertview, viewgroup parent) { if (convertview == null) { // there's no view re-use, inflate new one. // assumes you've created layout "weather_list_item.xml" // textviews pressure, temperature, , humidity convertview = minflater.inflate(r.layout.weather_list_item, parent, false); // cache views findviewbyid() efficiency convertview.settag(new weatherviewholder(convertview)); } // weather item list position weather weather = getitem(position); weatherviewholder holder = (weatherviewholder) convertview.gettag(); // assign text, icons, etc. layout holder.pressure.settext(weather.pressure); holder.temperature.settext(weather.temperature); holder.humidity.settext(weather.humidity); homecoming convertview; } public static class weatherviewholder { public final textview pressure; public final textview humidity; public final textview temperature; public weatherviewholder(view v) { pressure level = (textview) v.findviewbyid(r.id.pressure); humidity = (textview) v.findviewbyid(r.id.humidity); temperature = (textview) v.findviewbyid(r.id.temperature); } } }

android android-json

excel - Unable to find small syntax error in VBA code -



excel - Unable to find small syntax error in VBA code -

i cannot find error(s) in code. trying insert formula in column s, when "cn equity" used in column a. want macro run row 6 69.

sub fx() dim x long x = 6 if instr(1, (range("a" & x).value), "cn equity") > 0 sheets("sheet1").range("s" & x).formula = "=bdp("cadusd bgn curncy","last_price")" & x end if x = x + 1 loop until x = 70 end sub

consider:

sub fx() dim x long x = 6 if instr(1, (range("a" & x).value), "cn equity") > 0 sheets("sheet1").range("s" & x).formula = "=bdp(""cadusd bgn curncy"",""last_price"")+" & x end if x = x + 1 loop until x = 70 end sub

note

replace + in formula * or & if necessary.

excel vba syntax-error

java - In Android, is it necessary to loop through all files/directories in a zip to read content from a file at known location? -



java - In Android, is it necessary to loop through all files/directories in a zip to read content from a file at known location? -

i want read first line of file within zip file. using while loop 1 sample stackoverflow quesion link

but know exact location of file within zip. , zip file big(can more 500mb).

so i'm thinking there way read file without looping through files using while.

use zipfile instead of zipinputstream. reads zip file's central directory (see wikipedia article) , not whole file. can utilize entries() or getentry(java.lang.string) , getinputstream(java.util.zip.zipentry) input stream entry:

string entryname = // set name of entry here file file = // set zip file here zipfile zipfile = null; seek { zipfile = zipfile(file); zipentry zipentry = zipfile.getentry(entryname); inputstream = null; seek { = zipfile.getinputstream(zipentry); // read stream here e.g. using bufferedreader } grab (ioexception ex) { // todo: handle exception or delete grab block } { if (is != null) { seek { is.close(); } grab (ioexception ex) { } } } } { if (zipfile != null) { zipfile.close(); } }

java android file file-io zip

Multiplying variables in Ruby? -



Multiplying variables in Ruby? -

i'm trying create simple pay predictor program.

i capturing 2 variables, want multiply variables. have tried doing

pay = payrate * hourrate

but seems not work. told set pay in definition, tried display variable still didn't work. when looked @ documentation, seems using right operator. guesses?

# simple budgeting programme puts "what budget type?\nyou can 'monthly' 'weekly' or 'fortnightly'" payperiod = gets.chomp case payperiod when "monthly" puts "you paid monthly" when "weekly" puts "you paid weekly" when "fortnightly" puts "you paid every 2 weeks." else puts "you did not input right answer." end puts "what hourly rate?\n" payrate = gets.chomp puts "how many hours have worked during pay period?\n" hourrate = gets.chomp def pay payrate * hourrate end puts "#{pay}" preventclose = gets.chomp

the def has nil it. payrate , hourrate strings , * means different thing strings. need convert them numbers first to_i or to_f.

payrate.to_f * hourrate.to_f

ruby variables

java - FluentWait ignore not working as expected -



java - FluentWait ignore not working as expected -

i have selenium webdriver test failing after dismissing modal window waiting element. specifically, fails looking element in fluentwait call. i've tried various different ways of setting wait, none working. here think should work:

the test code failing:

driver.findelement(by.classname("dismiss")).click(); // dismisses modal window driver.switchto().defaultcontent(); fluentwait<webdriver> fluentwait = new fluentwait<webdriver>(driver) .withtimeout(30, timeunit.seconds) .pollingevery(500, timeunit.milliseconds) .ignoring(nosuchelementexception.class); fluentwait.until(expectedconditions.elementtobeclickable(driver.findelement(by.classname("next")))); driver.findelement(by.classname("next")).click();

here failure happens looking element in wait call:

org.openqa.selenium.nosuchelementexception: unable locate element: {"method":"class name","selector":"next"} command duration or timeout: 1.33 seconds documentation on error, please visit: http://seleniumhq.org/exceptions/no_such_element.html build info: version: '2.41.0', revision: '3192d8a', time: '2014-03-27 17:17:32' scheme info: host: '7rzrgv1.bsolver.local', ip: '10.0.3.103', os.name: 'linux', os.arch: 'amd64', os.version: '2.6.32-431.el6.x86_64', java.version: '1.7.0_60' session id: 56c5a752-68fd-4cdb-ae57-2fcefc930f6f driver info: org.openqa.selenium.firefox.firefoxdriver capabilities [{platform=linux, acceptsslcerts=true, javascriptenabled=true, cssselectorsenabled=true, databaseenabled=true, browsername=firefox, handlesalerts=true, browserconnectionenabled=true, webstorageenabled=true, nativeevents=false, rotatable=false, locationcontextenabled=true, applicationcacheenabled=true, takesscreenshot=true, version=24.6.0}]

if replace fluentwait.until phone call thread.sleep(5000), click() works every time.

an interesting note... occurs when running test on headless machine running firefox on top of xvfb. doesn't occur when actual gui present.

so, couple of questions:

why fluentwait not ignoring nosuchelementexception?

does have thoughts on more elegant way deal other implicit wait?

i had same problem. @karna , @axl helped me figure out. using import java.util.nosuchelementexception; instead of import org.openqa.selenium.nosuchelementexception;.

java selenium selenium-webdriver

Estimate RBF SVM training time in Matlab -



Estimate RBF SVM training time in Matlab -

i coded smo algorithm in matlab myself. evaluate time take train. dataset 7000 samples , 1000 features c = 10, epsilon=0.1, teta(rbf)=0.1

my cpu i3 3.3ghz , ram 8go.

i started training there 1 day , not finished yet.

i coded viola jones algorithm takes weeks learn, wanted know if same thing svm.

matlab time svm smo

db2 - Multiple query with iDB2DataAdapter -



db2 - Multiple query with iDB2DataAdapter -

i trying run multiple statements in idb2dataadapter , not know separator utilize between sql query statements or if can run multiple statements sql server.

using scheme inavigator (sql server management studio db2) "run sql scripts" functionality (query analyzer), can run multiple query statements when separate them semicolon ";". not work idb2dataadapter.

if terminate first command ";", returns error:"sql0104 token ; not valid. valid tokens: ."

replacing ";" "end-of-statement" returns error:"sql0199 keyword end not expected. valid tokens: utilize skip wait fetch order union except optimize."

putting "begin" , "end' around statements did not help.

any suggestions appreciated. thanks, mike

db2 dataadapter

MySql how to show zero when no value found -



MySql how to show zero when no value found -

i've got query:

select ent_video_tipo, count(ent_video_tipo) cnt entradas entradas.ent_user= '1' grouping ent_video_tipo order cnt desc

and give me:

ent_video_tipo|cnt 3 | 3 1 | 3 4 | 1 2 | 1

when

select ent_video_tipo, count(ent_video_tipo) cnt entradas entradas.ent_user= '2' grouping ent_video_tipo order cnt desc

i

ent_video_tipo|cnt 1 | 4 2 | 2 3 | 2

and wanted receive 0 ent_video_tipo = 4. this

ent_video_tipo|cnt 1 | 4 2 | 2 3 | 2 4 | 0

ent_video_tipo has own table:

type_id|type_name 1 | 2 | b 3 | c 4 | d

ok since ent_video_tipo has own type can utilize left bring together as

select evt.type_id, coalesce(count(e.ent_video_tipo),0) cnt ent_video_tipo evt left bring together entradas e on e.ent_video_tipo = evt.type_id , e.ent_user= '2' grouping evt.type_id order cnt desc ;

demo

update way of doing it

select evt.type_id, coalesce(cnt,0) cnt ent_video_tipo evt left bring together ( select ent_video_tipo, count(ent_video_tipo) cnt entradas ent_user= '2' grouping ent_video_tipo )e on e.ent_video_tipo = evt.type_id

demo

mysql

Android: Trouble with FragmentStatePagerAdapter -



Android: Trouble with FragmentStatePagerAdapter -

i'm new android development , have been trying create application allows users flip either left or right alter fragments. i'm using fragmentstatepageradapter this.

i first, in loop, created each fragment separately in main activity's oncreate() method , added them fragmentmanager fmanager.

for(day day: days){ screenslidepagefragment fragment = new screenslidepagefragment(); this.fmanager.begintransaction().add(r.id.pager, fragment).commit(); } fmanager.executependingtransactions();

i set ui elements , set viewpager's adapter so

this.setupui(); mpager.setadapter(mpageradapter);

the problem is maintain encountering exception java.lang.illegalstateexception: fragment added...

i confused going on because place add together fragments fragmentmanager in for-loop above. fragmentstatepageradapter's in background might cause issue or not implementing screenslidepageradapter correctly?

here code screenslidepageradapter class:

private class screenslidepageradapter extends fragmentstatepageradapter { public fragmentmanager fm; public screenslidepageradapter(fragmentmanager fm) { super(fm); this.fm = fm; } @override public fragment getitem(int position) { fragment f = fm.getfragments().get(position); homecoming f; } @override public int getcount() { homecoming fm.getfragments().size(); } }

input appreciated.

you show create fragments within getitem(pos) method of adapter. adapter internally utilize fragmentmanager provide in constructor. this:

@override public fragment getitem(int position) { fragment f = new screenslidepagefragment(); homecoming f; }

android

c++ - Using local variable assigned to return value of a function or using function directly -



c++ - Using local variable assigned to return value of a function or using function directly -

is there difference between this:

myclass c = getmyclass(); calculate(c.value);

and this:

calculate(getmyclass().value);

in scope of performance , memory allocation?

yes, there serious difference. in first case, c lvalue, , not destroyed until end of scope. can delay useful things reosurce cleanup. more problematically, beingness lvalue means cannot moved, must copied, inefficient many classes downright illegal of import classes, unique_ptr.

in sec case, compiler cleans temporary right away, resources released promptly, , beingness rvalue gives compiler more freedom optimize , permits move semantics.

this still true when value fellow member or fellow member function, result of both can inherit value category parent object.

you should scope objects minimum scope required, , if don't need access c later, should utilize temporary.

c++ performance compiler-construction

ruby on rails - Use Regexp to replace optional match between charaters -



ruby on rails - Use Regexp to replace optional match between charaters -

i'm trying replace html entity blank space actual space between occurrences of {{ , }}

example example

"this &nbsp;&nbsp;&nbsp; gap {{ &nbsp;for user in&nbsp;users&nbsp;}}" => "this &nbsp;&nbsp;&nbsp; gap {{ user in users }}"

i've found answers similar had led me write (which doesn't work)

.gsub(/(?<=\{\{).*(&nbsp;?).*(?=\}\})/,' ')

any help such regex appreciated thanks!

single phone call gsub using \k , \g

it's bit tricky, in ruby 2.0+, can compact regex \k , \g tokens. utilize regex , replace space:

[^{}]*\k(?:{{|\g).*?\k&nbsp;(?=[^{]*})

see demo.

in ruby:

result = subject.gsub(/[^{}]*\k(?:{{|\g).*?\k&nbsp;(?=[^{]*})/, ' ')

explanation

[^{}]* matches chars not braces \k tells engine drop matched (?:{{|\g) either matches opening curlies or asserts positioned after lastly match .*?\k lazily matches chars (and drops them), to... &nbsp; our match! which, lookakead (?=[^{]*}) asserts, must followed chars not opening brace before meeting closing brace

ruby-on-rails regex

javascript - disable checkbox if input value is zero -



javascript - disable checkbox if input value is zero -

i have list of check-boxes created dynamically , there input field each check box want disable check box if input field value zero. below code

html code

<input class="check" id="check" name="check" type="checkbox"><label for="check">checkbox <input type="hidden" id="test" value="0" /></label> <input class="check" id="check1" name="check1" type="checkbox"><label for="check1">checkbox1 <input type="hidden" id="test" value="6" /></label>

jquery

if($("#test").val() == "0"){ $('.check').attr("disabled", "disabled"); }

jsfiddle

you used twice id=test , javascript works first of them.

change id=test class=test, or works 2 differents ids.

working code:

$('.test').each(function() { if ($(this).val() == '0') { $(this).parent().prev().attr('disabled', 'disabled'); } });

http://jsfiddle.net/cdd5l/

javascript jquery html

How do I set a cursor css for text inside li element? -



How do I set a cursor css for text inside li element? -

how set cursor css text within li element?

the cursor arrow when on li, outside of text inside. when move text turns text cursor. want cursor remain same time.

li { cursor:default; }

jsfiddle example

you can see various cursor options @ https://developer.mozilla.org/en-us/docs/web/css/cursor

css

jQuery & CSS: how to convert this drawer menu from left to right? -



jQuery & CSS: how to convert this drawer menu from left to right? -

it's simple jquery drawer menu uses toggle feature i've never worked 3d translations i'm unsure of how adjust menu slide right side instead of left.

http://jsfiddle.net/mhgsr/

#site-wrapper { overflow:hidden; position:relative; width:100%; height:100%; } #site-canvas { position:relative; width:100%; height:100%; -webkit-transform:translatex(0); transform:translatex(0); -webkit-transform:translate3d(0,0,0); transform:translate3d(0,0,0); -webkit-transition:300ms ease all; transition:300ms ease all; -webkit-backface-visibility:hidden; backface-visibility:hidden; } .show-nav #site-canvas { -webkit-transform:translatex(300px); transform:translatex(300px); -webkit-transform:translate3d(300px,0,0); transform:translate3d(300px,0,0); } #site-menu { width:300px; height:100%; position:absolute; top:0; left:-300px; box-sizing:border-box; -webkit-box-sizing:border-box; -moz-box-sizing:border-box; background:#428bca; padding:15px; }

just add together text-align: right; #site-wrapper , reverse 300px values have set.

demo http://jsfiddle.net/mhgsr/1/

jquery css

vb.net - How to copy .exe from output directory on project/solution build automatically in Visual Studio -



vb.net - How to copy .exe from output directory on project/solution build automatically in Visual Studio -

so looking @ post, vs2010 how include files in project, re-create them build output directory automatically during build or publish.

this seems pretty close looking do, want have .exe built copied sec output directory.

to help explain, when build/rebuild project/solution .exe's set in

[somepath]\projects\[nameofsolution]\[nameofproject]\bin\release\outputfile.exe

what have visual studio automatically create re-create of outputfile.exe other directory, server share on network have read/write access to. grab server share not available since write code on traveling laptop. need have sort of logic check guess...

i don't know begin; if it's possible in visual studio. tried looking post-build actions in project settings, have no thought in dialog box. tried googling how it, since don't know how explain want well, google results useless.

this in fact duplicate of copy file(s) 1 project using post build event...vs2010

like said, didn't know how explain wanted, when searched didn't find relevant results.

in case comes question via google search in future, next post-build event command worked me (has on 1 line):

if $(configurationname) == release re-create /b /y /v "$(targetpath)" "\\some\path\to\file\share\$(targetfilename)"

vb.net visual-studio visual-studio-2012 build

subscription - Paypal option for vbulletin - Sorry — your last action could not be completed -



subscription - Paypal option for vbulletin - Sorry — your last action could not be completed -

i'm setting vbulleitn 5 forum very high traffic website. ready launch testing getting error paypal. happens me when paypal prompts me credit card info or sign in. when sign in, this

<input type="hidden" value="_xclick-subscriptions" name="cmd"></input> <input type="hidden" value="mybiz@emailaccount.com" name="business"></input> <input type="hidden" value="paid user subscription" name="item_name"></input> <input type="hidden" value="4c771001a64b035f5267958784d91112" name="item_number"></input> <input type="hidden" value="usd" name="currency_code"></input> <input type="hidden" value="" name="charset"></input> <input type="hidden" value="23.95" name="a3"></input> <input type="hidden" value="1" name="p3"></input> <input type="hidden" value="y" name="t3"></input> <input type="hidden" value="1" name="src"></input> <input type="hidden" value="1" name="sra"></input> <input type="hidden" value="2" name="no_shipping"></input> <input type="hidden" value="0.00" name="shipping"></input> <input type="hidden" value="https://mysitedomain.com" name="return"></input> <input type="hidden" value="https://mysitedomain.com" name="cancel_return"></input> <input type="hidden" value="https://mysitedomain.com/core/payment_gateway.php?method=paypal" name="notify_url"></input> <input type="hidden" value="pptest" name="custom"></input> <input type="hidden" value="1" name="no_note"></input> <input type="hidden" value="0.00" name="tax"></input>

paypal subscription vbulletin

actionscript 3 - Loop only showing the last array element ActionScript3 -



actionscript 3 - Loop only showing the last array element ActionScript3 -

this actionscript3 code made 2 text fields , assign them textformats, , 2 array. want value of array in new text field each iteration of loop.but showing lastly element value of array.i think there problem y position.thanks in advance.

var heading:array = ["home","about","services","contact"]; var subheading:array = ["mydata","aboutus","servicesprovided","contactus"]; var i:int = 0; var j:int = 0; var headformat:textformat = new textformat(); headformat.size = 20; headformat.color = 0xffffff; headformat.align = textformatalign.center; var subformat:textformat = new textformat(); subformat.size = 15; subformat.color = 0x000000; subformat.align = textformatalign.center; var headtext:textfield = new textfield(); headtext.width = 200; headtext.text headtext.height = 50; headtext.background = true; headtext.defaulttextformat = headformat; headtext.backgroundcolor = 0x0000ff; var subtext:textfield = new textfield(); subtext.width = 200; subtext.height = 50; subtext.background = true; subtext.backgroundcolor = 0xcccccc; subtext.defaulttextformat = subformat; for(i=0;i<heading.length;i++) { headtext.text = heading[i]; headtext.y = j; addchild(headtext); j+= 60; subtext.text = subheading[i]; subtext.y = j; addchild(subtext); j+=60; }

the problem utilize same instance of text boxes set creation of text boxes loop, each iteration create instance of text box.

var headtext:textfield; var subtext:textfield; for(i=0;i<heading.length;i++) { headtext = new textfield(); headtext.width = 200; headtext.text headtext.height = 50; headtext.background = true; headtext.defaulttextformat = headformat; headtext.backgroundcolor = 0x0000ff; subtext = new textfield(); subtext.width = 200; subtext.height = 50; subtext.background = true; subtext.backgroundcolor = 0xcccccc; subtext.defaulttextformat = subformat; headtext.text = heading[i]; headtext.y = j; addchild(headtext); j+= 60; subtext.text = subheading[i]; subtext.y = j; addchild(subtext); j+=60; }

actionscript-3

ios - How to use "context" in " observeValueForKeyPath:ofObject:change:context:" -



ios - How to use "context" in " observeValueForKeyPath:ofObject:change:context:" -

having read kvo guide, kvc guide, kvo protocol ref, have never seen solid illustration on how/when utilize lastly parameter of observevalueforkeypath:ofobject:change:context:

the description on "context" vague in apple's document, examples through kvo/kvc!

can point out me? many thanks!!!

ios key-value-observing

ruby on rails - How render body content without sidebar and header in rails4 app? -



ruby on rails - How render body content without sidebar and header in rails4 app? -

i'm developing rails application, have sidebar treeview, main content crud forms , header of page.

but when click new, or create, or show, rails reload page.

what can render yield without sidebar , header of page? ( e.g. treeview collapse when go 1 page other page ).

layout

you'll best reading on layouts within rails -

every time application loads view, wrap layout - way define how application looks

i recommend looking @ app/views/layouts/application.html.erb - default / standard layout application, , sidebar & other layout elements reside

--

options

the selection have either utilize conditions determine aspects of layout, or utilize other layouts determine different look

to set other layouts, can this:

#app/controllers/your_controller.rb class yourcontroller < applicationcontroller def action layout "form" #-> utilize app/views/layouts/form.html.erb end end

ruby-on-rails layout rendering partial-views

javascript - Django / jQuery - Button to update a value on each row of a table -



javascript - Django / jQuery - Button to update a value on each row of a table -

i learning django, making app can maintain track of books boolean whether have read them or not learning project. model relatively self explanatory books have title , id , boolean completed "field". want have page lists books , has button next each book alter read status true , update using ajax/jquery (and similar unread button mistakes). having problem getting button work. think need somehow assign sort of id each row jquery knows item working with.

apologies obvious errors. new web programming , regret having inquire help, have been trying work out solution myself few days now.

here django template snippet:

{% book in lib_dict.books %} <tr> <td>{{ book.title }}</td> <td>{{ book.date_due }}</td> <td id="book_completed_{{ book.id }}">{{ book.completed }}</td> <td> <button id="{{ book.id }}" data-bookid="{{ book.id }}" class="btn-mini btn-primary c" type="button">complete</button> </td> </tr> {% endfor %}

views.py:

def complete_book(request): context = requestcontext(request) book_id = none if request.method == 'get': book_id = request.get['book_id'] if book_id: book = book.objects.get(id=int(book_id)) if book: book.completed = true book.save() homecoming httpresponse(book.completed)

jquery code - imagine error(s) here

$('.btn-mini btn-primary c').click(function(){ var bookid; bookid = $(this).attr("data-bookid"); $.get('/libco/complete_book/', {book_id: bookid}, function(data){ var bookstring = '#book_completed_' + bookid; $(bookstring).html(data); \\trying update completed table cell $('#bookid').hide(); \\trying hide button }); });

please note, of connectivity works fine. if create button single row dedicated id, , utilize appropriate #-tag in first line of jquery works, having problem generalization. maybe "." thing isn't way class in first line?

also, much trying teach myself, if there resources kind of thing please allow me know. started working on official jquery tutorial, looked through , nil seemed related this.

thanks all!

change this:

$('.btn-mini btn-primary c')

to:

$('.btn-mini.btn-primary.c')

javascript jquery django

security - Is Storing User Input in a PHP Serialized Array Secure? -



security - Is Storing User Input in a PHP Serialized Array Secure? -

i'm taking user input , writing array:

$array = ( 'name'=>$_get['some name'], 'text'=>$_get['some text'] );

i'm storing data:

file_put_contents($myfile,serialize($array));

i'm wondering, since text , name user generated, type of security issues i'm looking @ here.

if write access file limited script - it's safe that.

php security serialization

Calculate alphanumeric string to an integer in Excel -



Calculate alphanumeric string to an integer in Excel -

i have issue i've not been able figure out many of ideas presented in other posts. info comes in excel , here examples of each manner given cell might have data:

4days 4hrs 41mins 29seconds 23hrs 43mins 4seconds 2hrs 2mins 52mins 16seconds

the end result calculate total minutes while allowing seconds ignored, previous values end follows:

6041 52 1423 122

would have thought how go that?

thanks assistance!

bit tedious (and assumes units plural - produces results in different order example) but, formulae only, if info in column a, in b1 , copied down:

="="&substitute(substitute(substitute(substitute(substitute(a1,"days","*1440+"),"hrs","*60+"),"mins","*1+"),"seconds","*0")," ","")&0

then re-create b , paste special values c , apply text columns c tab delimiter.

string excel excel-vba time excel-formula

javascript - Why is window.open prepending a default url? -



javascript - Why is window.open prepending a default url? -

code

<a href="www.someurl.com" id="equipment_url_readonly">www.someurl.com</a> $(document).on('click','#equipment_url_readonly', function(event) { event.preventdefault(); var url = $(this).attr('href'); console.log(url); //it console logs correctly url window.open(url,"_blank"); });

but whenever click on anchor tag, prepends url of parent, illustration current page has url www.mycurrentpage.com/this-page. when click on link, opens new window url of:

www.mycurrentpage.com/this-page/www.someurl.com

any thought how happened?

as mentioned in comments, problem anchor doesn't contain absolute url because misses protocol (i.e. "http://" or "//").

this should prepare it:

<a href="//www.someurl.com" id="equipment_url_readonly">www.someurl.com</a>

the above work both secure , non-secure pages.

javascript jquery html

c# - Position DataGridViewComboBoxColumn's position -



c# - Position DataGridViewComboBoxColumn's position -

i ask, how place datagridviewcomboboxcolumn's specific column? generated datagridviewcomboboxcolumn positioned on lastly column.

datagridviewcomboboxcolumn cmb = new datagridviewcomboboxcolumn(); cmb.headertext = "select data"; cmb.name = "cmb"; cmb. //cmb.maxdropdownitems = 4; (listitem = 0; listitem < dtlstitem.rows.count; listitem++) { cmb.items.add(dtlstitem.rows[listitem][1]); } dtgpo.columns.add(cmb);

use displayindex property

gets or sets display order of column relative displayed columns.

cmb.displayindex = 0; //first column

c#

linux kernel - Can unix sockets be accessed without using __sock_recvmsg? -



linux kernel - Can unix sockets be accessed without using __sock_recvmsg? -

i'm trying debug interaction between driver , user programme talks each other using unix socket. question is: "is method __sock_recvmsg (in net/socket.c) way info received socket or there other methods in kernel read info socket?"

the reply found kinda... if socket normal unix socket output must go through __sock_recvmsg possible alter function called socket when receiving message it's not normal unix socket.

sockets linux-kernel kernel unix-socket

c# - How to store values in SignalR State Variables -



c# - How to store values in SignalR State Variables -

i'm using onconnected , ondisconected maintain trap of users , cut down memory.

my problem can't assign variables in signalr. i'm using next code.

when read clients.caller.userid it's null. can read fine after assign xxsameprocess variable not null.

is there i'm missing?

public override system.threading.tasks.task onconnected() { var user = createuser(); clients.caller.userid = user.userid; object xxsameprocess = clients.caller.userid; homecoming base.onconnected(); } public override system.threading.tasks.task ondisconnected() { object xx = clients.caller.userid; createdelete( clients.caller.userid ); homecoming base.onconnected(); }

on side, store variable client when connects

<script src="~/signalr/hubs"></script> <script type="text/javascript"> (function ($) { //some stuff $.connection.hub.qs = { 'uid': '@guid' }; $.connection.hub.start(); })(jquery); </script>

the, can access server query strings

public override task onconnected() { var uid = context.querystring["uid"]; //some stuff homecoming base.onconnected(); } public override task ondisconnected() { var uid = context.querystring["uid"]; //some stuff homecoming base.ondisconnected(); } public override task onreconnected() { var uid = context.querystring["uid"]; //some stuff homecoming base.onreconnected(); }

c# signalr

javascript - Safely parsing and evaluating user input -



javascript - Safely parsing and evaluating user input -

i'm working on project that's templating domain-specific language. in project, take lines of user input in next form:

'{{index(1, 5)}}' '{{firstname()}} x. {{lastname()}}' '{{floating(-0.5, 0.5)}}' '{{text(5, "words")}}'

any command between double curly braces ({{ }}) has corresponding javascript method should called when command encountered. (for example, function index(min, max) {...} in case of first one).

i'm having hard time figuring out how safely take input , phone call appropriate function. know way i'm doing isn't safe. eval() between 2 sets of curly braces.

how can parse these input strings such can flexibly match function phone call between curly braces , execute function parameters given, while still not blindly calling eval() code?

i've considered making mapping (if command index(), phone call function index() {}), doesn't seem flexible; how collect , pass parameters (e.g. {{index(2, 5)}}) if present?

this written in node.js.

this problem breaks downwards into:

parsing string

evaluating resulting function graph

dispatching each function (as part of #2 above)

parsing string

unfortunately, requirements have, parsing {{...}} string quite complex. have @ to the lowest degree these issues deal with:

functions can nested {{function1(function2(), 2, 3)}}.

strings can contain (escaped) quotes, , can contain commas, without requirement #1 above trivial approach finding discrete arguments (splitting on comma) won't work.

so...you need proper parser. seek cobble 1 advertisement hoc, parser generators come picture, peg.js or jison (those examples, not recommendations — did happen notice 1 of jison examples json parser, half battle). writing parser out of scope answering question on i'm afraid. :-)

evaluating resulting function graph

depending on tool use, parser generator may handle you. (i'm pretty sure peg.js , jison both would, instance.)

if not, after parsing you'll presumably end object graph of sort, gives functions , arguments (which might functions arguments...which might be...).

functiona 1 "two" functionb "a" functionc 42 functiond 27

functiona there has 5 arguments, 3rd of functionb 2 arguments, , on.

your next task, then, evaluate functions deepest first (and @ same depth, left-to-right) , replace them in relevant arguments list result, you'll need depth-first traversal algorithm. deepest first , left-to-right (top-to-bottom in bullet list above) mean in list above, have phone call functionc first, functionb, functiond, , functiona.

dispatching each function

depending 1 time again on tool use, may handle bit too. 1 time again suspect peg.js does, , wouldn't surprised if jison did well.

at point you're ready phone call function (no longer) has function calls arguments, you'll presumably have function name , array of arguments. assuming store functions in map:

var functions = { index: function() { /* ... */ }, firstname: function() { /* ... */ }, // ... };

...calling them easy bit:

functionresult = functions[functionname].apply(undefined, functionarguments);

i'm sorry not able "just x, , you're there," isn't trivial problem. throw tools @ it, wouldn't invent wheel myself.

javascript node.js parsing eval

javascript - Font colors set in a textarea created by wp_editor does not stay across updates (but stays correct in database) -



javascript - Font colors set in a textarea created by wp_editor does not stay across updates (but stays correct in database) -

i created meta boxes utilize wp_editor create rich-text fields (which retrieved via wordpress' get_metadata(). when utilize tinymce buttons create word specific color, saves , shows on website color. but when go page editor again, shows in tinymce box black and if click update, makes text show black on website. why not saving color information?

wp_editor( $savedvalue, "mytextbox", array( "wpautop" => false, "media_buttons" => false, "textarea_rows" => 5, "quicktags" => true, "tinymce" => array( "height" => 250 ) ) );

when form submitted, in javascript if check value shows word tags:

<span style="color: #00ffcc">word</span>

but after it's been updated , reloaded tinymce box, it's just:

<span>word</span>

some wordpress code removing quotation marks.

javascript php wordpress tinymce

javascript - AngularJS Animation -



javascript - AngularJS Animation -

i trying implement angular js animations when view changes in app. reason can no animation @ all.

here app.js:

var myapp = angular.module('myapp', [ 'ngroute', 'nganimate', 'categorycontrollers' ]); //--------------------controllers----------------------------// var categorycontrollers = angular.module('categorycontrollers', []); categorycontrollers.controller('datacontroller', ['$scope', '$http','$routeparams', function($scope, $http, $routeparams) { $http.get('json/data.json').success(function(data) { $scope.project = data; $scope.currentcat = $routeparams.cat; $scope.currentex = $routeparams.exid; }); }]); //---------------------routing----------------------------// myapp.config(['$routeprovider', function($routeprovider) { $routeprovider .when('/list', { templateurl: 'partials/list.html', controller: 'datacontroller' }) .when('/splash', { templateurl: 'partials/splash.html', controller: 'datacontroller' }) .when('/:cat', { templateurl: 'partials/details.html', controller: 'datacontroller' }); }]);

and css:

.animate-enter, .animate-leave { -webkit-transition: 300ms cubic-bezier(0.250, 0.250, 0.750, 0.750) all; -moz-transition: 300ms cubic-bezier(0.250, 0.250, 0.750, 0.750) all; -ms-transition: 300ms cubic-bezier(0.250, 0.250, 0.750, 0.750) all; -o-transition: 300ms cubic-bezier(0.250, 0.250, 0.750, 0.750) all; transition: 300ms cubic-bezier(0.250, 0.250, 0.750, 0.750) all; } .animate-enter { left: 100%; } .animate-enter.animate-enter-active { left: 0; } .animate-leave { left: 0; } .animate-leave.animate-leave-active{ left: -100%; }

and how implemented in html, implemented in index.html opposed partials.

<script src="lib/angular/angular-animate.min.js"></script> <script src="js/app.js"></script> <link rel="stylesheet" href="css/style.css"> </head> <body> <div class="animate" ng-view></div> </body> </html>

thanks help!

you should utilize ng-animate="'animate'" instead of class='animate'

javascript angularjs animation

struct array initialization in Swift -



struct array initialization in Swift -

continuing play around in swift , trying convert c world , have been stuck trying various syntax. have fixed info want initialize construction array. here's how wold in c can't figure out in swift rather maintain guessing i'll inquire know more. here's c code.

#include <stdio.h> typedef struct my_data { const char *company; const char *city; const char *state; float latitude; float longitude; } my_data; int main() { my_data data[2]={ { "joes crab shack", "miami", "fl", 30.316599, -119.050254}, { "jims crab shack", "los angeles", "ca", 35.316599, -112.050254} }; }

in swift can create similar struct...

struct my_data { var company = string(); var city = string(); var state = string(); var latitude:float; var longitude:float; }

now stuck in how declare , initialize fixed info doing in c. guessing simple , getting syntax right has baffled me. i'd maintain initialization style in similar format c since can extract , format info file.

one alternative might instead utilize array of tuples:

var info = array<(company: string, city: string, state: string, latitude: float, longitude: float)>()

now individual elements of tuple labeled , can accessed labels, if weren't used create instance of tuple in first place:

var datumone = ("mycompany", "mycity", "mystate", 40.2, 139.45) info += datumone println(data[0].state) // mystate info = [ ( "joes crab shack", "miami", "fl", 30.316599, -119.050254), ( "jims crab shack", "los angeles", "ca", 35.316599, -112.050254) ] println(data[1].company) // jims crab shack

however, doing doesn't give type goodness out of structure... in swift structures automatically what's called "member-wise initializer", requires initialize them so, using fellow member names argument labels (and in order in declared in structure):

var mydatum = mydata(company: "the company", city: "the city", state: "the state", latitude: 90.2, longitude: 140.44)

you able define own init() method structure, however, if you'd utilize initializer improve suited purpose.

so, give array of structures using default member-wise initializer you'd do:

let allmydata = [ mydata(company: "jims crab shack", city: "los angeles", state: "ca", latitude: 35.316599, longitude: -112.050254), mydata(company: "joes crab shack", city: "miami", state: "fl", latitude: 30.316599, longitude: -119.050254) ]

swift

javascript - Representing Points on a Circular Radar Math approach -



javascript - Representing Points on a Circular Radar Math approach -

i coding simple app can show friends around you, not in normal map on circular radar ui:

(http://i.imgur.com/9epw0xh.png)

like this, have every users latitude, longitude, , of course of study own beingness center.

i measure distance of every user position them info know lat, longitude , distance me.

for mathematical reasons let's radar 100 pixels radius, can distance them distance me using left or right positioning, in terms of top or bottom gets litte trickier, since seek convert latitude - latitude percentual result , set them on radar... think there maybe improve ways polar cartesian coordinates, im kinda clueless.

is there best approach these types of interfaces or implemented around there?

convert long,lat of points cartesian 3d space coordinates

it conversion spherical -> cartesian 3d space. math behind here. after points (long,lat,alt) became (x,y,z) (0,0,0) center of earth

x axis lat=0,long=0 [rad] y axis lat=0,long=+pi/2 [rad] z axis north xy plane equator

if want more precision handle earth ellipsoid instead of sphere

long = < 0 , +2*pi > [rad] lat = < -pi/2 , +pi/2 > [rad] alt = height above sea level [m] re =6378141.4; [m] rp =6356755.0; [m] r=alt+sqrt( (re*cos(lat))^2 + (rp*sin(lat))^2 ) x=r*cos(lat)*cos(long) y=r*cos(lat)*sin(long) z=r*sin(lat)

create radar local cartesian coordinate system

basically need obtain 3d vectors x,y,z axises. must perpendicular each other , pointing right direction radar origin point (p0).

you can utilize vector multiplication because creates perpendicular vector multiplicants. direction dependent on order of multiplicants experiment little.

//altitude 1 easy z = p0 //north (chose 1 non zero, resp. bigger avoid accuracy problems) x = (1,0,0) x z // old x axis * height x = (0,1,0) x z // old y axis * height //east easy y = x x z // normalize of them unit vectors x = x / |x| y = y / |y| z = z / |z| // , check if not negative (x,y) // if swap multiplicants or multiply -1 // not forget x computed 2 methods swap right 1 here math behind constructing 4x4 transform matrix here can see on image difference between homogenous 4x4 , direct 3x3 3d transform matrices , math

convert points radar coordinate system

just multiply points radar transform matrix m

q(i) = p(i)*m

so points q(i) local radar

(0,0,0) means radar origin (center) (1,0,0) points north (0,1,0) points east (0,0,1) points up

so multiply cordinates radar scale

scale = radar_radius/radar_range; radar_radius size of radar on screen in pixels or units of coordinates radar_range max distance radar biggest circle represents [m]

after draw dot radar (swap x,y because utilize x north not y) , can discard points more distant range. can add together 3d radar in old elite adding z coordinate vertical axis (or draw l line)

hope helps little , not much confusing...

javascript google-maps math maps

javascript - Mutation Summary Library: How to append html elements to added elements -



javascript - Mutation Summary Library: How to append html elements to added elements -

i'm using mutation summary library observe when particular type of elements have been added , append html element each of them:

var observer = new mutationsummary({ callback: thenextpageloaded, queries: [{ element: "li.sweet" }] }); function thenextpageloaded(summaries) { var sc = summaries[0], sc_length = sc.added.length, btn = $('<button>', { class: 'my_btn', text: 'please work!' }); sc.added.foreach(function(newel) { newel.appendchild(btn); console.log(typeof(newel)); //newel's type 'object' }); }

code above not working. i'm not sure can utilize appendchild on object. help appreciated!

your problem mixing "bare" dom elements mutation summary response , jquery elements. pure dom appendchild not understand jquery-wrapped btn.

so, need create them both same type:

$(newel).append(btn); // jquery newel.appendchild(btn.get(0)); // pure dom

either works, first 1 more idiomatic.

javascript jquery google-chrome-extension mutation-observers

c++ - opencl kernel file not entirely loading -



c++ - opencl kernel file not entirely loading -

once opencl kernel file exceeds length, not correctly loaded anymore. programme build log (clbuildprogram) returns lots of errors, seems there cuts in middle of line (example int test; -> error unknown identifier 't').

here function load programme source:

char * load_program_source(const char *filename) { file *fh; char* source; long lsize; fh = fopen(filename, "r"); if (fh == 0) homecoming 0; //get filesize fseek(fh,0,seek_end); lsize = ftell(fh); rewind(fh); source = (char *) malloc(lsize); memset(source,'\0',lsize); fread(source, sizeof(char), lsize, fh); homecoming source; }

and here code programme build:

//load programme file, compile kernels cl_program program[1]; cl_kernel kernel[13]; const char * filename = "addkernel.c"; char *program_source = load_program_source(filename); program[0] = clcreateprogramwithsource(context, 1, (const char**)&program_source, null, &err); if (err == cl_out_of_host_memory){ textbox1->text += "error: out of host memory!\r\n"; } else if (err == cl_invalid_context){ textbox1->text += "error: invalid context!\r\n"; } else if (err == cl_invalid_value){ textbox1->text += "error: invalid value!\r\n"; } err = clbuildprogram(program[0], 0, null, null, null, null); textbox1->text += "program build error: " + err + "\r\n"; cl_build_status status; size_t logsize; clgetprogrambuildinfo(program[0], deviceid[0], cl_program_build_status, sizeof(cl_build_status), &status, null); clgetprogrambuildinfo(program[0], deviceid[0], cl_program_build_log, 0, null, &logsize); char* programlog; programlog = (char*)calloc(logsize + 1, sizeof(char)); clgetprogrambuildinfo(program[0], deviceid[0], cl_program_build_log, logsize + 1, programlog, null); std::string tmp = std::string(programlog); this->textbox1->text += "program build info: error=" + err + ", status=" + status + ", programlog:\r\n" + gcnew system::string(tmp.c_str()) + "\r\n" + "in case of error please create sure opencl has been initialized\r\n";

i happy if cound help me out!

try next code. if doesn't help, attach kernel source

file reading:

static char* read_source_file(const char *filename) { long int size = 0, res = 0; char *src = null; file *file = fopen(filename, "rb"); if (!file) homecoming null; if (fseek(file, 0, seek_end)) { fclose(file); homecoming null; } size = ftell(file); if (size == 0) { fclose(file); homecoming null; } rewind(file); src = (char *)calloc(size + 1, sizeof(char)); if (!src) { src = null; fclose(file); homecoming src; } res = fread(src, 1, sizeof(char) * size, file); if (res != sizeof(char) * size) { fclose(file); free(src); homecoming src; } src[size] = '\0'; /* null terminated */ fclose(file); homecoming src; }

programm building:

cl_int ret; programme = clcreateprogramwithsource( context, 1, (const char**)&src_file, null, &ret); if(ret != cl_success){ fprintf(stderr, "error code %d happened.\n", ret); } // warnings treated errors, useful debug char build_params[] = {"-werror"}; ret = clbuildprogram(program, 0, null, build_params, null, null); if (ret != cl_success) { size_t len = 0; char *buffer; clgetprogrambuildinfo(program, device_id, cl_program_build_log, 0, null, &len); buffer = calloc(len, sizeof(char)); clgetprogrambuildinfo(program, device_id, cl_program_build_log, len, buffer, null); fprintf(stderr, "%s\n", buffer); free(buffer); }

c++ winforms opencl