Posts

Showing posts from August, 2011

c# - Grouping Row In Datatable -

i have data this.. id 1234-001 1234-002 1234-003 5678-001 7890-001 7890-002 i holding data in datatable. attempting processing on rows groups based on base number i.e. 1234, 5678, 7890 how can iterate through datatable , hold in new (temp) datatable 1234-001,1234-002, 1234-003 clear temp datatable hold 5678-001 clear temp datatable hold 7890-001,7890-002 i working on old code base , linq not available. cant come elegant solution. maybe dataviews im not sure? you don't want use linq prefer elegant solution... unless missing vital in question, linqified code seems let want. var grouped = d in data group d d.id.split('-').firstordefault(); foreach(var g in grouped) { // each group } non-linq, non-var answer: datatable data = new datatable(); data.columns.add("id"); data.columns.add("value"); data.rows.add("1234-001", "row 1"); data.rows.add("1234-002", "row 2"); data.rows.add(&

c# - Dynamically Add Rows in Google Visualization API (JavaScript) -

i working on asp.net mvc 3 project requires me upload a.xls / .xlsx user input, load datatable , place visual of in view. sounds easy enough... i able create datatable , pass object view, unable render data table on view via google's visualization api -- of examples have seen require statically denoted fields, i.e.: var data = new google.visualization.datatable(); data.addcolumn('string', 'task'); data.addcolumn('number', 'hours per day'); data.addrows([ ['work', 11], ['eat', 2], ['commute', 2], ['watch tv', 2], ['sleep', {v:7, f:'7.000'}] ]); however, since application taking user input, column headers, dimensions, , content dynamic. looking way add data dynamically. here code have, model datatable being passed in: @model system.data.datatable @using gridmvc.html @{ viewbag.title = "file upload"; <h2>@viewbag.message</h2> } <html> <head&

jquery - Javascript Code For HTML5 Form Validation Not Working -

