Posts

Showing posts from May, 2013

java - Libgdx: Scoring points basic -

i trying code score system increments whenever collision occurs between enemy , player. initialize score 100 , incremented once collision detected, means the old score 100 , new 1 101. happen old score 0 while new score 100. can me debut code. thank you. here code: code in bpaste when call getscore() first time, hasn't been initialized yet, returns 0. what scoreincrement() method add 100 tempscore, added score (which 100). if understood intentions correctly, use this: //initialize score 100 private int score = 100; //method incrementing score 1 public void scoreincrement() { score++; } //score getter public int getscore() { return score; }

Using for next loop step 50 php? -

i want steps using next loop. on vb or vb.net for i=0 1000 step 50 .... next how can use code in php? you can use this: for ($i = 0; $i <= 1000; $i += 50) { // code... } it wise read php for more details.

sql server - SQL max(DateTime) and category filter without group by -

i've written below query : select datetime, configid, rowid linkedtabledefinition a, inner join tabledefinition b, on a.target = b.id inner join viewwithinfo c, on a.target = c.id this gives following output: datetime configid rowid 12-09-2013 11:00 4 12 12-09-2013 12:00 4 12 12-09-2013 13:00 3 11 12-09-2013 12:00 3 11 12-09-2013 11:00 4 11 what need of output following: per rowid , configid combination need highest value datetime column. above example want following output: datetime configid rowid 12-09-2013 12:00 4 12 12-09-2013 13:00 3 11 12-09-2013 11:00 4 11 does know answer? avoid group because select statement extended lot more columns. thanks in advance edit current query: select testresults.resultdate, testresults.configurationid, testresultstestcaseid dbo.factworkitemlinkhistory workitemlink inner join dbo.dimwork

javascript - CanJS right click event -

how can bind right click event in canjs? i've attempted following, guess click captures left clicks (as ev.which doesn't log 3 on right clicks). '.btn click': function (el, ev) { console.log(ev.which); switch(ev.which) { case 1: var val = 1; break; case 3: ev.preventdefault(); var val = -1; break; } var item = can.data(el.closest('tr'), 'item'); item.attr('rel', item.rel + val); } i don't know canjs is, use oncontextmenu : elem.oncontextmenu = function(e) { e = e || window.event; if(e.preventdefault) e.preventdefault(); e.returnvalue = false; // code };

loading opencv::mat images with alpha channel in opengl texture -

i want load opencv::mat images alpha channel opengl texture. with of following posts manage load rgb images opengl texture opencv::mat. https://stackoverflow.com/questions/16809833/opencv-image-loading-for-opengl-texture https://stackoverflow.com/questions/9097756/converting-data-from-glreadpixels-to-opencvmat/9098883#9098883 but when try load image alpha channel, there problem. here how glteximage2d function called. glteximage2d(gl_texture_2d, // type of texture 0, // pyramid level (for mip-mapping) - gl_rgba, // internal colour format convert image.cols, // image width image.rows, // image height 0, // border width in pixels (can either 1 or 0) gl_bgra_integer, // input image format gl_unsigned_byte, // image data type

multithreading - Multithreaded Pipeline for Java(7) -

i'm building summarizer , need pipeline implementation. i've used own implementation, work grows see won't cut. is there mature framework in java provides me foundation (basically synchronization logic)? i need declare stage, , each stage has workers, workers process items , return results stage, sends next stages (might fan out). the whole point of implementation give me foundation doesn't work (race condition brings deadlock) i've tried getting apache library (which dead basically) doesn't have feature create stage workers. just connect stages blocking queues, , work reliably. use bounded arrayblockingqueue avoid saturation of queues if producers work faster consumers. most pipeline/dataflow/actor frameworks deal tasks small assigning single thread stage overhead stages share thread pool, , have limited number of working threads. framework (probably) exploits several threads per stage fbp , not sure.

c++ - boost spirit qi match multiple elements -

