Posts

Showing posts from April, 2013

ruby on rails - Active Record or SQL query for leaderboard (postgres rank and sum) -

i looking or creating advanced query in rails/active record (or sql using postgres) contest. i have contest table, users table , activities table. contests have many users (participants) , users have many activities. each activity has points, 'trackable_type', , other attributes. what want selected: - first_name users table - last_name users table - sum of points each user total_contest_points - count of activities have type 'course' each user total_contest_courses - results returned ranked total_contest_points , total_contest_courses i have taken @ postgres_ext gem , tried writing sql, can't seem ranking work. here's have far: time_range = start_time..end_time contestants = participants.joins(:activities).where('activities.created_at' => time_range).select(" users.id, users.first_name, users.last_name, sum(activities.points) total_contest_points, sum( case when activities.trackable_type='course'

python - How to combine sub-sublists only if they share a common value? -

i have sublists filled own sublists. if sub-sublists share common value @ index 1, i'd combine 2 sublists 1 merging/combining items in sub-sublists create 1 sub-sublist. l = [[ ['sublist1','aaa','10','apple,pear,banana'], ['sublist1','aaa','50','peach,orange,banana'], ['sublist1','ddd','3','bike,street'] ],[ ['sublist2','ccc','50','tomator,lemmon'], ['sublist2','eee','30','phone,sign'], ['sublist2','ccc','90','strawberry'], ['sublist2','fff','30','phone,sign'] ],[ ['sublist3','bbb','100','tomator,lemmon'], ['sublist3','bbb','100','pear'], ['sublist3','fff','90','strawberry'],

Wrong multidiemnsional-array initialization trying to build the pascal triangle (JAVA) -

i trying write class creates object of pascal triangle using multidimensional arrays. have in place (at least think so) except correct initialization of array. program reads follow: class pascal{ //object variables int size; int[][] pascal; pascal(int size){ //constructor this.size = size; //defines how many rows/columns triangle has. pascal = new int[size][]; //allocation of arrays for(int i=0;i<pascal.length;i++) pascal[i] = new int[i+1]; pascal[0][0] = 1; //the tip of triangle one. need value start with. //initialisation of elements for(int x=0;x<pascal.length;x++){ for(int y=0;y<pascal[x].length;y++){ if(x>0){ if(y==0 || y == (pascal[x].length)-1) pascal[x][y] = 1; //initialisation of first , last element of actual array x else pascal[x-1][y-1] = pascal[x-1][y] + pascal[x-1][y-1];//initialisation of elements in between

Determine if function is called in a test using Perl -

i use test::more i want see if 1 of functions called or not. there 2 scenarios have: 1 not call function, other will. function not mocked out, want see if called or not. something like: my $called; $orig_function = \&yourpackage::yourfunction; { no warnings 'redefine'; *yourpackage::yourfunction = sub { ++$called; goto &$orig_function }; } # code may or may not call yourfunction here ok($called, 'function called');

haskell - typeclass for repetitive actions until fixed point -

i noticed common pattern of executing action until stops having effects, when 1 knows signifies fixed point (ie, there can no future effects). there typeclass this? is covered monadfix? looking @ code, seems be, scared off wiki page "it tempting see “recursion” , guess means performing actions recursively or repeatedly. no." it seems me fixed points dual of identities. is, identity disappears when combined non-identity (0 (+), 1 (*), [] append, etc). whereas fixed point causes non-fixed point disappear under 'relax' operation below. there way formalize duality, , useful so? ie, there relationship between monadplus and/or monoid , monadrelax? lastly, notice relax unfold/anamorphism. better express such? {-# language multiparamtypeclasses, functionaldependencies #-} import control.monad.loops (iterateuntilm) -- cabal install monad-loops -- states relax fixed point under step class monad m => monadrelax m s | s -> m isfixed :: s -> bool ste

c++ - Where can I find fio.lib and fmath.lib on Fortran x64 installation in Windows -

i in process of re-writing code written in 32 bit (by else no-longer around!) 64 bit. compiling requires linking couple of 64 bit fortran libraries (fio.lib , fmath.lib.) i installed redistributable fortran library package intel 64 don't see either of above libraries in there (under \common files\intel\shared files\fortran\lib\intel64.) can point me can find 64 bit versions of these libraries? os: windows thanks! the redistributable package contains .dlls needed running executable/library. development need .lib files under intel fortran 64bit compiler directory structure. differs version version, try in release notes compiler. e.g. ifort 11.1 (section 2.4) c:\program files\intel\compiler\11.1\lib\intel64\*

playframework 2.0 - Turn Scala Anorm record into a specific object -

using findby seen below, can search authentications table record key , value def findby(key: string, value: string): = db.withconnection { implicit connection => sql("select * authentications {key}={value} limit 1").on('key -> key, 'value -> value) } example: authentication.findbyme("email", "toot@toot.com") returns: res1: = simplesql(sqlquery(select * authentications ?=? limit 1,list(key, value),none),list((key,parametervalue(email,anorm.tostatement$$anon$3@4ca9aed5)), (value,parametervalue(toot@toot.com,anorm.tostatement$$anon$3@18154945))),<function1>) how can turn authentication object? object fields got query. i've tried following, can't passed nullable object error when there's there's null in 1 of columns. can't figure out how put use solutions offered here val authentication_parser = get[string]("email") ~ get[string]("encrypted_password") ~ get[string](&

javascript - How to disable dropdowns and buttons based on the value of a column in a table -

i have table set of columns fetching values database along dropdown , button in each row. depending on value of 1 of columns(year), dropdown (salary) , button (update) need disabled. i tried 2 different approaches using javascript , jquery. both don't seem work. 1) tried triggering event on pageload using javascript <body onload="dropdowndisabler();"> javascript part: function dropdowndisabler() { if ($("#year").val() >= 2005) { $("#salary").enabled=false; $("#update").enabled=false; } } 2) tried matching year column elements have criteria using jquery: if($('#year').val() >= 2005) { $(this).find("#salary").prop('disabled',true); $(this).find("#update").prop('disabled',true); } you can iterate on rows, check value of year , set disabled property on select , button element in row: $(document).rea

html - How do I use PHP to apply css properties? -

i want use php link css document's properties html would: <link rel="stylesheet" href="mobile.css" type="text/css"> to specific, don't want import css file displays in between 2 css <style> tags in html. want php apply properties css document. i want php able work in if statement: <?php if ($mobile == true) { //your solution here } ?> thanks! this you're asking for, isn't best practice , wouldn't recommend it. refer @nietonfir's suggestion (despite being little harsh, he/she right). doing mobile stuff in css part of responsive design (media queries) soooooo better , easier. <?php if ($mobile == true){ echo '<link rel="stylesheet" href="mobile.css" type="text/css">'; } ?>

c - How to ensure user-input data is an integer -

i new c, know c#. in c#, use tryparse ensure user typed in correct datatype. here basic code have c: int shallowdepth; { printf ("\nenter depth shallow end between 2-5 feet: "); scanf ("%d", &shallowdepth); if (shallowdepth < 2 || shallowdepth > 5) { printf("\nthe depth of shallow end must between 2-5 feet."); } } while (shallowdepth < 2 || shallowdepth > 5); the problem if type characters, such "asdf", program goes crazy , repeatedly says "enter depth shallow end between 2-5 feet: ". i'm not sure why happening, has because expects int , i'm passing characters. so how verify user inputted data of int type before trying store in variable? thanks. this happening because %d scanf refuse touch not number , leaves text in buffer. next time around again reach same text , on. i recommend ditch scanf , try fgets , 1 of functions in strtoxxx family such strtoul or

ubuntu - Is there any downside to setting ulimit really high? -

i running problem many open files tomcat7 on ubuntu 12, increased hard , soft limit on number of open files 4096 , 1024, respectively, 16384. i'm not getting more errors open files, overall cpu% seems have risen. increasing number of max files have cost in cpu time? if not, why not set ulimit extremely high? the entire reason ulimit exists protect overall performance of system preventing process using more resources "normal". "normal" can different depending on doing, setting limits extremely high default defeat purpose of ulimit , allow process use ridiculous amounts of resources. on server without users less critical big multiuser environment, still useful safeguard against buggy or exploited processes. your cpu went because computer doing more work instead of erroring out. ps - want sure there isn't wrong in tomcat environment too... might ok have thousands of open files, don't know application, sign of gone buggy. if is, allowed

cloudcontrol - How can I use cctrlapp without constantly entering credentials? -

i've started playing experimenting cloudcontrol.com . provide cli application called cctrlapp managing projects. however, many useful operations require login. cumbersome , frustrating have put in email address , password every time push current state of app. can ccrtlapp configured use stored credentials? recommended: support authentication via public-keys between cli , api more secure , more convenient. set up, run: $ cctrluser setup read more here: http://www.paasfinder.com/introducing-public-key-authentication-for-cli-and-api/ alternatively: can set credentials via 'cctrl_email' , 'cctrl_password' environment variables. if set, they're automatically used cctrlapp.

modify moses.ini for incremental training -

i need update following moses.ini support incremental training, followed tutorial , found must add line in moses.ini file phrasedictionarydynsuffixarray source=<path-to-source-corpus> target=<path-to-target-corpus> alignment=<path-to-alignments> but no matter how put in moses.ini doesn't work , give errors when try start mt model here how put moses.ini [ttable-file] phrasedictionarydynsuffixarray source=<path-to-source-corpus> target=<path-to-target-corpus> alignment=<path-to-alignments> then set appropriate paths, can me ? in advance

javascript - Overlay line graph on stacked bar in d3.js when x-axis is strings -

i'm having issue adding line graph in svg, partially think because x-axis using months strings. wondering if there way incorporate line when don't have standard date. function barstack(d) { var l = d[0].length while (l--) { var posbase = 0, negbase = 0; d.foreach(function(d) { d=d[l] d.size = math.abs(d.y) if (d.y<0) { d.y0 = negbase negbase-=d.size } else { d.y0 = posbase = posbase + d.size } }) } d.extent= d3.extent(d3.merge(d3.merge(d.map(function(e) { return e.map(function(f) { return [f.y0,f.y0-f.size]})})))) return d } //assets , debts var data = [[{y:3000},{y:2000},{y:2500},{y:1000},{y:3000},{y:5000}], [{y:-700},{y

android - Eclipse device chooser -

my tablets not show in device chooser. ive set api levels android:minsdkversion="8" android:targetsdkversion="19" . turned on usb debugging.i can transfer files , tablet. set run config pick device. tried 4.1.1 , 4.0.3 device. not sure else may missing if you're running windows, check see if there devices listed in device manager without drivers. if strangling "android device" listed, manually install google adb drivers it. can found in android sdk installer.

PHP WebSocket Client? Or way to run JavaScript inside of PHP (without a browser)? Hopefully with Ratchet -

i'm new websockets , have been playing ratchet , gotten simple chat room work on aws ec2 instance. i'm trying use service can run custom php script (hosted on servers) open websocket connection on server , send message. i got ec2 url working, , when run in browser (including on phone, isn't on same network computer) works. i'm passing testing api key , value in url (grabbed php get), so: http://ec2-22-222-22-222.us-west-2.compute.amazonaws.com/path/to/script/ws-trigger.php?key=12345&name=bing this works, because ws-trigger.php page loads following javascript , runs browser: <script type="text/javascript"> var conn = new websocket('ws://22.222.22.222:8080'); conn.onopen = function(e) { console.log("connection established!"); conn.send(<?php echo $_get['name']; ?>); }; </script> what easiest way me run "connect websocket" , "send message on socket" v

php - How to set a variable based on time/date -

how can set variable, $a, specific value based on day of week , time of day. for example, in pseudocode: mon 09.00h - 16.59h, $a = 5, sat 12.00h - 13.00h, $a = 10 $time = time()%86400; $date = date("d"); // since 9 hours = 32400 seconds , 16 hours , 59 minutes = 61140 seconds if($date == "mon" && $time >= 32400 && $time <= 61140){ $a = 5; } // since 12 hours = 43200 seconds , 13 hours = 46800 seconds else if($date == "sat" && $time >= 43200 && $time <= 46800){ $a = 10; }

html - cant set css stylesheet height, width on div from stylesheet -

update: figured out happening. hosts (ipage.com) has type of caching after update css , clear cache show old 1 long time. if web search "ipage css refresh" can read more it. resolved: when put www.domain.com shows old stylesheet had that's not on host anymore. domain.com works fine. don't know why i'm looking it. thank help. i can't seem set height , width of div. if put style inside tag works, style-sheet doesn't. thanks. <html> <head> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="/stylesheet1.css"> <title>website</title> </head> <body> <div id="menu" > <b>item1</b> <br> <b>item2</b> </div> </body> </html> the css is: #menu { display : inline-block; background-c

How to access/verify the contents of the firebase auth object when using firebase simple login? -

is possible access/verify contents of firebase auth object when using firebase simple login? useful debugging / configuring security rules. for additional debugging of auth. token , security rules when using firebase simple login, have 2 great tools @ disposal: enable debug mode, passing optional debug: true flag when generating custom firebase token. cannot automatically when using delegated authentication service due security constraints, may generate tokens via custom login . also, try enabling debug-mode on client library following command, yield additional information such paths being read or written to, , data going on wire: firebase.enablelogging(true, true); authclient.login('twitter', { debug: true }); as suggest, take peek @ contents of authentication token. there few ways this. easiest manually pass firebaseref.auth() , , examine response payload returned in callback, contains contents of auth. token. alternatively, since firebase auth. token

php curl only works on browser. why? -

i have been struggling code through out yesterday , today. no suitable answer on forum can apply.i have used code before , worked perfectly, wonder doing wrong. when enter url , values on browser, works curl function doesn't. when checked error gave me info:0 still doesn't work or post value. here code $contact_phone = $_post['contact_phone']; $message = $_post['message']; function sendmessage($contact_phone, $message) { $postvalue = "sender=$contact_phone&message=$message&pass=***"; $apiurl = "http://mydomain.com/components/com_simserver/sim_api.php?"; //next fake browser form submitted //firefox our choosing browser $browsertype = "mozilla/5.0 (windows; u; windows nt 5.0; en-us; rv:1.4) gecko/20030624 netscape/7.1 (ax)"; /initiating curl library $ci = curl_init(); curl_setopt($ci,curlopt_failonerror,true); //set url used processing data curl_setopt($ci,

list - Breaking a number into groups of threes in Scheme -

i trying create function takes in number , breaks groups of 3 : (group-of-three 12345) -> '(12 345) this code i've been working on: (define (group-of-three n) (cond ((< n 1000) n)) (cond ((> n 1000) (cons (group-of-three (quotient n 1000)) (remainder n 1000))))) and when call (group-of-three 9999) '(# . 999) any appreciated, i'm new scheme i'm sure solution pretty easy , i'm not seeing it. there couple of problems code: cond being used incorrectly, single cond required, 2 mutually exclusive conditions. or simpler, use if expression the base case of recursion wrong, remember: we're building list, result must end empty list to output list in right order, input number ought processed right-to-left. easier if use helper procedure parameter accumulating results - incidentally, produce tail-recursive solution. alternatively, use named let this mean: (define (group-of-three n) (helper n '())) (define (

php - Router Error with CI -

i trying current controller's name following line: $this->router->fetch_class(); i found line here: https://gist.github.com/svizion/2325988 this how i'm trying use in hook. <?php if (!defined('basepath')) exit('no direct script access allowed'); class sys_prescript { public function is_logged_in() { $public_access = array('login', 'registration'); if (!in_array($this->router->fetch_class(), $public_access)) { $user_id = $this -> session -> userdata('user_id'); if (($user_id == false) || (is_numeric($user_id) == false) && (strlen($user_id) < 5)) { redirect('login'); } } } } only issue i"m getting following errors. a php error encountered severity: notice message: undefined property: sys_prescript::$router filename: controllers/sys_prescript.php line number: 9 fa

c++ - What is the purpose and function of the dereference operator in this map? -

std::map< int, std::vector< raddr > * > writesetlist; i understand how map works instance keys of type int , values of type vector holds user defined type "raddr" , name of map writesetlist. dont understand dereference operator doing. value type pointer vector? in advance. couldn't find examples this... that not dereference operator, rather declaration of pointer type. map binds int std::vector<raddr>* , pointer vector of raddr

asp.net - How to pass clientId of a control in Repeater to JavaScript function? -

i have repeater having 2 columns. in first column have image button on click of calling javascript function. in second column have label. want pass client id of label javascript function called on click on imagebutton. <asp:repeater id="rptelements" runat="server"> <itemtemplate> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td> <table> <tr> <td id="tdelementtype" runat="server"> <asp:imagebutton id="imgshow" runat="server" visible="false" onclientclick="return displayelementdetails(this);" /> </td> <td> <asp:label id="lblelementdetails" text='<%# eval("elementdetails")%>&

jquery - sticky subscribe box at bottom -

hi guys m working on sticky subscribe box below site https://generalassemb.ly/ i used following js $.fn.is_on_screen = function(){ var win = $(window); var viewport = { top : win.scrolltop(), left : win.scrollleft() }; viewport.right = viewport.left + win.width(); viewport.bottom = viewport.top + win.height(); var bounds = this.offset(); bounds.right = bounds.left + this.outerwidth(); bounds.bottom = bounds.top + this.outerheight(); return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom)); }; $(window).scroll(function(){ // bind window scroll event if( $('#foot').length > 0 ) { // if target element exists in dom if( $('#foot').is_on_screen() ) { // if target element visible on screen after dom loaded $('.subscribebox').fadeout(1000); } else { $('.subscribebox

c# - Using DateTime to terminate application? -

i'm curious pros , cons of following code terminate application running after date in time. datetime expire = new datetime(2014, 2, 20); if (datetime.now > expire) { messagebox.show("this software's license has expired!"); this.close(); } i'm considering using in small beta software i've written wonder if fool proof or can datetime class "tampered" setting clock on system? i'm not entirely sure if datetime relies on ever os system thinks time or not. yes, datetime.now report current system time, , can affected user changing clock. if wants continue using application after license has expired, can pretty easy crack kind of technique anyway. not mean type of approach has no value you. there's plenty of discussion on around type of idea: create application expire after trial period how make software expire on date on windows what copy protection technique use

php - Session values are not stored after submiting the form -

here enquiry form code..the session not stored after form submission on ie form not retaining values in google chrome fine..all fields in form emptied after submission..i want store values if captcha code incorrect.. can 1 plz help <?php session_start(); ob_flush(); include("header.php"); if(isset($_post["submit"])) { if ($_post["vercode"] != $_session["vercode"] or $_session["vercode"]=='') { $msg="incorrect verification code"; $ssubject = $_post['subject']; $name = $_post['name']; $address = $_post['address']; $_session['subject'] = $ssubject; $_session['name'

javascript - Initiate File Download via GET request -

so have extjs application in open in combo leads download of file (read: export pdf). using window.open in hit specific url restful in nature , similar to. window.open('https://example.com/myapp/api/module/someid/exportpdf.pdf?clientid=bizzare123&param1=somevalue'); this opens new tab , file download. theoretically request (though doesn't appear in chrome devtools' network tab), , want pass json data request body (data large can't fit in request params). can done calling same url using ext.ajax.request , passing jsondata ? (i believe i'll have handle file coming in response within success callback. thanks! p.s. i'm on extjs 4.0 update earlier had request download file support new feature, had customize download sending post request first, , api sent file directly in response post request. but rixo mentioned in comments async download of file might not possible directly, had change api such sends file url instead, in post request,

jsf - javax.el.PropertyNotFoundException: Target Unreachable, identifier 'flowScope' resolved to null -

javax.el.propertynotfoundexception: /flow1/flow1.xhtml @ line 17 , column 70 value="#{flowscope.value}": target unreachable, identifier 'flowscope' resolved null. i have flow.xhtml page there i'm setting value below : <span id="param1fromflow1"> flow bean param1value: <h:inputtext id="input" value="#{flowscope.value}" /> </span> but implicit object flowscope not picking server getting error in websphere 8.0.0.7. after changed page bean .page bean declare @flowscoped ,again getting error below in same page; javax.faces.facesexception: javax.el.propertynotfoundexception: /flow1/flow1.xhtml @ line 17 , column 69 value="#{flow1bean.name}": target unreachable, identifier 'flow1bean' resolved null here bean : package com.webage.beans; import java.io.serializable; import javax.faces.flow.flowscoped; import javax.inject.named; @named @flowscoped("flow1") public cl

android - how to change the intent when ball touch the bottom or top the canvas -

in game ball moves top bottom , bottom top,my requirement when ball touches top edge or bottom edge want print toast message "game over".later want move control other intent.to animate ball using following code public class animatedview extends imageview{ static int count=0; private context mcontext; int x = 130; int y = 450; private float a,b; private int xvelocity = 25; private int yvelocity = 20; private handler h; private final int frame_rate = 30; bitmapdrawable ball; boolean touching; boolean dm_touched = false; float move=3; int bm_x = 0, bm_y = 0, bm_offsetx, bm_offsety,bm_w,bm_h; boolean paused; public animatedview(context context, attributeset attrs) { super(context, attrs); mcontext = context; h = new handler(); } @override public void builddrawingcache() { // todo auto-generated method stub super.builddrawingcache(); }

pointers - How to access a dynamic array in two different functions c++ -

i need access dynamic array in 2 different functions. changes made in 1 need transfer on other. these functions: void populate(int size, int *ptr) { ptr = new int[size]; (int = 0; < size; i++) { ptr[i] = rand() % 51; } } void display(int size, int *ptr) { (int i=0; < size; i++) { cout << ptr[i] << endl; } } it called in main int* ptr = null; in populate , attempting make pointer pass function point dynamically allocated array. pass pointer value . has no effect on caller side, , results in memory leak. need pass either pointer reference: void populate(int size, int*& ptr) ^ or return it int* populate(int size) { int* ptr = new int[size]; .... return ptr; } but easiest , safest thing use std::vector<int> both functions instead. example std::vector<int> populate(size_t size) { std::vector<int> v(size); (auto& : v) {

ios - After creating a Custom CellView of a tableView, still i am not getting the multiple column view. Can anyone help me out? -

Image
i having app wherein have created custom cell uitableviewcell. in main view need 4 rows 4 columns. not getting column view, rows seen in screenshot. i went through many related post did not understand them clearly. can give me exact explanations , related code? if got question , of comments right, table 4 columns required. approach realize such view following. add uitableviewcontroller in storyboard. choose dynamic prototypes cells (and optionally set number of cells 2, if add header row later on). select cell , set style custom. set cell's identifier "warehousecell". set header cell's identifier "headercell". add 4 uilabels each cell , arrange them required. give uilabels of "warehousecell" tags 1 4. assuming have data model consists of array of dictionaries store warehouses (e.g. @property nsarray *warehouses; ), implement in uitableviewcontroller subclass... - (void)viewdidload { [super viewdidload]; self.wa

Scringo framework app crashes in ios? -

i'm facing strange problem, ios app crashes on devices , simulatore, developed app on 1 mac , system , move source code mac, on new mac scringo framework showing different types of crash reports "terminating app due uncaught exception 'nsunknownkeyexception', reason: '[ setvalue:forundefinedkey:]: class not key value coding-compliant key closebutton.'". done lot of googled, didn't solution. contacted scringo support also, didn't response on http://www.scringo.com/about.php the source of error has connection action or outlet called done doesn't exist in code class.

Ruby variable inside shorthand array -

i trying insert variable deploy[:deploy_to] shorthand array below. node[:deploy].each |application, deploy| %w[ #{deploy[:deploy_to]}/current/cache #{deploy[:deploy_to]}/current/public/projects_icons ].each |path| directory path user deploy[:user] group deploy[:group] mode "0777" end end end how can this? %w supports interpolation: %w[ #{deploy[:deploy_to]}/current/cache #{deploy[:deploy_to]}/current/public/projects_icons ].each |path| directory path user deploy[:user] group deploy[:group] mode "0777" end end

IllegalStateException: Could not execute method of the activity with Android -

when press button(named "current location") should shows current address on textview(named "tvaddress") , should place marker on map in meantime.but it's not working expect. it's giving me errors.errors given below. error : 02-05 23:37:22.429: e/androidruntime(20293): fatal exception: main 02-05 23:37:22.429: e/androidruntime(20293): java.lang.illegalstateexception: not execute method of activity 02-05 23:37:22.429: e/androidruntime(20293): @ android.view.view$1.onclick(view.java:3680) 02-05 23:37:22.429: e/androidruntime(20293): @ android.view.view.performclick(view.java:4191) 02-05 23:37:22.429: e/androidruntime(20293): @ android.view.view$performclick.run(view.java:17229) 02-05 23:37:22.429: e/androidruntime(20293): @ android.os.handler.handlecallback(handler.java:615) 02-05 23:37:22.429: e/androidruntime(20293): @ android.os.handler.dispatchmessage(handler.java:92) 02-05 23:37:22.429: e/androidruntime(20293): @ android.os.loope

c++ - about function pointer: why the overhead time changes when the content of the function changes -

here c++ code, , use vs2013, release mode #include <ctime> #include <iostream> void tempfunction(double& a, int n) { = 0; (double = 0; < n; ++i) { += i; } } int main() { int n = 1000; // 1000 8000 double value = 0; auto t0 = std::time(0); (int = 0; < 1000000; ++i) { tempfunction(value, n); } auto t1 = std::time(0); auto tempfunction_time = t1-t0; std::cout << "tempfunction_time = " << tempfunction_time << '\n'; auto tempfunctionptr = &tempfunction; value = 0; t0 = std::time(0); (int = 0; < 1000000; ++i) { (*tempfunctionptr)(value, n); } t1 = std::time(0); auto tempfunctionptr_time = t1-t0; std::cout << "tempfunctionptr_time = " << tempfunctionptr_time << '\n'; std::system("pause"); } i change value of n 1000 8000, , record tempfunction_time , tempfunct

math - PHP (int) / braces mathematically wrong - Possible Bug? -

this question has answer here: int((0.1+0.7)*10) = 7 in several languages. how prevent this? 7 answers me , colleges discussing following problem, , although came theories still seeing odd... <?php echo (int) ((0.1 + 0.7) * 10); ?> outputs 7 whilst <?php echo (int) (0.1 + 0.7) * 10; ?> outputs 8 (as expected , output if calculator) could (int) causing issue here? have idea? thanks lot , day! the cast integer (and related rounding error) occurs @ different point in formula calculate 0.1 plus 0.7, multiply 10 , cast integer; with expected rounding error, should result in 7 against calculate 0.1 plus 0.7, cast integer, , multiply 10 casting 0.1 + 0.7 (ie 0.8) integer should give 0, multiplied 10 still 0

File in the classpath not being published (Eclipse + JBoss AS) -

i working in activejdbc project requires instrumentation step before build in order entity mapping. did adding script generates activejdbc.properties @ classpath. the build part fine , file being generated in workspace. however, when publish project file being packed in war file (all other classes fine though). it simple dynamic web project, no changes in build or classpath besides instrumentation step. using: - os x mavericks. - eclipse juno. - maven 3. - jboss 7. - jre 1.6. i used following tutorial: http://javalite.io/eclipseintegration can guys give me hint on whats going on? there no error or warning in console... i think mean activejdbc_models.properties file. file produced instrumentation process , placed @ root of classpath, target/classes. please see if there. if there, placed @ root of war file: war_root/web-inf/classes. unpack war file , see if there. if not, wring in how create war file.

ios7 - Pixate not styling my views first time after launching app on iPad -

i using pixate style views. whole application works storyboards. app ipad app. i have valid pixate licensekey , setting in main: int main(int argc, char * argv[]) { @autoreleasepool { [pixate licensekey:@"<my pixate license key>" foruser:@"<my email address>"]; return uiapplicationmain(argc, argv, nil, nsstringfromclass([whvvappdelegate class])); } } when launch app first time on device, views have no styling pixate. when kill app, , launch again pixate start working. when saw happening, tried call [pixate updatestylesforallviews]; in [viewdidappear:] method of first view of app. results remain same. anyone familiar problem? how troubleshoot further here? have tried running on device without testflight, rule out?

java - Write variables automatically into child class -

i’m trying achieve following. have several model has basic methods, such savemodel, loadmodel, laodmodel from. now, have other classes extend model, e.g. user , movie. user has variables id username usermail userpw movie has id movietitle movielength moviegenre now, create new user object , load database. when load model movie, have json-object containing following information: id = x movietitle = "bla" movielength = "bla" moviegenre = "bla" as can see, json contains correct key , values, have write them child model. how possible, model writes field values user object? in php this foreach ($row $key=>$val) { $this->$key = $val; } in java, doesn’t seem possible. how can parent class automatically write variables child class. or isn’t possible , have manually? problem see here, is, have every model again, when in super class. how that? one way achieve define parent class have maps holding possible fields; , ha

spring - java temporary files created but contents write issue -

package com.studytrails.tutorials.springremotingrmiserver; import java.lang.object; import java.awt.desktop; import java.io.*; import org.springframework.context.applicationcontext; import org.springframework.context.support.classpathxmlapplicationcontext; import org.springframework.core.io.resource; public class greetingserviceimpl implements greetingservice { @override public string getgreeting(string name) { return "hello " + name + "!"; } public string gettext() { applicationcontext appcontext = new classpathxmlapplicationcontext(new string[]{"spring-config-server.xml"}); resource resource = appcontext.getresource("file:d:\\text\\test.txt"); stringbuilder builder = new stringbuilder(); try{ inputstream = resource.getinputstream(); bufferedreader br = new bufferedreader(new inputstreamreader(is)); file temp=file.createtempfile("output", ".tmp"

ruby on rails - ThinkingSphinx throws 'wrong constant name' error -

i'm using thinkingsphinx on rails 4.0.0 search through customer records. works lot of time throws error: wrong constant name "\u008b­\u0089~\u008föv" with constant name varying depending on searched for. search term escaped etc , alphanumeric only.

ios - How to get verified status of Facebook user in Facebook sdk v3.12 -

i trying access verified status of logged in user.below code have tried faar.i getting verified value null when login using code.is there other permission need add in order access verified status? greatfull. login fbloginview *loginview =[[fbloginview alloc] initwithreadpermissions:@[@"basic_info", @"email", @"user_birthday",@"user_location"]]; loginview.delegate=self; [self.view addsubview:loginview]; login delgate method - (void)loginviewfetcheduserinfo:(fbloginview *)loginview user:(id<fbgraphuser>)user { nslog(@"userinfo %@",[user objectforkey:@"verified"]); } finally got it.it "user_status" permission had add in order verified status. fbloginview *loginview =[[fbloginview alloc] initwithreadpermissions:@[@"basic_info", @"email", @"user_birthday",@"user_location",@"user_status"]];

jquery - Dojo javascript event and query selection issue -

Image
i have menu item. and created event hanler handle parent. on(query(".listmenu"), ".cbinfo:click", function (event) { if (event.type === 'click') { var tooltip = query(this).parent('li'); } }); when click icon now, gives error. uncaught typeerror: object [object object] has no method 'parent' i write console console.log(query(this)) returns: [span.cbinfo, _wrap: function, slice: function, splice: function, indexof: function, lastindexof: function…] but chrome watch expression resurns breakpoint this. do have dojo/nodelist-traverse module loaded?

multithreading - Nodejs to utilize all cores on all CPUs -

i'm going create multithreaded application highly utilize cores on cpus doing intensive io (web browsing) , intensive cpu (analyzis of crawled streams). nodejs (since it's single threaded , don't wanna run couple of nodejs instances [one per single core] , sync between them). or should consider other platform? javascript v8 engine made work async tasks running on 1 core. however, doesn't mean can have multiple cores running same or perhaps, differente applications communicate between each other. you have aware of multiple-cores problems might occur. for example, if going share lots of information between threads, perhaps not best language you. considering factor of multi-core language, have been introduced elixir, based on erlang ( http://elixir-lang.org/ ). it cool language, developed 100% thinking multi-thread applications. made make easy, , fast applications can scalonable many cores want/can. back node, answer yes, support multi-thread, decide

sql - Updating a table with the result of a query on 2 other tables -

i need update column on table value result of query. however, customerid column on receiving table needs matched customer id column on query. here query far: insert paymentfacilities (policyid) (select c.id, p.policyid customers c inner join policies p on c.id = p.customerid (not (p.policyreference null) , p.cancelled = 0)) in example above want insert p.policyid field select query policyid column of paymentfacilities table customerid field of paymentfacilities matches c.id field select query. thanks help the number of columns in select statement should same insert statement. you try removing columns except p.policyid1 : insert paymentfacilities (policyid) (select p.policyid customers c inner join policies p on c.id = p.customerid (not (p.policyreference null) , p.cancelled = 0)) keep in mind insert multple rows, , every time run query have duplicates. if describ

How to disable the EDIT-TEXT in android for entire activity -

how disable edit-text after clicking button entire activity? here have 2 or more activities example: activity , b contains both edit_text , button in activity entered values in edit_text , click ok button in coding part mentioned edittext1.setenabled(false) . here edittext1 disabled after switching activity b, , activity b activity a. edittext1 enabled can 1 tell me how disable edittext1 entire activity in advance add = (button) findviewbyid(r.id.button1); add.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { ed = (edittext) findviewbyid(r.id.edittext1); final string sq=ed.gettext().tostring(); if(sq.equals("a") || sq.equals("a")) { result++; display.settext(""+result);} } }); in activity a read edittext1 i.e findviewbyid , set edittext1.setenabled(false) on onresume() method of ac

mysql - Confusion in JOIN Query -

Image
select i.invoice_date inv, i.invoice_id, i.total_amount, oi.invoice_date oi_inv, oi.offline_invoice_number, oi.invoice_amount ci_invoices left join ci_offline_invoice oi on oi.customer_id = 9 i.customer_id = 9 order i.invoice_date limit 10 this query give result as see in screenshot have 1 row in highlighted section , want result according date: 2014-02-03 2014-01-16 2014-01-16 2014-01-16 2014-01-16 2014-01-16 .......... but got date 2014-02-03 every time(limit 10) try this select i.invoice_date inv, i.invoice_id, i.total_amount, oi.invoice_date oi_inv, oi.offline_invoice_number, oi.invoice_amount ci_invoices left join ci_offline_invoice oi on oi.customer_id = i.customer_id i.customer_id = 9 order i.invoice_date limit 10 ** edit ** they not same thing