Posts

Showing posts from August, 2013

grape api - use rails 4.0 strong parameter in non rails application -

i use active-record 4.0 in grape api application, strong parameter works in rails controller, how permit params in grape api class there seems way use strong parameters outside controller raw_parameters = { :email => "john@example.com", :name => "john", :admin => true } parameters = actioncontroller::parameters.new(raw_parameters) user = user.create(parameters.permit(:name, :email)) for more info check repository documentation on github https://github.com/rails/strong_parameters regards

java - not able to insert values in my postgresql database -

in java code: callablestatement cs=null; int bcode=1; int dcode=3; int noftab=3; string sql2 = "{? = call public.insertdepttables('"+bcode+"','"+dcode+"','"+noftab+"')}"; cs = conn.preparecall(sql2); cs.registeroutparameter(1,types.integer); rset1=cs.getint(1); system.out.println("success="+rest1); in insertdepttables:(function in db-postgresql) create or replace function public.insertdepttables ( in branch_code integer, in dept_code integer, in no_tables integer ) returns integer $$ declare count integer; begin if no_tables>0 loop insert t_dept_tables(branch_code,dept_code,table_no)values(branch_code,dept_code,no_tables); no_tables=no_tables-1; count=count+1; exit when no_tables =0; end loop ; end if; return count; end $$ actually need insert no_table (i.e.,3) times row in t_dept_tables in postgresql. wat have done hav written function...

rest - Accessing JSON Resource on a RESTful one page app -

given 1 page app uses push state , restful backend, can imagine accessing listing of resource @ /resourcename (i.e. /users ). /users create formated list of users now problem resource json or xml feed should mapped /resourcename , if boot form application entry point @ / good, when navigating /users js router can trigger ajax call json data. problem if url pointing directly @ /users land on json feed instead of actual listing. route call main entry point , let js router work though if ajax call fetch json wil brake. i remember while ago people adding .json json request, or parameter ?format=json , having controller taking different actions. find hacky.. there other ways go this? for matter using laravel4 backend , backbonejs i think .json on end of request best approach. other approach create separate endpoint endpoint api request api.mydomain.com vs www.mydomain.com

android - GeoCoder throws "service not available" exception and geocoding api has usage limits -

i have seen similar question none of them cleared doubts. geocoder.getfromlocationname() throws exception "service not available", solution problem reboot device. can use geocoding api has usage limits upto 25000 request per day. so, how other apps "maps" , "google drive" being running. using geocoding api or "android.location.geocoder" class? i'm not familiar andriod. however, limit of geocoding has 2,500 requests per day (map loads per day 25,000) . usage limits use of google geocoding api subject query limit of 2,500 requests per day. (user of google maps api business may perform 100,000 requests per day.) google maps api business starts $10,000 per year of 2013/08/26 (we've spoken person google couple of days ago).

Magento how to display a block with a small image over the actual product image by using product id -

i have table contain product ids , small images. need display image on actual product image. how can display small image in every place product image appeared, is: product view, related product, list, grid.. without changing there template. is there programmatic way display small image everywhere without need change in every template product image display. yes quite possible. not easy though. there helper that mage_catalog_helper_image within helper extend init function , rewrite assignment of watermark. enable in backend in system > configuration > design > watermark. use helper init function assign additional image have. when finished, make sure clean cache , image cache. otherwise images not generated. it still possible images wont have additional image overlay. more of template issue doesn't use helper function.

multithreading - Where to begin serious concurrent (multi-threaded, parallel ?) programming -

i want begin multi-threaded/parallel/concurrent programming in real world . mean trying solve real problems in parallel , concurrently , not learning low-level details of pthread or mpi , locks, races , or academic, text-book examples. regarding low level mechanism of parallel programming, in fact rather not know them , stick more actor model :). i have heard programming languages inherently looking , paradigm @ problem @ hand in parallel (concurrent, multi-threaded, multi-processed) fashion , provide language level tools , constructs implement task in parallel (e.g. erlang has concept of process language construct?). i fancy language type system of scala ... know php , used lot of coding in c/c++. have working knowledge of scala , java , can read haskell i'm not particularity proficient @ it. i'm quite familiar functional paradigm , i'm willing learn more. interested in high level theoretical discussions parallelism/concurrency. i'd mention first ...

osx - Mac Terminal Curl for textfile -

