Posts

Showing posts from June, 2010

c# - Flatten List<string[]> into single string with one line for each element -

i have instance of type list<string[]> convert string each string[] on newline. i'm using following linq query flatten out list i'm not sure how can add new line between each string[] without expanding query far more ugly. there way without gutting query , using string.join or ienumberable.aggregate inside foreach loop? results.selectmany(x => x).aggregate((c, n) => c + ", " + n) string.join(environment.newline, results.select(a => string.join(", ", a))); complete sample: var results = new list<string[]> { new[]{"this", "should", "be", "on"}, new[]{"other", "line"} }; var result = string.join(environment.newline, results.select(a => string.join(", ", a))); result: this, should, be, on other, line update here aggregation done right - uses stringbuilder build single string in memory results.aggregat...

java - Unique column validator in Spring -

i want add validator return error if value not unique. how this? current validator: @component public class addformvalidator implements validator { public boolean supports(class<?> clazz) { return addform.class.isassignablefrom(clazz); } public void validate(object target, errors errors) { addform addform = (addform) target; validationutils.rejectifemptyorwhitespace(errors, "title", "title.empty", "title must not empty."); string title = addform.gettitle(); if ((title.length()) > 30) { errors.rejectvalue("title", "title.toolong", "title must not more 16 characters."); } validationutils.rejectifemptyorwhitespace(errors, "content", "content.empty", "content must not empty."); string content = addform.getcontent(); if ((content.length())...

Cannot get Cairo working on R install on CentOs 5.7 -

i trying cairo package r 3.0.1 work on centos 5.7 (yes know; it's i've been given work with!). cannot r find cairo. i've installed cairo , pango , pixman. can 'locate' them. when try re-install r, find in config long after running ./configure: r_cv has_cairo=no r_cv_has_pangocairo=no what, precisely, causing them not found configure? can shed light on this, can try fix problem. thanks! use latest r 3.0.2 , gcc-4.8.0 can install successful. http://cran.csiro.au/src/base/r-3/r-3.0.2.tar.gz

How to dynamically generate variables in JavaScript? -

this question has answer here: how add property javascript object using variable name? 7 answers use variable property name in javascript literal? 3 answers variable property name in javascript object literal? [duplicate] 3 answers my goal dynamically generate variables foo1 , foo2 , foo3 , assign bar them using following code: for (var i=1;i<=3;i++) { myapp.set({ foo+i: "bar" }) } i tried using eval on foo doesn't work. ideas? for (var i=1;i<=3;i++) { var myobj = {}; myobj['foo' + i] = 'bar'; myapp.set(myobj); }

displaying html from a "php foreach" on a fixed number of columns -

i have code: <?php if(count($this->items)): ?> <section class="itemlist"> <?php foreach ($this->items $item): ?> <...> <?php endforeach; ?> </section> <...> represents item title, description etc... each item: how can work on css/html make items displayed on fixed number of rows, 3, instead of on unique long column? can help if can use css3 can use propery -webkit-column-count:3; -moz-column-count:3; column-count:3; . otherwise have in different way (splitting in php code).

vb.net - Exception when starting SQL Server 2012 service from .NET code -

i'm attempting start sql server instance following code: dim computer new managedcomputer dim pmsql serverinstance = computer.serverinstances("theinstance") when upgraded sql server 2012 gives following error: sql server wmi provider not available on machinename. with inner exception of: invalid namespace do need install additional on system? make sense worked pre-2012 not 2012? edit: i'm using .dlls c:\program files\microsoft sql server\100\sdk. it turns out app using dlls previous version of sql server. updated 2012 version , seems work well.

javascript - Can't graphic with Chart.js and JQuery Mobile -

i'm having small problem here, i'm traying make charts can't make work , don't know why. i'm using chart.js charts graphics. here html5, has "canvas" chart going id=canvasejercicio2. <div data-theme="a" data-role="header"> <a data-role="button" data-inline="true" data-direction="reverse" data-theme="a" data-transition="slideup" href="#principal" data-icon="home" data-iconpos="left" class="ui-btn-left"> volver </a> <h3 id="nombreaplicacion"> nombre aplicacion </h3> </div> <div data-role="content"> <h4 id="tituloestadisticas"> estadisticas </h4> <canvas id="canvasejercicio2" width="400" height="400"></canvas> </div> here jquery code, here not working charts, c...

c++ - Error free(): invalid next size (fast): 0x08912058 -

as part of exercise, modifying class represents different way of creating arrays: template<class t> class array { public: array(int size, t defaultvalue) : _size(size) { _arr = new t[_size] ; _def = defaultvalue; } array(const array& other) : _size(other._size) { _arr = new t[other._size] ; // copy elements (int i=0 ; i<_size ; i++) { _arr[i] = other._arr[i] ; } } ~array() { delete[] _arr ; } array& operator=(const array& other) { if (&other==this) return *this ; if (_size != other._size) { resize(other._size) ; } (int i=0 ; i<_size ; i++) { _arr[i] = other._arr[i] ; } return *this ; } t& operator[](int index) { if (index>_size) { int prevsize = _size; resize(index); (int = prevsize+1; i<=ind...

Data table in C#.net -

i have problem related datatable in .net. trying fill datatable on page_load .that part ok no issue datatable correctly filled data. noticed when clicked button on page... again try fill datatable time-consuming task... want datatable should fill once ,when , when site open in browser .. not @ every click ... because have large amount of data in table takes time load in datatable.. plz me out ... here code: protectd void page_load(object sender, eventargs e) { cnn.connectionstring= configurationmanager.connectionstrings["con"].connectionstring; // if (this.ispostback == true) { dr1 = tableutop(); dtwordslist.load(dr1); } } oledbdatareader tableutopunj(string arrword) { if (cnn.state == connectionstate.open) { cnn.close(); } cnn.open(); oledbcommand cmd = new oledbcommand(); cmd.commandtext = "select u, p utop"; cmd.connection = cnn...

javascript - Meteor: How to trigger reRun of helper function after collectionHandle.ready() is true -

this new version of old question : so tom coleman's figured out on how check if subscription ready() or not. my current code structure looks this: /client/app.js: eventshandle = null; groupshandle = null; // ... // first deps.autorun(): // not depend on session var, should run every time deps.autorun(function() { eventshandle = meteor.subscribe("events", function() { console.log('deps.autorun(): events loaded'); }); }); // second deps.autorun(): // contains subscriptions dependent on session var "ehash" deps.autorun(function() { if(session.get('ehash')) groupshandle = meteor.subscribe("groups", session.get('ehash'), function() { console.log('deps.autorun(): groups loaded ehash: ' + session.get('ehash')); }); }); // ... then have view specific .js , .html files template stuff in folder called: /client/views/ --> <page>.js: template.x.dataloa...

javascript - What is the analytics.js equivalent of _trackPageview found in ga.js -

using previous version of google analytics (ga.js) can track virtual page view using _trackpageview method record when downloaded or other metric if desired. using new analytics.js syntax track virtual page view? just use standard _trackpageview method ga.js, in analytics.js can track virtual pageview using standard function. assume have arleady initialised analytics tracking code below: function(i,s,o,g,r,a,m){i['googleanalyticsobject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new date();a=s.createelement(o), m=s.getelementsbytagname(o)[0];a.async=1;a.src=g;m.parentnode.insertbefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'ua-xxxxxxxx-x', 'name seen in ga tracking code'); now inside function block in page, want track virtual page view , call send pageview suitable name , title want virtual page: ga('send', ...

ios - Delegate Method failing to call when tested with If statement, but calls correctly without If statement -

i have if statement checking if delegate has implemented given method: if ([[self delegate] respondstoselector:@selector(didfinishsettingnotificationondialog:)]) { [self.delegate didfinishsettingnotificationondialog:self withnotification:notification]; } however code not getting executed within if statement. have other delegate calls working between these objects and if remove if statement , call [self.delegate didfinishsettingnotificationondialog:self withnotification:notification]; on own works! my delegate implement correctly: - (void)didfinishsettingnotificationondialog:(notificationdialogview *)dialogview withnotification:(notificationcontext *)setnotification{ nslog(@"notification is: %@", setnotification); } so doing wrong? the name of method wrong. should didfinishsettingnotificationondialog:withnotification: . try this: if ([[self delegate] respondstoselector:@selector(didfinishsettingnotificationondialo...

.htaccess - Htaccess mod_rewrite: how to change page.php to /page? -

simple question: domain.com should lead index.php and domain.com/lala (or other word) should lead products.php?name=lala could give me rewrite rule? thanks assuming have .htaccess file in web root / directory rewriteengine on rewritebase / rewritecond %{request_filename} !-d # not dir rewritecond %{request_filename} !-f # not file rewriterule ^(.*)$ products.php?name=$1 [r=301,l] rewritecond %{request_uri} ^/$ rewriterule ^ index.php [r=301,l]

c++ - SDL_BlitSurface doesn't seem to work -

resolved brainsteel. code below fixed , works. window width: 640, window height: 480 the function calling order: start() loop() stop() (currently commented because if loop doesn't return 0 call stop before returning 1) the structure: #define max_images 50 struct imagestructure{ sdl_surface* texture; int x; int y; }; imagestructure image[max_images]; //all image textures set null default in start function sdl_event event; sdl_surface* screen = null; now start function. i've cleaned out setup code int program::start(){ for(int id = 0; id < max_images; id++){ image[id].texture = null; image[id].x = 0; image[id].y = 0; } if(loadimg(1, 0, 0) != 0){ return 1; } if(printtext(2, "hello world", 10, 310) != 0){ return 2; } return 0; } the loop function. cleaned out event code int program::loop(){ while(event.type != sdl_quit){ for(int id = 0; id < max_i...

Qt 4.8.5 will not compile statically -

i'm trying compile qt statically. i download source of qt 4.8.5, edited qmake file in /mkspecs/win32-g++ include -static @ qmake_lflags , ran "c:\qt\qt-everywhere-opensource-src-4.8.5>configure -platform win32-g++ -static - release -no-exceptions" which gave me: creating qmake... g++ -c -oproject.o -o -i. -igenerators -igenerators/unix -igenerators/win32 -ige nerators/mac -igenerators/symbian -igenerators/integrity -ic:\qt\qt-everywhere-o pensource-src-4.8.5/include -ic:\qt\qt-everywhere-opensource-src-4.8.5/include/q tcore -ic:\qt\qt-everywhere-opensource-src-4.8.5/include -ic:\qt\qt-everywhere-o pensource-src-4.8.5/include/qtcore -ic:\qt\qt-everywhere-opensource-src-4.8.5/sr c/corelib/global -ic:\qt\qt-everywhere-opensource-src-4.8.5/src/corelib/xml -ic: \qt\qt-everywhere-opensource-src-4.8.5/mkspecs/win32-g++ -ic:\qt\qt-everywhere-o pensource-src-4.8.5/tools/shared -dqt_no_textcodec -dqt_no_unicodetables -dqt_li te_component -dqt_no_pcre -dqt_nodll -dqt...

javascript - RequireJS doesn't work on a multipage project with CDN hosted libraries (jQuery) -

i'm using requirejs on multipage project, javascript folder structure looks kinda (how make fancy dir trees again in markdown?): common.js lib/ -- jquery-1.9.1.min.js -- modernizr-2.6.2.min.js -- underscore-amd.min.js page/ -- index.js -- start.js -- checkout.js anyway, common.js main script file set configuration parameters. looks like: common.js file // configure requirejs requirejs.config({ baseurl: "assets/js/lib", paths: { page: '../page', jquery: [ '//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min', //if cdn location fails, load location 'jquery-1.9.1.min' ], modernizr: [ '//cdnjs.cloudflare.com/ajax/libs/modernizr/2.6.2/modernizr.min', //if cdn location fails, load location 'modernizr-2.6.2.min' ], underscore: [ 'underscore-amd.min' ] } }); all pa...

dos - DOSKEY to change path and run a command -

so have 2 things need do, , seems doskey way go new it. trying c prompt change drives d, go folder called run_folder execute command redirect log file. this. c:\users> d: d:\> cd run_folder d:\run_folder> run_command.exe > d:\run_folder\logs_current_date_time.txt i trying convert have type run_ca c prompt.. ideas? how can accomplish using doskey put 3 lines of code file named run_ca.cmd . can type run_ca execute it. no need doskey.

objective c - FSEvents callback function event flag trouble -

i have fsevents stream, observe folder. when add files folder, callback function triggers that. but, thought can check specific event fseventstreameventflags constants, add file folder, or check file modified, can't. make history done: void filesystemeventcallback(constfseventstreamref streamref, void *clientcallbackinfo, size_t numevents, void *eventpaths, const fseventstreameventflags eventflags[], const fseventstreameventid eventids[]) { char **paths = eventpaths; int i; (i = 0; < numevents; i++) { if (eventflags[i]==kfseventstreameventflaghistorydone) { nslog(@"history done"); } } i check others fseventstreameventflags constants , there no constant trigger add file folder or modify file or delete. use construction now: void filesystemeventcallback(constfseventstreamref streamref, void *clientcallbackinfo, size_t numevents, void *eventpaths, const fseventstreameventflags eventflags[], const fseventstreameventid eventids[]) { char *...

mod rewrite - Using "?" when rewriting the URL -

i have been researching weeks looking how rewritting file/directory complementary "?" or "question mark" what need: http://mydomain.com/demo01.php to like: http://mydomain.com/?theme=jerus theme > simple directory need use websites products(in case themes) jerus > name of theme extra info: i plan on rewritting every url individually refrain wildcard varibles.** wouldn't easy instead of doing url rewriting put php in directory called theme , name index.php? http://mydomain.com/theme/?t=jerus but if you're re-writing urls make rule acutally make route this: http://mydomain.com/theme/jerus/ which waaaay prettier see question: using clean urls in restful api

vector - java 3D rotations not working -

i've had old graphics project laying around (written in oberon) , since wrote 1 of first projects looks kinda chaotic. descided that, since i'm bored anyway, rewrite in java. everything far seems work... until try rotate and/or eye-point transformation. if ignore said operations image comes out fine moment try of operations require me multiply point transformation matrix goes bad. the eye point transformation generates stupidly small numbers end coördinates [-0.002027571306540029, 0.05938634628270456, -123.30022583847628] causes resulting image empty if multiply each point 1000 turns out it's very, small and, in stead of being rotated, has been translated in (seemingly) random direction. if ignore eye point , focus on rotations results pretty strange (note: image auto scales depending on range of coordinates): setting xrotation 90° makes image narrow , way high (resolution should 1000x1000 , 138x1000 setting yrotation 90° makes wide (1000x138) setting zrot...

python 3.x - How do add onto a text file when after writing a code? -

so trying code read infile text line line. has split each line run through check if valid or not. reason reads last line , prints in outfile 00-7141858-x assuming reading each line down there there first. went through processes on last line? 019-923-3241 818-851-703x 5703781188 031-x287085- 00-7141858-x i want outfile this 019-923-3241 - valid 818-851-703x - invalid 5703781188 - valid 031-x287085- invalid 00-7141858-x - valid thanks! def pre_process (processed_s): st = '' ch in processed_s: if ch == '-': st = st + '' else: st = st + ch return st def digit_check (processed_s): digit_nums = '0123456789xx' nums = set(digit_nums) ch in processed_s: if not ch in nums: print ("invalid isbn") return processed_s def length_check(processed_s): if len(processed_s) < 10 or len(processed_s) > 10: print ("invalid isbn") def v...

node.js - Tuning node-mongodb-native connection pool size -

i've got express app talking mongodb via node-mongodb-native driver. requests in app intermittently slow. tools or strategies confirm or rule out driver connection pool size bottleneck? here's some discussion of tuning pool size, it's pretty inconclusive. aheckmann notes default of 5 plenty, while tinana saw significant gains bumping pool many concurrent request. update: question me understand tuning , tooling driver pool size rather troubleshoot immediate performance issue. described issue give question little context. in scenarios this, first step start db. if have queries slow respond, queries should appear in slow logs. take @ official docs profiling . default value "slow" queries 100ms, if slow queries because of db, see evidence there. additionally, take @ graphs db. "the graphs", mean nagios/cacti/zabbix/serverdensity/mms charts of server doing. if not have these, start there. tweaking connection pool size useless if do...

mysql - How do I correctly redirect after update in PHP -

the table seems update, not redirect me main page. have try different things no luck. if can me. thans in advance. put update code only, if there need put complete code of page will. $id_actividades = $_get['idactividades']; include('../includes/eamoschema.php'); $stmt = $dbh->prepare("select * actividades idactividades=:id_actividades"); $stmt -> bindparam(':id_actividades', $id_actividades); $stmt->execute(); $result = $stmt->fetchall(pdo::fetch_assoc); if($_server['request_method']== 'post'){ if (isset($_post['tname']) || isset($_post['place']) || isset($_post['organizer']) || isset($_post['from']) || isset($_post['to']) ) { $tname = $_post['tname']; $place = $_post['place']; $organizer = $_post['organizer']; $from = $_post['from']; $to = $_post['to']; try{ $stmt = $dbh->prepare("up...

How to make a camera move in the direction it is facing in java? -

i need way(in java) calculate direction camera move forward on x , z axes based on direction camera facing(yaw), , y(the vertical axis), pitch. i'm making own game engine , own camera. with values defaulting @ zero, moving camera correctly directs movement along positive z axis. however, when pan camera left or right(thereby changing yaw), camera still moves along z axis... how calculate change in direction x, y, , z axes? the value range on yaw 0(south), 45(southwest), 90(west), 135(northwest), 180(north), 225(northeast), 270(east), 315(southeast), , 360(south, same 0). what i'm looking compass directions(where '+' or '-' indicates change in value along axis): south = x, y, z+ southwest = x+, y, z+ west = x+, y, z northwest = x+, y, z- north = x, y, z- northeast = x-, y, z- east = x-, y, z southeast = x-, y, z+ the value range on pitch 0.0(middle), 100.0(up way), , -100.0(down way). if need post code, can, might complicated. hope i'm making ...

c# - UserControl Dependency Property design time -

i'm creating simple user control in wpf contains textblock inside button. <usercontrol x:class="wpfexpansion.mybutton"..... > <grid > <button background="transparent" > <textblock text="{binding path=text}"/> </button> </grid> </usercontrol> and "text" dependency property. public partial class mybutton : usercontrol { public mybutton() { initializecomponent(); this.datacontext = this; } public string text { { return (string)getvalue(textproperty); } set { setvalue(textproperty, value); } } public static readonly dependencyproperty textproperty = dependencyproperty.register("text", typeof(string), typeof(mybutton), new propertymetadata(string.empty)); } and use usercontrol this: <mybutton text="test" /> the problem visual studio design not change, ...

ruby - rails cannot load such file -- mysql2/mysql2 (LoadError) -

i newbie ruby on rails not find solution error: rails s /usr/local/share/gems/gems/mysql2-0.3.13/lib/mysql2.rb:8:in `require': cannot load such file -- mysql2/mysql2 (loaderror) /usr/local/share/gems/gems/mysql2-0.3.13/lib/mysql2.rb:8:in `<top (required)>' /usr/local/share/gems/gems/bundler-1.3.5/lib/bundler/runtime.rb:72:in `require' /usr/local/share/gems/gems/bundler-1.3.5/lib/bundler/runtime.rb:72:in `block (2 levels) in require' /usr/local/share/gems/gems/bundler-1.3.5/lib/bundler/runtime.rb:70:in `each' /usr/local/share/gems/gems/bundler-1.3.5/lib/bundler/runtime.rb:70:in `block in require' /usr/local/share/gems/gems/bundler-1.3.5/lib/bundler/runtime.rb:59:in `each' /usr/local/share/gems/gems/bundler-1.3.5/lib/bundler/runtime.rb:59:in `require' /usr/local/share/gems/gems/bundler-1.3.5/lib/bundler.rb:132:in `require' /home/harish/documents/simple_cms/config/application.rb:7:in `<top (required)>' /usr/local/share/gems/gem...

Python Read Large Text Files Probelm -

i trying compare 2 large text files line line (10gb each) without loading entire files memory. used following code indicated in other threads : with open(in_file1,"r") f1, open(in_file2,"r") f2: (line1, line2) in zip(f1, f2): compare(line1, line2) but seems python fails read file line line. observed memory usage while running code > 20g. tried using: import fileinput (line1, line2) in zip(fileinput.input([in_file1]),fileinput.input([in_file2])): compare(line1, line2) this 1 tries load memory. i'm using python 2.7.4 on centos 5.9, , didn't store of lines in code. what going wrong in code? how should change avoid loading ram? any suggestion appreciated! thank you! python's zip function returns list of tuples. if fetches complete files build list. use itertools.izip instead. return iterator of tuples. with open(in_file1,"r") f1, open(in_file2,"r") f2: (line1, line2) in izip(f1, f2):...

Handling an HTTP Connect with Netty 4 -

my library betamax stubbing out http endpoints unit tests. operates http(s) proxy , in https mode performing mitm attack. using jetty spins 2 proxy instances , responds http connect on http port tunneling https port. i'm trying replace jetty netty dependency. when trying replicate functionality netty 4.0.7.final i'm getting stuck handling connect & ssl handshake. missing instead of new get request going proxy when accept connect connect request getting re-routed. is there example of handling http connect netty 4? i've looked @ secure chat example netty socks protocol quite different http proxy protocol. i've seen littleproxy , that's been helpful point it's using older version of netty , api has changed quite bit.

c# - mysql table is not getting updated -

i copying data sql server mysql. load table sql server , table mysql , copy data over. data getting copied new table tables in database remains empty. in advance. here code - private void writetable(datatable table, string tablename) { long maxid=0; mysql.data.mysqlclient.mysqlcommand cmd = new mysql.data.mysqlclient.mysqlcommand("select * " + tablename, mysqlconn); mysql.data.mysqlclient.mysqldataadapter adapter = new mysql.data.mysqlclient.mysqldataadapter(cmd); datatable dest = new datatable(); adapter.fill(dest); txtmessages.text += table.rows.count.tostring()+"\r\n"; foreach (datarow row in table.rows) { datarow newrow = dest.newrow(); newrow.beginedit(); foreach (datacolumn col in table.columns) { newrow[col.caption] = row[col.caption]; } newrow.endedit(); dest.rows.add(newrow); ...

How to consume the wcf services in ios development -

i'm working on ipad application needs consume wcf service, known solutions creating bindings in objective-c? to consume wcf service in cocoa touch application use link http://iphonedevsdk.com/forum/iphone-sdk-development/39819-how-to-call-wcf-service.html also try changing configuration. found walkthrough @ at code project: how create json wcf restful service in 60 seconds on proper setup.

trouble of ruby plugin of eclipse -

i'm trying install rdt on eclipse indigo on macbook pro. installation seems ok, can create new ruby project. problem in ruby explorer: could not create view: org/eclipse/search/internal/ui/text/resourcetransferdragadapter i googled this, there many people reported same problem, nobody provided solution. could me please? in advance.

web services - Android App integration with other websites -

i student of android. aim develop android apps talk different websites , exchange/process/return data. not sure should starting point. coming backend development can put layout backend development follows a) understand relational db concepts b) sql c) plsql d) procedures/functions e) solve realworld problems ....etc similarly can tell me should starting point learning android integration. http or web services or rest api or json/xml or else all these terms new me , when googled/wikied terms can (kinda) grasp mean not able see big picture how fit etc...wrt integrating app website. tldr.what should starting point learning android integration ?. ps : if wrong forum, let me know forum post on. !!! your question general, , there no clear answer it, , not ready build real app unless can answer own, need know more each term of above, question "what best practice?" you can start below: ibm: using xml , json android xml vs json based web servic...

Write to csv: columns are shifted when item in row is empty (Python) -

basic read, al ok: with open('kres.csv', newline='') f: reader = csv.reader(f, quoting=csv.quote_all) row in reader: print(row) kres.append(row) here writing csv, columns shifted when field (item) in row empty, that's (i assume) because program doesn't know how many columns in file , writes 1 one. want not skip empty field, want write default character or none. don't know how check field empty. with open('kres2.csv', 'w', newline='') f: # use 'w' mode in 3.x writer = csv.writer(f) writer.writerows(kres) python 3.3.2 on windows 7 edit: trying chak every field in list, not working with open('article_all_krestianin_ru.csv', newline='') f: reader = csv.reader(f, quoting=csv.quote_all) row in reader: in row: if == '': = '-' print(row) krestianin.append(row) edit 2: ['А теперь - пр...

unit testing - Instance mocking and implicit constructors -

i trying use tdd on class manages database connections. i developing away network databases available i want test classes not mess real connections, sqlite :memory: i may want test connections in platform-independent manner (eg. exchanging pdo objects mysqli objects etc). databases not mysql, sqlserver. essentially want this: class connectionmanager { ... public function getconnection($name) { $params = $this->lookup($name); return new \pdo($params['spec'], $params['username'], $params['password']); } } and in test runner: class connectionmanagertest extends \phpunit_framework_testcase { public function testgetconnection() { $cxn = new connectionmanager(); $this->assertnotnull($cxn->getconnection('test')); // or whatever } } somehow use mock of pdo class. option add explicit parameter test class constructor or 1 of methods? i've tried using 'instance mocking' pe...

c++ - Create Two Way Local/Unix Socket -

is there way create 2 way local/unix socket using boost::asio . current operating system (ubuntu) supports unix sockets can't quite figure out how create one. official boost resources don't tell me appears resource available @ time. yes, use boost::asio::local::connect_pair() free function. can used stream or datagram local sockets.

delphi - EmbeddedWB & jQuery -

how can inject jquery , execute function inside embeddedwb control , it's result. you can use ihtmldocument2 interface of document loaded browser @ , manipulate dom. see http://www.delphidabbler.com/articles?article=21 , includes how return value script.

compiler construction - Definitive length of primitive C and Fortran types -

i revamping native bindings blas/lapack (fortran libraries) major os on 32/64 bit java library: netlib-java . however, i've started hit problems data type differences between unix/windows world, , between fortran / c. tables of fortran , c data types pretty non-commital because sizes are not explicitly defined c language . is there canonical source (or can create 1 referencing authoritative sources?) of bit sizes in practice of primitive data types on major oses both fortran , c? or, @ least, fortran types in terms of c types. i.e. populate table following columns (with few begin): os arch language type bits linux x86_64 c int 32 linux x86_64 c long 64 linux x86_64 c float 32 linux x86_64 c double 64 linux x86_64 fortran logical 32 linux x86_64 fortran integer 32 linux x86_64 fortran real 32 linux x86_64 fortran do...

How to stop Runaway Perl Process -

i'm on linux pc. inadvertantly created perl script endless recursion: subroutine calls subroutine b calls a, calls b, etc. i want stop these, don't want reboot. how can it? if try kill process ids, , there's 900 of them, time finishes, there's hundreds more. perhaps can use killall kill of running processes name: http://linux.die.net/man/1/killall

winapi - C# app getting Watson dialog when calling TerminateProcess -

i have wpf application written in c# i'm using terminateprocess() when events happen , app needs shutdown i'm not sure why, i'm seeing occasional watson dialog box appear when called? it's not 100% is excepted? passing non-0 result code? why watson popping, think silent exit? [dllimport("kernel32.dll", setlasterror = true)] [return: marshalas(unmanagedtype.bool)] private static extern bool terminateprocess(intptr hprocess, uint uexitcode); [dllimport("kernel32.dll")] private static extern intptr getcurrentprocess(); terminateprocess(getcurrentprocess(), 2); <-- whats triggering watson (sometimes) you know calling terminateprocess close application jerking power plug out of wall shut down computer, right? doesn't ask nicely, , doesn't right thing. forcibly rips process out of memory. it therefore makes deal of sense dr. watson debugger going pop up—no correctly functioning application going request terminated i...

jquery - What is this: $('<div />') -

in tutorial came across jquery: var encodedname = $('<div />').text(name).html(); i havent seen '<div />' before. doesnt css selector. ideas? this construction creates new jquery object contains 1 div element. can shorter though: $("<div>")

.htaccess - URL Rewrite GET parameters -

i want url following www.website.com/home&foo=bar&hello=world i want first parameter change however actual "behind scenes" url this www.website.com/index.php?page=home&foo=bar&hello=world all tutorials find change of parameters. any appreciated! add .htaccess in web root / directory rewriteengine on rewritebase / rewriterule ^home$ index.php?page=home&%{query_string} [nc,l] if want work pages i.e. /any-page gets served index.php?page=any-page use rewriteengine on rewritebase / rewritecond %{request_filename} !-d # not dir rewritecond %{request_filename} !-f # not file rewriterule ^(.*)$ index.php?page=$1&%{query_string} [nc,l] how these rules work? a rewriterule has following syntax rewriterule [pattern] [substitution] [flags] the pattern can use regular expression , matched against part of url after hostname , port (with .htaccess placed in root dir), before query string. first rule the pattern ^hom...

android - Bitmap - Matrix operations (scale, rotate and translate) -

i need matrix operations. i'm trying achieve is: scale down move specific position rotate degree (in center of bitmap) my code looks this: matrix matrix = new matrix(); matrix.prerotate(mship.getrotation(), mship.getx() + mship.getcurrentbitmap().getwidth()/2f, mship.gety() + mship.getcurrentbitmap().getheight()/2f); matrix.setscale((1.0f * mship.getwidth() / mship.getcurrentbitmap().getwidth()), (1.0f * mship.getheight() / mship.getcurrentbitmap().getheight())); matrix.posttranslate(mship.getx(), mship.gety()); mcanvas.drawbitmap(mship.getcurrentbitmap(), matrix, mbasicpaint); but rotation has wrong center, , can't figure out how solve - i've looked around on did find similar problems, no solutions this. think might have apply 1 of operations one's values executed in sequence cant figure out how to. try code: matrix matrix = new matrix(); matrix.settranslate(-mship.getcurrentbitmap...

java - Use ImageIO.read for class extending BufferedImage -

(what people have against hello?) i have class extends bufferedimage : public class namedimage extends bufferedimage{ string name; public namedimage(int width, int height, int imagetype) { super(width, height, imagetype); } public void setname(string text){ name = text; } } before had this, got images with: image image = imageio.read(res); now, want translate namedimage , following tries don't work: namedimage image = imageio.read(res); namedimage image = (namedimage) imageio.read(res); how can achieve want do? why can't cast buffered image class, extends custom class? (what people have against thank you?) here's possibility, if want imageio use specific subclass. however, if want give name, i'd use @andrewthompsons suggestion map<string, bufferedimage> , because it's less verbose. imageinputstream stream = imageio.createimageinputstream(res); iterator<imagereader> readers = imageio.getim...

mysql - Can't Update and Delete data - SQL -

Image
i've create table , add data rows. need delete rows, can't using mysql-wokbench. delete rows disabled. can't edit data, when choose "edita table data". can me? why so? i can not delete hand, using workbench. can't sql query. in order able edit result set query select * table table must have primary key defined, wb uses find record.

wifi - Strange behaviour on android postioning -

i have pretty interesting case application im working on. need take current location of phone , testing application 2 testing devices. on samsung fame takes current location , updates every time activate event, on samsung galaxy s4 there no updates. gives me same coordinates. im pretty sure wrong code, cant figure out what. both of phones wifi turnded on , mobile data turned off. this code on application: import android.app.alertdialog; import android.content.context; import android.content.dialoginterface; import android.content.intent; import android.location.location; import android.location.locationlistener; import android.location.locationmanager; import android.os.bundle; import android.provider.settings; import android.util.log; import android.webkit.webview.findlistener; import android.widget.textview; public final class gpstracker implements locationlistener { private final context mcontext; public boolean isgpsenabled = false; boolean isnetworkenabled = f...

ruby on rails 3 - simple_form radio button (need to add <span> tag inside of <label> -

what best way create following html using simple_form_for gem? <label> <input name="form-field-radio" type="radio" /> **<span class="lbl"> radio option 2</span>** </label> note default when create radio buttons using following statements, above not created. how can add tag in? <%= f.input :state, :collection => project::states, :as => :radio_buttons %> i had similar need (to embed <span> within <label> ). isn't cleanest solution did work , think tweaking ability have input , span embedded within label. following modification results in: <label>name: <span class="hint">this hint...</span> </label> i added following initializer (using rails 4 , simple_form 3) override label_text method: # initializers/simple_form_custom.rb module simpleform module components module labels def label_text if hint hin...

c# - The type or namespace name 'GetAdminMasterPage' could not be found -

Image
i've been testing example code here http://mywsat.codeplex.com/ , trying move project existing project i've built. i've copied of files , folders project following error repeated many times pages containing : getadminmasterpage the type or namespace name 'getadminmasterpage' not found (are missing using directive or assembly reference?) the example code behind in 1 of pages is using system; public partial class admin_admin_edit_css : getadminmasterpage { protected void page_load(object sender, eventargs e) { } } which assume means getadminmasterpage inherited? of folders , classes have been copied across , getadminmasterpage.cs located in app_code/class/getadminmasterpage.cs. code above same in mywsat doesn't give error. i've copied web.config file across hasn't fixed error. please can advise on how fix this? update: if copy of files, include in project works okay. select folders/files , select "include in pr...

c# - Zoom and Move for Canvas -

what's best way implementing zoom (possibly pinch) , move (possibly slide) canvas ? i'm drawing simple stuff (e.g lines, ellipses , more) on canvas , want allow user zoom-in, zoom-out , move view-port freely around. here go. in xaml code, wrap scroll viewer. this <scrollviewer x:name="scrl" zoommode="enabled" horizontalscrollmode="enabled" verticalscrollmode="enabled" horizontalscrollbarvisibility="visible" verticalscrollbarvisibility="visible" sizechanged="onsizechanged" minzoomfactor="1"> <canvas background="aliceblue" rendertransformorigin="0.5,0.5" x:name="main"> <image source="assets/floorplan.gif" canvas.left="358" canvas.top="84"></image> </canvas> </scrollviewer> then in c#code put this. private void onsizechanged(object sender, sizechange...

php - Detect if browser supports WebP format? (server side) -

there thread detecting webp support using client-side. how detect webp support using server side? today, should check accept header image/webp . browsers support webp send part of accept string requests (images , non-images). in short: if( strpos( $_server['http_accept'], 'image/webp' ) !== false ) { // webp supported! } (you might want use preg_match instead , add word boundary checks , case insensitivity, in real world should fine) here's original answer several years ago, when above not reliable the "proper" way check accept header sent, bug in chrome means won't list image/webp though support it. this relevant forum thread: https://groups.google.com/a/webmproject.org/forum/#!topic/webp-discuss/6nyupcsaors which links bugtracker: https://code.google.com/p/chromium/issues/detail?id=169182 in turn links one: https://code.google.com/p/chromium/issues/detail?id=267212 end result? while isn't implemented yet, go...