i create parser based on boost spirit qi able parse list of integer values. extremely easy , there tons of examples. list though bit smarter comma separated list , looks like: 17, 5, fibonacci(2, 4), 71, 99, range(5, 7) the result of parser should std::vector following values: 17, 5, 1, 2, 3, 71, 99, 5, 6, 7 where fibonacci(2, 4) results in 1, 2, 3 , range(5, 7) results in 5, 6, 7 edit: looking if have parsers have attribute int (say int_) , parsers have attribute std::vector fibonacci , range, how can combine results in single parser. like: list %= *(int_ | elements [ fibonacci | range ] ); where elements magic necessary magic results form fibonacci fit in list. note: not looking solution includes append functions like list = *(int_[push_back(_val, _1)] | fibonacci[push_back(_val, _1)] | range[push_back(_val, _1)] ] ); here's simplist take: live on coliru typedef std::vector<int64_t> data_t; value_list = -value_expression % ','

assembly - Merge sort segmentation Fault NASM -

Image
hi trying implement mergesort algorithm in nasm on linux, getting segmentation fault, typed in konsole "gdb mergesort core" , got "el núcleo se generó por «./mergesort». el programa terminó con la señal 11, segmentation fault. #0 0x080481a5 in ?? () (gdb) bt #0 0x080481a5 in ?? () #1 0x080481b1 in ?? () #2 0x080480af in ?? ()" but don`t understand or segmentation fault taking place. me please? im sorry first time pasting code here don`t know how indent way should the code in nasm following: bits 32 extern printf section .data section .text global _start global main, main: _start: nop; mov edi, sorted mov esi, array mov ecx, 10 rep movsd push 10 push 0 push sorted call mergesort add esp, 12 push sorted push 10 call print add esp, 8 ret merge: push ebp mov ebp, esp push eax push ecx push edx push edi push esi mov ecx, [ebp+20] sub ecx, [ebp+12] shl dword[ebp+12], 2 shl dword[ebp+16], 2 shl dword[ebp+20], 2 mov edx, tem

asp.net mvc 3 - This page isn't redirecting properly error with MVC3 + AJAX + Forms Authentication -

edit: removed non-relevant code/desc, since issue not initial code there. i have mvc3 based application uses lot of ajax calls (such jqgrid) , forms authentication. use [authorize] attribute on controller/actions call ajax in cases. every application falls on 'this page isn't redirecting properly' or 'this page has redirect loop'. i checked out fiddler. after logging in user , trying access pages require authentication, redirected account/logon goes infinite loop. happens when i'm calling controller/action authorize attribute ajax call. application seems send out 302 redirect account/logon. account/logon call seems redirect itself. , textview on fiddler shows following. <html><head><title>object moved</title></head><body> <h2>object moved <a href="/account/logon">here</a>.</h2> </body></html> i have following in global.asax file protected void application_endreq

bad performance when passing around boolean-arrays in clojure -