i trying download csv file local webserver (the webserver runs on signal conditioning instrument) with: curl -o http://10.0.0.139/crv01.csv the output curl weird symbols. if put same url in safari csv file correctly depicted. there encoding problem curl? i tried verbose option gives: gunthers-macbook-pro:documents guenther$ curl -v -o http://10.0.0.141/crv01.csv * connect() 10.0.0.141 port 80 (#0) * trying 10.0.0.141... % total % received % xferd average speed time time time current dload upload total spent left speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* connected * connected 10.0.0.141 (10.0.0.141) port 80 (#0) > /crv01.csv http/1.1 > user-agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 openssl/0.9.8x zlib/1.2.5 > host: 10.0.0.141 > accept: */* > < http/1.1 200 ok < date: mon aug 26 21:03:12 2013 < server: vega-http-server < cache-c...

c++ - How to use the RegLoadKey function to load the NTUSER.DAT file from the Default User? -

i thought use regloadkey load ntuser.dat file located in c:\users\default folder using code: hkey hkey = hkey_local_machine; lpctstr lpsubkey = l"software\\load"; lpctstr lpfile = l"c:\\users\\default\\ntuser"; long r=regloadkey(hkey, lpsubkey, lpfile); it did not work. can tell me how have use function load ntuser.dat file hklm\software\load sub-key? thanks! as @xearinox mentioned need privilages ( se_backup_name , se_restore_name ) also must load ntuser.dat , otherwise create new registry hive. , lpsubkey can first level after hkey . so should set privilages , load this: long ret = regloadkey(hkey_local_machine, l"load", l"c:\\users\\default\\ntuser.dat");

java - Get background color of text from webpage -

my web application has primary , secondary search. based on search term web application highlights first search term in blue color , second search term (or search within call) highlighted in purple color. done using java script in end not have access. i need automate scenario, since color of element not seen in page source unable identify background color of element using selenium. please suggest me suitable solution background color of searched terms from understood far question is, wanted style anchor visiting search links. links can styled css property (e.g. color, font-family, background, etc.). in addition, links can styled differently depending on state in. the 4 links states are: a:link - normal, unvisited link a:visited - link user has visited a:hover - link when user mouses on a:active - link moment clicked you can change background color of link styling anchor tag directly in css external or inline file. can handled javascript or jquery styling attrib...

rails button_to replace quotes with single quoute -

i try should button_to no qoutes while rendering button_to "delete", radio_tag_path(tag), :method=>:delete, :class=>:destroy, :confirm=>"are sure?" the output is <form action="/radio/tags/654" class="button_to" method="post"> <div> <input name="_method" type="hidden" value="delete" /> <input class="destroy" data-confirm="are sure?" type="submit" value="delete" /> <input name="authenticity_token" type="hidden" value="exm0mcntzuhnyixrllyf7kjp76fdmdzpq6hpc++ogog=" /> </div> </form> but need no qoutes than rendered (button_to "delete", radio_tag_path(tag), :method=>:delete, :class=>:destroy, :confirm=>"are sure?" ).gsub('\"','\'') but output html_safe &lt;form action=&quot;/radi...

JAVASCRIPT: OK button proceed to another .php form -

i have basic javascript code saving entry. scenario: i have 2 forms, first form,[view_netbldg.php], data entry when user click "add" button proceed next form [save_netbldg.php]. in save_netbldg.php form there if else condition code know first if variable of $bldgname or $netname empty. okay, concern when code detect either of 2 variables empty code below i'm using executed. here's code: if($bldgname == "" || $netname == "") { echo "<script type='text/javascript'>\n"; echo "alert('please complete fields building name or network name');\n"; echo "</script>"; header("location:view_netbdlg.php"); } *the result of program is, not displaying alert instead jump header the correct way is, if $bldgname == "" || $netname == "" == true** alert display , when user click ok button proceed next form "view_netbdlg.php". don't need confirmati...

Junit testing Struts2 action with Spring -

