Posts

Showing posts from February, 2013

python - How to specify constraints in statsmodels OLS? -

i using statsmodels ols run linear regression on data. problem coefficients add 1 (i plan not use constant parameter). is possible specify @ least 1 constraint on coefficients in statsmodels ols. see no option so. thanks in advance. coder.

bash - Seeing shell commands as they are being executed including variables -

this question has answer here: difference between single , double quotes in bash 3 answers i can do bash -x mysellh.sh to see commands being executed, don't see variables replaced values. instance, if have in shell script: screen -d -m sh -c 'rails_env="$r_env" bundle exec rake sunspot:solr:reindex[500] > "$project_dir"/solr/indexing_out.txt' i see: + screen -d -m sh -c 'rails_env="$r_env" bundle exec rake sunspot:solr:reindex[500] > "$project_dir"/solr/indexing_out.txt' even though i've declared earlier: r_env=test is there option want? in case, doing asked: command line "word" $r_env in have enclosed in single quotes, inhibit expansion. -x output showing non-expansion. if want variables expanded, enclose first "word" in double quotes , use single qu

PHP SQLITE - How to insert new records and update existing records conditionally -

trying wrap head around this. posting data sqlite db , insert records if not exist, , update existing records if requirements met (basically if 1 field has changed values). not sure how this. i've seen examples using on duplicate key, updates records when there duplicate. need check change before updating. any ideas?

html - Is it safe to only redirect non logged users on php? -

i'm creating little website , i'm wondering since had lessons on http headers if it's safe use such logging algorithm : if(! isset($_session["user"]) { header("location : logout.php"); } // , here start web page if conditin above not satisfied <html> ........ i think it's not because redirection can ignored web client isn't ? its better add 'else' statement prevent bugs trolling :) if(!isset($_session["user"]) { header("location : logout.php"); exit("you not authorized!"); } else { ?> <html>...</html> <?php } ?>

css3 - How to align html div elements horizontaly in popover bootstrap? -

