Monday, 15 September 2014

compare different datasets with stacked bar graphs in R -



compare different datasets with stacked bar graphs in R -

i need compare 2 different methods each of them has 3 different results in 1 graph using stacked bar style.

i want draw plot x axis shows experiment , y axis shows results. , each bar fills 3 results in stacked bar format.

experiment method resuult1 result2 result3 1 m1 1 2 3 1 m2 4 5 6 2 m1 7 8 9 2 m2 10 11 12 3 m1 13 14 15 3 m2 16 17 18

i have code comparing 2 info set how can alter it.

library(ggplot2); pdf(file = '$filename.pdf', width=5, height=5); data1 <- as.matrix(read.table('$input_file1', header = t)); data1.experiment <- as.numeric(data1[,\"experiment\"]); data1.obs <- as.numeric(data1[,\"result1\"]); data1.method <- as.factor(data1[,\"method\"]); df <- data.frame(data1.experiment, data1.method, data1.obs);

orderlist = c("70", "100", "130", "160", "190", "260");

ggplot(df, aes(x = data1.experiment, y = data1.obs, fill = data1.method), ylim=c(60000, 2800000)) + geom_bar(stat='identity', position='dodge')+ labs(x='$xlabel',y='$ylabel', fill='methods') + scale_fill_manual(values = c('red','blue'), labels = c('dtb-mac', 'ieee802.11p')) + scale_x_continuous(breaks = orderlist)+ theme(legend.position = c(1, 1), legend.justification = c(1, 1), legend.background = element_rect(colour = na, fill = 'white'));

you said need compare methods. if represent experiment on x-axis , result on y how represent method??? way of doing using facet. here code how using ggplot2.

dat <- read.csv("data.csv") library(reshape2) library(ggplot2) dat1 <- melt(dat,id.vars = c("experiment","method")) p <- ggplot(dat1,aes(experiment,value,fill=variable))+geom_bar(stat="identity")+ facet_wrap(~method,nrow=1) p

r

c# - How to best map a string array from a legacy database to EF5 property? -



c# - How to best map a string array from a legacy database to EF5 property? -

we need map string column database, used array of values, list of business entities in entity framework 5.

in database info stored string of length 12, each character in string defines whether enabled/disabled. value of 0 character means item disabled, value of 1 character means enabled.

for illustration if first , sec items enabled , rest disabled value in db 110000000000.

in business entities want these configurations represented list manipulation , binding presentation layer easier, ideally represented list of objects containing index value , boolean define whether active or not.

normalizing database sadly not option, in active utilize other applications.

we perhaps create view in database , map that, or additional property in entity marked "not mapped database" create transformation each has limitations.

and of course of study happens in more 1 place if can define pattern case can reuse way throughout project , save hair.

any suggestions on way accomplish this?

you should able accomplish fluent api

something imagining needing.

[complextype] public class magicstring { public string key { get; set; } public <ilist> yourmagicallist { get; set; } } public class context : dbcontext { public dbset<someconfigurationobject> configurationobjects { get; set; } protected override void onmodelcreating(dbmodelbuilder modelbuilder) { modelbuilder.entity<someconfigurationobject>().property(u => u.magicstring.key) .hascolumnname(""yourcolumn"); } }

c# asp.net-mvc entity-framework

ember.js - Ember - binding Ember.select in a component -



ember.js - Ember - binding Ember.select in a component -

i inherited ember project , have been learning go along. several questions deal ember.select bindings in controller/view context. im working in component context , having issues translating advice & help.

and may not need. goal have select menu alter based on select , vice versa. if user chooses measurementtype below should cut down units of measure (uoms) list of measurement type. if there no measurement type , user chooses uom measurement type should switch 1 used uom.

handlebars code:

{{! ############## }} {{! # meas. type # }} {{! ############## }} {{#unless hasmeasurementtype}} <td class='col-lg-1'><span class="label label-default">{{unbound attribute.measurementtype}}</span></td> {{else}} <td class='col-lg-1'> {{view em.select content=measurementtypes optionvaluepath="content.name" optionlabelpath="content.name" value=attribute.measurementtype }} </td> {{/unless}} {{! ############## }} {{! # uom # }} {{! ############## }} <td class='col-lg-1'> {{view em.select content=uoms optionvaluepath="content.name" optionlabelpath="content.name" value=attribute.uom }} </td>

coffee script:

app.numberattributecomponent = ember.component.extend( tagname: 'tr' attributebindings: ['data-id'] precisions: [0, 1, 2, 3, 4, 5, 6] 'data-id': ember.computed.oneway('attribute.id') 'hasmeasurementtype': false attributemeasurementtype: '' attributeuom: '' sethasmeasurementtype: (-> attribute = @.get('attribute') @.set('attributemeasurementtype', attribute.get 'measurementtype') console.log("mt: " + @get 'attributemeasurementtype') @.set('hasmeasurementtype', ember.isnone(@get 'attributemeasurementtype')) ).on("init") setattributeuom: (-> attribute = @.get('attribute') @.set('attributeuom', attribute.get 'uom') console.log("uom: " + @get 'attributeuom') ).on("init") setmeasurementtypelookup: (-> store = specx.__container__.lookup('store:main') store.find('measurementtype').then ((measurementtypes) => @set 'measurementtypes', measurementtypes ) ).on("init") getalluoms: (-> console.log("get uoms") attribute = @.get('attribute') store = specx.__container__.lookup('store:main') store.find('uom').then ((uoms) => @set 'uoms', uoms ) ) getuomsbymeasurementtype: (-> console.log("get uoms") attribute = @.get('attribute') store = specx.__container__.lookup('store:main') store.find('uom').then ((uoms) => @set 'uoms', uoms.filterby('measurementtype',attribute.get 'measurementtype') ) ) updateuom: (-> console.log("in updateuom") attribute = @get 'attribute' if ember.isnone(@get 'attributemeasurementtype') @.getalluoms() else @.getuomsbymeasurementtype() ).observes('attributemeasurementtype', 'attributeuom') # didinsertelement: -> # console.log("in didinsertelement") # attribute = @.get('attribute') # @set 'attributemeasurementtype', attribute.get 'measurementtype' # @set 'attributeuom', attribute.get 'uom' # console.log("new: " + attribute.get 'measurementtype' + "; " + attribute.get 'uom') # # willdestroyelement: -> # console.log("in willdestroyelement") # attribute = @.get('attribute') # @set 'attributemeasurementtype', attribute.get 'measurementtype' # @set 'attributeuom', attribute.get 'uom' actions: edit: -> @toggleproperty('isediting') save: -> model = @.get('attribute') editor = @ @.set('attributemeasurementtype', model.get 'measurementtype') @.set('attributeuom', model.get 'uom') model.save().then ((specification_attribute) => $.growl.notice title: "attribute", message: "attribute saved!" editor.toggleproperty('isediting') ) cancel: -> @toggleproperty('isediting')

ember.js

uinavigationcontroller - ios slideout navigation as second controller in navigation controller -



uinavigationcontroller - ios slideout navigation as second controller in navigation controller -

i have slideout navigation controller (https://github.com/andreamazz/slideoutnavigation) sec controller in navigation controller. navigation controller's root view controller login page. slideout controller has 3 kid controllers. 1 of kid controllers has ability logout, after take user login view controller. trying popping root view controller doesnt seem solution:

[[self parentviewcontroller].navigationcontroller poptorootviewcontrolleranimated:yes]; [self dismissviewcontrolleranimated:yes completion:nil];

what needs happen root controller? thanks

ios uinavigationcontroller

character encoding - What is the charset of URLs? -



character encoding - What is the charset of URLs? -

when types url in browser access page, charset used url? there standard? can consider utf-8 used everywhere? characters accepted?

urls may contain subset of ascii, urls valid ascii.

international domain names must punycode encoded. non-ascii characters in path or query parts must encoded, percent-encoding beingness agreed-upon standard.

percent-encoding takes raw bytes , encodes each byte %xx. there's no followed standard on encoding should used determine byte representation. such, it's impossible assume particular character set beingness used in percent-encoded representation. if you're creating links, you're in total command on used charset before percent-encoding; if you're not, you're out of luck. though encounter utf-8, not guaranteed.

url character-encoding

javascript - How to properly prevent bubbling when using toggle()? -



javascript - How to properly prevent bubbling when using toggle()? -

i trying show lists on page load if more 768px hide them if less , create them show on clicking titles.

it works ok not after resizing window , don't why happening? advice?

how should handle bubbling properly?

html:

<nav> <h3 class="nav__title">first</h3> <div class="links"> <ul> <li><a href="#">first one</a></li> <li><a href="#">first two</a></li> <li><a href="#">first three</a></li> </ul> </div> </nav> <nav> <h3 class="nav__title">second</h3> <div class="links"> <ul> <li><a href="#">second one</a></li> <li><a href="#">second two</a></li> <li><a href="#">second three</a></li> </ul> </div> </nav>

js:

(function () { function footerlinks() { if ($(window).width() < 768) { $(".links").hide(); $(".nav__title").on("click", function (e) { e.preventdefault(); $(this).next(".links").toggle("fast"); }); } else { $(".links").show(); } } footerlinks(); $(window).resize(function () { footerlinks(); }); }());

jsfiddle

i think want, adding event handlers every time window resized:

(function () { $(".nav__title").on("click", function (e) { e.preventdefault(); // drop out of function if window big plenty if( $(window).width() >= 768 ){ return; } $(this).next(".links").toggle("fast"); }); function footerlinks() { if ($(window).width() < 768) { $(".links").hide(); } else { $(".links").show(); } } footerlinks(); $(window).resize(function () { footerlinks(); }); }());

http://jsfiddle.net/e64j4/6/

javascript jquery event-bubbling

internet explorer - Methods from Javascript file will load in IE but not Chrome -



internet explorer - Methods from Javascript file will load in IE but not Chrome -

the webpage loading several different javascript files, of show correctly in "sources" tab of chrome's console, trying phone call methods 1 of pages results in console showing either "uncaught reference error: undefined not function" or "uncaught reference error: [name of function] not defined" depending on way function declared1. there's error in chrome console "uncaught syntaxerror: invalid left-hand side in assignment" coming page won't load, isn't nowadays in ie. error comes next function:

listofnumbers.prototype.reset = function () { = new listofnumbers; };

why can't access of functions on page?

1 difference in error messages that

variablename = function() {}; produces undefined not function, while function functionname() {} produces functionname not defined.

the invalid left-hand side error explained in javascript function using “this = ” gives “invalid left-hand side in assignment”. ie give same error if seek run function, can see entering

var test = new listofnumbers(); test.reset();

in ie's console.

ie detects error when attempting run function, chrome observe on page load , prevent in javascript file running, though still show file under "sources". fixing invalid left-hand side should solve chrome problem.

javascript internet-explorer google-chrome

javascript - getItemByFileId undefined in onSubmitted with FineUploader -



javascript - getItemByFileId undefined in onSubmitted with FineUploader -

i'm working off angularjs example

at point, uploads working (to s3), onsubmit callback exploding: [fine uploader 5.0.2] caught exception in 'onsubmitted' callback - undefined not function

this may cofeescript fat arrow problem, since transpiled illustration coffeescript build environment (and preference coffeescript), i'm stumped anyhow.

here's relevant dict options.

callbacks: { onsubmitted: (id, name) => console.log "calling onsubmitted(#{id}, #{name})" console.log "this shouldn't undefined: #{@getitembyfileid}" # _is_ undefined $file = $(@getitembyfileid(id)) console.log $file $thumbnail = $file.find(".qq-thumbnail-selector") $thumbnail.click -> openlargerpreview( $scope, $(element), largepreviewsize, id, name ) homecoming homecoming }

here's skinny arrow version (see comments below) rendered js:

callbacks: { onsubmitted: function(id, name) { var $file, $thumbnail; console.log("calling onsubmitted(" + id + ", " + name + ")"); $file = $(getitembyfileid(id)); console.log($file); $thumbnail = $file.find(".qq-thumbnail-selector"); $thumbnail.click(function() { openlargerpreview($scope, $(element), largepreviewsize, id, name); }); } }

the result (when upload something)

[fine uploader 5.0.2] received 1 files or inputs. [fine uploader 5.0.2] attempting validate image. calling onsubmitted(0, imag0161.jpg) shouldn't undefined: undefined [fine uploader 5.0.2] caught exception in 'onsubmitted' callback - undefined not function

as indicated in code, problem (as understand it) @getitembyfileid not defined on this properly, (again, understand it) this should fineuploaders3 object.

there's no need utilize fat arrow in fine uploader event handlers. context of event handler set fine uploader instance (by fine uploader). utilize "skinny arrow".

javascript coffeescript this fine-uploader

android - Resume old activity by passing new data in bundle -



android - Resume old activity by passing new data in bundle -

i have couple of activities , b, c. activity starts b , b starts c , on. in app have set navigation drawer allows users go activity a. when user goes activity have passed flags don't restart activity resumes it.

intent = new intent(activity, a.class); intent.setflags(intent.flag_activity_clear_top | intent.flag_activity_single_top);

now m trying pass info using bundles.

bundle.putint("selectedtab", featured_coupons); intent.putextras(bundle);

but in activity bundle null.

if(bundle != null) { if(bundle.containskey("selectedtab")) { int tab = bundle.getint("selectedtab"); } }

you're going things in wrong way.

if want set integer intent extras don't this...

bundle.putint("selectedtab", featured_coupons); intent.putextras(bundle);

from docs putextras(bundle extras)...

add set of extended info intent. the keys must include bundle prefix, illustration app com.android.contacts utilize names "com.android.contacts.showall".

instead use...

intent.putextra("selectedtab", featured_coupons);

this isn't real cause of problem however. sumit uppal mentions, should implement onnewintent(intent intent) in activity a. can utilize set 'current' intent new intent...

@override protected void onnewintent(intent intent) { if (intent != null) setintent(intent); }

then in onresume() can use...

intent intent = getintent();

...and bundle intent.

android android-intent android-activity android-bundle

javascript - What is data-toggle="modal" used for? -



javascript - What is data-toggle="modal" used for? -

this question has reply here:

the data-toggle attributes in twitter bootstrap 8 answers

i have button code created it. here button code:

<button class="demo btn btn-primary" data-toggle="modal" href="#long" onclick="javascript:add();"><i class="icon-plus-sign icon-white"></i> add together employee</button>

i've edit function related button (send new info button, , phone call in function), nil happened. tried delete data-toggle="modal", pop didn't show. so, wonder, data-toggle="modal" utilize for?

i thought here link modal:

<script src="js/bootstrap-modalmanager.js"></script> <script src="js/bootstrap-modal.js"></script>

can explain me data-toggle="modal"? give thanks you.

from bootstrap docs

<!--activate modal without writing javascript. set data-toggle="modal" on controller element, button, along data-target="#foo" or href="#foo" target specific modal toggle.--> <button type="button" data-toggle="modal" data-target="#mymodal">launch modal</button>

javascript jquery

java - why does SBT insist on recompiling all files when I switch machines? -



java - why does SBT insist on recompiling all files when I switch machines? -

i'm using cluster multiple machines share filesystem. managed using slurm, , in order compute time, request node period of time , 1 of 100 or more possible machines, name 'c222-103'. when switch machines, sbt insists on recompiling every single 1 of scala , java files rather ones have changed.

this doesn't happen if lastly compilation on same machine next one, e.g. if compile multiple times in single session or if request new compute session , happen same node lastly time, somewhere sbt noting machine i'm on , deciding recompile if changes, though paths same due shared filesystem.

how debug and/or prepare problem?

java scala sbt cluster-computing recompile

ios - Setting custom divider image in UITabBar using setDividerImage:forLeftState:rightState: -



ios - Setting custom divider image in UITabBar using setDividerImage:forLeftState:rightState: -

https://developer.apple.com/library/ios/documentation/userexperience/conceptual/uikituicatalog/uitabbar.html

in above link images section "by default, there no divider image between tabs on tab bar. can set custom divider images each combination of left , right tab command states using setdividerimage:forleftstate:rightstate:method. if utilize custom dividers, create sure set divider images combinations of tabs states: left selected, right selected, or both unselected."

how can utilize setdividerimage:forleftstate:rightstate: method setting custom divider in uitabbar?

i tried many options [uitabbar appearance], [uitabbaritem appearance], [uitabbarcontroller appearance], self.tabbarcontroller.tabbar , self.tabbarcontroller.tabbaritem xcode code completion didn't show me aforesaid method.

i using xcode 5.1.1 ios sdk 7.1.

looking forwards hear guys!

thanks & regards,

mihir

ios objective-c uitabbarcontroller uitabbar uitabbaritem

AngularJS - Using Directive in template -



AngularJS - Using Directive in template -

i have question custom directive.

is possible

create custom directive provide templateurl attribute , in template url create utilize of ng-grid attribute ?

i tried although grid not getting rendered if declared in template. how template code looks like

<div class="gridstyle" ng-grid="gridoptions"> </div>

and controller code within custom directive looks

treeapp.controller('treecontroller',function ($scope, $http,treefactory) { console.log("calling controller"); treefactory.gettreedata().success(function(data){ $scope.mydata = data; $scope.gridoptions = { data: 'mydata' }; });;

and how custom directive looks like

treeapp.directive('ngtree', function(treefactory) { homecoming { restrict: 'a', require: '^ngmodel', templateurl: 'js/angular/templates/ngtree-template.html', });

angularjs-directive

asp.net - how to disable a pageload property under certain circumstances -



asp.net - how to disable a pageload property under certain circumstances -

in .net have gridview has display on mainpage default settings. set in pageload code. in same page have "list" button; people take date etc. , when press button gridview loads info stored procedure. set code under list button event. after people press list button , gridview comes needed data, if press else (because of page refresh itself) gridview turns default settings.

how maintain gridview wanted data?

protected void page_load(object sender, eventargs e) {

opsbelgegridview.datasource = db.opshavuzgetir(); opsbelgegridview.databind();

protected void listelebtn_click(object sender, eventargs e) {

opsbelgegridview.datasource = db.opshavuzdetaylistelebtn(tarih1.tostring("yyyy-mm-dd"), tarih2.tostring("yyyy-mm-dd"), durumdd.selecteditem.text.tostring(), islemtipdd.selecteditem.text.tostring()); opsbelgegridview.databind();

you can utilize ispostback() , load initial grid on first load of page. if grid info changes stay.

private void page_load() { if (!ispostback) { opsbelgegridview.datasource = db.opshavuzgetir(); opsbelgegridview.databind(); } }

asp.net events button gridview pageload

what can I do with hadoop and elasticsearch together? -



what can I do with hadoop and elasticsearch together? -

i'm reading hadoop elasticsearch, i'm confused how works.

i guess in case elasticsearch substitute hdfs/hbase, write hadoop jobs , process info in elasticsearch.

is correct?

if yes, works hive , pig too?

you can utilize elasticsearch in hadoop :

input , output mapreduce input (storage) hive , pig write , read straight in elasticsearch cascading

hadoop elasticsearch

ios - how can i get app store link before approve by apple -



ios - how can i get app store link before approve by apple -

this question has reply here:

link app in app store before approved? 2 answers

in application mail service send , in mail service client want send link of application in message body while application still not approved apple how can link?

when create app in itunesconnect , can see link "view in app store"

ios objective-c

angularjs - Pass $http from Controller to Directive -



angularjs - Pass $http from Controller to Directive -

i need utilize $http.get grab json file in controller:

module.controller 'samplemapcontroller', ($http, $scope) -> $http.get('../../highcharts/mapdata/world.geo.json'). success (data) -> $scope.mapdata = info # works , logs out correctly

and pass directive, uses json mapping purposes:

module.directive 'mapdirective', () -> require: '?samplemapcontroller' templateurl: '../template.html' link: ($scope) -> console.log $scope.mapdata # undefined $scope.$watch 'an.object.that.contains.more.data', (newvalue) -> chart = new highcharts.chart({ chart: { renderto: 'container div' } # ... utilize $scope.mapdata somewhere in here render global map }) true

but i'm not having luck accessing $scope, , not sure if should putting on $rootscope, or event require controller.

i'm generating high charts map within of link:

a detailed explanation of i'm looking in abstracted jsbin.

you cant inject $scope in directives , instead can pass scope in link function in directive

should utilize : link:function(scope,element,attributes){ // notice function scope // have access scope , , can whaterver want . }

note in dependency injection philosophy , in controller's can inject $scope dependency , , $ sign known in angularjs .and other thing , dependency injection in controllers not follow order , mean consider :

app.controller('youcontroller',function($scope,$location,$http,...){ // see in injection , injected $scope first , doesn't matter , mean can inject $location first , , $scope , , ... // there no order here ! // stuff here });

but in directives , order of passing dependencies link function is important, on other hand , names not of import !

app.directive('yourdirective',function(){// cannot inject $scope here ! homecoming { link : function(scope,element,attributes){// order of import // comes first , scope // sec element // 3rd attributes // : // function(scooooope,elem,att) // see changed names , because here names not of import , order of import } } });

edit : cleared code : :(

module.directive('mapdirective',function(){ return{ require: '?samplemapcontroller' templateurl: '../template.html' link: function(scope){ console.log scope.mapdata // please test , if still undefiend ; } } })

angularjs coffeescript angularjs-scope angularjs-http

mysql - How to modify data type of a column that is foreign key or primary key? -



mysql - How to modify data type of a column that is foreign key or primary key? -

i have 3 tables. 1 course, section , other prerequisite.

create table course( course_number int(11) not null auto_increment, course_name varchar(20) not null, credit_hours int(11) not null, section varchar(5) not null, primary key (course_number) ) create table section ( section_id int(11) not null, course_number` int(11) not null, semester varchar(6) not null, year year(4) not null, instructor varchar(20) default null, primary key (section_id), foreign key (course_number) references course of study (course_number) ) create table prerequisite( course_number int not null auto_increment, prerequisite int not null, primary key (course_number), foreign key (prerequisite) references course(course_number) );

i want alter datatype of course_number in both tables, when run query

alter table course of study alter course_number course_number varchar(20);

i see next error:

cannot alter column 'course_number': used in foreign key constraint 'section_fk' of table 'university.section'

what problem in here? best solution? saying best solution, mean, not loosing info or dropping table , creating scratch.

drop foreign key, alter both tables , add together foreign key. btw thought name constraints explicitly. have constraint name in catalog:

select constraint_name information_schema.referential_constraints table_name = 'prerequisite' , referenced_table_name = 'course' alter table prerequisite drop constraint ...; alter table course of study alter course_number course_number varchar(20); alter table prerequisite alter course_number course_number varchar(20); alter table prerequisite add together constraint <name> foreign key (course_number) references course of study (course_number) <actions>;

mysql sql

runtime - Handling screen rotation changes in android? -



runtime - Handling screen rotation changes in android? -

my problem unable handle portrait , landscap mode operations. in screen have 1 register form in gone state. when click register button come. when goes landscape in if rotate screen come 1 time again in gone in portrait. please give suggestions how can handle that.

code:

@override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.equipmentmanagement); context = this; insertanalasysmethodvlaues(); insertequipmenttypevalues(); initui(); showequipmenttypespinner(); showanalasistypespinner(); equipmenttable = new equipmenttable(context); listequipment = equipmenttable.selectallrecords(); showrecords(listequipment); equipment_add.setonclicklistener(this); equipment_search.setonclicklistener(this); search.setonclicklistener(this); insert.setonclicklistener(this); cancel.setonclicklistener(this); equipmentmanagement_text.setonclicklistener(this); equipment_loadall.setonclicklistener(this); equipment_type_spinner.setonitemselectedlistener(this); analysis_method_spinner.setonitemselectedlistener(this); } @override public void onconfigurationchanged(configuration newconfig) { super.onconfigurationchanged(newconfig); }

what have save if login displayed user. 1 way overriding onsaveinstancestate() , adding info bundle:

@override protected void onsaveinstancestate(bundle outstate) { super.onsaveinstancestate(outstate); outstate.putboolean("login_visible", isloginvisible); }

and in oncreate can value savedinstancestate this:

@override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); ... if(savedinstancestate != null) { boolean isloginvisible = savedinstancestate.getboolean("login_visible"); if(isloginvisible) { // set visibility of login view.visible! } } }

android runtime state landscape handle

javascript - Easeljs: When loading image on to easeljs bitmap class, does it use original image? -



javascript - Easeljs: When loading image on to easeljs bitmap class, does it use original image? -

i using easeljs on website. tried load image on bitmap object createjs.bitmap. since not using total size image, if scaled bitmap, downsample original image accordingly.

there no down-sampling of actual image, pixels laid downwards on canvas down-sampled.

to down-sample source image, scale easeljs bitmap, retrieve canvas image using stage.todataurl(). returns image used elsewhere.

javascript html image easeljs

php throw exception stop execution -



php throw exception stop execution -

i have code:

function divide($a,$b){ try{ if($b==0){ throw new exception("second variable can not 0"); } homecoming $a/$b; } catch(exception $e){ echo $e->getmessage(); } } echo divide(20,0); echo "done";

it throws exception when sec parameter 0. how can stop done printing?

don't grab exception in divide() , grab later:

function divide($a,$b){ if($b==0){ throw new exception("second variable can not 0"); } homecoming $a/$b; } seek { echo divide(20,0); echo "done"; } catch(exception $e){ echo $e->getmessage(); }

php exception

c# - ASP.NET MVC 4: Only allow one request at a time -



c# - ASP.NET MVC 4: Only allow one request at a time -

in asp.net mvc application, want handle requests sequentially; no action/controller code should executed concurrently another. if 2 requests come in @ similar times, should run first 1 first, sec 1 when first 1 done.

is there improve way of doing besides using global lock variable?

edit: application more of batch/service on web performs web service calls , cleans database. different urls in site lead different batch operations. not site end-users. thus, need create 1 request url (which batch operations) done @ time, otherwise batch operation corrupted if code runs concurrently itself, or other batch operations. in fact, if request comes when 1 executing, should not run @ all, after previous 1 finishes; should give error message.

i know if there way in iis instead of code. if have global lock variable, create code more complicated, , might run in deadlock lock variable set true never can set false.

edit: sample code of implementation plan

[httppost] public actionresult batch1() { //config.lock global static boolean variable if(config.lock) { response.write("error: batch process running"); homecoming view(); } config.lock = true; //run batch calls , web services (this code cannot interleaved executebatchcode2() or itself) executebatchcode(); config.lock = false; homecoming view(); } [httppost] public actionresult batch2() { if(config.lock) { response.write("error: batch process running"); homecoming view(); } config.lock = true; //run batch calls , web services (this code cannot interleaved executebatchcode1() or itself) executebatchcode2(); config.lock = false; homecoming view(); }

would need worried case code not reach config.lock = false, resulting in config.lock = true forever, causing no more requests served?

you write attribute:

public class exclusiveactionattribute : actionfilterattribute { private static int isexecuting = 0; public override void onactionexecuting(actionexecutingcontext filtercontext) { if (interlocked.compareexchange(ref isexecuting, 1, 0) == 0) { base.onactionexecuting(filtercontext); return; } filtercontext.result = new httpstatuscoderesult(httpstatuscode.serviceunavailable); } public override void onresultexecuted(resultexecutedcontext filtercontext) { base.onresultexecuted(filtercontext); interlocked.exchange(ref isexecuting, 0); } }

then utilize on controllers/methods want control:

[exclusiveaction] //either here, every action in controller public class mycontroller : controller { [exclusiveaction] //or here specific methods public actionresult dothething() { //foo homecoming someactionresult(); } }

c# asp.net-mvc request sequential controller-action

jquery - How to remove clicked div and corresponding item in menu -



jquery - How to remove clicked div and corresponding item in menu -

i wanted removeclass click parent remove , iconclass remove please helpme......

<div class="itemlabel"> <div class="icon"><a href="#select1">1</a></div> <div class="icon"><a href="#select2">2</a></div> <div class="icon"><a href="#select3">3</a></div> <div class="icon"><a href="#select4">4</a></div> <div class="icon"><a href="#select5">5</a></div> <div class="icon"><a href="#select6">6</a></div> <div class="icon"><a href="#select7">7</a></div> <div class="icon"><a href="#select8">8</a></div> <div style="clear:both"></div> </div>

//css

.remove{ display:inline-block; padding:20px; background-color:red; color:#fff; margin:10px; cursor:pointer; }

// jquery

$(".remove").on('click', function() { $(this).parent().remove(); $(".itemlabel .icon").remove(); /*this problem .. want 1 icon remove remove */ });

see illustration how utilize thesame number remove iconclass

http://jsfiddle.net/kisspa/74xsc/

it remove clicked div , corresponding itemlabel div

try this

$(".remove").on('click', function() { $(this).parent().remove(); var idd=$(this).next().attr('id') $('.itemlabel div').find('a[href="#'+idd+'"]').parent().remove(); });

demo

jquery css

html - SCSS Grid: more columns in row then maximum margin issue -



html - SCSS Grid: more columns in row then maximum margin issue -

i have own made grid scheme wich supports 12colums. can alter in these variables:

$column-count: 12; $row-max-width: 1024px; $gutter-width-px: 10px !default; $gutter-width-procent: percentage($gutter-width-px / $row-max-width);

this how sizes calculated:

@function calculate-one-column() { $a: 100%; @if ($gutter-width-px > 0px) { $a: ($a - ($gutter-width-procent * ($column-count - 1))); } @return $a / $column-count; } @function calculate-each-gutter() { @if ($gutter-width-px > 0px) { @return $gutter-width-procent; } @return 0; } @function calculate-function($function, $size, $first-child: false, $responsive: false) { $each-column: calculate-one-column() * $size; $each-gutter: calculate-each-gutter() * ($size - 1); @if ($function == 'size') { @return $each-column + $each-gutter; } @else if ($function == 'offset' , $first-child == false) , ($responsive == false) { @return $each-column + $each-gutter + ($gutter-width-procent * 1.5); } @else if ($function == 'push' or $function == 'pull') , ($responsive == false) or ($function == 'offset' , $first-child == true) { @return $each-column + $each-gutter + $gutter-width-procent; } @else if($function == 'offset' or 'push' or 'pull') , ($responsive == true) { @return auto !important; } } @mixin make-grid-sizes() { @for $index 1 through $column-count { &.#{$column-size}-#{$index} { width: calculate-function('size', $index); } } }

the html markup row 12 columns in of size-1 looks this:

<div class="row"> <div class="column size-1">...</div> <div class="column size-1">...</div> <div class="column size-1">...</div> <div class="column size-1">...</div> <div class="column size-1">...</div> <div class="column size-1">...</div> <div class="column size-1">...</div> <div class="column size-1">...</div> <div class="column size-1">...</div> <div class="column size-1">...</div> <div class="column size-1">...</div> <div class="column size-1">...</div> </div>

ofcourse, can aswell:

<div class="row"> <div class="column size-2">...</div> <div class="column size-2">...</div> <div class="column size-2">...</div> <div class="column size-2">...</div> <div class="column size-2">...</div> <div class="column size-2">...</div> </div>

or other combinations.

first, looks (12 columns of size-1, 1 row):

i had give :first-child margin-left of 0, , :last-child margin-right of 0.

this because every column has margin on every side of $gutter-width-procent / 2:

margin: 0 #{$gutter-width-procent / 2};

then looks (this 1 row):

this working perfect, limited putting 12 columns in 1 row.

now when add together illustration 24 columns of size-1 in row, looks (still same row):

i able prepare adding these css rules it:

(each lastly column margin-right of 0 , each first column margin-left of 0)

&:first-child, &:nth-of-type(#{$column-count}n + 1) { margin-left: 0; } &:last-child, &:nth-of-type(#{$column-count}n) { margin-right: 0; }

but worked column size-1.

question

how can create every first column in 'row' in row html elementhas margin-left 0.

and same lastly column, margin-right of 0.

demo here

one solution add together negative margins .row:

.row { margin: 0 -#{$gutter-width-procent / 2}; }

then can remove &:first/last/nth-child-selectors col gutters "slip" negative margin space.

updated js-fiddle

i had alter width values (didn't alter all) business relationship added width caused negative margins. bit unfamiliar me since utilize susy takes care of me. need alter function calculating widths somewhat. how did calculation:

$column-count: 12; $row-max-width: 1024px; $gutter-width-px: 10px !default; @function col($cols: 1) { $row-width-neg-margin-width: $row-max-width + $gutter-width-px; @return ( ( $row-width-neg-margin-width / ($column-count / $cols) ) - $gutter-width-px ) / $row-width-neg-margin-width * 100%; }

html css grid sass

javascript - Having trouble in sending the results from pdo to ajax -



javascript - Having trouble in sending the results from pdo to ajax -

i want if user registered pdo provide info , send ajax , ajax message if user registered or not. working after set status in pdo , wont insert no more , ajax tells "error registering user!" time.

script:

<script type="text/javascript"> $(document).ready(function() { $('#submit').click(function (e) { e.preventdefault(); var info = {}; data.name = $('#name').val(); data.age = $('#age').val(); data.gender = $('#gender').val(); data.address = $('#address').val(); data.image = $('#imginp').val(); $.ajax({ type: "post", url: "user.php", data: data, cache: false, success: function (response) { if (number(response) == 1) { alert("user registered"); } else { alert("error registering user!"); } } }); homecoming false; }); }); </script>

user.php:

<?php $host = "localhost"; $user = "root"; $pass = ""; $db = "test"; $dbc = new pdo("mysql:host=" . $host . ";dbname=" . $db, $user, $pass); $dbc->setattribute(pdo::attr_errmode, pdo::errmode_exception); $name = @$_post['name']; $age = @$_post['age']; $address = @$_post['address']; $gender = @$_post['gender']; $imagename = @$_files['image']['name']; $q = "insert students(name, age, address, gender, imagename ) values(:name, :age, :address, :gender, :image)"; $query = $dbc->prepare($q); $query->bindparam(':name', $name); $query->bindparam(':age', $age); $query->bindparam(':address', $address); $query->bindparam(':gender', $gender); $query->bindparam(':image', $imagename); $results = $query->execute(); $results ? echo "1"; : echo "2"; ; ?>

it seems have error in :

$results ? echo "1"; : echo "2"; ;

yours demo

try :

echo $results ? "1" : "2";

working demo

you can see here tutorial.

javascript php jquery ajax pdo

ios - NSNotificationCenter callback while app in background -



ios - NSNotificationCenter callback while app in background -

one question , 1 issue: have next code:

- (void) registerforlocalcalendarchanges { [[nsnotificationcenter defaultcenter] addobserver:self selector:@selector(localcalendarstorechanged) name:ekeventstorechangednotification object:store ]; } - (void) localcalendarstorechanged { // gets phone call when event in store changes // have go through calendar changes [self getcalendarevents]; }

these methods in class/object called calendareventreporter contains method getcalendarevents (in callback).

two things: 1) if app in background callback not run. there way create that? 2) when bring app foreground (after having changed calendar on device) app crashes without error message in debug window or on device. guess calendareventreporter object contains callback beingness garbage-collected. possible? other thoughts on might causing crash? or how see error messages?

1) in order app run in background should using 1 of modes mentioned in "background execution , multitasking section here:

uses location services records or plays audio provides voip services background refresh connection external devices through ble

if not using of above, not possible asynchronous events in background.

2) in order see crash logs/call stack place exception breakpoint or "device logs" section here: window->organizer->devices->"device name" on left->device logs on xcode.

ios objective-c nsnotificationcenter ekeventkit

shell - Problems with basename in a loop -



shell - Problems with basename in a loop -

i new @ shell script programming , i'm trying execute software reads text , perform it's pos tagging. requires input , output, can seen in execute example:

$ cat input.txt | /path/to/tagger/run-tagger.sh > output.txt

what i'm trying execute line not text, set of texts in specific folder, , homecoming output files same name input files. so, tried script:

#!/bin/bash path="/home/rafaeldaddio/documents/" program="/home/rafaeldaddio/documents/lx-tagger/postagger/tagger/run-tagger.sh" arqin in '/home/rafaeldaddio/documents/teste/*' out=$(basename $arqin) output=$path$out cat $arqin | $program > $output done

i tried 1 file , works, when seek more one, error:

basename: operand ‘/home/rafaeldaddio/documents/teste/3’ seek 'basename --help' more information. ./scriptlxtagger.sh: 12: ./scriptlxtagger.sh: cannot create /home/rafaeldaddio/documents/: directory

any insights on i'm doing wrong? thanks.

you don't want quotes around pattern, , quote variables:

for arqin in /home/rafaeldaddio/documents/teste/* out=$(basename "$arqin") output=$path$out "$program" <"$arqin" >"$output" done

shell for-loop

Model form within another model's form in Ruby on Rails -



Model form within another model's form in Ruby on Rails -

i have content model, playlist model , bring together association in model called playlistitem.

this how they're connected:

class content < activerecord::base has_many :playlist_items has_many :playlists, through: :playlist_items end class playlist < activerecord::base has_many :playlist_items, -> { order 'position asc' } has_many :contents, through: :playlist_items end class playlistitem < activerecord::base belongs_to :content belongs_to :playlist end

when edit playlist, form shows field name, that's attribute has. want able add together content playlist (in position, that's playlistitems attribute) within form.

how can that?

this code have now:

<%= form_for(@playlist) |f| %> <div class="field"> <%= f.label :name %><br> <%= f.text_field :name %> </div> <%= f.fields_for :playlist_items |builder| %> <fieldset> <%= builder.label :content, "content id" %><br> <%= builder.text_area :content_id %> </fieldset> <% end %> <div class="actions"> <%= f.submit %> </div> <% end %>

first, can allow playlist model take nested attributes playlist_items.

class playlist < activerecord::base has_many :playlist_items, -> { order 'position asc' } has_many :contents, through: :playlist_items accepts_nested_attributes_for :playlist_items end

then, can add together content_id collection select, create drop downwards selection of contents each playlist item.

<%= f.fields_for :playlist_items |builder| %> <%= builder.label :position %><br> <%= builder.integer :position %><br> <%= builder.label :content %><br> <%= builder.collection_select :content_id, @contents, :id, :title, include_blank: 'please select' %> <% end %>

finally, in controller, you'll need allow playlist items attributes passed params, , set @contents instance variable.

class playlistcontroller < applicationcontroller before_action :load_contents, only: [:new, :edit] def edit @playlist = playlist.find(params[:id]) # build 10 playlist_items added playlist 10.times do; @playlist.playlist_items.build; end end private def load_contents @contents = content.all # or query specific contents you'd end def playlist_params params.require(:playlist).permit(:name, playlist_items_attributes: [:id, :position, :content_id]) end end

remember you'll need build each playlist item you'd use. can in new , edit methods desire.

ruby-on-rails ruby forms model associations

javascript - Jquery- On an Ajax response create row and group them based on column value? -



javascript - Jquery- On an Ajax response create row and group them based on column value? -

i need phone call rest api using ajax. based on ajax response have add together row html table. able accomplish using jquery.

now, want grouping rows based on column in ajax response , show them different groups based on that. mean say... ajax phone call me info required row, when adding table, has go corresponding grouping based on column value... how accomplish this?

any help , ideas welcome.

thanks

i utilize multidimensional array contains of values table. then, each time ajax returns can add together new values array , recreate table right grouping.

javascript jquery ajax jquery-ui jqgrid

android - hasStableIds () in Expandable ListView? -



android - hasStableIds () in Expandable ListView? -

i creating app using expandablelistview ,i referred tutorials .the hasstableids () set false? exact need making hasstableids() false?

documentation of hasstableids()

indicates whether kid , grouping ids stable across changes underlying data.

returns whether or not same id refers same object

it's used when alter info of adapter, everytime alter info expandablelistview should update it's views reflect changes.

if true expandablelistview can reuse same view if id same.

if false should recreate views since can't have thought changes.

the id refer id returned getgroupid , getitemid.

you should override methods too!

some questions:

baseadapter: set hasstableids() false? android - meaning of stableids?

android expandablelistview

Facebook - tag people in posts by a page using API -



Facebook - tag people in posts by a page using API -

i have page , have ipad app. using graph api login facebook user , post photo taken ipad page. thing photos shown in "posted others" section, doesn't show detail default.

so doing posting on page administrator privileges. question - how mention/tag people in post?

they have logged in app can utilize credentials post has done page admin.

anybody has thought of how such thing?

facebook facebook-graph-api tags facebook-page

Android application as a service without activity -



Android application as a service without activity -

i making set of apps , have pretty much same background service of them.

i'm trying create app has service. don't repeat in of them, thing don't need activity. because there no ui needed it, , user can't close except if stop service.

i tried remove activity, app doesn't run or start. my question is: can create app google play services other apps can utilize service.

if yes snippet or sample welcome.

sure! no reason cannot have application service. ...and no need aidl unless want to.

the problem is, how create application run. when create application activity, add together intent filter, in manifest, makes activity startable launcher. if there's no activity, you'll have find way start it.

it easy do, though. fire intent 1 of other programs, this:

startservice(new intent("my.service.intent"));

... service registered manifest, this:

<service android:name=".someservice" > <intent-filter> <action android:name="my.service.intent"/> </intent-filter>

you utilize intent pass parcelable parameters service, , service can reply broadcasting intents back.

of course of study startservice , broadcastintent bit clunky if need complex api between applications , service. if need richer, will want aidl , bound service.

edited add together intent filter

android android-service google-play-services background-service

windows phone 8.1 - How to read data files included in the app -



windows phone 8.1 - How to read data files included in the app -

for programme have include huge index , info files in programme bundle. because universal app, have included these files in folder named "data" within "shared" project.

now seek read:

storagefile file = await applicationdata.current.localfolder.getfileasync("data/"+filename); stream stream = (await file.openreadasync()).asstreamforread(); binaryreader reader = new binaryreader(stream); windows.storage.fileproperties.basicproperties x = await file.getbasicpropertiesasync();

i system.argumentexception "mscorlib.ni.dll" @ first line. what's wrong?

if can help me , file, want find filesize. hope, can find info within fileproperties (last line of code).

then want set filepointer within file , read defined number of binary data. can without reading whole file in memory?

what trying access localfolder, not same package.current.installedlocation.

if want access files included package, can illustration - by using uri schemes:

class="lang-cs prettyprint-override">storagefile file = await storagefile.getfilefromapplicationuriasync(new uri(@"ms-appx:///data/"+filename)); using (stream stream = (await file.openreadasync()).asstreamforread()) using (binaryreader reader = new binaryreader(stream)) { windows.storage.fileproperties.basicproperties x = await file.getbasicpropertiesasync(); }

or - getting file package, can access storagefolder - pay attending here utilize right slashes (as may source of exception):

class="lang-cs prettyprint-override">storagefile file = await windows.applicationmodel.package.current.installedlocation.getfileasync(@"data\" + filename); using (stream stream = (await file.openreadasync()).asstreamforread()) using (binaryreader reader = new binaryreader(stream)) { windows.storage.fileproperties.basicproperties x = await file.getbasicpropertiesasync(); }

note i've set stream , binaryreader using, idisposable , it's suitable release resources no longer needed.

note when shared project has name mysharedproject, have modify path of above uri:

class="lang-cs prettyprint-override">storagefile file = await storagefile.getfilefromapplicationuriasync(new uri(@"ms-appx:///mysharedproject/data/"+filename));

or obtain suitable storagefolder:

class="lang-cs prettyprint-override">storagefile file = await windows.applicationmodel.package.current.installedlocation.getfileasync(@"mysharedproject\data\" + filename);

one remark after discussion:

when add together file .txt extension project, build action default set content. when add together file .idx extension, i've checked, build action set none default. include files in package, alter them content.

windows-phone-8.1 win-universal-app

angularjs - Access Single Child Controller From Repeat? -



angularjs - Access Single Child Controller From Repeat? -

the best way explain example:

<table ng-controller="groupofpeoplecontroller"> <tr ng-repeat "person in peoples"> <td>{{person.name}}</td> <td><button ng-click="load_data(person.id)">load data</button> <td><div class="persondata" ng-controller="persondatacontroller"></div></td> </tr> </table>

what i'm looking populate div.persondata it's own data. have function in groupofpeoplecontroller called load_data(id):

// groupofpeoplecontroller $scope.load_data = function(id){ $rootscope.$broadcast('load_data'id); }

that pass kid element controller persondata.

// persondatacontroller $scope.$on('load_data',function(e,id){ // impact div within current loop... });

the problem is, attached every loop of persondata. click on 1 person, affects every row, seeing attached same controller.

how go making separate instances of persondata? broadcast wrong way go this?

do not broadcast $rootscope, dispatches event name downwards kid scopes (and children recursively).

what do, broadcast from current scope, rather scopes. see plunker.

the main trick need kid scope ng-repeat creates, pass keyword "this" function gets current scope, there broadcast event.

element:

<button ng-click="load_data(this, person.id)">load data</button>

groupofpeoplecontroller:

$scope.load_data = function(childscope, id){ childscope.$broadcast('load_data', id); }

however, recommend against method. why have broadcasts/$on's @ all? move persondatacontroller entire contents of tr, , have loaddata function called straight ng-click in this plunker. it's save headaches , bugs.

angularjs

Merging multiple text files in R with a constraint -



Merging multiple text files in R with a constraint -

i have 10 text files containing 1000's of rows.

example: first file:

v1 v2 1 2 2 3 10 20 1 4 .....

second file:

v1 v2 1 2 8 10 .....

what want final file contain 12 columns. first 2 columns representing relationship , next 10 columns telling different files ( represented 1 if pair nowadays , 0 if not nowadays ) example:

final file:

v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 1 2 1 1 0 0 1 0 1 1 0 1 2 3 1 0 1 1 0 0 0 1 1 0

now, did sort every file pairs 1 first number appears on top followed other numbers, i.e.

for particular file, did that,

v1 v2 1 2 1 3 1 10 1 5 2 10 2 15 .......

then, tried using merge command, however, know it's not right one. not able think of other method it.

here's 1 way it. i'll assume you've read files list of data.frames, e.g. l <- lapply(filenames, read.table). i'll simulate l below.

# create dummy info l <- replicate(5, expand.grid(1:10, 1:10)[sample(100, 10), ], simplify=false) # add together column each data.frame in l. # indicate presence of pair when merge. l <- lapply(seq_along(l), function(i) { l[[i]][, paste0('df', i)] <- 1 l[[i]] }) # merge things # (hat-tip @charles - http://stackoverflow.com/a/8097519/489704) l.merged <- reduce(function(...) merge(..., all=t), l) head(l.merged) # var1 var2 df1 df2 df3 df4 df5 # 1 1 2 na na na 1 na # 2 1 5 1 na na na 1 # 3 1 9 na na na 1 na # 4 1 10 na na 1 1 na # 5 2 5 na na 1 na na # 6 2 6 na 1 na 1 na

easy plenty convert na 0 if want, e.g. with:

l.merged[is.na(l.merged)] <- 0

relevant post: merge multiple info frames in list simultaneously

r

webkit - iOS - How to integrate my application into a browser? -



webkit - iOS - How to integrate my application into a browser? -

since i'm not sure , how start solving issue appreciate every smallest force right direction.

so, need write ios application maintain track on events of or @ to the lowest degree webkit-based browsers, or integrate app's "open with..." item browser's context menu. @ to the lowest degree possible?

p.s. yeap, since there's no way utilize browser extensions in ios, i'm trying find workarounds without need implement own browser rather tiny 3-rd side application working along of existing browsers.

ios webkit integration

normalization - Normalizing data in Redshift -



normalization - Normalizing data in Redshift -

i've started using redshift housing millions of info points schema looks following:

create table metrics ( name varchar(100), value decimal(18,4), time timestamp ) sortkey (name, timestamp);

(the real schema bit more complex, satisfy question)

i'm wondering if makes sense normalize metric name (currently varchar(100)) mapping integer , storing integer. (e.g. {id: 1, name: metric1}). cardinality name ~100. adding mapping, create application logic quite bit more complex since has many streams of input. also, querying ahead of time require reverse mapping.

in traditional sql database, obvious yes, i'm not how redshift handles it's columnar info store. think nice have in general, assume redshift would/could similar mapping underneath hood since columns in table have lower cardinality others.

the reply no. redshift makes first-class utilize of compression , store few duplicates of name field.

however need ensure making utilize of redshift's compression options. section in docs should tell need know: http://docs.aws.amazon.com/redshift/latest/dg/t_compressing_data_on_disk.html

tl;dr: run analyze compression on table see compression redshift recommends, create new table using encodings, , insert info table.

normalization amazon-redshift

Server for python website developments in windows 7 -



Server for python website developments in windows 7 -

i trying develop website using python. tried install apache 2.2.25 on windows 7. worked , able run static websites. changed configuration of httpd.conf enable me execute python stated in apache documentation. however, believe windows not giving apache permission execute python. getting forbidden, don't have permission access /index.py on server. problem solved lunix in apache documentation not find windows 7. have been trying solve problem lastly 3 days appreciate if can help. in addition, there software appserv python can install python, mysql , apache or tool enable me run python websites in browser website development?

python windows apache cgi

oracle - updating my customer table-sql -



oracle - updating my customer table-sql -

good morning all, writing code update client table,

update alekwe_customer c set recently_purchased= (select case when (date_purchased between add_months(sysdate,-12) , sysdate) 'y' else 'n' end alekwe_customer_product d c.customer_id=d.customer_id)

but bringing error

single query returning more 1 row

is there improve way can write code? thankks help

if need find out if client has purchased year can utilize max function ('y' > 'n') 1 row:

update alekwe_customer c set recently_purchased = (select max(case when (date_purchased between add_months(sysdate,-12) , sysdate) 'y' else 'n' end ) alekwe_customer_product d c.customer_id=d.customer_id )

sql oracle

grails - GORM low level api finds object (Mongodb record) but its still NULL? -



grails - GORM low level api finds object (Mongodb record) but its still NULL? -

i have code in controller method:

db db = mongoclient.getdb("twcdb"); dbcollection coll = db.getcollection('countrycodes') println coll.findone() println coll.findone().class

and output @ console:

[_id:539848b2119918654e7e90c3, country:bermuda, alpha2:bm, aplha3:bmu, numeric:60, fips:bd, iga:model 2] null

so how can it finds record class null? because record isn't modeled of domain classes? recognize record's individual fields strings tested record overall classed null? how, why?

you should never phone call class on object there scenarios fail (e.g. getproperty('class') gets called or on "mapish" object, means groovy phone call get('class') -- case basicdbobject (subsubclass of linkedhashmap)). utilize getclass()

mongodb grails gorm

C# Compiler thinks these variables should be initialized -



C# Compiler thinks these variables should be initialized -

here sample of application i'm writing:

bool x3k = false, y3k = false; // of these functions homecoming nullable ints (int?) var comparing = dosomething(x, y) ?? dosomething2(x, y) ?? dosomething3(x, y, out x3k, out y3k) ?? dosomething4(x, y) ?? dosomething5(x, y); if (comparison.hasvalue) homecoming comparison.value; if (x3k) // compiler error here if don't init x3k { }

i don't understand, in null coalescing chain, how x3k uninitialized if comparison null , don't homecoming early. what's going on here?

you encountering short-circuit behavior: if dosomething or dosomething2 homecoming non-null, dosomething3 never execute, leaving x3k , y3k uninitialized.

c#

xpath - MSDeploy setParameter not working -



xpath - MSDeploy setParameter not working -

we trying integrate 'build once, deploy anywhere' model in our build-deploy system.

msdeploy works wonders this, cutting downwards build time dramatically crc checksum comparisons , (for part) works when using parameterisation alter applications web.configs depending on environment deploy to.

i have bulk of these parameters nailed down, few elements , attributes never seem change, no matter how many different ways phone call them in parameters.xml file. have outlined 3 examples of this, here web.config file trying change:

<?xml version="1.0" encoding="utf-8"?> <configuration> <connectionstrings> <add name="dbconnectionstring" connectionstring="data source=null;initial catalog=null;trusted_connection=no;user id=user1;password=pass*9;" providername="system.data.sqlclient" /> </connectionstrings> <system.web> <customerrors mode="on" defaultredirect="/library/error/pagenotfound.aspx"> </customerrors> </system.web> <applicationsettings> <settings> <setting name="service_address" serializeas="string"> <value></value> </setting> <settings> </applicationsettings> </configuration>

here parameters.xml file:

<parameter name="dbconnectionstring" defaultvalue=""> <parameterentry kind="xmlfile" scope="\\web.config$" match="/configuration/connectionstrings/add[@name='dbconnectionstring']/@connectionstring" /> </parameter> <parameter name="customerrorsmode" defaultvalue=""> <parameterentry kind="xmlfile" scope="\\web.config$" match="configuration/system.web/customerrors/@mode" /> </parameter> <parameter name="service_address" defaultvalue=""> <parameterentry kind="xmlfile" scope="\\web.config$" match="/configuration/applicationsettings/aim.web.properties.settings/setting[@name='service_address']/value" /> </parameter>

and here corresponding setparameters.xml file:

<setparameter name="dbconnectionstring" value="data source=dbserver;initial catalog=db1;trusted_connection=no;user id=user1;password=pass*9;"/> <setparameter name="customerrorsmode" value="off"/> <setparameter name="service_address" value="https://myservice.asmx"/>

i have tested each xpath look , results exact same of other working parameters, above never seem change.

does see obvious i'm missing here?

service_address

i found reply problem here:

replace web.config elements msdeploy

i missing 'text()' @ end of xpath expression, right xpath is:

/configuration/applicationsettings/aim.web.properties.settings/setting[@name='ai‌​m_web_addressservice_address']/value/text()

customerrorsmode

for customerrorsmode problem, missing '/' @ start of xpath expression. right look is:

/configuration/system.web/customerrors/@mode

connectionstrings

this 1 got me, lastly 1 figured out. after doing bit of digging found out msdeploy automatically parameterizes elements, connection string beingness 1 of them, more info here:

configuring parameters web bundle deployment

my parameter declaration connection string in question should have been:

<parameter name="dbconnectionstring-web.config connection string" defaultvalue=""> <parameterentry kind="xmlfile" scope="\\web.config$" match="/configuration/connectionstrings/add[@name='dbconnectionstring']" /> </parameter>

my setparameter definition should have looked this:

<setparameter name="dbconnectionstring-web.config connection string" value="data source=dbserver;initial catalog=db1;trusted_connection=no;user id=user1;password=pass*9;" />

xpath web-config msdeploy webdeploy web.config-transform

date - Javascript method to find number of milliseconds from 1970-01-01? -



date - Javascript method to find number of milliseconds from 1970-01-01? -

this question has reply here:

how timestamp in javascript? 32 answers

say, have date

var dt = new date('2012-01-01');

is there method in javascript homecoming number of milliseconds since 1970-01-01? particulat date homecoming 1325376000000

for purpose, there method "toutc()" runs in chrome only. know because can in chrome's console. see screen attached below:

however, when search method on internet, don't find , doesn't work in firefox either wierd , confused.

anyhow, if know way this, appreciated.

thank you

use gettime function:

var dt = new date('2012-01-01'); var time = dt.gettime();

javascript date timestamp compare utc

plpgsql - How to check if deletion is caused by CASCADE in PostgreSQL trigger -



plpgsql - How to check if deletion is caused by CASCADE in PostgreSQL trigger -

in pl/pgsql trigger function, there way know deletion invoked cascading delete action? have number of checks in trigger function see if deletion allowed, don't want perform if deletion cascading master table.

i can't think of built-in way check that. instead check existence of master row in master table ...

if exists ( select 1 master_table m m.master_id = old.master_id) -- run checks end if;

if it's cascading delete master row should gone already.

postgresql plpgsql cascading-deletes postgresql-9.3

python - Reading in a xml file and regex matching to find dimensions: Nonetype error -



python - Reading in a xml file and regex matching to find dimensions: Nonetype error -

i've been working on project taking in .svg files , finding dimensions. instead of converting them png, or using pysvg see (best way of getting swf file dimensions python) not trying scan xml dimensions.

i've been using open("thefile").read() , cannot see why code not working. issue regex?

an illustration of xml file might this:

str: <?xml version="1.0" encoding="utf-8" standalone="no"?> <svg xmlns:xlink="http://www.w3.org/1999/xlink" height="25.6px" width="74.9px" xmlns="http://www.w3.org/2000/svg"> <g transform="matrix(1, 0, 0, 1, 0.5, 0.5)"> <path d="m71.3 0.15 q73.9 0.75 73.9 4.0 l73.9 20.6 q73.9 24.6 69.9 24.6 l4.0 24.6 q0.9 24.6 0.2 22.2 l0.0 20.6 0.0 4.0 0.2 2.4 q0.7 0.6 2.6 0.15 l4.0 0.0 69.9 0.0 71.3 0.15" fill="#ffffff" fill-rule="evenodd" stroke="none"/> <path d="m71.3 0.15 l69.9 0.0 4.0 0.0 2.6 0.15 q0.7 0.6 0.2 2.4 l0.0 4.0 0.0 20.6 0.2 22.2 q0.9 24.6 4.0 24.6 l69.9 24.6 q73.9 24.6 73.9 20.6 l73.9 4.0 q73.9 0.75 71.3 0.15" fill="none" stroke="#8e8e8e" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.0"/> </g> </svg>

the code error occurs:

x=re.findall("width=\"[^\"]*",svgf)[0]

my variable x found , equal 74.9px in case. i've been looking for. don't see error coming from. if allow error occur info want extracted. ideas?

the error:

error evaluating: thread_id: pid54226_seq2 frame_id: 140505356028928 scope: look attrs: svgf traceback (most recent phone call last): file "/applications/eclipse/plugins/org.python.pydev_3.4.1.201403181715/pysrc/pydevd_vars.py", line 422, in resolvecompoundvariable homecoming resolver.getdictionary(var) attributeerror: 'nonetype' object has no attribute 'getdictionary'

svg xml document, shall utilize standard tools xml. regexps not serving in these situations.

following illustration uses xpath , lxml library (install first)

>>> xmlstr = """<?xml version="1.0" encoding="utf-8" standalone="no"?> ... <svg xmlns:xlink="http://www.w3.org/1999/xlink" height="25.6px" width="74.9px" xmlns="http://www.w3.org/2000/svg"> ... <g transform="matrix(1, 0, 0, 1, 0.5, 0.5)"> ... <path d="m71.3 0.15 q73.9 0.75 73.9 4.0 l73.9 20.6 q73.9 24.6 69.9 24.6 l4.0 24.6 q0.9 24.6 0.2 22.2 l0.0 20.6 0.0 4.0 0.2 2.4 q0.7 0.6 2.6 0.15 l4.0 0.0 69.9 0.0 71.3 0.15" fill="#ffffff" fill-rule="evenodd" stroke="none"/> ... <path d="m71.3 0.15 l69.9 0.0 4.0 0.0 2.6 0.15 q0.7 0.6 0.2 2.4 l0.0 4.0 0.0 20.6 0.2 22.2 q0.9 24.6 4.0 24.6 l69.9 24.6 q73.9 24.6 73.9 20.6 l73.9 4.0 q73.9 0.75 71.3 0.15" fill="none" stroke="#8e8e8e" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.0"/> ... </g> ... </svg>""" ... >>> lxml import etree >>> svg = etree.fromstring(xmlstr) >>> svg <element {http://www.w3.org/2000/svg}svg @ 0x7f7d180d2638> >>> svg.xpath("//@width") ['74.9px']

python regex svg

php - Im having one issue editing my image gallery from my news (Im deleting my images from my folder even when I dont want to edit my images gallery) -



php - Im having one issue editing my image gallery from my news (Im deleting my images from my folder even when I dont want to edit my images gallery) -

i have table "news" , 1 "gallery".

in table "gallery" have field "news_id", bacause when insert images in gallery table, im inserting images belong news.

i have file "news-create.php", have form asks title, content , have input file select images gallery(this input file optional, no required).

im creating news sucess, our without image gallery, im creating news correctly.

but now, editing news in "news-edit.php", im having 1 problem doing images gallery update.

first, in "news-index.php" have list of news have, , have link in each news when click in each news pass url id of clicked news: , id:

$newsid = $_get['news_id'];

then have if command when form submited:

if(isset($_post['sendform'])){ $f['title'] = $_post['title']; $f['content'] = $_post['content']; }

then have update:

$updnot = $pdo->prepare("update news set title=?, content = ? id_news = ?"); $updnot->bindparam(1,$f['title']); $updnot->bindparam(2,$f['content']); $updnot->bindparam(3,$newsid); $updnot->execute();

then if update homecoming sucess, want verify if field select images gallery selected take images or not.

if not selected , news have images gallery want maintain actual images gallery.

if news dont have images gallery, , in edit form dont select images gallery, dont want insert images.

but if select images gallery, want verify if exists images in gallery, if exists want remove them folder, , want upload folder , update in gallery table new images.

the problem is, when dont select images im entering in if if($_files['gb']['tmp_name']), , im removing images folder. , so, when have images gallery in news , in edit news page dont take images gallery, images beingness removed folder, , dont want that.

i want remove images folder, when user in edit news page select new images gallery, , so, first remove images folder relative news beingness edited, , upload , update in gallery table new images.

somebody there can help me solve problem? im here hours , dont find solution this, bcause when if verify if user selected new images, when user dont select images im entering in if, seems have images selected when dont select it...

so, when update homecoming sucess have code:

if($updnot->rowcount() >=1){ if($_files['gb']['tmp_name']){ $readgall = $pdo->prepare("select * gallery news_id = ?"); $readgall->bindparam(1, $nesid); $readgall->execute(); if($readgall->rowcount()>=1){ while ($resultg = $readgall->fetch(pdo::fetch_assoc)){ if(file_exists($path.$resultgall['img']) && !is_dir($path.$resultgall['img'])){ unlink($path.$resultgall['img']); } //here upload , update on gallery table when can prepare problem } } }

you never bothered checking if file uploaded. blindly process upload. if nil uploaded, or upload failed, trash database invalid/incorrect "upload" information.

at bare minimum should have

if($_files['gb']['error'] === upload_err_ok) { ... file uploaded }

php

What is it? [ulisting] in html page and $listing in php page. Is it related? -



What is it? [ulisting] in html page and $listing in php page. Is it related? -

i faced project. saw html page, of code below:

<div class="span6"> <div class="control-group"> <label class="col-wrap control-label" for="username">user id</label> <div class="col-wrap controls"> <select name="username" id="username" class="span12"> [ulisting] </select> <br><div id="show_hide" class="show_hide"><font color="red">user id exist</font></div> </div>

and found in php file:

$ulisting =""; $url = 'http://'.$_session["url"].'/-/vo/public/user.api_userlist?sess='.$_session["sessid"].'&format=json'; $content1 = file_get_contents($url); $json = json_decode($content1, true); foreach($json['user'] $item) { $name=$item['name']; $ulisting=$ulisting. "<option value=\"$name\">$name</option>"; }

after analysed code, thought related. can explain me it? keywords find article this? want larn how works.. give thanks you..

you find looks this

$template=str_replace('[ulisting]',$ulisting,$template); //or diff way replace

that [ulisting] marker programmer set there using php can replace actual values select field later on. if not done, means nil special , should display in html is.

if replacement there, add together alternative values select box , there wont text [ulisting] in final output html.

php

mysql - Select using where and different tables -



mysql - Select using where and different tables -

i have code:

dim oledbcon1 new oledb.oledbconnection("provider=microsoft.jet.oledb.4.0;data source=c:\users\utilizador.utilizador-pc\documents\visual studio 2013\projects\windowsapplication1\windowsapplication1\doc_vendas_cab.mdb;persist security info=true") oledbcon1.open() dim oledbstr1 string = "select mov_venda_lin.ftlquantidade, mov_venda_lin.fltprecounitario, tbl_gce_artigosprecos.strcodartigo,tbl_gce_artigosprecos.intnumero,tbl_gce_vendedores.strnome " & _ "from mov_venda_lin,tbl_gce_artigosprecos,tbl_gce_vendedores, mov_venda_cab " & _ "where (mov_venda_lin.strcodartigo = tbl_gce_artigosprecos.strcodartigo) , (mov_venda_lin.strcodseccao = mov_venda_cab.strcodseccao) , (mov_venda_lin.intnumero = mov_venda_cab.intnumero) , (mov_venda_cab.intcodvendedor = tbl_gce_vendedores.intcodigo);" dim oledbconcomm1 new oledb.oledbcommand(oledbstr1, oledbcon1) dim olebddr oledb.oledbdatareader = oledbconcomm1.executereader oledbcon1.open()

i want select , relate info doesn't work error:

an unhandled exception of type 'system.data.oledb.oledbexception' occurred in system.data.dll

additional information: there no value given 1 or more required parameters.

can help me? in advance.

mysql vb.net select oledb where-clause

events - How to capture process output asynchronously in powershell? -



events - How to capture process output asynchronously in powershell? -

i want capture stdout , stderr process start in powershell script , display asynchronously console. i've found documentation on doing through msdn , other blogs.

after creating , running illustration below, can't seem output displayed asynchronously. of output displayed when process terminates.

$ps = new-object system.diagnostics.process $ps.startinfo.filename = "cmd.exe" $ps.startinfo.useshellexecute = $false $ps.startinfo.redirectstandardoutput = $true $ps.startinfo.arguments = "/c echo `"hi`" `& timeout 5" $action = { write-host $eventargs.data } register-objectevent -inputobject $ps -eventname outputdatareceived -action $action | out-null $ps.start() | out-null $ps.beginoutputreadline() $ps.waitforexit()

in example, expecting see output of "hi" on commandline before end of programme execution because outputdatareceived event should have been triggered.

i've tried using other executables - java.exe, git.exe, etc. of them have same effect, i'm left think there simple i'm not understanding or have missed. else needs done read stdout asynchronously?

unfortunately asynchronous reading not easy if want properly. if phone call waitforexit() without timeout utilize function wrote (based on c# code):

function invoke-executable { # runs specified executable , captures exit code, stdout # , stderr. # returns: custom object. param( [parameter(mandatory=$true)] [validatenotnullorempty()] [string]$sexefile, [parameter(mandatory=$false)] [string[]]$cargs, [parameter(mandatory=$false)] [string]$sverb ) # setting process invocation parameters. $opsi = new-object -typename system.diagnostics.processstartinfo $opsi.createnowindow = $true $opsi.useshellexecute = $false $opsi.redirectstandardoutput = $true $opsi.redirectstandarderror = $true $opsi.filename = $sexefile if (! [string]::isnullorempty($cargs)) { $opsi.arguments = $cargs } if (! [string]::isnullorempty($sverb)) { $opsi.verb = $sverb } # creating process object. $oprocess = new-object -typename system.diagnostics.process $oprocess.startinfo = $opsi # creating string builders store stdout , stderr. $ostdoutbuilder = new-object -typename system.text.stringbuilder $ostderrbuilder = new-object -typename system.text.stringbuilder # adding event handers stdout , stderr. $sscripblock = { if (! [string]::isnullorempty($eventargs.data)) { $event.messagedata.appendline($eventargs.data) } } $ostdoutevent = register-objectevent -inputobject $oprocess ` -action $sscripblock -eventname 'outputdatareceived' ` -messagedata $ostdoutbuilder $ostderrevent = register-objectevent -inputobject $oprocess ` -action $sscripblock -eventname 'errordatareceived' ` -messagedata $ostderrbuilder # starting process. [void]$oprocess.start() $oprocess.beginoutputreadline() $oprocess.beginerrorreadline() [void]$oprocess.waitforexit() # unregistering events retrieve process output. unregister-event -sourceidentifier $ostdoutevent.name unregister-event -sourceidentifier $ostderrevent.name $oresult = new-object -typename psobject -property ([ordered]@{ "exefile" = $sexefile; "args" = $cargs -join " "; "exitcode" = $oprocess.exitcode; "stdout" = $ostdoutbuilder.tostring().trim(); "stderr" = $ostderrbuilder.tostring().trim() }) homecoming $oresult }

it captures stdout, stderr , exit code. illustration usage:

$oresult = invoke-executable -sexefilename 'ping.exe' -cargs @('8.8.8.8', '-a') $oresult | format-list -force

for more info , alternative implementations (in c#) read this blog post.

events powershell asynchronous

Problems with python super method -



Problems with python super method -

i have problem: super class is:

class regressionb(object): def __init__(self, datamatrix, targets): self.x = datamatrix self.y = targets def theta_x_product(self, theta, x): homecoming self.add_column_zero(x).dot(theta) def add_column_zero(self, x): m = len(x) homecoming np.concatenate((np.ones([m,1],1]), x), axis = 1)

than, kid class:

from regressionb import * class linearregressionb(regressionb): def __init__(self, datamatrix, targets): regressionb.__init__(self, datamatrix, targets) #tryed super().__init__(datamatrix, targets) def hypothesis(self, theta): homecoming lambda x : regressionb.theta_x_product(self, theta, x) #also tryed homecoming lambda x : super().theta_x_product(theta, x)

than run console:

x = np.matrix([ [11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34]]) theta = np.matrix([1, 1, 1, 1, 1]).t linearregressionb import * linear = linearregressionb(x, y) h = linear.hypothesis(theta)

for receive error:

hypothesis() takes 1 argument (2 given)

i dont see how give 2 parameters. mistake??

your kid class should like:

class linearregressionb(regressionb): def __init__(self, datamatrix, targets): super(linearregressionb, self).__init__(datamatrix, targets) def hypothesis(self, theta): homecoming lambda x : super(linearregressionb, self).theta_x_product(theta, x)

-- edit --

agreed, that, though super might not best thing since hypothesis has not been overridden, unnecessary or not, programmer. point here imho, how phone call method parent class, , proper syntax of using super, demonstrated. not sure why i'm beingness downvoted that.

python

objective c - iOS delegate method definition syntax -



objective c - iOS delegate method definition syntax -

how understand next syntax:

-(void) centralmanager:(cbcentralmanager *)central diddiscoverperipheral:(cbperipheral *) advertisementdata:.....

so method name diddiscoverperipheral, why central parameter defined first?

the method name centralmanager:diddiscoverperipheral:advertisementdata:.

the first parameter tells manager discovered peripheral. you'd otherwise have no thought talking you. it's standard practice delegate protocols in case want talk back.

ios objective-c

ruby - Parsing command and arguments with a regex? -



ruby - Parsing command and arguments with a regex? -

i have little ruby cli should take command , arguments.

for example, should able do:

attribute value

or:

attribute (value1, value2)

or:

attribute (value1, value2) , attribute2 (value3, value4)

or combination.

i'd like:

[['attribute', ['value1', 'value2']], ['attribute2', ['value3', 'value4']]]

i came regex

(\b[a-z_]{1}\w+)\s{1}\((.*?)\)

which gets me partially there, in matches attribute , both values (as whole, [['attribute', 'value1, value2']], doesn't match attribute value.

i dont know how extensive of input require, this might trick. works shell getopts.

ruby regex

jQuery Sortable for combination of two different lists -



jQuery Sortable for combination of two different lists -

i want combine 2 list sorting work single list. code is.

$(function () { $("#sortable").sortable({ connectwith: "#sortable1" }); $("#sortable1").sortable({ connectwith: "#sortable" }); $("#sortable,#sortable1").disableselection(); });

my html is.

<ul id="sortable"> <li class="ui-state-default">1</li> <li class="ui-state-default">2</li> <li class="<ui-s></ui-s>tate-default">3</li> <li class="ui-state-default">4</li> <li class="ui-state-default">5</li> <li class="ui-state-default">6</li> <li class="ui-state-default">7</li> <li class="ui-state-default">8</li> <li class="ui-state-default">9</li> <li class="ui-state-default">10</li> <li class="ui-state-default">11</li> <li class="ui-state-default">12</li> </ul> <ul id="sortable1"> <li class="ui-state-default">1</li> <li class="ui-state-default">2</li> <li class="ui-state-default">3</li> <li class="ui-state-default">4</li> <li class="ui-state-default">5</li> <li class="ui-state-default">6</li> <li class="ui-state-default">7</li> <li class="ui-state-default">8</li> <li class="ui-state-default">9</li> <li class="ui-state-default">10</li> <li class="ui-state-default">11</li> <li class="ui-state-default">12</li> </ul>

when remove

</ul> <ul id="sortable1">

from html work want want same result 2 different lists. clear understanding please check http://jsfiddle.net/67hew/4/

thanks

sortable connectwith not work float. remove "float:left" , add together "display:inline-block":

#sortable li, #sortable1 li { margin: 3px 3px 3px 0; padding: 1px; display:inline-block; width: 100px; height: 90px; font-size: 4em; text-align: center; }

jquery jquery-ui jquery-ui-sortable jquery-sortable

.net - Messagebox customization is not shown correctly -



.net - Messagebox customization is not shown correctly -

time ago i've taken this code of @hans passant create modifications, works fine i've noticed custom messagebox not shown properly.

this how shown normal messagebox custom windows theme:

and else how shown custom messagebox:

as can see darkened bottom layer in custom messagebox not alligned or resized or don't know.

how can prepare issue?, total code:

' [ centered messagebox ] ' ' author of original code hans passant: ' http://stackoverflow.com/questions/2576156/winforms-how-can-i-make-messagebox-appear-centered-on-mainform ' ' examples : ' ' using new centeredmessagebox(me, new font(new fontfamily("lucida console"), font.sizeinpoints, fontstyle.bold)) ' messagebox.show("test text", "test title", messageboxbuttons.ok, messageboxicon.information) ' end using #region " centered messagebox class" imports system.drawing imports system.runtime.interopservices imports system.text imports system.windows.forms class centeredmessagebox : implements idisposable private mtries integer = 0 private mowner form private mfont font ' p/invoke declarations private const wm_setfont integer = &h30 private const wm_getfont integer = &h31 private delegate function enumthreadwndproc(hwnd intptr, lp intptr) boolean friend declare function setwindowpos lib "user32" (byval hwnd intptr, byval hwndinsertafter intptr, byval x integer, byval y integer, byval cx integer, byval cy integer, byval wflags uint32) boolean <dllimport("user32.dll")> private shared function enumthreadwindows(tid integer, callback enumthreadwndproc, lp intptr) boolean end function <dllimport("kernel32.dll")> private shared function getcurrentthreadid() integer end function <dllimport("user32.dll")> private shared function getclassname(hwnd intptr, buffer stringbuilder, buflen integer) integer end function <dllimport("user32.dll")> private shared function getdlgitem(hwnd intptr, item integer) intptr end function <dllimport("user32.dll")> private shared function sendmessage(hwnd intptr, msg integer, wp intptr, lp intptr) intptr end function <dllimport("user32.dll")> shared function getwindowrect(hwnd intptr, byref rc rect) boolean end function <dllimport("user32.dll")> shared function movewindow(hwnd intptr, x integer, y integer, w integer, h integer, repaint boolean) boolean end function construction rect public left integer public top integer public right integer public bottom integer end construction public sub new(owner form, optional custom_font font = nothing) mowner = owner mfont = custom_font owner.begininvoke(new methodinvoker(addressof finddialog)) end sub private sub finddialog() ' enumerate windows find message box if mtries < 0 homecoming end if dim callback new enumthreadwndproc(addressof checkwindow) if enumthreadwindows(getcurrentthreadid(), callback, intptr.zero) if system.threading.interlocked.increment(mtries) < 10 mowner.begininvoke(new methodinvoker(addressof finddialog)) end if end if end sub private function checkwindow(hwnd intptr, lp intptr) boolean ' checks if <hwnd> dialog dim sb new stringbuilder(260) getclassname(hwnd, sb, sb.capacity) if sb.tostring() <> "#32770" homecoming true ' static command displays text dim htext intptr = getdlgitem(hwnd, &hffff) dim frmrect new rectangle(mowner.location, mowner.size) dim dlgrect rect getwindowrect(hwnd, dlgrect) if htext <> intptr.zero if mfont nil ' current font mfont = font.fromhfont(sendmessage(htext, wm_getfont, intptr.zero, intptr.zero)) end if sendmessage(htext, wm_setfont, mfont.tohfont(), new intptr(1)) ' resize , positionate messagebox window: movewindow(hwnd, _ frmrect.left + (frmrect.width - dlgrect.right + dlgrect.left) \ 2, _ frmrect.top + (frmrect.height - dlgrect.bottom + dlgrect.top) \ 2, _ (dlgrect.right - dlgrect.left), _ (dlgrect.bottom - dlgrect.top), true) ' resize messagebox text label if mfont isnot nil setwindowpos(htext, 0, 70, 35, 1920, 1080, 0) end if end if ' done homecoming false end function public sub dispose() implements idisposable.dispose mtries = -1 mowner = nil if mfont isnot nil mfont.dispose() end sub end class #end part

it looks code resize text label causing problem

' resize messagebox text label if mfont isnot nil setwindowpos(htext, 0, 70, 35, 1920, 1080, 0) end if

this code resizes text label big size , covers lower area. if alter height 1080 smaller, 30, problem disappears.

i able work removing if statement entirely. messagebox still centered in parent form , appears work correctly without it.

.net vb.net winforms winapi messagebox