Posts

Showing posts from May, 2015

mysql - Oversimplified design for empty parent class? (c++) -

i have dal class handle access mysql database. functions has same name such string insert( datatype data), string update(int pk, datatype data) , on. but datatype varies in type, seems meaningless have parent class insert , update , inherit because datatype different different table use. recommend have them group using inheritance data access layer. advise? alternatives? using template? or should use interface instead of inheritance?

hadoop - percentile_approx in hive returning zero -

i have been trying check percentile_approx set of users. intention behind top 25% of customers in data set. so, in order check that, ran following hive query. select percentile_approx(amount, 0.75) sales however, value returned query 0.0 . not sure problem is. when run query on sample of few records result expected. can please shed light on this? note - trying find percentile in data set containing more 3.3 m records. generally percentile_approx() works on integer type data. please make sure have applied on column has integers.

c++11 - Using iterator for removing items from map in c++ -

map<int, int> m_map; // ... map::iterator = m_map.begin(); while (it != m_map.end()) { m_map.erase(it++); } when ++ action take place? before or after erase ? when safe so? i don't think it's specified whether ++ happens before or after call erase . still, if guaranteed peformed before call, fact had asks shows code bad. there better, 100% safe alternative: while (it != m_map.end()) { = m_map.erase(it); } erase returns iterator element past erased one.

visual studio - Overwriting local changes in Git -

i using git in visual studio , getting error when trying pull: an error occurred. detailed message: 1 uncommitted change overwritten merge however when try , commit won't let me because have pull first, it's vicious cycle. there doesn't seem on how fix error within visual studio. how can latest version on server , overwrite local changes? how can latest version on server , overwrite local changes? in team explorer window, in list of pending changes (that’s create commits), can right click on files , click “undo…” undo whatever local changes did files. should able pull. however, shouldn’t need pull commit. git commits local repository, state of other remote repository never considered commits. there "out going commits", when "sync" gives me error. the “sync” button in “unsyched commits” view push , pull. indeed requires not have uncommitted changes (that overwritten) in working directory. go “changes” view , make com

css - How to hide Bootstrap column on some pages -