Image
i using bootstrap 3. want align 2 div elements horizontaly in popover dont know exact class apply style setting property display: inline-block; . idea how can achieve ? tried wrapping them div , setting property inline-block parent div did not work. $('#tag-input').popover({ container: 'body', trigger: "manual", html: "true", animation: true, content: "<div>first row</div><div>second row</div>" }); just wrap 2 divs in div class="row" . can add class="col-xs-6" each of them, each take 50% width of popover. demo here $('#tag-input').popover({ container: 'body', trigger: "hover", position: "bottom", html: "true", animation: true, content: "<div class='row'><div class='col-xs-6'>first row</div><div cla

sas - Logistic regression Macro -

%macro intercept(i1= ,i2= ); %let n = %sysfunc(countw(&i1)); %do = 1 %to &n; %let val_i1 = %scan(&i1,&i,''); %let val_i2 = %scan(&i2,&i,''); data scores; set repeat_score2; /* segment 1 probablity score */ p1 = 0; z1 = &val_i1 + * 0.03 + r * -0.0047841 + p * -0.000916081 ; p1 = 1/(1+2.71828**-z1); /* segment 2 probablity score */ p2 = 0; z2 = &val_i2 + r * 0.09 + m * 0.012786245 + c * -0.00179618 + p2 = 1/(1+2.71828**-z2); logit_score = 0; if max(p1,p2) = p1 logit_score = 1; else if max(p1

c++ - Trap cursor in Window -

i wrote own cameraclass in c++ using dx11. @ moment use wm_mousemove events around in scene. prevent cursur out of window, call function setcursorpos center mouse whenever wm_mousemove event occurs. if move mouse fast, cursor gets out of window. solution using function clipcursor, leads falter rotation of camera when cursor hits border of rect. clipcursor solved original problem, ended in another. do guys have solution that? the regular windows message not best solution drive precise controls. inherit os acceleration system, clipping , depends on other shenanigans can see. the best api receive mouse inputs raw input. has advantage expose better dpi , polling rate hardware can provide , free of under hood manipulation. once read mouse this, free use setcapture , clipcursor prevent unwanted click other window. you can find documentation here : https://msdn.microsoft.com/en-us/library/windows/desktop/ms645536(v=vs.85).aspx

java - Invalid object name of a temp table -

i'm salvaging java code left me previous employee, left source code itself, i've had recreate db structure myself. far restored it, 1 line throws exceptions @ me , can't understand why. connbeztirazh.execsqlu("declare @ki table (id_ki int); " + "declare @bil table (id_bilet int); " + "insert ki (i1,i2,i3,i4,i5,i6) output inserted.id_ki @ki values ("+i1+","+i2+","+i3+","+i4+","+i5+","+i6+"); " + "insert bilet(id_ki,data) output inserted.id_bilet @bil values ((select id_ki @ki),(select sysdatetime())); " + "insert rezultat (id_players, id_bilet) output inserted.id_bilet values ((select id_players players telnomer='"+number+"'),(select id_bilet @bil));", false); this line throws out following exception: com.microsoft.sqlserver.jdbc.sqlserverexception: invalid object name 'ki'. i triple-checked everything, recreated tables bilet , p

amazon web services - Will Cognito User Pools support internationalization? -

we excited new cognito user pools. looks there no way support multiple languages in messages. for example user germany should verification message in german while user new zealand should in english. without internationalization nobody use cognito user pools outside of english speaking countries. will feature in final release on cognito user pools? you can use lambda triggers functionality cognito user pools customize messages sent users. the custom message lambda trigger sends event source can identify particular user pool or user , return service message template used when sending sms or email message. should conform contract of including {####} code parameter. in specific case, identify users particular country can create custom attribute in user pool source country. in each signup call can set value , service send value lambda function.

symfony - Do you sort your classes? -

i'm developing , intranet application symfony2. i'm using 1 fat bundle features. seem what recommended , symfony2 developpers do . i wonder how deal growing application create entities again , again. create them in entitiy directory inside bundle? sort them subdirectories? the same question can me applied others classes forms. any advice on this? in opinion, if best practices use single bundle, big project can make lose time. in projects i'm used create : - 1 bundle statics pages , resources : example pagesbundle - 1 bundle member area : userbundle - 1 bundle core of application : articlesbundle in case of blog, example. this serves separate , save time in tree symfony2. tell me think.

rest - 302 Redirect for RESTful API -

i setting restful api server, , requiring clients use https. best set block port 80 , return 'not found' requests http, or should redirect of these requests https? setup web servers this, concern how clients handle 302 redirect in restful calls. there best practice or recommended way handle this? thanks! a common approach here respond status code 403 forbidden , specify in response body secure connection required.

java - Why is it considered good practice to return an empty collection? -

i have read several books , seen several blogs discussing how returning empty collection better returning null. understand trying avoid check, don't understand why returning empty collection better returning null. example: public class dog{ private list<string> bone; public list<string> get(){ return bone; } } vs public class dog{ private list<string> bone; public list<string> get(){ if(bone == null){ return collections.emptylist(); } return bone; } } example 1 throw nullpointerexception , example 2 throw unsupportedoperation exception, both generic exceptions. makes 1 better or worse other? also third option this: public class dog{ private list<string> bone; public list<string> get(){ if(bone == null){ return new arraylist<string>(); } return bone; } } but problem you're adding unexpected behavior code others may hav

C# Why can I not programmatically kill a console program started in Task Scheduler? -

i have console program run daily batch. have ui can use alter parameters in db console program uses. i thought great able stop , start program ui , can that. however, have console program set start before work day using task scheduler in case machine should rebooted - @ least know program running when day starts. however, cannot kill when has been started task scheduler. "access denied". why? , how can solve this? try using following method: private void killprocessbyprocessname(string strprocessname) { foreach (process p in system.diagnostics.process.getprocessesbyname(strprocessname)) p.kill(); } e.g: private void btnprocesskiller_click(object sender, eventargs e) { killprocessbyprocessname("winword"); }

Django app_label with spaces - leads to 404 error in admin -

i've been trying customize name of app displayed , have run issue when using spaces in app_label, results in 404 error page when try visit url. example, app_label = 'occupational therapy' results in text displaying intended, visiting url in admin site gives following, though pages individual models appear correctly. example: url/admin/occupational%20therapy/ returns this: page not found (404) request method: request url: url/admin/occupational%20therapy/ but url/admin/occupational%20therapy/model displays correctly. i've tried using this: app_label = 'occupational_therapy' as django documentation seemed state capitalized , strip out underscore automatically, underscore remains, occupational_therapy displayed. in case, urls work if there way strip out underscore, solve problem. otherwise, assume need edit urls.py file? app_label used indicate django application model belongs , not alter url. if application named polls example pla

Jenkins Build off specific branches (jenkins git plugin) -

i trying use <branches> <hudson.plugins.git.branchspec> <name>refs/heads/master</name> </hudson.plugins.git.branchspec> </branches> in config.xml which means intending build commits of master, apparently jenkins seems build commits other branches too. not sure doing wrong accomplish this. appreciated. ps: using jenkins git plugin you need branch name without refs <branches> <hudson.plugins.git.branchspec> <name>origin/master</name> </hudson.plugins.git.branchspec> </branches> or local branch: <branches> <hudson.plugins.git.branchspec> <name>master</name> </hudson.plugins.git.branchspec> </branches>

angularjs - Radio buttons plus a text field in Angular.js -

using angularjs, create list of options radio buttons, last of has empty text field labeled 'other' inputing option not in list. here's demonstration of have in mind bootstrapped in codepen . since stack overflow insists on including codepen code in message, here is: js: angular.module('choices', []) .controller("mainctrl", ['$scope', function($scope) { $scope.color = ''; $scope.colors = [ "red", "green", "blue", "other" ]; $scope.changecolor = function(){ $scope.color = "red" }; }]); html: <html> <head> <body ng-app="choices" ng-controller="mainctrl"> <div ng-repeat="color in colors"> <input type="radio" ng-model="$parent.color" ng-value="color" id="{{color}}" name="color"> <label> {{co

c# - How to allow unicode characters in web.config for my MVC application? -

i wanted add cool characters names , added in web.config picture of cow, this. <add key="sendername" value="&#x1f3eb; mr mooo"/> however, when start application, exception on line in _layout.cshtml nagging localization , such. @styles.render("~/content/css") i'm not sure how handle this. apparently, mvc hates cows can it? i've tried follow the suggested syntax according standard . added utf-16 @ top of config file. this has nothing @ unicode characters , xml escaping. as stated in xml standard linked to, xml defines 5 standard entities: < represents "<"; > represents ">"; & represents "&"; ' represents "'"; " represents '"'. all other entities (such &#x1f3eb; ) not valid in xml unless explicitly define them. there easy way out of situation, though. problem entity contains ampersand not escaped, makes incompat

ruby on rails 4 - Nested attributes text field isn't showing up in my views -

i new rails community. working on application users can have username nested attribute of first , last name. other text field associated user model works fine. any appreciated. attached app models, controllers, migration files, db schema, , views. models class user < activerecord::base has_one :username, dependent: :destroy accepts_nested_attributes_for :username, allow_destroy: true end class username < activerecord::base belongs_to :user end migrations class createusers < activerecord::migration def change create_table :users |t| t.string :email t.string :about_me t.string :nationality t.string :sexe t.timestamps null: false end end end class createusernames < activerecord::migration def change create_table :usernames |t| add_column :username, :first_name, :string add_column :username, :last_name, :string t.references :user, index: true, foreign_key: true t.timestamps null

java - How to add a JPanel in the center of another JPanel? -

Image
i want add jpanel map on top of jpanel worldview in it's center here code: public class worldview extends jpanel implements actionlistener{ private jpanel map; public worldview() throws ioexception{ this.setsize(1024,768); this.setbackground(color.black); map = new jpanel(); this.add(map); } you use gridbaglayout , modify gridbagconstraints#insets or emptyborder generate whitespace around component in combination gridbaglayout or other layout borderlayout example see how use gridbaglayout , how use borders more details

compiler errors - Assembly Program working in Qtspim but not PCSpim-Cache -

i have following assembly program compiles , runs correctly in qtspim , displays correct result in qtsspim console. however, wish observe data segment in pcspim-cache not compile correctly , display correct result in out (it displays 0 in each position) should program computes kronecker product of 2 vectors specified in data portion of file. here code: ## 4/20/16 ## lab 5 .data 0x10000480 str1: .asciiz "this lab 5, a2: \n" str2: .asciiz "c = " str3: .asciiz ", " def: .word 4 arraya: .word 1, 2, 3 arrayb: .word 8, 7, 6 arrayc: .space 100 .text main: ## print str1 li $v0, 4 la $a0, str1 syscall ## print str2 li $v0, 4 la $a0, str2 syscall la $s0, arrayb # load address of b $s0 la $s1, arraya # load address of $s1 #la $s2, arrayc # load address of c $s1 li $t0, 0 # initialize iterator li $s3, 3 # 3 count kproduct: li $t5, 1 # load value of li $t1, 0

xml - Unable to determine the XPATH used with nested SVG elements that do not contain IDs -

i need determine full xpath reach 3rd path element displayed here: <div id="myid"> <div> <svg version="1.1"> <g> <g> <g> <g> <g> <g> <path fill="green"> <path fill="orange"> <path fill-opacity="0.2"> ... plus relevant closing tags. i need use xpath in conjunction selenium-webdriver. looking @ example: selenium webdriver: clicking on elements within svg using xpath understand need need use either local-name() or name() methods interact svg element not sure how incorporate initial nested divs , reach through nested g elements no ids or other information work with. thank in advance if able help! you position each level: id('myid')/di

xcode - Unwind segue isn't editing a selected cell but keeps appending to the array -

so i'm working on contacts page , want able select cell , edit data. contacts information appears in contact page, particular contact being sent. it's when hit save creates new contact instead of modifying selected one. @ibaction func unwindtocontacts(sender: uistoryboardsegue) { if let sourceviewcontroller = sender.sourceviewcontroller as? newcontactviewcontroller, contact = sourceviewcontroller.contact { if let selectedindexpath = tableview.indexpathforselectedrow { // update existing contact. contacts[selectedindexpath.row] = contact tableview.reloadrowsatindexpaths([selectedindexpath], withrowanimation: .none) } else { // add new contact. let newindexpath = nsindexpath(forrow: contacts.count, insection: 0) contacts.append(contact) tableview.insertrowsatindexpaths([newindexpath], withrowanimation: .bottom) } // save contacts. { tr

clojure - Expanding macros in macros -

i have following macro : (defmacro add-children [this children] (map (fn [child] (list '.addchild child)) children)) and create following macro : (defmacro defgom [name & body] (let [sym (gensym)] `(let [~sym (model.)] (add-children sym body))))) considering model java class addchild function. expand defgom (let [*gensym* (model.)] (.addchild *gensym* (first body)) (.addchild *gensym* (second body)) ... (.addchild *gensym* (last body))) when evaluated, add-children macro gives correct result (the list of .addchild ). can't evaluate in defgom macro. "don't know how create iseq from: clojure.lang.symbol". tried ~ or ~@ (given add-children returns list), none worked. how expand macro inside macro? ps: know can function rather add-children macro, want know if it's possible macro. just change last line to: (add-children ~sym ~@body)

Android dialog not showing when background task is running -

this extension of question here, can see of code both fragment containing button , service being used: android sending messages between fragment , service i have button, when clicked start service, collect sensor data, insert database. when clicked again, want display progress dialog, wait existing background tasks finish , dismiss progress dialog. i can correctly send messages , forth between fragment , service using handler in fragment (as can seen in other question). problem progress dialog doesn't show in ui thread until after executor task queue has been cleared in fragment, button onclick looks this: //show stop dialog stopdialog = new progressdialog(mainactivity); stopdialog.setmessage("stopping..."); stopdialog.settitle("saving data"); stopdialog.setprogressnumberformat(null); stopdialog.setcancelable(false); stopdialog.setmax(100); stopdialog.show(); log.d(tag, "dialog up"); //stop service mainactivity.stopservice(new intent(ma

angular - Know when http requests are finished from provider in Angular2 -

i created provider this: import {injectable, provider, inject} 'angular2/core'; import {http, response, headers} 'angular2/http'; import {platform, storage, sqlstorage,localstorage} "ionic-angular"; @injectable() export class myprovider { constructor(@inject(platform)platform,@inject(http)http) { this.http = http; } getsomeotherstuff() { var headers = new headers(); headers.append('content-type', 'application/x-www-form-urlencoded'); this.http.post( 'http://localhost:3000/getotherstuff', {headers: headers} ).map( (res:response)=>res.json()) .subscribe( (response) => { //my response can used }, (err) => {

algorithm - high performance object trackers in computer vision -

i'm interested in tracking multiple objects in video using (potentially moving) single camera in environment partial occlusions , variable distance objects camera. wondering of tracking algorithms can solve problem? experimented mean , cam-shift background subtraction wasn't able results. i recommend reading through results of vot challenge 15. , continue researching selected trackers. http://www.votchallenge.net/vot2015/ correlation filter based trackers (like srdcf - https://www.cvl.isy.liu.se/research/objrec/visualtracking/regvistrack/ ) achieve high speed (due using fast fourier transform), state-of the-art results , not hard implement, first. (srdcf original implementation single-target, easy extend running multiple instances)

java - integer to color -

i coding java applet visual modified version of breadth first search. my problem trying convert number coordinated pixel on 2d array color. code : map 2d array of values should increasing 1 go away starting location except walls set 0 , appear black. string colorhex1 = integer.tohexstring(map[i][j]+100); g.setcolor(color.decode("#"+colorhex1)); if (map[i][j]==1) g.setcolor(color.white); else if (map[i][j]==0) g.setcolor(color.black); g.fillrect(i*10,j*10+40,10,10); how main search works increases number of each cell next 1 unless has been touched in visualization should show increase in vibrancy farther away starting location. design have 1 start off "black" color of walls. 2 head towards purple randomly change color again , again having quite weird. question : there way me code more gradual way of increasing color using number value of map array?

java - Method not correctly calculating and displaying values? -

i'd appreciate this. for example, code is; class candy extends dessertitem { double weight; double price; candy(string n, double w, double p) { super(n); weight = w; price = p; } public double getcost() { double cost = weight*price; int costincents = (int)cost*100; cost = costincents /100.0; return cost; } public string tostring() { return name+"\t\t\t\t$" + getcost() + "\n\t" + weight + " lbs @ $" + price; } } and output is: peanut butter fudge $8.0 2.25 lbs @ $3.99 why displaying $8.0 instead of $8.97? any appreciated! thanks. try int costincents = (int) (cost*100) concrete example: on cost = 3.5 ==> (int)cost*100 = 300 on cost = 3.5 ==> (int) (cost*100) = 350

c# - Fluent Assertions: Approximately compare a classes properties -

i have class vector3d has properties x , y , z of type double (it has other properties such magnitude ). what best way of approximately comparing properties or selection of properties @ given precision using fluent assertions? currently have been doing this: calculated.x.should().beapproximately(expected.x, precision); calculated.y.should().beapproximately(expected.y, precision); calculated.z.should().beapproximately(expected.z, precision); is there single line approach achieve same thing? such using shouldbeequivalentto , or require constructing generic extension method allows properties included / excluded? yes it's possible using shouldbeequivalentto . following code check properties of type double precision of 0.1 : double precision = 0.1; calculated.shouldbeequivalentto(expected, option => options .using<double>(ctx => ctx.subject.should().beapproximately(ctx.expectation, precision)) .whentypeis<double>()); if want compar

swing - Java - Get difference between old and new size of JFrame -

after resizing @ jframe, there method returns difference between old , new size, i.e (dx,dy) ? if not, there way info? (dx,dy) - image you need know size before frame resized, use componentlistener detect when frame's size changed. trick here knowning when "size" has changed fixed point taking measure worthwhile. once frame has "settled" need calculate difference "last resize" now start having @ how write component listener conceptually, want something this or this

angularjs - how to properly use toHaveBeenCalled() for unit testing? -

i need write test sets state test see if statemanagerservice has been called. i'm getting error: undefined not object (evaluating 'vm.statemanagerservice.go') main.controller.js export class maincontroller { constructor($state, statemanagerservice) { 'nginject'; this.$state = $state; if($state.current.name === 'main') { statemanagerservice.go('list'); } } } unit test main.controller.spec.js describe('controllers', () => { let vm; // beforeeach(inject(($controller, $state, statemanagerservice) => { vm = $controller('maincontroller'); })); it('should call statemanagerservice when current name main', ()=> { vm.$state.current.name = 'main' console.log(vm.$state.current.name) expect(vm.statemanagerservice.go()).tohavebeencalled(); }); also (slightly off-topic) i'm still confused

haskell - Yesod - converting resources to Text urls to be put in a JSON API including query parameters -

the function geturlrender used converting route (handlersite m) text , through use of monads . instance: routetotext :: monadhandler m => route (handlersite m) -> m text routetotext url = r <- geturlrender return $ r url gettestr :: text -> handler text gettestr = routetotext (testr something) but if want pass in query parameter? without dealing directly text s? question, simplify type declaration of function routetotext ? i use these urls accomplish json api specification regarding pagination, i've created abstraction work don't know how implement way put link http://example.com/articles?page=2 in concise way. if there better way put link query parameter integrating beautifully aeson library without converting text first, please, let me know.

x86 NASM Indirect Far Jump In Real Mode -

i have been messing around multi-stage bootloader , have got of code work, except last part: the jump . have gotten code work out before wanted make more modular replacing line: jmp 0x7e0:0 with one: jmp far [stage2read + sectorreadparam.bufoff] instead of hard coding code load in, wanted indirect jump it. here's rest of code: ; stage 1 of multi-stage bootloader bits 16 org 0x7c00 jmp 0:boot_main %include "io16.inc" boot_main: ; setup new stack cli mov ax, 0x100 mov ss, ax mov bp, 0x4000 mov sp, bp sti ; setup data segment xor ax, ax mov ds, ax ; save drive booted mov [stage2read + sectorreadparam.drive], dl ; home-made bios wrapper read sectors memory mov si, stage2read call readsectors ; change new data segment mov ax, [stage2read + sectorreadparam.bufseg] m

performance - C# Selenium Screenshot.SaveAsFile - Does Not Release Memory -

i have following code taking screenshot of web page , saving file screenshot screenshot = ((itakesscreenshot)webdriver).getscreenshot(); screenshot.saveasfile($"{filefullname}.png", imageformat.png); when debugging, in vs performace window can see memory jump of around 70-100mb (depending on page size) when calling saveasfile() not release when method finishes executing. is there way force screenshot object dispose? you can force garbage collection happen calling gc.collect . however, shouldn't reasons explained here . .net automatically handles freeing memory unused objects aren't being referenced anymore. garbage collection forces threads stop while occurring calling have toll on application.

Python TypeError: unsupported operand type(s) for -: 'str' and 'int' -

i want functions return single numerical quantity when printing result gives me error: traceback (most recent call last): file "c:/users/servio/desktop/traveltrue.py", line 64, in <module> print 'its total investment is',costo_viaje(ciudad, model, dias, otros_gastos, noches) ,"$ , ", " suerte!" file "c:/users/servio/desktop/traveltrue.py", line 59, in costo_viaje return type_auto(model) + alquiler_de_auto(dias) + costo_hotel(noches) + costo_del_vuelo(ciudad) + otros_gastos file "c:/users/servio/desktop/traveltrue.py", line 41, in alquiler_de_auto costo = costo - 100 typeerror: unsupported operand type(s) -: 'str' , 'int' the code def costo_hotel(noches): return 140 * noches def costo_del_vuelo(ciudad): cities = { "cordoba": 821, "iguazu": 941, "ushuaia": 1280, "bariloche": 1848, "palermo&qu

python - Django Update Model Field with Variable User Input... .update(key=value) -

i'm attempting create function allow updates fields based on front-end input. the handler receive profile_updates dictionary 2 keys. each contain list of key/value pairs. list_of_updates['custom_permissions'] = [{"is_staff":"true"},{"other_permission":"false"}] def update_profile(message): list_of_updates = message['profile_updates'] user_update_id = message['user_id'] update in list_of_updates['custom_permissions']: key, value in update.iteritems(): user.objects.filter(id=user_update_id).update(key=value) i make 'key' variable fed .iteritems(). appreciate anyone's input on how, or if, possible. you don't need loop through dict. can pass kwarg expansion. def update_profile(message): list_of_updates = message['profile_updates'] user_update_id = message['user_id'] update in list_of_updates['custom_permissio

Gettext/Django for german translations: formal/informal salutations -

i maintain pluggable django app contains translations. strings in python , html code written in english. when translating strings german, i'm fighting problem german differentiates between formal , informal speech (see t–v distinction ). because app used on different sites, ranging social network banking website, can't support either formal or informal version. , since translations can differ quite bit, there's no way can parameterize it. e.g. sentence "do want log out?" have these 2 translations: wollen sie sich abmelden? (formal) willst du dich abmelden? (informal) is there in gettext me this? you can use contextual markers give translations additional context. logout = pgettext('casual', 'do want log out?') ... logout = pgettext('formal', 'do want log out?')

c++ - read data from a file with multiple sections from VC++ in VS2013 -

i need read txt file vc++ in vs2013. in file, there mutiple sections: #section1 head1,head2,head3 dcscsa, sdew, safce ..... #section2 head1,head2,head3, head4,head5 112,633,788,632,235 ..... i need save lines different data structure section1: mapsection1> section12 mapsection2<string, map<string, int>> can use code : string aline; getline(file, aline); stringstream ss(aline); int cnt = 0; if (file.good()) { while (!file.eof()) { string substr; getline(file, aline); stringstream ss(aline); while (ss.good()) { // how save data different map different section? } also, can load whole file data set , process each line or process each line when file read line line. which 1 more efficient ? thanks can use code : ... not quite. use: int sectionno = 0; while (getline(file, aline)) { if (aline.empty()) continue; if (aline[0] == '#

javascript - How to stop an if statement when it's always true? -

if (userarray[0] === 1 ) { cardmaker(); return false; } i have array want call function cardmaker when first value array 1. problem above code keeps calling function on , over. tried return false doesn't seem work. how can function invoke once when first value of array 1? try var cnt = 1;// put line out side of function if (userarray[0] === 1 && cnt == 1) { cardmaker(); cnt++; return false; }

c - void* type to char* type leadng -

the man has code #include <conio.h> #include <stdio.h> void dbleint(void *a) { *((int*) a) *= 2; } void deleteevenint(void* a) { int tmp = *((int*) a); if (tmp % 2 == 0) { *((int*) a) = 0; } } void dbledouble(void *a) { *((double*) a) *= 2.0; } void deleteevendouble(void* a) { int tmp = *((double*) a); if (tmp % 2 == 0) { *((double*) a) = 0; } } // function takes array, size, size of 1 element , function //pointer, // applied elements of array void map(void *arr, unsigned num, size_t size, void (*fun)(void *)) { unsigned i; char *ptr = (char*) arr; (i = 0; < num; i++) { fun((void*) (ptr + i*size)); } } why leads void* type char* type? can see thats error, when change code , dont lead it, why? you're not allowed perform arithmetic on void pointers in c. following code illegal: void *foo = whatever; foo + 1; by casting foo char * , can perform arithmetic on pointer.

bash - How to run a script everywhere in linux -

i have script host_avai.sh in /home/campus27/zwang10/bin . , in .bashrc, add export path=$path:/home/zwang10/bin/host_avai.sh . after type host_avai.sh , shows host_avai.sh: command not found. . can me here? added $ echo $shell /bin/tcsh your path should path=$path:/home/zwang10/bin , add in .bash_profile . after run script following command : $ . .bash_profile make sure host_avai.sh must have execute permission. $ cd /home/zwang10/bin $ chmod +x host_avai.sh now run command anywhere.

Vim map for C/C++ case statements -

i want create mapping in vim following scenario: case blah: --> hit enter --> case blah:{ }break; i tried this: inoremap case<space><expression>:<cr> case<space><expression>:{<cr>}break;<esc>ko but don't know put "expression". put there? more complicated this? thanks! you may want have @ switch , case snippets mu-template / lh-cpp , , switch generator enum. either case automatically filled enum, or use placeholder can jump to. otherwise, ideal (simple) solution map enter , detect context case\s\+\s\+:\s* . in case insert {\n}\nbreak;\<up>\<up>\<c-f> . mapping may have recognize enter within pair of {} , on.

android - Boolean show null reference exception -

i tried many time creating setting page mean setting button handle on , off in application class extends application show me boolean reference null exception. following manifest. <application android:allowbackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/apptheme" android:name=".applicationclass"> <activity android:name=".splashscr"> <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> and java class. public class applicationclass extends application { myservice.reciver rec; private context context; public boolean getsoundfx_state() { return soundfx_state; } public void setsoundfx_state(boolean soundfx_state)

reactjs - Automatic this.props.children in nested components -

i'm going through react-router-tutorial , on lesson 5 , have question. the lesson talks defining navlink component wraps link component, , gives activeclassname attribute, used follows: <navlink to="/about">about</navlink> in lesson, define navlink component follows: // modules/navlink.js import react 'react' import { link } 'react-router' export default react.createclass({ render() { return <link {...this.props} activeclassname="active"/> } }) what confuses me use of self closing link component. no in definition of navlink put this.props.children inside of link component. tried out explicitly follows: export default class extends react.component { render() { return ( <link {...this.props} activeclassname="active">{this.props.children}</link> ) } } and works expected. question why? allows self closing link component in definition auto

Enable header filters in excel export using jquery datatables -

Image
i'm trying enable filters excel top row / header file generated table data using jquery datatables library. i've followed tutorial https://datatables.net/extensions/buttons/examples/initialisation/export.html , works great , generated excel file looks below. as can see in pic, there no filters top row. know can enable filters in excel file after opening. i'm trying when excel file gets generated. so, exported excel file should below. you can see highlights in red circle filters. so wondering if it's possible , suggestions how accomplish highly appreciated. thank you. you can enables filters automatically changing excel file schema in file buttons.html5.js. in buttons.html5.js file, can find below code. // excel - pre-defined strings build minimal xlsx file var excelstrings = { "_rels/.rels": '<?xml version="1.0" encoding="utf-8" standalone="yes"?>\ <relationships xmlns="http:

java - Directory only creates when run on localhost -

good day! wondering why codes on creating directory works on localhost. when project deployed live server , access on client-side, not work anymore. string path = system.getproperty("user.home") + file.separator + "documents"; path += file.separator + ("custom_folder"); file customdir = new file(path); customdir.mkdirs(); update: i modified code to file outreportdir = new file("c:/custom_folder"); outreportdir.mkdir(); and creates folder now. problem when client clicks button create folder, folder creates on c:\ of server war file placed, not on user's own c:\ why it? time.

php - Image Uploading Laravel 5.2 : Trying to get property of non-object -

Image
i'm trying upload images using method moving temporary files, , show on index page path. here's problem: errorexception in productcontroller.php line 69: trying property of non-object in controller contain line error: public function store(request $request) { $product=request::all(); product::create($product); $imagename = $product->id_prod . '.' . $request->file('images')->getclientoriginalextension(); $request->file('images')->move( base_path() . '/public/images/catalog/', $imagename ); return redirect('product'); } and here's database, file has been uploaded on temp folder, file fail moved. i'm using laravel 5.2, first time upload files. , can explain me why 1 error. sorry bad grammars. you can try this: public function store(request $request) { $product = $request->all(); $picture = ''; if ($request->hasfile(&

Use ckfinder in laravel 5.2 -

here code in config.php: $path = '/laravel/'; require _dir_.'/../../../../bootstrap/autoload.php'; $app = require_once _dir_.'/../../../../bootstrap/app.php'; $app->make('illuminate\contracts\http\kernel')->handle(illuminate\http\request::capture()); $_user = (auth::check()) ? auth::user()->username : ''; define('ckfinder_root_folder', $path.'resources/assets/uploads/' . $_user .'/'); $config['authentication'] = function () { return auth::check(); }; it works can't upload file (upload finished errors). if remove ->handle(illuminate\http\request::capture() test, run in session (not refresh page). problem. please help. issue looks permission need set 0777 on ckfinder_root_folder you may need add namespace -- use illuminate\support\facades\file; $path = '/laravel/'; require _dir_.'/../../../../bootstrap/autoload.php'; $app = require_once _dir_.'

android - How to change andorid layout as per image given below -

Image
currently listview design looks but want make below image where image on right hand side, title in bold , subtitle below it. changes need make in layout, below code. in advance. <?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/linearlayout1" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="4dp" android:orientation="vertical" > <linearlayout android:layout_width="match_parent" android:layout_height="wrap_content" > <imageview android:id="@+id/ivimage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="8dp" android:src="@drawable/ic_launcher&

bash - Using rsync in expect script with find -ctime give me an error? -

i need expect script , rsync. when run rsync in command line works fine: rsync -avz root@10.33.122.22:'$(find /cluster/storage/nobackup/coremw/var/log/saflog/faultmanagementlog/alarm/ -ctime -1)' /home/imstest/shared/generate/reportingt3/tmp/ but when use expect script looks error: #!/usr/bin/expect -f set host_ip [lindex $argv 0 ] set user [lindex $argv 1 ] set password [lindex $argv 2] set scp_remote_directory [lindex $argv 3 ] #set scp_remote_filename [lindex $argv 4] set local_directory [lindex $argv 4] set force_conservative 1 ;# set 1 force conservative mode if ;# script wasn't run conservatively if {$force_conservative} { set send_slow {1 .1} proc send {ignore arg} { sleep .1 exp_send -s -- $arg } } set timeout -1 #spawn scp $user@$host_ip:$scp_remote_directory/$scp_remote_filename $local_directory/ spawn rsync -azv $user@$host_ip:\'\$(find $scp_remote_directory -ctime