Posts

Showing posts from September, 2010

ios - JSON format issue in PHP REST service receiving POST from AFNetworking 2.0 -

i have situation post json string ios code using afnetworking 2.0 code. client code looks this: nsurl *url = [nsurl urlwithstring:baseurlstring]; nsstring *jsonstring = [[nsstring alloc] initwithdata:jsonpayloadforproject encoding:nsutf8stringencoding]; nsdictionary *parameters = @{@"project": jsonstring}; afhttpsessionmanager *manager = [[afhttpsessionmanager alloc] initwithbaseurl:url]; manager.requestserializer = [afjsonrequestserializer serializer]; manager.responseserializer.acceptablecontenttypes = [nsset setwithobject:@"text/html"]; [manager post:@"service.php" parameters:parameters success:^(nsurlsessiondatatask *task, id responseobject) { nslog(@"%@", [responseobject description]); } failure:^(nsurlsessiondatatask *task, nserror *error) { uialertview *alertview = [[uialertview alloc] initwithtitle:@"post json project error" message:[error localizedde

Template with Inheritance C++ -

using inheritance , templates, ive sort name array of employee information. got 3 classes, payroll, simplevector , sortingvector. payroll contains user info attributes, simplevector creates dynamic array of type payroll store user info. sortingvector class in charge of sorting array names. keep getting many different errors whenever tried fix previous error. posting each class: payroll class #pragma once #include<iostream> #include<string> #include<vector> using namespace std; class payroll { private: int empnumber; string name; double hours; double payrate; double grosspay; int *aptr; int arraysize; public: payroll(int size); payroll(); payroll(const payroll & apayroll); ~payroll(); //mutators void setvector(payroll &apayroll); void setempnumber(int empnumber); void setname(string name); void sethours(double hours); void setpayrate(double payrate); void setgr

angularjs - angular ng-repeat prefilter in javascript -

i have following angular js filter ng-repeat on tr element. how accomplish of in javascript? possible in 1 custom filter? note: showrow function returns bool, search string string ng-repeat="lob in filtered = (lobs | filter : showrow | filter : searchstring | orderby : 'name':true ) you can use $filter service, or $scope.$eval: $filter('orderby')( $filter('filter')( $filter('filter')($scope.lobs, $scope.showrow), $scope.searchstring), 'name', true); $scope.$eval("lobs | filter : showrow | filter : searchstring | orderby : 'name':true"); not tested, should close enough work. and yes, using first way, create own filter that.

c# - Memory efficient data structure for high performance -

i have need circular buffer (or other data structure), on can "toarray" or similar call current state of buffer , use whilst buffer carries on possibly overwriting values held. the reason use case returned data passed worker thread process , idea ensure little data overwritten possible in between calls. choice of circular data structure ostensibly reduce memory usage of buffer fixed value. i built data structure below, until yesterday sufficient needs. relevant calls takesnapshot, takeall , takeweakarraysnapshot variations on same theme. the call made quite when 1000 samples of reference types available. all calls result in out of memory exception @ point. exception takeweakarraysnapshot reverts null midway through using array (something guess fact gc handle weak?) is there more suitable memory efficient data structure use or doing wrong? changing gc handle type normal help. possible create output type wraps references (like attempted weakreference) reclaimed ga

c++ - StgOpenStorageEx returns STG_E_FILEALREADYEXISTS -

i struggling attempting find out why stgopenstorageex returns stg_e_filealreadyexists on compound document when opening readonly. didn't make sense. file there , wasn't trying create anything. open up. couldn't find answer online thought share answer found here. stgopenstorageex returns stg_e_filealreadyexists when file not compound document. in situation having problem encrypting , decrypting content compound document creating invalid. wasn't compound document @ all.

ruby on rails - Array function not working on a JavaScript array created from element text -

so have following element, when clicked on calls javascript function response(tag). pass element "rops" function. <li><div class="rops"><span class="rops-text"> tag2 </span></div></li> <li><div class="rops"><span class="rops-text"> tag2 </span></div></li> so when click on 1 of these elements adds them array. array functions work array, , created array. see following working case , not working case: they work if create array self: working case: var checka = []; checka[0] = "tag1"; checka[1] = "tag2"; alert(checka.indexof("tag2")); //gives me correct answer. not-working: array created this: response(tag) { myarray[i] = string($(tag).text()); //at current point has ["tag1", "tag2"] //but if same alert(myarray.indexof("tag2")); //gives me -1 (similar other array function). so in short

asp.net web api2 - Web Api Routing with 404 response IHttpActionResult -

i trying below routes work having issue. route api/user/name works fine; result "whats up". however, route api/user/register results in 404. private void configurewebapi(httpconfiguration config) { config.maphttpattributeroutes(); var jsonformatter = config.formatters.oftype<jsonmediatypeformatter>().first(); jsonformatter.serializersettings.contractresolver = new camelcasepropertynamescontractresolver(); } the controller: using system.web.http; using angular.data.iservices; using angular.data.modals; namespace angular.api.controllers { [routeprefix("api/user")] public class usercontroller : apicontroller { private iuserservice _userservice; [route("name")] [httpget] public string name() { return "whats up"; } [route("register")] public ihttpactionresult register(user usr, string password) { _

user interface - How to design android UI depending on different android OS versions -

i have 2 different android tablets have different os versions. one kitkat(4.4.2) sdk 19 , other jelly beans(4.1.6) sdk 16. my question how design ui in manner fits both os. designed ui based on sdk 19 kitkat. company says distribute app on jelly beans(sdk 16). when run app same code on lower version(sdk 16), see images not fit on screen. see images stretched out. way designed didn't provide ui images ldpi, mdpi, hdpi, , on used hdpi since assume jelly beans tablet(galaxy tab 2 10.1) has same resolution(1280x 800) galaxy tab 4 10.1) has. isn't there ways can write designer code(xml) able fit ui both versions? or should write separate ui layout fit both versions? according research android developer site, recommended should provide different size of images(ldpi,mdpi, hdpi, , on). since not differentiating size of tablet(10 inch screen), assume using 1 size feature enough. would please me on this? thanks,

python - Printing Only certain Rows from a CSV File in GNUPlott -

i have specific question using csv files , gnuplots. what trying programmatically in python, print set of graphs gnuplots. the specific problem trying resolve have csv files set of parsed data, processed servers, multiple columns. in first column there server names, other columns not need care right now, time columns , data columns. what trying each specific server (let's call them a, b, , c) take corresponding data time , value - , plot these onto gnuplot each line separate server. let's data looks this server time data a****** t1*** d1 a****** t2*** d2 a****** t3*** d3 b****** t1*** d1 b****** t2*** d2 b****** t3*** d3 c****** t1*** d1 c****** t2*** d2 c****** t3*** d3 --this simplified accurate enough

C/C++ app to view Wireshark Reset packets -

Image
is possible view, in real time reset (rst) packets sent out remote (source) ip local (destination) ip on machine in source code running? we looking obtain remote ip address rst packet has been sent local machine. this required in wireshark: have been looking @ netstat , getipstatistics. neither of these work. any ideas(windows based c/c++ code)? yes, possible in real time want. if wireshark able it, can it. you may want take @ libpcap, portable c library packet capture. information libpcap can obtained it's home page @ http://www.tcpdump.org/ . need additional processing captured packets: see if packet long enough have required data (this check needs done layer-by-layer in separate parts) see if ethernet source address address of ethernet adapter in computer (so it's sent packet, not received packet) see if it's ip packet using ethertype header field see if ip source address of packet address of interface in computer see if it's tcp packet

How to fetch email headers with Office 365 Mail REST APIs? -

i can't seem find way fetch raw rfc 2822 email headers message resource https://msdn.microsoft.com/office/office365/api/complex-types-for-mail-contacts-calendar#restapiresourcesmessage all standard headers to, from, subject available. how list of headers[] other standard once such "received", "delivered-to", etc.. feature not yet supported? igor - office 365 rest api doesn't support returning rfc 2822 email headers. on our roadmap add, don't have firm timeline yet.

jquery - Cycle 2 "Next" Button Not Working -

i attempting create website cycles through list of pictures. working correctly, "next" , "previous" buttons seem hiding underneath <div> contains photos. why isn't z-index correcting issue? (see 2 marked lines) <?php error_reporting( e_all ); ?> <!doctype html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script src="http://malsup.github.com/jquery.cycle2.js"></script> <script src="http://malsup.github.io/jquery.cycle2.center.js"></script> <meta http-equiv="content-type" content="text/html; charset=utf-8" > <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style type="text/css"> body{ background-color: black; } </style> </head> <body> <div class="cycle-slideshow" data-cycle-lo

javascript - updating multiple charts with one focus chart using Angular nvd3 directives -

i trying create dashboard controlled 1 focus chart. for example, if check out plunker here: http://plnkr.co/edit/waxnb57oka9vkrzzntrm?p=preview see "nvd3-line-with-focus-chart" on top , "nvd3-cumulative-line-chart" on bottom. <nvd3-line-with-focus-chart data="exampledata" id="exampleid" width="400" height="300" height2="50" x="xfunction()" y="yfunction()" forcey="[0]" interactive="true" tooltipcontent="tooltipcontentfunction()"> <svg></svg> </nvd3-line-with-focus-chart> <nvd3-cumulative-line-chart data="exampledata" id="examplechart2" showxaxis="true" showyaxis="true" tooltips="true"

mercurial - Bitbucket: Enforce merge-only by pull request on branch workflow -

our team uses bitbucket hosting our mercurial repository. have single repo cloned our dev vm's upon provisioning them. use typical feature branch -> pull request -> review -> merge feature default pr workflow. what we'd like: able restrict things such 1 cannot push default branch command-line (to avoid accidental commits branch). ie - want enforce way default modified via pull request. note forking isn't option due vm setup (we'd have add complexity vm provisioning fork, , set on provisioned vm, , means when accidentally pushes default they're messing fork). branch restrictions seem promising, , while can set nobody can push via command line, means single named user or group can actual merge of pr (which don't want, ideally on team can merge, through bitbucket pr). is possible? suggestions? so ended solving mercurial hooks. created following file, named prevent_default_push.py , put in .hg directory of clone. # branche

How can I access files on localhost from another laptop in the same network using xampp in ubuntu? -

i have installed xampp on laptop , have ubuntu 12.04. tried access files on laptop android phone entering local-ip-address/filename url. shows error 404 page not exist. note used local ip address because both in same network. used public ip , still did not work! can tell me exact procedure access files using xampp server in ubuntu?

CakePHP 3.x: Spread $conn to associated Tables during Eager Load -

well have several databases same tables. being used in way design, separate continent information. need change dynamically connection depends on user server requested. initially using this: $conn = connectionmanager::get($server); $this->connection($conn); but, of course, change not spread associated tables. how accomplish this? here soluction , alternative approach owner of cakephp https://github.com/cakephp/cakephp/issues/6126

node.js - How do I get the instance memory in use for a Node-Express App running in CloudFoundry? -

i building app node-express backend , deploying cloudfoundry. know can total instance memory vcap_application var , able os memory using 'os' module. seems can application memory using 'util' module, none of parameters of returned object process.memoryusage() seem i'm looking for. doing following that: // modules i've tried var express = require('express'), app = express(), os = require("os"), util = require("util"); // memory statistics can -> cannot instance memory in use var memlimit = json.parse(process.env.vcap_application)['limits']['mem']; totalmem = os.totalmem(), freemem = os.freemem(), memused = util.inspect(process.memoryusage()).split(" "), heapused = memused[6], heaptotal = memused[4].substr(0,memused[4].length-1); rss = memused[2].substr(0,memused[2].length-1); does know how can use heap/rss values or other modules looking for? i can think

python - Scrapy: Attempts to extract data from selector list not right -

i trying scrape football fixtures website , spider not quite right either same fixture repeated selectors or hometeam , awayteam variables huge arrays contain home sides or away sides respectively. either way should reflect home vs away format. this current attempt: class fixturespider(crawlspider): name = "fixturesspider" allowed_domains = ["www.bbc.co.uk"] start_urls = [ "http://www.bbc.co.uk/sport/football/premier-league/fixtures" ] def parse(self, response): sel in response.xpath('//table[@class="table-stats"]/tbody/tr[@class="preview"]'): item = fixture() item['kickoff'] = str(sel.xpath("//table[@class='table-stats']/tbody/tr[@class='preview']/td[3]/text()").extract()[0].strip()) item['hometeam'] = str(sel.xpath("//table[@class='table-stats']/tbody/tr/td[2]/p/span/a/text()").extract()[0].strip(

IIS8 and URL redirect using URL Rewrite Module -

i have 2 sites running on server 2012 r2 web server: firstsite, port 80 secondsite, port 1234 right now, users have type in host name, port number, , sub folder in order view 'second site' http://webserver:1234/subfolder . i'm trying simplify url users can type in url site.mydomain.com , have (permanently) redirected site.mydomain.com:1234/subfolder . i've tried applying following rule on secondsite: <rewrite> <rules> <rule name="redirect" stopprocessing="true"> <match url=".*" /> <action type="redirect" url="http://site.mydomain.com:1234/subfolder" /> </rule> </rules> </rewrite> but doesn't seem anything. a cname record has been configured in dns site.mydomain.com resolve http://webserver . i need getting redirection 'secondsite' @ port 1234. i assume first site hosted on ii

c# - Entity Framework: Two foreign keys connected by one collection -

i know there related topic: two foreign keys same table , can't find there fix problem. pretty new ef. i have following model classes (code-first): public class member { [key] public int memberid { get; set; } public string name {get; set;} public string surname { get; set; } public virtual icollection<marriage> marriages { get; set; } } public class marriage { [key] public int marriageid { get; set; } public string marriageplace { get; set; } public datetime marriagedate { get; set; } [foreignkey("husband")] public int husbandid { get; set; } [foreignkey("wife")] public int wifeid { get; set; } public virtual member husband { get; set; } public virtual member wife { get; set; } } my problem both husband , wife should connected same marriage collection in member class. did that: modelbuilder.entity<marriage>() .hasrequired<member>(m => m.husband)

php - Google o auth login SSL error -

since today google oauth login php application stopped working. i following error: stream_socket_client(): peer certificate cn= *.storage.googleapis.com' did not match expected cn= www.googleapis.com' stream_socket_client(): failed enable crypto stream_socket_client(): unable connect ssl://www.googleapis.com:443 (unknown error) i'm using endpoint: https://www.googleapis.com/oauth2/v1/userinfo . i had similar issue cakephp using http socket. likely happening if using framework, or http socket library. the fix in cakephp, disable ssl_verify_host according documentation: "set false if wish ignore hostname match errors when validating certificates." http://book.cakephp.org/2.0/en/core-utility-libraries/httpsocket.html e.g. $this->httpsocket = new httpsocket(array( 'ssl_verify_host' => false )); this solved issue me. suspect in other frameworks, there similar option, , should solve it!

css - How to make header align with bootstrap columns? -

Image
how can make layouts/header align col-md-9 & col-md-3 "p" in personal control center aligned panel below , downward arrow aligned right edge of sidebar? i able via padding in first picture, i'd align regardless of screen size. can see decreased width of browser becomes less aligned. *in last case downward arrow should align right edge of panel. application.html.erb <!doctype html> <html> <head> <title>personal control center</title> <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %> <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %> <%= csrf_meta_tags %> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- tells app mobile responsive --> </head> <body> <%= render 'layouts/header' %> <%

object - Python purpose of % attribute prefix -

i've seen python objects attributes %values . can't access such attributes, raise syntaxerror . seem require setattr created without syntaxerror : class a(object): pass = a() setattr(a, "%values", 42) a.%values # results in syntaxerror: invalid syntax class b(object): def __init__(self): self.%values = 42 # results in syntaxerror: invalid syntax does % have purpose or meaning here? why can %values set using setattr , otherwise raises syntaxerror ? does % have purpose or meaning here? most precisely prevent accessing attributes using regular dot notation, because, have seen, can't. discourages using them, making them in way "private" whatever application using them. there better ways achieve this, though. call smell if saw code this. why can %values set using setattr, otherwise raises syntaxerror? attributes stored in dictionary, , dictionary keys can anything. don't have follow same rules python

c++ - STL Scope of containers -

i wanted know of scope of stl containers. for eg. //have function creates unordered_map , passes set_map fill values in it. int foo() { unorderd_map<char,int>mymap; set_map(mymap); } set_map (unorderd_map<char,int> mmap){ //...setting values of map } in case scope of mymap in foo limited function foo() or mymap passed reference set_map() , whatever changes done in set_map reflected mymap in foo() ? i wanted know how still containers passed function parameters, i.e. passed value or passed reference. thank you mymap passed as copy set_map , set_map sees own copy of map, not original mymap . changes made in set_map applied copy, , not affect original mymap . to pass map reference need declare explicitly: set_map (unordered_map<char,int>& mmap) // ^ passed reference now. now changes in set_map alter original object passed parameter.

Can I use OpenEars (or other) to listen to & analyze speech from the Apple Watch microphone? -

is possible use openears (or other package) access speech apple watch's microphone? i wish build app able listen speech, using watch's microphone, , spots specific keywords. as of watchos 2.1, , ios 9, have been able propose, in 2 different ways: option 1 - record wav file , upload asr server recorded , saved wav file apple watch. after uploaded file paid speech recognition provider , worked fine! here code record, replace ui updating lines of code (and debug ones) own: //record audio sample var saveurl: nsurl? //this var initialized in awakewithcontext method// func recordaudio(){ let duration = nstimeinterval(5) let recordoptions = [wkaudiorecordercontrolleroptionsmaximumdurationkey : duration] // print("recording to: "+(saveurl?.description)!) //construct audio file url let filemanager = nsfilemanager.defaultmanager() let container = filemanager.containerurlforsecurityapplicationgrou

ocaml - OCamlfind local library unbound module -

i trying use ocamlfind install library . using ocamlmakefile. here makefile: ocamlmakefile = ocamlmakefile result = owebl sources = src/utils.ml src/verb.ml src/request.ml src/template.ml src/response.ml src/rule.ml src/handler.ml src/server.ml packs = unix str all: native-code-library byte-code-library install: libinstall uninstall: libuninstall include $(ocamlmakefile) so library collection of modules want distribute. basic usage of library (main.ml): open response open rule open verb open server let handler = handler.create (staticrouterule.create "/" [get]) (fileresponse.create ~static_file:(fileresponse.staticfile "/index.html") ()) let server = server.create "0.0.0.0" 8080 [handler];; server#serve i compile library running "make". generates 3 files: "owebl.a, owebl.cma, owebl.cmxa". install library using ocamlfind: ocamlfind install owebl meta owebl.a owebl.cma owebl.

java - What is difference between these two kinds of image loading code? -

these 2 kinds of code below used loading image file: a) file sourceimage = new file("filename"); image image = imageio.read(sourceimage); b) toolkit tk = toolkit.getdeafaulttoolkit(); img=tk.getimage("filename"); what's real difference between these 2 codes ? imageio.read(file) takes file , newer toolkit.getimage(string) takes filename (and has been part of language longer). also, first 1 provides additional functionality (that is, imageio.read(file) javadoc says in part) the current cache settings getusecache , getcachedirectory used control caching in imageinputstream created. note there no read method takes filename string; use method instead after creating file filename.

osx - Use combined titlebar + toolbar while preserving title visibility -

Image
the system preferences app feature combined title bar , toolbar vertically centered buttons , title. trying mimic in app. have been able combine title bar , toolbar using interface builder (on nswindow check title bar , unified title , toolbar), not center content vertically. discovered via this question can set window's titlevisibility nswindowtitlehidden vertically center stoplight buttons. unfortunately of course hides title. how can 1 vertically center content in unified titlebar/toolbar , show window's title system preferences - either in ib or programmatically? i ended setting titlevisibility nswindowtitlehidden , manually created nsview contains nstextfield mimics standard title appearance, providing window's addtitlebaraccessoryviewcontroller method. still find better solution use default title appearance, if possible.

ruby - pod install: command not found when called from bash script -

i'm improving continuos integration of project. , decided take step , start using cocoapods. rvm installation legacy , indeed have lot of troubles installing ruby 2.2.0. thing that, when test build script using terminal works fine, when try run them without opening terminal window (called applescript, jenkins or ruby script). command not found. already tried adding path .rvm/scripts path variable in both .bashrc , .bash_profile have try reconnect server after installed cocoapods? doesn't see new vars till disconnected , reconnected. also make suer vars see through terminal available jenkins user. can check through slave "script console" if still don't work, try set path in "execute shell", before run pod install. this how works me: echo "running pod install" cd ${workspace} export lang=en_us.utf-8 pod install

java - How to reference an xml file from resources? Eclipse -

Image
i'm parsing in xml file using sax , need add resource instead of hard coding file path. i set file path y using string this: private static final string game_file = "game.xml"; its been suggested use getresourceasstream i'm not sure how apply solution. does how reference file resources instead within project? this how reference xml file adding root of project, bad practice: public class parser extends defaulthandler{ private static final string game_file = "game.xml"; //you should have boolean switch each xml element, not attribute boolean location = false; boolean description = false; boolean item = false; boolean gamecharacter = false; boolean searchalgorithm = false; //read in xml file game.xml , use current object sax event handler public void parse() throws parserconfigurationexception, saxexception, ioexception{ xmlreader xmlreader = null; saxparserfactory spfactory = saxparserfact

c# - Why are extensions not available in @helper? -

i created view extension this: namespace myproject { public static class pageextensions { public static htmlstring myext(this webviewpage page) { so can type in razor view: @this.myext() please note views include namespace declared via web.config: <system.web.webpages.razor> <pages pagebasetype="system.web.mvc.webviewpage"> <namespaces> <add namespace="myproject" /> everything good. want write @helper function , use extension there: @helper myhelper() { var page = (webviewpage) currentpage; <div> @page.myext() </div> } but extension not available there. error is: compiler error message: cs1061: 'system.web.mvc.webviewpage' not contain definition 'myext' , no extension method 'myext' accepting first argument of type 'system.web.mvc.webviewpage' found (are missing using directive or assembly reference?) what

Why does manually programmed deviance and DIC calculated deviance differ in JAGS? -

Image
i fitting set of 16 models in jags. have function in jags calculates log of probability of each value of outcome variable , and function takes -2 * sum of log probabilities. i.e., have custom formula calculate deviance each model. wanted check definition of deviance same jags using. after running 5000 burnin , 5000 iterations, obtained following results: basically, models, deviance close not same, , other models (e.g., 7, 13, 16) vastly different. why deviance calculated using custom formula different obtained using automatic approach based on dic? after bit of messing around, think following case. first, dic deviance obtained using discrete set of samples main parameter estimates. thus, estimates differ between runs due inherent random aspects of mcmc estimation. assuming chain length long (several thousand) , burnin adequate , differences between main samples , dic samples should small if model converging , reasonably efficient. thus, big differences co-occur m

recursion - Python recursive zeno() function -

in python, need define recursive function takes number returns sum 1/2^0 + 1/2^1 + 1/2^2 + 1/2^3 + ... + 1/2^n. need accomplish without using or while loop. have tried. def zeno(n): if n==0: return 1/1 else: return float(1/1 + 1/2**zeno(n-1)) def zeno(n): if n==0: return 1 #return 1 base n==0 case, x ^ 0 1 else: return 0.5**n + zeno(n-1) #calculate (1/2) ^ n + (1/2)^(n-1) recursively

swift - '[AnyObject]?' does not have a member named 'Generator' -

i looping through contacted physics bodies game, getting strange error anyobject. var bodies = island1.island.physicsbody?.allcontactedbodies() body : anyobject? in bodies { } bodies here optional. you've gotta unwrap before can iterate it. if let bodies = island1.island.physicsbody?.allcontactedbodies() { body in bodies { // etc } } else { println("there no bodies") }

java - How to use addView to add CustomView? -

i use below code in main.java, work! framelayout view = (framelayout) findviewbyid(r.id.frame); textview product = new textview(this); product.settext("product"); view.addview(product); but want add customview, not work framelayout view = (framelayout) findviewbyid(r.id.frame); customview v = new customview(this); //can't create new object v.setimageresource(r.mipmap.scale); view.addview(v); how can add customview addview? thanks the customview class public customview(context context, attributeset attrs) { this(context, attrs, 0); } public customview(context context) { this(context, null); } public customview(context context, attributeset attrs, int defstyle) { super(context, attrs, defstyle); obtainstyledattributes(attrs); init(); } attrs.xml <resources> <declare-styleable name="customview"> <attr name="src" format="reference" /> <attr name="ed

io - In perl6, how do you read a file in paragraph mode? -

data.txt: hello world goodbye mars goodbye perl6 hello perl5 myprog.py: my $fname = 'data.txt'; $infile = open($fname, :r, nl => "\n\n"); $infile.lines(nl => "\n\n") -> $para { $para; '-' x 10; } actual output: hello world ---------- goodbye mars ---------- ---------- goodbye perl6 ---------- perl5 ---------- desired output: hello world goodbye mars ----------- goodbye perl6 perl5 ----------- ... $ perl6 -v perl6 version 2015.03-21-gcfa4974 built on moarvm version 2015.03 this appears bug in rakudo/moarvm, going fact moarvm expects single grapheme separator instead of arbitrary string (cf syncfile.c:38 , syncfile.c:119 , syncfile.c:91 , shows last character of separator string used instead of whole string). as quick workaround (but beware reads entire file memory), use $fname.io.slurp.split("\n\n") instead of $infile.lines() . you should file bug report or ask in #perl6 on freenod

filtering - Time-varying band-pass filter in Python -

i trying solve problem similar 1 discussed in this post i have broadband signal, contains component time-varying frequency. need monitor phase of component on time. able track frequency shifts (a brute force method of) peak tracking in spectrogram. need "clean up" signal around time varying peak extract hilbert phase (or, alternatively, need method of tracking phase not involve hilbert transform). to summarize previous post: varying coefficients of fir/iir filter in time causes bad things happen (it not shift passband, confuses filter state in ways cause surprising transients). however, there some way adjust filter coefficients in time (probably jointly modifying filter coefficients , filter state in intelligent way). beyond expertise, i'd open solutions. there 2 classes of solutions seem plausible: 1 use resonator filter (basically damped harmonic oscillator driven signal) time-varying frequency. model simple enough avoid surprising filter transients. try --

algorithm - Given a matrix of ints, find the longest consecutive snake of incrementing by 1 numbers -

this question has answer here: find maximum length of path in grid 4 answers basically, have this: 0 9 5 3' 4 1 5' 4' 5 7' 6' 9 2 8' 5 10 in case, longest snake 3 -> 4 -> 5 -> 6 -> 7 -> 8. put ' behind numbers in show visually. you can go both horizontally , vertically. matrix can n x m, there isn't limit number of rows , columns. what optimal way figure out? i've thought starting @ position n/2 , m/2, recursively doing breadth-first search , keeping track of max interval can find. i'm not sure how best tackle it. you create graph nodes matrix positions , vertices pointing number n n+1 neighbour. once graph built, problem amounts finding 1 of longest paths in graph.

Pointer ownership semantics, Attaching debug info and "unsigned" usage in LLVM -

i've started using llvm ir generation apis project. documentation , llc tool pretty helpful, haven't been able find answer following - question-1 - pointer ownership semantics all code creates llvm ir instructions using apis seems "new" instructions instead of creating them stack variables. auto x = new alloca(...) vs. alloca(...) x; i wondering ownership semantics pointers created? have call delete on these instruction objects. code i've seen calls "delete engine;". i guessing memory owned module object , when module destroyed, memory occupied these instructions destroyed. looking @ of code, seems these instruction objects created using "placement new" ... understanding correct? question-2 - why doe llvm ir apis take "unsigned" data-type args. (e.g. unsigned addresspace 1 common argument. why not sized type uint32_t ?) question-3 - how attach debug information ir instruction? pointers llvm apis attach debug info

raphael - working with Javascript object model -

what trying achieve creating objects following better pattern. using raphael.js library creation of graphical shapes. problem @ line: x: "" + this.canvas_x + this.paper["width"]/2 - self.width/4, the error getting : uncaught typeerror: cannot read property 'width' of undefined i figured out error @ this.paper["width"]/2 . new using javascript , not able understand error doing var graphics={ create_canvas: function(){ $("#canvasdiv").append("<div id='id1' width='80px' height='50px'></div>"); }, canvas_x:get_left_top("canvasdiv")[0], canvas_y:get_left_top("canvasdiv")[1], canvas_width:function(){return $("#canvasdiv").width()}, canvas_height:function(){return $("#canvasdiv").height()}, paper:{ width:900, height:700, create: function(