Tuesday, 15 April 2014

javascript - Can I get text source of link stylesheet? -



javascript - Can I get text source of link stylesheet? -

i seek css text link element. illustration style element simplest:

[].map.call(document.stylesheets, function(stylesheet) { var tag = stylesheet.ownernode.tagname.tolowercase(); if (tag == 'style') { homecoming stylesheet.ownernode.textcontent; } else if (tag == 'link') { //is possible receive source here without ajax? } });

is there way link source without loading text?

with document.stylesheets can interate through loaded stylesheets on page. each 1 list of css rules elements. can obtain csstext property of these css rules.

based on this post, i've come sample script css rules text loaded on page. hope helps...

http://jsfiddle.net/qmaw7/1/

var cssstyles = ""; //started @ index 1 index 0 browser's user agent stylesheet. for(var i=1; i<document.stylesheets.length; i++) { var style = null; (document.stylesheets[i]) { if (typeof cssrules != "undefined") style = cssrules; else if (typeof rules != "undefined") style = rules; } for(var item in style) { if(style[item].csstext != undefined) cssstyles = (style[item].csstext); } } alert(cssstyles);

javascript html css

Read many Excel files from R -



Read many Excel files from R -

it's first time r, maybe problem trivial

i need download date xls files url , each 1 should in 1 info frame. here .

i decided utilize gdata bundle (package ‘xlsreadwrite’ not available r version 3.1.0, rodbc not available win64)

downloading works great 1 file (year e.g = 2013 )

readxls<-function() { library("gdata") link<-paste0("http://nbp.pl/kursy/archiwum/archiwum_tab_a_",year,".xls") xlsdata <<- read.xls(link, sheet = 1, perl = "c:\\perl64\\bin\\perl.exe", header=true) }

i tried read many .xls list() using loop. (e.g. y_begin=2012, y_end=2014)

readxls<-function() { library("gdata") ldata<<- list() j=1 (i in y_begin:y_end) { link<-paste0("http://nbp.pl/kursy/archiwum/archiwum_tab_a_",i,".xls") xlsdata <<- read.xls(link, sheet = 1, perl = "c:\\perl64\\bin\\perl.exe", header=true) ldata[j] <<- xlsdata j<-j+1 } }

i thought after i'd able merge them, don't know how info single info frame in list illustration > view(ldata[2]) returns first collumn

avoid utilize for loop , specially side effect. improve utilize lapply here. r way things ( functional programming). here this:

library(gdata) readxls<-function() { ids <- seq(y_begin,y_end) links <-paste0("http://nbp.pl/kursy/archiwum/archiwum_tab_a_",ids,".xls") lapply (links,function(i) read.xls(link, sheet = 1, perl = "c:\\perl64\\bin\\perl.exe", header=true) ) }

this homecoming list of data.frame, merge them, assuming ll same:

ll <- readxls() do.call(rbind,ll)

r excel

c++ - Is VC++ still broken Sequentially-Consistent-wise? -



c++ - Is VC++ still broken Sequentially-Consistent-wise? -

i watched (most of) herb sutter's atmoic<> weapons video, , wanted test "conditional lock" loop within sample. apparently, although (if understand correctly) c++11 standard says below illustration should work , sequentially consistent, not.

before read on, question is: correct? compiler broken? code broken - have race status here missed? how bypass this?

i tried on 3 different versions of visual c++: vc10 professional, vc11 professional , vc12 express (== visual studio 2013 desktop express).

below code used visual studio 2013. other versions used boost instead of std, thought same.

#include <iostream> #include <thread> #include <mutex> int = 0; std::mutex m; void other() { std::lock_guard<std::mutex> l(m); std::this_thread::sleep_for(std::chrono::milliseconds(2)); = 999999; std::this_thread::sleep_for(std::chrono::seconds(2)); std::cout << << "\n"; } int main(int argc, char* argv[]) { bool work = (argc > 1); if (work) { m.lock(); } std::thread th(other); (int = 0; < 100000000; ++i) { if (i % 7 == 3) { if (work) { ++a; } } } if (work) { std::cout << << "\n"; m.unlock(); } th.join(); }

to summarize thought of code: global variable a protected global mutex m. assuming there no command line arguments (argc==1) thread runs other() 1 supposed access global variable a.

the right output of programme print 999999.

however, because of compiler loop optimization (using register in-loop increments , @ end of loop copying value a), a modified assembly though it's not supposed to.

this happened in 3 vc versions, although in code illustration in vc12 had plant calls sleep() create break.

here's of assembly code (the adress of a in run 0x00f65498):

loop initialization - value a copied edi

27: (int = 0; < 100000000; ++i) 00f61543 xor esi,esi 00f61545 mov edi,dword ptr ds:[0f65498h] 00f6154b jmp main+0c0h (0f61550h) 00f6154d lea ecx,[ecx] 28: { 29: if (i % 7 == 3)

increment within condition, , after loop copied location of a unconditionally

30: { 31: if (work) 00f61572 mov al,byte ptr [esp+1bh] 00f61576 jne main+0edh (0f6157dh) 00f61578 test al,al 00f6157a je main+0edh (0f6157dh) 32: { 33: ++a; 00f6157c inc edi 27: (int = 0; < 100000000; ++i) 00f6157d inc esi 00f6157e cmp esi,5f5e100h 00f61584 jl main+0c0h (0f61550h) 32: { 33: ++a; 00f61586 mov dword ptr ds:[0f65498h],edi 34: }

and output of programme 0.

the 'volatile' keyword prevent kind of optimization. that's it's for: every utilize of 'a' read or written shown, , won't moved in different order other volatile variables.

the implementation of mutex should include compiler-specific instructions cause "fence" @ point, telling optimizer not reorder instructions across boundary. since implementation not compiler vendor, maybe that's left out? i've never checked.

since 'a' global, think compiler more careful it. but, vs10 doesn't know threads won't consider other threads utilize it. since optimizer grasps entire loop execution, knows functions called within loop won't touch 'a' , that's plenty it.

i'm not sure new standard says thread visibility of global variables other volatile. is, there rule prevent optimization (even though function can grasped way downwards knows other functions don't utilize global, must assume other threads can) ?

i suggest trying newer compiler compiler-provided std::mutex, , checking c++ standard , current drafts that. think above should help know for.

—john

c++ multithreading visual-c++ concurrency compiler-optimization

how do I change the location of the httpd.conf for Apache on windows? -



how do I change the location of the httpd.conf for Apache on windows? -

i working on setting load balancing cluster on windows server 2012 , have shared drive want configuration files apache exist at. way each fellow member of lb can load exact same config files. how alter config file located independently of serverroot is?

start apache process -d parameter , give alternative serverroot argument, though i'd imagine much improve thought utilize mechanism sync files locally each server.

also read http://httpd.apache.org/docs/2.4/mod/core.html#mutex, it's advised if you're running networked file system.

if want specify main config file, start process -f parameter , path config file argument.

windows apache httpd.conf

inserting variables and looping over a python class call -



inserting variables and looping over a python class call -

i'm using flask-sqlalchemy , flask-wtf. want take string produced "row.form_field" query , place wtf form class call. ideas on how can pull off?

from forms import form_list models import form_value form = form_list values = form_value.query.filter_by(form_entry_id = id) row in values: print row.form_field, row.value #this works. form.row.form_field.data = row.value #this not! # form.???how insert "row.form_field" here???.data = row.value

you can utilize getattr:

getattr(form, row.form_field).data = row.value

but easier, can pass info instantiated wtforms class:

data = {row.form_field: row.value row in values} form_list = formlist(**data)

python class flask flask-sqlalchemy flask-wtforms

java - Why isn't Spring chaining ExceptionHandlers? -



java - Why isn't Spring chaining ExceptionHandlers? -

i have several spring @exceptionhandlers follows:

@exceptionhandler(mailerexception.class) @responsestatus(value = httpstatus.internal_server_error) public string mailerexception(mailerexception e, httpservletrequest request, locale locale) { flashmap outputflashmap = requestcontextutils.getoutputflashmap(request); if (outputflashmap != null) { outputflashmap.put("flashmessage", messagesource.getmessage("controller.internal_server_error", null, locale)); } homecoming "redirect:/index"; } @exceptionhandler(executionexception.class) public string executionexception(executionexception e) throws throwable { throw e.getcause(); }

when executionexception thrown mailerexception cause, executionexception handler invoked not mailerexception one...

i not sure why... can please explain?

here stacktrace:

grave: servlet.service() servlet [bignibou] in context path [/bignibou] threw exception [request processing failed; nested exception java.util.concurrent.executionexception: com.bignibou.mailerexception: messagingexception | mailsendexception] root cause com.bignibou.mailerexception: messagingexception | mailsendexception @ com.bignibou.service.preference.preferenceserviceimpl.sendpasswordresetinfo_aroundbody10(preferenceserviceimpl.java:122) @ com.bignibou.service.preference.preferenceserviceimpl$ajcclosure11.run(preferenceserviceimpl.java:1) @ org.springframework.transaction.aspectj.abstracttransactionaspect.ajc$around$org_springframework_transaction_aspectj_abstracttransactionaspect$1$2a73e96cproceed(abstracttransactionaspect.aj:59) @ org.springframework.transaction.aspectj.abstracttransactionaspect$abstracttransactionaspect$1.proceedwithinvocation(abstracttransactionaspect.aj:65) @ org.springframework.transaction.interceptor.transactionaspectsupport.invokewithintransaction(transactionaspectsupport.java:262) @ org.springframework.transaction.aspectj.abstracttransactionaspect.ajc$around$org_springframework_transaction_aspectj_abstracttransactionaspect$1$2a73e96c(abstracttransactionaspect.aj:63) @ com.bignibou.service.preference.preferenceserviceimpl.sendpasswordresetinfo_aroundbody12(preferenceserviceimpl.java:111) @ com.bignibou.service.preference.preferenceserviceimpl$ajcclosure13.run(preferenceserviceimpl.java:1) @ org.springframework.scheduling.aspectj.abstractasyncexecutionaspect.ajc$around$org_springframework_scheduling_aspectj_abstractasyncexecutionaspect$1$6c004c3eproceed(abstractasyncexecutionaspect.aj:58) @ org.springframework.scheduling.aspectj.abstractasyncexecutionaspect.ajc$around$org_springframework_scheduling_aspectj_abstractasyncexecutionaspect$1$6c004c3e(abstractasyncexecutionaspect.aj:62) @ com.bignibou.service.preference.preferenceserviceimpl.sendpasswordresetinfo(preferenceserviceimpl.java:111) @ sun.reflect.nativemethodaccessorimpl.invoke0(native method) @ sun.reflect.nativemethodaccessorimpl.invoke(nativemethodaccessorimpl.java:62) @ sun.reflect.delegatingmethodaccessorimpl.invoke(delegatingmethodaccessorimpl.java:43) @ java.lang.reflect.method.invoke(method.java:483) @ org.springframework.aop.support.aoputils.invokejoinpointusingreflection(aoputils.java:317) @ org.springframework.aop.framework.reflectivemethodinvocation.invokejoinpoint(reflectivemethodinvocation.java:190) @ org.springframework.aop.framework.reflectivemethodinvocation.proceed(reflectivemethodinvocation.java:157) @ org.springframework.aop.interceptor.asyncexecutioninterceptor$1.call(asyncexecutioninterceptor.java:128) @ java.util.concurrent.futuretask.run(futuretask.java:266) @ java.util.concurrent.threadpoolexecutor.runworker(threadpoolexecutor.java:1142) @ java.util.concurrent.threadpoolexecutor$worker.run(threadpoolexecutor.java:617) @ java.lang.thread.run(thread.java:745)

here gets displayed in browser:

etat http 500 - request processing failed; nested exception java.util.concurrent.executionexception: com.bignibou.mailerexception: messagingexception | mailsendexception

java spring exception exception-handling

RestKit , PUT complex JSON to server -



RestKit , PUT complex JSON to server -

the request json want set server

"type": "payment", "paymentoptions": [ { "type": "netbanking", "name": "netbanking - axis bank", "expirydate": null, "bank": "axis bank" } ]

class mapping

@interface ctspaymentdetailupdate : nsobject @property(nonatomic, strong, readonly) nsstring* type; @property(nonatomic, strong, readonly) nsmutablearray* paymentoptions; @interface ctspaymentoption : nsobject @property(nonatomic, strong) nsstring* type, *ownername, *number, *bankname, *expirydate;

code mapping

#define mlc_profile_update_payment_request_mapping \ @{ \ @"type" : @"type", \ @"bank" : @"bankname", \ @"owner" : @"ownername", \ @"number" : @"number", \ @"expirydate" : @"expirydate", \ @"name" : @"cardname" \ } rkobjectmapping* paymentoptionmapping = [rkobjectmapping mappingforclass:[ctspaymentoption class]]; [paymentoptionmapping addattributemappingsfromdictionary: mlc_profile_update_payment_request_mapping]; rkobjectmapping* paymentdetailreq = [rkobjectmapping requestmapping]; [paymentdetailreq addattributemappingsfromdictionary:@{ @"type" : @"type" }]; [paymentdetailreq addpropertymapping: [rkrelationshipmapping relationshipmappingfromkeypath:@"paymentoptions" tokeypath:@"paymentoptions" withmapping:paymentoptionmapping]]; rkrequestdescriptor* requestdes = [rkrequestdescriptor requestdescriptorwithmapping:paymentdetailreq objectclass:[ctspaymentdetailupdate class] rootkeypath:nil method:[self gethttpmethodfor:put]]; [objectmanager addrequestdescriptor:requestdes];

once utilize next set object server

[objectmanager putobject:object path:path parameters:queryparams success:^(rkobjectrequestoperation* operation, rkmappingresult* mappingresult) { //code } failure:^(rkobjectrequestoperation* operation, nserror* error) { //code }];

i nsunknownkeyexception on line 2014-06-22 11:12:22.587 restfulltester[1727:60b] *** terminating app due uncaught exception 'nsunknownkeyexception', reason: '[<ctspaymentoption 0x10bf2ae80> valueforundefinedkey:]: class not key value coding-compliant key owner.'

i think there wrong the way have made mapping not able understand,also there way test json code produce beforehand

this line:

withmapping:paymentoptionmapping]];

when creating relationship mapping should be:

withmapping:[paymentoptionmapping inversemapping]]];

json restkit restkit-0.20

Java - MySQL to Hive Import where MySQL Running on Windows and Hive Running on Cent OS (Horton Sandbox) -



Java - MySQL to Hive Import where MySQL Running on Windows and Hive Running on Cent OS (Horton Sandbox) -

before reply , comments. tried several alternative found in stackoverflow end failure. next links -

how can execute sqoop in java? how utilize sqoop in java program? how import table mysql hive using java? how load sql info hortonworks sandbox?

i tried in horton sandbox through command line , succeded.

sqoop import --connect jdbc:mysql://192.168.56.101:3316/database_name --username=user --password=pwd --table table_name --hive-import -m 1 -- --schema default

where 192.168.56.101 windows , 192.168.56.102 horton sandbox 2.6.

now want same thing java java code run somewhere else not in horton sandbox.

how loacate hive_home , other sqoop parameters because running in sandbox. parameters have pass. should passes sqoopoptions or sqoop.runtools string array arguments. both failing. i confused while import library (com.cloudera.sqoop , org.apache.sqoop) , this

the method run(com.cloudera.sqoop.sqoopoptions) in type importtool not applicable arguments (org.apache.sqoop.sqoopoptions) 2 line (option parameter added between 2 lines)

sqoopoptions options = new sqoopoptions(); int ret = new importtool().run(options);

if take cloudera method deprecated if take apace run method doesn't take options argument

i strucked in weeks. please help.

yes can via ssh. horton sandbox comes ssh back upwards pre installed. can execute sqoop command via ssh client on windows. or if want programaticaly (thats have done in java) have follow step.

download sshxcute java library : https://code.google.com/p/sshxcute/ add build path of java project contains next java code import net.neoremind.sshxcute.core.sshexec; import net.neoremind.sshxcute.core.connbean; import net.neoremind.sshxcute.task.customtask; import net.neoremind.sshxcute.task.impl.execcommand; public class testssh { public static void main(string args[]) throws exception{ // initialize connbean object, parameter list ip, username, password connbean cb = new connbean("192.168.56.102", "root","hadoop"); // set connbean instance parameter sshexec static method getinstance(connbean) retrieve singleton sshexec instance sshexec ssh = sshexec.getinstance(cb); // connect server ssh.connect(); customtask sampletask1 = new execcommand("echo $ssh_client"); // print client ip connected ssh server on horton sandbox system.out.println(ssh.exec(sampletask1)); customtask sampletask2 = new execcommand("sqoop import --connect jdbc:mysql://192.168.56.101:3316/mysql_db_name --username=mysql_user --password=mysql_pwd --table mysql_table_name --hive-import -m 1 -- --schema default"); ssh.exec(sampletask2); ssh.disconnect(); } }

java mysql hive sqoop hortonworks-data-platform

How to get_absolute_url with domain in Django template? -



How to get_absolute_url with domain in Django template? -

so struggling bit, logically seems simple due limited understanding of django not sure , how formulate solution.

basically have blog app set , shows complete(all content including disqus discussion) latest post on home page. post has farther link posts own page well. have set disqus , need key info utilize disqus_url , disqus_identifier. have set model follows method get_absolute_url follows:

def get_absolute_url(self): homecoming reverse('blog.views.renderblog',args=[str(self.id),str(self.slug)])

my view set follows:

def renderblog(request,postid=1,slug=none): template = 'blog_home.html' if(postid == 1 , slug == none): post = post.objects.latest('date_created') else: post = post.objects.get(slug=slug, id=postid) info = { 'post':post, } homecoming render(request, template, data)

as can see view set handle both url's follows:

url(r'^$', 'renderblog', name='bloghome'), url(r'^post/(?p<postid>\d{1,4})/(?p<slug>[\w-]+)/$', 'renderblog', name='blogpostpage'),

in template setting disqus_identifier = '{{ post.get_absolute_url }}' , hardcoding domain portion in meantime disqus_url = 'http://127.0.0.1{{ post.get_absolute_url }}';.. same goes comment count <a href="" data-disqus-identifier.

i dont doing things in hackish manner, best method me total absolute url. have looked @ request.get_absolute_uri not sure on how utilize want.

thanks

the way configure context_processor:

from django.contrib.sites.models import site def base_context_processor(request): homecoming { 'base_url': "http://%s" % site.objects.get_current().domain } # or if don't want utilize 'sites' app homecoming { 'base_url': request.build_absolute_uri("/").rstrip("/") }

in settings.py:

template_context_processors = ( ... 'path.to.base_context_processor', ... )

(in newer versions of django, modify context_processors under templates, options instead.)

then in templates:

<a href="{{ base_url }}{{ obj.get_absolute_url }}">object name</a>

another solution utilize request.build_absolute_uri(location), have create template tag takes request object , location or object has get_absolute_uri method. able utilize templates that: {% get_full_uri request=request obj=post %}. here documentation on how write custom tags.

django

python - pass multiple dictionaries to a function as an argument -



python - pass multiple dictionaries to a function as an argument -

i have 2 dictionaries: sp=dict{'key1':'value1','key2':'value2'}, cp=dict{'key1':'value1','key2':'value2'}

i have function take 2 dictionaries inputs, don't know how that.

i'd tried:

def test(**sp,**cp): print sp.keys(),cp.keys() test(**sp,**cp)

the real function more complicated lots of modification of 2 dictionaries. simple test function doesn't work me :(

if want take 2 dictionaries separate arguments, do

def test(sp, cp): print sp.keys(),cp.keys() test(sp, cp)

you utilize ** when want pass individual key/value pairs of dictionary separate keyword arguments. if you're passing whole dictionary single argument, pass it, same way other argument value.

python dictionary arguments

javascript - how to play only one popup onclick link on jsp page -



javascript - how to play only one popup onclick link on jsp page -

javascript file

<script type="text/javascript"> function voddisplay(a,b) { `document.getelementbyid(b).innerhtml="<embed type='application/x`-`shockwave-flash' src='flash/player.swf' width='500' height='400' allowscriptaccess='always'` allowfullscreen='true' `flashvars='file="+a+"&image=preview.jpg&autostart=true'/>";` } </script>

my jsp page

<% arr_pubitr = arr_public.iterator(); int myvaluep=0; while(arr_pubitr.hasnext()){ pb = arr_pubitr.next(); string url = "http://ar.fun2shoot.com/"+pb.getcontent_id()+".flv"; myvaluep++; %> <div class="rightdata"> <a href="javascript:void(0);" style="text-decoration: none;" `onclick="return hs.htmlexpand(this , { width: 510, objectwidth: 510, objectheight:` `465,height: 465}),voddisplay('<%=url%>', 'abc<%=myvaluep%>')" class="playbtn">preview </a>` <div class="highslide-maincontent"> <div id="abc<%=myvaluep%>" class="buyme"></div>loading please... wait</div> <div> <img src="<%=pb.getpreview() %>" title ="<%=pb.gettitle() %>"/>`enter code here` <input style="margin-top: 5px;" type="checkbox" name="video_cont" value="<%=pb.getcontent_id() %>"/> <%=pb.getview_count() %> views </div> </div>

need 1 popup different different link play

javascript jsp

javascript - Angular application architecture + controller re-initialising issues -



javascript - Angular application architecture + controller re-initialising issues -

i have been developing angularjs search our website on lastly week , have ran big problem, think maybe misunderstanding of technology case (this first medium sized angularjs app).

basic overview of how app works

user types in search query, api returns data, i utilize ng-repeat on checkbox input field iterate on facets returned, each input field has ng-model (e.g. <input type="checkbox" ng-model="filters['key']['name'] />, property on filters object have (plain old empty js object), when user clicks facet (checks checkbox), property added filters (e.g. { brand: { sony: true } }, a have watch on filters, updates url + performs search.

here issues having

the initial page load blocking ui (the more facets returned api, bigger freeze), it's not noticeable on 100~ items (although there tiny delay!), 1 time bigger that, blocking ui noticeably long time.

the above not issue in itself, happy little delay on initial page load whilst ng-repeat adding stuff dom, when update $location.path, pretty url (after filter clicked), controller getting re-initialised, , huge freeze again.

here why think huge delay: route has changed, hence angular go fetch template again, re-initialise controller , in turn add together items dom again, correct?

i found using $location.search , reloadonsearch set false in route, controller isn't re-initialised, when click in browser, have write code handle both cases, ideally i'd utilize same code both!

i have tried various fixes found in angularjs github issues prevent path changes reloading controller, , briefly tried ui.router, both without success!

my questions

is there uniform way modify $location.path doesn't issue total controller reload, works / forwards buttons in browser? (using $location.search not issue if there isn't, how can ng-repeat not lock page whilst adding hundreds of elements dom? (since in scrollable list, need write custom directive partially render list? + add together more on scroll)

cheers.

answered myself after long search, , doesn't produce elegant solution!

i dropped in ui-router reloadonsearch: false, in states, downside have hear $locationchangesuccess event , lot of manual work populate scope state that's in url.

javascript angularjs architecture

python - If/Elif/Else statement issue. If if and elif not met, not going into else -



python - If/Elif/Else statement issue. If if and elif not met, not going into else -

sorry extremely obvious question, i've been having problem if/elif/else statement. statement never proceeds "else" area. if difference equal 0.

if difference > 0: difference_string = "the combination have %s cm gap beingness enclosed." % (difference) elif difference < 0: difference_string = "the combination exceed dimensions of shelf unit %s cm." % (difference) else: difference_string = "the combination enclose %s cm shelf unit." % (uh)

i don't what's not right. guess elif == 0, want understand error before work on fixing it.

here whole code:

def x38door_fit(uh): """uh = unit height door_fit(uh) --> x*38 door heights fit on uh. """ uh = int(uh) doors = uh / int(38) if uh % int(38) not 0: tuh = 0 counter = 0 d38 = int(38) while tuh < uh: d38 += 38 tuh = d38 counter += 1 tdh = counter * 38 #total door height = tdh difference = uh - tdh if difference > 0: difference_string = "the combination have %s cm gap beingness enclosed." % (difference) elif difference < 0: difference_string = "the combination exceed dimensions of shelf unit %s cm." % (difference) else: difference_string = "the combination enclose %s cm shelf unit." % (uh) print difference_string print doors homecoming doors

your problem line of code:

if uh % int(38) not 0:

if pass in 0, assigned uh, conditional evaluates 0. if/else block in question never executed because never reached.

python if-statement

.net - Performance issue with reading integers from a binary file at specific locations in F# -



.net - Performance issue with reading integers from a binary file at specific locations in F# -

this morning asked here why python code (a lot) slower f# version i'm wondering whether f# version can made faster. ideas how create faster version of below code reads sorted list of unique indexes binary file 32-bit integers? note tried 2 approaches, 1 based on binaryreader, other 1 based on memorymappedfile (and more on github).

module simpleread allow readvalue (reader:binaryreader) cellindex = // set stream right location reader.basestream.position <- cellindex*4l match reader.readint32() | int32.minvalue -> none | v -> some(v) allow readvalues filename indices = utilize reader = new binaryreader(file.open(filename, filemode.open, fileaccess.read, fileshare.read)) // utilize list or array forcefulness creation of values (otherwise reader gets disposed before values read) allow values = list.map (readvalue reader) (list.ofseq indices) values module memorymappedsimpleread = open system.io.memorymappedfiles allow readvalue (reader:memorymappedviewaccessor) offset cellindex = allow position = (cellindex*4l) - offset match reader.readint32(position) | int32.minvalue -> none | v -> some(v) allow readvalues filename indices = utilize mmf = memorymappedfile.createfromfile(filename, filemode.open) allow offset = (seq.min indices ) * 4l allow lastly = (seq.max indices) * 4l allow length = 4l+last-offset utilize reader = mmf.createviewaccessor(offset, length, memorymappedfileaccess.read) allow values = (list.ofseq indices) |> list.map (readvalue reader offset) values

for comparing here latest numpy version

class="lang-py prettyprint-override">import numpy np def convert(v): if v <> -2147483648: homecoming v else: homecoming none def read_values(filename, indices): values_arr = np.memmap(filename, dtype='int32', mode='r') homecoming map(convert, values_arr[indices])

update in contrary said before here, python still lot slower f# version due error in python tests appeared otherwise. leaving question here in case in depth knowledge of binaryreader or memorymappedfile knows improvements.

i managed simplereader 30% faster using reader.basestream.seek instead of reader.basestream.position. replaced lists arrays didn't alter lot.

the total code of simple reader now:

open scheme open system.io allow readvalue (reader:binaryreader) cellindex = // set stream right location reader.basestream.seek(int64 (cellindex*4), seekorigin.begin) |> ignore match reader.readint32() | int32.minvalue -> none | v -> some(v) allow readvalues indices filename = utilize reader = new binaryreader(file.open(filename, filemode.open, fileaccess.read, fileshare.read)) // utilize list or array forcefulness creation of values (otherwise reader gets disposed before values read) allow values = array.map (readvalue reader) indices values

the total code , versions in other languages on github.

.net f# binaryfiles memory-mapped-files binaryreader

ExtJs. Set rowediting cell value -



ExtJs. Set rowediting cell value -

i have grid rowediting plugin. editor have 2 columns: 1 combobox , disabled textfield.

i need alter textfield value after changing combobox value.

i have combobox listener:

listeners = { select: function (combo, records) { var editorrecord = mygrid.getplugin('roweditplugin').editor.getrecord(); editorrecord.data["somecol"] = "somevalue"; } }

but value in textfield not refresh until calling of roweditor.

i need set text value cell, without updating store. , if click cancel button of roweditor, need cell value returning old one.

thanks time, replies , help.

you can alter using selection model of grid,something :

{ text: 'type', dataindex: 'type', editor: { xtype: 'combo', typeahead: true, selectontab: true, displayfield:"name", listeners: { select: function(combo, records) { mygrid= this.up('grid'); var selectedmodel = this.up('grid').getselectionmodel().getselection()[0]; //selectedmodel.set('dataindexofnextcol', "success"); val = combo.getvalue(); if(val == 'type1'){ ext.getcmp('textfld').setvalue("success"); } else{ ext.getcmp('textfld').setvalue("failure"); } } }, { text: 'item', dataindex: 'item', editor: { xtype: 'textfield', id: 'textfld' } }

you have commit changes on update.so can phone call edit event listener,

listeners: { edit: function(editor, e) { e.record.commit(); } },

for reference , have @ demo

extjs

git - (There is no extension able to load the configuration for "sonata_block" -



git - (There is no extension able to load the configuration for "sonata_block" -

i finding error while generating admin panel in symfony 2.5. can 1 please tell me ? new symfony , unable it. error using git, when clear cache using, app/console cache:clear or thing else, same error in browser.

[symfony\component\config\exception\fileloaderloadexception] cannot import resource "d:\xampp\htdocs\myassignment\app/config\config.yml" "d:\xampp\htdocs\myassignment\app/config/config_dev.yml". (there n o extension able load configuration "sonata_block" (in d:\xampp\ htdocs\myassignment\app/config\config.yml). looked namespace "sonata_bl ock", found "framework", "security", "twig", "monolog", "swiftmailer", "ass etic", "doctrine", "sensio_framework_extra", "member", "sonata_admin", "son ata_doctrine_orm_admin", "acme_demo", "web_profiler", "sensio_distribution" ) [symfony\component\dependencyinjection\exception\invalidargumentexception] there no extension able load configuration "sonata_block" (in d:\xampp\htdocs\myassignment\app/config\config.yml). looked namespace "sonata_block", found "framework", "security", "twig", "monolog", "swiftmai ler", "assetic", "doctrine", "sensio_framework_extra", "member", "sonata_ad min", "sonata_doctrine_orm_admin", "acme_demo", "web_profiler", "sensio_dis tribution"

here code

imports: - { resource: parameters.yml } - { resource: security.yml } - { resource: @memberbundle/resources/config/admin.yml } framework: #esi: ~ #translator: { fallback: "%locale%" } secret: "%secret%" router: resource: "%kernel.root_dir%/config/routing.yml" strict_requirements: ~ form: ~ csrf_protection: ~ validation: { enable_annotations: true } templating: engines: ['twig'] #assets_version: someversionscheme default_locale: "%locale%" trusted_hosts: ~ trusted_proxies: ~ session: # handler_id set null utilize default session handler php.ini handler_id: ~ fragments: ~ http_method_override: true # twig configuration twig: debug: "%kernel.debug%" strict_variables: "%kernel.debug%" # assetic configuration assetic: debug: "%kernel.debug%" use_controller: false bundles: [ ] #java: /usr/bin/java filters: cssrewrite: ~ #closure: # jar: "%kernel.root_dir%/resources/java/compiler.jar" #yui_css: # jar: "%kernel.root_dir%/resources/java/yuicompressor-2.4.7.jar" # doctrine configuration doctrine: dbal: driver: "%database_driver%" host: "%database_host%" port: "%database_port%" dbname: "%database_name%" user: "%database_user%" password: "%database_password%" charset: utf8 # if using pdo_sqlite database driver, add together path in parameters.yml # e.g. database_path: "%kernel.root_dir%/data/data.db3" # path: "%database_path%" orm: auto_generate_proxy_classes: "%kernel.debug%" auto_mapping: true # swiftmailer configuration swiftmailer: transport: "%mailer_transport%" host: "%mailer_host%" username: "%mailer_user%" password: "%mailer_password%" spool: { type: memory } sonata_block: default_contexts: [cms] blocks: # enable sonataadminbundle block sonata.admin.block.admin_list: contexts: [admin] # other blocks

here kernel

you should register sonatablockbundle in appkernel.php

git symfony2

Getting warning error in vhdl code -



Getting warning error in vhdl code -

i maintain getting unusual error in code, compiles fine maintain getting warning:

warning: unconnected, internal signal \s(0)d\ promoted input pin.

warning: unconnected, internal signal \s(1)d\ promoted input pin.

the code basic register resets, shifts left , inserts s_in, , loads values set register using pload. can help me figure out wrong it?

library ieee; utilize ieee.std_logic_1164.all; entity special_register port( data: in std_logic_vector(3 downto 0); reset: in std_logic; pload: in std_logic; s_right: in std_logic; s_in: in std_logic; clock : in std_logic; s: in std_logic_vector(1 downto 0); d: out std_logic_vector(3 downto 0); q : out std_logic_vector(3 downto 0)); end special_register; architecture behav of special_register begin process(clock, data, reset, s_in, s, s_right, pload) begin if rising_edge(clock) s(0) <= (s_right); s(1) <= (pload); if (s(1) = '1') d(3) <= data(3); d(2) <= data(2); d(1) <= data(1); d(0) <= data(0); else if (s(0) = '0') d(0) <= q(1); d(1) <= q(2); d(2) <= q(3); d(3) <= s_in; end if; end if; end if; end process; q(3) <= (not reset) , d(3); q(2) <= (not reset) , d(2); q(1) <= (not reset) , d(1); q(0) <= (not reset) , d(0); end behav;

in add-on brian's reply note design specification not vhdl compliant , presumed synthesis tool isn't either:

ghdl -a special_register.vhdl special_register.vhdl:21:2: port "s" can't assigned special_register.vhdl:22:2: port "s" can't assigned special_register.vhdl:29:14: port "q" cannot read special_register.vhdl:30:14: port "q" cannot read special_register.vhdl:31:14: port "q" cannot read special_register.vhdl:37:26: port "d" cannot read special_register.vhdl:38:26: port "d" cannot read special_register.vhdl:39:26: port "d" cannot read special_register.vhdl:40:26: port "d" cannot read ghdl: compilation error

(it seem trying read output port well).

warnings vhdl

javascript - Radio button and check box checked, depending on value on the top of the page -



javascript - Radio button and check box checked, depending on value on the top of the page -

i have page depending on val on top of page, select check boxes shown or hidden.

if value val check boxes shown , after selecting check box, values populated in text area. far works.

now if value mar check boxes hidden. values not populating in text area.

help much appreciated. fiddle

$('table').find("input[type=radio]:checked:enabled").each(function () { if($('table').find("input[type=checkbox][name='" + $(this).attr('name') + "']").is(':checked')) { // see if have text box, if utilize text var $text = $(this).parent().find('textarea.m-notes:visible'); var missingreason = $(this).parent().find('.reason').val(); // find closest ancestor id var selectedid = $(this).closest('[id]').attr('id'); var value = selectedid + "~" + $(this).val(); if ($text.length) { value += "~" + missingreason +"~" + $text.val(); } clicked.push(value); } }); //checked // display selected ids $("#inputhere").val(clicked.join('|')); }

javascript jquery

php array, only last item in array is correct -



php array, only last item in array is correct -

below code should create problem clear. code irrelevant problem has been left out, e.g. fetching contents of url, printing contents new file.

can explain why variables jumbled except lastly item?

<?php $f = fopen("cucina2.txt", "r"); // read line line until end of file while (!feof($f)) { // create array using newline delimiter $arrm = explode("\n",fgets($f)); //add word url address $url = 'hhttp://www.some.com/vocab/' . $arrm[0] . '/'; //create text file word $glossary = $arrm[0]; $glossary .= '.txt'; //check functions echo "arrm is: "; echo $arrm[0]; echo "\n"; echo "glossary is: "; echo $glossary; echo "\n"; echo "url is: "; echo $url; echo "\n"; } ?>

cucina.txt:

batticarne battuto bavarese bavetta

results:

arrm is: batticarne .txtsary is: batticarne /rl is: hhttp://www.some.com/vocab/batticarne arrm is: battuto .txtsary is: battuto /rl is: hhttp://www.some.com/vocab/battuto arrm is: bavarese .txtsary is: bavarese /rl is: hhttp://www.some.com/vocab/bavarese arrm is: bavetta glossary is: bavetta.txt url is: hhttp://www.some.com/vocab/bavetta/

it appears info file (cucina.txt) contains windows-style line breaks ("\r\n"). when split input lines @ \n, left trailing carriage homecoming \r @ end of each slice.

try instead:

$arrm = preg_split('/[\r\n]+/',fgets($f));

also, aware while (!feof($f)) wrong. should check eof when reading file, not @ top of loop. way avoid processing empty lines.

while (!feof($f)) { $s = fgets($f); if (!$s) break; $arrm = preg_split('/[\r\n]+/',$s); : : }

php arrays

ios - Get all latitudes and longitudes between source and destination coordinates in iPhone -



ios - Get all latitudes and longitudes between source and destination coordinates in iPhone -

i want retrieve latitudes , longitudes between source , destination coordinates.i know can create path between source , destination coordinates want latitudes , longitudes between them purpose of user movement.i using mkmapview show coordinates , cllocationmanager retrieve current location.i new in iphone.i searched question did not accurate results.please help me.

this high school algebra problem. if have point , point b (in views coordinate system) can find equation describes line between two. you'll want utilize point slope formula. 1 time have equation describes line can find points between them, there infinite number of points on line. you'll have decide level of of accuracy want. anyways simple loop point a's x point b's x, evaluating equation , solving y @ each iteration should yield set of points. can utilize convertpoint method mkmapview lat , long.

- (cllocationcoordinate2d)convertpoint:(cgpoint)point tocoordinatefromview:(uiview *)view

edit: update concrete example

this assuming have mkmapview instance someplace. should go within of mapview. if need more explanation might want check out mathisfun.com http://www.mathsisfun.com/algebra/line-equation-2points.html

mkmapview mapview.... //this job intialize, code belongs within //your mapview should assigned self. //point slope formula: y - y1 = m*(x - x1) //m = x-x1 / y - y1 //two points line starts @ 0,0 , goes diagonlly right @ 45 grade angle cgpoint pointa = cgpointmake(0, 0); cgpoint pointb = cgpointmake(10, 10); //find slope cgfloat m = (pointb.y - pointa.y) / (pointb.x - pointa.x); nsmutablearray *points = [[nsmutablearray alloc] init]; (int = pointa.x; <= pointb.x; i++) { //for each x value between , b utilize point slope formula find y value //since starting @ pointa (0, 0) our equation becomes //y - 0 = m * (x - 0), simplifying , solving y //y = m * (x - 0) -> y = m*x, , since increment x each time our equatio evaluate // y = m*i cgfloat y = m*i; cgpoint c = cgpointmake(i, y); cllocationcoordinate2d coordinate = [mapview convertpoint:c tocoordinatefromview:self.view]; //for simplicity in adding array convert cllocation object since nsarray can hold objects cllocation *location = [[cllocation alloc] initwithlatitude:coordinate.latitude longitude:coordinate.longitude]; [points addobject:location]; }

ios objective-c ios7

jquery - Move contents of hidden child div -



jquery - Move contents of hidden child div -

i'm trying move contents of hidden kid div class details div id section1target says details not defined.

i tried

$( '.profile' ).click(function() { $('#section1target').html($(this + '.details').html()); //also tried.. $('#section1target').html($(this).next('.details').html()); }); <div class="container margint30"> <ul class="thumbnails row-fluid" id="section1"> <li class="span3 offset3 profile"> <div class="thumbnail"> <div class="row-fluid"> <img src="img.png" alt=""> </div> <div class="row-fluid"> <h3></h3> <h4 class="margint10">title</h4> <div class="row-fluid details hidden-details"> <p> lorem ipsum dolor sit down amet, consect </p> <p> lorem ipsum dolor sit down amet, consectetur advertisement </p> </div> </div> </div> </li> <li class="span3 profile"> <div class="thumbnail"> <div class="row-fluid"> <img src="img.png" alt=""> </div> <div class="row-fluid"> <h3></h3> <h4 class="margint10">title</h4> <div class="row-fluid details"> <p> lorem ipsum dolor </p> <p> lorem ipsum dolor sit down amet </p> </div> </div> </div> </li> </ul> </div> <div id="section1target"></div>

use:

$('#section1target').html($(this).find(".details").html());

.next() works if element next sibling, not descendant. $(this)+".details" doesn't create sense @ all, since $(this) jquery object, not string.

jquery

java - JSON encoding returning NULL -



java - JSON encoding returning NULL -

im working on app users needs login to. coded in java, login works without problems. however, want receive "message" json , display it. said, code works, if json string "message" dosent contain special characters æ, ø, å. i've tried anything, also, have file gets info db , shows in listview, used exact same code, , works. json in login.php returns null, replaces whole string , replaces null.

my login.php (returning null)

<?php header('content-type:text/json;charset=utf-8'); $uname = $_post["txtuname"]; $pass = $_post["txtpass"]; $con=mysqli_connect("localhost","user","pass","db");// check connection if (mysqli_connect_errno()) { $response["success"] = 0; $response["message"] = "database error!"; die(json_encode($response)); echo "failed connect mysql: " . mysqli_connect_error(); } //mysql_query("set names 'utf8'", $con); mysql_query("set names 'utf8'"); $result = mysqli_query($con,"select * users email='$uname' , encrypted_password='$pass'"); while($row = mysqli_fetch_array($result)) { $response["success"] = 1; $response["message"] = $row['firstname'] . " " . $row['lastname']; die(json_encode($response)); //header("location: home.php"); } mysqli_close($con); ?>

my getdata.php (works)

<?php include "db_config.php"; $cat = $_get['app_category']; if($cat == '99'){ mysql_query("set names 'utf8'"); $sql=mysql_query("select * `test_fc`"); while($row=mysql_fetch_assoc($sql)) $output[]=$row; print ('{ "app_item":'); print(json_encode($output)); print ('}'); mysql_close(); } else { mysql_query("set names 'utf8'"); $sql=mysql_query("select * `test_fc` app_category={$cat}"); while($row=mysql_fetch_assoc($sql)) $output[]=$row; print ('{ "app_item":'); print(json_encode($output)); print ('}'); mysql_close(); } ?>

my java parser can read getdata.php without problem, special characters.

i've been stuck on past couple of days. help much appreciated!

edit: getting {"message":null,"success":}

the problem line:

mysql_query("set names 'utf8'");

you using mysql_* function while rest - , database connection - using mysqli_*. lead warning in php gets echoed out , invalidates json.

you should utilize either mysqli (preferred) or mysql (deprecated) not mix them.

java php android mysql json

android - Getting size from view that places inside a ViewGroup with GONE visibility (programatically it will be set as VISIBLE) -



android - Getting size from view that places inside a ViewGroup with GONE visibility (programatically it will be set as VISIBLE) -

i'm trying image photographic camera device, save it, , show preview in imageview.

my imageview (named imagepreview) defined within next layout:

<linearlayout android:id="@+id/ll_selected_image" android:layout_width="match_parent" android:layout_height="300dp" android:orientation="vertical" android:layout_gravity="center_horizontal" android:visibility="gone"> <!-- @ first gone --> <relativelayout android:layout_width="match_parent" android:layout_height="match_parent"> <imageview android:id="@+id/imagepreview" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_centerinparent="true"/> </relativelayout> </linearlayout>

when image acquired camera, seek scale image next this document, code is:

private void setpic() { // dimensions of view int targetw = mimageview.getwidth(); int targeth = mimageview.getheight(); // dimensions of bitmap bitmapfactory.options bmoptions = new bitmapfactory.options(); bmoptions.injustdecodebounds = true; bitmapfactory.decodefile(mcurrentphotopath, bmoptions); int photow = bmoptions.outwidth; int photoh = bmoptions.outheight; // determine how much scale downwards image int scalefactor = math.min(photow/targetw, photoh/targeth); // decode image file bitmap sized fill view bmoptions.injustdecodebounds = false; bmoptions.insamplesize = scalefactor; bmoptions.inpurgeable = true; bitmap bitmap = bitmapfactory.decodefile(mcurrentphotopath, bmoptions); mimageview.setimagebitmap(bitmap); }

the problem obtain "division zero" mimageview.getwidth(); , mimageview.getheight(); homecoming zero.

note visibility of parent linearlayout setted gone. then, application sets programmatically visible.

if remove gone, , add together visible instead, works good!

the unusual thing have tried add together in setpic(), first code lines, next code:

if(ivselectedimage.getvisibility() == view.visible) log.i(tag,"is visible!"); else if(ivselectedimage.getvisibility() == view.gone) log.i(tag,"is gone!"); else if(ivselectedimage.getvisibility() == view.invisible) log.i(tag,"is invisible!");

and prints in console "is visible"!

briefly: if set gone in xml, , set visible (programmatically) getheight() , getwidth() can't right value (also if when phone call these methods view visible). while, if set visible in xml, methods getheight() , getwidth() homecoming me right values.

you don't need utilize view size @ runtime example. based on code, while view visibility set gone main container, linearlayout, fixed height of 300dp. result, know 1 of dimensions of view since @ best android:layout_height="match_parent" can equal 300dp.

to scale need screen width - since main view (and nested relativelayout , imageview set match_parent). if you're in activity utilize this

display display = getwindowmanager().getdefaultdisplay(); point size = new point(); display.getsize(size); int width = size.x;

otherwise can display using

windowmanager wm = (windowmanager) context.getsystemservice(context.window_service); display display = wm.getdefaultdisplay();

just run calculation before need set image. store results sharedpreferences or , utilize ratio 300dp height , screen width scale image.

android android-layout imageview android-linearlayout android-bitmap

svn - Can I run mod_dav_svn and svnserve on the same server -



svn - Can I run mod_dav_svn and svnserve on the same server -

i need expose our subversion repo on http / https, i'm having problem getting maven , subversion play on svn+ssh. real issue corporate restriction whereby we're not allowed generic unix business relationship (so maven svn+ssh without using personal user account). intention utilize maven generic business relationship perform branch , release functions. can on http can set local .htaccess style business relationship authenticate maven.

my question if there concerns or gotchas need aware of when having users committing on http , via svn+ssh?

if there concerns or gotchas need aware

no. utilize same folder svnparentpath in apache , -r of svnserve (for simplicity - same hotname, protocol differ)

svn svnserve mod-dav-svn

mysql - Historical inventory by day -



mysql - Historical inventory by day -

i using mysql , have table log inventory orders. table (a simplification) looks this:

||id|ordered_date |date |itemid| status || ||1 |jan-4 |jan-4 | | ordered || ||2 |jan-6 |jan-6 | b | ordered || ||3 |jan-8 |jan-8 | c | ordered || ||4 |jan-8 |jan-9 | c | shipped || ||4 |jan-6 |jan-9 | b | shipped || ||4 |jan-4 |jan-10| | shipped ||

what want total number of orders per day have not yet shipped, this:

date | inventory jan-4 | 1 jan-5 | 1 jan-6 | 2 jan-7 | 2 jan-8 | 3 jan-9 | 1 jan-10| 0

i can find total number of unshipped orders on single day using query this:

select count(*) inventory status = "shipped" , date > "jan-8" , ordered_date <= "jan-8"

but need number of orders days. , above query has problem in won't find orders have not shipped yet. so, help appreciated.

(assume date column valid sql date)

try this:

select date, count(*) inventory status != 'shipped' grouping date order date;

mysql sql

JavaScript dynamically detect all CSS values -



JavaScript dynamically detect all CSS values -

this script dynamically detects possible style properties element supports...

for (i in document.getelementbyid('body').style) { document.getelementbyid('q').value = document.getelementbyid('q').value+', '+i; }

my question how dynamically observe possible values given property supports? dynamic clearly mean not creating array possible values (static) , iterating on array using css.supports.

im not sure that's possible since endless. looking see classes of values acceptable.

when property value number top accepts length can in, cm, mm, pt, pc, px, ex, em, percentage, auto, or inherit

in case of content accepts different range of values normal, none, string's, uri's, counter, attr(attrname), open-quote, close-quote, no-open-quote, no-close-quote, inherit (and it's possible it's looking combination of things)

(src:w3.org)

each property described in w3 document has different set of types accepts.

i don't know how javascript spit out kind of schema/dtd come exhaustive list of potential values represent classes of values , test each using css.supports(propertyname,value);

javascript css

c# - resolve dependencies in viewModel -



c# - resolve dependencies in viewModel -

i have viewmodel supplierviewmodel set datacontext of view viewmodel in xaml using mvvm lights viewmodellocator instance.

here view :

<usercontrol xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" x:class="rh_maize.supplierview" x:name="usercontrol" d:designwidth="1040" d:designheight="630" datacontext="{binding supplier, source={staticresource locator}}"> <!--ui elements goes here--> </usercontrol>

here viewmodel locator :

public class viewmodellocator { static viewmodellocator() { servicelocator.setlocatorprovider(() => simpleioc.default); simpleioc.default.register<mainviewmodel>(); if (viewmodelbase.isindesignmodestatic) { simpleioc.default.register<isupplierdataservice, supplierdataservicemock>(); } else { simpleioc.default.register<isupplierdataservice, supplierdataservice>(); } } #region here create , expose of applications viewmodels /// <summary> /// gets main property. /// </summary> [system.diagnostics.codeanalysis.suppressmessage("microsoft.performance", "ca1822:markmembersasstatic", justification = "this non-static fellow member needed info binding purposes.")] public mainviewmodel main { { homecoming simpleioc.default.getinstance<mainviewmodel>(); } } public supplierviewmodel supplier { { homecoming new supplierviewmodel(); } } } /// <summary> /// cleans resources. /// </summary> public static void cleanup() { } }

viewmodel :

public class supplierviewmodel : workspaceviewmodel,idataerrorinfo { #region fields readonly supplier _supplier; readonly supplierrepository _supplierrepository; private idialogservice _dialogservice; #endregion //fields #region constructor public supplierviewmodel(supplier supplier, supplierrepository supplierrepository, idialogservice service) { _supplier = supplier; _supplierrepository = supplierrepository; _dialogservice = service; } #endregion //constructor }

my problem:

how resolve these dependencies ?

how able populate disign time info on ui , know, back upwards design time info in view want paraemeterless constructor in viewmodel ?

c# wpf mvvm mvvm-light

amazon web services - Chef:Error executing action `install` on resource 'package[httpd]' -



amazon web services - Chef:Error executing action `install` on resource 'package[httpd]' -

i using chef create server in aws amazon environment using knife ec2 plugin.

i have created ec2 server using next command:

knife ec2 server create --image ami-7c807d14 --flavor t1.micro --region us-east-1 --security-group-ids sg-id --ebs-size 10 --ebs-no-delete-on-term --tags name=test_server --server-connect-attribute private_ip_address --subnet subnet-id --ssh-user ec2-user --identity-file ~/.ssh/key.pem --environment testing --node-name redhat-server

when ssh chef node , run next command sudo chef-client install apache on node, gives me error:

[2014-06-24t07:44:55+00:00] warn: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ssl validation of https requests disabled. https connections still encrypted, chef not able observe forged replies or man in middle attacks. prepare issue add together entry configuration file: ``` # verify https connections (recommended) ssl_verify_mode :verify_peer # or, verify connections chef-server verify_api_cert true ``` check ssl configuration, or troubleshoot errors, can utilize `knife ssl check` command so: ``` knife ssl check -c /etc/chef/client.rb ``` * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * starting chef client, version 11.12.8 resolving cookbooks run list: ["apache-tutorial-1"] synchronizing cookbooks: - apache-tutorial-1 compiling cookbooks... converging 4 resources recipe: apache-tutorial-1::default * package[httpd] action install ================================================================================ error executing action `install` on resource 'package[httpd]' ================================================================================ mixlib::shellout::shellcommandfailed ------------------------------------ expected process exit [0], received '1' ---- begin output of /usr/bin/python /opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.12.8/lib/chef/provider/package/yum-dump.py --options --installed-provides ---- stdout: [option installonlypkgs] kernel kernel-devel kernel-source installonlypkg(kernel) installonlypkg(kernel-module) installonlypkg(vm) stderr: yum-dump repository error: failure: repodata/repomd.xml amzn-main: [errno 256] no more mirrors try. ---- end output of /usr/bin/python /opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.12.8/lib/chef/provider/package/yum-dump.py --options --installed-provides ---- ran /usr/bin/python /opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.12.8/lib/chef/provider/package/yum-dump.py --options --installed-provides returned 1 resource declaration: --------------------- # in /var/chef/cache/cookbooks/apache-tutorial-1/recipes/default.rb 11: bundle 'httpd' 12: action :install 13: end 14: compiled resource: ------------------ # declared in /var/chef/cache/cookbooks/apache-tutorial-1/recipes/default.rb:11:in `from_file' package("httpd") action [:install] retries 0 retry_delay 2 guard_interpreter :default package_name "httpd" cookbook_name "apache-tutorial-1" recipe_name "default" end running handlers: [2014-06-24t07:45:04+00:00] error: running exception handlers running handlers finish [2014-06-24t07:45:04+00:00] error: exception handlers finish [2014-06-24t07:45:04+00:00] fatal: stacktrace dumped /var/chef/cache/chef-stacktrace.out chef client failed. 0 resources updated in 9.101137934 seconds [2014-06-24t07:45:04+00:00] error: package[httpd] (apache-tutorial-1::default line 11) had error: mixlib::shellout::shellcommandfailed: expected process exit [0], received '1' ---- begin output of /usr/bin/python /opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.12.8/lib/chef/provider/package/yum-dump.py --options --installed-provides ---- stdout: [option installonlypkgs] kernel kernel-devel kernel-source installonlypkg(kernel) installonlypkg(kernel-module) installonlypkg(vm) stderr: yum-dump repository error: failure: repodata/repomd.xml amzn-main: [errno 256] no more mirrors try. ---- end output of /usr/bin/python /opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.12.8/lib/chef/provider/package/yum-dump.py --options --installed-provides ---- ran /usr/bin/python /opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.12.8/lib/chef/provider/package/yum-dump.py --options --installed-provides returned 1 [2014-06-24t07:45:05+00:00] fatal: chef::exceptions::childconvergeerror: chef run process exited unsuccessfully (exit code 1)

please help me resolve issue.

in case there problem yum on linux ami.

the same command ran create centos machine worked.

amazon-web-services amazon-ec2 chef-recipe bootstrapping

c# - Select XElements from comma separated values -



c# - Select XElements from comma separated values -

i using linq-to-xml in project , want extract elements in comma separated string i.e.

here sample xml file

<?xml version="1.0" encoding="utf-8"?> <newdataset> <table> <entity>employee</entity> <entityid>2857</entityid> .. more nodes... .. more nodes... </table> <table> <entity>employee</entity> <entityid>2856</entityid> .. more nodes... .. more nodes... </table> ....... </newdataset>

here xelement:

xelement mainentities = xelement.load(strfilename); ienumerable<xelement> entityelements; entityelements = mainentities.elements("table").where(xtab => (string)xtab.element("entity").value == "employee");

and comma separated string

var filter = new list<string> { stremployeeids };

i tried

entityelements = mainentities.elements("table").where(xtab => (string)xtab.element("entity").value == "employee" && filter.contains((string)xtab.element("entityid").value));

but it's not working...

how can got elements in filter entityelements;

assuming stremployeeids defined this:

string stremployeeids = "1,2,3";

you need split string create list out of it:

string[] filter = stremployeeids.split(',');

c# xml linq

Android Fragment Tabs using - android.support.v4.app.Fragment -



Android Fragment Tabs using - android.support.v4.app.Fragment -

i trying create app 3 tabs fragments want utilize new android.support.v4.app.fragment in android. can't work.

i tried illustration implementing-fragment-tabs-in-android. works problem android.app.fragment; works api 11 , above. , want target api 8 , above.

here code:

import android.app.fragment; import android.os.bundle; import android.support.v4.app.fragmenttransaction; import android.support.v7.app.actionbar; import android.support.v7.app.actionbar.tab; import android.support.v7.app.actionbaractivity; import android.view.menu; import android.view.menuitem; public class mainactivity extends actionbaractivity implements actionbar.tablistener { public static final string tag = mainactivity.class.getsimplename(); // declare tab variable actionbar.tab tab1, tab2, tab3; fragment fragmenttab1 = new fragmenttab1();//error = type mismatch: cannot convert fragmenttab1 fragment fragment fragmenttab2 = new fragmenttab2();//error = type mismatch: cannot convert fragmenttab1 fragment fragment fragmenttab3 = new fragmenttab3();//error = type mismatch: cannot convert fragmenttab1 fragment @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); //hide action bar actionbar actionbar = getsupportactionbar(); actionbar.hide(); // hide actionbar icon actionbar.setdisplayshowhomeenabled(false); // hide actionbar title actionbar.setdisplayshowtitleenabled(false); // create actionbar tabs actionbar.setnavigationmode(actionbar.navigation_mode_tabs); // set tab icon , titles tab1 = actionbar.newtab().settext("tab1");//.seticon(r.drawable.tab1); tab2 = actionbar.newtab().settext("tab2"); tab3 = actionbar.newtab().settext("tab3"); // set tab listeners tab1.settablistener(new tablistener(fragmenttab1)); tab2.settablistener(new tablistener(fragmenttab2)); tab3.settablistener(new tablistener(fragmenttab3)); // add together tabs actionbar actionbar.addtab(tab1); actionbar.addtab(tab2); actionbar.addtab(tab3); }//-----end oncreate //implements actionbar.tablistener -------------------------- @override public void ontabreselected(tab arg0, fragmenttransaction arg1) { // todo auto-generated method stub } @override public void ontabselected(tab arg0, fragmenttransaction arg1) { // todo auto-generated method stub } @override public void ontabunselected(tab arg0, fragmenttransaction arg1) { // todo auto-generated method stub } //action bar of appcombat --------------------- @override public boolean oncreateoptionsmenu(menu menu) { // inflate menu; adds items action bar if present. getmenuinflater().inflate(r.menu.main, menu); homecoming true; } @override public boolean onoptionsitemselected(menuitem item) { // handle action bar item clicks here. action bar // automatically handle clicks on home/up button, long // specify parent activity in androidmanifest.xml. int id = item.getitemid(); if (id == r.id.action_settings) { homecoming true; } homecoming super.onoptionsitemselected(item); } }//--end body

thanks help. :)

import android.app.fragment;

your import(s) have consistent. if utilize back upwards library related imports should back upwards library.

android android-activity android-fragments fragment android-actionbaractivity

javascript - Use ID from one page in JQuery -



javascript - Use ID from one page in JQuery -

i have dynamic html in page. want utilize id , info 1 js file other.

i have next html in care.js file

$('#chat-box').html( '<p style="margin-top:10px;">enter name</p><input type="text" id="chat-box-name" class="chat-editing" />' );

now want utilize info entered in above input box in chat.js.

is possible can usethe id/data 1 js file other in same project??

thanks

when code executes have element code child:

<div id="chat-box"> <p style="margin-top:10px;">enter name</p> <input type="text" id="chat-box-name" class="chat-editing" /> </div>

if create sure code sec javascript file gets executed after added content #chat-box can utilize javascript value of inputbox. assuming utilize jquery, did in question:

var input = $('#chat-box-name').val(); //the input

pure javascript:

var input = document.getelementbyid('chat-box-name').value;

javascript jquery html

c# - Exceptions lose part of stacktrace in try/catch context -



c# - Exceptions lose part of stacktrace in try/catch context -

i have 2 examples. in first case, debugger catches unhandled exception:

static void main(string[] args) { exec(); } static void exec() { throw new exception(); }

and exception has total stacktrace:

@ consoleapplication28.program.exec() @ consoleapplication28.program.main(string[] args) @ system.appdomain._nexecuteassembly(runtimeassembly assembly, string[] args) @ system.appdomain.executeassembly(string assemblyfile, evidence assemblysecurity, string[] args) @ microsoft.visualstudio.hostingprocess.hostproc.runusersassembly() @ system.threading.threadhelper.threadstart_context(object state) @ system.threading.executioncontext.runinternal(executioncontext executioncontext, contextcallback callback, object state, boolean preservesyncctx) @ system.threading.executioncontext.run(executioncontext executioncontext, contextcallback callback, object state, boolean preservesyncctx) @ system.threading.executioncontext.run(executioncontext executioncontext, contextcallback callback, object state) @ system.threading.threadhelper.threadstart()

the sec case:

static void main(string[] args) { exec(); } static void exec() { seek { throw new exception(); } grab (exception ex) { } // breakpoint }

at breakpoint exception has short stacktrace:

@ consoleapplication28.program.exec()

why stacktraces cutting containing method in sec case, , how prevent it? need total stacktrace bugreports, otherwise it's not possible find there problem is, without total stacktrace.

what you're seeing in visual studio debugger unhandled exception visual studio hosting process trapping (ie after first 2 stack frames part of vs "host plumbing"). if disable hosting process (project properties->enable visual studio hosting process), you'll see "short" stack trace in both scenarios (notwithstanding won't see stack frame main in sec case because exception "handled", not allowed propagate main). shorter stack trace stack trace see if running application outside debugger.

the stack works imagine - each method phone call pushes stack frame onto it, , @ end of method stack frame "popped", or removed stack. stack trace see on exception composed of stack frames frame exception thrown, frame exception handled, stack "unwound".

c# .net exception exception-handling stack-trace

android - HtmlHelper library in java - source not found -



android - HtmlHelper library in java - source not found -

help me please found error in java-method onitemclick. when comment code in try-catch construction - programme runs, in otherwise - programme crashes error "source not found". prefer, error starts hh = new htmlhelper(new url((string) url)) string.

@override public void onitemclick(adapterview<?> adapter, view view, int position, long arg) { string stringdata; intent intent = new intent(stackparser.this, availablecontent.class); url = (string) murls.get(output.get(position)); toast.maketext(getapplicationcontext(), url, toast.length_short).show(); htmlhelper hh; seek { hh = new htmlhelper(new url((string) url)); timeunit.seconds.sleep(5); list<tagnode> links = hh.getlinksbyclass("texts"); iterator<tagnode> iterator = links.iterator(); iterator.hasnext(); tagnode divelement = (tagnode) iterator.next(); stringdata = divelement.gettext().tostring(); if(!stringdata.equals("")) { intent.putextra("send content-activity", stringdata); startactivity(intent); finish(); } else { intent.putextra("send content-activity", "empty"); startactivity(intent); finish(); } } grab (malformedurlexception e) { toast.maketext(getapplicationcontext(), "1", toast.length_short).show(); // todo auto-generated grab block e.printstacktrace(); } grab (ioexception e) { toast.maketext(getapplicationcontext(), "2", toast.length_short).show(); // todo auto-generated grab block e.printstacktrace(); } grab (interruptedexception e) { e.printstacktrace(); } } });

java android eclipse

tornado - Push javascript array back to server via a form? -



tornado - Push javascript array back to server via a form? -

how can force js variable server?

for example, have array:

i trying find way force array server , save csv file. using python end.

javascript tornado

python - Print encoded string -



python - Print encoded string -

i'm developing own mp3 decoder using python i'm little bit stuck decoding id3 tag. don't want utilize existing libraries mutagen or eyed3 follow id3v2 specification.

the problem frame info encoded in format cannot print, using debugger see value "hideaway" it's preceded unusual characters can see here:

'data': '\\x00hideaway'

i have next questions: kind of encoding that? how can decode , print string? think other mp3 files utilize different encoding in id3 tags?

by way, i'm using utf-8 declaration @ top of file

# -*- coding: utf-8 -*-

and i'm reading file using normal i/o methods in python (read())

the characacters \\x00 indicate single byte value of 0 precedes h. so, string looks this:

class="lang-none prettyprint-override">zero - h - - d - e ...

usually character strings have letters or numbers in them, not zero. perhaps usage specific id3v2?

considering idc3v2 standard (http://id3.org/id3v2.4.0-structure), see is:

class="lang-none prettyprint-override">frames allow different types of text encoding contains text encoding description byte. possible encodings: $00 iso-8859-1 [iso-8859-1]. terminated $00. $01 utf-16 [utf-16] encoded unicode [unicode] bom. strings in same frame shall have same byteorder. terminated $00 00. $02 utf-16be [utf-16] encoded unicode [unicode] without bom. terminated $00 00. $03 utf-8 [utf-8] encoded unicode [unicode]. terminated $00.

so, see 0 byte indicates iso-8859-1 encoding, next 0 byte.

your programme might deal so:

class="lang-python prettyprint-override">title = fp.read(number_of_bytes) if(title[0] == '\x00') title = title[1:].decode('iso8859-1') elif(title[0] == ... else ...) title = title[1:].decode('some-other-encoding') ...

python encoding mp3

regex - How can i get content between dates using java regular expressions -



regex - How can i get content between dates using java regular expressions -

below code did not me content between dates.can please help me.

string res="05/22/2014 03:22:39.288 ffff gggg kkkkkk lllllll ssss 05/22/2014 03:22:39.288 oooooo ppppp qqqq rrrrrr sss 05/22/2014 03:22:39.378 mmmmmm nnn oooo "; string regex="((0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])/((19|20)\\d\\d).*([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9].[\\d]*)(.*?)((0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])/((19|20)\\d\\d).*([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9].[\\d]*)?"; matcher matcher = pattern.compile(regex).matcher(res); while(matcher.find()) { string grouping = matcher.group(); system.out.println(group); }

even tried below using string split regular look in java gives 1 result:

string regex="((0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])/((19|20)\\d\\d).*([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9].([\\d][^\\s]+)?)"; string[] split = res.split(regex);

you can utilize regex capture text:

(?<=\d{2}/\d{2}/\d{4} \d{2}:\d{2}:\d{2}\.\d{3} )(.*?)(?=(?: \d{2}/\d{2}/\d{4} \d{2}:\d{2}:\d{2}\.\d{3}|$))

and grab text in grouping #1 i.e.

matcher.group(1); working demo

java regex

c# - How to get selected value from @Html.DropDownList -



c# - How to get selected value from @Html.DropDownList -

the project .net framework3.5 , mvc framework 1.0

in view have dropdown

@html.dropdownlist("prodlist",@model.products)

a add together product button

<td> <input type ="button" name ="add product" value ="add product" id="button1" /> </td>

and textbox @html.textbox ("prodselected")

when click add together product button should able display value of item selected on dropdownlist in textbox "prodselected"

please can 1 allow me know how it. if there alter needed in existing code please suggest.

the view is:

<%@ page language="c#" inherits="system.web.mvc.viewpage<mockbdpworkflowtestapp.viewmodels.workflowtestviewmodel>" %> <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="head1" runat="server"> <title>submission</title> </head> <body> <div> <% using (html.beginform()) { %> <div> <table> <tr> <td> <div id="sid"> <table id="tblid" cellpadding ="0" cellspacing ="0" border="1"> <tr> <td width ="50%"> <label for="process inastance id"> process inastance id: </label> &nbsp;&nbsp; <%=@html.textbox("pinstance",@model.processinstance) %></td> <td width ="50%"> <label ="mail id">mail id: </label> &nbsp;&nbsp; <%=@html.textbox("mail",@model.mail) %> </td> </tr> </table> </div> <br /><br /> <table id="tbldet" cellpadding ="0" cellspacing ="0" > <tr> <td width="50%"> <label for="submission number"> submission number: </label> &nbsp;&nbsp; <%=@html.textbox("sno") %></td> <td width ="50%"> <label ="name insured">name insured: </label> &nbsp;&nbsp; <%=@html.textbox("nameinsured") %> </td> </tr> <tr> <td width="50%"> <label for="broker code"> broker code: </label> &nbsp;&nbsp; <%=@html.textbox("brokercode") %></td> <td width ="50%"> <label ="broker name">broker name: </label> &nbsp;&nbsp; <%=@html.textbox("brokername") %> </td> </tr> <tr> <td width="50%"> <label for="product code"> product code: </label> &nbsp;&nbsp; <%=@html.dropdownlist("prodlist",@model.products)%></td> <td> <input type ="button" name ="add product" value ="add product" id="button1" /> </td> </tr> <tr> <td> <label for="product code"> product code selected: </label> &nbsp;&nbsp; <%=@html.textbox ("prodselected")%></td> <td> <input type ="submit" value ="submit submission" /> </td> </tr> </table> </td> </tr> </table> </div> <% } %> </div>

controller is:

namespace mockbdpworkflowtestapp.controllers { public class workflowtestcontroller : controller { // // get: /workflowtest/ public actionresult opensubmission(string processid, string mailid) { var submissionmodelview = new mockbdpworkflowtestapp.viewmodels.workflowtestviewmodel{processinstance =processid, mail service =mailid} ; submissionmodelview.products = new list<selectlistitem>(); submissionmodelview.products.add(new selectlistitem { text = "gl", value = "0", selected = true }); submissionmodelview.products.add(new selectlistitem { text = "property", value = "1" }); submissionmodelview.products.add(new selectlistitem { text = "package", value = "2" }); submissionmodelview.products.add(new selectlistitem { text = "island marine", value = "3" }); homecoming view("submission", submissionmodelview); } } }

the viewmodel is:

namespace mockbdpworkflowtestapp.viewmodels { public class workflowtestviewmodel { public string processinstance { get; set; } public string mail service { get; set; } public list<selectlistitem> products; } }

to view added jquery function below:

<%@ page language="c#" inherits="system.web.mvc.viewpage<mockbdpworkflowtestapp.viewmodels.workflowtestviewmodel>" %> <script src="/scripts/jquery-1.3.2.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $('#button1').click(function() { $('#prodlist').val($('#prodselected').val()); }); }); </script>

there no problem function prodlist not show value instead alert gives me junk jquery : tried this: $('#prodlist option:selected').text; not have selected value prodlist too, , instead alert gives me junk jquery .

try this:

create property in viewmodel store selected value dropdownlist

model public class workflowtestviewmodel { public string processinstance { get; set; } public string mail service { get; set; } public int product { get; set; } public list<selectlistitem> products; } view <td> <label for="product code">product code: </label> @html.dropdownlistfor(m => m.product, model.products)</td> <td> controller [httppost] public actionresult opensubmission(workflowtestviewmodel model) { //model.product dropdown value //your codegoes here }

here fiddle

c# asp.net-mvc

shell - OSX autotools: `aclocal.m4' not being output by `autom4te' -



shell - OSX autotools: `aclocal.m4' not being output by `autom4te' -

i have been trying build freetype2 library in osx mavericks several weeks now, without success.

the problem using gnu autotools create configure build script.

i have installed automake, autoconf, libtoolize, m4 , perl5 using macports port command.

when executing aclocal, there supposed file created in configure directory contains autotools macros: aclocal.m4. however, file not beingness output, , subsequent glibtoolize , autoconf commands generating spurious configure script.

the result is: no aclocal.m4 file, , usual contents of ./autom4te.cache/traces.* beingness dumped @ top of generated configure file (the traces.* files empty).

e.g.:

m4trace:configure.ac:14: -1- ac_subst([shell]) m4trace:configure.ac:14: -1- ac_subst_trace([shell]) m4trace:configure.ac:14: -1- m4_pattern_allow([^shell$])

any help appreciated.

gnu autotools not back upwards execution on working directory stored on fat32 file system. results in spurious m4trace debug messages beingness output generated configure script.

it unknown why is, may related reliance on sleep command check whether file has changed. fat32 rounds time stamps nearest second, execution , subsequent modification checks may happen on sub-second timescale.

this has been raised development team, now, move working directory osx boot partition before executing gnu autotools.

osx shell macports autotools m4

objective c - NSImageView size vs NSImage size -



objective c - NSImageView size vs NSImage size -

does size of image used nsimageview need same dimensions image view?

as example, when have icon image dimensions 64px 64px create sure nsimageview displays image 64px 64px. however, if have nsimageview 48px 48px create sure have image 48px 48px image view. both of these images same icon, 1 larger other. instead of having 2 separate images in app (which can increment app size if there lot of images), wondering if have 1 image (the 64x64 image) , utilize larger image smaller sized nsimageviews.

no, don't need same size. can alter nsimageview's imagescaling , imagealignment ensure nsimage resizes nicely fill nsimageview.

see apple's documentation farther details.

objective-c cocoa nsimage nsimageview

gnuplot - Octave: Log plot with arbitrary log base automatically -



gnuplot - Octave: Log plot with arbitrary log base automatically -

i want plot info in log scale can't find alternative automatically alter base of operations of log scale.

x = 1:100; y = 2 .^ x; semilogy(x, y);

gives me

i have been able manually alter y ticks.

x = 1:100; y = 2 .^ x; semilogy(x, y); set(gca, 'ytick', 2 .^ (0:20:100)); set(gca, 'yticklabel', {'2^{0}' '2^{20}' '2^{40}' '2^{60}' '2^{80}' '2^{100}'});

gives me

i satisfied plot get, out of curiosity, there alternative automatically alter log base of operations of log scale?

as christoph said there no alternative in octave or matlab. may automate little bit process, , ensure consistency between ticks positions , labels, explained here.

for instance

x = 1:100; y = 2 .^ x; semilogy(x, y); base of operations = 2; tick_exponents = 0:20:100; set(gca, 'ytick', base of operations .^ tick_exponents); format_string = sprintf('%d^{%%d}', base); tick_labels = num2str(tick_exponents(:), format_string) set(gca, 'yticklabel', tick_labels);

which yields

plot gnuplot octave

c++ - Confused about behaviour of shaders in OpenGL - switching declarations creates errors and crashes -



c++ - Confused about behaviour of shaders in OpenGL - switching declarations creates errors and crashes -

i'm creating functions load shaders, create meshes, , like, started simple programme test functionalities adding, 1 one, , found problem bit:

const char* vertexshader = prm.loadshader ( "simple_vs.glsl" ).c_str (); const char* fragmentshader = prm.loadshader ( "simple_fs.glsl" ).c_str (); gluint vs = glcreateshader ( gl_vertex_shader ); glshadersource ( vs, 1, &vertexshader, null ); glcompileshader ( vs ); gluint fs = glcreateshader ( gl_fragment_shader ); glshadersource ( fs, 1, &fragmentshader, null ); glcompileshader ( fs );

if tried compile it, no errors, there black screen. if removed fragment shader, display triangle, meant to, without colors. if switched 2 declarations, in:

const char* fragmentshader = prm.loadshader ( "simple_fs.glsl" ).c_str (); const char* vertexshader = prm.loadshader ( "simple_vs.glsl" ).c_str ();

i error, , programme crash:

error code #3: shader info shader 1: warning: 0:1: '#version' : version number deprecated in ogl 3.0 forwards compatible context driver error: 0:1: '#extension' : 'gl_arb_separate_shader_objects' not supported

however, if set this:

const char* vertexshader = prm.loadshader ( "simple_vs.glsl" ).c_str (); gluint vs = glcreateshader ( gl_vertex_shader ); glshadersource ( vs, 1, &vertexshader, null ); glcompileshader ( vs ); const char* fragmentshader = prm.loadshader ( "simple_fs.glsl" ).c_str (); gluint fs = glcreateshader ( gl_fragment_shader ); glshadersource ( fs, 1, &fragmentshader, null ); glcompileshader ( fs );

it works fine. clueless why case, ran original code no issues in prior versions of program. checked prm.loadshader function, works fine, , returns expected value. none of changes have made programme deal shaders, confused bizzarely particular behaviour. can more experience explain why happening?

presumably prm.loadshader returns std::string value. calling c_str gives internal character storage of std::string, lives long std::string does. end of each of loadshader lines, std::string returned destroyed because temporary object, , pointers you've stored no longer pointing @ valid character arrays.

you can around storing local re-create of returned strings.

std::string vertexshader = prm.loadshader ( "simple_vs.glsl" ); const char* cvertexshader = vertexshader.c_str(); std::string fragmentshader = prm.loadshader ( "simple_fs.glsl" ); const char* cfragmentshader = vertexshader.c_str(); gluint vs = glcreateshader ( gl_vertex_shader ); glshadersource ( vs, 1, &cvertexshader, null ); glcompileshader ( vs ); gluint fs = glcreateshader ( gl_fragment_shader ); glshadersource ( fs, 1, &cfragmentshader, null ); glcompileshader ( fs );

c++ opengl input shader glfw

java - Android NullPointerException while instantiating ViewPager Fragments onCreateView but not when swyping views -



java - Android NullPointerException while instantiating ViewPager Fragments onCreateView but not when swyping views -

i trying fill view pager fragments ability swype between different fragments. @ moment, when fragment calls oncreateview() nullpointerexception thrown while trying set text in textview, weirdly, if grab exception can swype through other fragments display correctly.

note: first , sec items not render in viewpager, if swype lastly fragment 1 time again display correctly.

here fragment class:

public class myfragment extends fragment { public static final string extra_message = "extra_message"; public static logiccontroller controller; public static mainactivity activity; public static final myfragment newinstance(string message, logiccontroller controller, mainactivity activity) { myfragment.activity = activity; myfragment.controller = controller; myfragment f = new myfragment(); bundle bdl = new bundle(1); bdl.putstring(extra_message, message); f.setarguments(bdl); homecoming f; } @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { seek { string message = getarguments().getstring(extra_message); // view v = inflater.inflate(r.layout.myfragment_layout, container, false); view v = activity.getlayoutinflater().inflate(r.layout.myfragment_layout, null); // view mainview = pager; textview messagetextview = (textview)v.findviewbyid(r.id.testertextview); system.out.println(controller.getupdategeonetworkdelay() + messagetextview.gettext().tostring()); messagetextview.settext(message); homecoming v; } grab (exception e) { e.printstacktrace(); homecoming null; } } }

here fragment pager adapter:

public class mainpageadapter extends fragmentpageradapter { private list<fragment> fragments; public mainpageadapter(fragmentmanager fm, list<fragment> fragments) { super(fm); this.fragments = fragments; } @override public fragment getitem(int position) { fragment frag = this.fragments.get(position); system.out.println("fragment: " + frag + " pos: " + position); homecoming frag; } @override public int getcount() { homecoming this.fragments.size(); } }

the exception thrown on line:

messagetextview.settext(message);

i have reason believe problem due not referencing textview beyond level of expertise.

logcat:

06-24 17:30:44.962: w/system.err(25639): java.lang.nullpointerexception 06-24 17:30:44.962: w/system.err(25639): @ com.g.geonet.items.myfragment.oncreateview(myfragment.java:48) 06-24 17:30:44.962: w/system.err(25639): @ android.support.v4.app.fragment.performcreateview(fragment.java:1500) 06-24 17:30:44.962: w/system.err(25639): @ android.support.v4.app.fragmentmanagerimpl.movetostate(fragmentmanager.java:927) 06-24 17:30:44.962: w/system.err(25639): @ android.support.v4.app.fragmentmanagerimpl.movetostate(fragmentmanager.java:1104) 06-24 17:30:44.962: w/system.err(25639): @ android.support.v4.app.backstackrecord.run(backstackrecord.java:682) 06-24 17:30:44.962: w/system.err(25639): @ android.support.v4.app.fragmentmanagerimpl.execpendingactions(fragmentmanager.java:1467) 06-24 17:30:44.962: w/system.err(25639): @ android.support.v4.app.fragmentmanagerimpl.executependingtransactions(fragmentmanager.java:472) 06-24 17:30:44.962: w/system.err(25639): @ android.support.v4.app.fragmentpageradapter.finishupdate(fragmentpageradapter.java:141) 06-24 17:30:44.962: w/system.err(25639): @ android.support.v4.view.viewpager.populate(viewpager.java:1068) 06-24 17:30:44.962: w/system.err(25639): @ android.support.v4.view.viewpager.populate(viewpager.java:914) 06-24 17:30:44.962: w/system.err(25639): @ android.support.v4.view.viewpager.onmeasure(viewpager.java:1436) 06-24 17:30:44.962: w/system.err(25639): @ android.view.view.measure(view.java:16504) 06-24 17:30:44.962: w/system.err(25639): @ android.view.viewgroup.measurechildwithmargins(viewgroup.java:5125) 06-24 17:30:44.962: w/system.err(25639): @ android.widget.linearlayout.measurechildbeforelayout(linearlayout.java:1404) 06-24 17:30:44.962: w/system.err(25639): @ android.widget.linearlayout.measurevertical(linearlayout.java:695) 06-24 17:30:44.962: w/system.err(25639): @ android.widget.linearlayout.onmeasure(linearlayout.java:588) 06-24 17:30:44.962: w/system.err(25639): @ android.view.view.measure(view.java:16504) 06-24 17:30:44.962: w/system.err(25639): @ android.view.viewgroup.measurechildwithmargins(viewgroup.java:5125) 06-24 17:30:44.962: w/system.err(25639): @ android.widget.linearlayout.measurechildbeforelayout(linearlayout.java:1404) 06-24 17:30:44.962: w/system.err(25639): @ android.widget.linearlayout.measurevertical(linearlayout.java:695) 06-24 17:30:44.962: w/system.err(25639): @ android.widget.linearlayout.onmeasure(linearlayout.java:588) 06-24 17:30:44.962: w/system.err(25639): @ android.view.view.measure(view.java:16504) 06-24 17:30:44.962: w/system.err(25639): @ android.view.viewgroup.measurechildwithmargins(viewgroup.java:5125) 06-24 17:30:44.962: w/system.err(25639): @ android.widget.framelayout.onmeasure(framelayout.java:310) 06-24 17:30:44.962: w/system.err(25639): @ android.view.view.measure(view.java:16504) 06-24 17:30:44.962: w/system.err(25639): @ com.sothree.slidinguppanel.slidinguppanellayout.onmeasure(slidinguppanellayout.java:516) 06-24 17:30:44.962: w/system.err(25639): @ android.view.view.measure(view.java:16504) 06-24 17:30:44.962: w/system.err(25639): @ android.widget.relativelayout.measurechildhorizontal(relativelayout.java:719) 06-24 17:30:44.962: w/system.err(25639): @ android.widget.relativelayout.onmeasure(relativelayout.java:455) 06-24 17:30:44.962: w/system.err(25639): @ android.view.view.measure(view.java:16504) 06-24 17:30:44.962: w/system.err(25639): @ android.view.viewgroup.measurechildwithmargins(viewgroup.java:5125) 06-24 17:30:44.962: w/system.err(25639): @ android.widget.framelayout.onmeasure(framelayout.java:310) 06-24 17:30:44.962: w/system.err(25639): @ android.view.view.measure(view.java:16504) 06-24 17:30:44.962: w/system.err(25639): @ android.view.viewgroup.measurechildwithmargins(viewgroup.java:5125) 06-24 17:30:44.962: w/system.err(25639): @ android.widget.linearlayout.measurechildbeforelayout(linearlayout.java:1404) 06-24 17:30:44.962: w/system.err(25639): @ android.widget.linearlayout.measurevertical(linearlayout.java:695) 06-24 17:30:44.962: w/system.err(25639): @ android.widget.linearlayout.onmeasure(linearlayout.java:588) 06-24 17:30:44.972: w/system.err(25639): @ android.view.view.measure(view.java:16504) 06-24 17:30:44.972: w/system.err(25639): @ android.view.viewgroup.measurechildwithmargins(viewgroup.java:5125) 06-24 17:30:44.972: w/system.err(25639): @ android.widget.framelayout.onmeasure(framelayout.java:310) 06-24 17:30:44.972: w/system.err(25639): @ com.android.internal.policy.impl.phonewindow$decorview.onmeasure(phonewindow.java:2291) 06-24 17:30:44.972: w/system.err(25639): @ android.view.view.measure(view.java:16504) 06-24 17:30:44.972: w/system.err(25639): @ android.view.viewrootimpl.performmeasure(viewrootimpl.java:1912) 06-24 17:30:44.972: w/system.err(25639): @ android.view.viewrootimpl.measurehierarchy(viewrootimpl.java:1109) 06-24 17:30:44.972: w/system.err(25639): @ android.view.viewrootimpl.performtraversals(viewrootimpl.java:1291) 06-24 17:30:44.972: w/system.err(25639): @ android.view.viewrootimpl.dotraversal(viewrootimpl.java:996) 06-24 17:30:44.972: w/system.err(25639): @ android.view.viewrootimpl$traversalrunnable.run(viewrootimpl.java:5600) 06-24 17:30:44.972: w/system.err(25639): @ android.view.choreographer$callbackrecord.run(choreographer.java:761) 06-24 17:30:44.972: w/system.err(25639): @ android.view.choreographer.docallbacks(choreographer.java:574) 06-24 17:30:44.972: w/system.err(25639): @ android.view.choreographer.doframe(choreographer.java:544) 06-24 17:30:44.972: w/system.err(25639): @ android.view.choreographer$framedisplayeventreceiver.run(choreographer.java:747) 06-24 17:30:44.972: w/system.err(25639): @ android.os.handler.handlecallback(handler.java:733) 06-24 17:30:44.972: w/system.err(25639): @ android.os.handler.dispatchmessage(handler.java:95) 06-24 17:30:44.972: w/system.err(25639): @ android.os.looper.loop(looper.java:136) 06-24 17:30:44.972: w/system.err(25639): @ android.app.activitythread.main(activitythread.java:5001) 06-24 17:30:44.972: w/system.err(25639): @ java.lang.reflect.method.invokenative(native method) 06-24 17:30:44.972: w/system.err(25639): @ java.lang.reflect.method.invoke(method.java:515) 06-24 17:30:44.972: w/system.err(25639): @ com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:785) 06-24 17:30:44.972: w/system.err(25639): @ com.android.internal.os.zygoteinit.main(zygoteinit.java:601) 06-24 17:30:44.972: w/system.err(25639): @ dalvik.system.nativestart.main(native method)

thanks help.

please check line :

system.out.println(controller.getupdategeonetworkdelay() + messagetextview.gettext().tostring()); messagetextview.settext(message);

my guess message content of arguments in bundle passed newinstance should this:

messagetextview.settext(getarguments().getstringextra(extra_message,"message not passed"));

also final modifier public static final myfragment newinstance in line seems inappropriate remove it.

java android android-fragments nullpointerexception android-viewpager