Posts

Showing posts from September, 2011

OrientDB query for hierarchical data -

orientdb server v2.0.10 , trying come query following scenario. i have 2 hierarchies: a->b->c , d->e->f number of nodes in hierarchy can change. node in 1st hierarchy can connected other hierarchy using relation 'assigned'. want parent node of 2nd hierarchy if there incoming edge of node in 2nd hierarchy 1st. for example, have car-child->engine-child->piston , country-child->state-child->city , relationship made_in relates car or engine or piston either country or state or city if there relation either of country or state or city, country should returned. example, engine1-made_in->berlin, return germany. sorry such toyish example. hope clear. thanks. you should consider reading chapter "traversing" - should missing link answer question. can find here: http://orientdb.com/docs/last/sql-traverse.html basically, if think of graph family tree, want achieve 3 things: find children, grand-children, grand-grand-children (an

javascript - find percentage of page height jquery -

i trying write code div telling user how far has scrolled down page. here code: $(document).scroll(function(){ var fullheight = $(this).height(); var currentheight = $(this).scrolltop(); var percentageofpage = currentheight/fullheight; percentageofpage = percentageofpage.tofixed(2); var t = $("#t"); t.html("you " + percentageofpage + " down page." ); }); fiddle code works how should: writes out percentage how far user has scrolled. stops @ .67 or .69. why that? want go way 1. also, how can display percentage, 60%, instead of decimal, .6? here page is. addition : how can make @ when user reaches bottom of page, message becomes: "you have reached bottom of page", instead of percentage? $(document).on('scroll.percentage', function() { var scrollpercent = math.round(100 * $(window).scrolltop() / ($(document).height() - $(window).height())); // if user has reached bottom of page // unbind scroll liste

haskell - How do I write a function which behaves differently depending on which monad is at the base of the transformer stack -

(at point more of puzzle i'd know how solve solution expect use in practice) i'm trying write function rundebug following specification: argument has type io () ; return type (monad m) => m () ; depending on m , behaves in 1 of 2 different ways; if monadio m , rundebug = liftio , , otherwise rundebug = const (return ()) . the approaches i've tried relied on type class like class monaddebug m rundebug :: io () -> m () i've tried using monadbase , , i've tried using monadio overlapping instances, of them have run issues ambiguity. i think works writing instances each transformer, i've been hoping avoid that. write instances of monaddebug each transformer , each base monad interested in supporting.

Akka persistence receiveRecover receives snapshots that are from other actor instances -

i experiencing unexpected behaviour when using akka persistence. new akka apologies in advance if have missed obvious. i have actor called pcnprocessor. create actor instance every pcn id have. problem experience when create first actor instance, works fine , receive processed response. however, when create further pcnprocessor instances using different pcn ids, already processed pcn response. essentially, reason snapshot stored part of first pcn id processor reapplied subsequent pcn id instances though not relate pcn , pcn id different. confirm behaviour, printed out log in receiverecover, , every subsequent pcnprocessor instance receives snapshots not belong it. my question is: should storing snapshots in specific way keyed against pcn id? , should filtering away snapshots not related pcn in context? or should akka framework taking care of behind scenes, , should not have worry storing snapshots against pcn id. source code actor below. use sharding. package com

java - Using WholeFileInputFormat with Hadoop MapReduce still results in Mapper processing 1 line at a time -

to expand on header in using hadoop 2.6.. , need send whole files mapper instead of single line @ time. have followed tom whites code in definitive guide create wholefileinputformat , wholefilerecordreader mapper still processing files 1 line @ time. can see i'm missing in code? used book example can see. guidance appreciated. wholefileinputformat.java public class wholefileinputformat extends fileinputformat <nullwritable, byteswritable>{ @override protected boolean issplitable(jobcontext context, path file){ return false; } @override public recordreader<nullwritable, byteswritable> createrecordreader( inputsplit split, taskattemptcontext context) throws ioexception, interruptedexception { wholefilerecordreader reader = new wholefilerecordreader(); reader.initialize(split, context); return reader; } } wholefilerecordreader.java public class wholefilerecordreader extends recordreader<nullwritable, byteswritable> { private fi

c# - disable maximize capacity in a wpf window -

Image
i'm trying disable maximize capacity (not maximize button) in wpf window, far nothing has succeded. i'm using window windowstyle="none", when drag window far top of screen, os "maximizes" window (terribly bad, way). i uploaded 3 pictures show happening exactly. (however, due fact don't have 10 reputation, have post links instead. sorry that. , can't put 3 links, 2 of them, first 1 of window working normally) during: after: http://i62.tinypic.com/f3c1mu.jpg http://i62.tinypic.com/f3c1mu.jpg set maxheight,minheight , maxwidth,minwidth property window. example <window x:class="test.mainwindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" title="mainwindow" maxheight="350" maxwidth="525" minheight="350" minwidth="525"> </window&g

c - My shell segfault when I do "kill -11 0" -

when try command "/bin/kill -11 0" on bash, tcsh or zsh, doesn't segfault when try in mine, does. so must have didn't handle. do know can ? thanks. your program doesn't segfault when sends signal 11. if execution of programs results in "segment fault" (that is, program performs illegal memory reference), operating system sends program sigsegv (signal 11 on linux). program cannot distinguish between sigsegv sent operating system result of program fault , sigsegv sent call raise or kill , possibly process, respond though there had been real program error. if want protect shell signals sent pid 0 child process, need make sure child processes in different process group calling setpgid in child after fork. by default, program terminated sigsegv. default, shell invoked program report program terminated sigsegv. popularly known "segfaulting", indicated above, might not have been result of real program fault. if want program

python - Efficiently applying a function to a grouped pandas DataFrame in parallel -

i need apply function groups of large dataframe (of mixed data types) , take advantage of multiple cores. i can create iterator groups , use multiprocessing module, not efficient because every group , results of function must pickled messaging between processes. is there way avoid pickling or avoid copying of dataframe completely? looks shared memory functions of multiprocessing modules limited numpy arrays. there other options? from comments above, seems planned pandas time (there's interesting-looking rosetta project noticed). however, until every parallel functionality incorporated pandas , noticed it's easy write efficient & non-memory-copying parallel augmentations pandas directly using cython + openmp , c++. here's short example of writing parallel groupby-sum, use this: import pandas pd import para_group_demo df = pd.dataframe({'a': [1, 2, 1, 2, 1, 1, 0], 'b': range(7)}) print para_group_demo.sum(df.a, df.b) and

Filtering data in excel without having to use 'Filter' -

Image
i trying filter data in table based on month. has date cell. know can use filter option, don't want go through method decide month select. rather have more user friendly drop down box through select month , data shown of month only. know how implement this? open using macros , vba. this example of technique........you have modify meet needs. have: with data validation pull-down in cell c1 . put event macro in worksheet code area: private sub worksheet_change(byval target range) dim t range, mn variant set t = range("c1") if intersect(t, target) nothing exit sub mn = t.value cells.entirerow.hidden = false if mn = 0 or mn = "" exit sub = 2 24 mnt = month(cells(i, 1).value) if mnt <> mn cells(i, 1).entirerow.hidden = true end if next end sub the macro monitor selection , display/hide rows accordingly. because worksheet code, easy install , automatic use: right-click tab name near

datetime - PHP add weekdays not working properly for Friday -

i trying add weekdays date using below formula: $date = strtotime($effdate." +5 weekdays"); $date = date('m/d/y', $date); it works fine other days not friday. points next sunday rather friday. googled many solutions, didn't clear idea. is there workaround fix bug? if you're running php < 5.5.0 known bug , fixed in php 5.5 demo the bug report provide alternative function work versions of php susceptible bug, though it's using datetime objects rather unix timestamps

css - Why do I have to include the font files with Font-Awesome? -

the font-awesome docs not mention anywhere other files need downloaded , included within project why icons missing? i know font files should within relative path font-awesome can see them, understand that, reference other techniques combining , minifying css files , javascripts, why there more http requests fonts? [error] failed load resource: server responded status of 404 (not found) (fontawesome-webfont.woff, line 0) you can see state need copy entire directory onto webserver. http://fortawesome.github.io/font-awesome/get-started/ easy: default css use method default font awesome css. copy entire font-awesome directory project. so including css file in header isn't going much, because others have pointed out.. it's font. think of wingdings, that's font file. then css sets classes background images, using content written using font. minifying can cause disruption paths of css files. basically, need make sure things being

ios - Casting struct to NSUserDefaults in Swift? -

is there way can cast swift data set in someway form acceptable nsuserdefauts ? i.e. nsobject nsset ? (p.s. realize nsuserdefaults isn't type of data, i'm testing) struct users { var name: string = "" var stores: [store] } struct store { var name: string = "" var clothingsizes = [string : string]() } init() { let userdefaults = nsuserdefaults.standarduserdefaults() if let userspeople = userdefaults.valueforkey("users") as? i think can use dictionary. you'll need make method wrap data struct , vice versa. for example: var users : [string: anyobject]() users["name"] = "somename" users["stores"] = yourstorearray nsuserdefaults.standarduserdefaults().setobject(users, forkey: "users") something that. and when need struct if let mydictionaryfromud = userdefaults.objectforkey("users") as? [string:anyobject]

c# - Gmail API: forcing the authorization to reprompt the user -

the credentials authorizing access gmailapi seem cached somehow. when change client id , secret, , email address, nothing changes. also, when change scope, nothing changes. trying force credentials refresh. there way force credentials reprompt user? is there file can find , delete? i using c# , gmail api package nuget. code credentialing is: _emailaddress = settings.emailaddress; string clientsecret = settings.clientsecret; string clientid = settings.clientid; clientsecrets clientsecrets = new clientsecrets {clientid = clientid, clientsecret = clientsecret}; usercredential credential; credential = googlewebauthorizationbroker.authorizeasync( clientsecrets, scopes, "user", cancellationtoken.none).result; _service = new gmailservice(new baseclientservice.initializer() { httpclientinitializer = credential, applicationname = "draft sender", //applicationname, }); also, once credential, scope set: cannot change scope until delete ,

uri - REST convention for parent insert and parent + joinId insert using same endpoint -

in context of event management system speakers talking @ different sessions. entities speakers , sessions let's endpoint 1) post /speakers (to insert detail of speaker only) 2) post /speakers (to insert detail of speaker + id of session he's talking on) point 2 requires additional insert in join table. how can specify both kinds of operations within same endpoint. a speaker represented including session speaks on. example: { "id": 1234, "firstname": "joe", "lastname": "doe", "sessions": [] } this representation means speaker is not speaking on session . sessions empty array. doing post /speakers content-type: application/json with json body show above, create speaker . if client knows in advance sessions speaker speaking , json this: { "id": 1234, "firstname": "joe", "lastname": "doe", "sessions": [ {

asp.net mvc 4 - Having error in updating my record in database my method as follows -

what have done wrong in code ? (i using mvc4 , ef) example: please clear fresher use mvc4 editresponse response = new editresponse(); try { using (wematchcontext db = new wematchcontext()) { b_member_register update = new b_member_register(); var output = db.b_member_register.where(x => x.member_id == model.member_id).firstordefault(); if(output != null ) { update.first_name = model.first_name; update.last_name = model.last_name; update.gender = model.gender; update.dob = model.dob; int resultcount = db.savechanges(); if (resultcount > 0) { response.member_id = update.member_id; response.resultcode = 0; response.message = "updated successfully"; } you have attach updated data db entity. please try this, using (wematchcontext db = new wematchcontext()) { var update

scala - How can I benchmark performance in Spark console? -

i have started using spark , interactions revolve around spark-shell @ moment. benchmark how long various commands take, not find how time or run benchmark. ideally want super-simple, such as: val t = [current_time] data.map(etc).distinct().reducebykey(_ + _) println([current time] - t) edit: figured out -- import org.joda.time._ val t_start = datetime.now() [[do stuff]] val t_end = datetime.now() new period(t_start, t_end).tostandardseconds() i suggest following : def time[a](f: => a) = { val s = system.nanotime val ret = f println("time: " + (system.nanotime - s) / 1e9 + " seconds") ret } you can pass function argument time function , compute result of function giving time taken function performed. let's consider function foobar take data argument , following : val test = time(foobar(data)) test contains result of foobar , you'll time needed well.

python - Try alternative xpaths, or else continue -

i have pieced web crawler selenium uses xpath find elements. on web page i'm scraping, there 2 possible layouts loaded, depending on content. if run code on wrong layout, error: message: unable locate element: {"method":"xpath","selector": how can create try / except (or similar) tries alternative xpath, if first xpath not present? or if none present, continue on next section of code? i haven't got experience python i'm not able write example code, should create 2 try/catch (or in case try/except ) block try find element find_element_by_xpath . after catch nosuchelementexception , can work webelement(s). in java looks this: boolean isfirstelementexist, issecondelementexist = true; webelement firstelement, secondelement; try { firstelement = driver.findelement(by.xpath("first xpath")); } catch (nosuchelementexception e) { isfirstelementexist = false; } try { secondelement = driver.findel

String with functions to JSON -

i need turn string: "{ click : myclickfunction, render : myrenderfunction }" or variation of it, into : { click : myclickfunction, render : myrenderfunction } where myclickfunction , myrenderfunction functions defined else , not strings try this: function myclickfunction (test) { return "foo"; } function myrenderfunction (test) { return "bar"; } var mystring = "{click : myclickfunction,render : myrenderfunction}"; var obj=eval("("+mystring+")"); console.log(obj); console.log(obj.click()); console.log(obj.render());

ios - Accessing previous values in a ReactiveCocoa -flattenMap:/-then: chain -

let's have chain of reactivecocoa signals using -flattenmap: , -then: , so: __weak typeof(self) weakself = self [[[self foosignal] flattenmap:^racstream *(foo *foo) { return [weakself barsignal]; }] then:^racsignal *{ // create signal using foo }]; in case, barsignal dependent on foosignal completing ( next -ing, strictly speaking, foosignal once) without error, , next value barsignal nonsensical ( +combinelatest: doesn't apply). if sending next , they're dependent operations, not parallel ones. obviously, can use __block variable access foo , feels stylistically incorrect , hard follow (not strict chain downwards). i can write custom operator achieve this, that's more code __block variable , difficult make generic, think. is there clean way access foo ? i drop second -flattenmap: , instead add -then: end of barsignal . foo variable in scope there, , wait until barsignal complete before being subscribed to. __weak typeof(se

php explode the values and make spaces -

i have string in database. sorry can change database. tueslunch|monlunch|mondinner|tuesbkfast so has days name dinner, lunch , bkfast want make string show in php this tues lunch mon lunch mon dinner tues bkfast i have done far $weekdays = tueslunch|monlunch|mondinner|tuesbkfast; $days = explode('|',$weekdays); so can tell me how this? , suggestions appreciable. thanks you can use regular expressions this: $weekdays = "tueslunch|monlunch|mondinner|tuesbkfast"; $days = explode('|', $weekdays); $strings = []; foreach ($days $day) { preg_match_all('/[a-z][^a-z]*/', $day, $results); $strings[] = implode($results[0], ' '); } print_r($strings);

python - Why are commands executed via subprocess.call( ) different than commands executed via terminal? -

this question has answer here: python subprocess popen: why “ls *.txt” not work? [duplicate] 2 answers python subprocess wildcard usage 2 answers i'm running raspbian on raspberry pi 2 , wrote simple python script copy .png files home directory ( ~/ ) predetermined usb drive. the command run in terminal works: cp -r *.png /media/kingston/ in python have following: from subprocess import call # code call(['cp', '-r', '*.png', '/media/kingston/']) but when run script says cp: cannot stat `*.png' : no such file or directory i'm in right directory when try copy it. pwd gives correct results , ls shows correct .png files.

In R Convert list of lists into data frame based on multiple citeria -

if create list using code metrics<-list(m1=1,m2=2,m3=3) region_mertic <- list("west"=metrics,"east"=metrics) country_metric <- list("us"=region_mertic,"uk"=region_mertic) country <- list("country"=country_metric) the hierarchy of list looks this: > names(country) [1] "country" > names(country[[1]]) [1] "us" "uk" > names(country[[1]][[1]]) [1] "west" "east" > names(country[[1]][[1]][[1]]) [1] "m1" "m2" "m3" how can convert following data frame. in essence filter countries, region "east" , metrics "m2","m3" , values. us east m2 2 east m3 2 uk east m2 3 uk east m3 3 this should scalable big lists containing many lists of lists.

python - "from math import sqrt" works but "import math" does not work. What is the reason? -

i pretty new in programming, learning python. i'm using komodo edit 9.0 write codes. so, when write "from math import sqrt", can use "sqrt" function without problem. if write "import math", "sqrt" function of module doesn't work. reason behind this? can fix somehow? you have 2 options: import math math.sqrt() will import math module own namespace. means function names have prefixed math . practice because avoids conflicts , won't overwrite function imported current namespace. alternatively: from math import * sqrt() will import math module current namespace. that can problematic .

python - Create a time series from data -

i have dataframe contains information on defaults within loan portfolio , time origination occurred. each 'observation' pair representing time t in days, , amount of loan default: df['time_to_default'] # time origination default df['default_amnt'] # loan amount defaulted i create series represents cumulative amount of defaults given time t. (assume time_to_default evenly divisible t). cannot figure out how create new dataframe element, assign initial value 0 , iterate through series.... it sounds need use groupby cumsum since want running total: cum_defaults = df.groupby('time_to_default').default_amnt.sum().cumsum() you need reindex new series fill in missing days: cum_defaults = cum_defaults.reindex(index=range(min(cum_defaults.index), max(cum_defaults.index) + 1), method='ffill') with example data: df = pd.dataframe({

angularjs - ng-click not fire when on small width device -

i have angular web app have responsive. use bootstrap , responsive grid system. in every page have interact users set app, or change page. that, use ng-click , ng-href directives. i have tested many times, works great except when device screen width close phone portrait's width. noticed issue when use chrome dev tools phone emulator , check on phone wiko. have clue problem ? it's kinda weird, isn't ? edit : added ngtouch app, no change. i discovered ngclick item behind div no ng-click directive when on small screen device. fixed revising responsive.

javascript - iPad, iPhone modal dialog scrolling issue -

various pages on our website open jquery 'modal dialog' boxes. these work fine in every web browser. however problem occurs when viewing on ipad or iphone, , believe common issue. on pages modal dialog box big ipad screen, therefore need scroll modal box. however when dialog box doesnt move, background (i.e. main screen behind it) scrolls. i want disable background scrolling when modal open enable modal dialog scroll. i have tried 'position:fixed' underneath 'overflow:hidden' has solved issue others, unfortunately me, issue still exists. does have other ideas/things can try? below example of code 1 of pages opens in modal dialog box. thanks <script> function myonload() { window.parent.$('body').css('overflow', 'hidden'); } </script> <body onload="myonload()"> <div class="wrapper"> <div id="popup" class="modaldialog2"&

c# - Save image on disk from byte array (using EF), A generic error occurred in GDI+ -

i'm working on winforms program byte array database, transform image , save on disk. the picture displayed in picturebox element when try save file, code throw error : "the generic error occurred in gdi+". picture generated in folder, unreadable (weighs 0 octets). var profilimage = (from user in _context.mytable user.id == itemdata.id select user.profilimage).firstordefault(); image dcimage = bytearraytoimage(profilimage); this.picturebox1.image = dcimage; dcimage.save(this.tb_choose_folder.text + @"\test.jpg", imageformat.jpeg); method bytearraytoimage() // convert byte array image private image bytearraytoimage(byte[] bytearrayin) { if(bytearrayin == null) { throw new nullreferenceexception("bytearrayin"); } using (memorystream mstream = new memorystream(bytearrayin)) { return image.fromstream(mstream);

javascript - Magento Quick Simple Product Creation stuck on Please wait… screen -

when have configurable product, can't create associate products through quick simple product creation menu because screen gets stuck on loading please wait... screen. doesn't matter how long wait, simple product not created. i thought @ first maybe javascript thing, removed javascript server , uploaded javascript fresh install (1.7.0.2 version) still problem persists. when create simple product can assign fine, quicker , less error-prone if add simple products through quick simple product creation menu. anyone have idea might wrong? there 2 things need into. check www vs. no www redirects: site has accessible 1 of them. not both ways. double check .htaccess & under cpanel. mod_security: cause why magento stuck on 'please wait' when adding products or updating them. disable & see problem solved. might want contact server admin have rules whitelist magento admin backend.

haskell - Need help to understand the usage of `liftBase` -

i reading through (for self studying purpose) source code of bryan o'sullivan's popular pool library . and have question in function takeresource , ask haskell experts here. function defined as: takeresource :: pool -> io (a, localpool a) takeresource pool@pool{..} = local@localpool{..} <- getlocalpool pool resource <- liftbase . join . atomically $ ents <- readtvar entries case ents of (entry{..}:es) -> writetvar entries es >> return (return entry) [] -> used <- readtvar inuse when (used == maxresources) retry writetvar inuse $! used + 1 return $ create `onexception` atomically (modifytvar_ inuse (subtract 1)) return (resource, local) the line having problem is ... resource <- liftbase . join . atomically $ ... why here usage of liftbase necessary? can write instead ... resource <- join . atomically $ ... the compiler accepts both versions. missing here trivial or why liftbas

html - How to fill div with image -

i have responzive grid , dont know hot remove space between top , bottom of div. how fill image whole div? can see here https://jsfiddle.net/jo3jorch/1/ <div> <img src="http://beyondeurope.net/wp-content/uploads/2014/08/top_10_universities_in_new_york_city.jpg"> </div> div { width: 50%; float: left; } div img { width: 100%; } here go https://jsfiddle.net/b7nxzt8m/1/ this missing img { display:block; }

How to use Python newspaper library? -

i'm trying make web parser , saved it. had found newspaper library. i'm using eclipse. couldn't result. please me. import newspaper cnn_paper = newspaper.build('http://cnn.com') article in cnn_paper.articles: print(article.url) this error message: traceback (most recent call last): file "d:\workspace2\jeselasearchsys\nespaperscraper_01.py", line 2, in <module> import newspaper file "c:\python27\lib\site-packages\newspaper3k-0.1.5-py2.7.egg\newspaper\__init__.py", line 10, n <module> .article import article, articleexception file "c:\python27\lib\site-packages\newspaper3k-0.1.5-py2.7.egg\newspaper\article.py", line 12, in <module> . import images file "c:\python27\lib\site-packages\newspaper3k-0.1.5-py2.7.egg\newspaper\images.py", line 15, in <module> import urllib.request importerror: no module named request there nothing wrong code. need install or lo

javascript - CKEditor.replace not working -

for reason ckeditor stopped loading, same thing happening in example ckeditor.replace('test') ckeditor not loading in opera, can't tell when , why happened. other js working properly. if else faces problem try other browsers.

ms word - Java - POI - Add a picture to the header -

i have been trying add picture new docx file using java poi header. 1) have added header, , added text (using xwpfheaderfooterpolicy). 2) have create image (using customxwpfdocument). 3) not insert image inside header area. have tried through adding picture same paragraph of header, did not work. here function should add picture header. takes customxwpfdocument object has been created: private void addlogo(customxwpfdocument doc) throws invalidformatexception, ioexception, xmlexception { string imgfile = "1.jpg"; ctp ctp = ctp.factory.newinstance(); ctr ctr = ctp.addnewr(); cttext textt = ctr.addnewt(); textt.setstringvalue( " page 1" ); xwpfparagraph codepara = new xwpfparagraph( ctp, doc ); xwpfparagraph[] newparagraphs = new xwpfparagraph[1]; //add logo string blipid = codepara.getdocument().addpicturedata(new fileinputstream(new file(imgfile)), document.picture_type_png); doc.createpicture(blipid, doc.

c++ - What are copy elision and return value optimization? -

what copy elision? (named) return value optimization? imply? in situations can occur? limitations? if referenced question, you're looking the introduction . for technical overview, see the standard reference . see common cases here . introduction for technical overview - skip answer . for common cases copy elision occurs - skip answer . copy elision optimization implemented compilers prevent (potentially expensive) copies in situations. makes returning value or pass-by-value feasible in practice (restrictions apply). it's form of optimization elides (ha!) as-if rule - copy elision can applied if copying/moving object has side-effects . the following example taken wikipedia : struct c { c() {} c(const c&) { std::cout << "a copy made.\n"; } }; c f() { return c(); } int main() { std::cout << "hello world!\n"; c obj = f(); } depending on compiler & settings, following outputs are valid : he

java - Why do some servers run both Tomcat and also Apache Web Server? -

tomcat used running java servlets, has webserver functionality built in, can run independently. however, see several articles on how integrate apache webserver tomcat? what's purpose of doing this? improve performance? i using tomcat serving webservices. tomcat fine servlet container, there lot of things apache httpd can better (easier and/or faster). for example apache can handle security, ssl, provide load balancing, url rewriting etc. you can split content: can have apache httpd serve static content images, static html, js etc. , leave dynamic content (like servlets, jsp etc.) tomcat. has advantage failure in tomcat not render whole web site unusable / unavailable (just servlets/jsp pages). you can separate 2 , increase security: can run apache httpd on 1 server (which reachable on internet) , direct server running tomcat, invisible outside.

org.neo4j.rest.graphdb.entity.RestNode cannot be cast to Spring Data Neo4j Node Entity in SDN 3 -

not able typecast restnode neo4j node entity. using mapresult has been deprecated in spring data neo4j version 3. should right way convert? not sure if still needing answer, i'm using neo4joperations.convert method, pretty straight forward conversion: t convertedentity = neo4joperations.convert(object value, class<t> type);

Lame Encoding iOS in queue -

i'm trying convert wav file mp3 file using lame. i using code. want in background (or in queue). input file large, can take full control till finishing. can me so? int read, write; file *pcm = fopen([mergefile cstringusingencoding:1], "rb"); //source fseek(pcm, 4*1024, seek_cur); //skip file header file *mp3 = fopen([mp3filepath cstringusingencoding:1], "wb"); //output const int pcm_size = 8192; const int mp3_size = 8192; short int pcm_buffer[pcm_size*2]; unsigned char mp3_buffer[mp3_size]; lame_t lame = lame_init(); lame_set_in_samplerate(lame, 44100); lame_set_vbr(lame, vbr_default); lame_init_params(lame); { read = fread(pcm_buffer, 2*sizeof(short int), pcm_size, pcm); nslog(@""); if (read == 0) write = lame_encode_flush(lame, mp3_buffer, mp3_size); else write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, mp3_size); } while (read != 0); lame_close

ios - NSLocalized Creating a varying string from strings file -

i have string hold varying part in middle according cases. example: lost 255 points. the point value "255" varying part , want hold non-varying part in string file. don't want have 2 entries in strings file like. "string_start" = "you lost" "string_end" = "points." btw points part (255) in example nsmutableattributedstring support different color , font style. thanks in advance. i this: [nsstring stringwithformat:nslocalizedstring(@"you lost %d points", nil), 255] and localize @"you lost %d points" in whatever language want.

Python - Determine Matrix cells are a group -

given set of tuples represent position in matrix. for example {(1, 2), (1, 3), (2, 2), (0, 3), (0, 4)} where tuple (r,k) represents row r , column k. how can determine if hang together? examples {(1, 2), (1, 3), (2, 2), (0, 3), (0, 4)} => hangs {(1, 2), (1, 4), (2, 2), (0, 3), (0, 4)} => doesnt hang i'd simple bfs or dfs, example: def connected(cells): if cells: cells = cells.copy() stack = [cells.pop()] while stack: i, j = stack.pop() neighbors = {(i-1, j), (i+1, j), (i, j-1), (i, j+1)} & cells stack.extend(neighbors) cells -= neighbors return not cells usage/demo: for cells in ({(1, 2), (1, 3), (2, 2), (0, 3), (0, 4)}, {(1, 2), (1, 4), (2, 2), (0, 3), (0, 4)}): print(connected(cells)) prints: true false

How to get the record from table as hourly basis in SQL server? -

i have table called dailysales(id int,date date,time time,cashsale money,cardsale money,totalsale money).now want below result... date : 04-06-2015 time : 09:01 - 10:00 cashsale cardsale totalsale 10000.00 15000.00 25000.00 time : 10:01 - 11:00 cashsale cardsale totalsale 20000.00 15000.00 35000.00 . . . please me, thanks.. i'd suggest best bet store date/time in datetime or datetime2 column rather storing time, use can use datepart function hour. assuming time column datetime , like: select date, datepart(hour, time) hour, sum(cashsale) bycash, sum(cardsale) bycard, sum(totalsale) netsale dailysales group date, datepart(hour, time) this split hour hour, on hour (e.g 09:00:00 09:59:59, 10:00:00 10:59:59, etc.). if wanted offset split takes place, example @ 1

selenium - Dynamic xpath handling -

below xpath driver.findelement(by.xpath("html/body/div[9]/div/a/div")).click(); in above code value of div[6] keep changing. will driver.findelement(by.xpath("html/body/div[6]/div/a/div")).click(); or driver.findelement(by.xpath("html/body/div[1]/div/a/div")).click(); please provide solution. we faced issue dynamic page content making xpath identification useless. took decision make sure needed identified in test have id set. so: driver.findelement(by.xpath("html/body/div[6]/div/a/div")).click(); becomes: driver.findelement(by.id("mydivid")).click();

python - Custom dimension in collective.googleanalytics report -

i'm using collective.googleanalytics ( https://pypi.python.org/pypi/collective.googleanalytics ) add ga reports plone site. how can use custom dimensions (like ga:dimension1 or ga:dimension2) in new google analytics report? can't see related option in query dimensions field. solved updating collective.googleanalytics config.py support custom dimensions. dimensions_choices = ( ... "ga:dimension1", "ga:dimension2", "ga:dimension3", "ga:dimension4", "ga:dimension5",

jquery - Bootstrap not being applied to a dynamically loaded table in datatables -

so i'm trying run allow run query on db , i'd display result on page. since query can return number of columns i'm calculating number of columns after query has returned , creating table. issue i've tried using bootstrap styling provided in datatables docs although page buttons correctly styled table isn't. the html comes page styled correctly , classes generated seem correspond ones in bootstrap docs still style isn't applied. you can check out page on www.dito.ninja complete code. extends layout block head link(rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css") link(rel="stylesheet" type="text/css" href="//cdn.datatables.net/plug-ins/1.10.7/integration/bootstrap/3/datatables.bootstrap.css") script(type="text/javascript" language="javascript" src="//code.jquery.com/jquery-1.10.2.min.js") scri

php - Sort Array Date wise if given at Zero index Key -

actually have 1 array , need sort according date wise unfortunately becomes difficult me. can me out ... i have array in below $data = array ( array('july 2015', 2 , 5, 0, ''), array('september 2015', 2 , 5, 0, ''), array('august 2015', 2 , 5, 0, ''), array('march 2017', 2 , 5, 0, ''), array('december 2015', 2 , 5, 0, ''), array('march 2016', 2 , 5, 0, ''), ); now want sort array according date wise start smallest date bigger date like, becomes that. $data = array ( array('july 2015', 2 , 5, 0, ''), array('august 2015', 2 , 5, 0, ''), array('september 2015', 2 , 5, 0, ''), array('december 2015', 2 , 5, 0, ''), array('march 2016', 2 , 5, 0, '')

visual studio 2013 - Branches in TFS are physical or Virtual? -

we have branched our tfs based code , and when got latest version created separate physical directory on our machine unlike git can have 1 copy @ time , can switch branches? creating separate physical directory creating separate project, confused tfs branching concept. central on server or creating separate directory on server too? the branches in team foundation version control (tfvc) separate "directories" on server also; branch folder "keeps" differences parent folder size of stored data far less double of parent size. , yes you'll have 2 different folders same project on local workspace; three's no concept of active branch.

ruby on rails - Mongoid::Errors::MixedRelations in AnswersController#create -

getting following error msg while saving answer: problem: referencing a(n) answer document user document via relational association not allowed since answer embedded. summary: in order access a(n) answer user reference need go through root document of answer. in simple case require mongoid store foreign key root, in more complex cases answer multiple levels deep key need stored each parent hierarchy. resolution: consider not embedding answer, or key storage , access in custom manner in application code. above error due code @answer.user = current_user in answerscontroller. i want save login username answer embaded in question. deivse user model: class user include mongoid::document has_many :questions has_many :answers class question include mongoid::document include mongoid::timestamps include mongoid::slug field :title, type: string slug :title field :description, type: string field :starred, type: boolean validates :title, :presence =>

Retrive data and paste using Excel VBA -

vba code here 'this function ur comnad button private sub cmdgetdata() call getdata end sub here module 1 getting data configuration file. 'module 1 public sub getdata() dim oexcelconn adodb.connection '===== dim oconn adodb.connection '* connection string dim orst adodb.recordset '* record set dim squery string '* query string dim sconnstr string dim wb workbook, wbcurr workbook sconnstr = getexcelconnstr(thisworkbook.path & "\data\exceldata.xlsx") set oconn = new adodb.connection oconn.open sconnstr set wb = workbooks.open thisworkbook.path & "\template\mytemplate.xltx" ictr = 1 sheet2.range("name_std").rows.count squery = "select * [config$a:r] column = " & sheet2.range("name_std").cells(ictr,1) set orst = new adodb.recordset orst.open squery, oconn set wbcurr = wb.worksheets("sheet1").copy after:=worksheets("sheet1") wbcurr.range("

php - Efficiently checking a hashed password from database -

firstly have tried best find definitive answer on this. secondly, code appears work, want confirm doing in efficient manner , not leaving myself open security breaches. firstly, use php password_hash when adding user admin table; $stmt = $dbh->prepare("insert admin (username, password) values (:username, :password)"); $stmt->bindparam(':username', $username); $stmt->bindparam(':password', $password); $password = password_hash('password', password_default); secondly, when user attempts login, retrieve users admin table matching username only, couldn't see way check hash during query (this part unsure if there better way), , define $password variable post input; $stmt = $dbh->prepare("select * admin username = :username"); $stmt->bindparam(':username', $username); $username = $_post['username']; // define $password use in password verify $password = $_post['password']; th

file - Image is not attached in quickblox for android -

i have made demo sending image private chat using quickblox, struggling attach image chat message, have gone through document , have used below links, no luck attach image my code below: chatmessage = new qbchatmessage(); sendbutton = (button) findviewbyid(r.id.chatsendbutton); sendbutton.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { final string messagetext = messageedittext.gettext().tostring(); if (textutils.isempty(messagetext)) { return; } // send chat message // // send message // ... int fileid = r.raw.ic_launcher; inputstream = chatactivity.this.getresources() .openrawresource(fileid); file file = filehelper.getfileinputstream(is, "sample_file.png", "myfile"); boolean fileispublic = true; qbcontent.uploadfiletask(file, fileispublic, messagetex

c# - RedirectToRoute doesn't work -

i'm making first web app. until haven't got problems redirecttoroute or redirecttoaction. @ end of post action want redirect, doesn't work @ here code: [httppost] public actionresult delete(int id) { var post = this.data .posts .all() .where(x => x.id == id) .firstordefault(); if (post != null) { var thread = this.data .threads .all() .where(x => x.id == post.threadid) .firstordefault(); this.data .posts .delete(post); this.data.savechanges(); return this.redirecttoroute(commonconstants.redirecttorouteshowthread, new { area = "", id = thread.id, title = thread.subcategory.title, name = thread.title, action = "display"

Restricting access to particular URL for sesame server deployed on JBoss (WildFly 8.2) -

i have sesame server running deployed in wildfly 8.2.0 final container. how can restrict access particular urls? i know have edit xml files (deployment descriptor , other files) don't know files , find them. i figured out self. step 1: open openrdf-sesame.war total commander or file archiver. go web-inf folder , open web.xml file. edit web.xml file adding constraints, roles , login-config tag in example : http://www.rivuli-development.com/further-reading/sesame-cookbook/basic-security-with-http-authentication/ save edited file within archive , redeploy openrdf-sesame.war file containing modified web.xml file. step 2: go wildfly folder , enter bin directory , run add-user.bat file. choose b) application user , hit enter. enter username , password new user. when asked "what groups want user belong to?", type in 1 of roles have created in web.xml file , hit enter. when asked “is new user going used 1 process connect process?” type “yes”

prolog is tree balanced -

i need implement predicate isbalanced/1 such isbalanced(t) true if t tree balanced. a binary tree in case, defined structure node(left,right), left , right can either node or prolog data item. what have far: height(node(l,r), size) :- height(l, left_size), height(r, right_size), size left_size + right_size + 1 . height(l(_),1). isbalanced(l(_)). isbalanced(node(b1,b2)):- height(b1,h1), height(b2,h2), abs(h1-h2) =< 1, isbalanced(b1), isbalanced(b2). expected output: ?- isbalanced(1). true. ?- isbalanced(node(1,2)). true. ?- isbalanced(node(1,node(1,node(1,2)))). false. it not work, advice appreciated! how representing tree? looks me that l(_) represents empty tree, and node(l,r) represents non-empty tree. and suspect height/2 has bug in seem have defined height of empty tree being 1 (rather 0). i represent binary tree follows: nil — empty tree tree(d,l,r) — non-empty tree, where d : payload data l : l

python - Override Django ImageField validation -

i trying create form users allowed upload image file + swf files. django's imagefield not support swf need override it. what want check if file swf, if true, return it. if it's not swf, call original method take care of file validation. however, not sure how implement that. here example of trying achieve, not work: from hexagonit import swfheader class swfimagefield(forms.imagefield): def to_python(self, data): try: swfheader.parse(data) return data except: return super(swfimagefield, self).to_python(data) what allowing only swf files @ moment. an alternative , possibly easiest solution use standard filefield custom validator: def my_validate(value): ext = os.path.splitext(value.name)[1] # [0] returns path filename valid = ['.jpg', '.swf'] if ext not in valid: raise validationerror("unsupported file extension.") class myform(forms.form): fi

angularjs - Regular Expression date time using MVC Data Annotations -

i'm mixing mvc data annotations , angularjs validations ng-pattern. i've done far thing: [regularexpression("/^[0-9]{4}-[0-9]{2}-[0-9]{2} 20|21|22|23|([0-1][0-9]):[0-5][0-9]:[0-5][0-9]$/", errormessage = "date format: yyyy-mm-dd hh:mm:ss")] as can see, try format date: yyyy-mm-dd hh:mm:ss . want make 24 hours time. problem form getting valid when type: 2015-21 , 2015-22 // 2015-20 not valid, cannot understand why 2015-12-20 21 // want user enter minutes , seconds, because has datetimepicker, more useful , sets format want so, why regular expression not working expect? your regex not work expected because did not use ^ anchor (although guess expression anchored, still better play safe) , did not enclose alternatives group, , 21 , 22 , 23 valid values. here fixed expression: ^[0-9]{4}-[0-9]{2}-[0-9]{2} (?:20|21|22|23|(?:[0-1][0-9])):[0-5][0-9]:[0-5][0-9]$ ^^^ ^^ see demo

javascript - Aggregate values from selected divs -

i'm trying pass values selected divs, ids of divs values want , aggregate textbox, i'm not getting result. want id div , in example div id="thisone" when click. script looks this: <script> function myfunction(elmnt, clr) { elmnt.style.backgroundcolor = clr; document.getelementbyid("allvalues").value = document.getelementbyid(elmnt.value).value; } </script> view: <form method="post" action="<?=base_url()?>index.php/dashboard/test_val"> <div id="frame"> <table> <tbody> <?php for($i = 0, $size = count($farm)-1; $i < $size; $i++) { if($i == 0) echo '<tr>'; if($flag == 1){ echo '</tr>';

Get Params Hash with values as nested arrays - Rails template -

i params new template create action in nested array format. eg. trying build excel kind of form. have 3 main headings feelings, questions, events feelings , events have 5 columns each , events has 1 column events data in array of 5 hash elements want feelings , questions data nested array of 5 hash elements event = [{obj1},{obj2},{obj3},{obj4},{obj5}] want feelings , questions [[{obj1},{obj2},{obj3},{obj4},{obj5}],[{obj1},{obj2},{obj3},{obj4},{obj5}],[{obj1},{obj2},{obj3},{obj4},{obj5}],[{obj1},{obj2},{obj3},{obj4},{obj5}],[{obj1},{obj2},{obj3},{obj4},{obj5}]] currently stuff array of hashes [{"0"=>[{obj1},{obj2},{obj3},{obj4},{obj5}]},{"1"=>[{obj1},{obj2},{obj3},{obj4},{obj5}] ...] <tr> <th class="col1" colspan="5"><%= label_tag('feelings') %></th> <th class="col2" colspan="5"><%= label_tag('questions') %></th> <th class="col3" colspan="

javascript - Google Maps APIv3 very slow and large -

i'm creating website local business , have added google map page using api v3. i've been working on reducing page size , load time , have noticed google maps biggest , slowest thing on page. i'm still running locally , don't have anywhere host currently, related code below. without maps (emulation hdpi screen): - server requests: 14 - data transferred: 1.5mb - load time: 1.19s with maps (emulation hdpi screen): - server requests: 82 - data transferred: 2.6mb - load time: 8.08s i using google maps api v3 create map. <div id="map-canvas"></div> with script: function initialize() { var mylatlng = new google.maps.latlng(-43.537061, 172.632426); var mapoptions = { center: mylatlng, zoom: 15 }; var map = new google.maps.map(document.getelementbyid('map-canvas'), mapoptions); var marker = new google.maps.marker({