Posts

Showing posts from June, 2013

javascript - MongoDB: way of visualizing database? -

i've began learning mongodb research project i've been working on. i've gotten comfortable querying on command prompt, , command prompt in general, need way of making interactive, user-friendly tool people in workplace interact data (i.e. data, filter, etc.). in other words, expecting them use command prompt isn't option project. said, i'm not sure how go accomplishing this. appreciated! you can use robomongo. please refer www.robomongo.org more details

python - Determine if class attribute is a read-only data descriptor -

a read-only data descriptor descriptor defines both __get__ , __set__ , __set__ raises attributeerror when called. an example simple read-only property: class test(): _i = 1 @property def i(self): return self._i assert hasattr(test.i, '__get__') assert hasattr(test.i, '__set__') t = test() t.i # 1 t.i = 2 # error if have instance of class, can determine if instance attribute read-only data descriptor way (although don't @ all): def is_ro_data_descriptor_from_instance(instance, attr): temp = getattr(instance, attr) try: setattr(instance, attr, none) except attributeerror: return true else: setattr(instance, attr, temp) return false if know class doesn't require arguments instantiated, can determine if class attribute read-only data descriptor similar above: def is_ro_data_descriptor_from_klass(klass, attr): try: setattr(klass(), attr, none) except attributee...

java - Is there a way to 100% self-contain libraries in an Eclipse Android project? -

my question simple i've not been able find answer or work out solution myself. i'm using few libraries in projects (e.g. holoeverywhere, viewpagerindicator, etc.), , move between computers often, send projects colleagues, etc. anytime this, library references messed , have redo them. isn't more hassle, rather have library references self-contained rather having use references folders on drive. i've tried exporting libraries jar files , including in build path project no avail. that's thing i've thought do, have no clue how else accomplish this. basically, want able have library contained in project instead of referencing library projects elsewhere in workspace. possible? thanks help!

matlab - quiver3 arrow color corresponding to magnitude -

Image
i want color of each arrow in quiver3 plot matlab correspond magnitude of each arrow. there way that? i saw few examples online able 2d quiver , none of them work 3d variant, quiver3 . i have following plot , want replace blue arrows color corresponding magnitude. in old graphics system (r2014a , earlier) not possible using built-in quiver object. can of plot objects used compose quiver plot q = quiver(1:5, 1:5, 1:5, 1:5); handles = findall(q, 'type', 'line'); but tails represented 1 plot object, , arrow heads represented another. such, can't alter color of each head/tail individually . set(handles(1), 'color', 'r') set(handles(2), 'color', 'g') however, introduction of hg2 (r2014b , later), can access two (undocumented) linestrip objects ( matlab.graphics.primitive.world.linestrip ) (one represents heads , 1 represents tails). these accessible via hidden properties tail , head . q = quiver(1, 1, 1...

weka - False Acceptance Rate and False Rejection Rate calculation using a n*n confusion matrix -

far , frr used express results of biometric devices. below confusion matrix produced biometric data produced in weka. couldn't find resources explaining procedure calculate far , frr using n*n confusion matrix. explaining procedure of great help. in advance! weka gives these values, tp rate, fp rate, precision, recall, f-measure , roc area. please suggest if required values can calculated using these. === confusion matrix === a b c d e f g h j k l m n o <-- classified 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 | = user1 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 | b = user2 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 | c = user3 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 | d = user4 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 | e = user5 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 | f = user6 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 | g = user7 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 | h = user9 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 | = user10 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 | j = user11 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 | k = user14 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 | l =...

Meteor accounts Twitter not working when deployed (Passenger/Nginx) -

introduction i've developed , tested app in meteor, great until upload server. i use linode , got it admin phusion passenger nginx . first upload app given folder, start passenger (or meteor matter) - go ip address :3000 in browser , looks great. except when want log in twitter, pop based anuthentication shows web page not available question do need install these dependencies manually? , if so, how? or else?

Salt-stack error with state git.config -

i've run error while trying use git.config state saltstack version 2014.7.2 (helium). i'm using masterless setup. ---------- state: - git name: user.email function: config result: false comment: state git.config found in sls git unavailable changes: the state generating error here: git: pkg.installed gitconfigemail: git.config: - name: user.email - value: {{pillar['user']['email']}} - is_global: true - require: - pkg: git what error mean , how fix it? you want use git.config_set state, not git.config module. https://docs.saltstack.com/en/latest/ref/states/all/salt.states.git.html#salt.states.git.config_set

php - Internal Server Error 500 when sending mail to AWS SES with cakephp running on Hiawatha -

