Posts

Showing posts from February, 2011

How to use OCMock to return different result base on different argument -

i trying mock different method return when passing different argument same method. self.mymock = [ocmockobject mockforclass:[myclass class]]; [[[self.mymock expect] andreturnvalue:5] mystaticmethod:3]; [[[self.mymock expect] andreturnvalue:10] mystaticmethod:6]; but takes first one, when argument 3 return 5, , when argument 6, return nil instead of 10. know whether way test this? the real code: -(nsmutablearray*)convertchildstringtochilddic:(nsstring*)strchildren { nsarray *kididarray = [strchildren componentsseparatedbystring:@","]; //处理小孩信息 /*children = ( { avatarsmall = "<null>"; currentstatus = 0; displayname = stu1; "id_str" = "70938032-3811-e411-946a-005056c00008"; title = child; } )*/ nsmutablearray *rstchildarray = [nsmutablearray arraywithcapacity:1]; (nsstring *enrollment_id in kididarray) { if (enrollment_id.length <= 0) { ...

ios - Cells do not show up in my tableview -

i new swift / xcode. stuck, have created struct sectionname, sectionobject, , section image. believe code correct, when run simulator not populate tableview cells have created. cell type basic, , identifier cell. there no errors besides yellow triangle says "initialization of immutable value 'objectarray' never used; consider replacing assignment '_' or removing it" around object array variable when run code, doesn't call of tableview func 's . i have removed of content in objectarray ,and replaced them "xxxxx" make easier. i must missing , here code : class "classname" : uiviewcontroller, uitableviewdelegate, uitableviewdatasource { struct objects { var sectionname : string! var sectionobjects : [string]! var sectionimage : [uiimage]! } var objectarray = [objects]() @iboutlet weak var "myname"tableview: uitableview! override func viewdidload() { super.viewdidload() let objecta...

c# - How to make sure a loop within a task has run at least once -

let's have class called scheduler contains dictionary of <userid, task> , task continuously loops , updates internal dictionary schedules user <userid, schedule> information database i.e. want keep information updated in real time. i want have method on scheduler class getscheduleforuser checks see if there task user , if not it'll create task wait til finishes , retrieves schedules user (lazy load it). my question is, after first iteration of task i'll have schedule available , can retrieve schedule...no problem first iteration need wait until task finished @ least 1 time before retrieving schedule. i can start task , create while loop until flag set when it's finished first time loop seems me there better way , it'll useful first iteration. afterwards schedule available , won't need functionality. does have clean way accomplish this? the best solution can think of use taskcompletionsource , eser mentioned in comment. here...

angularjs - John Papa's Angular Style Guide Y165 Recommendation... what to inject in app.core module? -

in y165 , john papa recommends injecting cross app modules app.core. angular.module('app.core', [angular modules, 'nganimate', 'ngsanitize', cross-app modules, 3rd party modules]); however, in other examples, manually injects needs in own module... i.e. dataservice.$inject = ['$http']; $http common one, i'm thinking injecting app.core. bad idea? i'm little confused, inject app.core , how determine whether should injected manually or if should injected app.core? (i.e. there unspoken rule put app.core if 2+ modules share it? 3+ modules?)

c# - want to move each array from arrayList into int [ ] -

there 350 elements in arraylist , each of consist of array of 9 integers i-e count of each element 9 . want retrievere each of it. here trying giving me error "unable cast object of type 'system.collections.generic.list`1[system.int32]' type 'system.int32[]'." filename = "e:\\normalized_sheet1.txt"; filestream fs = file.openread(filename); streamreader sr = new streamreader(fs); while (!sr.endofstream) { line = sr.readline().split('\t'); //make array of text each time list<string> arr = new list<string>(); arr.addrange(line); list<int> intlist = arr.convertall(s => int32.parse(s)); myvalues.add(intlist); } sr.close(); fs.close(); (i = 0; < samples; i++) { inputparameter=(int[]) myvalues[i]; // error } myvalues.add(intlist.toarray()); because mentioned have list of arrays . if it's list<int[]> can't add lists - can add arrays. toarray() retu...

configure route to page that is in subfolder rails -

i have design.html.erb file in folder views/services/ how configure route page in routes.rb ? (i have controller static pages called static_pages_controller don't need backend actions) need this: '/services/design' => 'static_pages#what_to_write_here' get '/services/design' => 'static_pages#design' this render design.html.erb inside views/static_pages/ directory. in order specify view in sub-folder have specify in action: def design render 'services/design' end this render design.html.erb inside views/services/ directory.

Change date and time format via command prompt -

i wondering, in windows 7 , above, possible change way dates , times displayed via command prompt? yes, i'm in u.s. doing things european way: (in clock/language/region) short date: set "d/m/yyyy" long date: set "dddd, d mmmm yyyy" short time: set "hh:mm" long time: set "hh:mm:ss" yes, it's possible e.g. using reg add command . check hkey_current_user\control panel\international registry key: reg query "hkcu\control panel\international" for instance, query short time format: reg query "hkcu\control panel\international" /v sshorttime and set desired value: reg add "hkcu\control panel\international" /v sshorttime /t reg_sz /d hh:mm /f if value name or data contains spaces, use double quotes (surrounding double quotes not written registry): reg add "hkcu\control panel\international" /v sshorttime /t reg_sz /d "hh:mm" /f

python - Writing a function to add points after points = 0 -

this question has answer here: i have function supposed count points doesn't add them 7 answers i writing function find out how many points earn. supposed add points points after when print points outside of function, says points = 0. here function... points = 0 def correct(points): if question >= 0 , question <= 3: points = points + 100 print 'that 100 point question.' elif question >= 4 , question <= 7: points = points + 200 print 'that 200 point question.' elif question >= 8 , question <= 11: points = points + 300 print 'that 300 point question.' else: points = points + 400 print 'that 400 point question.' return points here example of function in code. if ranswer == ...

c# - How to resize images to display from database -

i doing small project have display images database listview. passing image id,width,and height querystring parameter. <asp:image id="image1" runat="server" imageurl='<%#"~/handler/imagehandler.ashx?imgheight=150&imgwidth=200&imgid="+eval("image_id")%>' height="150px" width="200px"/> public void processrequest (httpcontext context) { string imgwidth = context.request.querystring["imgwidth"]; string imgheight = context.request.querystring["imgheight"]; string imageid = context.request.querystring["imgid"]; if (imgwidth != string.empty && imgheight != string.empty && (imgwidth != null && imgheight != null)) { if (!system.web.ui.webcontrols.unit.parse(imgwidth).isempty && !system.web.ui.webcontrols.unit.parse(imgheight).isempty) { //create unit object height , width. convert paramete...

c# - Create a time Offset from string with NodaTime -

i have string represents offset of particular customer. example utc+1:00 . offset relative utc, string start utc followed + or - , offset in format hh:mm . the question is, how can take string , convert offset? not want date , time object offset applied, want object symbolizes offset, can later apply date, different altogether. at title says, i'm looking use nodatime this. it sounds want: var pattern = offsetpattern.createwithinvariantculture("'utc'+h:mm"); var offset = pattern.parse(text).value;

jquery - Enable javascript on a window being resized -

i want javascript/jquery execute piece of code once window being resized. there way this? believe read $(window).change (i have written wrong i'm learning) though misses indicator tells when window size changes. thanks in advance!! your can use .resize() function. bind event handler "resize" javascript event, or trigger event on element. use this: $(document).ready(function(){ $( window ).resize(function() { console.log("fired!"); }); })

backend - Where to put node.js code in cPanel -

i entirely new backend development might ridiculously easy , straightforward question, i'm not sure. trying learn node.js backend development, , of tutorials have seen far show how node can used run javascript terminal , create server on local host. while neat thing do, stuck there , having difficulty understanding put node.js code on cpanel , how use along rest of html/css/js code; examples have seen isolated , don't have interaction these other files. again, don't have backend experience, not helpful explain concept relative server-side language python, ruby, or php, have no idea put of code of stuff either or how fits bigger picture. if answer maybe touch on how integrate python or php , general patterns backend development---the easy stuff assumes no 1 explains---it appreciated. it doesn't matter put it. want keep in folder of username using it. created folder called app/ in users folder , put crap in there. set listen on port approved host. you ...

c# - Select specific text boxes on WebBrowser and write in them -

how select specific text box on web browser (the default c# webbrowser) , write string in it? have been thinking of webrequests may illegal due amount of packets send host server. if wanting fill in field, need use dom. here examples assume browser named browser , has navigated google.com. wpf mshtml.ihtmldocument2 htmldoc = browser.document mshtml.ihtmldocument2; ((mshtml.htmlinputelement)htmldoc.all.item("lst-ib")).value = "wpf web browser access dom"; winforms htmldocument htmldoc = browser.document; htmldoc.all["lst-ib"].innertext = "c# web browser access dom";

javascript - How can I make my slideshow fade? -

im trying edit current javascript file make image slideshow fade each other rather jumping picture picture. here current code: var myimage=document.getelementbyid("myphoto"); var imagearray=["workone.jpg", "worktwo.jpg", "workthree.jpg"] var imageindex=0; function changeimage () { myphoto.setattribute("src", imagearray [ imageindex]); imageindex++; if (imageindex>=imagearray.length) { imageindex=0; } } var intervalhandle = setinterval(changeimage,4000); myphoto.onclick=function() { clearinterval(intervalhandle); } you can use jquery here. check fadein , fadeout functions. can achieve raw javascript changing element's opacity gradually.

wordpress - jQuery Chosen for woocommerce -

i using woocommerce plugin wordpress. need use jquery chosen product variations drop down. woocommerce have chosen plugin in folder \plugins\woocommerce\assets\js\chosen how can enable it.? thanks! add_action('admin_print_styles', array($this, 'admin_scripts')); public function admin_scripts() { global $wp_scripts; wp_enqueue_script('wc-enhanced-select'); // if using recent versions //wp_enqueue_script('chosen'); // if using old versions wp_enqueue_style('woocommerce_admin_styles', wc()->plugin_url() . '/assets/css/admin.css'); } and in select box can apply class="wc-enhanced-select" or class="chosen_select" accordingly

ruby - Rails find_by_name on another table -

i have genders , based on gender name create category , subcategories. m = gender.create(:gender => 'masculine') c = category.find_by_name("t-shirt", gender: m ) c.subcategories.create(:name => "necklace" ) and on. you can try this. m = gender.create(:gender => 'masculine') c = category.where(name: "t-shirt", gender: m.gender ).first c.subcategories.create(name: "necklace" ) please note above code raise exception if no category found given condition, avoid can use following. m = gender.create(:gender => 'masculine') c = category.where(name: "t-shirt", gender: m.gender).try(:first) unless c.blank? c.subcategories.create(name: "necklace" ) end

sort a List<int> in c# ignoring the sign -

i have list below var initial = new list { 2, 5, 6,-1, -3, -4 }; expected output {-1,2,-3,-4,5,6} =>(sort given list ignoring -ve sign not removing them in result.) my attempt solve var initial = new list<string> { 2, 5, 6,-1, -3, -4 }; var dummylist = initial.findall(x => x < 0); initial .removeall(x => dummylist.contains(x)); foreach (var e in dummylist) { initial .add(e * -1); } initial.sort(); foreach (var e in dummylist) { var index = initial.findindex(x=>x==(e*-1)); initial.removeat(index); initial.insert(index, e); } can give better solution this. https://dotnetfiddle.net/gcd1i1 thanks! you can pass comparison sort method, compare using absolute value: list.sort((a, b) => math.abs(a).compareto(math.abs(b))); or using linq: list = list.or...

postgresql - How to turn String to Numeric With Characters in it (Postgres) -

i have field string want turn numerics. problem field can contain characters , it's hard me simple regular expression replace. here example, field1 1 1.5 2adfk3 2. section 2 0'#%0ls23 3.987 what want if field can natively casted numeric, return numeric, otherwise return null. example, want field, be field2 1 1.5 null null null 3.987 where field2 numeric. best way this? in excel suppose closest iferror you can case expression , regex: select column1, case when column1 ~ '^[0-9\.]+$' column1::numeric else null end column2 the_table the regex checks if contents of column consists of numbers , dot. if case, value can cast numeric value, otherwise returns null

jquery - How to use text from the url query string to populate the image name in the image src path? -

i new js , teaching myself amazing people on site. code on site have worked out how populate text on web page parameters pulled query string in url, cannot work out how use same parameters populate file name in image path. example url: http://www.mywebpage.com/editors.aspx?config=pagename&firstname=joe&lastname=bloggs what have far works populate text on page: <script type="text/javascript"> $(document).ready(function(){ function geturlvars() { var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexof('?') + 1).split('&'); for(var = 0; < hashes.length; i++) { hash = hashes[i].split('='); vars.push(hash[0]); vars[hash[0]] = hash[1]; } return vars; ...

ios - Retrieving Data using Firebase Swift -

i'm using firebase swift ios application. found retrieving data tutorial on firebase's guide bit confusing , not sure why when try access existing values in database results in nil values. this have far: usersref.queryorderedbychild("fbid").queryequaltovalue(userid).observesingleeventoftype(.value, withblock:{ snapshot in print("snapshot: ",snapshot.value) here result of printing snapshot. snapshot: { 1 = { fbid = 1; firstname = michelle; friendlist = { 9 = "kevin c"; }; lastname = c; profilepicurl = "https:; uid = "facebook:1"; }; } however, line below results in: fatal error: unexpectedly found nil while unwrapping optional value firstname = snapshot.value.objectforkey("firstname") as! string i retrieve values user (firstname, profilepicurl, friendlist, etc) , store them in variables. seems sim...

angularjs - Microsoft Graph api 403 access denied when reading other users -

i'm creating application in angular , nodejs , need able read user's list of events. right attempting use " https://graph.microsoft.com/v1.0/users/otherusername@companyurl.com/events " gives me 403 "access denied. check credentials , try again.". however, if use " https://graph.microsoft.com/v1.0/users/myusername@companyurl.com/events " works(as expect). question is, why when use outlook can use scheduling assistant see events "otherusername@companyurl.com" without being admin in application cannot see events due credentials? the library i'm using connect microsoft graph api https://github.com/azuread/azure-activedirectory-library-for-js the delegated permissions have set in azure are view users' email address sign users in read user contacts have full access user calendars read user calendars send mail user read directory data read users' basic profiles sign in , read user profile application permissions...

python - Pandas read_fwf: specify dtype -

i reading in huge fixed width text file in chunks , export data csv. because pandas.read_fwf not allow specify dtypes, wondering other way there exists force columns strings. reason pandas infers columns float though not , not want .0 within column. using data[column] = data[column].astype(str) not not rid of decimals. converting columns of float64 dtype int doesn't work either since nas cannot converted. ideas? here's snippet of code: dat = pd.read_fwf(file_to_read,colspecs=cols,header=none,chunksize=100000,names=header) #first chunk data.info() int64index: 100000 entries, 0 99999 columns: 562 entries, dtypes: float64(405), int64(4), object(153) memory usage: 429.5+ mb column in data.columns: if data[column].dtype == 'float64': data[column] = data[column].astype(int) else: pass i str().replace('.0','') , want find easier way iterating through column takes lot of time. the converter parameter can used pr...

Deploying ASP.NET Core to linux -- avoiding 50 MB deploy? -

i able deploy coreclr asp.net apps linux , have them run, hurray. using dnu publish --no-source -o <dest-dir> which gives me dest-dir full of many coreclr packages, 1 of package published app specifically. this folder pretty big, around 50 mb simple web application basic (no auth) described @ https://azure.microsoft.com/en-us/documentation/articles/web-sites-create-web-app-using-vscode/ . is there sensible way deploy linux without pushing around? can rid of bunch of coreclr packages somehow? there way of deploying source-only , doing work on server (i may have seen this, lost if did)? you publishing without runtime ( --runtime option on dnu publish ) reduces bundle size significantly. you need somehow packages on server. if deploy sources, you'll have restore download same amount of packages. also, running sources makes application start slower (depending on number of dependencies). however, if publish entire bundle once , app's dependencies don...

lua - Why have I errors when installing from Luarocks? -

i developer of small library: https://github.com/martin-damien/babel , have problem luarocks releases. from source when install source luarocks have no problem: $ luarocks make --local rockspecs/babel-1.2-2.rockspec from internet but when deployed (using: tag master , add new rockspec release , publish luarocks), can't install using $ luarocks install --local babel because encounter following error: installing https://luarocks.org/babel-1.2-2.src.rock ... using https://luarocks.org/babel-1.2-2.src.rock ... switching 'build' > mode stat: malsukcesis eltrovi statinformon pri «locales/zh-hk.lua»: no such > file or directory error: build error: failed installing locales/zh-hk.lua in /home/damien/.luarocks/lib/luarocks/rocks/babel/1.2-2/lua/locales/zh-hk.lua: locales/zh-hk.lua: no such file or directory as can see in https://github.com/martin-damien/babel/issues/14 error occure on different files (but until now, locale files, not babel...

c# - Xamarin: Deserializing XML - "There is an error in XML document" -

in order use xml files in xamarin-forms project, i'm trying recreate steps given in example code , error message: an exception of type 'system.invalidoperationexception' occurred in system.xml.xmlserializer.dll not handled in user code additional information: there error in xml document (2, 2). the example code works fine way. this xml file use (as embedded resource): <?xml version="1.0" encoding="utf-8" ?> <items> <item> <name>one</name> <state>alpha</state> </item> <item> <name>two</name> <state>two</state> </item> </items> this c# code use: using system; using xamarin.forms; using system.reflection; using system.io; using system.xml.serialization; using system.collections.generic; namespace xmltestproject { public class xmlcontentpage : contentpage { public xmlcontentpage() { ...

python - csv - take away data of one column from another -

i want take value of column 4 column 3 (their both integers), have. with open('classes.csv', 'rt')as f: reader=csv.reader(f) people=[] column in reader: people.append(column[0:8]) difference = [x[3] x in people] - [x[4] x in people] print(difference) i error typeerror: unsupported operand type(s) -: 'list' , 'list' when this. know why error can't think of way around it. any great! like @peter wood said in comment, need subtract inside of 1 list comprehension, not doing 2 list comprehension results in list - list . need convert numbers. difference = [int(x[3]) - int(x[4]) x in people] if want stuff this, better off using numpy or pandas . using numpy , it's genfromtxt function: import numpy np people = np.genfromtxt('classes.txt', delimiter=',', dtype=none) difference = people[:, 3] - people[:, 4] here people 2 dimensional numpy array, first index going on rows, second on column...

Auth State Managment for Firebase in Android -

i see firebase documentation states no user-auth information stored during login process. however, have few questions how handle internally. does firebase android sdk keep authentication state in memory? if does, design or pattern used purpose (singleton, weakreferences, etc) ? or execute call server each time ref.getauth() method called? thanks! i assume you're referring section of documentation describes how store such user data in database yourself. states: when authenticate user, no profile or user state stored in firebase database. firebase authentication separate service firebase database, though integrate nicely. when sign in user firebase authentication firebase client stores resulting token in app's sharedpreferences . means survives application restarts (although may expire while app not active). the authentication state kept in memory. firebase objects share same session behind scenes, there's single object between of them....

c# - Binding Command to ItemsControl Item -

i working on win10 uwp app using mvvmlight (i've never used mvvmlight, , never done commands "properly"). have itemscontrol bound observablecollection. participant has 2 properties - name , laps. have controls in itemscontrol.itemtemplate display button (subtract), name property of item, laps property of item, , button (add). here xaml: <itemscontrol itemssource="{binding participants, mode= twoway}"> <itemscontrol.itemtemplate> <datatemplate> <grid minwidth="300" margin="0, 12"> <grid.columndefinitions> <columndefinition width="2*"></columndefinition> <columndefinition ...

javascript - Passing base64 encoded image through form -

i using image editing tool users upload images , adjust: http://foliotek.github.io/croppie/ i able shorten base64 string sending through couple functions. trying insert hidden field , submit form. $('#submit-update-business').on('click', function(e){ e.preventdefault(); // console.log(vanilla.get()); vanilla.result('canvas', 'viewport', 'png', 0).then(function(src){ var processed = base64.encode(json.stringify(src)); $('#new_image').val(processed); $('#update-business').submit(); }); }); i know string long, can't figure out other way this. i've seen answers suggest submitting form through ajax, seems have same pitfalls. manages work ok on desktop browsers. it's mobile ones have problem. can limit dimensions of image less 3000x3000, unfortunately phones seem taking higher quality photos. the tool i'm using, croppie, has way data points , zoom, not orientation. if t...

c# - CefSharp WPF and MVVM? -

i using cefsharp wpf. want use in mvvm architecture. unfortunately there problem. in view have: <contentpresenter content="{binding browser}" horizontalalignment="center" verticalalignment="center"/> in viewmodel put new object browser : var settings = new cefsharp.settings { packloadingdisabled = true, } if (cefsharp.cef.initialize(settings)) { int counter = 0; this.browser = new webview(); } unfortunately cannot load url @ point after that. says browser not initialized , isbrowserinitialized property (in browser ) false . that weird because in test app, not mvvm, used same code instantiate webview works. difference programmatically added browser grid not mvvm. anyone got cefsharp in wpf mvvm app? ideas? thanks edit: have noticed in test non-mvvm app, isbrowserinitialized property set false until window constructor ends job. cefsharp version 1 not suited mvvm @ moment, u...

c# - conditional references in visual studio - how to define the customized variable -

i have project should reference other projects done way: <reference include="referenceddll" condition=" '$(configuration)' == 'debug' "> <hintpath>..\resources\external dlls\referenceddll.dll</hintpath> </reference> this works fine , copies dll in case in debug. want not depend on debug/ release other variable definition something like: <reference include="referenceddll" condition=" '$(releasetype)' == 'internal_release' "> <hintpath>..\resources\external dlls\referenceddll.dll</hintpath> </reference> i did not find how define releasetype variable? + there way use same variable both #if in code , conditional referencing? i saw option use use condition=" $(defineconstants.contains('internal_release'))" but did not work i'd expect i'm not sure if there way in visual studio. if running build msbuild directly...

c# - How can I get the base object of an object (not just the BaseType) -

i wondering how can actual base object of object? have base class named messagebase , , lot of classes inherit base class, inherited other classes in different depths. example: some classes inherit this: messagebase --> valuemessage --> doublevaluemessage others that: messagebase --> valuemessage --> [some class] --> [some other class] --> testmessage what need this: have object of 1 of these inherited classes, let's instance of doublevaluemessage. don't know in advance type of object, know somehwere down nested inheritance, there base object (messagebase) properties need set. now tried reference base object. tried valuemessage doublevaluemessage based upon, don't understand how . i tried that: public bool setpropertyvalue(object obj, string prop, object value) { var item = obj.gettype().getproperty(prop); //messagebox.show(obj.tostring()); if (item != null) { item.setvalue(obj, value); return true; }...

android - My Activity is crashing my app -

in app activity crashing when trying read text edittext , displaying onto activity. here code getting text edittext: intent intent = new intent(this, currenthomework.class); edittext edittext = (edittext) findviewbyid(r.id.homedue); string message = edittext.gettext().tostring(); intent.putextra(extra_message, message); here code getting text string , putting on textview: @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); intent intent = getintent(); string message = intent.getstringextra(addnewhomework.extra_message); textview textview = (textview) findviewbyid(r.id.textview99); textview.settext(message); to clarify shadab's answer, ensure prefix layout id r.layout , reads: @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_name_here); intent intent = getintent(); ...

c# - Word interop cross referencing an endnote -

i trying refer existing end note in word table cell in document (using netoffice): row.cells[2].range.insertcrossreference(wdreferencetype.wdreftypeendnote, wdreferencekind.wdendnotenumberformatted, 1); however, appears put reference @ beginning of row, rather @ end of text @ cell[2]. in general, haven't found on web on how programmatically add cross-reference footnotes , end notes. how can reference display properly? the problem target range specified in code snippet entire cell. need "collapse" range within cell. (think of range selection. if click @ edge of cell, entire cell selected, including structural elements. if press left-arrow, selection collapsed blinking i-beam.) to go start of cell: word.range rngcell = row.cells[2].range; rngcell.collapse(word.wdcollapsedirection.wdcollapsestart); rngcell.insertcrossreference(wdreferencetype.wdreftypeendnote, wdreferencekind.wdendnotenumberformatted, 1); if cell has content , want @ end of content,...

java - Correct way to persist Quartz triggers in database -

i'm quite new quartz , need schedule jobs in spring web application. i know spring + quartz integration (i'm using spring v 3.1.1) i'm wondering if right way follow. in particular i need persist scheduled tasks in db can re-initialize them when application restarted. are there utilities provided spring scheduling wrapper this? can suggest me "well known" approach follow? here 1 way handle scenario. first in spring configuration specify schedulerfactorybean can inject scheduler other beans. <bean name="schedulerfactory" class="org.springframework.scheduling.quartz.schedulerfactorybean"> <property name="applicationcontextschedulercontextkey"> <value>applicationcontext</value> </property> </bean> then when create job in application store details of job in database. service called 1 of controllers , schedules job: @component public class followjobservic...

Play Framework for Java 2.1 and MongoDB -

i'm build project in play framework java 2.1 , use mongodb store data. i've installed both play 2.1 , mongodb 2.4.4. is possible build play! project mongodb java driver? i've tried download mongo-java-driver.jar placed in lib / folder in root of play project according documentation . i've created model in i've added code below can't work. know tutorials or doing wrong? compilation errors unreported exception java.net.unknownhostexception; must caught or declared thrown import com.mongodb.mongoexception; import com.mongodb.writeconcern; import com.mongodb.db; import com.mongodb.dbcollection; import com.mongodb.basicdbobject; import com.mongodb.dbobject; import com.mongodb.dbcursor; import com.mongodb.serveraddress; mongoclient mongoclient = new mongoclient(); if take @ documentation , mongoclient() constructor may throw unknownhostexception , checked exception. may either catch exception in code or add throws unknownhostexception declaratio...

Youtube - how to get a list of videos in youtube channel and display them as a list? -

i browsing youtube api here: https://developers.google.com/youtube/v3/guides/working_with_channel_ids and don't quite see way of channel's videos. not common thing people do? , need channel id not sure how get. not channel. would please able point me in right direction here. seems if can embed video website, should able full channel list of videos. or missing something? you can retrieve channel id: retrieve youtube channel info "vanity" channel and later, channel id can retrieve channel's playlists: https://developers.google.com/youtube/v3/docs/playlists and can use each playlist id retrieve playlistitems, , in way retrieve videoids in channel: https://developers.google.com/youtube/v3/docs/playlistitems

facebook - Bot read from my api endpoint -

i creating bot on facebook messenger, following tutorial here is there way bot retrieve results own api endpoint? essentially, have set api endpoint results in json returned. results populate template in facebook messenger, how current cnn messenger bot shows news based on queries how do this? your bot can want him. have setup him first on server... what return, or behaviour you. you can use php api: https://github.com/fritak/messenger-platform just follow example , return generic template.

querying a view in oracle using java code with a where condition on a date field -

i need connect view in oracle view contains information matrix population in other tables. structure of view (v_matrix) is: period_start_time not null date, matrix_table varchar2(20), matrix_name varchar2(20), completion_time date i using java code using jdbc connect view. the query have is: string query = "select * v_matrix period_start_time \'2016-04-18 17:%\' , matrix_table = \'" + tablename + "\' , matrix_name in (" + inclausestr.tostring() + ")"; the problem query fetches nothing while can see around 200 records in view period_start_time in order of 17th hour on 18th april 2016. same query works fine in sql developer i tried googling bud not find tutorial on how filter records on date field using java code. i tried changing query to string query = "select * v_kpi_availability to_char(period_start_time,\'yyyy-mm-dd hh24:mi:ss\') \'2016-04-18 17:%\' , kpi_table = \'" + tablename + "\...

php - comparing date text field to todays date -

hope can help, have following code check both, if date field valid, , has happened in past. valid format part works keeps saying date in future (and therefore unacceptable) regardless of whether or isn't. missing here? if($_post['dateofcall']!=null) { $dt = $_post['dateofcall']; $array = explode("/",$dt); $day = $array[1]; $month = $array[0]; $year = $array[2]; if(!checkdate( $day,$month, $year)) { echo '<script type="text/javascript">' , 'alert ( "not valid date of call" );' , '</script>'; } else { $today = date("d/m/y"); if(strtotime($dt)>$today) echo '<script type="text/javascript">' , 'alert ( "date of call in future..." );' , '</script>'; } } } thankyou in advance! you mix dates in different format...

javascript - How to access an array in j-query returned by php script -

i want access array in j-query returned php script via ajax call ajax call getting result php script: $.ajax({ url: "http://localhost/wcpm/index.php/demand/check_demand_status", type: 'get', cache: true, data: { meter_group_name: $(this).val() }, success: function(data) { if(data["exists"]==1){ alert("request in pending group"); $('#meter_group_name').attr('selectedindex',0); } $("select#meter_number").html(data["option"]); } }); response of ajax call php script: array ( [exists] => 1 [option] => <option value=''>please select meter</option> <option value='5'>222000</option> <option value='6'>10101...

How to read in a file of numbers into an array list in Java -

i want able read in map file looks like: 0, 0, 0, 0, 0 0, 0, 1, 0, 0 0, 1, 1, 1, 1 0, 1, 1, 1, 0 0, 0, 1, 1, 0 and create array list looks like: {[0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 1, 1, 1, 1], [0, 1, 1, 1, 0], [0, 0, 1, 1, 0]} i have tried using br.readline() appears getting stuck not throwing error in middle. public static int[][] loadfile() throws ioexception{ filereader in = new filereader(main.currentfilepath + main.currentfile); bufferedreader br = new bufferedreader(in); string line; int [] intarray = {}; int [][] filearray = {}; int j = 0; while ((line = br.readline()) != null) { list<string> stringlist = new arraylist<string>(arrays.aslist(line.split(","))); string[] stringarray = stringlist.toarray(new string[0]); list<integer> intlist = new arraylist<integer>(); system.out.println("rrrrr"); ...

vb.net - How to retrieve data from SQL database in vb. net? -

i have problem in retrieving data database.. have 3 textboxes , textbox1 applicant_num, textbox2 applicant_name , textbox3 lot_num , want view data in listview.. how can data database using vb.net? hope can me.. thanks. code here: dim sql string = "select * pambujan app_num = '" & textbox1. text & "', app_name = '" & textbox2. text & "', lot_num = '" & textbox3. text &"'" the syntax accessing text property of text boxes incorrect. also, dynamic clause being generated should use 'and' instead of commas. this: dim sql string = "select * pambujan app_num = '" & textbox1.text & "' , app_name = '" & textbox2.text & "' , lot_num = '" & textbox3.text &"';"

dictionary - R construct document term matrix how to match dictionaries whose values consist of white-space separated phrases -

when text mining using r, after reprocessing text data, need create document-term matrix further exploring. in similar chinese, english have phases, such "semantic distance", "machine learning", if segment them word, have totally different meanings, want know how match pre-defined dictionaries values consist of white-space separated terms, such contains "semantic distance", "machine learning". if document "we use machine learning method calculate words semantic distance", when applying document on dictionary["semantic distance", "machine learning"], return 1x2 matrix:[semantic distance, 1;machine learning,1] it's possible quanteda, although requires construction of dictionary each phrase, , pre-processing text convert phrases tokens. become "token", phrases need joined other whitespace -- here, " _ " character. require(quanteda) packageversion("quanteda") ## [1] '...

Trying to make a photo filter's effects cumulative on the photo-java swing -

Image
basically have made interface displays picture , has multiple jsliders. each 1 has different function such blur, brighten, , saturate. have implemented sliders in such way override statechanged method when adding new slider. works fine when sliders individually, changes original picture once use different slider. want make picture accumulates filters on photo. suggestions? here example of 1 of sliders. brightslider.addchangelistener(new changelistener() { @override public void statechanged(changeevent e) { jslider source = (jslider) e.getsource(); double scalevalue = source.getvalue() / 100.0; picture newpic = new pictureimpl(picture.getwidth(), picture.getheight()); //picture newpic = picture; pixel zeropixel = new colorpixel(0, 0, 0); pixel p; (int = 0; < picture.getwidth(); i++) { (int j = 0; j < picture.getheight(); j++) { newp...

c++ - Custom file system implementation in Qt -

i researching way of implementing simple file system ui. requirement have in-memory tree (custom data structure), similar file system. not real file system of computer. so, want represent internal implementation user react adding new files, deleting files, editing files, adding folders, i.e. basic operations. i have no idea how achieve using qt uis. idea represent these files/folders using qlabel , setting pixmap them? if implement this, lot of work, like, once folder clicked, frame should cleared , new set of labels should loaded in same frame. what easiest way?

asp.net - MVC drop down list input post value and name -

i'm writing form uses drop down menus value selection. i'd know if possible post value , name of selectlist controller or add values every list item? need set lateralityid = value , lateralityname = text . i'll post snippets of code idea across. model i'm using is public class condition { public string lateralityname { get; set; } public string lateralityid { get; set; } } and values posted with @html.dropdownlistfor( m => m.condition.lateralityid, getlateralities() ) where public static list<selectlistitem> getlateralities() { return new list<selectlistitem> { new selectlistitem { text = "", value = "900" }, new selectlistitem { text = "left", value = "1001" }, new selectlistitem { text = "right", value = "1002" }, new selectlistitem { text = "midline", va...

swift - How to move or resize an NSView by setting the frame property? -

i created nsview in storyboard. in case, nstextfield . in nsviewcontroller 's viewdidload() method, want conditionally resize , reposition nstextfield , setting frame has no effect. for example: class viewcontroller: nsviewcontroller { @iboutlet var label: nstextfield! override func viewdidload() { super.viewdidload() // additional setup after loading view. label.frame = nsrect(x: 0, y: 0, width: 200, height: 17) label.setneedsdisplay() } } when view loads, label still has original frame set in interface builder, , not newly set frame. how 1 programmatically move/resize label? the autolayout system culprit here. when set frame, autolayout system overrides re-establish implicit constraints set in storyboard. set translatesautoresizingmaskintoconstraints property of label true . tells autolayout system should create new set of autolayout constraints satisfy new frame you've set: class viewcontroller: nsvi...

ios - Why the leading space is -20 when adding a constrain on super view -

Image
i added subview inside super view. have same x-location. added leading constrain between these 2 constrain value -20. faced issue many times. don't know why seems aligned constrain -20 different. the margins different each device size. the right way set space between boundaries , view 0 uncheck constrain margins checkbox

javascript - Checkbox isn't checking to the correct value -

i have should simple code, reason i'm not getting wrong logic setting checkbox properly. i'm using local storage checked state persistent among sessions. here code. happening reason though console.log prints out false when should false, or true when should true, either way checkbox ends being checked. var checkboxelement = document.getelementbyid("checkbox").getelementsbytagname('input')[0] checkboxelement.addeventlistener('click', function() { console.log(checkboxelement.checked) if (localstorage != undefined) { localstorage.setitem("checkbox", checkboxelement.checked) } }); if(localstorage != undefined) { console.log("local storage supported."); //set defaults if (localstorage.getitem("checkbox") == undefined) { localstorage.setitem("checkbox", false) } var ischecked = localstorage.getitem("...

excel vba - VBA UDF ParamArray Sequence -

Image
i want create function sumifs, i'm having hard time figuring our how handle paramarray portion. i'm looking solution allows same range1,criteria1,range2,criteria2,...,rangen,criterian sum ifs in "sumifscontains" function. i've attached code singular case, "sumifcontains" can see starting point: function sumifcontains(phraserange range, criteria string, sumrange range) dim element range elementcount = 0 each element in phraserange elementcount = elementcount + 1 next element dim sumarray: redim sumarray(1 3, 1 elementcount) elementcount = 0 each element in sumrange elementcount = elementcount + 1 sumarray(2, elementcount) = element next element elementcount = 0 each element in phraserange elementcount = elementcount + 1 sumarray(1, elementcount) = element if instring(cstr(element), criteria) sumarray(3, elementcount) = sumarray(2, elementcount) else sumarray(3, elementcount) = 0 end if next element...