Posts

Showing posts from May, 2014

javascript - need advice on dust temmplate -

i new dust (linkedin), working on first little template. after writing obvious (but long) way thought of way optimize using inline partial. long version looks this: {#parcours}<tr class="pcsel_pc" id="{id}"> <td class="pcsel_exp_btn"><a href="#" class="list{?exp}hide{:else}exp{/exp}btn"> <span class="glyphicon glyphicon-{?exp}minus{:else}plus{/exp}"></span></a></td> <td class="pcsel_col">{name}</td><td class="pcsel_col pcsel_num">{count}</td> </tr> {?exp} {#variants} <tr class="pcsel_var{?sel} pcsel_sel{/sel}" id="{id}" > <td class="pcsel_col">&nbsp;</td><td class="pcsel_var pcsel_col">{name}</td> <td class="pcsel_col pcsel_num">{count}</td> </tr> {/variants} {:else} {#variants} <tr class="pcsel_var pcsel_hide" id=&

c++ - Passing pointer to any member function as class template argument -

template<typename t, typename m, m method> class proxyobject { public: template<typename... args> void invoke (t& object, _in_ args&&... a) { (void)(object.*method)(std::forward<args>(a)...); } }; class object { public: int mymethod (int val) { wcout << l"hello!" << endl; return val; } }; int wmain () { object myobj; proxyobject<object, decltype(&object::mymethod), &object::mymethod> obj; obj.invoke(myobj, 10); return 0; } the decltype(&object::mymethod) seems redundant in definition of obj . there way make proxyobject automatically infer type of pointer-to-member-function being passed, can define obj follows: proxyobject<object, &object::mymethod> obj; i think it's impossible class template, because have specify member function type explicitly. template function lot argument deduction: template<typenam

xml - What does it mean apply-templates select='*'? -

forgive me learned xsl , , have trouble understand apply-templates well. in understanding. apply-templates find nodes match select . , search in current xsl document if there template defined specified select nodes. apply style these nodes. for example: <catalog> <cd> <title>empire burlesque</title> <artist>bob dylan</artist> <country>usa</country> <company>columbia</company> <price>10.90</price> <year>1985</year> </cd> <cd> <title>hide heart</title> <artist>bonnie tyler</artist> <country>uk</country> <company>cbs records</company> <price>9.90</price> <year>1988</year> </cd> <cd> <title>greatest hits</title> <artist>dolly parton</artist>

ruby on rails - Attribute not updating on update_attribute even after reload -

i'm doing rails tutorial on : https://www.railstutorial.org/book/account_activation_password_reset i have piece of code supossed create reset_token , save hash , time created database. def create_reset_digest self.reset_token = user.new_token update_attribute(:reset_digest, user.digest(reset_token)) value = update_attribute(:reset_sent_at, time.zone.now) print value end starting debug before update_attribute on reset_sent_at: self.reset_sent_at == 2000-01-01 12:36:53 utc after it: self.reset_sent_at == thu, 22 oct 2015 12:52:47 utc +00:00 but doing self.reload makes: self.reset_sent_at == 2000-01-01 12:36:53 utc so maybe update_attribute not saving on db? but print value returns true, indicating successful save. i'm not sure going on. found out happened, on schema had t.time "reset_sent_at" instead of t.datetime. weird update_attribute returned true.

c# - How can I observe changes in the AllowedFileTypes of FileSavePickerUI? -

Image
when register app file-save picker, filesavepickeractivatedeventargs in app.xaml.cs : protected override void onfilesavepickeractivated(filesavepickeractivatedeventargs e) { var filter = e.filesavepickerui.allowedfiletypes; // ireadonlylist<string> } when user selects different set of file-types: how notification collection changed? filesavepickerui.allowedfiletypes not observable. there trick? @methodman , in windows store apps can register app filesavepicker, allows show option when other apps want "save as...". ui contains app outside control, drop down "save type" (look @ photo above). drop down contains values filesavepickerui.allowedfiletypes . when user changes selection, need notification. except... can't. can't seem find way observe change. looks there's bug in windows 10 of (oct 2015) filenamechanged event not fire when type changed. seems work in windows 8. the filenamechanged event documented being rai

assembly - How to spot MARIE errors? -

after assembling current file in marie. if i'm prompted error, how can spot line error directed at? also i'm working on assignment requires me input length , width user , output perimeter or area. far here have : org 100 input length //take input length store length //store length in location length1 output length //show value of length input width //take input width store width //store location width output width //show input width load width subt width 1 //(subtract 1 w until 0) store width load a add length // add l area store a skipcond 00d //(skip when width hits 0) jump 007 // output area halt a, dec 0 b, dec 0 c, dec 0 end i wrote in java make more clear understand //find either perimeter or area of rectangle import java.util.scanner; public class perimeterorarea{ public static void main(string[] args){ int length, width; int perimeter, area; string ch; char character; scanner in = new scan

Is it possible to extract in c++ the container template class? -

i wondering if possible detect template class container type, , redefine parameters. example : typedef std::vector<int> vint; typedef typeget<vint>::change_param<double> vdouble; where vdouble std::vector<double> ? adding on @kerrek sb's answer, here generic approach: template<typename...> struct rebinder; template<template<typename...> class container, typename ... args> struct rebinder<container<args...>>{ template<typename ... uargs> using rebind = container<uargs...>; }; which work container under sun.

c# - The right way to add indexes for Entity Framework code-first applications? -

i've been researching quite while on how add indexes on columns, when work entity framework code-first. as see it, there 3 methods: add them in actual migrations (after ef 4.2) use new indexattribute in ef 6.1 add indexes columns directly i not fond of either method as: 1: seems quite risky. might want reset migrations , make "initial setup" again. indexes might deleted. in addition think it's little transparent , hidden quite well. 2: seems quite new , limited documentation. not sure how works? 3: dangerous if re-create database. so question is: how add indexes in entity framework code-first? manually adding code in migrations ok wouldn't recommend it. still need update model anyway migrations properly what makes think new , undocumented? there's absolutely nothing wrong this. definitely don't this. temptation manually cludge database shoudl avoided. you didn't mention this, can use fluent syntax, this: model

c# - MVC VirtualPathProvider GetFile not called when app root is different -

i have views, scripts, styles compiled embedded resource in different dll. iam using virtualpathprovider file. web running fine when it's places in web root -> www.xxx.com the problem when place website www.xxx.com/yyy checks files in virtualpathprovider if exist , yes, files found. controller function returns view called, getfile in virtualpathprovider not called , website says error 404. routing: public static void registerroutes(routecollection routes) { routes.ignoreroute("{resource}.axd/{*pathinfo}"); routes.maproute(name: "default", namespaces: new[] {"merz.ems.core.controllers"}, url: "{controller}/{action}", defaults: new {controller = "index", action = "index"}); routes.add(new route("resources/{*url}", new embeddedresourceroutehandler())); } the embeddedresourceroutehandler handles scripts , styles. virtualpathprovider: using system; using system.collections; usi

Divide String Parameter Into Different Lines in Perl -

i have perl line long , want divide 2 lines readability purposes. such system("someunixcommand paremeter1 parameter2 ... parametern"); can in perl? system("someunixcommand paremeter1 parameter2 parameterk" "parameterk+1 ... parametern"); one way concatenate quoted strings: system("someunixcommand paremeter1 parameter2 parameterk " . "parameterk+1 ... parametern");

css3 - Getting CSS divs to appear left -

Image
i'm new css , i'm having issues divs. i'm not quite sure how word question correctly , unfamiliar lot of terminology used, i'm having trouble finding answer question. basically, goal have container holds several square or rectangular divs @ different sizes (160x160px, 320x320px , 160x320px) can displayed in responsive grid. the issue i'm having larger divs 'push' things away them; example, smaller divs not appear left of bottom half of 320x320 div class. the css i've written looks this; body{ max-width: 1280px; background-color: #333333; } div{ border: 1px solid #333333; height: 158px; width: 158px; float: left; text-align: center; background-color: #cc00ff; display: block; float: left; vertical-align: text-bottom; } .extra{ height: 158px; width: 318px; background-color: #ccff00; } .feature{ height: 318px; width: 318px; background-color: orange; } i have linked in html p

AngularJS ng-repeat for an array JSON -

i'm working on code in cordova using angularjs , 2 json array feeds parse.com. food item multiple options variable pricing. have defined 2 classes called flavors , sizes (doesn't make sense type of food, please bear me i'm testing out). each food item has separate set of flavors , sizes defined. i'm having trouble populating flavors , sizes. here factory retrieves data parse: app.factory('parsedata', function($http) { var parsefactory = {}; parsefactory.getitems = function() { return $http({method : 'get',url : 'https://api.parse.com/1/classes/menu/', headers: { 'x-parse-application-id':'x', 'x-parse-rest-api-key':'x'}}) .then(function(response) { return response.data; }); }; parsefactory.getoptions = function() { return $http({method : 'get',url : 'https://api.parse.com/1/classes/options/', headers: { 'x-parse-application-id':'x', 'x-parse

c# - I am trying to understand another programmer's ForEach statement -

when try compiling code below on vs2015, following error: 'list int' not contain definition 'foreach'. please help, converting code below normal foreach (var in type) statement. enumerable.range (0, 4).tolist ().foreach (x => dashboard.rowdefinitions.add ( new rowdefinition { height = new gridlength (1, gridunittype.star) } )); for more readable , suitable here, because don't use argument of foreach method , have many usefull actions ( range , tolist ). for(int x = 0; x < 4; x++) { dashboard.rowdefinitions.add ( new rowdefinition { height = new gridlength (1, gridunittype.star)} ); }

Python - download all folders, subfolders, and files with the python ftplib module -

i have been working day trying figure out how use python ftplib module download folders, subfolders, , files ftp server come this. from ftplib import ftp import sys, ftplib sys.tracebacklimit = 0 # not display traceback errors sys.stderr = "/dev/null" # not display attribute errors host = "ftp.debian.org" port = 21 username = "" password = "" def mainclass(): global ftp global con host port ftp = ftp() con = ftp.connect(host, port) # connects host specified port def grabfile(): source = "/debian/" filename = "readme.html" ftp.cwd(source) localfile = open(filename, 'wb') ftp.retrbinary('retr ' + filename, localfile.write) ftp.quit() localfile.close() try: mainclass() except exception: print "not connected" print "check address", host + ":" + str(port) else: print "connected" if ftplib.error_pe

ruby on rails - Kaminari not limiting collection in Spree -

for reason kaminari not limiting child objects on parent show view. can see pagination links collection not limited. what doing wrong? view - <% if @handbag.microposts.any? %> <h3>posts (<%= @handbag.microposts.count %>)</h3> <div class="row"> <div class="col-md-8"> <ol class="microposts"> <% @handbag.microposts.each |micropost| %> <li id="micropost-<%= micropost.id %>"> <span class="user"><%= micropost.user.email %></span> <span class="content"><%= micropost.content %></span> <%= image_tag micropost.picture.url if micropost.picture? %> <span class="timestamp"> added <%= time_ago_in_words(micropost.created_at) %> ago. </span> </li>

mesos - marathon not run tasks -

i making mesos-cluster terraform provisioning. using marathon reflected following problem: tasks queued if leader associated marathon matches same machine leader assigned mesos-master. otherwise endless waits. any idea solve problem?

reactjs - In React how to decide whether to use componentWillReceiveProps or componentWillMount? -

componentwillmount called once @ first render componentwillreceiveprops called subsequent renders so - if want action (e.g. initialise data in store) when component rendered put code? - depends on prop passed in higher level component. the problem don't know sure if prop initialised time first render called. (the prop depends on asynchronous data). - can't put code in componentwillmount. if put in componentwillreceiveprops , change higher component chain data fulfilled synchronously code in componentwillreceiveprops never run. motivation post did , have refactor bunch of components. it seems solution put code in both methods. there no lifecycle method called - first time , subsequent. how can know sure if data in top level components available time of first render? or matter not. or maybe can - change this. this lifecyle approach seems fragile me. have missed something? (most likely). you have answer: put code in both methods. however, i'd suggest

asp.net - How can I retrieve data from a textbox in Visual Basic -

i have created simple username , password login form on visual basic. works perfectly. know there way retrieve usernames , passwords entered , save them string or similar? i assume have 2 different textboxes username , password do: dim username string dim password string the textboxes each have different name do: username = nameofyourtextbox1.text password = nameofyourtextbox2.text

angularjs - How to test vm.variable - function(){..} unit testing with jasmine? -

i using karma- jasmine framework test angular application. i'm facing problem in calling functions of controller or service form test-spec. tried using controller. scope. both of them didn't work me. the controller code is (function () {'use strict'; angular.module('selfui').controller('attendeescontroller', attendeescontroller); attendeescontroller.$inject = ['$state', '$stateparams', 'attendeeservice', 'settings', '$log']; function attendeescontroller($state, $stateparams, attendeeservice, settings, $log) { var vm = this; if ($stateparams.attendeedata === null) { vm.pagetype = "add attendee"; vm.isedit = false; } else { var tempattendee = $stateparams.attendeedata; vm.pagetype = "edit attendee"; vm.isedit = true; vm._id = tempattendee._id; vm.firstname = tempattendee.firstname; vm.lastname = tempattendee.lastname; } vm.checkavailable = function(email){

TeamCity + Allure -

i'm evaluating use of teamcity, , i'm having problems integrating allure plugin. running server , agent on win 8.1 x64. team city v9.1.3 downloaded v2.1 of allure plugin , commandline https://github.com/allure-framework/allure-teamcity-plugin/releases (release 2.1) unzipped , made sure add allure command line bin path. uploaded plugin zip through teamcity plugin uploader. at point expecting find allure build step in build steps no. what's going on?

ios - Using a Swift closure to capture a variable -

i have bit of code , errors out because when use foo in return statement it's outside of scope of function. know (i think know) need use closure capture variable can't figure out how that. using alamofire & swiftyjson. great! thanks! func getplayerid(named: string) -> string { alamofire.request(.get, "url", headers: headers) .responsejson { response in let json = json.self(response.result.value!) var index = 0; index < json.count; index++ { if json[index]["name"].stringvalue == named { var foo = json[index]["foo"].stringvalue } // if statement end } // loop end } // alamofire request end // return statement getplayerid function return foo } // getplayerid function end } // player struct end the basic idea getplayerid should not return anything, rather should have parameter closure, , once retrieve value want "return&q

powershell - RegEx Finding multiple matches with a quantifier -

i have powershell code: $uri = "http://charts.spotify.com/api/tracks/most_streamed/au/daily/latest" $contenttype = "application/json" $postblog = (invoke-webrequest -uri $uri).content -match 'track_name\s:\s(.*?)",' $matches[1] when run this, result: fourfiveseconds problem is, know there more songs 1 song. , know match using, string of text " track_name " exists more once. how can change regex matches every match can find? in other words, expected output multiple matches, allowing me list songs, e.g. $matches[1] , $matches[2] , $matches[3] , $matches[4] , etc. since using invoke-webrequest , assume using powershell v4.0. therefore, can use convertfrom-json on data received , iterate on it, instead of using regex solution: $uri = "http://charts.spotify.com/api/tracks/most_streamed/au/daily/latest" $contenttype = "application/json" $postblog = (invoke-webrequest -uri $uri).content | convertfrom-json

how jenkins in a docker access git-repo of gitlab in another docker -

i installed both gitlab-docker , jenkins-docker on same server(my laptop): docker run --name gitlab-postgresql -d \ --env 'db_name=gitlabhq_production' \ --env 'db_user=gitlab' --env 'db_pass=password' \ --volume /srv/docker/gitlab/postgresql:/var/lib/postgresql \ quay.io/sameersbn/postgresql:9.4-5 docker run --name gitlab-redis -d \ --volume /srv/docker/gitlab/redis:/var/lib/redis \ quay.io/sameersbn/redis:latest docker run --name gitlab -d \ --link gitlab-postgresql:postgresql --link gitlab-redis:redisio \ --publish 10022:22 --publish 80:80 \ --env 'gitlab_port=10080' --env 'gitlab_ssh_port=10022' \ --env 'gitlab_secrets_db_key_base=long-and-random-alpha-numeric-string' \ --volume /srv/docker/gitlab/gitlab:/home/git/data \ quay.io/sameersbn/gitlab:8.0.5-1 docker run --name myjenkins -p 8080:8080 -v /var/jenkins_home jenkins in myjenkins docker ,use bash run git ls-remote -h ssh://git@localhost:10022/rhtj/yirongtong.git he

php - Unserialized object can't be passed from origin? -

so have complex object wish cache after creation expensive initialize. i'm able reconstitute instance within class defining file need able return reconstituted instance in place of new myclass if scheme going of use. (don't i?) here's i've done far: class payperiodservice { public $type; // weekly,bi-weekly, semi-monthly, monthlly public $payday_first; public $close_first; public $hours_start; public $hours_end; public $length; // in days public $periods; // array of periods year public $dayinterval; public $oneweekinterval; public $twoweekinterval; public $semifirstinterval; public $monthinterval; public $initialyear; public $today; // date object public function __construct() { if( redis::exists('pay-period-instance')) { log:info( 'fetching pay-period cache.'); $instance = json_decode(redis::get('pay-period-in

javascript - Dynamic AngularJS data value not being used -

i have angularjs d3 dial uses data-actual attribute set dial values. if hard code in values works fine. however, if use angular $scope variables doesn't seem pick values. working code example: <div class="widget-container" data-expected="0.90" data-actual="0.30" indicator-widget></div> non working code: <div class="widget-container" data-expected="0.90" data-actual="{{ dataremaining | number:2 }}" indicator-widget></div> however, when @ source via firebug in both examples shows me below. both same. working result: data-actual="0.30" data-expected="0.90"> non working result: data-actual="0.39" data-expected="0.90"> what missing?

php - Laravel - display notification count on navigation bar -

currently im working on notification features in laravel apps. notification doesn't need real time, users refresh page system latest notification count again , display on top of navigation bar. i've achieved implementing count function in base controller other controller extend it. below example of how notification count. i've 2 table, ap_thread , ap_thread_comment . ap_thread has column last_visit_date , ap_thread_comment has column created_at . 1 thread can have many comments, query when ap_thread_comment created_date > ap_thread last_visit_date , getthe total unread comment. ap_thread last_visit_date update when thread owner visit thread. now problem when user comment on thread let's 2 unread comments. when thread owner visit thread again, show 2 unread comments it's because base controller trigger first follow controller update last_visit_date . can correct count if refresh page again. doing wrong implement notification this? below code class b

dynamic programming - Algorithm puzzle: minimum cost for allow all persons standing on a line to communicate with each other -

i have algorithm design puzzle not solve. the puzzle formulated this: there n persons standing on number line, each of them maybe standing on integer number on line. multiple persons may stand on same number. 2 persons able communicate each other, distance between them should less k. goal move them each pair of 2 persons can communicate each other (possibly via other people). in other words, need move them distance between neighboring 2 persons smaller k. question: minimum number of total moves? feels falls greedy algorithm family or dynamic programming. hints appreciated! we can following in o(n) : calculate cost of moving people right of person i towards person i @ acceptable distance: costright(a[i]) = costright(a[i+1]) + (a[i+1] - a[i] - k + 1) * count of people right k = 3; = { 0, 3, 11, 17, 21} costright = {32, 28, 10, 2, 0} calculate cost of moving people left of person i towards person i @ acceptable distance: costleft(a[i]) = costleft(a[i-1])

LAG/LEAD equivalent with grouping (SQL Server 2008 R2) -

note: using sql server 2008 r2 , built in lead/lag functions not available. i need update table's column contain 'previous' , 'next' values productid - table needs store prevproductid (lag), productid , nextproductid (lead). code below nicely , adapted geri reshef's answer http://blog.sqlauthority.com/2011/11/24/sql-server-solution-to-puzzle-simulate-lead-and-lag-without-using-sql-server-2012-analytic-function/ use adventureworks2008r2 go t1 ( select row_number() over(order salesorderid,productid) n, s.salesorderid, s.productid sales.salesorderdetail s salesorderid in (43670, 43667, 43663) ) select salesorderid, case when n%2=1 max(case when n%2=0 productid end) on (partition n/2) else max(case when n%2=1 productid end) on (partition (n+1)/2) end prevproductid, productid, case when n%2=1 max(case when n%2=0 productid end) on (partitio

postgresql - how to select IPs in same network in SQL -

i have table include ip addresses , netmasks, want select ips table in same network network address. ip_adress | netmask ----------------|----------- 192.168.13.25 | 29 192.168.13.26 | 29 192.168.13.1 | 30 192.168.13.2 | 30 for example, want ips table in network address 192.168.13.24/29: ip_adress | netmask ----------------|----------- 192.168.13.25 | 29 192.168.13.26 | 29 using postgresql's network address functions , operators can easly : select * network_adresse_table network(cast(format('%1$s/%2$s',ip_adress,netmask) inet)) = cast('192.168.13.24/29' inet) here sql fiddle

unit testing - How can I avoid passing the scheduler through my business logic, when writing tests for RXJS observables? -

i finding way make tests pass explicitly pass scheduler functions. illustration, consider function: function dostuff( stream ){ return stream.delay(100) .filter( x => x % 2 === 0 ) .map( x => x * 2 ) .flatmaplatest( x=> rx.observable.range( x, x+100) ) and test: it('example test', () => { let scheduler = new rx.testscheduler() let xs = scheduler.createhotobservable( onnext(210, 1), onnext(220, 2), onnext(230, 3) ) let res = scheduler.startscheduler( () => dostuff( xs, scheduler ), {created:0, subscribed:200, disposed:1000}) expect( res.messages ).toequal( [ onnext(321, 4), onnext(322, 5), onnext(323, 6) ] ) }) which gives error: expected [ ] equal [ ({ time: 321, value: onnextnotification({ value: 4, kind: 'n' }), comparer: function }), ({ time: 322, value: onnextnotification({ value: 5, kind: 'n' }), comparer: f

swift - iOS Navigation Back Button -

i want have button on second view controller have. when loads now, show button want change title else. implemented viewwillappear method invoke showing navigation bar. following didn't work: override func viewwillappear(animated: bool) { super.viewwillappear(animated); self.navigationcontroller?.navigationbar.hidden = false self.navigationcontroller?.navigationbar.backitem?.title = "something else" } please me change title. should in willappear or viewdidload? add right before push or popviewcontroller statement in first view: let backbutton = uibarbuttonitem(title: "something else",style: uibarbuttonitemstyle.plain ,target: nil,action: nil) self.navigationcontroller!.navigationbar.topitem!.backbarbuttonitem = backbutton or can in second view way: override func viewwillappear(animated: bool) { super.viewwillappear(animated); let backbutton = uibarbuttonitem(title: "something else",style: ui

iphone - Initial Interface Orientation to Landscape iOS 9 -

technical note tn2244: launching iphone application in landscape states: the values of uisupportedinterfaceorientations key determine how status bar positioned while the app launching. in ios 7 , below, if uiinterfaceorientationportrait value present, status bar positioned portrait orientation. otherwise, status bar positioned according first orientation appears under uisupportedinterfaceorientations key. so in ios 8 fine put uiinterfaceorientationlandscape first in uisupportedinterfaceorientations list have app start in landscape. it not work anymore in ios 9. having uiinterfaceorientationportrait in list @ any position forces app start in portrait. question is there known workaround this? need app start in landscape. note: using viewcontrollers' supportedinterfaceorientations() method not option takes effect after launchscreen presented. having uiinterfaceorientationportrait in list @ position forces app start in portrait. that absolutely

ios - How to make a 360 panorama app using DJI Mobile SDK like DronePan? -

i saw dronepan's app on facebook recently. dronepan simple app control dji's inspire 1 take cool 360 panorama, it's awesome. can check video: https://www.youtube.com/watch?v=szjimzhqcqe , excited , want make ios app too. google , figure out dronepan using dji mobile sdk make app. wondering if can give me clues start project? using api of dji sdk can make inspire 1 rotate camera take photos? thanks! good topic! panorama feature quite popular drones’ app recently. started play dji mobile sdk 2 weeks, google , found dji sdk’s github page . it’s helpful starters us. in page, found creating panorama application tutorial , recommend check it! can use dji mobile sdk’s intelligent navigation waypoint missions , joystick control aircraft’s camera rotate , take photos. joystick feature, please check djigimbal.h file, there method called: -(void) setgimbalpitch:(djigimbalrotation)pitch roll:(djigimbalrotation)roll yaw:(djigimbalrotation)yaw withresult:(djiexecuteresul

r - How to extract the first line from a text file? -

i have text file read this: file=read.table("file.txt",skip="1",sep="") the first line of text file contains information file followed observations. i want extract first line , write out new text file. to read first line of file, can do: con <- file("file.txt","r") first_line <- readlines(con,n=1) close(con) to write out, there many options. here one: cat(first_line,file="first_line.txt")

regex - python - Tkinter - How can I write Tkinter reg. expression to fetch the string after a word? -

[problem] how can write tkinter reg. expression fetch string after word ? [input] def addcutofffrombutton(): fieldtext = aftercutoff.get() searchtext = '[cut\-off:.*]' replacetext = 'cut-off:' + str(fieldtext) startposition = textpad.search(searchtext, "1.0", stopindex=end, regexp=true) print "startposition", '{!r}'.format(startposition) print len(searchtext) if startposition: endposition = '{}+{}c'.format(startposition, len(searchtext)) print "endposition", '{!r}'.format(endposition) textpad.delete (startposition, endposition) textpad.insert (startposition, replacetext) else: textpad.insert(end+'-1c', '\n' + 'cut-off:' + str(fieldtext)) [output] this code replace: "cut-off: xyz" if: - there no text before "cut-off: xyz" - there text befo

emacs 24.5 python-mode (stock version Vs 6.2.1) -

i have discovered issue python-mode in emacs. c++ develop , seldom python. i have discovered issue: i emacs –q i open python file it contains: import re myre var = [ % the % represents cursor location. then, @ location try tab , error: debugger entered--lisp error: (wrong-type-argument number-or-marker-p nil) python-indent-context() python-indent--calculate-indentation() python-indent-calculate-indentation(nil) python-indent-line(nil) python-indent-line-function() indent-for-tab-command(nil) call-interactively(indent-for-tab-command nil nil) command-execute(indent-for-tab-command) i have not developed in python month or cannot remember being issue. using emacs 24.5.1 windows 7 64, python 2.7.3 , – of course - -q no configuration. now, try apply python-mode 6.2.1 running this emacs –q in scratch (setq load-path (append load-path (list "~/.emacs.d/python-mode.el-6.2.1"))) (require 'python-mode) i open python file (the same above)

dns - Domain pointing from A -> B and B-A -

i trying redirect domains among each other. example a) domain -> b b) domain b -> a domain , b on different hosts , have different name servers. easiest way without migrating full sites ? aware can point domain -> b , if try point domain b -> after, go in infinite loop. i not expert in updating cname records willing if choice. any wonderful. thank you you need modify appropriate records in authoritative name servers. records this: aserver 192.134.56.78 bserver 192.134.56.79 some links read: https://en.wikipedia.org/wiki/name_server https://msdn.microsoft.com/en-us/library/bb727018.aspx https://www.linode.com/docs/networking/dns/introduction-to-dns-records

Android - Import CSV File Into SQLite Databse -

i want enable users able import csv files sqlite database, 1 table called inventory how user can select csv file within app , load in data database without replacing there? thanks you must read content of csv file , add content database. this read csv file. edited you can using read csv file storage public class mainactivity extends appcompatactivity { private static final int request_code = 1; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); intent intent = new intent(intent.action_get_content); intent.settype("file/*"); startactivityforresult(intent, request_code); } @override protected void onactivityresult(int requestcode, int resultcode, intent data) { super.onactivityresult(requestcode, resultcode, data); if(resultcode == result_ok){ if(requestcode == request_co

C: Segmentation fault (core dumped) -

this question has answer here: definitive list of common reasons segmentation faults 1 answer im writing program class assignment in c. simulate reading , writing custom-sized direct-mapped cache, involving custom-sized main memory. these parameters used before getting segmentation fault : enter main memory size (words): 65536 enter cache size (words): 1024 enter block size (words/block): 16 this code. not complete yet. #include<stdio.h> #include<stdlib.h> struct cache{ int tag; int *block; }; struct main { int value; int address; int word; struct main *next; }; struct cache *cacheptr; struct main *mainhd; int main() { int option = 0; while (option != 4) { printf("main memory cache memory mapping:\n--------------------------------------"); printf("\n1) set parameter

android - unexpected ACKing behavoir in GCM XMPP Protocol -

we using gcm’s xmpp protocol deliver push notifications our customers, problem facing when sending xmpp messages high speeds, don’t receive 'ack' or 'nack' messages gcm anymore, these results of several tests did matter : 500 xmpp messages - sent every 0.25 seconds: all messages acked 500 xmpp messages - sent every 0.1 seconds: on average, ~4 messages remained un-acked 500 xmpp messages - sent every 0.01 seconds: 72 messages remained un-acked 500 xmpp messages - sent no sleep time (as fast possible) reached 100 unacked message limit set gcm in less 0.5 seconds ! the results worse when go more 500 messages, e.g : 4000 xmpp messages - sent every 0.1 seconds: on average, number of un-acked messages rose 16 4000 xmpp messages - sent every 0.01 seconds: on average, reached 100 unacked limit in 800th xmpp message. —————————————————————————————————— these results tests done on google’s own cloud (google cloud compute servers), whil

ruby on rails - Warning regarding not using bundler when running guard init -

in rails app getting warning when running guard init rspec : warning: have gemfile, you're not using bundler or rubygems_gemdeps 14:54:15 - info - writing new guardfile /home/ubuntu/railsprojects/sillyfish/guardfile 14:54:16 - info - rspec guard added guardfile, feel free edit i don't understand why it's showing. okay ignore warning? here gemfile: source 'https://rubygems.org' gem 'rails', '4.2.4' gem 'pg' gem 'sass-rails', '~> 5.0' gem 'uglifier', '>= 1.3.0' gem 'coffee-rails', '~> 4.1.0' gem 'jquery-rails' gem 'turbolinks' gem 'jbuilder', '~> 2.0' gem 'sdoc', '~> 0.4.0', group: :doc group :development, :test gem 'rspec-rails', '3.3.3' gem 'guard-rspec', require: false gem 'spring-commands-rspec' gem 'byebug' end group :development gem 'web-console', '~>

Highcharts: generate blank chart -

my application takes in dynamic data , generates chart, option display message overlayed on top using chart.renderer.text() . sometimes dynamic request data malformed, , resultant data unreliable, in case i'd generate blank chart (with custom background colour) of same width , height requested (that part of request ok), , message overlay described above display message user. what easiest way of doing that? want blank chart literally that... solid colour no axes or anything, , no message "no data display" i've seen on couple of examples found when searching answer. , on top of blank background (with user-defined width , height) message overlay. it easiest create... empty chart. in load event add necessary text chart. this: http://jsfiddle.net/zkj36o7e/1/ $('#container').highcharts({ chart: { events: { load: function () { var text = this.renderer.text("malformed data").attr({

ruby - Print only even numbers from an array -

i'm working way through ruby tutorial. 1 of questions provides array. have to: "write loop puts values of my_array . (bonus points if use one-line if !)" my answer passes test shows syntax error, answer if statement below. can explain why syntax error? my_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] if my_array.each |x| % 2 == 0 puts x you're missing end statement do , left operand modulus. try this: my_array = (1..10).to_a my_array.each { |x| puts x if x.even? }

Add Google Services to Cordova Android app using Gradle -

i'm trying integrate google analytics cordova android app. have used guide https://developers.google.com/analytics/devguides/collection/android/v4/ , when want add apply plugin:'com.google.gms.google-services' into build.gradle throws error: a problem occurred evaluating root project 'android'. failed apply plugin [id 'com.google.gms.google-services'] plugin id 'com.google.gms.google-services' not found. i found solution: 1) had setup plugin.xml use custom ga.gradle file build <platform name="android"> <framework src="src/android/ga.gradle" custom="true" type="gradlereference" /> <framework src="com.google.android.gms:play-services-analytics:8.1.0"/> <resource-file src="src/android/google-services.json" target="google-services.json" /> ... </platform> 2) create ga.gradle file builds

How to print an int array returned in a method in the main function , Java -

this question has answer here: what's simplest way print java array? 24 answers first of all,i newbie in java , came across issue several times. trying return number of occurrences of char in string , implemented method called countcharacters looks this: public static int[] countcharacters(string s) { string alphabet="abcdefghijklmnopqrstuvwxyz"; int[] sircounter=new int[alphabet.length()]; for(int i=0;i<sircounter.length;i++) { sircounter[i]=0; } for(int j=0;j<alphabet.length();j++) { for(int i=0;i<s.length();i++) { if(alphabet.charat(j)==(s.charat(i))) { sircounter[j]++; } } } return sircounter; } in other words, each time character alphabet found in string ,the argument of method, value 0 each position sircounter incremented number of occurrence. wanted prin