i'm getting "internal server error 500" after third or @ first attempt send mail using cakephp 3 through aws ses account (in production mode) running on hiawatha server. here php code: public function sendmail() { $email = new email(); $email->transport('ses'); try { $res = $email->from(['account@example.com' => 'name']) ->to(['receiver@hotmail.com' => 'receiver']) ->subject('test mail') ->send('some text'); } catch (exception $e) { $this->flash->error('error. please, try again.'); echo 'exception : ', $e->getmessage(), "\n"; return $this->redirect('/'); } $this->flash->success('ok. receive confirmation mail'); return $this->redirect('/');} here transport configuration 'emailtransport' => [ ...

ruby on rails - Gem dependency hell installing redmine with CRM plugins -

i installing clean redmine 3.0 crm plugin on fresh install of ubuntu server 14.04lts. succeeded redmine , minor plugin, crm 1 has hit me this: # bundle install --without development test rails_env=production don't run bundler root. bundler can ask sudo if needed, , installing bundle root break application non-root users on machine. warning: gemfile contains multiple primary sources. using `source` more once without block security risk, , may result in installing unexpected gems. resolve warning, use block indicate gems should come secondary source. upgrade warning error, run `bundle config disable_multisource true`. fetching gem metadata https://rubygems.org/......... fetching version metadata https://rubygems.org/.. resolving dependencies... bundler not find compatible versions gem "i18n": in gemfile: rails (= 4.2.0) ruby depends on actionpack (= 4.2.0) ruby depends on activesupport (= 4.2.0) ruby depends on i18n (~> 0.7) ruby...

crm - How to impersonate a IOrganizationService -

once iorganizationservice object instanciated, it´s possible impersonate? better... how impersonate instanciated iorganizationservice object? iorganizationservicefactory servicefactory = executioncontext.getextension<iorganizationservicefactory>(); iorganizationservice service = servicefactory.createorganizationservice(someuserid);

shiny - Total distance of route using Leaflet routing machine in rMaps/rCharts -

i produce shiny app asks 2 addresses, maps efficient route, , calculates total distance of route. can done using leaflet routing machine using javascript library, bunch of further calculations distance of route , have embedded in shiny app. you can produce map using rmaps following demo ramnathv here . i'm not able pull out total distance travelled though can see has been calculated in legend or controller. there exists discussion on how using javascript library - see here . discuss using javascript code: alert('distance: ' + routes[0].summary.totaldistance); here working code rmap. if has ideas how pull out total distance of route , store it, grateful. thank you! # install dependencies if haven't done library(devtools) install_github("ramnathv/rcharts@dev") install_github("ramnathv/rmaps") # create function convert address coordinates library(rcurl) library(rjsonio) construct.geocode.url <- function(address, return.call = "jso...

Color repetition when using boxes in gnuplot -

Image
my data file has 2 columns.the following mwe on columns produces boxes repeated colors. possible produce unique colors each box? reset set term postscript eps size 5.5,4.5 enhanced color solid lw 2\ font "arial,28" set key right set xtics rotate -45 font ",20" set style fill solid 1 border -1 plot 'rankdefcount.dat' using ($0):2:($0):xticlabels(1) \ notitle w boxes lc variable quit here output got: you may try , redefine linetypes boxes want show. code should go before plot. colors="black red orange #fa8072 ...." #[as colors needed] [l=1:words(colors)]{ set linetype l lc rgb word(colors,l) } you can find colors gnuplot here. http://www.uni-hamburg.de/wiss/fb/15/sustainability/schneider/gnuplot/colors.htm

Multiselect in Impresspages Plugin Options -

how may use multiselect field in impresspages plugin options. this: { "label": "social nets", "name": "socialnets", "type": "select", "multiple": "multiple", "default": "", "values": ["", "facebook", "twitter", "pintrest"] } of course, field above "multiple" doesn't work in code snip. so, how implement in plugin options json file? you can use "checkboxes" field type "options": [ { "label": "xxx", "name": "xxx", "type": "checkboxes", "values": ["option1", "option2", "options3", "option4"] } ]

jquery - creating table header with javascript -

