Posts

Showing posts from June, 2015

arrays - Vector Subscript out of range in C++ -

i facing problem while loading vector array vector rgb array. after rgbv = pointcloud_rgb[i]; getting error "vector subscript out of range". can guide me please. regards suhas const std::vector<cv::vec3b>& pointcloud_rgb; (unsigned int i=0; i<points.size(); i++) { cv::vec3b rgbv(255,255,255); if (pointcloud_rgb.size() >= i) { rgbv = pointcloud_rgb[i]; } } you have off-by-one error. if pointcloud_rgb.size() == i , i 1 element past end of vector. to fix this, change condition this: if (pointcloud_rgb.size() >= i) { to this: if (pointcloud_rgb.size() > i) {

python - Accessing Google Cloud Endpoints from php - 403 forbidden -

i'm trying access python based google cloud endpoints api php-server, without using php client library (simply making post-request, don't need authorization). worked fine few week, doesn't work anymore, in server logs following error: <!doctype html><html lang=en><meta charset=utf-8><meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width"><title>error 403 (forbidden)!!1</title><style>*{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen , (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}#logo{background:url(//www.google....

swift2 - Cannot invoke `join` with an argument list of type (String, [String]) in Swift 2.0 -

var specializationtitles = ["a", "b", "c", "d"] let outputstring = join(" / ", specializationtitles) got error: cannot invoke join argument list of type (string, [string]) how solve this? let separator = " / " let outputstring = separator.join(specializationtitles) with xcode7beta6: specializationtitles.joinwithstring(" / ") with xcode7 release version: specializationtitles.joinwithseparator(" / ")

ruby - Run method class within block -

how can use instance variables , method within block in ruby? class foo @var = "my var" def meth() "my method" end module.something |variable| p @var #=> undefined p meth() #=> undefined end end i not sure understand context, might help: class foo def initialize @var = "my var" end def meth() "my method" end def fee amodule.something |variable| p @var p meth() p variable end end end # test: module amodule def self.something yield "bar" end end foo = foo.new foo.fee

ios - Linking to J2ObjC from another CocoaPod -

we use j2objc , trying make switch xcode 6's dynamic frameworks in order incorporate swift project. adding use_frameworks! our podfile works great in case we're just using j2objc, problem comes when adding other libraries reference it. in particular example, have 2 pods in podfile, j2objc , other pod uses it. let's call whatever . current j2objc podspec can found here . here's podspec whatever : pod::spec.new |s| s.ios.deployment_target = '8.0' s.requires_arc = true s.source_files = '**/*.{h,m}' s.dependency 'j2objc' s.xcconfig = { 'header_search_paths' => '${pods_root}/j2objc/dist/include', 'library_search_paths' => '${pods_root}/j2objc/dist/lib' } end so far good. now, if want reference java class, javautilarraylist inside app, can that. @implementation viewcontroller - (void)viewdidload { [super viewdidload]; javautilarraylist *arraylist = [[javautilarraylist alloc]ini...

json - Jquery DataTables : Not able to make dynamic header -

have 2 json files json1 callback({ "docs":[ { "a":"qwe", "b":"asd", "c":"zxc", "d":"mnb", }] }) json2 callback({ "docs":[ { "1":"123", "2":"456", "3":"789", "4":"012", }] }) reading json file , displaying in table using jquery datatables plugin. i want "a","b","c","d" , "1", "2", "3", "4" used table headers or column names each json file called based on different check box click, there different column headers each json want columns/table headers dynamic. here datatable initialization var table = $('#example').datatable({ "data": items, ...

mysql - How to structure/normalize this database? -

Image
i need make database should hold 50 questions, 3 possible answers each question , value of each answer. this first guess feels wrong , i'm not sure how access values properly. suggestions on how structure this? this seems correct way: questions table --------------- id title ... answers table ------------- id question_id answer value one way be questions table --------------- id title ... values table ------------ id value answers table ------------- id question_id answer value_id then answers of specific question do select a.*, v.value answers join questions q on q.id = a.question_id join values v on v.id = a.value_id q.title = 'what name of dr. who'

Implement Parallel::MPI in perl script -

i have code parallelize on 8 nodes, 8 processors per node. i don't have clue how implement parallel::mpi::simple here's basic code: #!/usr/bin/perl # initialize parallelizing here foreach(keys %hash1){ #fork job foreach $fh (@files) { #get data open out, ">>".$ofh; print out $data,"\n"; close out; } # end fork } # end script i run assume #pbs -l nodes=8:ppn=8 mpirun -n 64 perl parallelizing.pl i'm confused on documentation. i not need nodes talk each other . execute same command in different files on multiple nodes. open, print, , close. thanks much!

reactjs - React Router DefaultRoute Not Rendering -

i'm attempting configure react-router work app (it doesn't ton yet). i've attempted use configuration, defaultroute not ever render, base route. var routes = ( <route path="/" handler={app}> <defaultroute handler={loginform} /> </route> ); router.run(routes, function(handler) { react.render(<handler />, document.body); }) there no error, loginform never gets rendered (although app does). loginform , app both exist (so should able rendered). misunderstanding way react-router/defaultroute supposed work? according documentation , second parameter router.run should location object (either hash or history ). var routehandler = router.routehandler; var router = require('react-router'); var route = router.route; // declare our routes , hierarchy var routes = ( <route path="/" handler={app}> <defaultroute handler={home}/> <route path="about" handler={a...

ansible - Mesos slave not seen from web ui -

i’m building ansible recipe deploy mesos/marathon cluster ( https://github.com/gridpocket/ansible-mesos-cluster ). once setup, mesos , marathon ui have 2 problems: - mesos ui cannot see slave registered - same ui indicates "no master leading..." the setup following one: - 3 mesos master (192.168.1.191, 192, 193): each running mesos-master, zookeeper, marathon - 3 mesos slaves (192.168.1.194, 195, 196): each running mesos-slave, docker slaves configuration in each slave: /etc/mesos/zk: zk://192.168.1.191:2181,192.168.1.192:2181,192.168.1.193:2181/mesos masters configuration on each master: /etc/mesos/zk: zk://192.168.1.191:2181,192.168.1.192:2181,192.168.1.193:2181/mesos /etc/mesos-master/quorum: 2 /etc/mesos-master/hostname , /etc/mesos-master/ip ip_of_the_master am missing in configuration ? edit i rebuilt whole cluster , corrected zookeeper configuration (datadir). now, - mesos master interface working , indicates master n...

javascript - How to pass evaluated values to a custom element directive? -

i have custom element directive following template: <div> <input value="{{datafromrootscope}}" /> </div> and definition: dirmodule.directive('mydirective', function() { return { restrict: 'e', templateurl: '/scripts/app/directives/mydirective.html' }; } ); i use directive shown below: <my-directive my-value="{{datafromscope}}"></my-directive> i.e. want use evaluated datafromscope value inside custom directive datafromrootscope . how can reach this? you can use '@' sign : dirmodule.directive('mydirective', function() { return { scope: { myvalue: '@' }, restrict: 'e', templateurl: '/scripts/app/directives/mydirective.html' }; }); the '@' sign binds evaluated value of dom attribute directive. you can use directive asked : ...

Does Xamarin Studio allow debugging a library (dll) project in an easier way than this? -

i'm developing c# dll, called child.dll , loaded 3rd-party c# executable program, called parent.exe . don't have access source code of parent.exe . on visual studio, when want debug dll project, have attach debugger parent.exe , that's it. can't find easy way on xamarin studio. what i'm doing are: set env var monodevelop_sdb_test=1 enable "custom command mono soft debugger" launch xamarin studio using same terminal first step. uncheck "debug project code only; not step framework code" in xamarin studio options -> debugger add dummy exe project in same solution of child.dll . because xamarin studio doesn't allow "run with" library project type. doing this, can access "run with" feature of xamarin studio. build whole solution, copy child.dll parent.exe want , run mono --debug --debugger-agent=transport=dt_socket,server=y,suspend=n,address=127.0.0.1:55555 parent.exe parent-args . ( parent.exe load child...

json - Java - Retrieve values of variable type from JSONObject -

i have json so: {"result":[{"job":{"type":"employee","title":"","occupation":"underwater basket weaver"}}]} i getting occupation value so: import org.json.jsonarray; import org.json.jsonobject; string occupation = null; jsonarray resultarray = obj.getjsonarray("result"); jsonobject firstresult = resultarray.getjsonobject(0); occupation = firstresult.getjsonobject("job").getstring("occupation"); however, reason, occupation value not string . guess is int or null . end exception this: org.json.jsonexception: jsonobject["occupation"] not string. @ org.json.jsonobject.getstring(jsonobject.java:658) what should when dealing jsonobjects take on variable data types? apply receive data types in string format occupation = firstresult.getjsonobject("job").get("occupation").tostring();

Running a regression on a subset of observations using R -

let's have 2 variables a:{1,2,3,4,5,6,7,8,9,10} , b:{11,12,13,14,15,16,17,18,19,20} , want run regression in r, using observations have a>6, i.e. run regression using {7,8,9,10} , {17, 18,19,20}. in stata easy it: reg b if a>6, in r cannot find easy way (i use lm command). please notice new in r , can use vanilla r, not allowed install package. in advance. it's best make sure variables stored in same object , best that object data frame. way can more extend multiple regression , if reason reorder data reorganization extend variables. when subset, extend variables. so answer question: df = data.frame(a = c(1:10), b = c(11:20)) lm(a ~ b, data = df[df$a>6,]) or using subset function: lm(a ~ b, data = subset(df, > 6))

Google calendar like view in sharepoint? -

i building share point site wherein trying multiple calenders in single view. have been able overlay/merge calenders unable make select/unselect of calender set of merged calenders seamless. explaining using feature google calender - basically, when using multiple calendars in google calender, calendars menu on left. clicking on each individual calendar hide calendar if displayed or show if hidden. in sharepoint clicking calendar in overlay view opens particular calendar. want achieve view calendars overlayed , can shown or hidden simple mouse input. has done before? pointers? thanks

ajax - How to get value from header authorization bearer? -

my server give response header authorization bearer. how can value in angular? with $http service can receive headers through success functions response object. can access property through $http(....).success(function(result, status, headers, config){ var myauthheader = headers("myauthorizationheader"); ... headers.... } })

java - TreeMap of GregorianCalendars -

i have created treemap of <gregoriancalendar, integer> store dates in gps leap seconds introduced: leapsecondsdict = new treemap<gregoriancalendar, integer>(); gregoriancalendar calendar = new gregoriancalendar(timezone.gettimezone("utc")); calendar.set(1981, gregoriancalendar.june, 30, 23, 59, 59); leapsecondsdict.put(calendar, 1); calendar.set(1982, gregoriancalendar.june, 30, 23, 59, 59); leapsecondsdict.put(calendar, 2); calendar.set(1983, gregoriancalendar.june, 30, 23, 59, 59); leapsecondsdict.put(calendar, 3); the problem each time call put, treemap contains last inserted element, , size stays 1. why happening? guess when using calendar key, key class instance id , not value, when inserting second element treemap updating existing entry same key, if key same class different value. is assumption right, or there other reason? there farcier way of achieving other creating new calendar each entry? the set method not create new ...

c# - Azure WorkerRole trigger on queue like WebJob -

i'm used use webjob on azure triggering azure queue. works charm. azure tutorial webjob + queue static void main(string[] args) { jobhost host = new jobhost(); host.runandblock(); } public static void processqueuemessage([queuetrigger("logqueue")] string logmessage, textwriter logger) { logger.writeline(logmessage); } what's queuetrigger until process triggered message isnot done, message keep invisible (not delete). if turn off webjob (for webjob update example) message visible (after little timeout) in queue process updated webjob (perfect). now wanna same thing on worker role. today this. while (true) { var cloudmessage = await sourceimportationqueue.getmessageasync(); if (cloudmessage != null) sourceimportationqueue.deletemessage(cloudmessage); // process job (few hours) else await task.delay(1000 * 5); } but if stop worker during job, lost message. how can webjob triggering ? finally...

excel - Move specific word to beginning of cell -

i have large spreadsheet contains entries like: alabama men's sport bracelet team color dial for each 1 need move word men's front of text in cell. many of cells contain word ladies rather men's require same operation. a (marginally) shorter version @rwilson's, similar: =iferror(if(search("men's",a1),"men's "&substitute(a1,"men's ","")),iferror(if(search("ladies",a1),"ladies "&substitute(a1,"ladies ","")),a1))

Browser keeps "connecting" after jQuery Ajax request times out -

i have list of ip addresses couple of servers need pinged see if running. ip addresses stored in data-ip-address attributes of list of span elements, javascript function reads them in order, pings each of them, , displays result. more simplified version of full function this: function pingservers() { if($('span[data-ping-this]').length > 0) { element = $('span[data-ping-this]:first'); $(element).removeattr('data-ping-this'); var url = $(element).attr('data-ip-address'); $.ajax({ url: url, datatype: 'jsonp', timeout: 4000, success: function(response) { displaysuccess(); }, error: function(something){ displaywarning(); } }); settimeout(function(){ pingservers(); }, 1000); } } the main thing there timeout defined, , timeout working, because after 4 seconds of no response, warning displayed. browsers, both firefox , chrome, still showin...

c# - Refresh control on orientation change? -

i have custom panel control, built in mainpage.xaml.cs, , want redraw when orientation changes (because needs measure width of display how need it). haven't found way how anywhere online :/ declare in class private simpleorientationsensor _orientationsensor; then use _orientationsensor = simpleorientationsensor.getdefault(); if (_orientationsensor != null) { _orientationsensor.orientationchanged += delegate { // whatever need here }; } _orientationsensor must member of class, otherwise collected gc , event wont fire

pcre - Use Regex to match a set of numbers with variable positioning? -

i'm trying use regex match set of numbers inputed users. want user supply positions , values of 4 digits. idea take info, search list , return 'matching numerical string' of 10 digits if , if digits supplied user in right position. can provide regular expression can use? i'm @ wits end , trying not fired. quick update example: user inputs ##2#5#8##9 should match 1528578009 8324598769 shouldnt match 4726754839 5023859800 hope helps give idea of im trying do. responses as far understand input : p1 v1 p2 v2 p3 v3 p4 v4 where p position , v value of digit. if case, arrange them in increasing order of position assume p1 < p2 < p3 < p4. now calculate following values : a1 = p1 - 1 a2 = p2 - p1 - 1 a3 = p3 - p2 - 1 a4 = p4 - p3 - 1 a5 = 10 - p4 now use following regex [1-9]{a1}v1[0-9]{a2}v2[0-9]{a3}v3[0-9]{a4}v4[0-9]{a5} the method based on fact position 1 based. significant digit's position considered 1 , not ...

algorithm - How to do search in B+tree -

can explain how search done in b+ tree? confusing thing me in comparison b-tree, b+tree doesn't hold data in internal nodes, in leaves. examples have b+-tree index build on list of names. want find name "mary". root key in b+tree 20. how should compare "mary" 20, if 20 holds no data?

python - Implementing __getitem__ in new-style classes -

i have code: class a: def __init__(self): def method(self, item): print self, ": getting item", item self.__getitem__ = types.methodtype(method, self, self.__class__) class b(object): def __init__(self): def method(self, item): print self, ": getting item", item self.__getitem__ = types.methodtype(method, self, self.__class__) then works fine: a = a() a[0] but not: b = b() b[0] raising typeerror. i found new-style classes magic methods in class __dict__ instead of instance __dict__ . right? why so? know article explaining ideas behind? tried rtfm, maybe not right ones or did not catch thing... thank much! paul this documented in python datamodel documentation: special method lookup new-style classes : for new-style classes, implicit invocations of special methods guaranteed work correctly if defined on object’s type, not in object’s instance dictionary. and the...

virtual machine - vagrant - Vagrantfile: sync multiple folders -

i have tried following sync multiple folders host guest machine. 1 folder getting synced, later one. config.vm.synced_folder "host/site1", "/var/www/site1" config.vm.synced_folder "host/site2", "/var/www/site2"

How to setup publish with subset of data in Meteor? -

i have large set of documents (1.7 million) in collection. setup meteor.publish in such way accepts argument/parameter returns minimal data set. e.g. argument search value front-end. possible pass arguments? this have far. //how pass front-end input in 'arg' here meteor.publish('postcodestopic', function(arg){ return postcodes.find({postcode: arg}); }); yes, can following: server: meteor.publish('postcodestopic', function(postcode) { return postcodes.find({ postcode: postcode }); }); client: var postcode = 03885; meteor.subscribe('postcodestopic', postcode); the format of subscribe meteor.subscribe(name, [arg1, arg2...], [callbacks]) , arg1, arg2, etc. arguments meteor.publish(name, function(arg1, arg2...))

assembly - How to map own register operands in llvm-tablegen to instruction's opcode? -

i'm trying implement "address register offset"-type operands. consist of base registers , offset registers: [k1 + k3]. in instruction's opcode need keep code register separately. found no way of 1) getting code of operand (is thing?) 2) mapping reg:$rm, reg:$rn of operand rm , rn fields of instruction directly. i'm getting rm placed in slot rn , rn merely ignored. so how thing done? when try add them via buildmi , print code seem written correctly, guess operands parsed properly. operands description def memrrasmoperand : asmoperandclass { let name = "memrr"; let parsermethod = "parsememoperand"; } class memrr<registeroperand reg> : operand<i32> { let mioperandinfo = (ops reg:$rm, reg:$rn); <--- --- --- let parsermatchclass = memrrasmoperand; } let printmethod = "printmemoperand" in { def memjj : memrr<registeroperand<jss>>; def memkk : memrr<registeroperand<kss>>; } i...

mp4 - Calculate PSNR and MSE for individual frames using ffmpeg -

i have avi file.i converting avi file .mp4 codec h.264 , ain second case .mp4 file codec h.265.now want calculate psnr/mse/msad between ref file(avi file) , converted mp4 file using ffmpeg.came across ffmpeg command line filters psnr , ssim calculation gives average psnr value not psnr value frame frame.also want using code , not using command line.read several examples in demuxing.c separating whole file frames in av_read_frame before calling decode how can convert pkt frame , able calculate psnr or mse values. regards mayank ffmpeg has psnr video filter give per-frame psnr per-frame metadata. want use this, since allows extending code add ssim (using ssim filter ) without effort on end. you should able find documentation hooking libavfilter decoded avframes without effort.

backup - How to ensure data consistency across data sources -

i have situation have authority data source has service sending data data source across network every time original data source updated. similar offsite backup guess. i'm looking way ensure secondary data source consistent original data source. i think there atleast 2 different things need check. data integrity: believe can check checksum style error check. data reaching it's destination: i'm not sure how can ensure data getting recorded in secondary data source. there possibility data never reaching destination because of network issue or similar. are there best practices can use ensure secondary data source has data consistency original data source?

Can I remove things on a map -

i've never used google maps api before, wondering if remove on map except country borders. want country names , city names left on map. no color, no contour lines, no elevation lines, nothing except these. also, able set reference points write program highlight area (and control brightness or color or size of highlighted area dynamically @ runtime based on external input example). for first part of question (removing things standard maps), you're looking styled maps feature in maps api. to explore different styling options do, use styled maps wizard . when style want, click show json button data can plug api. the user interface of styled maps wizard little confusing. sure read panel , keep experimenting it.

android - FragmentTransaction.replace() fade-in transition shows "ghost" fragment -

you can download entire project try , debug. here repo of entire code: https://bitbucket.org/lexic92/studio48/ i have "ghost fragment" appearing in transition when try replace blank fragment blank fragment. how recreate problem: have navigation drawer , when click on item, opens fragment fills whole screen. navigation drawer: button 1 - fragment text button 2 - fragment empty when open app, starts out fragment text. then, open navigation drawer , click button 2. transition bad , , turns blank screen split second, switches fading text, until becomes blank screen. if open navigation drawer , click on button 2 again , fades full text blank screen. so, for 1 split-second, shows fragment text when not supposed to. ran through app on debug mode, step step, slow down , verify behavior happened. if open navigation drawer , click on button 2 again third time, correctly not show animations because fading same screen. does know why happens? think has naviga...

php - JSON Safe Values from MySQL -

i'm using mysql's group_concat() generate json string. decode in php json_decode() . i'm escaping double quotes in values this: replace(coalesce(`column_name`, ''), '"', '\\\\"') my problem there's other character in record that's invalid , causing json_error_syntax (4) when trying decode. rather track down specific character that's causing problem, i'd apply more generic solution makes values "safe". this blog solves problem using mysql's hex() function encode value, , php function on decode end each value: function hextostr($hex) { $string = ''; ($chariter = 0; $chariter < strlen($hex) - 1; $chariter += 2) { $string .= chr(hexdec($hex[$chariter] . $hex[$chariter + 1])); } return $string; } i'm looking solution requires less work on decode end. ideally doing work in mysql. after 3 downvotes , close vote, i'm not sure how better structure qu...

linux - filter a content file to table -

this input have generated , displays versions of courses both jany , marco @ different times . on 10:00 course of jany 1 : course:theory:nothing course:applicaton:onehour on 10:00 course of jany 2 : course:theory:math course:applicaton:twohour on 10:00 course of marco 1 : course:theory:geo course:applicaton:halfhour on 10:00 course of marco 2 : course:theory:history course:applicaton:nothing on 14:00 course of jany 1 : course:theory:nothing course:applicaton:twohours on 14:00 course of jany 2 : course:theory:music course:applicaton:twohours on 14:00 course of marco 1 : course:theory:programmation course:applicaton:onehours on 14:00 course of marco 2 : course:theory:philosophy course:applicaton:nothing using awk commands succeeded sort : awk -f '[\ :]' '/the course of/{h=$2;m=$3} /theory/{print " "h":"m" theory:"$3}' f.txt awk -f '[\ :]' '/the course of/{h=$2;m=$3} /application/{print " "h":...

c - Questions about void pointers -

i have 2 questions void pointers; have: void * foo=malloc(99) void **bar=(void**)malloc(99); int i=1; bar++; *bar = foo; 1.is above equivalent following? bar[i++] = foo; if yes it's unexpected because bar++; moves double pointer forward , not single pointer, different non void types. 2.why fine return void** void * foo(); ? for example: void * foo(){ void ** bar; return bar; } 1.is above equivalent following? bar[i++] = foo; if yes it's unexpected because bar++; moves double pointer forward , not single pointer, different non void types. it's fine because bar pointer array of pointers. size of void* known (it's size of pointer), know next element of void** array is. 2.why fine return void** void * foo(); ? because void* pointer anything. pointer pointer pointer anything, void** can implicitly converted void* .

excel - Sorting column triggers click to run Macro...How do I fix this? -

i have code runs macro when cells clicked. problem sorting column causes macro run. how can prevent code running when column sorted? private sub worksheet_selectionchange(byval target range) if selection.count = 1 if not intersect(target, range("ai13:ai10000")) nothing msgbox "hello world!" end if end if end sub i'm pretty sure it's irrelevant, rest of code taking values 1 workbook , using filter pivot tables in workbook. thanks! sorting trigger worksheet_selectionchange because range selected in sorting process. using worksheet_beforedoubleclick instead run macro double click on desired cell , event not triggered sorting. the following code worked me: private sub worksheet_beforedoubleclick(byval target range, cancel boolean) if selection.count = 1 if not intersect(target, range("ai13:ai10000")) nothing msgbox "hello world!" end if end if ...

How to send data from ASP.Net C# to Arduino through Serial and print it on LCD? -

Image
i have asp.net page login/register operations. i'm trying show user name on lcd when user logs in. hardware i'm using lcd keypad shield not lcd if matters. , lovely arduino uno. c# side i tried storing username in char array , send arduino 1 one serial.write() gives error if don't give string it. wanted send whole name @ once then, serial.read() seems reading 1 @ time. using system; using system.collections.generic; using system.linq; using system.web; using system.web.ui; using system.web.ui.webcontrols; using system.web.security; using system.io.ports; using system.text; using system.componentmodel; using system.windows; namespace ecomm { public partial class login : system.web.ui.page { serialport sp; protected void page_load(object sender, eventargs e) { sp = new serialport(); sp.portname = "com13"; sp.baudrate = 9600; txtpass.textmode = textboxmode.password; } ...

node.js - Mongoose. Use a constant in $or -

i'm building query , include access control: var q = { $and: [ { $or: [ isadmin, // use have access resources? // pattern doesn't appear work { ispublic: true }, { createdby: userid } ] }, query ] }; resource.find(q).sort('-createdat').limit(10)... isadmin can true or false. if false, i'd other tests. query rest of query. it's not working in mongoose 4.0.4. suggestions? ok, found 2 ways this. best way not include $or when isadmin. kind of obvious really. function findnewestresources(query, callback) { if (!isadmin) { query = { $and: [ { $or: [ { ispublic: true }, { createdby: userid } ] }, query ] }; } resource.find(query).sort('-createdat').limit(10) an alternate way use $where , table-scan, that's no good. $where worked on 2.6.10, not on 2.6...

java - DI-container vs. Factories -

i know there many aricles , threads on dependency injection, not on depenedency-injection-containers. found this 1 fabien potencier quite helpful, although targets php. more read containers come conclusion such none more simple collection of factory-methods, true? a deeper , more concrete view: when injecting dependency object foo.bar = new dependency(); i write foo.bar = new myfactory.createdependency(); or container foo.bar = mycontainer.createdependency(); here container within last approach not have 1 many other methods create other types also, container factory-methods, right? the whole point of di containers never need/should write code foo.bar = mycontainer.createdependency(); it considered antipattern. di container should used once in composition root(it main di container usage pattern). di container automatically construct objects , inject dependencies via constructors or properties based on configuration. in case of factory have yourself. bes...

magento - Phoenix Varnish Cache: ESI Tag Not Remove -

i install varnish cache 4.3 on linux ngnix server , pagecache powered varnish module in magento. /etc/varnish/default.vcl backend default { .host = "127.0.0.1"; .port = "80"; } this /etc/varnish/default.vcl_3.0 include "vars.vcl"; backend default { .host = "127.0.0.1"; .port = "6081"; } backend admin { .host = "127.0.0.1"; .port = "6081"; .first_byte_timeout = 18000s; .between_bytes_timeout = 18000s; } acl purge { "localhost"; "127.0.0.1"; } # purge request if (req.request == "purge") { if (!client.ip ~ purge) { error 405 "not allowed."; } ban("obj.http.x-purge-host ~ " + req.http.x-purge-host + " && obj.http.x-purge-url ~ " + req.http.x-purge-regex + " && obj.http.content-type ~ " + req.http.x-purge-content-type); error 200 "purged."; } this daemon_opts is daemon_opts=...

json - AFNetworking get responseObject in failure block -

i get json data server, json data has line break "\n", got error: error domain=nscocoaerrordomain code=3840 "the operation couldn’t completed. (cocoa error 3840.)" (unescaped control character around character 2333.) userinfo=0x7fa054a02ab0 {nsdebugdescription=unescaped control character around character 2333.} so want find where's broken json data, escape first , parse it. can't find response data is. any help? edited : if let d = error.userinfo { println(d) println(d[afnetworkingoperationfailingurlresponsedataerrorkey]) } i tried in failure block, d[afnetworkingoperationfailingurlresponsedataerrorkey] prints nil you can response data nserror of failure block: nsdata *errordata = [error.userinfo objectforkey:afnetworkingoperationfailingurlresponsedataerrorkey]; from that, may transform nsstring or else need escape , process appropriately.

javascript - How do I make my D3 collapsible chart, collapsible? -

i've created hierarchical chart using d3 , want make collapsible. i'm prety new d3 i'm getting used understanding code. need width between nodes increase don't know how this. text overlaps eachother why need expand width between each node. can too? d3 code: var margin = {top: 40, right: 120, bottom: 20, left: 120}, width = 960 - margin.right - margin.left, height = 500 - margin.top - margin.bottom; var = 0; var tree = d3.layout.tree() .size([height, width]); var diagonal = d3.svg.diagonal() .projection(function(d) { return [d.x, d.y]; }); var svg = d3.select("body").append("svg") .attr("width", width + margin.right + margin.left) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); root = treedata[0]; update(root); function update(source) { // compute new ...

android - System.currentTimeMillis() returns wrong date -

i trying save current time shared preferences reason current time of ridiculous amount, in far future year of 47486 . i have checked date settings on device , date there correct , cannot find problem anywhere. hoping here may able me. here problem is: public static void setlastsyncsucceeded(final context context) { sharedpreferences sp = preferencemanager.getdefaultsharedpreferences(context); long currenttime = system.currenttimemillis(); sp.edit().putlong(pref_last_sync_succeeded, currenttime).commit(); } so while debugging noticed currenttime 1436374427923 tue, 23 nov 47486 00:38:43 gmt ... the value have there milliseconds (as in currenttimemillis ) , you're treating if seconds. divide thousand (i.e., turn seconds) , more sensible value of wed, 08 jul 2015 16:53:47 gmt .

javascript - Is it possible to define different locations in your NPM package for browser and for server (NodeJS)? -

is possible define different locations in npm package browser , server (nodejs)? my code largely isomorphic, uglified , concatenated browsers. short answer, can't such thing. dependencies stored under /node_modules folder. you may override option running patches or installer script. here bug raised on github issue.it's described in official npm blogpost but don't feel disappointed, may use bower dependency injector client side code. prefer feels more semantically , separated: bower front end, npm end. moreover, npm packages built commonjs only, bower packages instead more plug , play solutions

Odd segmentation fault with CC/GCC but not G++ (C/SDL2/Linux) -

the code posted copied directly example of popular sdl2 tutorial, ensure wasn't had made silly mistake. i've done example changing path of image file in question, changed type bool int, false 0 , true 1. understand it, nothing c++ specific should remain. everything seems work regardless do, when compiling cc/gcc (i suppose that's same deal) segmentation fault in end, suspect in close(), i've been unable determine. compiling g++ somehow prevents segmentation fault. the solution of course simple, use g++, know wherein problem lies. main.c: //using sdl , standard io #include <sdl2/sdl.h> #include <stdio.h> //screen dimension constants const int screen_width = 640; const int screen_height = 480; //starts sdl , creates window int init(); //loads media int loadmedia(); //frees media , shuts down sdl void close(); //the window we'll rendering sdl_window* gwindow = null; //the surface contained window sdl_surface* gscreensurface = null; //the ...

c# - How to Serialize a Collection of Interface Objects Using Protobuf-Net -

i have following class definitions: [protoinclude(2, typeof(foo))] public interface ifoo { double bar { get; } } [protocontract] public class foo : ifoo { [protomember(1)] private double _bar { { return bar / 10; } set { bar = 10 * value; } } public double bar { get; private set; } } [protocontract] public class myclass { [protomember(1, overwritelist = true)] public ireadonlylist<ifoo> foos { get; private set; } } when try serialize myclass object using protobuf-net, exception: system.invalidoperationexception : not possible prepare serializer for: mynamespace.myclass ----> system.invalidoperationexception : no serializer defined type: mynamespace.ifoo in case, know concrete type of items stored in myclass.foos foo . how can tell protobuf use type foo anywhere sees type ifoo ? alternatively, how can make include foo 1 of classes available implement ifoo in collection? -- edit -- the answer sam close...

android - How to delete all Table records in Sqlite? -

i json value server , save data database in sqlite in android, create database , table sqliteopenhelper class: public class activitytabledbopenhelper extends sqliteopenhelper { private static final string logtag = "atdbopenhelper"; private static final string database_name = "mydatabase.db"; private static final int database_version = 1; public static final string activity_table = "'activity'"; public static final string column_activity_id = "'activityid'"; public static final string column_user_id = "'userid'"; public static final string column_program_id = "'programid'"; public static final string column_order = "'order'"; public static final string column_g_date = "'gdate'"; public static final string column_j_date = "'jdate'"; private static final string table_create = "create table " + activity_table + " ...

CakePHP 3 Find All Contain NULL data, displays nothing? -

update this join sql after selects, from users users left join userinfos userinfos on userinfos.id = (users.userinfo_id) inner join offices offices on offices.id = (userinfos.office_id) ok, have database (mysql) setup cakephp 3 users table has extended information held within table. this other table extended office / address information set null default, want include in 'contain' call dose not return user data when empty? so use currently, $userstable->find('all') ->contain(['userinfos','userinfos.offices']) ->toarray(); but, offices (office_id field in table usersinfos) not set, still want return users if don't have office set. so have tried, $userstable->find('all') ->contain([ 'userinfos', 'userinfos.offices' ]) ->where(['userinfos.office_id is' => null]) ...

java - @Resource UserTransaction is Null -

i have restful webservice implementation. maintaining transaction using usertransaction object injecting @resource. , see usertransaction object seems null. reason behind this? import javax.transaction.usertransaction; @path("user") public class userimpl { @resource private usertransaction tx; @context httpservletrequest httpservletrequest; public void doaction() { try { tx.begin(); // work... } { tx.commit(); } } } the reason behind usertransaction can injected managed component supports transactions. usual component supports transactions in java ee ejb bean. annotate userimpl class @stateless that. usertransaction indicates want manually manage transaction, have tell container @transactionmanagement . this: @stateless @transactionmanagement(transactionmanagementtype.bean) @path("user") public class userimpl

javascript - Measuring text width/height without rendering -

is there way estimate text width without rendering actual elements? canvas textmetrics? case: need estimate element heights reactlist. i'd need know how space text elements need (or how many lines span). eg. render(){ return <div><somecomponentwithknowndims/><p>{this.props.sometext}</p></div>; } if knew how wide sometext rendered 1 line , how long line be, come decent estimate components height. edit: note quite performance critical , dom should not touched please check this. solution using canvas function get_tex_width(txt, font) { this.element = document.createelement('canvas'); this.context = this.element.getcontext("2d"); this.context.font = font; return this.context.measuretext(txt).width; } alert('calculated width ' + get_tex_width("hello world", "30px arial")); alert("span text width "+$("span").width()); d...

javascript - HTML5 creating an animated 2d image -

newbie html5 developer here, i digging in on web create animated image using several jpg files should have in folder in website. idea create animation of rabbit running 1 side of page when user clicks on button. so, i've found far libraries transform images, , allow me move them, need images changing while -let's have div in rabbit images placed- rabbit moving. imgs/ rabbit-image1.jpg rabbit-image2.jpg rabbit-image3.jpg rabbit-image4.jpg rabbit-image5.jpg rabbit-image6.jpg once start move 1 point of page another, these images loop until reaches ending position, giving feeling of running rabbit. any suggestions? thank in advance. animating images pretty simple. need provide images , order (array) aswell kind of timer function animation(images, timeperimage) { this.images = images; // array of rabbit images this.currenttime = 0; // timer this.currentimage = 0; ...

sql - Insert multiple rows from select into another table -

let's have `table1(col1,col2,col3), values insert on col1 , col3 same, values insert on col2 come result of select query. how can write query can multiple insert @ once ? example of query should : col1 | col2 | col3 1 val1 0 1 val2 0 1 val3 0 if understand correctly, use insert . . .select : insert table1(col1, col2, col3) select 1, col2, 0 <your other query here>;

ruby - comparing keys in one array with another -

ruby newbie here. have been banging head against wall better part of 2 hours due assignment have. create method has 2 arguments - hash , array of keys derived hash's keys. method should return true if array has of keys in hash, , false if not. have make sure every key in hash argument contained in array_of_keys argument. method should return true if of elements in array_of_keys array within set of keys in hash argument, without regard specific order. writers of assignment suggested using .sort method this. this have far, having issue figuring out how sort both arrays in order compare. def do_i_have?(hash, array_of_keys) array_of_keys = [] hash.each |key, value| array_of_keys << key end hash.keys == array_of_keys end i have tried, no luck. def do_i_have?(hash, array_of_keys) array_of_keys = [] hash.each |key, value| array_of_keys << key end hash.keys.sort == array_of_keys.sort end what correct syntax in order sort , compare these 2 ...