Posts

Showing posts from February, 2010

encoding - Converting ISO-8859-1 to UTF-8 for MultipartFormData in Play2 + Scala when parsing email from Sendgrid -

i have hooked play2+scala application sendgrid parse api , i'm struggling in decoding , encoding content of email. since emails in different encodings sendgrid provides json object charsets: {"to":"utf-8","cc":"utf-8","subject":"utf-8","from":"utf-8","text":"iso-8859-1","html":"iso-8859-1"} in test case "text" "med vänliga hälsningar jakobs webshop" if extract multipart request , print out: logger.info(request.body.dataparts.get("text").get) i get: med v?nliga h?lsningar jakobs webshop ok given info sendgrid let's fix string utf-8 . def parsemail = action(parse.multipartformdata) { request => { val inputbuffer = request.body.dataparts.get("text").map { v => bytebuffer.wrap(v.head.getbytes()) } val fromcharset = charset.forname("iso-8859-1") val tochar

c# - Need help taking the results of a SQL select statment and outting them into a gridview -

try { sqlcommand cmd = new sqlcommand(select [name], count([name]) count [delegationtracker] [date] = @date group [name], connection);conn); sqlcommand cmd = new sqlcommand(select @user_tested whmis_user_tests;, connct); cmd.parameters.clear(); cmd.parameters.add(@name, sqldbtype.varchar).value = httpcontext.current.session[name].tostring(); cmd.parameters.add(@date, sqldbtype.varchar).value = date;mmddyyyy cmd.parameters.add(@grade, sqldbtype.varchar).value = null; connection.open(); using (sqldatareader reader = cmd.executereader()) { while (reader.read()) { test = reader.getvalue(0).tostring(); test2 = reader.getvalue(1).tostring(); } } sqldatareader dr = cmd.executereader(); sqldataadapter adapter = new sqldataadapter(cmd); d

IntelliJ IDEA, Test Runner Pane, maximize output pane -

Image
is there way maximize output pane of test? can't believe have endure review process of stacktrace in narrow pane! there shortcut (ctrl-shift-up) make pane grow little. know of shortcut or button maximize pane ? in eclipse output console (ctrl-m) anyway, idea great! it's not possible maximize it, please vote corresponding feature request: idea-64469 provide way view test console output maximized (like double-clicking it?)

Data in EXCEL, PDF, WORD (Data will be text, tables, images) to XML -

is there free tool convert data in excel sheets, pdf files , word files (data text,tables,images) xml? i had searched getting opposite thing (converting xml others) please try provide tools/links/code if available. thanks in advance. i have "save as" xml option when save in file tab. not sure if part of xml extensions pack have though. regardless can extensions pack microsoft if not have one. have developer tab came 1 one of expansion packs. word (and pdf) not have can import text data excel , go there. import data data tab -> text command. i have excel 2010.

XCode 4.6 - Can't click the Entitlements checkbox for iOS project -

i have ios project have been working on time. need add entitlements. when select target , check "entitlements" checkbox, automatically un-checks it's self 1 second later. i have .entitlements file in project. have removed , recreated it. have tried checking "entitlements" checkbox , without .entitlements file there. i'm not sure other details need provide illustrate issue, if have left out may important, please let me know. i ended figuring out resolution. had remove , delete entitlements file project, go both project's build settings tab , target build settings tab , remove references .entitlements file. after closed xcode , re-opened it. @ point able click "use entitlements" checkbox. i sorry not returning question earlier.

node.js - Closure and callback memory leak in javascript -

function(foo, cb) { var bigobject = new bigobject(); dofoo(foo, function(e) { if (e.type === bigobject.type) { cb(); // bigobject = null; } }); } the above example shows classic, accidental (or maybe not) memory-leaking closure. v8 garbage collector can't determine if it's safe remove bigobject because it's being used in callback function can called several times. one solution set bigobject null when job in callback function over. if using many variables (imagine there n variables bigobject , , used in callback) cleaning becomes ugly problem. my question this: there other way clean used variables? edit here's (real world) example: application mongodb , compare other application. callback mongodb uses variable application defined out of callback. after result mongodb return callback (because async , cant write return ). can happen propagate callback way source... function compareapplications(application, condition, c

c# - WCF using, closing and extensions -

i stumped. perhaps can shed light on wcf client behavior observing. using wcf samples, i've started playing different approaches wcf client/server communication. while executing 1m of test requests in parallel, using sysinternals tcpview monitor open ports. now, there @ least 4 different ways call client: create client, thing, , let gc collect it create client in using block, thing create client channel factory in using block, thing create client or channel, use wcf extensions thing now, knowledge, options 2-4, explicitly call client.close(). during execution see lot of ports left in time_wait state. i'd expect option 1 worst case scenario, due reliance on gc. however, surprise, seems cleanest of them all, meaning, leaves no lingering ports behind. what missing? update: source code private static void runclientworse(concurrentbag<double> cb) { var client = new calculatorclient(); client.endpoint.address = new endpointaddress(&

objective c - iOS NSManagedObjectContext - is it possible to get or send a notification when all changes is saved? -

i use core data - , have registered , listening nsmanagedobjectcontextdidsavenotification :s have collection of data (from json), want save, , after objects saved, kind of notification. seems notification sent after every object saved. there kind of built in solution getting desired notification? if not, how could/should it? there's no built-in notification gets posted after you've saved specific batch of objects. core data has no idea how many objects in collection, has no way know you've reached end of it. you'll nsmanagedobjectcontextdidsavenotification every time call save: on managed object context. wait save until you've handled of objects, mean 1 nsmanagedobjectcontextdidsavenotification . a better solution post own notification when know you've finished collection. define string constant called jsonupdatescompletenotification, , post notification name after last save: call. nsstring *jsonupdatescompletenotification = @"jsonupda

javascript - Do I need to add app.initialize() in all my html files in a cordova/phonegap project -

i making phonegap/cordova project. created skeleton project using command line, guide suggests making new android/phonegap project. in index.html file created there piece of code app.initialize() , , code comes file called index.js. my question is, have have piece of code in html files, since using jquerymobile front-end, might need have several html files. var app = { // application constructor initialize: function() { this.bindevents(); }, // bind event listeners // // bind events required on startup. common events are: // 'load', 'deviceready', 'offline', , 'online'. bindevents: function() { document.addeventlistener('deviceready', this.ondeviceready, false); }, // deviceready event handler // // scope of 'this' event. in order call 'receivedevent' // function, must explicity call 'app.receivedevent(...);' ondeviceready: function() {

java - jsoup unexpectedly fetching shopwiki image -

Image
i using following code fetch images web: import java.io.fileoutputstream; import java.io.ioexception; import org.jsoup.jsoup; public class fetchimagetest { public static void main(string[] args) throws exception { saveimage(args[0], args[1]); } private static boolean saveimage(string string, string destination) throws ioexception { string = string.replaceall(" ", "%20"); try { byte[] image = jsoup.connect(string).ignorecontenttype(true).timeout(10000).execute().bodyasbytes(); fileoutputstream os = new fileoutputstream(destination); os.write(image); os.close(); return true; } catch (ioexception e) { system.out.println("couldn't open " + string); return false; } catch (exception e) { system.out.println("couldn't open - general exception" + string

Comparing 2 Arrays in shell script -

i have read contents of folder , store them in array. , need pass array script. how can store , pass array , read array?? #!/usr/bin/ksh cd /path/applications-war arraywar=( $(ls /path/applications-war)) i need contents under folder array (@arraywar). login box , call script. need pass array script. /usr/bin/ssh -t -t username@machinename /path/myscript.sh @arraywar inside myscript.sh , want compare passed array @arraywar servicesarray. #!/bin/ksh @arraywar = $1 servicesarray=('abc.war' 'xyz.war') warfile in @arraywar if echo "${servicesarray[@]}" | fgrep "$warfile"; echo "$warfile matches" else echo "$warfile not matched" fi done here's script, takes variable number of files arguments: #!/bin/ksh servicesarray=('abc.war' 'xyz.war') warfile in "${@##*/}" if echo "${servicesarray[@]}" | fgrep "

php - Regex not returning matches from database, but works fine when manually put in to input string -

i know asked question yesterday regex ( regex not returning matches independent of expression used ). code got yesterday works fine long put url:s input string manually, when load database 0 matches. functioning code $url = "http://www.ltblekinge.se/download/18.9c16a31109c04a3e880003750 http://one.com www.two.com http://yourad.io"; preg_match_all('/((([a-za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[a-za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[a-za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[.\!\/\\w]*))?)/', $url, $matches); print_r($matches[1]); gives following output: array ( [0] => http://www.ltblekinge.se/download/18.9c16a31109c04a3e880003750 [1] => http://one.com [2] => www.two.com [3] => http://yourad.io ) non functional code <?php /*** mysql hostname ***/ $hostname = 'localhost'; /*** mysql username ***/ $username = 'root'; /*** mysql password ***/ $password = 'root'; try { $dbh =

python - Library to do a bluetooth dialer -

i need develop windows (and preferably linux) program dial number in bluetooth connected phone. i've doing research, , have found these 2 programs: bluetooth pc dialer : windows program input phone numbers dial them click hfp linux : linux software (library+program) use pc hands free device first approach think @ commands, haven't succeed that. ¿does know (or have experience) library use remote dial on bluetooth? update 9/5/2013: found some more info , not able work it. finally take approach of using operative system tools stablish serial connection device, , use chrome app+extension ( based on answer ) send @ commands javascript app, avoiding code multi-platform app.

javascript - AngularJS resource not forming url correctly -

i'm having problem using angularjs resources. i have resource looks this: loginmodule.service('testresource', function ($resource, $location) { var $scope = this; $scope.resource = $resource(window.location.path+'/:event', {event:'@event'}); $scope.inputdata = function(data1, data2, success){ return $scope.resource.save({'event':'inputdata'},{'data1':data1,'data2':data2},success); }; return $scope; }); and yes, i've tried using: // $scope.resource = $resource($location.path()+'/:event'); // $scope.resource = $resource(window.location.path+'/:event'); // $scope.resource = $resource(':event'); firebug reports address tries send 1 of these two: http://localhost/sandbox/test/undefined/inputdata http://localhost/sandbox/test/:event?event=inputdata what want address of: http://localhost/sandbox/test/inputdata what doing wrong? more specifically, shou

Access content in Windows Store package -

the article 'how load file resources' on msdn , others, discuss ms-appx , ms-appdata uri schemes addressing content in application package. http://msdn.microsoft.com/en-us/library/windows/apps/hh781229.aspx the problem is, can't see way load other image files. xmlreader, example, doesn't support these uri schemes , windows.storage.pathio static read methods throw comexception: "error hresult e_fail has been returned call com component." possibly exception caused bad uri/usage error. know silverlight used throw message sorts of reasons. has been able read non-image data package? luke i'm able answer own question. var f = windows.applicationmodel.package.current.installedlocation.getfolderasync("data").astask().result; var = f.getfileasync("sample data.xml").astask().result; var s = windows.storage.fileio.readtextasync(i).astask().result; var r = system.xml.xmlreader.create(new stringreader(s)); r.movetocon

tibco ems - Not able to retrieve messages from topic using EMS.NET API -

Image
i trying write simple application send messages topic use input , show messages published on topic. there 2 command line executables - 1 publisher , subscriber. when publish messages on topic, can see messages getting submitted topic. the following command shows there messages on topic (see f1.gif):- show stat ems.test.topic the following command shows messages getting consumed subscribers (see f2.gif) show stat consumers topic=ems.test.topic however, not able retrieve messages ems .net api. gets stuck on message msg = subscriber.receive(); . made sure connection details , authentication details correct because used when publishing messages. public string receivemessagesfromtopic(string topicname) { topicconnection connection = null; string messagefrompublisher = string.empty; try { var factory = new tibco.ems.topicconnectionfactory(serverurl); connection = factory.createtopiccon

c++ - Unable to detect USB device -

Image
please have @ following code #include "myclass.h" #include <qstring.h> #include <qdebug.h> myclass::myclass() { qlist<qextportinfo> ports = qextserialenumerator::getports(); int counter=0; while(counter<ports.size()) { qstring portname = ports[counter].portname; qstring productid= ports[counter].productid; qstring physicalname = ports[counter].physname; qstring vendorid = ports[counter].vendorid; qstring friendname = ports[counter].friendname; string convertedportname = portname.tolocal8bit().constdata(); string convertedproductid = productid.tolocal8bit().constdata(); string convertedphysicalname = physicalname.tolocal8bit().constdata(); string convertedvendorid = vendorid.tolocal8bit().constdata(); string convertedfriendname = friendname.tolocal8bit().constdata(); cout << "port name: " << convertedportname <

source maps - How do I debug client errors in JavaScript? -

i have window.onerror handler sends javascript errors our server. hoping analyse these using source maps link errors in minified source original code, seems chrome , firefox provide line numbers on error. far can see, source maps not useful without column number. so, given line number of minified source , error message of form x undefined , steps can take debug? (if makes difference, i'm using asset pipeline in rails 3.2). chrome (and ie10) give column number fourth argument in window.onerror callback. here's firefox bug adding column numbers , doesn't promising.

javascript - Centering Leaflet map with getbounds and related issues -

i ran leaflet issue can't solve it. may there's easy solution don't know. so centering map of grouped markers isn't difficult , can done following: var markerlayer = l.featuregroup(marker) .addto(map); var bounds = markerlayer.getbounds(); map.fitbounds(bounds); where marker array of markers. problem marker array information send code generated system. marker can far apart in map or can close. when markers far apart code above works , centers map. if markers close (for example if same street), or better yet if there 1 marker problems arise. because getbounds give me rectangle small leaflet breaks (and of no use user well). mean map tries zoom in marker. question how limit zoom. example if there marker in map want map show marker , few streets around it. you can give maxzoom map , fitbounds not override it.

python - Numpy - Regrid with Averaging redux -

i'm trying implement similar answered in this post regridding in python. question in post involved regridding array such output cell contain average of input cells contributed it. catch each input cell (i think) contributes 1 output cell - is, there's no real way account case input cell overlaps 2 output cells. i'm wondering if there's way generalize method account cell overlap - if, example, have 2 input bins span 0 1 , 1 2 , output cell spans 0.75 2, want take sort of weighted average calculate value in output cell recognizes input cell spanned 1 2 should contribute 4x more output cell 1 spanned 0 1. this isn't interpolation, per se, pretty every method i've seen attempting similar uses it. problem straight interpolating with, eg, np.interp routine ignores of points if more 1 input cell contributes output cell. i'm not quite you're looking for, working on similar right now. have 2 uniform finite difference grids, , need map inform

java 2d - Jdeveloper rendering messed up on Linux when JSF Designer -

Image
i have installed jdeveloper 11g on ubuntu 12.04 64 bit. after trying edit jsf page in design mode jdeveloper becomes messed on page below. i tried different versions of java 32 , 64 bit , result same. when trying use visual jsf editor, jdeveloper pracricaly unusable. after testing came conclusion problem related graphic card driver ati hd 7600m graphic card in laptop. tried replacing driver result remained same. finally came fix: after added line in the jdev.conf: addvmoption -dsun.java2d.opengl=true jdeveloper started working fine. i hope of someone.

python - Numpy loadtxt file path name -

i wondering if had information on how load csv file using numpy's loadtxt. reason claims there no such file or directory, when there is. i've copy/pasted full path (with , without leading / root), no avail. from numpy import * fh = loadtxt("/users/groenera/desktop/file.csv") or from numpy import * fh = loadtxt("users/groenera/desktop/file.csv") thanks help. documentation loadtxt unhelpful ( http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html ). this not loadtxt problem. try simply f = open("/users/groenera/desktop/file.csv") to make sure loadtxt 's fault. also, try using unicode string: f = open(u"/users/groenera/desktop/file.csv")

Spring ReloadableResourceBundleMessageSource works with Java 6, fails with Java 7 -

our declaration: <bean id="messagesource" class="org.springframework.context.support.reloadableresourcebundlemessagesource"> <property name="basenames"> <list> <value>web-inf/classes/caasmessages</value> </list> </property> <property name="usecodeasdefaultmessage" value="true" /> <property name="defaultencoding" value="utf-8"/> </bean> we've tried classpath:caasmessages, we've tried caasmessages. actual files in web-inf/classes , include caasmessages.properties, caasmessages_es.properties , on. the error: javax.servlet.jsp.jsptagexception: no message found under code 'screen.confirmloginstats.title' locale 'en_us'. @ org.springframework.web.servlet.tags.messagetag.dostarttaginternal(messagetag.java:184) @ org.springframework.web.servlet.tags.requestcontextawar

javascript - Incorrect Email validation hints -

i'm not big fan of email validation regexes myself have come across lot of sites have strict regexes , result have not been able user preferred email. basically use .+@.+ make sure not forgetting @. what i'd though give user hints if he/she has entered email incorrect. typos or weird characters. so if enter instance mike3292@hotmaik.com can ask user if sure, , maybe hint right solution in cases. so want know if there existing source of top email providers , common spelling mistakes. maybe regex unusual characters warn user about, asking him double check. regex bad validating emails. if want full/real validation you'll need very complicated expression what recommend make sure it's .*@.*\..* check ---@---.--- , have user enter twice. it makes easy you, easy user, , not annoying. wouldn't if pop-up suggested name invalid email address.

python filename on windows -

disclaimer have similar thread started think got big , convoluted in short problem import imghdr import os.path .... image_type = imghdr.what(os.path.normpath(filename)) fails ioerror: [errno 22] invalid mode ('rb') or filename: 'd:\\mysvn\\trunk\\assets\\models\\character\\char1.jpg\r' where aforementioned file exist help? :d there carriage return character \r @ end of filename. not valid character windows filename, doubt filename work. use .rstrip('\r') remove it: image_type = imghdr.what(os.path.normpath(filename.rstrip('\r'))) .rstrip() removes characters end of string, , in set name. since filename, any whitespace around filename incorrect, straight-up .strip() work too: image_type = imghdr.what(os.path.normpath(filename.strip())) this remove tabs, newlines, carriage returns , spaces both start and end of string.

C++ Identifier Not Found error -

i identifer not found error "startprocess": int main(int argc, char* argv[]) { bool result=startprocess(argc, argv); return 0; } bool startprocess(int argc, char* argv[]) { } but why? functions need @ least declared before use them, if not defined. try putting @ top of file. bool startprocess(int argc, char* argv[]); the above declaration , you're telling compiler @ point, you're going provide definition function, this: bool startprocess(int argc, char* argv[]) { code here... } this difference between declaration , definition important being able separate code separate files. if had placed definition of startprocess in different file, compiler never see while compiling file contains main . however, declaration , you're making promise exists somewhere.

c# - Using thread two part of a program differently -

i'm coding pacman (c# console) know how move ghost each seconds, able move pacman whenever want. i ghost keep mooving each second whatever pacman do, should able move pacman when ever want, , ghosts have move every second. i guess have use thread system, know if know how have proceed , how thread works, can't find information :s. you're confused because console.readkey() blocking ...so game loop stuck waiting user press key right? grab keystroke readkey() if there 1 in queue. can checked console.keyavailable returns true if key there. way game loop keeps looping around if no key has been pressed...but can still trap , it. try quick example out , see happens: class program { static void main(string[] args) { while (true) { system.threading.thread.sleep(250); console.write("."); if (console.keyavailable) { consolekeyinfo key = console.readkey(true); // r

for loop - How to vectorize matrix whose index is matrix in MATLAB? -

i have 2 for-loops embedded in code repeated many times. want speed things up: for = 1:10 j = 1:10 a(i,j) = b(i,j,d(i,j))*c(i,j); end end here d consist of integers indices b. without dependence on d for-loops replaced elementwise matrix multiplication. problem how evaluate b in elegant way. searched , mathworks-pages , tried linear indexing, produces errors: d = reshape(d, 100, []); b = reshape(b, 100, []); arrayfun(@(x) b(x,d(x)), 1:100); what doing wrong? there way replace 2 for-loops? you can transform d linear index: [rows,cols]=ndgrid(1:10,1:10); idx = sub2ind(size(b),rows(:),cols(:),d(:)); = zeros(10,10); %# initialize right size a(:) = b(idx).*c(:);

c# - Preferred method for binding in MVVM, Data Template in Resources file or just DataContext in View itself? -

this 1 has got me stumped thought looked @ must missing something. have went off traditional mvvm pattern msdn magazine: http://msdn.microsoft.com/en-us/magazine/dd419663.aspx while learning mvvm. copy of code , replace need today wanted build scratch , saw there may more thought. mvvm appeared not work bindings when used resource dictionary datacontext directly. question wants find other developers suggested use of binding find. summary of question this: why 'datatemplate' in resource dictionary appear not work shown below direct 'datacontext' method view right away bindings? is because doing mixture of code behind settings views in code behind. or potentially because of else. appears property , it's implementation set correct in viewmodel if set 'datacontext' directly in view's xaml, why not in resource dictionary? thought advantage of method set bunch of relationships @ once. curious if there other setting need done work. curio

database design - How to make drop-down menu within Oracle Application Express? -

Image
i appreciate if shed light on this, search engine results have been singularly unhelpful far. i attempting build gui oracle database through application express. there tend tricks of how set drop down menus through graphical user interface of product 1 uses (for instance know how in product microsoft access). for instance have form the foreign key business (fk_business_id) integer - not terribly user friendly! if drop down list of business names (business.name), great. hiding business primary key (business_id) make nicer, isn't altogether relevant. i have found source controls element in question. what sort of sql (or pl/sql) used both display data other table, , return selected foreign key selected user when form sent? solution open item, , change type select list for list of values definition , enter select business.name, fk_business_id [table] explanation select list shows display values user , returns corresponding id. source can remain same

Changing my Jquery project to plain javascript -

i created breakout game school project using jquery , helpful online tutorial. the working fiddle here: http://jsfiddle.net/kinetic915/kurvf/ edit revised fiddle: http://jsfiddle.net/kinetic915/nvctr/ i have changed javascript having problems changing jquery code renders ball javascript. i have marked , left spaces in areas there problems. thank given!! //*********************************************************************************** // start code //*********************************************************************************** // variables , other initializing functions here function start() { //****************************************************************************** //jquery // here main problem!!!!!! // here main problem!!!!!! cir = $('#canvas')[0].getcontext("2d"); //jquery //changing cir = canvas.getcontext("2d"); causes code fail. return setinterval(drawcircle, 10); } function windowsize

javascript - Lytebox showing "about:blank" instead of required link -

i'm having frustrating issue. have same exact code 3 links call using lytebox. the links follows : resources.php?cat=client achievments [this works fine] resources.php?cat=book recommendations [this works fine] resources.php?cat=savings ideas [this not work , loads blank page, specifically, about:blank] when open page in browser without going through lytebox, opens fine. reason when call last link through the javascript, doesn't complete process of loading same page. thanks help! -aethon the problem occurs when in url appear word ' avi ', ' mpeg ', ' mpeg ', ' mov ', or ' wmv '. in case savings contains 'avi'.

html - How do I remove element using .click and .remove in jQuery -

here jsfiddle and here code. html <h2>todo list</h2> <div id='additem'> <input type='text' name='additem'/> <button>add item</button> </div> <div id='todolist'> <ol> </ol> <!-- add item "additem" input field --> </div> js $(document).ready(function(){ $('button').click(function(){ var item = $('input[name=additem]').val(); $('ol').append('<li>'+ item +' <button id="remove">remove</button></li>'); }); $("#remove").click(function(){ $(this).parent('li').remove(); }); }); you need use on() dynamically added elements using event delegation. can delegate event parent element available when bind event using on or can use document otherwise. $(document).on("click", "#remove", functi

matlab - Vectorizing in Multiple Dimensions -

i have following loop in matlab code i'd rid of: for i=1:size(thepolygon,3) activevalues(:,i) = sum(normalvectors.*thepolygon(:,:,i),2); checkvalues(:,i) = sign(activevalues(:,i)-sum(normalvectors.*thepolygon3(:,:,i),2)); end i tried replacing i 1:size(thepolygon,3) , dimensions don't line element-by-element multiplication, , i'm not sure else try. in advance tips. it's difficult test without example data but: activevalues = squeeze(sum(bsxfun(@times, normalvectors, thepolygon), 2)) ok first test data: a = rand(3,3,3); b = rand(3,3); now test yours for i=1:size(a,3) c(:,i) = sum(b.*a(:,:,i),2); end on run got: c = 0.9773 1.0608 0.3673 0.6670 0.1597 0.7296 0.8372 1.1418 0.9828 and mine: squeeze(sum(bsxfun(@times, b, a), 2)) i get ans = 0.9773 1.0608 0.3673 0.6670 0.1597 0.7296 0.8372 1.1418 0.9828 so assuming mine correct. explanation: bsxf

php - Dependency Injection Container and defining all(?) dependencies -

i puzzled define dependencies. it seems huge overkill load every possible dependency while may not used @ all. defining them @ place of need result in code duplication. where defined? perhaps configuration of dependency initiated once? example logger or db connection. thanks in advance. in work had problem , used approach based on symfony2. have simple dependency container, holds lambda functions used create dependencies might need and, upon first usage, factory called. something like: dc['afactory'] = function() { return new a(); }; dc has "cache" of dependency objects, every time use dc->get('a'), first check whether caché filled, in case, existent instance, otherwhise, factory function called, stored in cache , results. way don't have load every possible dependency until it's used.

sql server - Cookies not working with SqlServer session state mode -

i have .net mvc4 application following in web.config under system.web section: <sessionstate mode="sqlserver" sqlconnectionstring="data source=db;userid=user;password=pass;" cookieless="false" timeout="20"/> when run site not see cookie on page nor saved in database. if change cookieless="true" session id saved in database. how can sqlserver session state work cookies? the session saved database when cookie explicitly added. example: httpcontext.session["hello"] = "hello"; i assumed cookie generated page loaded , when didn't see thought had problem. incorrect , correctly see cookie when add session state.

python - Randomized stratified k-fold cross-validation in scikit-learn? -

is there built-in way scikit-learn perform shuffled stratified k-fold cross-validation? 1 of common cv methods, , surprised couldn't find built-in method this. i saw cross_validation.kfold() has shuffling flag, not stratified. unfortunately cross_validation.stratifiedkfold() not have such option, , cross_validation.stratifiedshufflesplit() not produce disjoint folds. am missing something? planned? (obviously can implement myself) the shuffling flag cross_validation.stratifiedkfold has been introduced in current version 0.15: http://scikit-learn.org/0.15/modules/generated/sklearn.cross_validation.stratifiedkfold.html this can found in changelog: http://scikit-learn.org/stable/whats_new.html#new-features shuffle option cross_validation.stratifiedkfold. jeffrey blackburne.

foreach - Copy Files from folders to folder tree in php -

i have large number of books need categorize language , libraryid. the file-names structured , spread out in many folders: eng_filename_libraryname1.pdf eng_filename_libraryname2.pdf spa_filename_libraryname1.pdf spa_filename_libraryname2.pdf i need move them folders this eng ->libraryname1 --eng_filename_libraryname1.pdf ->libraryname2 --eng_filename_libraryname2.pdf here's code: foreach (glob("c:/wamp/www/projects/filemove/eth/*") $folderpath) { $foldername = preg_replace('/.*?\/(.*?)/', '$1', $folderpath); foreach (glob("c:/wamp/www/projects/filemove/eth/*/*") $librarypath) { $libraryname = preg_replace('/.*?\/(.*?)/', '$1', $librarypath); foreach (glob("c:/wamp/www/projects/filemove/pdf/*.pdf") $filepath) { $ethologue = preg_replace('/(.*?)_.*/', '$1', $filepath); $library = preg_replace('/.*?_.*?_.*?_(.*?)_.*/', '$1', $filep

java - OpenCV CascadeClassifier error -

i'm trying face detection through webcam, got error, cascadeclassifier error. after testing, found line of code generate error cascadeclassifier face_cascade = new cascadeclassifier(); the error got exception in thread "main" java.lang.unsatisfiedlinkerror: org.opencv.objdetect.cascadeclassifier.cascadeclassifier_0()j @ org.opencv.objdetect.cascadeclassifier.cascadeclassifier_0(native method) @ org.opencv.objdetect.cascadeclassifier.<init>(cascadeclassifier.java:38) @ camcapture.main(camcapture.java:24) is know how solve this? finally found answer, i should load library before use cascadeclassifier. put code system.loadlibrary(core.native_library_name); before cascadeclassifier.

javascript - Is there a trick to using d3 charts in jsf? -

i using prime faces in liferay, trick getting d3 examples show in jsf land prime faces on liferay. example trying make work in jsf one: how d3.js difference chart example work json data? i figured out. trick reference div element instead of body. of examples have seen use "body".in portal container don't want use body put outside of port let. div required , must referenced in javascript. have included new code below <%@ page import="javax.portlet.windowstate" %> <%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %> <%@ taglib uri="http://alloy.liferay.com/tld/aui" prefix="aui" %> <portlet:defineobjects /> <form action="<portlet:actionurl />" method="post" name="<portlet:namespace />fm"> <div id="svgcontainer" ></div> <script type="text/javascript" >

.net - Windows Phone - Set dark theme for application -

is possible set whole theme of application dark 1 phone settings? you can set theme default application.use jeffwillcox's phonethememanager hopes helped you.

oauth - YouTube api v3 debug oauth2 access token -

i oauth2 access token using following scopes user. scope: ["https://www.googleapis.com/auth/youtube"] then proceed use token calls youtube v3 api. these calls work @ first start getting response/error. { errors: [ { domain: 'global', reason: 'autherror', message: 'invalid credentials', locationtype: 'header', location: 'authorization' }], code: 401, message: 'invalid credentials' } is else experiencing intermitten errors? there way debug oauth token facebook tool ? token seems expire in 1 hour. get refresh token google api example url https://www.googleapis.com/youtube/v3/channels/?part=id,snippet,contentdetails,statistics,topicdetails&mine=true&access_token= {access_token} token expired. had use approval_prompt=force,access_type=offline when requesting access_token, gets new refresh token. used refresh token new token everytime needed access api on user's beh

c# - Context Menu commands to dynamically create UI controls using MVVM -

hopefully question isn't general, have started using wpf , i'm banging head against this. i developing application uses dynamically created controls. can not figure out how make commands create , add more controls current window because commands work when created in viewmodel can not see view. can't keep in xaml because controls except few empty stack panels dynamic. feel i'm missing easy here though. so here have binding <menuitem header="labelmenuitem" command="{binding path=spawnlabel}"/> and here have command public icommand spawnlabel { { return new delegatecommand(onspawnlabel); } } delegate command works relay command defined here. public class delegatecommand : icommand { private readonly action _command; private readonly func<bool> _canexecute; public event eventhandler canexecutechanged { add { commandmanager.requerysuggested += value; } remove { com

iphone - Geofencing Alert Analytics - Impossible? -

i work on side of things in company , i'm working on project ios developer. project app notify user of in-store offers alert when enter 250m radius geofenced area. there 160 of these geofenced areas. my company love have data concerning how many alerts being sent within each geofenced area per day/week/month (whatever can get!) assess areas users active in. i have been told developer in fact impossible. appreciate guidance if possible , can find more information, i.e. there mobile analytics services provide this? i have been trying best past 4 days find more information this, limited success. appreciate guidance. this possible, else impossible - tracking simultaneously 160 geolocations. drain battery life, , indeed maximum number of geolocation 1 app can track simultaneously around 20. (this ios limitation , there no workaround or "hack" around it) this indeed, possible. i'll try explain on high level of abstraction. in order notify user, app n

Overriding media queries without using an iFrame -

i have special requirement: i'd wrap responsive website in div can change width , height. end result i'd have drop down i'd change width , height of div, allowing "site" contained in div render width , heigh of div. i cannot use iframes browser plugins allow me not work (these not browser machines) basically, i'd "mock out" browser's api media queries.

Form with tinyMCE textarea having html5 required attribute cannot submit -

this not question, answer want share you. i've spent on 4 hours tearing hair out on turns out bug in either tinymce or firefox. with tinymce loaded, if specify html5 required attribute on textarea form not submit in firefox. no errors, nothing in firebug, stubborn refusal submit. i don't know if ff or tinymce bug , don't care. don't want other coders go through aggravation i've gone through these last hours. to ask question: bug documented anywhere? know? if inappropriate post stack overflow, tell me , i'll delete it. the problem far being firefox issue. indeed chrome , opera ("old" opera before "brain" transplanted chrome's) , every other modern browser give same headache. with both opera , chrome, there's flag insisting field required one, (despite fact have content in it). chrome nice enough give error message in console: an invalid form control name='<name of textarea>' not focusable. no

user interface - android: what's this slider bar called and how to implement it? -

Image
this may dumb question please tell me slider (highlighted in yellow) called in android? navigation bar? i want implement same slider in app, please let me know if there's sample can refer to? thanks. as part highlighted, doesn't have particular name, it's view selector background. as mechanism (pulling view reveal another), slidingdrawer . note has been deprecated in api 17, ui pattern not encouraged anymore.

pdf generation - How to set horizontal or vertical alignment Text in PDF? -

Image
i generating pdf, , outputting text, e.g.: bt /f1 7 tf 586 406 td (date shipped:) tj et a quick primer on pdf programming language : bt : begin text block /f1 7 tf : select font # 1 (which in case helvetica), , use font size of 7 point 586 406 td move current location (x= 586 pt, y= 406 pt) (date shipped:) tj : render text date shipped: et : end text block that text rendered @ location (586,406), bottom left of text block @ location: what want point define top center point: because not know size of rendered text; cannot fudge things up/down/left/right try make it. how can indicate in pdf text's "alignment" ? you cannot. pdf producing software needs know font metrics produce formatted output. as know selected helvetica @ size 7 , know current character , word spacing values, can calculate size of rendered text. the font metrics of standard 14 fonts available  here . you may want read pdf specification (made availab

javascript - Trigger event on animation complete (no control over animation) -

i've scenario requires me detect animation stop of periodically animated element , trigger function. i've no control on element's animation . animation can dynamic can't use clever settimeout . long story the simplified form of problem i'm using third party jquery sliding banners plugin uses obfuscated javascript slide banners in , out. i'm in need of figuring out hook on slidecomplete sort of event, have element id . take this jsfiddle example , imagine javascript has been obfuscated. need trigger function when red box reaches extremes , stops. i'm aware of :animated pseudo selector think need me poll required element. i've gone through this , this , , this , no avail. i've checked jquery promise couldn't figure out use in scenario. this question closest requirements has no answers. p.s. more information might helpful: the element isn't created javascript, present on page load. i've control on when apply plugi