i'm new javascript have no idea why code not work , validate html5 form should. the javascript code can found below supposed check if browser supports required attribute , if doesn't validate form , check empty spaces. i got code this website . in body of webpage containing form have this: below contactvalidate.js file: $('#formtemplate').submit(function() { if (!attributesupported("required") || ($.browser.safari)) { $("#formtemplate [required]").each(function(index) { if (!$(this).val()) { alert("please fill required fields."); return false; } }); } return false; }); do need change in code or should work? as i've said i'm new javascript guys give me appreciated. edit : here updated code: $(function(){ $('#contactform').submit(function() { if (!attributesupported("required") || ($.browser.safari)) { $("#contactform [req

node.js - Splitting big main file in modules: can modules functions access main.js variables and modify them? -

i have file named server.js 1267 lines of code right now, , want modularize file make better, don't know if possible, since didn't have intention modularize file in begin(i didn't think file big). have bunch of functions related db, control application , others, i'd split functions in different files(eg: db functions in db.js), i've run problem: i'm using variables inside functions inside server.js, can't read/modify them. should done?

mysql - Is it good practice to keep 2 related tables (using auto_increment PK) to have the same Max of auto_increment ID when table1 got modified? -

let see example, have 2 interrelated tables: table1 textid - text 1 - love.. 2 - men... ... table2 rid - textid 1 - 1 2 - 2 ... note: in table1: textid auto_increment primary key in table2: rid auto_increment primary key & textid foreign key the relationship 1 rid have 1 , 1 textid 1 textid can have few rid . so, when table1 got modification table2 should updated accordingly. ok, here fictitious example. build complicated system. when modify 1 record in table1, need keep track of related record in table2. keep track, can this: option 1 : when modify record in table1, try modify related record in table 2. quite hard in term of programming expecially very complicated system. option 2 : instead of modifying related record in table2, decided delete old record in table 2 & insert new one. easier program. for example, suppose using option2, when modify record 1,2,3,....,100 in table1, table2 this: table2 rid - textid 101 -

php - Using arrays/strings for mysqli prep statement -

i'm running issue mysqli prepared statement. it's rookie mistake; i'm not familiar things this. appreciated. i have 2 arrays, $alpha[] , $bravo[] . both have 20 pairings, simplify: $alpha = array('name', 'age', 'color'); $bravo = array( 'name' => 'john doe', 'age' => 22, 'color' => 'blue', ); i want insert data $bravo[] table defining column headers $alpha[] , binding data $bravo[] query, , executing query. here's example of want do: $columns = implode(',', $alpha); $query_values = '?,?,?'; $query = "insert table ($columns) values ($query_values)"; $type = 'sis'; $real_values = implode(',', $bravo); if($stmt = $mysqli->prepare($query)){ $stmt->bind_param($type, $real_values); if($stmt->execute()){ // success } } this not working me - or insight guys can offer (including other ways accomplish want

visual studio 2012 - cocos2dx c++ looping through cocos2d::Vector -

hi kind of new c++ , cocos2dx. trying following: //mainscene.cpp vector<string> frames; frames.pushback("ground"); frames.pushback("sky_bg"); each (string sprite_name in frames) { } this gives following error in vs2012 a 'for each' statement cannot operate on expression of type "cocos2d::vector so how should going this? correct way use : for (const string& sprite_name : frames) { // code }

Azure virtual machine underlined hardware replacement -

my azure vm experiencing disk drive errors. lot of messages "the io operation @ logical block address xxx disk 1 retried" appeared in event log , services fail because of io timeouts. seems underlined hardware failing. possible migrate vm somehow vm use underlined hardware? during hardware failure, azure infrastructure automatically reprovision vm - however, try handling proactively want open support ticket azure management portal.

android - Why is my custom object not persisted by onSaveInstanceState and onRestoreInstanceState -

when activity gets called first time, called in intent. received , stored in data member: class editblindscheduleactivity extends activity { private blindschedule blindschedule; protected void oncreate(bundle savedinstancestate) { ... if (savedinstancestate == null) { // not recreating, first load. blindschedule = (blindschedule) getintent().getserializableextra("blindschedule"); } there simple if/else determine if have blindschedule object or not. if (blindschedule == null) { settitle("create blind schedule"); } else { settitle("edit blind schedule"); } when load activity first time, indeed, title "edit blind schedule", meaning there blindschedule object. unfortunately, when rotate screen twice title reads "create blind schedule", meaning blindschedule object null , has failed persisted. why blindschedule object not being persisted, , can it? full code follows: public class editblind

android - sound stop when device sleeps flex mobile -

i developing simple android mobile app using flex. want download mp3 internet , save on sd card play it. my problems: 1. can download , play file can't save mp3 2. when device idle sometime , goes sleep mode, sound stops how can achieve that. regards, i looked through android powermanager api , found following working <uses-permission android:name="android.permission.partial_wake_lock" /> this allow process run after user presses power button or screen went dim. regards,

c# - Returning a large collection serialized as JSON via MVC controller -

i have large result set want return ajax call using json. i started creating collection of objects , serialize collection collection creation throw system.outofmemoryexception. i've tried change implementation stream json without having collection still system.outofmemoryexception. here current code snippets. using (var stream = new memorystream()) { using (var streamwriter = new streamwriter(stream)) { using (var jsonwriter = new jsontextwriter(streamwriter)) { var serializer = new jsonserializer(); serializer.serialize(jsonwriter,new { pins = makepins(model), missinglocations = 0 }); jsonwriter.flush(); } } stream.seek(0, seekorigin.begin); return new filestreamresult(stream, "application/json"); the makepins function looks this: var pindata = _geographyservice.getenumerationqueryable() .selectmany(x => x.enumeratedpersonrolecollection

Remove stopwords with javascript and regex -

i want remove stopwords text fail use regex , variables properly. example remove stopword "he" affects word "when". tried use word boundaries this: new regexp('\b'+stopwords[i]+'\b' , 'g') doesn't work... see small example here: jsfiddle var stopwords = ['as', 'at', 'he', 'the', 'was']; (i = 0; < stopwords.length; i++) { str = str.replace(new regexp(stopwords[i], 'g'), ''); } something maybe str = str.replace(new regexp('\\b('+stopwords.join('|')+')\\b', 'g'), ''); fiddle you have double escape in regexp, , join creating /\b(as|at|he|the|was)\b/g

Stop a YouTube embed video -

to embed youtube video , make begin specific second can add &start=25 @ end of src in example. question is: there way can stop video @ specific minute? (of course &stop=45 not work) here have example try: http://jsfiddle.net/79cd2/ <iframe width="640" height="360" src="//www.youtube.com/embed/amamk6hlyay?rel=0&start=25" frameborder="0" allowfullscreen></iframe> please use "end" <iframe width="640" height="360" src="//www.youtube.com/embed/amamk6hlyay?rel=0&start=25&end=32" frameborder="0" allowfullscreen></iframe>

laravel - Eloquent where condition based on a "belongs to" relationship -

let's have following model: class movie extends eloquent { public function director() { return $this->belongsto('director'); } } now i'd fetch movies using condition that's based on column directors table. is there way achieve this? couldn't find documentation on conditions based on belongs relationship. you may try (check querying relations on laravel website): $movies = movie::wherehas('director', function($q) { $q->where('name', 'great'); })->get(); also if reverse query like: $directorswithmovies = director::with('movies')->where('name', 'great')->get(); // access movies collection $movies = $directorswithmovies->movies; for need declare hasmany relationship in director model: public function movies() { return $this->hasmany('movie'); }

php - number of bound variables doesn't match number of tokens -

this question has answer here: warning: pdostatement::execute(): sqlstate[hy093]: invalid parameter number: number of bound variables not match number of tokens in 5 answers here sample of problem occurs. browser says error @ stmt->execute() ; function login($email, $password, $dbobj) { if ($stmt = $dbobj->prepare("select username, db_password, salt accounts email = :email limit 1")) { $stmt->bindparam(':username', $username); $stmt->bindparam(':db_password', $db_password); $stmt->bindparam(':salt', $salt); $stmt->bindparam(':email', $email); $stmt->execute(); // problem here $stmt->fetch(pdo::fetch_obj); $password = hash('sha512', $password . $salt); if ($stmt->rowcount() == 1)

python - How to implement Garbage Collection in Numpy -

i have file called main.py , references file optimisers.py has functions in , used in for loop in main.py . these functions have different optimisation functions in them. this optimisers.py references 2 other similar files functions in them well, in while loops. of these files use numpy. i believe because of loops functions calling on , creating arrays in numpy, leading memory overload. therefore cannot finish optimisation algorithms, or cycle through possible coordinates to. how ensure removal of variables in numpy? understand it, numpy's c libraries complicate standard python process. %reset array command (from link below) do? , should implement it? p.s. i've read " releasing memory of huge numpy array in ipython ", , gc.collect() not work either. when numpy array no longer referenced, automatically freed gc. c objects wrapped in python objects, should not matter how it's implemented. make sure arrays not referenced in global variab

sql - Schedule Windows Service to run once daily -

i have stored procedure written in sql server 2008 r2 needs run daily. stored procedure accepts parameters 2 dates start date & end date , based on these dates fetches data table a , writes table b . in order automate task of running stored procedure daily, have written windows service. have scheduled task in service1.cs follows: system.timers.timer otimer = null; public serviceexample() { initializecomponent(); otimer = new system.timers.timer(); settimer(); } private void settimer() { datetime currenttime = datetime.now; int intervaltoelapse = 0; datetime scheduletime = new datetime(currenttime.year, currenttime.month, currenttime.day, 8, 0, 0); //run @ 8 every morning if (currenttime <= scheduletime) intervaltoelapse = (int)scheduletime.subtract(currenttime).totalseconds; else intervaltoelapse = (int)scheduletime.adddays(1).subtract(currenttime).totalseconds; otimer = new system.timers.timer(intervaltoelapse); otimer.e

java - How do I redirect the output of one process as an input to another process? -

this question has answer here: what simple explanation how pipes work in bash? 8 answers i need execute command, ps -aux | awk ' /^user/ { system("pstree " $2) }' can't execute both in 1 process execute both in separate processes , redirect output of ps -aux process input awk process.how code this? please help. the pipe character ( | ) connects standard output of command left standard input of command right. it's doing ask. if question related java, want official pipe class (courtesy @kajacx).

multithreading - C - WinAPI - send message to thread and wait for it -

i want send message in winapi window, created in other thread , wait process message. is possible? in advance. use sendmessage() send message window. sendmessage() blocks calling thread until message had been delivered and processed target window's message dispatcher. from sendmessage() 's documentation : sends specified message window or windows. sendmessage function calls window procedure specified window , not return until window procedure has processed message.

multithreading - How does a single threaded engine such as noflo implement flow based programming? -

paul morrison says here the core concept of fbp of multiple component processes running asynchronously, communicating means of streams of data chunks run across called bounded buffers. so, how single threaded implementations such noflojs built on node.js simulate multiple concurrent asynchronous processes? , can same method used in other single threaded languages? not entirely sure scope of question is. but can tell node.js based on reactor design pattern . it possible emulate pattern in single-threaded language implementation, assuming adequate eventing model. means long-running process must delegated to, send event when ready...with reactor brokering exchange.

python - Dividing a list of vertices between left and right sides -

i trying divide spheres selected vertices between left , right (by measuring the vertices x value via pointposition ). if have 2 vertices on left , 1 on right selected however, returns have 3 on left, instead of 2 on left , 1 on right. how should restructure loop correctly creates exclusively left or right list? import maya.cmds mc iobj = mc.ls( sl = true, flatten = true ) selsize = len( iobj ) numvert in range ( 0, selsize ): possel = mc.ls( sl = true, flatten = true ) posselpos = mc.pointposition( possel[ numvert ], world = true ) if posselpos[ 0 ] > 0: leftverts.append( possel ) leftsidesize = len( leftverts[ 0 ] ) print "lside has " + "%s" % ( leftsidesize ) print leftsidesize print leftverts[ 0 ] elif posselpos[ 0 ] < 0: rightverts.append( possel ) rightsidesize = len( rightverts[ 0 ] ) print "rside has " + "%s" % ( rightsidesiz

objective c - iOS tableView with sections - how to get global index -

i have question : created table multiple sections (they set webservice response, dynamic). example, first section have 3 cells (0,1,2), second section - 4 cells (0,1,2,3), third section - 7 cells (0,1,2,3,4,5,6). when click, example, on third cell in third section, can number in cell (third section), , number of cell in current section (third cell). know, no matter section, cell's number (so, in above example - third cell in third section, tenth cell) what do? how number? for example in tableview:cellforrowatindexpath: if want use in cell text. -(uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath { //.... nsinteger sum = 0; for(nsinteger idx = 0; idx < indexpath.section, ++idx){ sum += [tableview tableview:tableview numberofrowsinsection:idx]; } sum += indexpath.row +1; //.... } but tableview:didselectrowatindexpath: work.

ios - reload REFrostedViewController -

i have implemented refrostedviewcontroller , amazing. menu implemented correct view controllers (when correct row tapped, goes appropriate view controller). however, unable reload menu new view controllers , labels depending on flow of application. for example, assume menu has row called "sign in" take user "signinviewcontroller". let's assume signed in successfully. wish reload menu row says "sign out" , contains "signoutviewcontroller". can tell me how can done? of now, menu rows , view controllers created @ initialization within demomenuviewcontroller.m (in uitableview delegate methods). you - simplicity, code has single section in menu. @property (strong,nonatomic) nsmutable array *menutitles; -(void) viewdidload { [super viewdidload]; self.menutitles=[[nsmutablearray alloc]init]; [self.menutitles addobject:@"login"]; // can change later using [self.menutitles setobject:@"logout"

java - Building First App Tutorial Button not working -

so, i'm trying make android app tutorial on android page, build first app.( https://developer.android.com/training/basics/firstapp/index.html?hl=it ) i'm doing on intellji, found bit different.. so, made third part, make interface, things got weird in forth part, create activity. i created displaymessageactivity.java file, , copied code site. problem found because file wasn't made automatically, or other reason, intellij didn't know r.id.action_settings , container. so, looked on code, , figured now, "start activity" section, needed "oncreate" method. greyed out theonoptionsitemselected boolean now. when ran this, however, interface came out send button didn't when suppose show new page message... so, wondering how fixed. these codes myactivity.java package com.example.myfirstapp; import android.app.activity; import android.content.intent; import android.os.bundle; import android.view.view; import android.widget.button; import and

c# - Error using Windows Phone 8.1 mmppf - getting parse exception when trying to navigate to page -

i'm getting weird exception when trying navigate page in windows phone 8.1 application (universal) a first chance exception of type 'windows.ui.xaml.markup.xamlparseexception' occurred in myapplcation.exe winrt information: cannot create instance of type '%0' [line: 25 position: 44] it says: the text associated error code not found. i have code in mainpage.xaml.cs navigates page called details: private void button_click(object sender, routedeventargs e) { frame.navigate(typeof(details)); } details has little code: <page x:class="myapplcation.views.details" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:myapplcationviews" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/200

javascript - sending image to my c# application -

i made code camera feed in javascript using getusermedia in html5. want send image c# api. question related this, sending base64 string c# server no luck. want ask other way send image html5 , javascript c# server. found interesting article on 1 on @ ode code . shows how write both javascript , c# code handle posting content of image captured html5 video element (from previous blog post ) c# asp.net server. code not difficult follow. i'd regex little differently, should work you. you can 'capture' current content of video object drawing html canvas , convert content of canvas data: uri can post c# application. the fun part converting data: uri image, ode code article shows how do. after you. o2c code saves disk, run through memorystream , load memory using system.drawing.image.fromstream or similar.

java - iText combining rowspan and colspan - PDFPTable -

Image
working on calendar projcet , using itext generate pdf print appointments. can plot cell colspan, , cell rowspan, can't combine it. table has width of 4 cells. want achieve this: (a)(b)(c)(c) (d)(e)(c)(c) so (1,1), (1,2) , (2,1) (2,2) regular cells. there should cell in (1,3) covering (1,3) (1,4) (2,3) , (2,4) having colspan of 2 , rowspan of 2. current code: pdfptable table = new pdfptable(4); pdfpcell cell = new pdfpcell(new phrase(" 1,1 ")); table.addcell(cell); cell = new pdfpcell(new phrase(" 1,2 ")); table.addcell(cell); pdfpcell cell23 = new pdfpcell(new phrase("multi 1,3 , 1,4")); cell23.setcolspan(2); cell23.setrowspan(2); table.addcell(cell23); cell = new pdfpcell(new phrase(" 2,1 ")); table.addcell(cell); cell = new pdfpcell(new phrase(" 2,2 ")); table.addcell(cell); // 2,3 , 2,4 should filled because 1,3 has rowspan 2 , c

javascript - HttpContext.Current.Response.End() skip the execution -

i exporting gridview excel sheet through javascript using webmethod . since rows in gridview contains template controls label,anchor,etc ., created @ runtime through javascript not @ design, use pass rows array web method. export have created table , map array returned javascript function. problem while debugging, execution skipped on httpcontext.current.response.end , couldn't export grid. don't know why happening. below code of web method <webmethod(enablesession:=true, transactionoption:=enterpriseservices.transactionoption.requiresnew)> _ <scriptmethod(responseformat:=responseformat.xml, usehttpget:=true)> _ public shared sub xlexport(byval filename string, byval row object()()) httpcontext.current.response.clear() httpcontext.current.response.addheader("content-disposition", string.format("attachment; filename={0}", filename)) httpcontext.current.response.contenttype = "application/vnd.ms-excel" dim sw s

objective c - Split string by particular character ,iOS -

this question has answer here: nsstring tokenize in objective-c 9 answers i have string structured in way: "description#data#img" what's best method obtain 3 distinct strings through position of sharps? nsstring *str=@"description#data#img"; //is str nsarray *items = [str componentsseparatedbystring:@"#"]; //take 1 array split string nsstring *str1=[items objectatindex:0]; //shows description nsstring *str2=[items objectatindex:1]; //shows data nsstring *str3=[items objectatindex:2]; // shows img nslog(@"your 3 stirs ==%@ %@ %@", str1, str2, str3); swift //is str var str: string = "description#data#img" let items = string.components(separatedby: "#") //take 1 array split string var str1: string = items.objectatindex(0) //shows description var str2: string = items.

javascript - Create arraybuffer from large Blob in Chrome -

i have simple method creating arraybuffer blob: var blob=somehowgetblob(); var reader = new filereader; reader.onload = function () { oncomplete(reader.result); }; reader.onerror = function (err) { switch (err.target["error"].code) { case err.target["error"].not_found_err: console.log("not found"); break; case err.target["error"].not_readable_err: console.log("not read"); break; default: console.log("default"); break; }; }; reader.readasarraybuffer(blob); everything normal it's supposed , reader triggers onload event when ran in ie11, in chrome normal if blob has small size (i tested 4mb), when tested using 90mb, triggers not_found_err, is normal? or there workarounds? or bug in chrome?

c# - How would you go about detecting events defined by libraries in other classes? -

so i'm working sdldotnet - converts sdl calls c# should , ran issue. that issue being because sdldotnet running in different class main part of application - can't detect when it's closing. the sdldotnet library has event fires when told close, , event is: sdldotnet.core.events.quit in object viewer - event shown such: public static event system.eventhandler<quiteventargs> quit member of sdldotnet.core.events what i've done, there main windows form application calls upon sdl class so: private void drawtoscreen() { //starts sdl off drawing screen sdldraw sdl = new sdldraw(); sdl.startdrawing(); //how go detecting sdldotnet.events.quit //from class i've instanced //when on original windows forms implementation //it worked this: ////sdl.formclosed += new formclosedeventhandler(detectclose); //but copying structure , trying ////sdl.events.quit += new quitargs(detectclose); //doesn't have same

c# - Visual Studio How to Publish Application that uses data from an Online Database -

Image
hi published desktop application on visual studio clickonce installation seem have problems sql , entity framework exceptions software uses in order display data. there other way around problem ? here image of happens when user wants see specific data. exceptions range both sql , entity frameworks. happens upon computer , not mine software created on. any appreciated ! if wish deploy database application binaries can try sql server compact instead of full version of server, requires server installed on machine. msdn link here process - http://msdn.microsoft.com/en-us/library/aa983326(v=vs.110).aspx and can download application here - http://www.microsoft.com/en-us/download/details.aspx?id=17876 in short, sql server compact databases files (.sdf) can deployed along application , binaries , dlls work on destination. msdn topic show how this. the full documentation , starting point here - http://msdn.microsoft.com/en-us/library/aa983321(v=vs.110).aspx import

javascript - jQuery Mobile 1.4.2 + Photoswipe Associates All The Links With Itself -

i have implemented photoswipe jquery mobile 1.4.2. gallery works perfecty after viewing gallery navigation links, etc. being associated photoswipe , link blank photoswipe images cannot leave page. live demo: http://jsfiddle.net/flymen8888/jfw7s/6/ $("#gallery a").photoswipe( { jquerymobile: true, loop: false, enablemousewheel: false, enablekeyboard: false }); any ideas how fix it? change $("#gallery a").photoswipe $("#gallery .gallery-item a").photoswipe .

c++ - template template parameters with boost::fast_pool_allocator -

why doesn't compile: std::map<int, int, std::less<int>, boost::fast_pool_allocator< std::pair< int, int > > a_test; but compiles fine: typedef boost::fast_pool_allocator< std::pair< int, int > > fast_alloc; std::map<int, int, std::less<int>, fast_alloc > a_test; a separate question: far can see in definition of boost::fast_pool_allocator takes 4 non-defaulted template parameters, in example above works fine. can please explain reason this? thanks! your definition should read std::map< int, int, std::less<int>, boost::fast_pool_allocator< std::pair< int, int > > > a_test; you should format longer template instantiations parameters on separate lines. way cannot miss closing brackets. boost::fast_pool_allocator forward-declared default template parameters in poolfwd.hpp . just clarify naming conventions: allocator parameter not template template parameter here since specif

cuda-gdb Error message -

i tried debug cuda application cuda-gdb got weird error. i set option -g -g -o0 build application. run program without cuda-gdb, didn't correct result. hence decided use cuda-gdb, however, got following error message while running program cuda-gdb error: failed read valid warps mask (dev=1, sm=0, error=16). what means? why sm=0 , what's meaning of error=16 ? update 1 : tried use cuda-gdb cuda samples, fails same problem. installed cuda 6.0 toolkit followed instruction of nvidia. problem of system? update 2 : os - centos 6.5 gpu 1 quadro 400 2 tesla c2070 i'm using 1 gpu program, i've got same bug message gpu selected cuda version - 6.0 gpu driver nvrm version: nvidia unix x86_64 kernel module 331.62 wed mar 19 18:20:03 pdt 2014 gcc version: gcc version 4.4.7 20120313 (red hat 4.4.7-4) (gcc) update 3 : tried more information in cuda-gdb, got following results (cuda-gdb) info cuda devices error: failed read valid warps mask (dev=1, s

Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago... -

i trying convert timestamp of format 2009-09-12 20:57:19 , turn 3 minutes ago php. i found useful script this, think it's looking different format used time variable. script i'm wanting modify work format is: function _ago($tm,$rcs = 0) { $cur_tm = time(); $dif = $cur_tm-$tm; $pds = array('second','minute','hour','day','week','month','year','decade'); $lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600); for($v = sizeof($lngh)-1; ($v >= 0)&&(($no = $dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm-($dif%$lngh[$v]); $no = floor($no); if($no <> 1) $pds[$v] .='s'; $x = sprintf("%d %s ",$no,$pds[$v]); if(($rcs == 1)&&($v >= 1)&&(($cur_tm-$_tm) > 0)) $x .= time_ago($_tm); return $x; } i think on first few lines script trying looks (di

c# - Move a rectangle using angles -

Image
i need move rectangle using angles. want change direction of moving rectangle when reaches location have given in code in if statement! i need way can find out how move rectangle @ 60, 30, 60, 120, 150, 270 degrees! suppose if circle.y>=this.height-80 see this: i need change direction of rectangle movement using angles! @ location reaches can change rectangle direction according angle of own choice! such that: if(circle.y>=this.height-80) move in direction of 90 degrees if(circle.x>=this.width-80) move in direction of 60 degree as can see in screen shot! what have been trying is: public partial class form1 : form { rectangle circle; double dx = 2; double dy = 2; public form1() { initializecomponent(); circle = new rectangle(10, 10, 40, 40); } private void form1_load(object sender, eventargs e) { this.refresh(); } private void form1_paint(object sender, painteventargs e)

javascript - Plotting Global variable Highcharts -

after many failed attempts, thought let smarter me correct me. creating simple chart using highcharts. data retrieved once (php code below) using $.post method. in console see formatted. yet, cannot highcharts display it. have tried many different ways variety of posts still nothing. everything works fine if use $.getjson , create chart. however, end user go , forth many time review same data. not want query every time. idea place data on global variable using data generate chart. here php: <?php require_once "../includes/config_rev.php"; require_once "../includes/connect.php"; global $db; $st = $db->prepare("select * mdo"); $st->execute(); $category = array(); $category['name'] = 'mes'; $series1 = array(); $series1['name'] = 'temporeros'; $series2 = array(); $series2['name'] = 'planta'; $series3 = array

c# - MVC 3 EF Migrations on Multiple Database Instances -

all, i trying solve seemingly common problem of updating our development database , our production database simultaneously, whenever change made our development database. something this: pm > add-migration addmynewcolumncolumntomytable pm > update-database - dev pm > update-database - prod i've seen solutions while researching nothing yet simple , straight forward running sqlcompare on dev , production databases , exporting , running sql script on production database. how doing this? thanks well long both of databases following same migration stream meaning both created same migration , updated in same chronological order, should not have issues using same migrations. what can create 2 connection strings in web.config (or app.config) , when updating database use following syntax: update-database -connectionstringname yourproddbcontextconnectionstringname so assume have 5 migrations total: migration1, migration2, migration3, migration4 , mig

xml - Datepicker on Android-studio looks different in two different apps I am coding? -

Image
i'm coding 2 different apps on android-studio (one built ground up, has been worked on while). i've added datepicker xml both apps: <datepicker android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/datepicker" android:calendarviewshown="false" android:layout_below="@+id/addturtledialogbutton" android:layout_alignparentleft="true" android:layout_alignparentstart="true" /> but 1 of them looks this: and other looks this: i'd other app have better, updated looking datepicker , i've been fiddling styles , themes, haven't been able change first datepicker looks like. help! date picker pop affected aap them mentioned @ manifest file change app them in manifest file different look. hope you! you can change below <style name="appbasetheme&

c++ - How to make indentation smaller in qt tooltips with html listing format? -

i using html listing format write tooltips in qt below. widget->settooltip(tr("<ul><li>first sentence</li></ul>")); i found indentation large. how can set indentation smaller? quite time has passed here information might you. after doing digging , because qt designer replacing , screwing html wanted use tooltip looked closely , found following: <ul style="margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; -qt-list-indent:x;"> ... </ul> with x being number >= 0 (0 equivalent of left alignment). <li/> etc. can use -qt-block-indent:x inside style parameter of tag. that sad unable make indention less without loosing bullet points. if set -qt-list-indent:0 have (as mentioned above) text on several lines left alignment. if set -qt-list-indent:1 default behaviour want change. i'm not of css/html person , qt documentation extremely lacking on topic believe decimal value

javascript - Getting an element by its CSS class name starting with a dot -

i had rename css class used start # sign dot handled extjs framework properly. that jquery script used work fine until made change, whines cannot find element. i'm not used jquery, question is supposed work? $('.x-panel-body-cssmenu li.has-sub>a').on('click', function(){ //some code errors out because .x-panel-body-cssmenu can't found apparently... }); this html in question: <div class="x-panel x-border-item x-box-item x-panel-cssmenu" style="height: 441px; right: auto; left: 0px; top: 100px; margin: 0px; width: 200px;" id="navigationmenu-1011"> <div id="navigationmenu-1011-body" class="x-panel-body x-panel-body-cssmenu x-layout-fit x-panel-body-cssmenu" style="height: 441px; left: 0px; top: 0px; width: 200px;"> <ul> <li class="active"><a href="#"><span>home</span></a></li&

java - HTML Web Application Notification System -

i'm using play framework 2.3 (java) , mysql. i'm building notification system reads "notifications" table in mysql. i've tried using ajax polling request sent asynchronously every 30 seconds, table read , if new notifications exist, sent via json client. however, performance concerning, many concurrent users. what's best way build such system? there particular java libraries work this? thanks in advance. i see read fast, you're using play framework, don't know. quick search reveals has websocket capabilities: http://www.playframework.com/documentation/2.3.x/javawebsockets ---- old answer below ---- if you're using jee7, why not try use websockets? limit application 'newer' browsers, supporting websockets, improve performance, since connection bi-directional , suffers less overhead. more information on subject can found here: http://docs.oracle.com/javaee/7/tutorial/doc/websocket.htm i've found following

php - SugarCRM SugarLogic Formulas -

in sugarcrm i'm trying make dependent field visible if sales stage equal "closed won" or "closed lost." using formula builder found can recognize 1 way: equal($sales_stage,"closed won") but don't understand formula(s) use both. this should it: or(equal($sales_stage,"closed won"),equal($sales_stage,"closed lost"))

java - Missing permissions attribute in main jar (but it exists in the jar) -

background main.jar <-- main codebase util.jar html code: <applet id="app" archive="main.jar,util.jar" code="com/business/app/app.class" mayscript="true"> ... params ... </applet> error "missing required permissions manifest attribute in main jar http://localhost/main.jar " what have done i signed both jar files our certificate , running following fine. jarsigner -verify main.jar jarsigner -verify util.jar also, included manifest before signing jar files. in main.jar have manifest.mf file: manifest-version: 1.0 ant-version: apache ant 1.8.4 codebase: * permissions: all-permissions application-library-allowable-codebase: * caller-allowable-codebase: * application-name: appname created-by: 1.7.0_45-b18 (oracle corporation) i have taken @ following question no avail securityexception during executing jnlp file (missing required permissions manifest

file - Saving hex data in binary using PHP does not work properly -

i learning php , files , trying write code put data in binary file. here's code: write <?php echo "\n\nwrite: \n\n"; $c = array(); $data = ''; $c['name'] = 'abcdefghijklmnopqrstuvwxyz'; $data .= implode('', $c); $fp = fopen('test.bin', 'wb'); $len = strlen($data); echo "\nfile content: $data (strlen: $len)\n\n"; ($i = 0; $i < $len; ++$i) { $hx = dechex(ord($data{$i})); fwrite($fp, pack("c", $hx)); } echo "last char is: $hx mean: "; echo chr(hexdec('7a')); echo "\n--------------------------------------------\n"; fclose($fp); output file content: abcdefghijklmnopqrstuvwxyz (strlen: 26) last char is: 7a mean: z read <?php echo "\n--------------------------------------------\n"; echo "\n\nread: \n\n"; $fp = fopen('test.bin', 'rb'); $fseek = fseek($fp, 0, seek_set); if($fseek == -1) { return false; } $da