Posts

Showing posts from May, 2012

How to get arguments for 2 different objects from the command line when there is a naming conflict in Python argparse -

i have 2 classes, , b, each have own argument parser defined (using argparse) want add functionality a, calls class b. doing using composition (i.e has instance of object b) i asked here how combine 2 arg parse objects, argparsea include arguments in argparseb in question can 2 python argparse objects combined? problem follows: both , b have arguments same names. but- need 2 different values entered user (ie. argpasea.val1 needs values argparsea.val1 , argparseb.val1) (the obvious solution renaming val1 in either argparsea or argpaseb, there on 50 scripts inherit class a, , 50 scripts inherit class b, want changes , b minimal possible.) i thought of adding new , differently named argument argpasea called val2, can passed argparseb val1. my question is- proper way of doing such conversion or arguments argparsea argparseb? or there better way design this? i'm going guess trying parents suggestion, , illustrate might going on. if you've adopted approach m...

meteor - ReportProcessingStatus": "_CANCELLED_" while try to get Orders Report in Amazon MWS -

i want orders details whatever time are. trying generate order report of amazon mws via report api , sending enumeration "_get_flat_file_orders_data_" or other report enum hit api requestreport gives in response reportrequestinfo": { i20160628-13:14:55.462(5.5)? "reporttype": "_get_flat_file_orders_data_", i20160628-13:14:55.462(5.5)? "reportprocessingstatus": "_submitted_", i20160628-13:14:55.462(5.5)? "enddate": "2016-06-28t07:44:54+00:00", i20160628-13:14:55.462(5.5)? "scheduled": "false", i20160628-13:14:55.463(5.5)? "reportrequestid": "50692016981", i20160628-13:14:55.463(5.5)? "submitteddate": "2016-06-28t07:44:54+00:00", i20160628-13:14:55.463(5.5)? "startdate": "2016-06-28t07:44:54+00:00" i20160628-13:14:55.463(5.5)? } i20160628-13:14:55.463(5.5)? }, bu...

php - How can I set a catch all route as the very last route in Laravel -