i've started solving project euler problems in clojure means of learning language. when implementing sieve of eratosthenes problem 10 experienced extremely poor performance appears stem passing around boolean-array . i've found can work around problem either adding type hints or reordering code helper functions can access boolean-array directly parent scope, don't understand why it's needed. (type sieve) in of helper functions returns [z , appears clojure knows it's boolean-array . can please explain why type hints needed here? apologies wall of code, don't know parts can removed while still illustrating problem. ;;; returns vector containing primes smaller limit (defn gen-primes-orig [limit] (defn next-unmarked [sieve v] (loop [i (inc v)] (cond (>= limit) nil (false? (aget sieve i)) :true (recur (inc i))))) (defn mark-powers-of! [sieve v] (loop [i (+ v v)] (if (>= limit) sieve (do

javascript - .animate step TypeError: object is not a function -

i building svg animations using raphael.js. trying build pie chart. call function within step option through .animate() method. the error get: uncaught typeerror: object not function line: pie_fill.attrs({'path': arc(1, 2, 3, 4)}); it doesn't understand arc() function @ within step option. have no idea why, please help. var r = raphael("paper"); pie_fill = r.path(("m 150 77 l77 77 z")).attr({'fill':'#009bca', 'stroke':'#1c1c1c', 'stroke-opacity':'1', 'stroke-width':'1'}); var pie = new raphael($('#paper'), 300, 154); $('#paper').animate({ 'margin': '0' }, { 'duration': 1500, step: function( now, fx ) { pie_fill.attr({'path': arc(1, 2, 3, 4)}); } }); arc =function(center, radius, startangle, endangle) { console.log('ran') };

python - Lock in multiprocessing package not working -

the following code simple, testing purposes, not getting output desired: from multiprocessing import process,lock def printing(l,i): l.acquire() print l.release() if __name__ == '__main__': lock = lock() in range(10): process(target=printing,args=(lock,i)).start() the output is: 0 1 2 3 5 6 4 7 8 9 locks supposed suspend other processes executing. why isn't happening here? what output did expect? output looks fine me: permutation of range(10) . order in processes happen execute may vary run run. that's expected. i suspect misunderstand lock does. when acquire lock, every other process trying acquire same lock blocks until lock released. that's all. in test run, process 0 happened acquire lock first. other processes trying acquire lock blocked until process 0 releases lock. process 0 prints 0 , releases lock. happened process 1 acquired lock. etc. comment out l.release() , , you'll see program n

java - @EnableJpaRepositories does not obey to @Primary annotated beans -

i've simple spring setup using @inject , @componentscan , @enablejparepositories . there no need have specific @configurations test, integration or production environments. i'm using spring test mvc framework , i'm introducing @testconfig containing mocked beans (spring data) repository classes have @primary annotation. @enablejparepositories seems not obey @primary repository beans in testconfig . is there easy way solve or should split using specific profiles not enabling spring data jpa repositories?

c++ - How can i say visual studio to link a library with my project? -

i want write network program in visual studio, write little programm #include<iostream> #include <winsock.h> int main() { wsadata wsadata; // if doesn't work //wsadata wsadata; // try instead // makeword(1,1) winsock 1.1, makeword(2,0) winsock 2.0: if (wsastartup(makeword(2,0), &wsadata) != 0) { std::cout << "error" << std::endl; exit(1); } wsacleanup(); return 0; } but there link errors, in beej's guide seys should link wsock32.lib library, don't know visual studio good, can me? add wsock32.lib text field in project properties -> linker -> input -> additional dependencies check project properties -> linker -> command line verify it's added command line. alternatively, drag , drop lib file project in visual studio - should linked automatically.

android - How to place UI components uniformly using dip -

Image
i need make below ui android app. specifications: ui contains total 4 sections (1-4). component 1,2 & 4 must of same size. component 3 must twice size of component 1. but how can calculate exact dip size component uniformly sized on different sized screens? if approach wrong please advice. thank you if approach wrong please advice. use vertical linearlayout , android:layout_weight on children. if pretend moment children buttons, use: <?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <button android:layout_width="match_parent" android:layout_height="0dip" android:layout_weight="1" android:text="1"/> <button android:layout_width="match_parent" androi

c++ - Test for end of line and white space -

i reading file of 5 doubles in line through loop , storing them vector of structs , there less 5 doubles on line. file looks like 111.111 222.222 333.333 444.444 555.555 666.666 777.777 (whitespace) 888.888 999.999 struct temp_struct{ double d1,d2,d3,d4,d5 }; vector<temp_struct> data; for(int i=0;i<3;i++) file>>data.at(i).d1>>data.at(i).d2>>data.at(i).d3>>data.at(i).d4>>data.at(i).d5; is there way test empty space after 666.666 , inbetween 777.777 , 888.888. because right way reading in, after 666.666 go next line of file , read 777.777 , 888.888 999.999 struct looks data.at(1).d1=666.666 data.at(1).d2=777.777 data.at(1).d3=888.888 , data.at(1).d4=999.999 rather have data.at(1).d1=666.666, break because of end of line data.at(2).d1=777.777, data.at(2).d2=0, data.at(3).d3=888.8888 i programming in vs2010 c++ the usual way parse line-based text use std::getline() in combination std::istringstream , e.g.: for

html - Repeat image to extend header to fill screen -

i have header (2300x328px) , image (456x328px). want second image extend header left , right, header fills whole width availiable.it needs connect without overlapping, because there pattern. here image of mean: http://imgur.com/0ji3hae circles pattern (why should not overlap) , images extend header can repeated infinitely. for pattern align need align background pattern according header image (ex. center, left etc) , make sure pattern starts @ right place. i made fiddle explain mean - http://jsfiddle.net/taneleero/g99xa/ .header { background:url(http://i.imgur.com/bzvtzl4.jpg) repeat-x center; } .header img { display:block; margin:0px auto; }

algorithm - Why does iterative deepening A star not need to test for duplicate states? -

iterative deepening star (id a*) memory bounded search. question when reach new state s' open state s in id a*, why not test whether s' in "open states" or "closed states"? for problem, e.g.: sudoku, state never reached twice, because "graph of states of problem" tree. however, other problem, e.g.: 8-puzzle, reach state again , again. so, should tested whether state "visited" (either in open or closed states) or not. if such tests have done, id a* not memory bounded anymore because large hash table of possible states has stored. we don't test whether s' duplicate in order keep memory profile small. in general, ida * will, in fact, expand same state multiple times.

c++ - Going back to a previous line in a .txt file -

i've read numerous articles on how read specific line .txt file, none of them need. i'm creating simple parser sort of "programming language" , want include "label" system. thing is, though, in order go specific label, may have go or forwards in text file. how go specific line in .txt file? there way can return original line afterwards? thanx in advance. the best can try random access of files move position of file. refer : http://www.learncpp.com/cpp-tutorial/137-random-file-io/

jquery convert nested list of radio buttons to dropdown with optgroup headings -

i've seen more few few posts on looking take list of links , turning them drop-down. i've taken examples , have not had luck applying them markup bit different. need turn nested list of radio buttons labels , convert them drop down list <optgroup> headings, removing nested radio inputs , labels. basically list of radio buttons im working wildly out of control , clean drop down list better usability , screen real estate. once handle conversion, plan hide original radio button set, , map user drop-down selection corresponding radio buttons process on submission of form. first need generate drop-down list . . . here simplified sample of starting markup: <ul> <li> <label><input type="radio">usa</label> <ul class="children"> <li> <label><input type="radio" >northeast</label> <ul class="children">

concatenation - SML, Write a function that concatenates a list of lists -

i need write concat function in standardml such that: concat [[5,4,3],[],[9,5],[],[],[1,1]] = [5,4,3,9,5,1,1] i new @ sml, don't think understand how breakdown lists , append them. answer may use built in append function alist @ blist thanks! if you're expected write such function, i'm assuming have learned how build recursive functions iterate through list. knowledge plus @ function should enough. if you're unsure list method use, lista @ listb creates new list combination of lista , listb, while item1 :: lista creates new list item1 added head of lista .

c++ - arrays, removeFirst() not working? -

i have created method should remove first element of array, when run code, debugger flips out , i'm not sure why. this removefirst() method: loan & listofloans :: removefirst(){ index = 0; //determine if container needs shrunk if((numberofelements < capacity/4) && (capacity >= 4)){ // shrink container when array 1/4 full cout<<"shrinking array! \n"; loan ** temp = elements; elements = new loan * [numberofelements/2]; //copy temp array elements for(int = 0; i<numberofelements; i++){ temp[i] = elements[i]; numberofelements = numberofelements/2; delete [] temp; } } numberofelements--; return **elements; } and header file measure: #include <iostream> #include "loan.h" using namespace std; class listofloans { public: listofloans(int initial_size=4); ~listofloans(void); void add(loan & aloan); loan &

How would I use Socket.io on a dedicated node.js server on a php site? -

for web application coded in php, powering lot of functionality traditionally utilize ajax, real-time chat, socket.io. in order use websockets without straining apache servers, have servers running node.js websocket connections. intend use dnode allow php scripts call node.js websocket functions. how this? please provide simple example if possible. i realize may not efficient structure, because of large number of connections utilizing real-time functionality @ same time, running websockets php server-intensive. know there other ways of achieving real-time communication between server , client, long polling , forever iframes, there specific reasons behind choice of websockets. this alternative send data php node.js: <?php $ch = curl_init(); $data = array('name' => 'foo', 'file' => '@/home/user/img.png'); curl_setopt($ch, curlopt_url, 'http://localhost:8082/test'); /* nodejs */ curl_setopt($ch, curlopt_post, 1); curl_se

Attempt to convert a C++ program to Java. Memcpy help needed -

i'm converting c++ program java, , have hit hitch in there no memcpy in java. i've taken best crack @ it, after doing research, i'm hesitant , unsure if doing c++ program should, found information found far little confusing. (java code still has memcpy in commented out refernce) the notes both image = input image output = output image n = width of image m = height of image. in c++ code, element unsigned short int. c++ code void medianfilter(element* image, element* result, int n, int m) { // check arguments if (!image || n < 1 || m < 1) return; // allocate memory signal extension element* extension = new element[(n + 2) * (m + 2)]; // check memory allocation if (!extension) return; // create image extension (int = 0; < m; ++i) { memcpy(extension + (n + 2) * (i + 1) + 1, image + n * i, n * sizeof(element)); extension[(n + 2) * (i + 1)] = image[n * i]; extension[

assembly - Custom Raspberry Pi OS File System -

i trying write os raspberry pi assembly code , want implement file system. cannot find out how read or write data sd card. nothing trivial , time consuming. you need study e.mmc standard jedec understand how host , card side works. can documents free site registration. you need understand how connection made emmc host interface. lead work spi . best what's available open source projects linux or uboot .

node.js - express logging response body -

the title should pretty self explanetory. for debugging purposes, express print response code , body every request serviced. printing response code easy enough, printing response body trickier, since seems response body not readily available property. the following not work: var express = require('express'); var app = express(); // define custom logging format express.logger.format('detailed', function (token, req, res) { return req.method + ': ' + req.path + ' -> ' + res.statuscode + ': ' + res.body + '\n'; }); // register logging middleware , use custom logging format app.use(express.logger('detailed')); // setup routes app.get(..... omitted ...); // start server app.listen(8080); of course, print responses @ client emitted request, prefer doing @ server side too. ps: if helps, responses json, there solution works general responses. not sure if it's simp

regex - Java regular expression is not matching valid results -

this question has answer here: getting url parameter in java , extract specific text url 8 answers i'm trying write simple java regular expression extract out video id of given youtube video url. e.g for: http://www.youtube.com/watch?v=-mzvaauco1c i want extract out: -mzvaauco1c . here's i'm trying: pattern pattern = pattern.compile("v=([^&]+)"); string url = "http://www.youtube.com/watch?v=-mzvaauco1c"; matcher matcher = pattern.match(url); system.out.println(matcher.getgroupcount() ); //outputs 1 system.out.println(matcher.matches() ); //returns false; system.out.println( matcher.group(0) ); //throws exception, same 1 what doing wrong? invoke find match partial string . dont call matches after calling find - result in illegalstateexception . want capture group 1 rather 0 latter returns full string patter

html - Float logo to the left, and content to the right -

i have following html , css , logo floats on left side, i'd able have content float on right side. <html> <body> <div id="logo"> <img src="images/logo.gif" height="376" width="198" alt="logo" title="" /> </div> <div id="maintext"> <p id="main">first paragraph</p> <p>second paragraph.</p> </div> <footer>...</footer> </body> </html> in css, selector logo is: #logo { display: block; float: left; } #maintext { padding: 0 0.5em 0 0.5em; } what's happening logo " images/logo.gif " shows left side of on top of footer. should show on left side of "maintext" selector. any ideas? add css: footer { clear: both; }

java - Lucene: exact matches aren't shown first -

i using demo indexfiles , searchfiles classes index , search in org.apache.lucene.demo packet. my issue when use query contains more word, not getting results have exact match. instance: enter query: "natural language" searching for: "natural language" 298 total matching documents 1. download\researchers.uq.edu.au\fields-of-research\natural-language-processing .txt 2. download\researchers.uq.edu.au\research-project\16267.txt 3. download\researchers.uq.edu.au\research-project\16279.txt 4. download\researchers.uq.edu.au\research-project\18361.txt 5. download\www.uq.edu.au\news\%3farticle%3d2187.txt 6. download\researchers.uq.edu.au\researcher\2115.txt 7. download\ceit.uq.edu.au\content\2013-2014-summer-research-scholarship-project s-dr-alan-cody%3fpage%3d1.txt 8. download\ceit.uq.edu.au\content\2013-2014-summer-research-scholarship-project s-dr-alan-cody%3fpage%3d2.txt 9. download\ceit.uq.edu.au\content\2013-2014-summer-research-scholarship-project s-dr-alan-c

javascript - Internet Explorer leaks click event after adding an overlay in a jQuery mousedown handler -

in mousedown event-handler of div new div created , appended body. new div has position:fixed (can position:absolute ) , has 100% width , 100% height. therefore covers source div triggered mouse down event. latest google chrome (v30), latest firefox (v24), opera v12.16 , older safari v5.1.1 (on windows) after mousedown event no click event gets fired on event listener attached body. only internet explorer (both 9 , 10) does fire click event on body afterwards! why? , how can prevented? bug in ie? the html: <div class="clickme">click me</div> the css: .clickme { background-color: #bbb; } .overlay { position: fixed; /* or absolute */ left: 0; top: 0; height: 100%; width: 100%; background-color: #000; } the javascript: $(document).on('click', function(event) { console.log('body click'); }); $('.clickme').on('mousedown', function(event) { console.log('div mousedown');

php - Joomla 2.5: Migration to new server, but all links keep redirecting back to old server -

migrated joomla 2.5 site new server different domain. homepage showing correct url address. when hovering on links, shows correct address, when clicked on navigation links, redirected old server domain. acesef installed on site, disabled it. , it's still not working. any ideas? thanks check @live_site parameter in configuration.php file , check .htaccess file if have one. also try clearing cache.

c++ - Arguments in function -

i new c++ student , trying make basic program kids learn basic math. work in progress of code not done. trying compile have done far , getting error says: 47 59 [error] new declaration 'void add(int, int, std::string, char)' , 18 5[error] ambiguates old declaration 'int add(int, int, std::string, char)' #include <iostream> #include <iomanip> #include <time.h> #include <string> #include <cstdlib> #define over2 "\t\t" #define over3 "\t\t\t" #define over4 "\t\t\t\t" #define down5 "\n\n\n\n\n" #define down8 "\n\n\n\n\n\n\n\n" #define down10 "\n\n\n\n\n\n\n\n\n\n" #define down12 "\n\n\n\n\n\n\n\n\n\n\n\n" using namespace std; int add(int,int,string,char); int sub(); int multi(); int div(); int main(int argc, char** argv) { int num1, num2; unsigned seed = time(0); srand(seed); num1 = 1 +rand() % 4; num2 = 1 +rand() % 4; // corr

Haskell - Return item from custom type -

i'm working on haskell problem class, , can't seem syntax right pulling item out of custom type. here's type: -- finite state machine m = (q, q0, f, d) type fsm = ([int], int, [int], [(int,char,int)]) and here's test value i've been working with: testfsm :: fsm testfsm = ( [ 1, 2, 3 ], 1, [ 3 ], [ ( 1, 'a', 2 ), ( 2, 'b', 3 ), ( 1, 'b', 1 ) ] ) i want able pull out each piece of data fsm type, i'm not quite sure on how that. have tried this: fsmgetq fsm = [ q | ( q, q0, f, d ) <- fsm ] but if run function testfsm get: <interactive>:102:9: couldn't match type `([int], int, [int], [(int, char, int)])' `[(t0, t10, t20, t30)]' expected type: [(t0, t10, t20, t30)] actual type: fsm in first argument of `fsmgetq', namely `testfsm' in expression: fsmgetq testfsm in equation `it': = fsmgetq testfsm i've got lot of helper functions working individ

html - CSS No image for first ul in horizontal menu -

i trying make horizontal menu using ul, custom bullet image. want first menu item not have bullet on left hand side looks neat. bullets appearing in between items, not before menu items start. here have far: #navwrap ul.nav > li > a, #navwrap ul.nav > li .separator { text-align: left; text-transform: uppercase; color: #777; font-family: trajan; background-image: url('../images/bullet.jpg'); background-repeat: no-repeat; background-position: 0px 15px; padding-left: 25px; } #navwrap ul.nav > li > a:hover, #navwrap ul.nav > li .separator:hover { color: #333; background-image: url('../images/bullet.jpg'); background-repeat: no-repeat; background-position: 0px 15px; padding-left: 25px; } #navwrap ul.nav > li.active > a, #navwrap ul.nav > li.active .separator { color: #333; text-align: left; background-image: url('../images/bullet.jpg'); background-repeat: no-repeat

python - Create tree hierarchy using os.walk and gobject gtk+3 -

i trying create simple file browser. trying add tree hierarchy files. wrote sample method prints hierarchy correctly, having hard time model same concept create gtk.treestore object. following sample code list files: def list_files(startpath): dirname, subdirs, files in os.walk(startpath): level = dirname.replace(startpath, '').count(os.sep) indent = ' ' * 4 * (level) print('{}{}/'.format(indent, os.path.basename(dirname))) subindent = ' ' * 4 * (level + 1) f in files: print('{}{}'.format(subindent, f)) and following code create gtk.treestore : def add_paned(self): paned = gtk.paned.new(gtk.orientation.horizontal) test_dir = '/home/myuser' store = mytreestore(str) store.generate_tree(test_dir) treeview = gtk.treeview(store) renderer = gtk.cellrenderertext() column = gtk.treeviewcolumn("filename", renderer, text=0) treeview.append

bash - In Linux, how to redirect wall output in script to file? -

i'm trying log events in bash script following lines: #!/bin/bash { ... echo "photo backup finished on $(date)" | wall ... } &>> "/var/log/$(basename "$0").log" & however, in log file, corresponding line instead appears as: wall: cannot tty name: inappropriate ioctl device it seems wall outputs can't directed file. how can work? (be able post wall , log message file) one possibility use "tee -a" instead of ">>". example: echo "hello world"|tee -a myfile.log|wall

c - Naming a file with a loop counter -

how write line runs in loop , uses loop counter k give file name? int k; for(k = 0; k < 10; k++) fopen("/home/ubuntu/desktop/" + k + ".txt", "w"); // java-like code also how can create folder on local directory put files there instead of using desktop? there 2 parts question: creating directory, , writing numbered files. try following (updated directory protection set explicitly, correct headers included, , 1 file closed before next 1 opened): #include <stdio.h> #include <sys/stat.h> int main(void) { const char* mydirectory = "/users/floris/newdirectory"; char filename[256]; int ii, ferr; file *fp; ferr = mkdir(mydirectory, (mode_t)0700); for(ii=0; ii< 10; ii++) { sprintf(filename, "%s/file%d.txt", mydirectory, ii); if((fp = fopen(filename, "w"))!=null) { // whatever need } else { printf("could not open %s\n", filename); } fclo

App Engine: jar in WEB-INF/lib but still getting java.lang.ClassNotFoundException -

during app engine application's runtime, receive following exception: java.lang.exceptionininitializererror @ org.hibernate.validator.messageinterpolation.resourcebundlemessageinterpolator.interpolateexpression(resourcebundlemessageinterpolator.java:227) ... (removed brevity) caused by: java.lang.classnotfoundexception: de.odysseus.el.expressionfactoryimpl i had seen error on dev server , fixed including juel-impl in pom.xml when use appcfg.sh pull application server, see has juel-impl-2.2.7-20130801.163115-1.jar included in web-inf/lib i'm not sure make of this. update: according gae issue tracker , has been fixed in version 1.9.7. earlier versions, see below. hibernate validator 5.x makes use of unified expression language . in particular, uses static api method looks implementation of expressionfactory . bug in app engine 1.9.4 , earlier, however, seems prevent use of expression factory implementation in production only . until fixed, there 2 wo

html - Would like to convert from a PHP row to a column -

i have ranking system on website , display in column rather row. $result = mysql_query("select *, round(score/(1+(losses/wins))) performance images order round(score/(1+(losses/wins))) desc limit 0,10"); while($row = mysql_fetch_object($result)) $top_ratings[] = (object) $row;

java - AsyncPlayerChatEvent, Trying to see if a string from a string array is contained within another string from a second string array -

i making plugin bukkit minecraft server running version 1.6.4. plugin supposed stop players spamming, censor swear words allow words have swear words embedded in them (e.g. hello, molasses). have created 2 string arrays. 1 containing swear words , second containing "allowed" words. string[] curse = {"swear1", "swear2", "etc..."}; string[] allowed = {"allowed1", "allowed2", "etc..."}; what trying whenever player speaks in chat, have plugin check message swears while ignoring spaces , special characters. here have far (sorry if it's bit messy): public int seconds1 = 0; public int seconds2 = 0; public int spam = 0; @eventhandler public void onplayerchat(asyncplayerchatevent event){ player player = event.getplayer(); string name = player.getname(); seconds2 = seconds1; seconds1 = ((int) (system.currenttimemillis())); if (seconds1 - seconds2 <= 2500){ spam++; swi

Install Scala on Linux without administrator permisisons -

instructions install scala on linux here , requires administrator permissions. i working in shared environment without admin access. can install scala? of course, install in home directory. download .tgz file here: http://www.scala-lang.org/download/ then run tar xzf scala-[version].tgz that create directory installation of scala. set environment variables accordingly (e.g. $scala_home directory uncompressed, , add bin subdirectory $path )/

RegEx: Match Mr. Ms. etc in a "Title" Database field -

i need build regex expression gets text strings title field of database. i.e. complete strings being searched are: mr. or ms. or dr. or sr. etc. unfortunately field free field , written it. e.g.: m. ; a ; cfo etc. the expression needs match on except: mr. ; ms. ; dr. ; sr. (note: list bit longer simplicity keep short.) what have tried far: this using on on field: ^(?!(vip)$).* (this match every string except "vip") i rewrote expression this: ^(?!(mr.|ms.|dr.|sr.)$).* unfortunately did not work. assume because because of "." (dot) reserved symbol in regex , needs special handling. i tried: ^(?!(mr\.|ms\.|dr\.|sr\.)$).* but no luck well. i looked around in forum , tested other solutions not find works me. i know how can build formula search complete (short) string , matches except "mr." etc. appreciated! note: question might seem unusual , seems have many open ends , possible errors. rest of application hand

ruby on rails - Calculating karma from upvotes/downvotes on a user's posts -

i have user , post model , using acts_as_votable gem (which gives me 'votes' table) upvote/downvote post. want assign karma each user, karma number of upvotes user has gained his/her posts minus total number of downvotes. currently have instance method on user's model calculate karma: def karma count = 0 self.posts.each |post| count += post.upvotes.size - post.downvotes.size end return count end i don't think above efficient run time of o(2n), because every post 2 additional database queries required, 1 upvotes, , 1 downvotes. any ideas on how combined above single query, or otherwise make more efficient? not efficiency, such design not in terms of oop. user model considers beyond scope. karma belongs user , should not tied in else. a better approach separate "karma" post. # add "karma" column $ rails g migration addkarmatouser # or use dedicated table class user < activerecord::base has_one :

php - How to direct top-level menu to second-level menu and have the top-level menu have unique name? -

goal in wordpress, attempting have admin menus automatically create if in menu "appearance -> menus". this, able develop. the part in having troubles due specificity. attempting have top-level menu direct second-level menu , have top-level menu maintain original name. code setup in "appearance -> menu" callsigns -> alpha -> bravo -> charlie the top-level menu "callsigns" has modified options. navigation label "alpha" , title attribute "callsigns". functions.php add_action('init', 'register_my_menus' ); function register_my_menus() { register_nav_menus( array('admin-menus' => 'admin menus')); } add_action('admin_menu', 'my_admin_menus'); function my_admin_menus() { $locations = get_nav_menu_locations(); $menu = wp_get_nav_menu_object($locations['admin-menus']); $pages = wp_get_nav_menu_items($menu->term_id

Can an Android App connect directly to an online mysql database -

android 3.3 api 18 hello, i developing first app using android. app have connect online database store user data. i looking cloud storage mysql database included. however, can app connect directly mysql database , push , pull data it. or there other things need do? many suggestions, yes can that. materials need: webserver a database stored in webserver and little bit android knowledge :) webservices (json ,xml...etc) whatever comfortable 1. first set internet permissions in manifest file <uses-permission android:name="android.permission.internet" /> 2. make class make httprequest server (i using json parisng values) for eg: public class jsonfunctions { public static jsonobject getjsonfromurl(string url) { inputstream = null; string result = ""; jsonobject jarray = null; // download json data url try { httpclient httpclient = new defaulthttpclient();

Controller validation in Cakephp -

i wish validate in controller in cakephp. though validations working in models instead of model wish validate in controller well. what did validate in contrller. $validates = array('email' => array( 'required' => array( 'rule' => array('notempty'), 'message' => 'a email required' ), 'isunique' => array( 'rule' => array('notempty'), 'message' => 'this email registered' ), 'email' => array( 'rule' => array('email'), 'message' => 'enter valid mail address' ) )); if ($this->user->validates($validates)) { die("action