Posts

Showing posts from June, 2012

python 2.7 - pandas DataFrame metadata and set_index -

after several hours of writing nice metadata handler pandas dataframe, this: >>> import pandas pd >>> = pd.dataframe({'frame':[0,1,2,3,4,5,6,7], 'x':[1,2,2,2,3,4,2,11], 'y':[2,2,3,2,2,3,2,10]}) >>> frame x y 0 0 1 2 1 1 2 2 2 2 2 3 3 3 2 2 4 4 3 2 5 5 4 3 6 6 2 2 7 7 11 10 >>> a.set_index('frame') x y frame 0 1 2 1 2 2 2 2 3 3 2 2 4 3 2 5 4 3 6 2 2 7 11 10 >>> type(a._metadata) list >>> a._metadata.append(dict()) >>> a.set_index('frame') --------------------------------------------------------------------------- typeerror traceback (most recent call last) <ipython-input-11-a271477b5f41> in <module>() ----> 1 a.set_index('frame') /usr/lib/python2.7/dist-packages/pand

java - Spring classNotFound when creating spring bean -

when creating bean name usersevice, got classnotfound exception. i'm using spring web-mvc , spring-security this bean in servlet.xml <bean id="userservice" class="tr.com.xxx.service.userservice"></bean> this class want create it's bean public class userservice implements userdetailsservice { @autowired private accountrepository accountrepository; @postconstruct protected void initialize() { //accountrepository.save(new account("user", "demo", "role_user")); //accountrepository.save(new account("admin", "admin", "role_admin")); system.out.print("inside aouth"); } @override public userdetails loaduserbyusername(string username) throws usernamenotfoundexception { system.out.print("inside loadbyusername"); account account = accountrepository.findbyemail(username); if(account == null) { throw new usernamenotfoundexception(

asp.net - DropDownList in Bootstrap XS do not open -

i have asp application , problem dropdownlist. not open on xs mobile devices: <div class="row"> <div class="col-xs-4 col-sm-2 col-md-1"> <!-- anzahl zeilen dropdownlist --> <asp:dropdownlist id="ddlusergridviewrows" runat="server" autopostback="true" cssclass="form-control font-13" data-style="btn-primary"> <asp:listitem value="5"> 5 </asp:listitem> <asp:listitem value="10"> 10 </asp:listitem> <asp:listitem value="15"> 15 </asp:listitem> <asp:listitem value="20"> 20 </asp:listitem> <asp:listitem value="30"> 30 </asp:listitem> <asp:listitem value="50"> 50 </asp:listitem> </asp:dropdownlist> </div> <div

c# - How to run n Task and keep the order of them -

i have method listen communication channel. each package have put in concurrent queue , call task.run handle input. the handle method create new task concurrentqueue trydequeue , on package ( take first queue input ). how can keep order of task ? how can sure task1 handle package1 handled , finish task before task2 handle package2 , finish task ? there can scenario task1 take package1 , task2 take package2 task2 finish running before task1 ... , must avoid. how ?

jsf - Validation password doesn't work in p:dialog -

i'm using primefaces 4.0 , i'm trying use dialog change password. used password component job n't work in dialog works fine when i'm not using dialog. here code <h:form> <p:dialog widgetvar="changepw" resizable="true" appendto="@(body)" modal="true" closable="false" id="changepw"> <p:panel header="change password"> <p:messages id="messages" showdetail="true" showsummary="false" autoupdate="true" /> <h:panelgrid columns="2" id="matchgrid"> <h:outputlabel for="pwdnew" value="new: *" /> <p:password id="pwdnew" value="#{passwordbean.newpw}" feedback="true" match="pwdconf" required="true"

bitbucket - Remove files from git repository without cloning it -

for reason repository on bitbucket need clone contains large files don't require. is possible clone repository without these files ? or maybe possible delete these files without cloning repo in first place? with git cannot clone partially repository bitbucket, can delete directly file website open bitbucket , go dashboard of repo click on source select branch click on file want delete near of edit button, select arrow, , delete edit commit message [optionnal] can create pull request validate commit enjoy

ssas - Get count of invoices for last three months? -

thank all. mdx query , returns count of invoices generated on march 2015 , works charm! set [myset] [customer].[store group].[store group] * {[measures].[sales #]} member [measures].[setdistcount] distinctcount([myset]) select { [measures].[sales #] } on 0 ,non empty [customer].[store group].[store group] on 1 ( select {[calendar].[month].[march 2015]} on 0 [f1_salesbi] ); output like: sales # store 1 156 store 2 56 store 3 546 ... store 10 69 but wish report this: march february january store 1 156 656 145 store 2 56 89 41 store 3 546 215 215 ... store 10 69 69 96 for desired output, how supposed query? please me! generate looks over-complicating situation maybe little simpler required: select { [calendar].[month].[march 2015], [calendar].[month].[february 2015], [calendar].[mo

Doing an if statement with wordpress <?php the_permalink(); ?> -

i want make condition when template loads, if perma link /xxxx/butiker this... and if /xxxx/services loop this. or if /xxxx/cafeer loop this. if render out <?php the_permalink(); ?> full link, need code check .com/xxx/this part. assist? split url using phps explode() function: $link = get_permalink(); $temp = explode("/",$link); print_r($temp); the get_permalink() function returns url, , print_r prints array. part want check in if condition like; for example: array ( [0] => www.xyz.com [1] => xxx [2] => services ) if($temp[2] == "services"){ //your loop services ,cafeer etc.. }

Apache Marathon app and container relation -

i understand relation between marathon app , container. so, marathon app definition can contain single container definition (1:1)? far understand marathon rest api, link attached, answer yes. https://mesosphere.github.io/marathon/docs/rest-api.html#post-/v2/apps but supposed use app groups in order define such complex applications built more single container? have checked kubernetes, , idea of "pod" in case seems convenient build such applications, composed multiple containers, containers in same pod have single network stack, , application scaling happens on pod level. can say, kubernetes pod corresponds marathon app group? or should not try find similarities, rather should better understand marathon philosophy? thank you! regards, laszlo an app in marathon specifies how spawn tasks of application. while can specify how many tasks want spawn, every single on of these tasks corresponds 1 command or container. to you, need understand more use case.

html - unable to position div at bottom of another div -

am trying position div in bottom of div unable that <div class="div"> <img src="dual.png"/> <h1>boot cd or usb drive on pc</h1> <div>footers</div> </div> css .div{ float:left; height:300px; width:22%; margin-top:15px; margin-left:15px; background-color: #e4f2ff } .div img{ width:100%; height:180px; } .div h1{ font-size:20px } .div div{ background:red; float: bottom; position: absolute; bottom: 0; } here jsfiddle trying make design http://i.stack.imgur.com/cdgky.png can me how position div @ bottom of parent div.. in advance display:table : http://jsfiddle.net/j1raqvc8/4/ .div { float:left; height:300px; width:22%; margin-top:15px; margin-left:15px; background-color: #e4f2ff; dis

sql server - MS Access - Pass Through query best practice solution -

so have particular situation here crm i'm tasked developing, , i'd see if can insight on more of sanctioned, best-practice approach specific scenario. basically, have form called accounts displays information specific account subform needs display quotes , orders associated account give user snapshot of work done. due complexity of query , number of possible records, scrolling through subform can slow if using sql view or more obviously, local access query. best solution here pass through query can shoot processing straight sql. i've done quite bit of research , best approach i've seen either 1) use vba change definition of pass through query or 2) use insert statement populate local table can used recordsource subform. @ point want confirm either or both of these approaches qualify best practice situation , possibly example of code make happen. right i'm struggling processing belongs. don't want call code subform launches main accounts form since form

python - Grab output from shell command which is run in the background -

i saw useful information in this post how can't expect run process in background if retrieving output using subprocess . problem ... want do! i have script drops commands various hosts via ssh , don't want have wait on each 1 finish before starting next. ideally, have this: for host in hostnames: p[host] = popen(["ssh", mycommand], stdout=pipe, stderr=pipe) pout[host], perr[host] = p[host].communicate() which have (in case mycommand takes long time) of hosts running mycommand @ same time. now, appears entirety of ssh command finishes before starting next. (according previous post linked) due fact capturing output, right? other cat ing output file , reading output later, there decent way make these things happen on various hosts in parallel? you may want use fabric this. fabric python (2.5-2.7) library , command-line tool streamlining use of ssh application deployment or systems administration tasks. example file: from fabric.api i

javascript - jQuery/Ajax - Trying to create a POST method by Ajax and get response to HTML -

guys i'm trying create simple html post method ajax. here code: <?php function callinstagram($url) { $ch = curl_init(); curl_setopt_array($ch, array( curlopt_url => $url, curlopt_returntransfer => true, curlopt_ssl_verifypeer => false, curlopt_ssl_verifyhost => 2 )); $result = curl_exec($ch); curl_close($ch); return $result; } $tag = mage::getstoreconfig('vivastags/vivasgroup/instagra_tag'); $client_id = "1e0f576fbdb44e299924a93cace24507"; $next_url = $_get["nexturl"]; if($next_url == ""){ $url = 'https://api.instagram.com/v1/tags/'.$tag.'/media/recent?client_id='.$client_id.'&count=24'; } else { $url = $next_url; } $inst_stream = callinstagram($url); $results = json_decode($inst_stream, true); $maxid = $results['pagination']['next_max_id']; $nexturl = $results['pagination'

C: Passing array to pointer function -

i'm not sure if question has asked before, couldn't find similar topics. i'm struggeling following piece of code. idea extend r time later on without writing lots of if-else statements. functions ( func1 , func2 ...) either take 0 or 1 arguments. void func1() { puts("func1"); } void func2(char *arg){ puts("func2"); printf("with arg %s\n", arg); } struct fcall { char name[16]; void (*pfunc)(); }; int main() { const struct fcall r[] = { {"f1", func1}, {"f2", func2} }; char param[] = "someval"; size_t nfunc = rsize(r); /* array size */ for(;nfunc-->0;) { r[nfunc].pfunc(param); } return 0; } the code above assumes functions take string argument, not case. prototype pointer function declared without datatype prevent incompatible pointer type warning. passing arguments functions not take parameters results in too few arguments .

bitwise operators - What is | in C# here? -

in following code block there few bitwise or's. i've never used them before trying understand code block meant. document doc = new document("cleanupoptions.docx"); doc.mailmerge.cleanupoptions = mailmergecleanupoptions.removeunusedregions | mailmergecleanupoptions.removeunusedfields | mailmergecleanupoptions.removecontainingfields; doc.mailmerge.executewithregions(dataset); so in block above, if used doc.mailmerge.cleanupoptions, how pick of statements cleanupoptions equal to? or combined? they combined. enum can marked [flagsattribute] allows combination of values: https://msdn.microsoft.com/en-us/library/system.flagsattribute(v=vs.110).aspx

python - Is there an easy way to get probability density of normal distribution with the help of numpy? -

i know, can use own function this: def gauss(x, mu, sigma): return (2*pi)**(-0.5) * sigma**(-1) * math.exp( - 0.5 * ((x - mu) / sigma)**2) probably, knows standard numpy or scipy function exists same? thanks! you can use scipy : from scipy.stats import norm x = np.arange(20) mu = 5 sigma = 3 mypdf = norm.pdf(x=x, loc=mu, scale=sigma)

ios - EZAudio Plot Mirror Not Consistant -

i implemented ezaudioplotgl in 4 different view controllers. @ times top part of showing , though shouldmirror set yes @ times. suggestions ? i have used "ezaudioplot.h" class rather "ezaudioplotgl.h". resolves issue of inconsistent wave form , works same "ezaudioplotgl.h" and implemented clear method in "ezaudioplot.m" class because not have implementation or clear method. -(void)clear { float empty[_changinghistorysize]; // figure out better way for(int = 0; < _changinghistorysize; i++ ) { empty[i] = 0.0f; } for(int = 0; < _scrollhistorylength; i++) { _scrollhistory[i] = 0.0f; } _scrollhistoryindex = 0; [self setsampledata:_scrollhistory length:(!_setmaxlength?kezaudioplotmaxhistorybufferlength:_scrollhistorylength)]; }

python - How can I convert a BitString to a ctypes Byte Array? -

i've started out bitstring , ctypes, , have part of binary file stored in startdata , bitarray class. > print(startdata) 0x0000000109f0000000010605ffff now, have pass data as-is c function takes unsigned char * argument, i'm first trying this: buf = (c_ubyte * len(startdata))() to this: buf_ptr = cast(pointer(buf), pointer(c_ubyte)) this works, how assign byte data startdata array / buffer created? this doesn't work: > buf = (c_ubyte * len(startdata))(*startdata.bytes) typeerror: integer required here's possible solution (note i'm using python 3): import ctypes def bitarray_to_ctypes_byte_buffer(data): """convert bitarray instance ctypes array instance""" ba = bytearray(data.bytes) ba_len = len(ba) buffer = (ctypes.c_uint8 * ba_len).from_buffer(ba) return buffer (note: same apply converting bytes instance ctypes byte array, remove .bytes in data.bytes ). you can pass buf

Android check if string changed over time -

so, question simple. have program check every minute if specific string has changed. hoping textwatcher work on strings aswell unfortunately wasn't case. similar or better ways achieve this? edit: string im talking broadcast receiver. save last received string sharedpreferences see . compare each received string preference know if has changed. if has changed, save new string.

sql - Using dbms_application_info.set_module before running a long query in Oracle -

i trying figure out how set module name in v$session before running long query can track progress. possible? not quite work. how change will? begin dbms_session.set_identifier(client_id=>'abc'); dbms_application_info.set_client_info(client_info=>'abc test'); -- dbms_application_info.set_module(module_name=>'some name', action_name=>'some action'); -- select * tablename ..... -- dbms_application_info.set_module(module_name=>'',action_name=>''); end; it must this: begin dbms_application_info.set_module('my procedure', 'starting'); dbms_application_info.set_action('running'); select * tablename ..... dbms_application_info.set_module(null, null); end; while query executing can select (at session of course) v$session

java - How to solve compile errors in custom JpaRepositoryFactory after upgrade from Spring Data JPA 1.4 to 1.8? -

basically situation when want upgrade 1.8.0.release 1.4.5.release. i've noticed far this: lockmoderepositorypostprocessor has become crudmethodmetadatapostprocessor lockmetadataprovider has become crudmethodmetadata now, have custom jpa repository factories , extend jparepositoryfactory this: class customjparepositoryfactory extends jparepositoryfactory { protected <t, id extends serializable> jparepository<?, ?> gettargetrepository{ simplejparepository<?, ?> repo; // custom code lockmoderepositorypostprocessor lockmodepostprocessor = lockmoderepositorypostprocessor.instance; repo.setlockmetadataprovider(lockmodepostprocessor.getlockmetadataprovider()); } } this possible because lockmoderepositorypostprocessor enum public. now, new crudmethodmetadatapostprocessor package protected , same trick not work. realized can this: super.gettargetrepository(metadata); and in back-end happen: repository.setrepositorymethodm

junit - How to mock a method which takes Class as parameter -

i can mock method printmyvalue(string value); when(myclass.printmyvalue(anystring())then return "some value"; but how can mock printmyvalue(myclass value); you can use "any" method. can't statically import it. code this: package jtsandbox; import static org.hamcrest.corematchers.is; import static org.hamcrest.matcherassert.assertthat; import static org.mockito.mockito.mock; import static org.mockito.mockito.when; import org.junit.test; import org.mockito.mockito; /** * explains mocking question http://stackoverflow.com/questions/29392623/how-to-mock-a-method-which-takes-class-as-parameter/29393040#29393040 * @author jason w. thompson (https://plus.google.com/+jasonwthompson_softwaredeveloper) */ public class teststuff { /** * tests mocking * @throws exception exception not expected thrown */ @test public void testmethod() throws exception { // given final foo mockfoo = mock(foo.class);

javascript - AngularJS controller does not work, why? (simple controller example) -

i saw video of introduction angularjs , use following example the html: <!doctype html> <html ng-app> <head lang="en"> <meta charset="utf-8"> <title></title> </head> <body ng-controller="maincontrl"> <h2>{{message}}</h2> <script src="bower_components/angular/angular.min.js"></script> <script src="js/test.js"></script> </body> </html> the js: var maincontrl = function($scope){ $scope.message = "hello friend"; }; in example i've seen structure works, when test not work. console gives me error: error: [ng:areq] http://errors.angularjs.org/1.3.15/ng/areq?p0=maincontrl&p1=not%20a%20function%2c%20got%20undefined can used in way controller? or bad practice example in plunker: code example i think, it's bad practice you better use: var myapp = angular.module('myapp', []

node.js - Mongoose $ project -

using mongoose 4.0.x , need execute following (working) mongodb query: db.bookings.find( { user: objectid("10"), // replaced real id 'flights.busy.from': {$gte: isodate("2015-04-01t00:00:00z")}, 'flights.busy.to': {$lte: isodate("2015-04-01t23:59:00z")} }, { 'flights.$': 1 // don't know replicate } ).pretty() the mongoose find operator not accept projection operator, mongodb find 1 does. how can replicate above query in mongoose? filtering array once query returned solution avoid. you want @ docs model.find , not query.find . second parameter can used field selection: mymodel.find( { user: objectid("10"), // replaced real id 'flights.busy.from': {$gte: isodate("2015-04-01t00:00:00z")}, 'flights.busy.to': {$lte: isodate("2015-04-01t23:59:00z")} }, 'flights.$' ).exec(function(err, docs) {...});

database - restore from different server on a db2 server -

we have production server , restored file system of server on quality server. after restore, changed directory name because here source instance/database name different target instance/database name. we created configuration file used initializing database on target server. we uncatalogued database on server , started database instance. for initializing database executed : db2inidb e2q snapshot relocate using relocate_e2q_mar31st_2015 but gave me error: relocating database... dbt1020n configuration file contains invalid entry @ line "3". reason code = "7". unable relocate database, cannot continue the content of configuration file : instance=source_instance,target_instance db_name=source_db,target_db nodenum=0 <some other source target information> what wrong in using nodenum=0 here? i tried list db directories gave me 1 entry of report_db. when tried list db directories on default path, got entry: local database directory on <pa

Python: Error = Class 'Foo' has no 'bar' member? -

i receiving error: attributeerror: type object 'shop' has no attribute 'inventory' my class set: class shop(object): def __init__(self, name, inventory, margin, profit): self.name = name self.inventory = inventory self.margin = margin self.profit = profit # initial inventory including 2 of each 6 models available inventory = 12 # markup of 20% on sales margin = .2 # revenue minus cost after sale bike in bikes.values(): profit = bike.cost * margin and want print inventory: print "mike's bikes has {} bikes in stock.".format(shop.inventory) but keep getting same error. can make work with: print "mike's bikes has %d bikes in stock." % (inventory) but trying make switch .format() you never created instance of class, shop.__init__() method never run either. your class doesn't have such attribute; attribute defined shop class __init__ method itself. create instance

Android QCMediaPlayer not present -

i have small problem. logcat gives me error "e/mediaplayer-jni﹕ qcmediaplayer mediaplayer not present" searched , found out looks device doesn't support qcmediaplayer. else can play audio files? also how can ceck if qcmediaplayer supported? thanks mine got solved using static create method of mediaplayer: mediaplayer player= mediaplayer.create(cntx, uri.parse(this.path)); for resource files: mediaplayer player = mediaplayer.create(cntx, sound_resource_id, loop);

Git - Unlink of file .idx and .pack failed (The only process owned handle to this file is git.exe) -

Image
please, @ picture! git stupid? git couldn't unlink file, git.exe holding handle file. (permissions ok - full control) please, there safe solution problem? git version 1.9.5-preview20141217 i had issue , solved command : git gc above command remove temp , unnecessary files (garbage collector): https://stackoverflow.com/a/26229658/532575

recursion - recursive function in c# get a parameter -

i'm trying parameter function... public static int subsumer(string id,int acc,sqlconnection connection) { acc++; sqlcommand cercas = new sqlcommand("select * common_relation id_source ='" + id + "' , type='@' ", connection); sqldatareader leggsyn = null; leggsyn = cercas.executereader(); int f = 0; while (leggsyn.read()) { f= subsumer(leggsyn["id_target"].tostring(),acc,connection); if (acc <= f) { acc = f; } } //siamo arrivati alla fine return acc-1; } each cycle parameter acc increment , debugging see in case reach value 3, in final recursion 0...i can't it...thank all by returning acc - 1 , decrementing f returned recursive call , don't think that's expect. public static int subsumer(string id,int acc,sqlconnection connection) { sqlcommand cercas = new sqlcommand("select * common_relation id_sou

postgresql - Rails and jsonb type "jsonb" does not exist -

psql --version psql (postgresql) 9.4.1 rails -v rails 4.2.0 i added jsonb column through migration class addpreferencestousers < activerecord::migration def change add_column :users, :preferences, :jsonb, null: false, default: '{}' add_index :users, :preferences, using: :gin end end i error : pg::undefinedobject: error: type "jsonb" not exist line 1: select 'jsonb'::regtype::oid any ? after looking around discovered postgresql version not 9.4 running right command postgres=# show server_version; server_version ---------------- 9.1 so had upgrade postgresql 9.4. by way followed this article upgrading found handy. now : postgres=# show server_version; server_version ---------------- 9.4.1 hope in same situation.

java - JMS publish to topic takes really long time and gets killed by the transaction reaper -

so have code publishes jms topic: public void notifycreatelisteners(mycreatedobject payload) { logger.trace("serviceimpl.notifycreatelisteners"); topicconnection conn = null; topicsession session = null; topic topic = null; try { properties props = new properties(); props.setproperty("java.naming.factory.initial", "org.jnp.interfaces.namingcontextfactory"); props.setproperty("java.naming.factory.url.pkgs","org.jboss.naming"); props.setproperty("java.naming.provider.url", "jnp://localhost:49227"); context context = new initialcontext(props); topicconnectionfactory tcf = (topicconnectionfactory) context.lookup("/connectionfactory"); conn = tcf.createtopicconnection(jbossjaasauthenticator.principal, jbossjaasauthenticator.credentials); topic = (topic)context.lookup("topic/create_notify_topic"); sess

VBA IE call a javascript containing 'this' keyword -

i attempting call javascript function on webpage contains 'this' keyword referring <input> textbox on webpage. function looks this: functiondostuff('hdnattribute',this,'key') using js = "functiondostuff('hdnattribute',this,'key')" call ie.document.parentwindow.execscript(js) doesn't throw error not produce results of function since this cannot identified. stepping through website this = [object disphtmlinputelement] instead of element name while function running. have ideas? good morning, adding more issue. there seems 2 problems, 1st setting window.event, functiondostuff begins with: if (window.event && window.event.keycode == 13) , when function called exits out due event being null. there way pass event 13 website? second issue submitting "this" htmlinputobject. does know method fire 'onkeypress' event? @ point of trying sendkeys avoid calling function have not been a

html - dynamic div container with multiple content -

i try make kind of banner css. div contain 2 images , bit text splittet 2 lines. looks on display if load side on other display smaller resolution and/or 4:3 whole container "falling appart" :( have tried different methodes nothing seems work. may of can point me in right direction :) here css , html: css: #head_box_banner { position: absolute; height: 150px; width: auto; right: 13px; left: 13px; top: 4px; background-color: #dbdbdb; border-radius:3px; } .logo1 { margin-top: 19px; margin-left: 139px; } .logo2 { margin-top: -112px; margin-left: 1380px; } .text_banner_1 { margin-top: -125px; margin-left: 426px; font-size: 46px; color: #062916; font-weight:bold; font-family: comic, serif; font-style: oblique; text-shadow: 0 1px 0 #ccc, 0 2px 0 #c9c9c9, 0 3px 0 #bbb, 0 4px 0 #b9b9b9, 0 5px 0 #aaa, 0 6px 1px rgba(0,0,0,.1), 0 0 5px rgba(0,0,0,.1), 0 1px 3px rgba(0,0,0,.3), 0 3p

ios - using Twitter SDK to send tweet failed, but I'dont know why -

i'm using twitter sdk loggin , tweet. authenticate it's ok, when use twtrcomposer simple text, sdk callback return 'twtrcomposerresultdone', simulator/device show 'the tweet "text" cannot sent because connection twitter failed. debugger show 'plugin com.apple.share.twitter.post invalidated' aparently correct. is there bug or forgot thing. my code: twtrcomposer *composer = [[twtrcomposer alloc] init]; [composer settext:@"some text"]; [composer showwithcompletion:^(twtrcomposerresult result) { if (result == twtrcomposerresultcancelled) { nslog(@"tweet composition cancelled"); } else { nslog(@"sending tweet!"); } }]; tweet using sdk 1. crearte app on twitter.developer 2. add twitter frameworks twittercore.framework, twitterkit.framework, fabric.framework, twitterkitresources.bundle 3. write below code in tweet button

junit - Unit Test Service method Consuming Soap Service -

in spring based rest services have service method returns token, method actaully consumes soap service, not able decide how write unit test that. method signature below public string methodname(){ string token=""; try { token = util.getsoapservice(); }catch(exception e){ } return token; } can use junit , mockito test code you need create mock implementation of service, assign util variable , implement expected behaviour. after check trat token value correct.

java - What is the best approach to use multiple services inside a resource controller? -

i have controller call 3 services : public class productcontroller(){ @autowired private accountservice accountservice; @autowired private processservice processservice; @autowired private releaseservice releaseservice; @requestmapping("/process") public product process(@requestparam(value="name", defaultvalue="docs") productprocessed process) { accountservice.notify(); releaseservice.sendrelease(process); return processservice.process(process); } } what best approach encapsulate service calls?? what looking possibly design patterns. approach create coarse-grained facade on fine-grained services (account, process , release). (see coarse-grained vs fine-grained ) the facade have these 3 services injected in them , encapsulate behavior making controller perform currently. way minimize business logic invoking coarse grained service in controller further encapsulating guts of system.

javascript - I have a "onclick" that runs 3 functions but only runs one? -

so have button onclick runs 3 functions , each function display random symbol. when press button, should output 3 random symbols, 1 symbol outputted when click button. <!doctype html> <html> <head> <title>myfirstjavascript</title> </head> <body> <script> function slots1() { var slot1 = math.floor(math.random()*4); if (slot1 == 0) { document.getelementbyid('value').innerhtml = "\u2663"; } if (slot1 == 1) { document.getelementbyid('value').innerhtml = "\u2665"; } if (slot1 == 2) { document.getelementbyid('value').innerhtml = "\u2666"; } if (slot1 == 3) { document.getelementbyid('value').innerhtml = "\u2660"; } } function slots2() { var slot2 = math.floor(math.random()*4); if (slot2 == 0) { document.getelementbyid('value').innerhtml = "\u2663"; } if (

javascript - var checkedValue - Jquery - how to change language? -

i using extract checkbox value: var checkedvalue = $('.messagecheckbox:checked').val(); however, when checkbox on, displays "on", when off, displays nothing. like this: is checked (yes): on checked (no): what should change make appear on/off, , how can change language or @ least edit result's text? try this. var text = checkedvalue ? 'yes' : 'no'; console.log(text); https://jsfiddle.net/twugud15/

android - Foreign Key Constraint Failed 787 causing abort on attempt to insert entry into table -

trying insert accounts table. data collected fine , thing runs smooth until after confirms account added. @ point operation aborted due foreign key constraint failure shown here : logcat 04-01 22:58:58.750 23053-23053/? e/sqlitelog﹕ (787) abort @ 37 in [insert accounts(terms,amount,accountname,datecreated,status,balance,purpose,payperiod) values (?,?,?,?,?,?,?,?)]: foreign key constraint failed 04-01 22:58:58.999 23053-23053/? e/sqlitedatabase﹕ error inserting terms=0 amount=10000 accountname=acc 1 datecreated=04-01-2015 22:58:58 status=1 balance=10000 purpose=test payperiod=1 i've pulled dbfile , opened check if tables accounts referenced we're populating , are. i've ran database schema in sqlfiddle see fails , ran without problems. now i'm lost , don't know should looking for, if can point me in direction of mistake appreciated. database helper oncreate @override public void oncreate(sqlitedatabase db) { db.execsql("create table

Add command to Grails build process -

i using grails-cdn-asset-pipline plugin . i've gone through installation , configuration steps on github , reach usage section says add command build process (usually before war generation , deployment). // if settings defined in config.groovy grails asset-cdn-push // or grails asset-cdn-push --provider=s3 --directory=my-bucket --gzip=true --storage-path=some-prefix --expires=365 --region=eu-west-1 --access-key=$my_s3_access_key --secret-key=$my_s3_secret_key where in project put command? is can within context of project, or need keep separate in build process , run in environment jenkins? in _events.groovy , tried invoke script in eventcreatewarstart , having no luck there. (code taken this question ) eventcreatewarstart = { warname, stagingdir -> def pluginmanager = pluginmanagerholder.pluginmanager def plugin = pluginmanager.getgrailsplugin("cdn-asset-pipline") def plugindir = plugin.descriptor.file.parentfile map<string, st

Android Unable to access java files in library -

Image
after lot of struggle , research writing help. being new in android , java literally spent few days. sure missing silly need insight. i using android studio , have added zxing qr scanner in project. want edit few methods in library customisation. have added library via gradle. library have used https://github.com/dm77/barcodescanner . i have followed basic instructions , added library via gradle. integration successful. want customise ui. got hold of library here when got hold of viewfindview , tried edit method, wan not able edit it. realised class , auto generated. supposed edit java files. respective java file code in methods here viewfinderview.java how use it? is there way hold of java files respect class files. how can edit files can customise them? i think above questions kind of same. do? happy provide more information. greatly appreciate time. in advance. i have added library via gradle. that problem. in order add library project have import

How would this C struct be translated into Cobol -

i'm pretty new cobol , i'm having difficulty figuring out how use structs. c structs below when converted cobol? these structs have: struct datat { int m; }; struct stack { int top; struct datat items[stacksize]; } st; how statement represented in cobol? st.items[st.top].m this stab in dark since i've never written line of cobol before today 1 . however, after little googling 2 , playing around in ideone , think i've @ least captured flavor of code like, if not actual solution: identification division. program-id. ideone. environment division. data division. working-storage section. 01 ws-stack. 05 ws-top pic 9 value 0. 05 ws-items occurs 10 times indexed i. 10 ws-m pic 9 value 0. procedure division. add 1 ws-top. move 9 ws-m(ws-top). add 1 ws-top. move 8 ws-m(ws-top). display "ws-stack :" ws-stack. display "ws-top :" ws-top. display "ws-items[ws-stack.ws-top]

aps - Why is enpoint.sh not creating a cert or a config directory -

why enpoint.sh not creating cert or config directory. when use script, creates , deploys scripts successfully. config folder , cert not created. there steps missing congratulations! endpoint configured successfully endpoint url: ......countermgmt this script not supposed create config directory or certificates. unpacks scripts package , creates .htaccess files redirect incoming requests. the config folder , certificates created when provision fist application instance.

SAS - proc sql for table update in a macro -

i have code tries update table in macro block using macro variables in sub-query. challenge have @ times of macro variables null, making code fail. how can set ignore when macro varible produces null value? %macro update_bucket; %let macro_fudge = %nrstr(%mend); proc sql; %do i=1 %to &rows.; %do j=1 %to &max_comb.; %do k=1 %to &max_lgd_comb.; %do l=1 %to &max_pd_comb.; %let x = _&&k.lgd&i.; %let y = _&&l.pd&i.; %if &x. ^=ltv %then %do; update sbbook_rb_a set riskbucket = (select risk_bucket portfolio_split_d b a.businessgroup = b.portfolio , a.product2 = b._&j.subport , a.&&&x. >= b.min_lgd_driver_%left(&k.) /* @ times "a.&&&x." returns null value */

ember.js - Input helper valueBinding is deprecated - what's the alternative? -

i've got few text-input helper this {{input type="text" valuebinding="name" focus-out="focusoutname"}} i upgraded ember 1.11.0 , deprecation warning: deprecation: you're attempting render view passing valuebinding view helper, syntax deprecated. should use value=somevalue instead. however when using value not bound in controller , value sets text whatever value. how correctly bind it? you should have change: {{input type="text" valuebinding="name" focus-out="focusoutname"}} to: {{input type="text" value=name focus-out="focusoutname"}} or better (don't need type="text", it's automatic): {{input value=model.name focus-out="focusoutname"}} then next can display value, , see change when change input (so can test bindings set already): {{input value=model.name focus-out="focusoutname"}} {{model.name}}

java - NoSuchMethodError: com.google.common.base.Platform.systemNanoTime() In GWT project -

i exception in gwt project i'm using systemnanotime() ... threw unexpected exception: java.lang.nosuchmethoderror: com.google.common.base.platform.systemnanotime()j @ com.google.gwt.user.server.rpc.rpc.encoderesponseforfailure(rpc.java:389) @ com.google.gwt.user.server.rpc.rpc.invokeandencoderesponse(rpc.java:579) ........ i'm using guava-18. jar in java build path. the problem i'm using google-collect-1.0-rc1.jar , guava-18.0.jar in java build path same project had removed google-collect

class - How can I call this function? -

i stuck right now, have tried seams logical me make work having no luck... i got in separate swift file: import foundation import uikit class myviewcontroller: uiviewcontroller { func background() { var imageview : uiimageview imageview = uiimageview(frame:cgrectmake(0, 0, 100, 300)); imageview.image = uiimage(named:"bg.jpg") self.view.addsubview(imageview) } } i want call separate view controller file. reason doing because can call background class in view controllers , don't have same code in each one. the ways have tried calling are: myviewcontroller.background() - error missing parameter #1 in call background() - error use of unresolved identifier 'background' myviewcontroller() - don't error nothing happens. i appreciate if tell me how can call function 'viewdidload' part in view controller. thank you. you're barking wrong tree. if call background method in myviewco

javascript - Onsen UI pull hook throws error when used in tabbar -

i using pull hook component on page contains ons-list element. page 1 of 3 (also list pages) use tabbar component navigate between. use pull hook on 1 page. when switching pages (via tabbar component) error gets thrown: "error: undefined not function (evaluating 'element.off(:scroll",this._bindedonscroll)')_destroyeventlisteners@www/components/loader.js:1440:53691 _destroy@www/components/loader.js:1440:53771" can pull hook component used tabbar? the error happens when pull hook unloaded. it's issue in destructor. if make tab "persistent" won't experience issue since won't unload pull hook: <ons-tab persistent> the error has been fixed in latest beta version of onsen ui (1.3.0-beta). can install "bower install onsenui#1.3.0-beta" or can wait 1.3.0 release due in couple of days.

Sharing scope between nested directives and controllers in Angularjs -

i have created controller , directive in angular application defined following: app.controller('crudctrl', ['$scope', '$http', function($scope, $http) { $scope.isloading = true; $scope.pagechanged = function(){ $http({ method: 'get', url: 'http://localhost:8080/rest/repository'+$scope.repository.path, params: { size: 3, page: $scope.currentpage } }). success(function (data, status){ $scope.rowcollection = data._embedded['rest-original-product']; $scope.totalpages = data.page.totalpages; $scope.currentpage = data.page.number + 1; $scope.totalelements = data.page.totalelements; $scope.pagesize = data.page.size; $scope.isloading = false; $scope.numpages = 5; }). error(function (data, st

c# - Convert jbyte* to array<Byte>^ -

my c# code using system; using system.collections.generic; using system.linq; using system.text; using sourceafis.simple; using system.windows.media.imaging; namespace tempsample { public class templetextractorsample { // inherit fingerprint in order add filename field [serializable] class myfingerprint : fingerprint { public string filename; } // inherit person in order add name field [serializable] class myperson : person { public string name; } static afisengine afis; // take fingerprint image file , create person object image public static string gettemplate(byte[] bytearray, string name) { console.writeline("enrolling {0}...", name); // initialize empty fingerprint object , set properties myfingerprint fp = new myfingerprint(); //bitmapimage image = new bitmapimage(new

javascript - JSONP throwing script error -

i making ajax request rest api not under control. getting cross-origin error because of set datatype "jsonp". but, throwing script error saying "unexpected token :". when @ network tab of chrome tools, can see request being placed , response getting back. how response looks like: {"uniqid":"1427907503","membersid":"1245678","istypeauth":null,"secretkey":"abcdefghijklmnopqrstuvwxyz"} now, thinking because rest api doesn't send jsonp. how can resolve issue? thanks in advance.

plt.bar (matplotlib in python) does not make bars -

i trying make bar plot. have count data have distributed bins of size 1000 (say). on x-axis, have bin coordinate, i.e., -3000, -2000, ..., 0, 1000, 2000, 3000 (in form). now when plt.bar(x-coord, y-coord), vertical lines. how make sure bars? did try playing around width coordinate, had no luck. thank in advance answering question. your barwidth small. because x values large, bar appears line. try this: import numpy np import matplotlib.pyplot plt values = (20, 35, 30, 35, 27, 12, 38) index = np.array((-3000, -2000, -1000, 0, 1000, 2000, 3000)) barwidth = 400 plt.bar(index, values, barwidth) plt.xticks(index + barwidth/2) plt.show()

jquery - Shrink a text if more than 10 characters length -

hi have following <h2> "example example example example". want detect lenght of <h2> , if it's more 10 characters, shrink "example ex...". it? shrink 10 characters long , add "..." end. here's code: html <h2>example example example example example</h2> <h2>example</h2> jquery $(document).ready(function(){ var dtl = $('.h2').text().length; if(dtl>10){ $('.h2').text().length = 10; $('.h2').text($('.h2').text()+"..."); } }); but that's not working... you need use substr in case: and have h2 tag elements , not .h2 classname. $(document).ready(function(){ var dtl = $("h2").text().length; if(dtl>10){ $('h2').text($('h2').text().substr(0,10)+"..."); } }); am doing 1 element, may need use $("h2").each() target elements. more comple

php - Check if object contains an property matching a string -

stdclass object ( [id] => 11 [type] => 5 [color_a] => 57 [color_b] => 3 [date] => 2 ) how check if object has attributes contain string "color" ? i tried array_diff_key , array_filter cannot use array_filter_use_key because runs on php 5.4. no loops if possible :) this should work you: (here cast object array , search preg_grep() in array_keys() . flip array array_flip() ) $result = array_flip(preg_grep("/\bcolor/", array_keys((array)$o))); print_r($result); output: array ( [color_a] => 2 [color_b] => 3 ) and if want use check true or false in_array() don't need flip , can use this: if(preg_grep("/\bcolor/", array_keys((array)$o))) echo "match";

c# - Nested partials and templates; How to implement a conditional view or editor? -

i've been using c# while, , have done share of web-forms, i'm new mvc , don't know how phrase question googles. i'm developing mvc site backed ef , trying hang of things. have view allows user create entity "a". entity has reference entity b, it's address, in turn has reference entity c, address' region. so i've figured out can create editor template can injected create view entity a, , returns model it's entity b reference populated. can same thing on entity b template, injecting editor template entity c , getting correct entity in b's reference property. my problem entity c created entity. user needs ability create one, , it's trivial entity (has name , country_enum), don't want user have visit special page create entity after they've figured out correct c entity isn't yet in list, come page , reenter other fields might have filled. how can create "conditional" view or set of views, allow user either