i'm building basic cms seo slugs, want catch @ end of routes slug. @ end of routes file added: route::get('/{page?}', ['as' => 'page', 'middleware' => 'web', 'uses' => 'pagecontroller@index']); which works fine, until added laravel file manager , has routes of own. these routes added after of routes in main routes file. catch picks meant file manager. how can load other routes, including in other vendor folders, before running catch all? there way can state route must not match route prefixed laravel-filemanager ? i've not been able find on in laravel documentation or through google. as requested here app providers: 'providers' => [ /* * laravel framework service providers... */ illuminate\auth\authserviceprovider::class, illuminate\broadcasting\broadcastserviceprovider::class, illuminate\bus\busserviceprovider::class, illuminate\cache\cacheserviceprovider::...

javascript - Structuring a Vue + Vuex project -

i kind of confused here on place global functions. in lot of examples main.js file points app component , placed somewhere within html. workflow fine me if contain logic within app component. combining components laravel functionality not work me. currently main.js file contains bunch of methods need have access anywhere in app. these methods don't contain broadcasting events can placed anywhere long vue-resource instance. my main.js file: https://github.com/stephan-v/beerquest/blob/develop/resources/assets/js/main.js hopefully can tell me place friendship methods if use vuex or in general since not seem best practice @ all. thank you. vuex manages of data in application. it's "single source of truth" data on front-end. therefore, changes state of application, such adding friend, or denying friend, needs flow through vuex. happens through 3 main function types, getters, actions, , mutations. check out: https://github.com/vuejs/vuex/tree/mas...

swift - How to create enum optional instance -

i leraning swift 3 "the swift programming language (swift 3 beta)". below enum example. in end of example, have written "use init?(rawvalue:) make instance of enumeration raw value". can tell me, how make that. thanks. enum rank: int { case ace = 1 // raw value case two, three, 4 , 5 , six, seven, eight, nine, ten case jack, queen, king init?(rawvalue: int) { self = rawvalue == 1 ? .ace : .jack } func simpledescription() -> string{ switch self { case .ace: return "ace" case .jack: return "jack" case .queen: return "queen" case .king: return "king" default: return string(self.rawvalue) } } } as can see here: enum rank: int "your" rank enums raw value must of type int . therefore, create new rank element ace value, write: let ace = rank(...

Differentiating between Binary semaphore and Mutex using same code -

void forward(void *pvparam) { while(1) { if(xsemaphoretake(xsemaphore,1000)==pdtrue) { uart0_sendstr("frwd took it\n"); } else { uart0_sendstr("frwd couldn't take it\n"); } vtaskdelay(1000); } } void back(void *pvparam) { vtaskdelay(100); while(1) { if(xsemaphoregive(xsemaphore)==pdtrue) { uart0_sendstr("back gave it:mf\n"); } else { uart0_sendstr("back couldn't give it:ms\n"); } vtaskdelay(1000); } } above code 1 using both binary semaphore , mutex. difference binary semaphore writing "xsemaphorecreatebinary(xsemaphore);" in main , mutex xsemaphorecreatemutex(xsemaphore) in main. according definetion "a semaphore(mutex) occupied task can given task , semaphore(binary) created task can given of tasks" but both codes...

sql - Raw pg GROUP BY query in rails application -

i have simple sql query trying execute in rails console. select name, manual_score objectives group manual_score but throws error is: activerecord::statementinvalid: pg::groupingerror: error: column "objectives.name" must appear in group clause or used in aggregate function i have tried prepending table name columns error remains. appericiated. thanks! the problem listing column not "grouped". should add name group by or remove select. select name, manual_score objectives group name, manual_score -- or select manual_score objectives group manual_score -- or select count(name), manual_score objectives group manual_score why have add column group by or use aggregate function? imagine have following data: name | manual_score 1 | 1 2 | 1 3 | 2 now, try group elements manual_score , think how show name column corresponds manual_score=1 .

c# - How read form file Text language Arabic -

i have text file contains single word language : arabic want extract my code is: string text = system.io.file.readalltext(@"c:\cinprocessing\nom.txt"); console.writeline(text ); i have result unknown characters : ???? how can fix it? thanks, your code reads text correctly variable text . (debug , see) however, dispalying arabic characters in windows console issue (check how solve here )

I can't make a right legend by d3.js -

Image
this result belowing: but want put every bars this: and follow belowing major code legend: the traditional (and versatile) way creating such legends among d3 community using <text> , <rect> svg elements (which can position way want). once you're using html <li> , try 1 of these 2 approaches in css: li { display: inline; } or li { float: left; }

android - I have an error on my activity -

hope me solve error. i have public class open : @suppresswarnings("deprecation") public class addpostactivity extends appcompatactivity { in wich have code written, on section of map in activity appears error : " cannot resolve method getmap();" the code : ` mapfragment fm = (mapfragment)getfragmentmanager() .findfragmentbyid(r.id.maps_fragment); map = fm.getmap(); map.setmaptype(googlemap.map_type_normal); muisettings = map.getuisettings(); muisettings.setcompassenabled(true); muisettings.setmylocationbuttonenabled(false);` *i have tried replace getmap(); getmapasync(); :` public class addpostactivity extends fragmentactivity implements onmapreadycallback { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_add_post); mapfragment fm = (mapfragment) getfragmentmanag...

wordpress - Virtual Host Subsites apache 2.4 -

i'm setting 2 wordpress sites. scenario there 2 wordpress installations, in folder var/www/domain/us , var/www/domain/eu. domain.com/us should default option when access site domain.com users access site through: domain.com/us or domain.com/eu right setup virtual host is: (i don't have real domain name attached, ip address far) <virtualhost *:80> servername [ip-address] serveralias [ip-address] documentroot /var/www/domain/us errorlog /var/www/html/domain.com/logs/error.log customlog /var/www/html/domain.com/logs/access.log combined </virtualhost> <virtualhost *:80> servername [ip-address]/us documentroot /var/www/domain/us serveralias [ip-address] errorlog /var/www/html/domain.com/logs/error.log customlog /var/www/html/domain.com/logs/access.log combined </virtualhost> <virtualhost *:80> servername [ip-address]/eu documentroot /var/www/domain/eu serveralias [ip-address] errorlog /var/www/html/domain.com/logs/error.log cus...

yii2 - Redirecting unauthorized users to another controller action -

i have controller code login: public function actionlogin() { if (!\yii::$app->user->isguest) { return $this->redirect(yii::$app->request->baseurl.'/telephone/index'); } $model = new loginform(); if ($model->load(yii::$app->request->post()) && $model->login()) { return $this->redirect(yii::$app->request->baseurl.'/telephone/index'); } return $this->render('login', [ 'model' => $model, ]); } and preventing add , delete action unauthorized users used: public function behaviors() { return [ 'access' => [ 'class' => accesscontrol::classname(), 'only' => ['add','delete'], 'rules' => [ // allow authenticated users ...

javascript - Detect hide/leave event of mobile phone browser -

i've surveyed of questions on web still gets me confused.... my question is, how detect hide/leave event of website tab in mobile phone browser, situation not closing tab(like pressing x button @ up-right or up-left corner), , not closing whole mobile browser app directly. (previously, have webpage websocket connected receive encoded audio content, , use audiocontext play sound) below 2 situations i've encountered. when press home button , mobile browser app hides. when click url in messenger app or facebook app of iphone, , press button go back. the url link opened in in-app browser made facebook directly, , when press button on left-up corner, view jumps messenger window or facebook timeline. in these 2 cases, have listened beforeunload (and pagehide event ios), neither 1 catched. , have found websocket connection still connecting , audio still playing. seems whole page still running somewhere(but cannot see). tried listening div :visible , s...

excel - vba WorksheetFunction.Match search for multiple values -

i searching hr sheet column header contains specific text. text can change each week, example, column called " state/province " have no spaces in 1 week, following week " state / province " (notice space between words). i using below code looks 1 condition stateprovince = worksheetfunction.match("state/province", hr.sheets("open").rows(1), 0) this works fine, looking add looks second example containing spaces if case column header. suggestions? use: stateprovince = worksheetfunction.match("state*/*province", hr.sheets("open").rows(1), 0) this answer specific question. if want more generic solution you'll have provide other examples.

delphi - Load database field of all records into ListView Item Detail Object -

using delphi xe8 i'm testing functionality firemonkey tlistviews. one thing i'm trying load field of records tfdmemtable component listview item, detailobject of listview item. for example, have 3 records in table (db field called 'name'): record 1 = name 1 record 2 = name 2 record 3 = name 3 there 1 detailobject property per listview item question is, able add of fields (name 1, name 2, name 3) 1 detailobject? below i've attempted far no luck. not 100% sure need do. procedure mainform.buildlist; var litem : tlistviewitem; begin listview1.beginupdate; try listview1.clearitems; litem := listview1.items.add; litem.objects.detailobject.visible := true; memtable begin while not eof begin litem.detail := fieldbyname('name').asstring; end; end; listview1.endupdate; end; end; i'm sorry if isn't clear enough, please let me know. any great. i think should warn bef...

javascript - showTextTrack in Video.js 5 -

i trying change active caption track javascript in video.js v5.10.4. saw few posts , suggested use showtexttrack , when execute command says showtexttrack not function . have following code var video = videojs('video'); var first_track_id = video.texttracks().tracks_[0].id; // returns vjs_track_399 video.showtexttrack(first_track_id, "captions"); // returns error above is there other way accomplish trying do, or doing wrong? showtexttracks() video.js 4. set mode of track showing : video.texttracks()[0].mode = 'showing';

c++ - Decoding and playing audio with ffmpeg and XAudio2 - frequency raito wrong -

i'm using ffmpeg decode audio , output using xaudio2 api, works , plays synced video output using pts. it's high pitched (i.e. sounds chipmunks). setting breakpoints can see has sets correct sample rate audio codec in createsourcevoice. i'm stumped. any appreciated. #include "dvdaudiodevice.h" handle m_hbufferendevent; cdvdaudio::cdvdaudio() { m_pxaudio2 = null; m_pmasteringvoice = null; m_psourcevoice = null; m_pwfx = null; m_voicecallback = null; m_hbufferendevent = createevent(null, false, false, "buffer end event"); } cdvdaudio::~cdvdaudio() { m_pxaudio2 = null; m_pmasteringvoice = null; m_psourcevoice = null; m_pwfx = null; m_voicecallback = null; closehandle(m_hbufferendevent); m_hbufferendevent = null; } bool cdvdaudio::create(int ichannels, int ibitrate, int ibitspersample, bool bpasstrough) { coinitializeex(null, coinit_multithreaded); hresult hr = xaudio2create( ...

generics - Java instance for comparable -

why legal create new box(); , new box<integer>(); ? because box comparable? public class box<comparable> { private boolean compareto(box b) { return (this.y > b.y); } double x=0; double y=0; public static void main (string[] args) { box = new box(); box b = new box<integer>(); system.out.println(a.compareto(b)); } } you have declared class generic type parameter. not same implementing comparable interface: public class box<comparable> { } is same as: public class box<t> { } which not same as: public class box<t> implements comparable<t> { @override public int compareto(final t o) { return 0; } } because type parameter unbounded, accept type. can use integer or string : public class box<t> { public static void main(string[] args) { box = new box(); box b = new box<>(); box c = new box<integer>(); box d =...

eclipse - How to display a hint message in an SWT StyledText -

swt text has method called setmessage() can used display message hint user, indicating purpose of field. it seems styledtext not have setmessage() method. can similar done styledtext nonetheless? recently, had need display hint within styledtext. share solution here. the setmessage() method of styledtextmessage shown below can used display hint on styledtext widget. class adds paint listener draw message text , several listeners , display filters redraw message whenever may invalidated. public class styledtextmessage { public static void main( string[] args ) { display display = new display(); shell shell = new shell( display ); shell.setlayout( new filllayout() ); styledtext styledtext2 = new styledtext( shell, swt.border ); button button = new button( shell, swt.push ); button.settext( "push button" ); new styledtextmessage( styledtext2 ).setmessage( "please enter stylish..." ); shell.setsize( 600, 600 ...

angularjs ui-select set default value and can not select the default value -

Image
i follow example in angularjs ui-select bootstrap website. here html part code: <div class="form-group"> <div class="col-sm-6"> <ui-select ng-model="ctrl.person.selected" theme="bootstrap"> <ui-select-match placeholder="select or search person in list...">{{$select.selected.name}}</ui-select-match> <ui-select-choices group-by="'country'" repeat="item in ctrl.people | filter: $select.search"> <span ng-bind-html="item.name | highlight: $select.search"></span> <small ng-bind-html="item.email | highlight: $select.search"></small> </ui-select-choices> </ui-select> and here js part code: $scope.person = {}; $scope.people = [ { name: 'adam', email: 'adam@email.com', age: 12, country: 'united states' }, { name: 'a...

powershell - How do I check if all the files in a folder is read only recursively? -

currently getting the total file number , file number of read files , see if same: function allreadonly{ param([string]$path) $file_count = get-childitem $path -recurse -file | measure-object | %{$_.count} $read_file_count = get-childitem $path -recurse -file -attributes readonly | measure-object | %{$_.count} $read_file_count $file_count } even if correct takes long time , can't feel there should better way this. currently you're looping twice on files, improvement if incremented 2 variables in same loop, , returned boolean value indicating whether count different or not: function allreadonly { param([string]$path) $all = 0 $ro = 0 get-childitem $path -recurse -file | foreach-object { $all++ if ($_.attributes.value__ -band 1) { $ro++ } } $all -eq $ro } however, since want check if all files read-only suffice return $false encounter first writable file: function allreadonly { param([string]$...

asp.net mvc - wrong user/password didn't checked at AD -

Image
i have created mvc 5 application windows authentication, <authentication mode="windows" /> <authorization> <deny users="?" /> </authorization> i have below code user's display name along want validation, protected void session_start(object sender, eventargs e) { if (context.user != null) { mapuseraddetails(context.user); } } private void mapuseraddetails(iprincipal user) { using (hostingenvironment.impersonate()) using (var domain = new principalcontext(contexttype.domain, "test.com")) using (var usr = userprincipal.findbyidentity(domain, user.identity.name)) { if (usr == null) { return; } session.add("userdisplayname", usr.displayname); } } now hosted app iis windows authentication enabled. when browsing it, it's prompt username , password...

c# - How to get values from a text file and set them in a Textbox? -

this question has answer here: c# put string textbox 3 answers here problem: i've got 2 classes. form 1 creates .txt-file , sets 2 values (strings) in it. want these 2 strings pressing button(bdirekt), , set each string in textbox in form 2. form 1 (should correct far know, please tell me if i'm wrong): public void txfw() { string txbetrag = gbetrag.text; string txmonate = gmonate.text; string[] vars = new string[] { txbetrag, txmonate }; using (streamwriter sw = new streamwriter(@"c:\users\p2\desktop\variablen.txt")) { foreach (string s in vars) { sw.writeline(s); } } } form 2 (got no idea how go ahead): private void bdirekt_click(object sender, routedeventargs e) { using (streamreader sr = new streamreader(...

swift - How to handle error with Realm during writing? -

i'm used working sql database, i'm new realm and, far, i'm impressed ease of use of new mobile database. there don't undestand: how handle error throwing? take simple example: i want store in realm db market stocks. each stock has "symbol" unique identifier: appl apple inc, tsla tesla motors inc, etc. believe make sense declare these symbols primary keys, since it's not possible have multiple times same symbol in database when user clicks on symbol (among list of symbols), symbol saved in db. in raywenderlich tutorial , said: "to simplify code required in tutorial, you’ll used try! when calling realm methods throw error. in own code, should using try , / catch catch errors , handle them appropriately." so according following pattern: do { try realm.write { realm.add(symbol) } } catch let error nserror { print("something went wrong: \(error.localizeddescription)") } so far makes sense. , if user...

java - Static or new instance for every object? -

i saw piece of code looks public class { public void dosomething(b b) { b.addsometing("queue1", getdefault()); b.addsometing("queue2", getdefault()); b.addsometing("queue3", getdefault()); } private c getdefault() { c c = new c(); c.setautocreate(true); c.setexired(false); c.setdelay(3500); return c; }} if put c c var. (which default objects of class ) every object of class a , use lot of memory large of objects of class a , maybe better make c c static ? create 1 instance of class c whole class , use every object of class a . if ,after code like public class { private static c c = new c(); static { c.setautocreate(true); c.setexired(false); c.setdelay(3500); } public void dosomething(b b) { b.addsometing("queue1", c); b.addsometing("queue2", c); b.addsometing("queue3", c); } } i think it's better way , perhaps i'm wrong . please give ...

Mysql Triggers for timestamps -

i have mysql table several columns : id, starttime (timestamp), endtime (timestamp), status. i add triggers : automatically set timestamp 'starttime' field when new entry created automatically set timestamp 'endtime' field when corresponding line 'status' set "closed" newbie in mysql, have difficulties declaring these triggers... thank help, here complete solution : (for drupal use) trigger 1 : $slqquery = 'create trigger `trigger_name` '; $slqquery .= 'before insert on `table_name` '; $slqquery .= 'for each row begin set new.starttime=now(); end;'; $query = db_query($slqquery); trigger 2 : $slqquery = 'create trigger `trigger_name` '; $slqquery .= 'before update on `table_name` '; $slqquery .= 'for each row begin '; $slqquery .= "if (!(old.column_name <=> new.column_name) , (new.column_name <=> 'whatever')) "; $slqqu...

java - How to use SQL Case in Group by Clause? -

i'm using sql case in select , in group clause , i'm working in java. whenever execute java program says: column 'dbo.john_dashboard.log_date' invalid in select list because not contained in either aggregate function or group clause. my query is: select ep.site_code [site_code], db.[site] [site], db.[utility] [utility], case ? when 'raw' dateadd(mi,datediff(mi,0,db.[log_date]),0) when 'hour' dateadd(hh,datediff(hh,0,db.[log_date]),0) when 'day' dateadd(dd,datediff(dd,0,db.[log_date]),0) when 'week' dateadd(wk,datediff(wk,0,db.[log_date]),0) when 'month' dateadd(mm,datediff(mm,0,db.[log_date]),0) when 'year' dateadd(yy,datediff(yy,0,db.[log_date]),0) else db.[log_date] end [log_date], sum(case when db.[value] >= 0 db.[value] else 0 end) [value], sum(case when db.[cost] ...

php - Joins in Laravel and showing data in a view -

how use aliases of table use in joins in view.i write following join query $show data = db::table('jobs_users') ->join('jobs', 'jobs_users.job_id', '=', 'jobs.id') ->join('users u1', 'jobs_users.user_id', '=', 'u1.id') ->join('users t1', 'jobs_users.trainer_id', '=', 't1.id') ->get(); i have 2 table jobs , users , ids stored in pivot table. in user table have user trainer , user student. want show name of job, student , trainer in view. getting name of job, trainer not getting name of student. in view use join result follows @for each ($show data $u) <td> {{$u->company name}} // job name </td> <td> {{$u ->user name}} //trainer name </td> <td> {{$u->user name}}</td> // student name </tr> @end each in la ravel 5.2 user table p...

java - Vulnerabilities using model beans in view JSP -

i saw hundreds of examples in spring , struts model beans used in view , know if vulnerability , best approach solve it. a dumb example. have model bean: public class user { private string name; private string pass; //getters , setters } and have views (jsp) adminview: view allowed admin have form 2 fields (name , password). userview: view common users have form 1 field (name) in service layer (which should abstract view) have method: if(pass.isempty) createnormaluser(); else createadminuser(); in userview intruder use both fields (modifying data in browser example) due opened in both views (userview , adminview) because same bean (user). ok dumb example in complex webapp priori can not guarantee behavior model beans avoid because can have complex business logic , hundred of cases modify bean produce unwanted behavior. more, having in mind service layer should independent view layer. so necessary control in controllers layer (controllers in s...

php - CORS request in AngularJs -

i have created mail service on php, service send letter user. here code: <?php require 'vendor/autoload.php'; header('content-type : application/json'); header('access-control-allow-origin: *'); header('access-control-allow-methods: post, get, put, delete, options'); header('access-control-allow-headers: x-requested-with, content-type'); $response = array( 'text' => ''); if(!empty($_post)){ $json = json_decode($_post["req"]); $key = $json->key; $sub = $json->subject; $toemail = $json->emailto; $fromemail = $json->emailfrom; $html = $json ->html; $sendgrid = new sendgrid($key); $email = new sendgrid\email(); $email->addto($toemail) ->setfrom($fromemail) ->setsubject($sub) ->sethtml($html); $sendgrid->send($email); $response['text'] = 'email sent '.$fromemail.' to'. $toemail.'. success.'; }else{ $response[...