Posts

Showing posts from March, 2014

c++ - Can std::this_thread::sleep_for() have spurious wakeups? -

note, not question std::condition_variable::wait_for() . know can wake spuriously. my program’s behavior suggests answer question yes, stl documentation quite clear condition_variable case. @ least @ cppreference.com , correct answer this_thread appears no. compiler gcc 4.8.1, in case defect. the relevant sections of c++ standard (paragraphs [thread.thread.this]/7-9) not mention spurious wake-ups std::this_thread::sleep_for , unlike e.g. std::condition_variable::wait_for . template <class rep, class period> void sleep_for(const chrono::duration<rep, period>& rel_time); 7 effects : blocks calling thread relative timeout (30.2.4) specified rel_time . 8 synchronization : none. 9 throws : timeout-related exceptions (30.2.4). this implies behavior observing non-conforming.

c# - WCF ServerInspectorBehavior - How to keep a header in AfterReceiveRequest to use in BeforeSendReply -

i have wcf service have extended behavior. this code: public object afterreceiverequest(ref message request, iclientchannel channel, instancecontext instancecontext) { if (logger.isinfoenabled) { // header sent client need keep can return in beforesendreply var securitytoken = request.headers.getheader < string > (request.headers.findheader("token-id", "securityinfo")) var bufferedcopy = request.createbufferedcopy(int.maxvalue); var sizelog = string.format("request message size: ~{0} kb", getmessagelengthinkb(bufferedcopy.createmessage())); logger.info(sizelog); request = bufferedcopy.createmessage(); } return null; } public void beforesendreply(ref message reply, object correlationstate) { if (logger.isinfoenabled) { // here want securitytoken value ??? var bufferedcopy = reply.createbufferedcopy(int.maxvalue); var sizelog = string.format("r...

uml - 2 actors, same parent use case but each one having his own child use case -

i have parent use case child uses cases, example: parent use case: "selling subscriptions" child uses cases: "self buy subscription" "sell subscription else" etc my question is: correct have 2 different actors (customer , vendor) linked parent use case in top level use case diagram, each of them linked 1 child use case in more detailed use case diagram or there wrong ? the 2 actors should linked primary parent use case. then in detailed use case diagram can specific link secondary use cases. (if doesn't answer question please provide diagram want do)

css - Where should I divide a mobile-friendly website from it's android counterpart? -

i creating both mobile-friendly website , android app client. each have similar functionality , objectives. began create responsive pages website, thought occurred of using pages making webview menus android app. lead me thinking, android app needed @ all? my question what functionality can android app provide responsive website not? the purpose of app reading content(think ebook), sharing content others, , link buy physical book. believe reading content offline justification enough existence of app wondering else provide app can offer? my second question from design standpoint, should use webviews main menus , content? or should duplicate responsive pages android layouts/buttons.? webview based menus seems awkward, having use javascript run android functions. duplicating web pages android activities seems equally awkward. having webview apps not using native resources. means doesn't experience best of resources of apps. (it may lag little or doesn't cons...

vba - Access 2013 - Visual Basic issue -

i experiencing issue access 2013 while creating vba code button. button open form using: docmd.openform command implement while condition filters form going opened. i have 2 fields on current form with: - start date - end data the while condition must filter records column "date" between 2 given dates in previous form. this: where date >= me.begin_date.value , date <= me.eind_date.value i cant figure out use in while condition of vba code. can other things filters in vba like: search_filter = "itemid '*" & me.search_bar.value & "*' " docmd.openform "#3 search-result", acnormal, , search_filter but want have first code sample, translated vba code above piece of code. how can achieve this? sorry bad english btw. if recall correctly; generate query based on 2 values (in query builer do) forms!formname.recordsource = sql query ...

excel - Custom menu Passing a WorkSheet variable through .OnAction -

i have been using post guide pass variables until excel, vba: how pass multiple variables .onaction and has worked well. unfortunately, trying pass worksheet argument time, , not working. here block of code can take look. right click menu: menu.controls.add(temporary:=true, type:=msocontrolbutton, before:=i_menu) .begingroup = false ' ' ' ' ' ' .onaction = "'" & thisworkbook.name & "'!" & "'saute """ & num_doc & """,""" & num_etape & """'" .onaction = "'" & thisworkbook.name & "'!" & "'saute """ & num_doc & """,""" & num_etape & """,""" & ws & """'" .faceid = 478 .caption = "sauté" ...

java - ResourceNotFoundException on existing path -

i have following class: public class emailservice { static { velocity.setproperty("resource.loader", "class"); velocity.setproperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.classpathresourceloader"); velocity.init(); } public void sendterminalmoderationstatuschangedemail(terminal terminal, string to) { ... template subjecttemplate = null; try { subjecttemplate = velocity.gettemplate(existedpath, "utf-8"); } catch (urisyntaxexception e) { e.printstacktrace(); } ... } } in debug see existed path exists. got following error: unable find resource 'c:/program files (x86)/apache/apache-tomcat-7.0.52/webapps/root/web-inf/classes/velocitytemplates/terminalmoderationstatuschanged.vm' but file c:/program files (x86)/apache/apache-tomcat-7.0.52/webapps/root/web-inf/classes/velocityte...

Regex For International Email Addresses (Javascript) -

right now, trying international email addresses validate... right regex works charm email addresses: /^[_a-za-z0-9-]+(\.[_a-za-z0-9-]+)*@[a-za-z0-9-]+(\.[a-za-z0-9-]+)*(\.[a-za-z]{2,4})$/ however, international email address this: amartiñez@yahoo.com not pass validation. how can change above regex make pass? include spanish charset regex ^[_a-za-záéíñóúüÁÉÍÑÓÚÜ0-9-]+(\.[_a-za-záéíñóúüÁÉÍÑÓÚÜ0-9-]+)*@[a-za-z0-9-]+(\.[a-za-z0-9-]+)*(\.[a-za-z]{2,4})$ demo source: interesting character classes

c# - Know When Child Form Closed -

i've form1 button. when click button, code block executes: form2 frm = new form2(); frm.name = "form" + musterinumarasi.tostring(); frm.text = "kullanıcı - " + musterinumarasi.tostring(); lets i've clicked 3 times. there 4 forms now: main, child1, child2, child3. when user closes 1 of child forms, main form needs know 1 closed. how can that? subscribe closed event form2 frm = new form2(); frm.formclosed += new formclosedeventhandler(form_closed); void form_closed(object sender, formclosedeventargs e) { form2 frm = (form2)sender; messagebox.show(frm.name); }

multithreading - Android - IntentService runs on UI thread when called with bus event -

i'm having intentservice perform background request api. i'm using otto bus communicate it. public class myservice extends intentservice { private myapi mapi; private mybus mbus; myservice () { super("myservice "); } @subscribe public void onloadsearchdata(loadsearchdataevent event) { log.d("onloadsearchdata "+ thread.currentthread().getname()); mapi.loadsomedata(); } @override protected void onhandleintent(intent intent) { thread.currentthread().setname(getclass().getcanonicalname()); log.d("thread name " + thread.currentthread().getname()); if (mapi==null) mapi = new myapi(getapplicationcontext()); if (mbus==null) { mbus = mybus.getinstance(); mbus.register(this); } } } the onhandleintent performed on secondary thread, normal. when call onloadsearchdata bus event main ui, it runs on ui thread !!!! i do...

ruby on rails - How to install RVM on Xubuntu 14.04 -

i try install rvm using this tutorial. en error on step $ \curl -l https://get.rvm.io | bash -s stable --ruby . message: oleg@olegx301a:~$ \curl -l https://get.rvm.io | bash -s stable --ruby % total % received % xferd average speed time time time current dload upload total spent left speed 100 184 100 184 0 0 330 0 --:--:-- --:--:-- --:--:-- 331 100 22721 100 22721 0 0 30495 0 --:--:-- --:--:-- --:--:-- 30495 downloading https://github.com/rvm/rvm/archive/1.26.11.tar.gz downloading https://github.com/rvm/rvm/releases/download/1.26.11/1.26.11.tar.gz.asc gpg: signature made вт, 31-бер-2015 00:52:13 +0300 eest using rsa key id bf04ff17 gpg: can't check signature: public key not found warning, rvm 1.26.0 introduces signed releases , automated check of signatures when gpg software found. assuming trust michal papis import mpapis public key (downloading signatures). gpg signature verific...

python - Exception not called when using side_effect with mock -

i have function in class called "my_class" in module called "my_module" contains snippet: try: response = self.make_request_response(requests.post, data, endpoint_path) except requests.exceptions.httperror err: if err.response.status_code == requests.codes.conflict: logging.info('conflict error') and i'm trying test so: error = requests.exceptions.httperror(mock.mock(response=mock.mock(status_code=409)), 'not found') mock_bad = mock.mock(side_effect=error) mock_good = mock.mock() mock_good.return_value = [{'name': 'foo', 'id': 1}] upsert = my_module.my_class(some_data) mock.patch.object(upsert, 'make_request_response', side_effect=[mock_bad, mock_good]) mock_response: some_function() what expect httperror raised in test after patch it. however, when run test, exception never raised. "response" set mock_bad, contains desired exception, although it's never raised. idea i'm ...

php - Site isn't seeing the autoload -

i'm getting error: warning: require(/home/wiseman/public_html/path/to/facebook-php-sdk-v4/autoload.php): failed open stream: no such file or directory in /home/wiseman/public_html/facebook.php on line 3 fatal error: require(): failed opening required '/home/wiseman/public_html/path/to/facebook-php-sdk-v4/autoload.php' (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/wiseman/public_html/facebook.php on line 3 the sdk has been installed host server , can see autoload file in path it's looking for. know problem be? i'm new working facebook , green gentle! :)

python - Managed VM Background thread loses environment -

i having problems using background threads in managed vm in google app engine. i getting callbacks library linked via ctypes need executed in background explaining in previous question . the problem is: application loses execution context (wsgi application) , missing environment variables application id. without cannot make calls database fail. i call background thread like background_thread.start_new_background_thread(saveitemstodatabase, []) is there way copy environment background thread or maybe execute task in different context? update: traceback makes clear problem is: _todatastoreerror(err)google.appengine.api.datastore_errors.badrequesterror: application id (app) format invalid: '_' application context thread local in appengine when created through standard app handler. remember applications in appengine run in python27 thread enabled have threads. each wsgi call environment variables has thread local, or information leak between handled r...

php - How to limit item in the cart for each category in woocommerce -

hi have visual images, first click add-to-cart button, check validation of qty allowance each category, output error message on top of cart widget. how count product in each cateogy in cart woocommerce? in advance public function check_product_in_cart($product_in_cart) { //check see if user has product in cart global $woocommerce; // start of loop fetches cart items foreach ( $woocommerce->cart->get_cart() $cart_item_key => $values ) { $_product = $values['data']; $terms = get_the_terms( $_product->id, 'product_cat' ); // second level loop search, in case items have several categories // started editing guillaume's code $cat_ids = array(); foreach ($terms $term) { $cat_ids[] = $term->term_id; } if(in_array(70, (array)$cat_ids) ||in_array(69, (arr...

c# - Why are exceptions in a static constructor wrapped in TypeInitializationException -

the exception static constructor wrapped in typeinitializationexception. consider example below using system; namespace consoleapp { class program { static void main(string[] args) { try { new myclass(); } catch (exception e) { console.writeline(e.gettype().tostring()); } } public class myclass { static myclass() { throw new exception(); } } } } the output of program is system.typeinitializationexception what reasons wrapping exception in typeinitializationexception ? why original exception not returned ? what reasons wrapping exception in typeinitializationexception ? exceptions in static constructors difficult. basic issue execution context of exception vague. cli not give specific promise when constructor runs. guarantee run enough, how unspecified. so dooms-day scenario without exception being wrapped vague bug repor...

TFS 2013 Kanban Board: Show Custom Fields -

visual studio online allows change elements included on work item cards (custom fields, 'remaining work', etc.) on kanban board clicking on gear icon. using tfs 2013, , cannot find similar settings menu. can similar customization in tfs 2013? if so, please point me in right direction. by visual studio 2013 mean tfs 2013? if functionality isn't in tfs 2013. believe it's in tfs 2015 available release candidate.

sql - How to select a field based on the maximum number of rows -

i'm using laravel 4.2 , have following table looks id|chosen(boolean('0','1'))|subject|user_id 1|1 |cricket|2 2|0 |cricket|3 3|1 |rugby |2 i choose user_id has chosen rows or in other words user has 1s in chosen column. in case user 2 correct result. you can using query builder $table = db::table('table') ->select(array(db::raw('count(user_id) countuser'))) ->where('chosen', 1) ->orderby('countuser', 'desc') ->groupby('user_id') ->first();

Spring Security 4.0.1 Sample Contacts Deployment Issue -

i deploying contacts-xml.war jboss eap 6.4.0. deployment says started have error may not issue have. 12:03:55,612 info [org.springframework.jdbc.support.sqlerrorcodesfactory] (serverservice thread pool -- 162) sqlerrorcodes loaded: [db2, derby, h2, hsql, informix, ms-sql, mysql, oracle, postgresql, sybase, hana] 12:03:55,616 info [stdout] (serverservice thread pool -- 162) failed drop tables: statementcallback; bad sql grammar [drop table contacts]; nested exception java.sql.sqlsyntaxerrorexception: user lacks privilege or object not found: contacts in statement [drop table contacts] issue: unable access http://localhost:8080/contacts url. web.xml has correctly configured , gets deployed: 12:03:56,724 info [org.springframework.web.servlet.handler.simpleurlhandlermapping] (serverservice thread pool -- 162) mapped url path [/frames.htm] onto handler of type [class org.springframework.web.servlet.mvc.parameterizableviewcontroller] 12:03:56,739 info [org.springframework.we...

java - index.jsp not working, just shows source code on browser -

in spring mvc application, i'm trying pass list jsp page , show on table, index.jsp isn't rendered , shows source code on browser. here controller: package com.orantaj.controllers; import com.orantaj.service.eventservice; import org.springframework.beans.factory.annotation.autowired; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.restcontroller; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; @restcontroller public class indexcontroller { @autowired eventservice eventservice; @requestmapping(value = "/") public void setevents(httpservletrequest request, httpservletresponse response) { try { request.setattribute("basketballevents", eventservice.getbasketballevents()); request.getrequestdispatcher("index.jsp").forward(request, response); } catch (exception e) { e...

ios - NSRegularExpression change following text's color after a character -

i trying change character's color , text comes , using nsregularexpression character , have no idea how can change following characters example here text : ● title...... description xxxxxx x x x x x so in case need change ● character's color , following strings here code : nsregularexpression *regex2 = [nsregularexpression regularexpressionwithpattern:@"●" options:kniloptions error:nil]; [regex2 enumeratematchesinstring:puretext options:kniloptions range:range usingblock:^(nstextcheckingresult *result, nsmatchingflags flags, bool *stop) { nsrange substringrange = [result rangeatindex:0]; [stringtext addattribute:nsforegroundcolorattributename value:[uicolor orangecolor] range:substringrange]; }]; _textview.attributedtext = stringtext; this code finds , changes ● character's color . use regex ●.* match characters after dot before newline: nsregularexpression *regex2 = [nsregularexpression ...

recursion - How to write procedure that recursively outputs the number of odd digits in a natural number? (racket) -

if input number, how can write procedure checks every digit , produces output equal number of odd digits in number? i'm thinking turning number list first, i'm trying think of easier solution. also, we're not allowed use "odd?". instead of using "odd?" check whether or not digit odd, can use "quotient" rather convert string in marekful's comment, try recursively taking off significant digit @ time using mod operation. then, can use quotient function test odd or even.

javascript - Weird Moment.js format issue -

i'm not sure if moment.js issue, here is. date range widget, picked date time of '03-01-2015 12:00 - 04-30-2015 11:59 pm'. startdate , enddate, both moment objects, passed callback function seem correct based on first 2 lines output console.log. however, if create new moment instance based on startdate.valueof() , print out formatted date string again, new moment object displays different timestamp (one hour ahead.) here code snippet: this._daterangepicker = this.$('#datetimerange').daterangepicker({ timepicker : true, timepickerincrement : 1, format : 'mm/dd/yyyy hh:mm a' }, function(startdate, enddate, label) { let searchcontroller = self.get('controller'); console.log(`time picker date start ${startdate.format('mm-dd-yyyy hh:mm a')}`); console.log(`time picker date end ${enddate.format('mm-dd-yyyy hh:mm a')}`); console.log(`time picker reformat date start ${moment(startdate.valueof(...

c# - Regex not matching when input string contains an ampersand -

i trying come regex starts letter followed letters, spaces, commas, dots, ampersands, apostrophes , hyphens. however, ampersand character giving me headaches. whenever appears in input string, regex no longer matches. i using regex in asp.net project using c# in 'format' property of textinput (a custom control created in project). in it, using regex.ismatch(text, format) match it. for example, using regex: ^[a-za-z][a-za-z&.,'\- ]*$ the results are: john' william-david pass john, william'david allen--tony-'' pass john, william&david fail whenever put & in input string regex no longer matches, without works fine. how can fix issue? why ampersand causing problem? notes: i've tried escape ampersand ^[a-za-z][a-za-z\&.,'\- ]*$ has same issue i've tried put ampersand @ beginning or end o ^[a-za-z][&a-za-z.,'\- ]*$ or ^[a-za-z][a-za-z.,'\-\...

Deploying a git branch together with its submodule from Github to Heroku -

i in reference heroku's deployment github feature allows deploy github branch heroku. see: https://devcenter.heroku.com/articles/github-integration i know if can deploy github project includes git submodule? if necessary steps other running submodule command below on project? git submodule add git://github.com/whomsoever/whatever.git it seems have found answer question , unfortunately not seem possible achieve want i.e. deploy github repo uses submodules... to quote official heroku documentation ( https://devcenter.heroku.com/articles/github-integration#git-submodules ): github repos use submodules not deploy correctly on heroku. because github not include submodule contents when repo-content tarballs generated.

javascript - jQuery animate odd behavior IE/Safari -

i have code show , hide navbar @ top animation. it's working fine chrome , firefox, not versions of ie (11, example) , safari: nav slides down automatically slides (hides) in loop. i wonder if, solution in javascript, solved css. it's wordpress site. html: <nav class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="container"> <div class="row"> <div class="col-md-12"> <div id="navbar-header-container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> ...

Posting a Facebook Story causes two entries to appear in Activity Log -

i posting facebook story using open graph action , object. seems work great except when on activity log. seeing 2 entries, 1 expected one "<'name> <'action> <'noun> in <'game>" but seeing 1 don't expect "<'name> posted <'noun> in <'game>" i've tracked down , seems posted create open graph object using fb.api("/me/objects/<'game>:<'object>", facebook.httpmethod.post, createobjectcallback, oparams); which believe required create object used in story post. know how create object use in story post without having entry added activity log it? thanks!

c++ - Android cmake cannot find -lpthread -

i'm trying compile shared library using cmake. followed instruction on this tutorial change toolchain android ndk. however, i'm getting following output error: /home/usr/android-toolchain/bin/../lib/gcc/arm-linux-androideabi/4.9/../../../../arm-linux-androideabi/bin/ld: error: cannot find -lpthread collect2: error: ld returned 1 exit status make[2]: *** [../libs/armeabi-v7a/libutils.so] error 1 make[1]: *** [src/cmakefiles/utils.dir/all] error 2 make: *** [all] error 2 a bit of googling around , stumble upon this stackoverflow post. modified cmakelists.txt add: set(cmake_cxx_flags"-dhave_pthreads") but seems still doesn't work. going wrong way? thanks!

r - Rescale for NBA heatmap: dplyr equivalent to plyr function? -

there great example of how use ggplot2 create heat map 'r; way: rheatmap provides link raw data , source code. there followup using ggplot2: ggplot2 lays out ggplot2 code. at key points ggplot2 code uses reshape2 , plyr. nba.m <- melt(nba) nba.m <- ddply(nba.m, .(variable), transform,rescale = rescale(value)) my goal duplicate these calculations using tidyr , dplyr. nba.m <- melt(nba) has tidyr equivalent in: nba.g <- gather(nba, name) what dplyr equivalent line? nba.m <- ddply(nba.m, .(variable), transform,rescale = rescale(value)) eipi10 kindly suggested nba.m2 <- nba.m %>%group_by(name) %>% mutate(rescale=rescale(value)) however, looks rescale calculation not occuring in quite same way: > head(nba.m) name variable value rescale 1 dwyane wade g 79 0.9473684 2 lebron james g 81 0.9824561 3 kobe bryant g 82 1.0000000 4 dirk nowitzki g 81 0.9824561 5 danny granger...

C generic Parameter into Function pointer -

is possible in c(not c++) have fuction pointer takes generic value(not pointer), -pedantic , -wall -werror flags set. note: can't change parameter type. code has support uint8_t, uint16_t, etc... types parameters goal: solve problem code. question is there way typecast uint8_t(and/or uint16_t) parameter void*(approach1)? pass non-pointer type value void* value. is there way setup generic type work different values(approach 2)? last resort there way set specific compiler exception in code?( this question has been answer ) approach 1(causes invalid conversion uint8_t void*) typedef struct { void (*set_func)(void*); } setfunction; void setvalue(uint8_t bytevalue)//not pointer parameter { bytevalue++; } void setshortvalue(uint16_t bytevalue)//not pointer parameter { bytevalue++; } int main() { uint8_t = 123; uint16_t b = 321; setfunction pointerfuncion; setfunction pointerfuncionshort; //typecast setvalue appease compiler warning...

C# file not found in System32 when running in 32 bit -

i'm trying run quser , resulting string. when run code below, see following message the resulting string empty: 'quser' not recognized internal or external command, operable program or batch file. process p = new process(); p.startinfo.useshellexecute = false; p.startinfo.redirectstandardoutput = true; p.startinfo.filename = "cmd.exe"; p.startinfo.arguments = "/c quser /server:someserver"; p.start(); string output = p.standardoutput.readtoend(); p.waitforexit(); console.writeline(output); so full command gets run cmd.exe /c quser /ser:someserver which runs fine when directly, fails c#. i found similar question no answer here: executing quser windows command in c#; returning result string . question doesn't have quser not recognized message though. why command not recognized when running code? i tried running quser command directly so, file not found... strange process p = new process(); p.startinfo.useshellexecute = fal...

c++ - Dynamically construct tuple from vector -

this question has answer here: c++ : convert vector tuple 3 answers i've got interesting problem need dynamically create tuple vector number of type parameters of tuple equals length of vector. vector<int> v1 = {1,2,3}; tuple<int, int, int> t1 = create_tuple(v1); vector<int> v2 = {1,2}; tuple<int, int> t2 = create_tuple(v2); vector<int> v3 = {1}; tuple<int> t3 = create_tuple(v3); i'm guessing can done, if possible, @ compile time? of course can done @ compile-time: "members" of tuple baked type.

502 Bad Gateway for Large Requests (nginx + django) -

i have site running django nginx. running good, there sections 502 bad gateway. after bit of analysis, figure out pages ones large contents in them while loading. for example: have "college" app , "course" app. college can have many courses, if try edit college less 10 courses, works well, if try edit college more 10 courses, gives me 502 bad gateway. has happened such colleges. any kind of assist. have tried increasing server limits.

javascript - $scope.$apply() in angular working but throwing error -

i put isolated example in jsbin: http://jsbin.com/deqerelita/1/ scenario idea simple. click button, controller adds model, view gets updated accordingly hidden input type="file". after view updated, controller clicks last file input added. problem when controller clicks file input before running $scope.$apply() nothing happens till second click, presumably because angular has not registered new input yet. when run $scope.$apply() console throws errors click input. here html: <div ng-controller="filebuttons"> <input type="button" ng-click="handleimage.add()" value="add file button"/> <div class="imageuploadpreviewcontainer"> <div class="imageuploadpreview hide" data-ng-repeat="file in files" file-index="{{$index}}"> <input type="file" class="hide"/> </div> </div> </div...

php session issue in remove value from Cart Sessin Array -

i using yii framework , unable remove value session. when call function using ajax, error in console indirect modification of overloaded element of chttpsession has no effect any suggestion helpful in advance . below code public function actiondeleteproductajax() { $session = yii::app()->session; $id = isset($_post['id']) ? $_post['id'] : ""; $key = array_search($id, $session['cart_items']); if ($key !== false) { unset($session['cart_items'][$key]); echo 'success'; } } i want remove index of array because value containt similar ids of products added more 1 time try this: $cartitems = yii::app()->session['cart_items']; $id = isset($_post['id']) ? $_post['id'] : ""; $key = array_search($id, $cartitems); if ($key !== false) { unset($cartitems[$key]); echo 'success'; } yii::app()->session['cart_items'] = $cartite...

sql server - Login failure with error 18456 using Windows Groups -

i have application using ef connecting sql server 2008 express database , using windows authentication. if add login specific user, connects successfully. if add user new security group in active directory , create login group, connection database fails. error log says: 2015-05-29 15:45:53.59 logon error: 18456, severity: 14, state: 38. 2015-05-29 15:45:53.59 logon login failed user 'domain\test'. reason: failed open explicitly specified database. [client: 192.168.x.y] i've tried setting default database login , giving permissions on master database, can't work. i don't know how debug further.

javascript - React Js conditionally applying class attributes -

i want conditionally show , hide button group depending on passed in parent component looks this: <topicnav showbulkactions={this.__hasmultipleselected} /> .... __hasmultipleselected: function() { return false; //return true or false depending on data } .... var topicnav = react.createclass({ render: function() { return ( <div classname="row"> <div classname="col-lg-6"> <div classname="btn-group pull-right {this.props.showbulkactions ? 'show' : 'hidden'}"> <button type="button" classname="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false"> bulk actions <span classname="caret"></span> </button> <ul classname="dropdown-menu" role="menu"> <li><a href="#"...

excel - VBA Webscrape not picking up elmenents; pick up frames/tables? -

tried asking question. didn't many answers. can't install things onto work computer. https://stackoverflow.com/questions/29805065/vba-webscrape-not-picking-up-elements want scrape morningstar page excel code below. problem is, doesn't feed real elements/data back. want dividend , cap gain distribution table link put my_page. this easiest way, entire page scrape way, , excel-->data-->from web don't work. i've tried use elements tag name , class before, failed @ being able in case.this might way go... once again, want dividend , cap gain distribution table. not seeing results in via debug.print working code below, need parse excel. updated attempt below: sub macro1() dim ie new internetexplorer ie.visible = true ie.navigate "http://quotes.morningstar.com/fund/fundquote/f?&t=annpx&culture=en_us&platform=ret&viewid1=2046632524&viewid2=3141452350&viewid3=3475652630" doevents loop until ie.rea...

OpenGL fixed coordinate transformations -

was trying rendering opengl , happened think that: how run transformations in fixed coordinate system. in other words, if rotate object around 1 axis see others going rotate too? therefore, following rotations done on newly construct axis. i read on documentation (see part 9.070 ) https://www.opengl.org/archives/resources/faq/technical/transformations.htm , have no idea: 1. if works 2. how implement cause don't understand supposed do. i think won't 1 want , it's guess interesting question. edit: here implementation doesn't work , fix evoid display() { glclear(gl_color_buffer_bit | gl_depth_buffer_bit); // clear color , depth buffers glmatrixmode(gl_modelview); // operate on model-view matrix // render color-cube consisting of 6 quads different colors glloadidentity(); // reset model-view matrix gltranslatef(1.5f, 0.0f, -7.0f); // move right , screen //glrotatef(anglecube, 1.0f, 1.0f, 1.0f); // rotate (1,1,1)-axis [new] //matrix tran...

matlab - Calculate great circle distance of all matrix elements to all matrix elements -

i have following vector of coordinates ll = [lat lon]; % 5000 x 2 and want calculate distances of elements elements using: [dist, ~] = deg2km(distance[lat1, lon1, lat2, lon2]); so final matrix be, guess, 5000x5000. btw function distance comes in mapping toolbox. tried loop one-by-one, takes centuries run. update ll = -79.49583374 40.029166991 -79.50416707 40.029166991 -79.50416707 40.037500324 d = pdist(ll, @(x2,x1)(deg2km(distance(x1(1),x1(2),x2(1),x2(2))))) d = 2014.58795578131 2014.58795578131 0.168797611011563 while first 2 coordinates: d = deg2km(distance(ll(1,2),ll(1,1),ll(2,2),ll(2,1))) d = 0.709531880098433 ---- any please? i didn't realise distance matlab function, sorry. try this: d = pdist(ll, @(x1,x2) (distance(x1(:,1),x1(:,2),x2(:,1),x2(:,2)))) what @(x1,x2) (distance(x1(:,1),x1(:,2),x2(:,1),x2(:,2))) do? it's anonymous function exp...

php - Creating hooks on woocommerce, finding hook_names -

i working on website using woocommerce rather have shopping facility i'm trying change wording, whilst keeping functionality able add products shopping cart calling enquiry, , call quote in replace prices. i have set prices when 0 entered won't display standard 'free!' , instead states 'call quote' adding functions.php add_filter( 'woocommerce_product_single_add_to_cart_text', 'woo_custom_cart_button_text' ); // 2.1 + function woo_custom_cart_button_text() { return __( 'add enquiry', 'woocommerce' ); } this works fine, , sourced particular hook online obtain code, starting further project wanting edit more button texts. my question is, how know obtain hook names can start create own hooks this, can seen class names when inspecting on google devtools? dragging woocommerce folder on sublime text 2 , conducting search woocommerce_product_single_add_to_cart_text can returned reults able see hook, how come across hook...

c++ - g++ problems, possibly with && operator -

i took c++ course during first year of college , stay sharp on fundamentals. used g++ trying use can continue use terminal commands necessary school's way of programming. code wrote: #include <iostream> using namespace std; int main() { (int = 0; < 100; i++){ if ((i % 3) == 0) && ((i % 5) == 0){ cout << "fish , chips" << endl;} else if ((i % 3) == 0){ cout << "fish" << endl;} else if ((i % 5) == 0){ cout << "chips" << endl;} else {cout << << endl;} } return 0; } and following error: fish.cpp: in function ‘int main()’: fish.cpp:7:24: error: expected identifier before ‘(’ token if ((i % 3) == 0) && ((i % 5) == 0){ ^ fish.cpp:7:24: error: expected ‘;’ before ‘(’ token i believe g++ isn't recognizing '&&' operator. have advice? your parenth...

python - Remove border from html table created via pandas -

i using python script display dataframe on webpage. used df.to_html convert dataframe html. however, default, sets border 0. tried overriding having custom css template didn't work. here pandas code: ricsubscription.to_html(classes='mf') is there parameter can pass set border 0 while making call? to_html() generates <table border="1" class="dataframe">... you do: ricsubscription.to_html().replace('border="1"','border="0"') also, answer specifically, there not appear can pass. border="1" appears hardcoded: https://github.com/pydata/pandas/blob/e4cb0f8a6cbb5f0c89b24783baa44326e4b2cccb/pandas/core/format.py#l893

ios - Working with transparency: View behind transparent view should only shine through and not overlap -

Image
i'm working transparency , i'd have following effect: as can see line takes full width of view. there transparent uiviews on screen. line seems below transparent uiview , if overlaps has color, because of transparent uiview above. when there no overlapping line normal color. how can effect? i tried set background of uiview transparent, didn't helped. line has normal color , doesn't interact transparency. furthermore tried change transparency of view same wrong result. the rectangle above done code uiview rectangle = new uiview (new cgrect (10, 10, 200, 120)); rectangle.backgroundcolor = uicolor.fromrgba (204,115,225, 50); uiview line = new uiview (new cgrect (0, 105, 320, 1)); line.backgroundcolor = uicolor.red; view.addsubview (line); view.addsubview (rectangle); line.sendsubviewtoback (rectangle); the rectangle below created in ios designer. am missing something? its z order of subviews. line.sendsubviewtoback (rectangle); is not ...

Why $scope doesn't change in the alert box? (angularJS) -

i'am trying understand behaviour: when change input view change when click on button alert box don't change $scope.firstname. give me advices. regards var app = angular.module('myapp', []); app.controller('myctrl', function($scope) { $scope.firstname = "john"; $scope.lastname = "doe"; var test=$scope.firstname; $scope.test=function(){ alert(test); }; }); <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myapp" ng-controller="myctrl"> first name: <input type="text" ng-model="firstname"><br> last name: <input type="text" ng-model="lastname"><br> full name: {{firstname + " " + lastname}} <button ng-click="test()">click</button> </div> currently, when l...

jsf - MyFaces doesn't append javax.faces.ViewState back on ajax update of stateless view -

i'm experiencing trouble running multiple times same ajax request updates enclosing form stateless jsf (myfaces 2.2.8 + cdi openwebbeans 1.2.7 running on tomcat 7). here sscce depict issue better words. let's consider simple form both inputtext , outputtext bound bean parameter. submitting form displays value next inputtext field. test.xhtml <!doctype html> <html lang="fr" xmlns="http://www.w3.org/1999/xhtml" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html"> <f:view transient="true"> <h:head> <title>test</title> </h:head> <h:body> <h:form> <h:inputtext value="#{testbean.txt}" /> <h:outputtext value="#{testbean.txt}" /> <h:commandbutton value="submit"> <f:ajax execute="@form" render="@f...

c++ - Why is iostream::eof inside a loop condition considered wrong? -

i found comment in this answer saying using iostream::eof in loop condition "almost wrong". use while(cin>>n) - guess implicitly checks eof, why checking eof explicitly using iostream::eof wrong? how different using scanf("...",...)!=eof in c (which use no problems)? because iostream::eof return true after reading end of stream. not indicate, next read end of stream. consider (and assume next read @ end of stream): while(!instream.eof()){ int data; // yay, not end of stream yet, read ... instream >> data; // oh crap, read end , *only* eof bit set (as fail bit) // stuff (now uninitialized) data } against this: int data; while(instream >> data){ // when land here, can sure read successful. // if wasn't, returned stream operator>> converted false // , loop wouldn't entered // stuff correctly initialized data (hopefully) } and on second question: because if(scanf("...",...)!...

How to communicate between HtmlService Javascript and Server Google Apps Script -

i'd create first google docs script generate amount seems not working : function onopen(e) { documentapp.getui().createaddonmenu() .additem('start', 'showsidebar') .addtoui(); } function oninstall(e) { onopen(e); } function showsidebar() { var ui = htmlservice.createhtmloutputfromfile('sidebar').settitle('calcul tarification icecom'); documentapp.getui().showsidebar(ui); } function calculprice(compagnytype, hours) { // here i'm not able "compagnytype" , "hours" var priceperday = 300; switch (compagnytype) { case 'pme': priceperday = 350; break; case 'esi': priceperday = 400; break; case 'ge' : priceperday = 450; break; } return priceperday * hours; } <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css"> <!-- css...

Why this code is wrong and Java in a Nutshell said so? -

i read java in nutshell now, , met question java in nutshell. example come book. see: e.g.: package de; public class { protected string x; } package uk; import de.*; class b extends { //first 1 public string getx(a a) { return "getx works" + a.x;//error: x has protected access in } //second 1 public string getx(b b) { return "getx works" + b.x; // works! } } the author means because instances of b not have access arbitary instances of a. , if change code second one, compiler happy, because instances of same exact type can see each other’s protected fields. can not understand author's meaning, actually? b extends a. x protected in a. b can access x's in b's. b can not access x's in a's (that not b's). consider class c extends a. can see reasoning (objecte oriented principle) behind b's can't access c's x's.

Is there any anchor tag in Onsen UI? -

i have long onsen ui page. after scrolling bottom of page, able load new content in same page. however, page still displayed @ same , current position. note: using ons-list. there auto scroll top in ons-list after list refreshed? i wonder how can make top position after new content loaded. anchors , scrolling depend on browser.you can use angular $anchorscroll or similar handle behavior. find useful in onsen ui events. can address scroll mentioned tool in postpop event in case using poppage , or in other event listed in onsen ui's docs . hope helps.

matlab - Splitting image into RGB channels with strange result -

Image
i used matlab split 1 image rgb channel , export binary rgb image, following original image: i split image rgb channel following code: r = secretimg(:,:,1); g = secretimg(:,:,2); b = secretimg(:,:,3); imwrite(r,'redchannel.tif'); imwrite(g,'greenchannel.tif'); imwrite(b,'bluechannel.tif'); however, following results: as can see, in red channel binary image, cannot see colour red component, show blue; in blue channel, cannot see in blue component! what happened? this isn't strange. works should. here simple illustration may easy understand pure red    -> r-1 g-0 b-0. pure green -> r-0 g-1 b-0. pure blue    -> r-0 g-0 b-1. white           -> r-1 g-1 b-1. black           -> r-0 g-0 b-0. gray            -> r-x g-x b-x. (x between 0-1 same components) so when view red component image, don't see difference between white , red color both holds value 1 . similarly figure out reason mis...

c# - .NET Winforms project with complex GUI and constraints between fields -

i work @ company repairs stuff , each time repair have fill paper tables everywhere , tons of fields. want rid of papers , need application replace whole thing, , store results in db. have use c# .net , windows forms. the problem now : there comboboxes in form values affect behavior of other controls. example, if combobox1 has value1, combobox2 available values choose value2, value3, value6, ... consider : ╔════╦════════╗ ║ ok ║ not ok ║ ╠════╬════════╬═════════════════════════════════════════════════════════╗ ║ ║ ║ measure 1 : ....... (threshold value1 : > 180cd/m²) ║ ║ ∙ ║ ∘ ║ (threshold value2 : > 130cd/m²) ║ ║ ║ ║ measure 2 : ....... (threshold value3 : > 100cd/m²) ║ ╚════╩════════╩═════════════════════════════════════════════════════════╝ the cells under 'ok' , 'not ok' radiobuttons. until (on paper) checked manually according values of measure 1 , 2. winforms app, have checked automatically lower...

SGEN : error : Mixed mode assembly -

can me im getting error when im publishing project on release mode sgen : error : mixed mode assembly built against version 'v2.0.50727' of runtime , cannot loaded in 4.0 runtime without additional configuration information. please me im stuck on issue. for build/publish in release mode please follow below step create new file sgen.exe.config keep below code in file <?xml version ="1.0"?> <configuration> <runtime> <generatepublisherevidence enabled="false"/> </runtime> <startup uselegacyv2runtimeactivationpolicy="true"> <supportedruntime version="v4.0"/> </startup> </configuration> please keep file in below path c:\program files (x86)\microsoft sdks\windows\v8.1a\bin\netfx 4.5.1 tools folder and x64 c:\program files (x86)\microsoft sdks\windows\v8.1a\bin\netfx 4.5.1 tools\x64 folder now restart vis...

php - Json response to ajax -

the data inserted , receive in console json response page move insert php , gives json response start in page (form) , after submit moves page b (insert)giving me json response. i'm having problem getting response of following php ajax if (move_uploaded_file($_files['filetoupload']['tmp_name'], $uploadfile)) { $target_path = "/uploads/" . basename($_files['filetoupload']['name']); $sql = "insert `ebspma_paad_ebspma`.`formacoes`(idescola, nome, inicio, horas, local, destinatarios, datalimite, visto, path) values(?, ?, ?, ?, ? ,?, ?, ?, ? )"; $stmt = $mysqli->prepare($sql); if ($stmt === false) { trigger_error('wrong sql: ' . $sql . ' error: ' . $mysqli->error, e_user_error); } $stmt->bind_param('issssssis', $escola, $form, $data, $horas, $local, $dest, $datas, $visto, $target_path); if (!$stmt->execute()) { echo json_encode(array('status' => 'error', 'message...