i want test struts action facing following problem: severe: [09:16.218] error building bean it seems spring not dependency injection. indeed, if create default constructor npe because service not instantiated. unit test extend strutsspringtestcase, why action not instanciate correctly ? here action : public controllerauthentification(ldapuserservice service) { this.ldapuserservice = service; } public string connection() { if (userldap != null) { ldapuserservice.save(userldap); addactionmessage(gettext("success.connect")); return success; } return input; } unit test : public class controllerauthentificationtest extends strutsspringtestcase { public void testconnection() throws exception { request.setparameter("userldap.login", "login"); request.setparameter("userldap.password", "password"); proxy = getactionproxy("/connection"); con...

ember.js - Callback for change in URL in Ember v1.0.pre -

i want call function when change in url. in newer versions of ember, can observing currentpath . in version, tried this: ember.route.reopen({ enter: function(router) { console.log('change in url , need called once per change in url'); } }); since there nested routes, method called mutiple times. if using ember.hashlocation can this, observing lastseturl property: window.app = ember.application.create({ ... urlchanged: function(a,b,c,d) { var url = this.get('router.location.lastseturl'); if (!ember.none(url)) { alert(url); } }.observes('router.location.lastseturl'), ... }); here example of working http://jsfiddle.net/marciojunior/ba4hj/

libraries - Deprecated java classes in stdlib.jar -

i'm facing problem deprecated classes in set of libs programming in java tutorial. currently, i'm trying run threesum.java , getting noclassdeffounderror in cmd (windows). problem readints(args[0]) class deprecated. programming skills not enough fix myself. appreciate help. readints method not class. /** * reads ints stdin. * @deprecated more consistency, use {@link #readallints()} */ public static int[] readints() { return readallints(); } as can see here, fix use readallints() . however, deprecated methods should still work. verify have setup stdlib.jar correctly, , including in class path when compiling.

javascript - Express.js - Send an alert as a response while staying on same page -

i have 3 forms on view that, when submitted, add new entries in mysql database. send alert saying "you have added x" whenever entry added, without navigating page. // form submitted <form method="post" action="route/action/"> <input type="text" name="name"> </form> // route exports.action = function (req, res) { client.query(); // kind of response send? } how can send alert? kind of response should send? thank you! what need ajax request express server , evaluate response , alert user accordingly. client part same other programming language. for example. in jquery client side part can $.ajax({ url: 'route/action/', type: "post", data: 'your form data', success: function(response){ alert('evaluate response , show alert'); } }); in epxress app can have this app.post('route/action', function(req, res){ //process request here , d...

iphone - Make UIView behind transparent UIView invisible -

i have transparent view alpha set 0.3, , behind there views, there option in ios set of views behind transparent view hidden? i need when half of view behind transparent, , other half not, show half of view you can hide after making iboutlet connection [yourview sethidden:yes];

MySQL filling out values from other tables -

Image
i have table called vacancy looks so role company location each have table of there own query pull information other tables fill in vacancy i tried select r.title, c.company, l.town, l.country, v.term role r, vacancy v, location l, company c but gives 300 rows of same title when should in fact have 3 rows returning. company role location you can use join display data 4 tables select v.id, r.title, c.company, l.town, l.country, v.term vacancy v join location l on (v.location = l.id) join company c on (v.company = c.id) join role r on (v.role = r.id)

ruby on rails - Improving factories of associated models -

i have 3 models : user, product , ownership. ownership belongs user , product. product , user have many ownerships. i created following factories factorygirl gem : factory :user sequence(:name) { |n| "robot #{n}" } sequence(:email) { |n| "numero#{n}@robots.com"} association :location, factory: :location end factory :product sequence(:name) { |n| "objet #{n}" } association :location, factory: :location end factory :ownership association :user, factory: :user association :product, factory: :product end and use : let(:user) { factorygirl.create(:user) } let(:product) { factorygirl.create(:product) } let(:ownership) { factorygirl.create(:current_ownership, user: user, product: product) } but want improve factories, in order : let(:user) { factorygirl.create(:user) } let(:product) { factorygirl.create(:product, owner: user) } do have idea how ? you can using factory girl after_create callback: factorygirl.define ...

jquery - stubbornly floating to the right although there is no command -

this question has answer here: how vertically center div browsers? 38 answers http://jsfiddle.net/6j7zc why adminbox floating although there no command? http://jsfiddle.net/6j7zc/1 ** fixed div center not working properly .adminbox { width: 200px; height: 17px; margin-top: 20px; padding: 20px; font-size: 12px; color: white; background-color: black; font-size: 12px; font-family:"gears of peace"; } lines 57-61 of css... .adminbox { width: 50px; height: 35px; font-family: verdana; font-size: 24px; margin: auto; color: green; background-color: transparent; float: right; margin-top: 4px; margin-left: 60px; font-style: italic; } there's float: right in there ;)

java - The request sent by the client was syntactically incorrect. HTTP Status 400 - -

i have method signature in @controller @requestmapping("/savecandidate") public string savecandidate(model model, @modelattribute("candidatefromrequest") candidate candidatefromrequest, @modelattribute("skillsidlist") set<skill> skills, @modelattribute("vacanciesforcandidate") set<vacancy> vacanciesforcandidate) and form: <form action="savecandidate" id="formid" method="post"> .... <input type="submit" value="save changes"/> </form> in debug see, @modelattribute entities put on request. why result see the request sent client syntactically incorrect. http status 400 - in browser code: @modelattribute(value = "candidatefromrequest") public candidate loadcandidatebyid(@requestparam(required = false) integer id) { if (id!= null) return candidateservic...

c++ - Boost Spirit Qi Attribute Propagation -

i have issue boost spirit qi grammar emitting undesired type, resulting in compilation error: error c2664: 'std::basic_string<_elem,_traits,_ax> &std::basic_string<_elem,_traits,_ax>::insert(unsigned int,const std::basic_string<_elem,_traits,_ax> &)' : cannot convert parameter 1 'std::_string_iterator<_elem,_traits,_alloc>' 'unsigned int' here grammar causing issue: qi::rule<iterator, qi::unused_type()> gr_newline; // asmast::label() contains identifier struct emitted gr_identifier qi::rule<iterator, asmast::label(), skipper<iterator> > gr_label; gr_newline = +( char_('\r') |char_('\n') ); this fails: gr_label = gr_identifier >> ':' > gr_newline; but following work: // parses ok gr_label = gr_identifier > gr_newline; // parses ok gr_label = gr_identifier ...

multiple dynamically created jquery slider galleries on one page -

i trying create page user can add jquery slider galleries page on click of button. i have got working having problems rotation of images on additional sliders when there more one. , original slder jumps , shows 2 images. i have created jsfiddle demonstrate http://jsfiddle.net/uukp4/25/ the additional sliders loop round once , stop any appreciated. code fiddle css: #slideshow { position:relative; height:350px; } #slideshow img { position:absolute; top:0; left:0; z-index:8; opacity:0.0; } #slideshow img.active { z-index:10; opacity:1.0; } #slideshow img.last-active { z-index:9; } jscript var i; var topplus=50; function buildslider(i, id, content) { id = id + i; var newdiv = document.createelement('div'); newdiv.setattribute('id', id); newdiv.style.position = "absolute"; newdiv....

php - Result form crontab is not same as manually execute? -

i have php script execute shell commands. once manually executed it. worked fine. but after used crontab execute, result shell commands missing. these 2 commands. ip route iptables -t nat -l | grep 8800 and here sample php code. #!/usr/bin/php -q <? $route = exec('ip route'); $iptable = exec('iptables -t nat -l | grep 8800'); echo $route; echo $iptables; ?> the above code worked manually execute not crontab. i found commands worked both. example ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}' cat /tmp/example | grep test any ideas problem, , thank in advance. a couple of things worth noting: the exec function's signature string exec ( string $command [, array &$output [, int &$return_var ]] ) to full output of command you'll have call so: $output = array();//declare in advance best because: $lastline = exec('ip route', $status, $output);//sig...

Android - Communicating from Activity to fragment that it hosts -

currently have been diving fragment world: http://developer.android.com/guide/components/fragments.html#communicatingwithactivity i understand creating listener in fragment , implementing in activity hosts fragment great way communicate fragment activity, how communicate activity fragment? listener? perhaps don't understand listener doing. topic explaining how communicate activity fragment appreciated! p.s. converting activity (b) made fragment. use intent.putextra("value") activity before starting activity b looking replace... doesn't @ thought i'd try , put perspective doing. i may have found solution, lol. i'll checks make sure works , confirm later. @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { bundle b = getactivity().getintent().getextras(); wid = b.getstring("wid"); rid = b.getstring("rid"); view view = inflater.inf...

.net - URL Rewriting in ASP.Net MVC 2 -

i have written below code achieve url rewriting. in global.asax routes.maproute( "studentdetail", // route name "studentdetail", // url parameters new { controller = "udashboard", action = "uaboutmestudentdetails", sortfield = urlparameter.optional } ); in view <a href="/studentdetail?sortfield='major'" >students</a> when click link, goes action of controller perfect. but url https://localhost/studentdetail?sortfield='major' and don't want that. i want url https://localhost/studentdetail can please tell me change should achieve above url. thanks, prashant if want value of sortfield major, not show in url, need this: routes.maproute( "studentdetail", // route name "studentdetail", // url parameters new { controller = "udashboard", action = "uaboutmestudentde...

c - how to stop linux framebuffer to clear automatically while drawing multiple frames -

i writing gif decoder, image animated image.when write first frame, displays fine. when, display second frame, displays changed pixels. other pixels automatically changed black. don't know why?. my first frame has complete picture. second frame has again pixel changed , contains rest of unchanged pixels. now, when draw second buffer, redraws unchanged pixels also. , unchanged pixels drawn black ( or precisely in monitor see these unchanged pixels absent). that's when has draw second frame.it draws changed pixels( correct), re-draws unchanged pixel well. , unchanged pixel seen black ( no color). feel refreshing issue. or else. appreciated. required: should redraw complete image. in short, snippet of function. unfortunately, clears off previous display - linux framebuffer. want stop clearning linux framebuffer. here complete file. /** using direct fb calls here; , tightly coupled linux framebuffer **/ static int fbfd = 0; static struct fb_var_screeninfo vinfo; st...

java - Assign argument to variables in multithreading -

i have written code send , receive files between 2 client , server want both functions in 1 program. wrote separate class containing send , receive functions. have declared 2 variables sendfilepath , receivefilepath . called method transfer(string sendfilename, string receivefilename) , assigned values these variables showing null. how can this? actually want send sendfilepath rf.receive(); , receivefilepath sf.send(); method how can done? class transferfile implements runnable { thread thread; string sendfilepath, receivefilepath; sendfile sf = new sendfile(); receivefile rf = new receivefile(); public void transferfilecreatethread(string name) { thread = new thread(this,name); thread.start(); } public void run() { rf.receive(sendfilepath); sf.send(receivefilepath); } public void transfer(string sendfilename, string receivefilename) { try { sendfilepath =...

where should I locatemy Quartz Code in asp.net -

i have asp.net website , want task once day. task is: sending email users 2 days before expiration of registration. used quartz.net version 1.0. have wrote sample code opens window in each second. don't know should locate code in asp.net project?! in simple page. want independent pages. public class dumbjob : ijob { public dumbjob() { } public void execute(jobexecutioncontext context) { console.writeline("dumbjob executing."); system.windows.forms.messagebox.show("nice"); } } protected void page_load(object sender, eventargs e) { if (!ispostback) { // construct scheduler factory ischedulerfactory schedfact = new stdschedulerfactory(); // scheduler ischeduler sched = schedfact.getscheduler(); sched.start(); // construct job info jobdetail jobdetail = new jobdetai...

ios - Best way to load data from a website/server to iPhone -

i have own website , want write app loads data (strings/texts) fill tableview on iphone (like to-do-list). want change content of app (of tableview) time without doing update in app store. when app starts should grab content website... should use ftp doing things or there better ways load , manipulate data? if content in simple text/string there no need of ftp (it's useful in case of large file transfer web app) suitable methodology restful services . restful services able get/post data in easy way. can transfer data website ios application . , whenever change data automatically change data of iphone app . there no need change after app store upload of application. hope helps !

ruby - rails: organizing data into a table using for -

Image
i have following view: <table class="fixed"> <tr> <th>student name</th> <!-- create many <th> there evaluations --> <% @eval_count.times |i| %> <th>evaluation <%= i+1 %></th> <% end %> <th>student average <br />(for goal)</th> </tr> <% eval in @evals %> <tr class="<%= cycle("odd", "even", name: "evals")%>"> <!-- eval returns { s_id [eval],[eval]} --> <td><%= eval[1].first.student.name%></td> <!-- in each student's row, print score each con...

java - Specify multiple filters in hbase -

is there way specify multiple filters during scan? example - specify both columnfamilyfilter , rowfilter ? filter rowfilter = new rowfilter(comparefilter.compareop.equal, new regexstringcomparator( rowfilterstring)); scan s = new scan(); s.setfilter(rowfilter); i wanted add columnfilter s . overrides latest filter. you have create filterlist object, , add filters want that, , set filterlist object filter. can either use constructor or use addfilter() method add filters filter list. filterlist filterlist = new filterlist(); filterlist.addfilter(new rowfilter(...)); filterlist.addfilter(new columnfilter(...)); scan s = new scan(); s.setfilter(filterlist);

javascript - Array.prototype.find, what's its spec? -

those have chrome 30.0.1599.14 dev seem gifted of new function: string(array.prototype.find); // "function find() { [native code] }" however, haven't found reference addition. tests seems accepts arguments a-la some , every , on: array.some(callback[, thisobject]); and callback usual callback function of kind: function([item[, index[, array]]]) { ... } the function expected return true when "right" item passed, item becomes value returned find . example: array.prototype.slice.call(document.getelementsbytagname("*")) .find(function(element) {return element.id === "content";}); it's odd way re-define document.getelementbyid , except when item isn't found find returns undefined instead of null . it nice if function accept initial index, or if there dual function lastfind parses array end. is there who's seen function , can tell me can find spec? it ecma script 6. here's html vers...

javascript - Dojo.query remove class -

i want remove class use following code : var styletoremove = query(".someclass").parent().parent().parent().parent(); styletoremove.foreach(function(node) { domclass.remove(node, "ui-state-default"); }); the code works on firefox(styletoremove returns object htmldivelement) not on ie8(styletoremove returns object). why ? you don't need manually iterator on nodelist query returns. can require in "dojo/nodelist-dom" dependency , dojo automatically add "removeclass" method nodelist class. require(['dojo/query', 'dojo/nodelist-dom'], function (query, nodelistdom) { query('#x').removeclass('myclass'); }); i made simple jsfiddle demonstrating this.

database - Make a column nullable in Ingres -

i make column nullable in ingres database , couldn't find statement, or tool allow me this. anyone can me? ingres version: 9.2.1 so let's create table not null field: create table test ( field_1 char(10) not null ) in order convert field allows null values need this: alter table test alter column field_1 char(10) null for reference actian ingres sql manual can found here: actian ingres 2006 sql reference guide

Cannot install Android Studio under Windows 8 64bit -

Image
i bizarre error trying install android studio under windows 8. know comes or can it? thanks lot in advance! i not know why, installing "java chrome" (.exe) made work. awkward did have java (same version 1.7.u25) installed , used before environment variables set.

php - How to detect that username already use in the database -

<?php if(isset($_post["add"])) { $name=$_post["emp_username"]; $pass=$_post["emp_password"]; $fname=$_post["emp_fname"]; $lname=$_post["emp_lname"]; $hph=$_post["contactno_home"]; $hp=$_post["contactno_hp"]; $mail=$_post["emp_email"]; $add=$_post["emp_address"]; $age=$_post["emp_age"]; $pos=$_post["position"]; $dept=$_post["dept_id"]; mysql_query(" insert employee(dept_id, emp_address, emp_age, position, >emp_username, emp_password, emp_fname, emp_lname, contactno_home, contactno_hp, emp_email) >values('$dept','$add','$age','$pos','$name','$pass','$fname', '$lname','$hph','$hp','$mail'>) "); ?> <script type="text/javascript"> alert("record saved."); </script> <?php } ?> ...

c# - Negative tests - should I expect the exact exception? -

consider following method public void foo(string str) { if (str == null) throw new argumentnullexception("str"); if (str.length != 5) throw new myexception(); } suppose want write negative test so: public void testfoo() { try { foo(null); //this remote call (e.g. wcf) assert.fail("expected argumentnullexception"); } catch (argumentnullexception) {} //should "exception" instead? try { foo("four"); //this remote call (e.g. wcf) assert.fail("expected myexception"); } catch (myexception) {} //should "exception" instead? } it seems me catching specific exception above implementation detail, may make test brittle , coupled implementation (rather interface). myexception change 1 day, argumentnullexception may be, say, wrapped inside other exception (for example future wcf behavior). typically test knows "four" should fa...

Different css styling for last element of a php array -

when looping through array how can create different css div style last element output in array. for($i=0;$i<=count($productid);$i++){if($productrank[$i]>0 ){ <? if (($productid[$i] % 2 ) && !( last element of array){ echo '<div class="centerboxcontentsfeatured centeredcontent vline " style="width:50%;">';} else { echo '<div class="centerboxcontentsfeatured centeredcontent " style="width:50%;">';} ?> just check if last $productid for(...) { if ($i === (count ($productid) - 1)) // last 1 -> special css } } also, not use count() in loop if don't have to. assign value before , use : $count_temp = count ($productid); ($i = 0; $i < $count_temp; ++$i) and use $count_temp again if if statement check if it's last element answer comment : how same method first element? if ($i === 0) or // special css $i = 0 // start loop @ 1 instead of 0 ($...

r - Add extra arguments to implicit S4 generic for a primitive function -

take function names : that's primitve function in r. primitive functions, implicit s4 generic created, possible construct s4 methods function. take s4 class defined follows : setclass("aclass", representation=list( values = "character", id = "numeric" ), prototype=list( values = character(0), id = numeric(0)), validity=function(object){ length(object@values)==length(object@id) } ) now want create function extract names, either sorted or unsorted. wanted using function names avoid having make new function getnames() or whatever, that's less intuitive. the following gives idea of needs done: setmethod("names",signature="aclass", function(x,ordered=true){ if(ordered) x@values[x@id] else x@values } this won't work, names primitive function , ordered not argument impli...

javascript - Jquery .animate() stop scrolling when user scrolls manually? -

i have set snippet scrolls page section view when it's clicked, problem if user wants scroll in middle of animation scroll kinda stutters. $( "section" ).click(function(e) { $('html,body').animate({ scrolltop: $(this).position().top }, 'slow'); return false; }); how can stop jquery animation if user scrolls manually? change function this: var page = $("html, body"); $( "section" ).click(function(e) { page.on("scroll mousedown wheel dommousescroll mousewheel keyup touchmove", function(){ page.stop(); }); page.animate({ scrolltop: $(this).position().top }, 'slow', function(){ page.off("scroll mousedown wheel dommousescroll mousewheel keyup touchmove"); }); return false; }); this will: stop animation if user scrolls manually (only during animation) does not obstruct normal jquery animation, such of other answers would some i...

java - JFreeChart using shifting one series by a given offset value -

let's assume have 1 instance of org.jfree.data.xy.defaultxydataset , adding 2 series in way: dataset.addseries(name, values); dataset.addseries(name2, values) how can move first or second series x or y offset value? assume offset >= 0. moving 'right' mean each (x,y) point transform (x + offset, y) point. moving 'left', 'up' , 'down' analogy. defaultxydataset convenient accessing individual elements of different series, doesn't expose methods needed manipulate internal data structures in way. instead, implement xydataset interface extending abstractxydataset , shown here , can encapsulate offset plumbing. may want @ slidingxydataset , cited here .

php - Is there a way to change the rate at which a cURL SSL session ID becomes stale? -

i have set of php scripts running on low-powered embedded device use curl php library post data every second remote server. curl transfer secure, slowdown calculate handshake each connection untenable. changed make use of curl's connection caching, , initial connection takes long time. however, every 2 hundred connections or so, once every 5 minutes, following messages: * ssl re-using session id * ssl connection using dhe-rsa-aes256-sha * old ssl session id stale, removing then ssl handshake happens again, causing noticeable delay in data, , subsequent connections work 5 minutes. i understand need refresh connection, on such slow cpu, , such high granularity, make refreshes less frequent. haven't had success search engines. know enforces refresh, , whether there frequency variable can change? the remote server under control. uses apache , openssl provide secure connections. since using apache , openssl, may want change sslsessioncachetimeout value 15 minute...

c# - Setting up Session Variables -

i have radiobuttonlist 2 options -beach bach -bush bach i want create 2 session variables doing right session["beachbach"] = bachradiobuttonlist.selectedvalue = "beach bach"; session["bushbach"] = bachradiobuttonlist.selectedvalue = "bush bach"; so if users press chose "beach bach", 1 added session["beachbach"] same goes bush bach or need create 2 radiobuttonlist?? thanks i think want == instead of = : session["beachbach"] = bachradiobuttonlist.selectedvalue == "beach bach"; session["bushbach"] = bachradiobuttonlist.selectedvalue == "bush bach"; otherwise you're setting selectedvalue of each radio button storing that string in session variables. if use == comparing values , storing true or false in session variables. if really want store 1 or 0 (which don't recommend - bool values should work fine , make server side code cleaner) use (con...

java - Spy private method on thread with mockito -

i have runnable call void private method during lifetime. want test, using powermockito, method "processstep" call 1 time each argument. myrunnable class public class myrunnable extends runnable { myrunnable(args){ ... } @override public final void run{ ... processstep(); ... } private void processtep(a){ ... addattributeresult(); ... } private void addattributeresult(){ ... } } my test class testing myrunnable class @powermockignore("org.apache.log4j.*") @runwith(powermockrunner.class) @preparefortest({ dbreader.class, myrunnable.class }) public class cyclemanagertest { @test public void mytest(){ myrunnable myrunnable = new myrunnable(arg[] {a,b}); thread t = new thread(myrunnable); t.start(); while (myrunnable.getnbrendcycle() < 1) { thread.sleep(10); } t.interrupt(); for(string s : a...

javascript - AngularJS: How to make parent directive using transclusion be compiled before the child directive? -

i have following structure: <dad-dir> <kid-dir></bar-dir> <kid-dir></bar-dir> </dad-dir> here, daddir parent directive, , kiddir child directive. in daddir , transclude set true. output looks this: <div class='dad-dir'> <span class='kid-dir'>kid directive output</span> <span class='kid-dir'>kid directive output</span> </div> the problem i'm having is, kiddir s being compiled / linked before daddir . problem because want daddir set attributes want kiddir s inherit. have console.log line in link functions of both daddir , kiddir , ones in kiddir logged before daddir 's. i have tried changing priority, setting daddir 's priority 10 , kiddir 's 1, has no effect. any ideas? i believe bug in angularjs version 1.0.5 using. upgraded 1.2 , magically, require: '^daddir ' kiddir works.

jsf - Google chart: How to pass the datatable from Java files to JavaScript -

hello try using google chart display trendlines, based on datas generated java files. here part of codes public void resolveevolution() { this.evolution = new arraylist<long>(); this.evolutiontime = new arraylist<string>(); calendar first = calendar.getinstance(); first.settime(this.start); first.set(calendar.day_of_month, 1); calendar last = calendar.getinstance(); last.settime(this.end); int = 0; this.dt = datatable.create(); dt.addcolumn(columntype.number, "time"); dt.addcolumn(columntype.number, "utilisation"); dt.addrow(); while (first.before(last)) { calendar endmonth = calendar.getinstance(); endmonth.settime(first.gettime()); endmonth.add(calendar.month, 1); endmonth.add(calendar.day_of_month, -1); this.evolution .add(actionqueries.countbycomponent(this.s...

apache - How do I rewrite this url with htaccess / mod_rewrite? -

how rewrite url .htaccess mod_rewrite http://55.100.10.66:81/var/class/tag?isajax=true&id=189&key=ejwvxzeowjamb&callback=_prototypejsonpcallback_0 to http://55.100.10.66:81/index.php/var/class/tag?isajax=true&id=189&key=ejwvxzeowjamb&callback=_prototypejsonpcallback_0 amongst lot of things tried below doesn't work rewriterule ^var/class/tag(.*) /index.php/var/class/tag$1 [l,nc,qsa] thanks! this solution rewritecond %{request_uri} ^/var/class/tag(.*) rewriterule .* index.php [l] you cannot match query_string rewriterule. enable mod_rewrite , .htaccess through httpd.conf , put code in .htaccess under document_root directory: options +followsymlinks -multiviews # turn mod_rewrite on rewriteengine on rewritebase / rewriterule ^(var/class/tag/?)$ /index.php/$1 [l,nc]

sql - Is it possible to automaticly have in a row a substraction between two MYSQL variables -

i have : +----------+------+-----+--------+ | image_id | | bad | result | +----------+------+-----+--------+ | 1 | 10 | 2 | x | +----------+------+-----+--------+ | 2 | 4 | 1 | y | +----------+------+-----+--------+ where x , y calculated automaticaly respectively 10 - 2 , 4 - 1. (good - bad) -avoid negative number if possible- i value change if values (good or bad) changes well. +----------+------+-----+--------+ | image_id | | bad | result | +----------+------+-----+--------+ | 1 | 10 | 2 | x | +----------+------+-----+--------+ | 2 | 4 | 1 | y | +----------+------+-----+--------+ i can in php there way directly mysql ? calculate result , return no less zero, avoiding negative numbers: select image_id, good, bad, greatest(good-bad, 0) result `table`;