i having 2 issues table, 1 of them want show when click button when shows , hides , other how send parameter based on select option createtable function part of code <form class="form-inline" role="form"> <select multiple class="form-control" style = "width:250px"id = "theselect"> <option selected disabled> chose number </option> <option> </option> <option> 1 </option> <option> 2 </option> </select> <button type="submit" id = "load" class="btn btn-default">load</button> </form> <div id ="test"> </div> <script type = "text/javascript"> $(document).ready(function(){ $("#example").hide(); $("#load").click(function(e){ $("#example").show(); }); }); function createtable(param){ var c...

gulp command not return to shell -

i have gulp script, , when run command line, not return shell. this simple gulp command delete files dist directory 'use strict'; var del = require('del'); var gulp = require('gulp'); gulp.task('clean', function (cb) { return del(['dist/**/*'], cb); }); run command: gulp clean [13:39:10] using gulpfile gulpfile.js [13:39:10] starting 'clean'... [13:39:11] finished 'clean' after 6.35 ms npm warn package.json abc@0.0.0 no description npm warn package.json abc@0.0.0 no repository field. npm warn package.json abc@0.0.0 no readme data npm warn package.json karma-coverage@0.2.7 no readme data npm warn package.json karma-phantomjs-launcher@0.1.4 no readme data it not return shell, have ctrl+c return shell. new gulp, please let me know did wrong, thanks. try removing callback argument. gulp.task('clean', function () { return del(['dist/**/*']); });

php - Check for duplicate in array -

i have created html form passes data text file , text file saves data on array. i cannot figure out how go checking see if value exists before putting input in array or text file. name: <input type="text" name="name" /><br /> email: <input type="text" name="email" /><br /> <input type="submit" name="save" value="submit" /><br /> <?php $myarray = array(); if (isset($_post['save'])) { /*the file created in same directory php code resides *a+ not overwrite text*/ $myfile = fopen("donorlist.txt", "a+") or die("unable open file!"); //get data entered user form fwrite($myfile, $_post['name']); fwrite($myfile, " "); fwrite($myfile, $_post['email']); fwrite($myfile, "\r\n"); //next line fclose($myfile);//close file textoutput();//call function } print_r($myarray); //creating function ma...

Creating table with variable name php mysql -

i'am trying create table variable name , columns via forms here's query $execute = mysql_query('create table '.$tname.'( '.$cname.' '.$ctype.' )'); and it's creating table name variable $tname doesnt create columns. try this: $sql= "create table $tname($cname $ctype(45),$cname $ctype(50))"; //echo $sql; $op =mysql_query($sql);

unit testing - How to avoid the 'Error: Unexpected request: GET' every time an AngularJS test does a rootScope.digest() or httpBackend.flush() -

all unit tests, not e2e tests, explicit rootscope.digest() or httpbackend.flush() flush asynchronous callback, experience error: how avoid 'error: unexpected request: get' no more request expected i reckon because httpbackend calls ui-router template. don't know why wants so. i'm not asking this. want call mocked json service. this error forces me have following statement in each it() block: $httpbackend.whenget(/\.html$/).respond(''); there must neater way. specially if test has no use of $httpbackend in first place: it('should return list of searched users', function() { // use statement avoid error $http service making request application main page $httpbackend.whenget(/\.html$/).respond(''); var users = null; userservice.search('toto', 1, 10, 'asc', function(data) { users = data.content; }); $rootscope.$digest(); expect(users).toequal(restservice.allusers.content); });...

Java socket hanging when inside of java servlet -

so i've been trying figure out how send messages between arduino , java servlet (tomcat) , have been bumping problems. i'm using code in java servlet: serversocket server; //socket server port on listen int port = 9876; string message = ""; //create socket server object server = new serversocket(port); system.out.println("server socket created"); //keep listens indefinitely until receives 'exit' call or program terminates while(true){ system.out.println("waiting client request..."); //creating socket , waiting client connection socket socket = server.accept(); bufferedreader buff = new bufferedreader(new inputstreamreader (socket.getinputstream())); system.out.println("input stream established"); message = buff.readline(); system.out.println("message received: " + message); buff.close(); socket.close(); //termina...

c - Passing a pipe address through argv -

i'm trying set program 1 process establishes pipe, passed children either reading or writing. tried using argv parameter communicate address of pipe children use, i'm doing wrong , keep getting segmentation fault when try run it parent: void main(int argc, char *argv [ ]){ int temp,b,c,d,num; char *arg[1]={0}; int fd[2]; pipe(fd); b=1; c=1; d=1; sprintf(arg[0], "%d", fd); b=fork(); if (b==0){execv("pipew1", arg);} c=fork(); if (c==0){execv("pipew2", arg);} d=fork(); if (d==0){execv("piper", arg);} children void main(int argc, char *argv [ ]){ int *fd = atoi(argv[0]); //pipe(fd); close(fd[1]); well one, argv[0] name of executable, first "real" argument in argv[1] . might idea check if have appropriate number of arguments before accessing them in argv array. another thing in child process should initialize fd int not pointer int. third problem might in close(fd[1]) treating fd array when in fact scala...

c++ - Why isn't sizeof for a struct equal to the sum of sizeof of each member? -

why 'sizeof' operator return size larger structure total sizes of structure's members? this because of padding added satisfy alignment constraints. data structure alignment impacts both performance , correctness of programs: mis-aligned access might hard error (often sigbus ). mis-aligned access might soft error. either corrected in hardware, modest performance-degradation. or corrected emulation in software, severe performance-degradation. in addition, atomicity , other concurrency-guarantees might broken, leading subtle errors. here's example using typical settings x86 processor (all used 32 , 64 bit modes): struct x { short s; /* 2 bytes */ /* 2 padding bytes */ int i; /* 4 bytes */ char c; /* 1 byte */ /* 3 padding bytes */ }; struct y { int i; /* 4 bytes */ char c; /* 1 byte */ /* 1 padding byte */ short s; /* 2 bytes */ }; struct z { int i; /* 4 bytes */ sh...

ruby on rails - Capistrano fails to deploy due to a bundler error: "An error occurred while installing json...", but I am able to install that manually -

i rails , capistrano novice , whole day today i've ruined trying make stuff work. for have problem don't have idea how solve. syptom: cap staging deploy ... lots of stuff goes here , then... info [ba405350] running /usr/bin/env bundle install --path /home/ftpusers/my-server.com/rails/stage/shared/bundle --without development test --deployment --quiet rreimche@my-server.com debug [ba405350] command: cd /home/ftpusers/my-server.com/rails/stage/releases/20150414185146 && /usr/bin/env bundle install --path /home/ftpusers/my-server.com/rails/stage/shared/bundle --without development test --deployment --quiet debug [ba405350] error occurred while installing json (1.8.2), , bundler cannot continue. debug [ba405350] make sure `gem install json -v '1.8.2'` succeeds before bundling. (backtrace restricted imported tasks) cap aborted! sshkit::runner::executeerror: exception while executing rreimche@my-server.com: bundle exit status: 5 bundle stdout: error ...

javascript - Navigation within a phonegap application -

i playing around local storage on phonegap, trying create javascript login. current problem when run application, not go main menu if username , password correct. i believe problem window.location.href method. want navigate local page, not online one. van suggest way this? $(document).ready(function() { if (typeof(localstorage) === 'undefined' ) { alert('your browser not support html5 localstorage. try upgrading.'); } else { $("#return_form2").submit(function(){//load items getitems(); }); } }); var getitems = function() { var timelog, loglength, i; = 0; loglength = localstorage.length-1; //how many items in database starting 0 timelog = ''; // loop through each item in database (i = 0; <= loglength; i++) { ...

xcode - What's the difference between deep and shallow static analysis? -

Image
what's difference between shallow , deep static analysis? i'm using xcode @ moment, , noticed there's build setting distinguishes between two. i'm curious in general case, , i'm wondering if there's difference in how clang implements distinction. i tried google-foo , couldn't find answer. tried going through apple , clang docs see if explain didn't find anything. didn't miss obvious stone overturn in searching. (1) talk apple's evan cheng (compilation tech) gives indication (see pages 157/158): shallow - quick analysis deep - more thorough analysis recommendation: always analyze in deep mode part of qualifications (2) more details can find in source code of analyzeroptions there usermodekind variable: 00184 /// \brief describes kinds high-level analyzer mode. 00185 enum usermodekind { 00186 umk_notset = 0, 00187 /// perform shallow fast analyzes. 00188 umk_shallow = 1, 00189 /// perform deep a...

sorting - Keep observations only overlapped id in two data sets in R? -

i have 2 data sets. suppose data , data b , 2 data sets have id variables. in 2 data sets, want remove ids not overlapped. in other words, want keep ids exist in 2 data sets. it depends on whether want separately each data set or if merge both data sets 1 data set (or data frame). can try dplyr . library(dplyr) df1 <- data.frame(id = c("a", "b", "c"), var1 = c(1,2,3)) df2 <- data.frame(id = c("a", "c", "e"), var2 = c(4,5,6)) # matching ids in data frame 1 dplyr::semi_join(df1, df2, "id") > id var1 > 1 1 > 2 c 3 # matching ids in data frame 2 dplyr::semi_join(df2, df1, "id") > id var1 > 1 4 > 2 c 5 # merge column both data frames # matching id dplyr::inner_join(df1, df2, "id") > id var1 var2 > 1 1 4 > 2 c 3 5

asp.net - Web Api app that does not rely on IIS -

i need make single page web application web api doesn't rely on iis. i've read, should configure run in owin pipeline , remove reference system.web. is correct? relying on iis equals have references system.web? , having references system.web means relying on iis? the package want rid of microsoft.owin.host.systemweb . used enable owin server run web api on iis . you can self-host web api (no dependencies on iis) using this package: microsoft.aspnet.webapi.owinselfhost . summarizing web api must rely on these packages only: microsoft.aspnet.webapi.client microsoft.aspnet.webapi.core microsoft.aspnet.webapi.owin microsoft.aspnet.webapi.owinselfhost microsoft.owin owin microsoft.owin.hosting microsoft.owin.host.httplistener newtonsoft.json if want diagnostics can add: microsoft.owin.diagnostics i've published experiment on github tests, if you're interested.

c# - Pass Id to controller through ng-include -

how id view controller in ng-include? i have following view: @model nybroe.fightplan.sql.model.eventrecord @{ var eventid = model.id; } <div ng-app="tournamentapp"> <div ng-include src="'/apps/modules/fightcard/fightcard.html'"> <div ng-init="id = @eventid"></div> </div> </div> the ng-controller defined in fightcard.html template. and trying id parameter controller so: $scope.evid = $scope.id but turns undefined. i hope guys can me out! :) thank in advance. use object notation x.id , should work. id in isolated scope

java - DELETE Request with Payload or Form Data causes Bad Request -

i building restful web service java jersey 2.17. client it. developing extjs 5. my classes on service main.java public class main { public static final string base_uri = "http://localhost:8080/app/rest/"; public static httpserver startserver() { final resourceconfig rc = new resourceconfig(); rc.packages(true, "app"); rc.register(responsecorsfilter.class); return grizzlyhttpserverfactory.createhttpserver(uri.create(main.base_uri), rc); } public static void main(final string[] args) throws ioexception { final httpserver server = main.startserver(); system.out.println(string.format("jersey app started wadl available @ " + "%sapplication.wadl\nhit enter stop it...", main.base_uri)); system.in.read(); server.stop(); } } userri.java @path("/user") public class usersri { @delete @path("/{id}") @produces(...

.net - Awaiting AWS EC2 instance stop or start completion -

i send request through aws ec2 api stop (or start) instance , callback when machine in stopped state (or running ). i'm using aws sdk .net, , i've tried ec2client.stopinstancesasync method. returns request has posted, does not make asynchronous callback after state transition. what i'm aiming overall stop instance, change instancetype once machine stopped , start instance. appears way might make stop request, start own polling mechanism watch instance state transition stopped , continue instancetype change once has completed. i'd love think there's simpler, less chatty way of waiting transition complete. know of way notified when ec2 state transition has completed? it looks answer no. there appears no way notified when ec2 instance transition has completed. polling way accomplish this.

HTTP Content-Location for setting base URL -

according w3 , 14.14 content-location includes: content-location defines base uri entity i'm trying do: /foo/123 url document can served json or html i want serve html requests such html-linked resources(images, css, ect) subsequently required use base url other /foo however, browsers not respecting this. there way outside <base> ? you looking @ outdated spec (which way ietf spec, not w3c spec). please see http://greenbytes.de/tech/webdav/rfc7231.html#header.content-location

ios - Setting mask layer on UITableViewCell's subview overrides Auto Layout constraints -

i have uitableviewcell multiple subviews. 1 of subviews uilabel , cell's height dynamically sized based on amount of text in uilabel . works perfectly. i have subview in cell has constraints well. subview supposed have exact same height cell. works well. however, run problems when trying set mask layer on subview. mask layer works correctly, subview's height wrong , not same height cell. here mask layer code: uibezierpath *maskpath = [uibezierpath bezierpathwithroundedrect:self.mysubview.bounds byroundingcorners:(uirectcornertopleft | uirectcornertopright | uirectcornerbottomleft | uirectcornerbottomright) cornerradii:cgsizemake(10, 10)]; cashapelayer *masklayer = [cashapelayer layer]; masklayer.frame = self.mysubview.bounds; masklayer.path = maskpath.cgpath; self.mysubview.layer.mask = masklayer; i have been doing research , trying find way fix can both set mask l...

javascript - Why do web sites replace unicode chars with images? -

Image
recently installed noscript plugin in firefox control execution of javascript. noticed websites use fancy unicode charaters place holders images, replaced images once allow javascript. 1 example site github.com, see screenshot taken before enabled javascript. what's advantage of instead of place image directly in html or css? the sites using icon font (or more one). an icon font regular font file contains images. it's technique cut down on http requests , enable other features. now, how or why that's defeated noscript plugin, don't know. ( edit — it's apparently configurable noscript option, selected default. @font-face rules blocked, ostensibly security reasons.) in github sample, quick trip developer tools shows there's font called "octicons".

How to draw complex signals in simulink -

i want draw output qpsk modulator in simulink but scope block couldn't , message signal complex , scope couldn't draw it. how can plot such signal , block used output qpsk modulator. thanks you need separate real , imaginary parts using complex real-imag block , can plot signals on scope. if want them on same scope, can either change scope parameters have 2 inputs (similar subplot in matlab) or multiplex 2 signals mux block (to have 2 traces on same set of axes).

How can I split PHP up and reuse parts of it? -

i'm trying split line of php up, reason being don't need of code , can reuse parts of it. the main reason i'm doing because currency shows more digits currencies e.g. 1.2562 instead of 1.25, want use substr function on get's , able modify other get's. http://prntscr.com/6ttw8o symbol required, substr isn't, $converter required, end part of substr isn't can change, new currency required. $symbol[2] . substr(($converter->convert($defaultcurrency, $newcurrency) * 1), 0, 4) . " <b>" .$newcurrency. "</b>"; i've tried doing explode, i'm not entirely sure how have never had split before i'm little puzzled on how go it. once code has gone through checking current 1 set, want grab specified split code pieces , output it. put code in function this: function formatcurrency($symbol, $converter, $defaultcurrency, $newcurrency, $factor=1.0, $suffix="", $substrchars=0) { if($substrchar...

extract contact information from html with python -

here sample html <div class="yui3-u-5-6" id="browse-products"> <div id="kazbah-contact"> <span class="contact-info-title">contact 00nothing:</span> <a href="mailto:info@00nothing.com">info@00nothing.com</a> | 800-410-2074 | c/o score x score &nbsp;8118-d statesville rd , charlotte, nc 28269 </div> <div class="clearfix"></div> i want extract contact information here, email, phone, , address. how should python? thanks i use code extract information # _*_ coding:utf-8 _*_ import urllib2 import urllib import re bs4 import beautifulsoup import sys reload(sys) sys.setdefaultencoding('utf-8') def grabhref(url,localfile): html = urllib2.urlopen(url).read() html = unicode(html,'gb2312','ignore').encode('utf-8','ignore') soup = beautifulsoup(html) myfile = open(localfile,'wb')...

python - Capture frame with Opencv using BlackMagic card (intensity shuttle) -

i want process videos using blackmagic card. first step capturing frame don't know how it. tried use usual opencv code detect cam , display frames didn't work. know it? thank you this code: i'm recording there, it's ok, that's not main thing want created class able set properties of webcam, don't think right way bmcc from capture import capture import cv2 import os src import improcess # video recorder capture = cv2.videocapture(1) cap = capture(capture) fourcc = cv2.cv.cv_fourcc(*'msvc') # cv2.videowriter_fourcc() not exist video_writer = cv2.videowriter("c:\users\syllia\videos\output3.avi", fourcc, 30.0, (640, 480)) = 0 cap.set_brightness(25) while(capture.isopened()): # capture frame-by-frame ret, frame = cap.cap.read() gray = cv2.cvtcolor(frame, cv2.color_bgr2gray) if(i==120): cap.adjust_brightness(100, frame) if >= 240 , i<360: frame = improcess.binarize(170, frame) if i...

latex - How to convert PDF figures to EPS while keeping the original quality? -

i have 10 figures (graphs , schematics) in pdf format published in journal. the journal accepts figures in eps format correctly locate them when compiles latex file containing article. what best way convert pdf figures eps while maintaining quality? use tool such ghostscript or 1 of front-ends.

ruby on rails - undefined method 'article' - use data from other model -

there articles , comments. article has_many :comments comment belongs_to :article i want comments value_id equal value_id attribute in article comment belongs_to. class comment < activerecord::base belongs_to :article def self.value_comments where(value_id: self.article.value_id) end end i error: undefined method `article' #<class:0x007fd2a7e46d18> controller @value_comments = comment.value_comments.where(user_id: current_user.id).order("created_at desc") having read question again, understanding want find comments value_id matches value_id of associated article . your code correct - need few more parts work. need join comment table article table using joins . then, refer column in function using arel_table . so should end this: def self.value_comments joins(:article).where(self.arel_table[:value_id].eq article.arel_table[:value_id]) end you consider using sexy_scopes make easier access columns.

python - Pygame - maintain playing speed of game when keys are pressed -

i've got space invaders style game works okay when press key move player's ship, aliens slow down until key released. because there's more code being run when key pressed if there isn't (obviously). here's code that's run when press key keys = pygame.key.get_pressed() if keys[pygame.k_up]: objship.move(1) elif keys[pygame.k_right]: objship.move(2) elif keys[pygame.k_down]: objship.move(3) elif keys[pygame.k_left]: objship.move(4) which calls following code def move(self, d): self.direction = d if self.direction == 1: self.image = pygame.image.load("shipu.png").convert() if self.yco >= 0: self.yco -= 1 if self.xco >= 884: self.xco = 860 is there way of way of equalising speed of aliens doesn't involve putting wait command (or empty loop or whatever) else statement act make-work delay? i can put code here it's bit lengthy @ moment thought i'd try wit...

python - Conditionally replacing items in nested list based on values in dictionary -

right have nested list , dictionary: phrases = [['lionhearted', 'baby preach'], ['lionhearted baby', 'preach'], ['lionhearted', 'baby', 'preach']] artist_info = {u'baby': u'baby justin bieber', u'lionhearted': u'lionhearted porter robinson', u'preach': u'preach drake', u'baby preach': u:'baby preach pop singer'} basically, try replace values in phrases values artist_info if there match, other wise omit particular nested list. since there dictionary entry 'lionhearted' , 'baby' , 'baby preach' , 'preach' , output read this: phrases2 = [['lionhearted porter robinson','baby preach pop singer'] ['lionhearted porter robinson', 'baby justin bieber', 'preach drake']] is there way this? i've been @ hours. it's important 3 phrases result in order of "lionhearted baby preach". ...

How can I initialize multiple variables of different type in a C# for loop? -

this did i'am not sure if right int e = 1; int m = 500; ( e = 1; m = 500; e < 4; m >= 300; e++; m-100;) what trying is possible, have few pieces wrong. you can execute multiple statements in each "area" of for-loop structure, need separate them differently. valid loop this: for ( e = 1, m = 500; e < 4 && m >= 300; e++, m -= 100) { } notice in first , third blocks, use commas separate initialization , increment/decrement statements. second block has single conditional, used && , them together. i fixed "m" decrement statement modified m. subtraction operator non-destructive, wouldn't modify n original code.

inputstream - How to get live stream url from youtube live? -

i have link live stream youtube: https://manifest.googlevideo.com/api/manifest/hls_variant/upn/v377i0zgs9u/id/igtik_8ydoi.1/itag/0/gcr/vn/pmbypass/yes/expire/1429081762/sver/3/keepalive/yes/playlist_type/live/source/yt_live_broadcast/maudio/1/signature/648757b5224bb06a23dada58d1d514f8465b5b01.bea5b2ee61132ab1a1768e9852b12f6dd641322f/ip/192.168.1.1/key/yt5/ipbits/0/ratebypass/yes/fexp/3300112%2c3300133%2c3300137%2c3300161%2c3310698%2c3311881%2c900720%2c907263%2c916656%2c932627%2c932631%2c934954%2c938028%2c9405998%2c9407115%2c9408031%2c9408163%2c9408347%2c9408708%2c9408732%2c947233%2c947243%2c948124%2c948703%2c951703%2c952612%2c952626%2c952637%2c954815%2c957201%2c961404%2c961406/hfr/1/sparams/gcr%2chfr%2cid%2cip%2cipbits%2citag%2cmaudio%2cplaylist_type%2cpmbypass%2cratebypass%2csource%2cexpire/file/index.m3u8 i got link page source, when cannot restream ffmpeg/ffplay, error message: [tcp @ 0000000004442220] failed resolve hostname manifest.googlevideo.com: th e name not resolve sup...

ios - CGFloat and NSTimeInterval "Cannot assigned a value of type Float to a value of type Int" -

i keep getting cannot assigned value of type float value of type int" on touchvelocityx = xfloat / timefloat though i'm converting floats. let lasttouchx = locationoflasttouch.x let lasttouchy = locationoflasttouch.y let currenttouchx = touchlocation.x let currenttouchy = touchlocation.y let xdistance = currenttouchx - lasttouchx let ydistance = currenttouchy - lasttouchy let xfloat = float(xdistance) let yfloat = float(ydistance) let timesincelasttouch = nsdate().timeintervalsincedate(timeoflasttouch) let timefloat : float = float(timesincelasttouch) touchvelocityx = xfloat / timefloat touchvelocityy = yfloat / timesincelasttouch timeoflasttouch = nsdate() locationoflasttouch = touchlocation

android - Why is Azure SQL query hanging my app? -

i'm writing first app makes use of azure mobile services platform. have sql server configured , table showing on azure management portal. have manually added entries table ensure nothing wrong on server-side. my problems lie in fact app hangs when perform query on table. here's code: public mumanager(context con){ context = con; try { log.i("counter", "before mclient"); mclient = new mobileserviceclient("https://blah.com","apikey",context); log.i("counter", "after mclient"); mutable = mclient.gettable("table1",muitem.class); } catch (malformedurlexception e) { log.i("counter", "malformedurl"); e.printstacktrace(); } log.i("counter", "end of constructor"); } now, i'm not having issues above code, have no way of confirming client connecting azure mobile service. below code causes issue. ...

compilation - libpcap compiling as external library -

i'm making project requires libpcap library, downloaded library official website (libpcap-1.7.2.tar.gz) , want compile , project on unix server, not allowed install library there (school server) , cannot run gcc root. what command shall use? or possible? can't find info. (.. aim run binary on linux os (with root permissions) without need of installing lib.) i tried: gcc -wall test.c -lpcap -ilib/libpcap-1.7.2 but getting error: lib/libpcap-1.7.2/pcap.h:43:23: fatal error: pcap/pcap.h: no such file or directory #include <pcap/pcap.h> ^

video - How can I make Android's VideoView to read padded file? -

is possible android's videoview read mp4 file skip first 512 bytes? our client not want videos transferred/copied on different devices. did "obfuscate" mp4 file adding random 512 bytes @ beginning of file , renaming files different file extension. obviously, above approach not protect videos being pirated. he's fine enough protection "non-techies". currently, upon playing video, our android app extracts actual video content new temporary file skipping first 512 bytes. temp file 1 played videoview. the problem takes long time our videos more 100mb+ each. not acceptable solution. i think, if can make videoview skip first 512 bytes, we're set. possible? if not, better alternatives? disclaimer: i'm web developer of server app adds 512-byte padding. i'm not android developer. i'm posting question on behalf of android dev colleague. forgive me if our approach totally noob. feel free suggest better (and hopefully) easy ways. ...

jquery - Applying styles to html page using stylesheets included in xml -

i'm trying create theme switcher using user can change website themes clicking buttons. don't want use either local storage or cookies. i'm trying using xml. can attach stylesheet xml file , run html. forces style changes in xml file. html page doesn't change. how go it. please help. <html> <body> <h3>populate data xml file using jquery</h3> <input id="btngetdata" type="button" value="populate data xml file" /> <div id="updatepanel" style="padding:20px 10px"> <form action="datacheck.xml"> <input type="submit" value="blue"> </form> <form action="datacheck1.xml"> <input type="submit" value="red"> </form> <form action="datacheck2.xml"> <input type="submit" value="g...

javascript - D3js Geo unzoom element when zoom map -

i have d3js map built topojson.js. var projection = d3.geo.mercator(); everything works fine, looking effect cannot manage achieve. when, zooming map pins on scale down, if scale down, need recalculate coordinates , can't find formula so. zoom handler scale = d3.event.scale; if (scale >= 1) { main.attr("transform", "translate(" + d3.event.translate + ") scale(" + d3.event.scale + ")"); } else { main.attr("transform", "translate(" + d3.event.translate + ")scale(1)"); } //43x49 size initial pine size when scale = 1 var pins = main.select("#pins").selectall("g").select("image") .attr("width", function () { return 43 - (43 * (scale - 1)); }) .attr("height", function () { return 49 - (49 * (scale - 1)); }) .attr("x", function () { ...

c# - XSLT Conditional Template transformation -

i having 1 xml, want remove portion of based upon condition. xml follows : <?xml version="1.0" encoding="utf-8"?> <root xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"> <header> <messageid>0a9d3ba5-9025-4e24-a0de-2403a0c0919b</messageid> <messagedate>2015-04-10</messagedate> <ppmversion>6.0.0.0</ppmversion> <schemaversion>1.0</schemaversion> </header> <package xsi:type="ritter_sales_template" path="/package/product/launch_entity" businessid="010170" id="a13b6861-bb32-47fa-8ef4-f0ddcc0bc134"> <name>moto_pack</name> <category_id product_line_id="5">5</category_id> <effective_start_date>2015-02-23</effective_start_date> <available_start_date>2015-02-23</available_start_date> <element_guid>a13b6861-bb32-47fa...