i need hide "right" column in "md position" on pages (login, registration,contacts...) , extend "main" col-md-12. my index.php <div class="container"> <div class="row"> <div id="main" class="col-md-9 col-xs-12"> <jdoc:include type="component" /> </div> <div id="right" class="col-md-3 col-xs-12"> <?php if($this->countmodules('right')) : ?> <jdoc:include type="modules" name="right" style="none" /> <?php endif; ?> </div> </div> </div> i think easiest way checking option & view in template , act based on value , example : $app = jfactory::getapplication(); if(in_array($app->input->get('view'), array('login', 'registration') && in_array($app->input->get(

Adding things to a git bare repository -

i know if have files in bare repository, can access them using git show head:path/to/file . but can add new content bare repository without cloning , modifying working tree? if add 1 file, 1 file in commit, aka added new , it's set in stone there's several convenient ways add single-file commit tip of master branch in bare repo. so appears need create blob object, attach tree, attach tree object commit. all ways commit boil down doing that, it's question of how convenience commands suit purpose. git add creates blob , makes entry in index; git commit git write-tree adds new trees what's in index, , git commit-tree adds commit of top-level resulting tree, , git update-ref keep head date. bare repos have head commit, attached (aka symbolic ref for) branch master , . . . so git's convenience commands doing want. 1 file, going easy. say example files appear in ~server/data/logs/ , bare repo you're using distribution @ ~serve

python - Django project on two domains - limiting access to urls/views -

i working on django project. utilizes multiple small apps - 1 of them used common things (common models, forms, etc). i want separate whole project 2 domains, i.g.: corporatedomain.com , userportal.com i want corporatedomain.com use different urls, same userportal.com. is possible? if so, how can this? how should configure urls? you have separate settings file anyway define different root_urlconf each domain. update : if don't want use different settings have write middleware change request.urlconf attribute using http_host header. here example of such middleware .

expression - Are any languages strictly "statement-oriented"? -

are there modern languages require each line statement? apparently fortran did this, languages since c? i've heard of expression-oriented languages, including functional programming languages, can't find term opposite, "statement-oriented" language, or 1 not allow expression, e.g. x + 3; or call value-returning function without assignment? this typical of low-level compiler intermediate languages, such three-adress codes .

haskell - Ambiguous type variable with Haskeline auto-completion -

i'm trying implement autocompletion function haskeline : import system.console.haskeline import system.console.haskeline.io import data.list mysettings :: settings io mysettings = defaultsettings { historyfile = "myhist" , complete = completeword nothing " \t" $ return . search } keywords :: [string] keywords = ["point","line","circle","sphere"] search :: string -> [completion] search str = map simplecompletion $ filter (str `isprefixof`) keywords main :: io () main = inputline <- initializeinput mysettings putstrln "done" but bit disappointed ghc error : ambiguous type variable `t0' in constraint: (control.monad.io.class.monadio t0) arising use of `defaultsettings' probable fix: add type signature fixes these type variable(s) i set type each function didn't solve pr

Java String.replace() - replaces more than just the substring I specify? -

as per this codingbat problem trying following: given string, if first or last chars 'x', return string without 'x' chars, , otherwise return string unchanged. my code: public string withoutx(string str) { if (str.startswith("x")) { str = str.replace(str.substring(0, 1), ""); } if (str.endswith("x")) { str = str.replace(str.substring(str.length()-1), ""); } return str; } this code replaces x characters in string, rather first , last. why happen, , way solve it? from sdk replace method: returns new string resulting replacing all occurrences of oldchar in string newchar. you can solve without replace: public string withoutx(string str) { if (str == null) { return null; } if (str.startswith("x")) { str = str.substring(1); } if (str.endswith("x")) { str = str.substring(0, str.length()-1);

log4j - Solr retaining disk space -

i'm experiencing following problem on productions solr slaves servers, solr keeps retaining disk space, if can't see file holding onto space , need solve issue restart solr every day, honest not ideal. we think way log4j log rotation, seems when actual log file rotated solr leaving kind of thread open , thread continuously writing on log file. this log4j.properties of now: solr.log=logs/ log4j.rootlogger=info, file, console log4j.appender.console=org.apache.log4j.consoleappender log4j.appender.console.layout=org.apache.log4j.patternlayout log4j.appender.console.layout.conversionpattern=%-4r [%t] %-5p %c %x \u2013 %m%n #- size rotation log cleanup. log4j.appender.file=org.apache.log4j.rollingfileappender log4j.appender.file.maxfilesize=4mb log4j.appender.file.maxbackupindex=9 #- file log , log format log4j.appender.file.file=${solr.log}/solr.log log4j.appender.file.layout=org.apache.log4j.patternlayout log4j.appender.file.layout.conversionpattern=%-5p - %d{yyyy-mm-

cron - Inside Docker container, cronjobs are not getting executed -

i have made docker image, dockerfile, , want cronjob executed periodically when container based on image running. dockerfile (the relevant parts): from l3iggs/archlinux:latest copy source /srv/visitor workdir /srv/visitor run pacman -syyu --needed --noconfirm \ && pacman -s --needed --noconfirm make gcc cronie python2 nodejs phantomjs \ && printf "*/2 * * * * node /srv/visitor/visitor.js \n" >> cronjobs \ && crontab cronjobs \ && rm cronjobs \ && npm install -g node-gyp \ && python=/usr/sbin/python2 && export python \ && npm install expose 80 cmd ["/bin/sh", "-c"] after creation of image run container , verify indeed cronjob has been added: crontab -l */2 * * * * node /srv/visitor/visitor.js now, problem cronjob never executed. have, of course, tested "node /srv/visitor/visitor.js" executes when

gruntjs - How to set the environment for Grunt? -

i defined task section of gruntfile.js 2 environments -- development , production . don't understand, how grunt decides, wheter use environment section. gruntfile.js module.exports = function(grunt) { // project configuration. grunt.initconfig({ pkg: grunt.file.readjson('package.json'), less: { development: { options: { paths: ["public/css"] }, files: { "public/css/style.css": "public/css/style.less" } }, production: { options: { paths: ["public/css"], plugins: [ ], modifyvars: { } }, files: { "public/css/style.css": "public/css/style.less" } } }, watch: { css: { files: 'public/css/*.less', tasks: ['less'], options: { livereload: true, }, }, } }

clojure - best way to increase date by x days -

i need read in date string in yyyymmdd format , increase x amount of days - @ minute doing converting millis , adding 1 day in mills converting yyyymmdd. (.print (.withzone (datetimeformat/forpattern "yyyymmdd") (datetimezone/forid "est")) (+ 86400000 (.parsemillis (.withzone (datetimeformat/forpattern "yyyymmdd") (datetimezone/forid "est")) "20150401"))) is there cleaner way this? clj-time library not available me, , using clojure 1.2 since cant't use clj-time , best option in case, can't think of better using org.joda.time did. however, suggest rewriting code little bit: there no need time zones here; you create datetimeformat object once , reuse it. here how function look: (defn add [date pattern days] (let [fmt (datetimeformat/forpattern pattern) add (* 86400000 days)] (->> date (.parsemillis fmt) (+ add) (.print fmt)))) (add "

linux - Ruby-on-rails - rake db:migrate - error -

my question error when try run command: rake db:migrate on linux vm set @ nitrous.io. error "rake aborted!". here snapshot: ~/workspace/myblog$ rake db:migrate rake aborted! no rakefile found (looking for: rakefile, rakefile, rakefile.rb, rakefile.rb) i've searched on stack overflow , found several similar questions , answers. before try of specific responses wanted ask question bit differently. reason answers seem remarkably varied , specific others environments. here thoughts: is problem suspect "path" settings aren't finding rake file needed? if so, can find ways fix in linux? to vm set followed great instructions at: http://railsapps.github.io/rubyonrails-nitrous-io.html in doing created di

MYSQL Select with joins and where -

i got 2 tables: device deviceid devicename categoryid category categoryid categoryname it seems stupid solve problem; need select query brings me result: resulttable deviceid categoryid categoryname i tried this, no success: select deviceid , categoryid , categoryname category left join device on (category.categoryid = device.categoryid) deviceid = '1'; in short, need table shows me categorie's id , name, of category certain device in. hope me, since english not good. your query should this: select d.deviceid, c.categoryid, c.categoryname device d inner join category c on c.categoryid = d.categoryid d.deviceid = 1

php - PHPMailer refuses to send attachment -

i've been trying while head around , have no clue. i'm trying write simple form send email uploaded file (which expanded useful) , isn't working @ all. the emails coming through appropriate body, no attachments being included. i've tried file upload form, addattachments linking file on server , addattachments pointing image on imgur , none of them work; attachment never comes through. i'm @ end of patience right now, know i'm doing wrong or way without phpmailer? html form <form action="xxxx.php" id="upload" method="post" name="upload"> <input id="filetoupload" name="filetoupload" type="file" /> <input type="submit" /> </form> php code require("../../../classes/class.phpmailer.php"); $mail = new phpmailer(); $mail->from = "xx@xx.co.uk"; $mail->fromname = "uploader"; $mail->addaddress("xx@xx.co.uk&

javascript - Backbone ID attribute is different than the parameter I need for the API -

i'm using backbone collections , models api. id attribute default id attribute mongo (_id) in api, use different unique key single model. slug unique. the problem when want save(), put request instead of post because assumes there model key (slug) because user able enter slug himself (with proper validations of course). is there way can 'say': "ok, idattribute _id want use slug when fetching data? well, got working doing following: var page = new pagemodel({_id: param}); // no idea why works tbh page.fetch(); have no idea why works since model _id not equal param i'm giving somehow finds correct model anyway.

Wordpress Database Gone but Site Online... Rebuild Possible? -

the database site yokebreak.com has gone awol. no idea how or why, , host mediatemple claims not have backups nor have made effort explain happened. (very disappointed in great mt customer service right it's been week no real answers.) anyway, what's done done, , need site rebuilt. considering cached site , content still online, wondering if had ideas or experience restoring db still-live wordpress site? is possible or @ least there faster way done copying , pasting old content? any tips or advice much, appreciated! thanks! cheers, kyle duck unfortunately, if database gone , looking @ cached version of website, there not way recover database except form of backup. as have stated there no backup available, best thing can try , salvage of site possible sources content might reside such saving images cached version, copying , pasting text, or perhaps or else involved in original build may still have content, images, text, files on offline disk.

html - How to validate text box in Angular js -

i have text box , search button in ui. want validate numbers should entered on button click. i didn't use in form(i got know lot of ways validate form control). i've designed it(independent) in div. so can pls guide me validate control in angular. <div id="srchbox"> <p id="ptext">please enter movie id</p> <input type="text" class="form-control" placeholder="search" id="srchtxt" ng-model="_id"> <button type="submit" class="btn btn-default" id="btnsrch" ng-click="search(_id)"><span class="glyphicon glyphicon-search"></span></button> </div> use ngpattern directive. from documentation sets pattern validation error key if ngmodel value not match regexp found evaluating angular expression given in attribute value. if expression ev

How does the Enumeration.Value of a scala enumeration knows the name of the member? -

in scala, can create enumeration this: object weekday extends enumeration { val monday, tuesday = value } you can call tostring() name of member @ runtime val name = weekday.monday.tostring // name = "monday" how possible? value method creates new object time, how can method access name of declared member without of compiler? pure scala magic me.

reporting services - ssrs parameter using lookup -

i'm trying retrive multiple values of same row of dataset. have first parameter uses dataset called "getcyclevie" there retrive row identifier of dataset. have retrive 2 other values of row use parameter in dataset, dtdebut , dtfin works in textbox =lookup( trim(parameters!cyclevie.value) ,trim(fields!cyclevie.value) ,fields!dtdebut.value ,"getcyclevie" ) however when add default value of parameter or if add paramter in dataset following error une expression de la propriété value utilisée pour le paramètre de rapport de l'objet 'dtdebut' fait référence à un champ. les champs ne peuvent pas être utilisés dans les expressions de paramètre de rapport. translates an expression of property value used report parameter object 'dtdebut' referencing field. field cannot used in parameter expressions of report i don't need lookup, need retreive multiple values of same row of dataset. i don't think lookup p

http - Testing API with Curl -

i'm writing api flask. testing browser works great: http://stuff.com/login?username=test@test.com&password=testpassword returns expect. however, tried typing curl 2 ways (forgive ignorance, new lamp) curl http://stuff.com/login?username=test@test.com&password=testpassword curl -i http://stuff.com/login?username=test@test.com&password=testpassword unfortunately, variables in query aren't making server, error message similar passing: http://stuff.com/login?username= help? i believe reason because shell evaluating get arguments using, instead of passing them on string. prevent this, use single quotes around request url. example: curl 'http://stuff.com/login?username=test@test.com&password=testpassword'

ios - Is there any way to enable NSURLSession to run more than 4 NSURLSessionUploadTasks concurrently? -

when create , start 20 nsurlsessionuploadtasks 3-4 run @ time, when httpmaximumconnectionsperhost set 20! i understand can limit number of max uploads httpmaximumconnectionsperhost. however, want increase number of concurrent uploads. have started 'resumed' 20 new tasks 3 or 4 run concurrently. when 1 batch finishes, 3 or 4 more start until tasks have completed. not ok, because server requires substantial amount of time process each upload, meaning i'm not getting out of user's available bandwidth while server working respond post requests. how can make nsurlsession run httpmaximumconnectionsperhost? httpmaximumconnectionsperhost works fine limit number of concurrent uploads, nsurlsession appears throttle down 3 or 4 regardless of value set httpmaximumconnectionsperhost. means httpmaximumconnectionsperhost allows choose between 1 , 4 concurrent uploads, instead of between 1 , your_max concurrent uploads!! to clear, question is, there way run 5 or more co

Referencing worksheets in excel spreadsheet by index rather than name in r -

im trying use xlconnect in order import worksheets datasource if use code below subsequent error library(xlconnect) wk = loadworkbook("/users/sebastianzeki/desktop/sequencingscripts/bedtools/bedtools2-master/cohortcomparisons/pancancercommonscnas.xlsx") amp_genesall_cancer = readworksheet(wk, sheet="amp_genes.all_cancer.txt", header=true) error: illegalargumentexception (java): sheet index (-1) out of range (0..25) one work around convert names numbers of worksheets still need have control on how each 1 imported rather importing 1 dataframe. not sure how though assuming wk = code runs correctly, , see 'formal class workbook' object appear, have misspelled sheet name. index -1 means string given title not match. to use indexes, use: amp_genesall_cancer = readworksheet(wk, sheet=1, header=true) with 1 being sheet number

java - How to use file picker in android app -

i developing simple android app, want use file picker when press button, how can implement file picker in app. i spent time earlier figuring out wrap intents provide ability hook third-party app components content selection. works media files, if want users able select file, must have existing "file explorer" app installed. because many android devices don't have stock file explorers, developer must instruct user install one, or build one, themselves. afilechooser solves issue. you can clone ipaulpro/afilechooser .

javascript - x-editable post value is undefined -

i created x-editable form : <a href='#' class='username' data-pk='<?php echo $key['idca']; ?>' data-type="text" data-placement="right"> <?php echo $key['categoryname']; ?> </a> then created javascript function handle x-editable form : $.fn.editable.defaults.success = function() { $(this).show() }; $.fn.editable.defaults.mode = 'inline'; $('.username').editable({ url:'edit.php', pk:'1', type:'text', send:'always', ajaxoptions:{ datatype:'json' }, success: function(response, newvalue) { window.alert('oke'); }, error: function(response, newvalue) { window.alert('failed'); } }); and in php create follow : <?php $pk = $_post['pk']; $val = $_post['value']; $nam

metaprogramming - C++11 variadic template parameter expansion -

i following: template<typename func> class functionwrapper { public: typedef decltype(func()) returntype; typedef ... argstype; functionwrapper(func func) { func_ = func; } returntype operator() (argstype args) { return func_(args); } private: func func_; }; the problem don't know how deduce argstype func type. i'd make work when function returns/accepts nothing well. the usecase be: functionwrapper<myfunction> wrapper; auto result = wrapper(1, 2, 3); you can determine argument , return type(s) in operator() , use perfect forwarding: template <typename func> class functionwrapper { func func_; public: functionwrapper(func func) : func_(func) {} template <typename... args> auto operator() (args&&... args) -> decltype(func_(std::forward<args>(args)...)) { return func_(std::forward<args>(args)...); } };

eclipse - How to cherry pick from branch A to branch B on a system without history? -

suppose have new system no git history , take fresh checkout of branch a. branch has commit c1 did yesterday other system. want cherry-pick commit c1 in branch b. issue: if take checkout of branch , go commit c1 (in history in git view) , click 'cherry pick', says want cherry pick in branch a? so, there no discussion of branch b here. if take checkout of branch b not show commit c1 @ all. now, how cherry pick commit c1 of branch branch b? using gerrit, gitblit , egit in eclipse. i'm not familiar gui using in particular, concept describing acceptable in git. to cherry-pick commit branch branch b, use following command line commands: git checkout branchb git cherry-pick hashofc1 there should sort of 'view branches' mode in gui using can see commit c1 while having branch b checked out, if not, above commands simple enough execute.

Yii2 MaskedInput with alias 'url' limits input to 60 characters -

i using following code in yii2: <?php $form = activeform::begin(); ?> <?= $form->field($model, 'link')->widget(maskedinput::classname(), [ 'clientoptions' => [ 'alias' => 'url', ], ]) ?> <?php activeform::end(); ?> it seems, input field limited 60 characters. how remove limitations? see url example on: http://demos.krajee.com/masked-input the limitation in jquery.inputmask . see https://github.com/robinherbots/jquery.inputmask/issues/863 . limitation disappear if issue solved , new jquery.inputmask.js included in yii2 bower package.

java - Spring false positive circular dependency reported -

spring reports false positive circular dependency error when dependency order looks below factorybean depends on list (example animalfeeder) animalfeeder depends on list of strings. interesting things are issue not observed when spring instantiation order changes ie) factorybean comes before animalfeeder. issue seen when animalfeeder comes before factorybean. this happens when factorybean involved. issue not observed when simple bean class used instead of factorybean. here source code public interface feeder { void feed(); } public class animalfeederimpl implements feeder { private list<string> feedingtypes; public animalfeederimpl(list<string> feedingtypes) { this.feedingtypes = feedingtypes; } @override public void feed() { //feed here } } public class feedermanager { private final list<feeder> feeders; public feedermanager(list<feeder> feeders) { this.feeders = feeders; } //this method trigger feed

objective c - Core Data's raw date string -

core data store date in format 441922215. sql query grabbing dates strings. is there way raw date value of 441922215 nsdate form? nsdate *date = [nsdate datewithtimeintervalsince1970: coredata value ]

oop - How to do logic based on object ID -

suppose have game, there buildings sorted type. each type represented separate class, have uncommon logic buildings of same type. how 1 implement kind of behaviour? for example, can identify buildings id, can have giant switch or command pattern inside building type class. think not right approach. another approach have different class divergent logic. proposes lot of small classes. this polymorphism aims solve, , 1 of big differences between procedural , oop programming. can achieve through extending base class, or implementing interface. here extending base class: public abstract class building { abstract void destroy(); } public brickbuilding extends building { @override public void destroy() { bricks.falltoground(); } } public haybuilding extends building { @override public void destroy() { straw.blowinwind(); } } in places in code have used switch statement switch on building type, hold reference abstract buildin

apache - .htaccess Force Trailing Slash Rewrite -

apologies i'm new url rewrites. i've managed rewrite working in conventional sense cannot force have trailing slash. here code: rewriteengine on rewritecond %{request_filename} !-f rewritecond %{request_filename} !-d rewritecond %{request_filename}\.html -f rewriterule ^(.*)$ /$1.html [l,qsa] you can try: rewriteengine on rewritebase / # add trailing slash non-files rewritecond %{request_filename} !-f rewriterule [^/]$ %{request_uri}/ [l,r=301,ne] rewritecond %{request_filename} !-f rewritecond %{request_filename} !-d rewritecond %{request_filename}\.html -f rewriterule ^(.*)/?$ $1.html [l]

xamarin.ios - Xamarin CollectionViewCell not instantiating from storyboard -

i collaborating designer styles elements on xamarin project storyboard. have trouble referencing placed elements in code. outlets created, in uicollectionviewcell uilabels etc not instantiated. here code simple test app demonstrate problem. the xamarin generated code-behind: [register ("cardcell")] partial class cardcell { [outlet] [generatedcode ("ios designer", "1.0")] uilabel txtname { get; set; } void releasedesigneroutlets () { if (txtname != null) { txtname.dispose (); txtname = null; } } } my attempt set ui properties causes crash: public partial class cardcell : uicollectionviewcell { public cardcell (intptr handle) : base (handle) { } public void update(string name) { txtname.text = name; // throws exception here, because textname null } } the view controller delegate methods: public partial class testcollectioncontroller : uicollec

python - Using Fibonacci Program to Sum Even Elements -

i trying solve following using python: each new term in fibonacci sequence generated adding previous 2 terms. starting 1 , 2, first 10 terms be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... by considering terms in fibonacci sequence values not exceed 4 million, find sum of even-valued terms. so far, have been able generate fibonacci elements in trying sum elements, code seems stall. here code below: def fib(n): if n==0: return 0 elif n==1: return 1 if n>1: return fib(n-1)+fib(n-2) n=0 total=0 while fib(n)<=4000000: if fib(n)%2==0: total+=fib(n) print(total) any suggestions welcome. you have infinite loop n isn't ever incremented 0 in while loop. additionally, why not sum fibonacci total as as find next fibonacci value in same while loop, this: x= 1 y=1 total = 0 while x <= 4000000: if x % 2 == 0: total += x x, y = y, x + y print (total) outputs: 4613732

javascript - Should I / how do I clear a mousemove JQuery event listener? -

when use $(".page").mousemove(function(event){}); as mouseup event comes, no longer need listener. since i'll applying listener repetitively different actions, seems me these listeners might stick around , build (needlessly wasting cpu) user activates function many times. i'm not sure how works internally, that's guess. should / how clear mousemove jquery event listener? here code: $('.page').off('mousemove'); but please note following approach turns off functions firing on mousemove . if want turn off prticular function should following: // define function fires on mousemove function anyfunctionname () { // code } // set listener $('.page').on('mousemove', anyfunctionname); // turn off function called funcionname $('.page').off('mousemove', anyfunctionname); another way turning off particular function defining name event: // define function fires on mousemove function anyfunction

vagrantfile - Share a single file in vagrant -

how share single file, instead of sharing whole folder like config.vm.synced_folder "host/folder", "box/folder" ? in other words there way have like: config.vm.synced_folder "host/folder/file.conf", "box/folder/file.conf" use include flag in rsync args array: config.vm.synced_folder "host/folder/", "box/folder/", type: "rsync", rsync__args: ["--include=file.conf"]

java - rotate Frame in JavaCV -

i write simple app android whick use ffmpeg + javacv. can capture image camera , can recorde video. want rotate frame when record video, don't can :-( please see image stop , save code: public void stoprecording() { runaudiothread = false; try { audiothread.join(); } catch (interruptedexception e) { e.printstacktrace(); } audiorecordrunnable = null; audiothread = null; if (recorder != null && recording) { if (record_length > 0) { log.v(log_tag,"writing frames"); try { int firstindex = imagesindex % samples.length; int lastindex = (imagesindex - 1) % images.length; if (imagesindex <= images.length) { firstindex = 0; lastindex = imagesindex - 1; } if ((starttime = timestamps[lasti

Is it possible to launch the Google Drive image viewer? -

basically, want reproduce behaviour of when double-click on image in google drive folder , presented image viewer images , videos contained in folder. possible? if so, how? thanks! what you're looking known google drive viewer . close guess though. far know, isn't service can use. however, here facebook's explanation how implemented theirs. hope gives idea helps decide whether wanna implement or not.

vim winminwidth "E36 Not enough room" error -

i'm having problems setting 'dynamic' window width in .vimrc. doing winheight works fine. here's code: " dynamic current window sizing tbot art of vim set winheight=9 set winminheight=9 let &winheight = &lines - 9 set winwidth=40 set winminwidth=40 " e36 not enough room here let &winwidth = &columns - 40 the winheight settings work great; winwidth settings error. however, works once i'm in vim; have 3-7 related windows open in single tab , dynamic resizing means have lots of space horizontally , vertically work in. i can reproduce this, , tried work around via :autocmd vimenter , other such tricks, failed. if works out in end, can suppress error prepending :silent! command.

php - Symfony is changing where it's looking for assets depending on url -

Image
symfony looks looking assets in relative location based on url path navigate to. assets load , applied correctly when navigate "first-level" path such example.com/mpre , example.com/test , example.com/foo , of assets 404 when navigate "second-level" url such example.com/mpre/test , example.com/test/foo , example.com/foo/bar . why this? there way framework in 1 spot assets regardless of url? i have 2 urls example.com/mpre example.com/mpre/test my assets (css, js) load fine on first url, example.com/mpre , of them 404 when navigate second url, example.com/mpre/test when go inspector on each page see path assets, see following: example.com/bundles/app/css/023f7f6_style.css_4.css //example.com/mpre 200 ok response example.com/mpre/bundles/app/css/c8b625f_style.css_3.css //example.com/mpre/test 404 not found response in config.yml have following line assetic: assetic: write_to: %kernel.root_dir%/../web/bundles/app/ additional inf

php - Create html table from fields in foreach loop -

i have following code displays custom fields html form: <?php foreach ( $job_fields $key => $field ) : ?> <fieldset class="fieldset-<?php esc_attr_e( $key ); ?>"> <label for="<?php esc_attr_e( $key ); ?>"><?php echo $field['label'] . apply_filters( 'submit_job_form_required_label', $field['required'] ? '' : ' <small>' . __( '(optional)', 'wp-job-manager' ) . '</small>', $field ); ?></label> <div class="field <?php echo $field['required'] ? 'required-field' : ''; ?>"> <?php get_job_manager_template( 'form-fields/' . $field['type'] . '-field.php', array( 'key' => $key, 'field' => $field ) ); ?> </div> </fieldset> is there way customize code display fields in html tab

matlab - Getting intensity value for all pixels in an image -

i have create algorithm determine dark "grayscale image" in matlab, have collect pixels' intensity value evaluate if 65% of pixels in particular image lesser 100 dark. the question how collect/get these value create algorithm this? assume image contained in array img (for instance, obtained imread ). then: % define threshold th = 100; % percentage of pixels below threshold p = nnz(img<th)/numel(img)*100; % decide if p<65 ... else ... end hope helps,

Python: Accessing elements of multi-dimensional list, given a list of indexes -

i have multidimensional list f, holding elements of type. so, if example rank 4, elements of f can accessed f[a][b][c][d] . given list l=[a,b,c,d] , access f[a][b][c][d] . problem rank going changing, cannot have f[l[0]][l[1]][l[2]][l[3]] . ideally, able f[l] , element f[a][b][c][d] . think can done numpy, types of arrays i'm using, numpy not suitable, want python lists. how can have above? edit: specific example of i'm trying achieve, see demo in martijn's answer. you can use reduce() function access consecutive elements: from functools import reduce # forward compatibility import operator reduce(operator.getitem, indices, somelist) in python 3 reduce moved functools module, in python 2.6 , can access in location. the above uses operator.getitem() function apply each index previous result (starting @ somelist ). demo: >>> import operator >>> somelist = ['index0', ['index10', 'index11', ['

Using Powershell to remove a user from a list of groups -

trying script remove user list of groups. not sure part of language here wrong. doesn't return error in ise. i'm admittedly rookie in writing own powershell scripts instead of modifying others. appreciated. import-module activedirectory $group = @('grouopname1','groupname2','groupname3') $user = "testa" if ($user.memberof -like $group) { foreach ($user in $group ) { remove-adprincipalgroupmembership -identity $user -memberof $group -confirm:$false } } on thing you'll need learn when using powershell it's important test kind of output , object give you. $user = "testa" | $user.memberof that give error, because string doesn't have member property "memberof" $user = get-aduser testa -properties memberof that give object containing user "testa", , since memberof property isn't retrieved default, need add in. $user.memberof this return distinguishedname of g

Create Twitter app - Rate Limit Exceeded -

when creating new twitter app @ https://apps.twitter.com/ receive following error upon clicking submit. "error: rate limit exceeded" according other developers on twittercommunity.com, seems recent bug affecting new apps... there solution soon edit: trying create new application past 2 days , succeeded... looks bug , it's ok now... try :) https://twittercommunity.com/t/rate-limit-exceed-in-creating-new-app-at-apps-twitter-com/34985 https://twittercommunity.com/t/rate-limit-exceeded-when-i-try-to-create-an-application/21453/3

error handling - Possible to Have Multiple Try/Catch Blocks Within Each Other in a SSIS Script? -

i have project i'm working on , wanted double check before going through work of coding , testing if possible. i'm attempting along lines of: try { // stuff try { // other stuff } catch { // fail silently } // more stuff } catch (...) { // process error } is possible have try/catch's within try/catch's? languages allow when attempted search web not, life of me, find answers. thanks an ssis script task c# (or vb.net). c# allows this, ergo ssis allows this. having written few ssis script tasks in time, i'd encourage take advantage of raising events in script task . depending on version + deployment model + invocation method, might want turn on native ssis logging. project deployment model (in 2012+) provides native logging. otherwise, need specify events you'd log logging provider(s) you'd use them. need done part of package development. otherwise, dtexec call /rep ewi ensure errors, warnings , information even

javascript - Perform multiple clicks as long as user is hovering over an element in jQuery -

i have following jquery. once hover on next or previous arrows, clicks on them, making slider move. need modify code, keeps clicking long hovering, right now, once. $( "#slider .next, #slider .prev" ).hover( function() { $(this).click(); }, function() {} ); the slider uses jquery plugin called tiny carousel thanks this trigger click on elements every second: var clr; $(".next, .prev").hover(function (e) { clr = setinterval(function () { $(e.target).click(); }, 1000) }, function () { clearinterval(clr); }); jsfiddle example

sql - Query Result(NULL value/Datetime format) -

i have query use put rows in 1 column, dynamic because need @ least 8 tables: declare @tblname varchar(20) = 'location' declare @columns nvarchar(max), @sql nvarchar(max) select @columns = coalesce(@columns, '') + '+[' + column_name + '],+'''''',''''''' information_schema.columns table_name = @tblname , table_schema='les' select @columns set @sql = 'select concat(''''''''' + stuff(@columns, 103,9, '') + '+'''''') ' + @tblname select @sql -------------------------------------------------------------------------- r1: select concat(''''+[location],+''','''+[location type],+''','''+[region],+''','''+[world region],+''','''+[refresh date]+''') location if execute query (without datetime column

linux - how to plot an array directly using plotutils -

i'm trying plot array.. example [1.0,2.0,3.0,4.0] know can plot files, want plot directly like: plot [1.0,2.0,3.0,4.0] is possible , how?? there go.. echo 1 2 3 4 | graph -t ps -a > plot.ps you find in same directory can add arguments color plot , optimize it...

httpserver - Can nginx handle duplicated HTTP headers? -

client sending requests duplicated headers server. this: get /somefile.txt http/1.1 host: example.com accept: */* if-modified-since: tue, 31 mar 2016 20:00:12 gmt if-modified-since: tue, 31 mar 2016 20:00:12 gmt if-modified-since: tue, 31 mar 2016 20:00:12 gmt apache handling requests concatenating duplicating headers ", ". resulting (handled) request like: get /somefile.txt http/1.1 host: example.com accept: */* if-modified-since: tue, 31 mar 2016 20:00:12 gmt, tue, 31 mar 2016 20:00:12 gmt, tue, 31 mar 2016 20:00:12 gmt but nginx returning code 400 (bad request). can not modify client's behaviour. need tmp solution on nginx server handle these request (as apache example) thanks. the uniqueness check header "if-unmodified-since" hardcoded (see [1] [2] ). cannot disabled or dismissed, because nginx validates headers during parsing, on stage of request processing before other handler or configuration option can intercept process. so, right

image processing - OpenCV: GoPro video editing blur -

i attempting post-process video in opencv. problem gopro video blurry, high frame rate. is there way can remove blur? i've heard deinterlacing, don't know if applies gopro 3+, or begin. any appreciated. you can record @ high frame rate remove blur, make sure recording enough natural light, recording outdoors recommended. look @ video: https://www.youtube.com/watch?v=-nu2_erc_oe at 30 fps, there blur in car, @ 60fps blur non existant, doubling fps can good. since have hero3+ can record 720p 60 , remove blur. wvga 120fps can justice (example 1080p still applies)

Using ASM to get the reference returned via ARETURN bytecode instruction -

i have method returns value generated in method similar this: public static filechannel open() { return provider.newobject(); } so bytecode of method looks this: invokevirtual org/test/helper.process ()lorg/test/myobject; areturn i have java agent uses asm bytecode-transformation when jvm starts up. now inject code access returned myobject without doing changes invoke itself, i.e. ideally add bytecode instructions before areturn. which asm/bytecode construct allows me access object returned here? for simple, can put dup instruction in there followed desired use. if need inject more complex code, should store in register (it doesn't matter since won't used after code except in exceedingly unlikely event areturn throws exception , there's exception handler in method). so if you're using register 0 go astore_0 (your code) aload_0 areturn .

ios - How can I make a textView sit on top of the keyboard when pressed? -

i have text view on bottom of 1 of views, , hidden keyboard when pops if didn't anything. did when keyboard appear, text view moves 160 points. problem doesn't sit in exact same place on every iphone because of different sizes. know if possible text view sit say, 20 points on top of keyboard, instead of pushing 160 points its' origin. override func viewdidload() { super.viewdidload() nsnotificationcenter.defaultcenter().addobserver(self, selector: selector("keyboardwillshow:"), name:uikeyboardwillshownotification, object: nil); nsnotificationcenter.defaultcenter().addobserver(self, selector: selector("keyboardwillhide:"), name:uikeyboardwillhidenotification, object: nil); } var isshown: bool = false var willhide: bool = false func keyboardwillshow(sender: nsnotification) { isshown = true } func keyboardwillhide(sender: nsnotification) { willhide = true } func textviewdidbeginediting(textview: uitextview) { if issho

Piping cmd output to variable in PowerShell -

i have following in powershell script: cmd /c npm run build-release $succeeded = $lastexitcode what i'd is: pipe output of cmd variable doesn't write host only if $succeeded eq $true , write-host output variable cmd how can done? use invoke-expression : $output = invoke-expression "cmd /c npm run build-release" $succeeded = $lastexitcode if($succeeded -eq 0) { write-output $output }

jsf 2 - Error when trying to use custom realm for Shiro -

using balusc tutorial implementing shiro jsf app http://balusc.blogspot.fi/2013/01/apache-shiro-is-it-ready-for-java-ee-6.html currently trying add own custom realm on top of example, missing something. i have shiro.ini follows (mainly copied given tutorial , not necessary): [main] user = com.example.filter.ajaxsessionfilter mockrealm = com.example.realm.mockrealm authc.loginurl = /login.xhtml user.loginurl = /login.xhtml [users] admin = password [urls] /login.xhtml = user /* = user securitymanager.realms = $mockrealm my mockrealm in short: import org.apache.shiro.realm.authorizingrealm; public class mockrealm extends authorizingrealm { /* implement stuff */ } i running on glassfish v4.1. worked far correctly until tried add custom realm. results in following error: exception while loading app : java.lang.illegalstateexception: containerbase.addchild: start: org.apache.catalina.lifecycleexception: java.lang.illegalargumentexception: there no filter name '$mockr

grep regex: search for any of a set of words -

i want search large set of files set of words in order, or without spaces or punctuation. so, example, if search hello, there, friend , should match hello there friend friend, hello there theretherefriendhello but not hello friend there there friend i can't figure out way this. possible using grep, or variation of grep? is possible using grep, or variation of grep? you can use grep -p ie in perl mode,the following regex. ^(?=.*hello)(?=.*there)(?=.*friend).*$ see demo. https://regex101.com/r/sj9gm7/37

Meteor Collections schema not allowing Google authentication -

i'm building simple user account using meteorjs. user given option login/register using google. if registering first time, users prompted fill out profile information after authenticating user account. i'm using collections2 manage schema user account , attaching meteor.users, seen here: var schemas = {}; schemas.userprofile = new simpleschema({ firstname: { type: string, regex: /^[a-za-z-]{2,25}$/, optional: true }, lastname: { type: string, regex: /^[a-za-z]{2,25}$/, optional: true }, gender: { type: string, allowedvalues: ['male', 'female'], optional: true } }); schemas.user = new simpleschema({ username: { type: string, regex: /^[a-z0-9a-z_]{3,15}$/ }, _id : { type: string }, createdat: { type: date }, profile: { type: object }, services: { type: object, black

Change Number Formatting on X-Axis Matplotlib -

Image
i'm sure easy answer, not find anywhere. want x-axis read values 2000, 2001, 2002, 2003, 2004, not 2 x e**3. import numpy np import matplotlib.pyplot plt x = [2000, 2001, 2002, 2003, 2004] y = [2000, 2001, 2002, 2003, 2004] plt.xticks(np.arange(min(x), max(x)+1, 1.0)) plt.plot(x,y) plt.show() the code returns graph represents values this. how change it? @ avinash pandey can use plt.xticks(np.arange(min(x), max(x)+1, 1.0), x) try in code space there labels needed... more follow link

jQuery slideshow ... how to add text from alt tag? -

i have been playing around slideshow: http://tympanus.net/codrops/2013/02/26/full-width-image-slider/ what have text current image alt tag show below image in center .... possible? there .attr() property in jquery. clear usage of property in link this official jquery page

javascript - Disappearing data, what's going on? Pebble newbie -

brand new , naive pebble sdk , c lots of experience in other languages. means i'm going embarrassed when solves me but... have 2 files in watchface project based on tutorials... i'm pulling in different data works getting started tutorial until point code updates 1 of text layers with... nothing. it's got me puzzled becuase data it's supposed putting in there appears fine in console log it's getting passed over. anyways, here's c include #define key_monthmiles 0 #define key_monthelevation 1 #define key_totalmiles 2 #define key_totalelevation 3 static window *s_main_window; static textlayer *s_time_layer; static bitmaplayer *s_background_layer; static gbitmap *s_background_bitmap; static textlayer *s_weather_layer; static void update_time() { // tm structure time_t temp = time(null); struct tm *tick_time = localtime(&temp); // create long-lived buffer static char buffer[] = "00:00"; // write current hours , minute

python - How to get the name of an object through the template_tag? -

i want pass name of object through template tag got error: 'str' object has no attribute 'mymodelone_set' my models: class mymodelone(models.model): name = models.charfield(max_length=50) show = models.foreignkey('mymodeltwo') def __unicode__(self): return self.title class mymodeltwo(models.model): title = models.charfield(max_length=50) description = models.textfield(blank=true) def __unicode__(self): return self.name my template tag looks this: in base.html: {% load my_tags %}{% my_func obj%} in model_tag.py register = template.library() @register.inclusion_tag('myapp/widget.html') def my_func(obj): param1 = obj.mymodelone_set.all() return {} what doing wrong? class mymodelone(models.model): name = models.charfield(max_length=50) show = models.foreignkey('mymodeltwo') def __unicode__(self): return self.name class mymodeltwo(models.model): tit

python - String variable args are treated as dict types in robot framework -

*** test cases *** log test run keyword logtype *** keyword *** logtype ${type_object}= evaluate type( ${tc_args} ) log console type object ${type_object} when run command, pybot -v tc_args:'{"a":"b"}' a.robot , robot prints, the type object <type 'dict'> but, isn't default behavior treat single quoted literals strings ? so, ideally must have printed <type 'str'> instead of <type 'dict'> . your variable string. check it, try dictionary keyword on (like "get dictionary" collections lib) , see fails. run code see it: *** settings *** library collections *** test cases *** log test # let's test proper dictionary ${dict} = create dictionary b ${value} = dictionary ${dict} should equal ${value} b log console ${\n}this real dictionary # ${tc_args} passed on command line # evaluate might let thing have dict ${type_object} = evaluate type( $