Friday, 15 May 2015

java - Entity with @Column length greater than 255 characters -



java - Entity with @Column length greater than 255 characters -

since default 255 how specify "infinite" length hold info such huge text? should not vendor specific solution such "columndefinition" property.

try "text" (lob) http://www.postgresql.org/docs/8.0/static/datatype-character.html

@lob @type(type = "org.hibernate.type.texttype")

java sql hibernate postgresql java-ee

eclipse - Disable selection change in JFace TreeViewer -



eclipse - Disable selection change in JFace TreeViewer -

i have treeviewer in view. whenever press button (say s), viewer selects first item in tree starting letter (say stackoverflow). there way disable behaviour?

thank you.

restricting key events on tree looks promising loose navigating tree construction , expand/collapse on tree node , other functionality.

tree.addkeylistener(new keyadapter() { @override public void keypressed(keyevent e) { e.doit = false; } });

eclipse selection jface treeviewer

ruby on rails - rake assets:precompile issue. parsing error -



ruby on rails - rake assets:precompile issue. parsing error -

i getting issue, while precompile assets in production env.

assetsync: using default configuration built-in initializer rake aborted! caught encoding::compatibilityerror @ '["ok","/*!\n * jquer': incompatible encoding regexp match (ascii-8bit regexp utf-8 string) (in /home/rails_work/bunk1_dev/app/assets/javascripts/active_admin.js) /usr/local/rvm/gems/ruby-1.9.3-p194@bunk1/gems/json_pure-1.7.6/lib/json/pure/parser.rb:242:in `rescue in parse_string' /usr/local/rvm/gems/ruby-1.9.3-p194@bunk1/gems/json_pure-1.7.6/lib/json/pure/parser.rb:213:in `parse_string' /usr/local/rvm/gems/ruby-1.9.3-p194@bunk1/gems/json_pure-1.7.6/lib/json/pure/parser.rb:257:in `parse_value' /usr/local/rvm/gems/ruby-1.9.3-p194@bunk1/gems/json_pure-1.7.6/lib/json/pure/parser.rb:121:in `parse' /usr/local/rvm/gems/ruby-1.9.3-p194@bunk1/gems/json_pure-1.7.6/lib/json/common.rb:155:in `parse'

any help appreciating.

i have resolved issue, issue related json_pure gem precompilation. remove "require 'json/pure'" code , apply "require 'json'". hope reply help others.

thanks

ruby-on-rails deployment

jquery - How can i read an object filelist array in javascript? -



jquery - How can i read an object filelist array in javascript? -

i have created array store list of selected files. well, have honest, looked code , when realized worked purpose, used it. need access array in order delete files manually, have tried using index of each sector, not work.

this how create array , store files.

var files = []; $("button:first").on("click", function(e) { $("<input>").prop({ "type": "file", "multiple": true }).on("change", function(e) { files.push(this.files); }).trigger("click"); });

how read array files[] if contains object filelist or obtain indexs array?

here's how understand code:

each time first button in dom clicked file input dialogue accepts multiple files generated. upon homecoming dialogue emits change event files variable (a filelist object) attached function context (this). code pushes newly created filelist onto files array. since input accepts multiple files each object pushed onto files array filelist object.

so if want iterate through elements in files array can set function in change event handler:

var files = []; $("button:first").on("click", function(e) { $("<input>").prop({ "type": "file", "multiple": true }).on("change", function(e) { files.push(this.files); iteratefiles(files); }).trigger("click"); }); function iteratefiles(filesarray) { for(var i=0; i<filesarray.length; i++){ for(var j=0; j<filesarray[i].length; j++){ console.log(filesarray[i][j].name); // alternatively: console.log(filesarray[i].item(j).name); } } }

in iteratefiles() function wrote filesarray[i][j] isn't multidimensional array -- rather single dimensional array containing filelist objects behave much arrays...except can't delete/splice items out of them -- read-only.

for more info on why can't delete see: how remove file filelist

javascript jquery arrays html5 arraylist

asp.net - Input string was not in a correct format in replace mehod -



asp.net - Input string was not in a correct format in replace mehod -

i want edit text , there dynamic fields in it, used replace method have these fields in special place in context. problem when want replace these fields in context gave me error: input string not in right format. error happen in emailbody. , content of body variable this:

from: {journalabbreviation} &lt; {journalabbreviation}@test.com&gt;<br /> subject: review submitted {journalabbreviation}<br /> body:<br /> manuscript id:&nbsp; {manuscriptid}<br /> title: {title}<br /> <br /> <br /> dear {prefix} {firstname} {middlename} {lastname},<br /> <br /> give thanks review {journalabbreviation}. appreciate time , feedback , hope collaborate 1 time again in near future.<br /> <br /> kind regards,<br /> {firstnamesender}, phd<br /> associate editor<br /> {journalfullname}<br /> http://{journalabbreviation}.test.com<br /> <br />

this code has been saved string in database , body variable fill these code.

body = body.replace("{prefix}", "{0}"); body = body.replace("{firstname}", "{1}"); body = body.replace("{middlename}", "{2}"); body = body.replace("{lastname}", "{3}"); body = body.replace("{manuscriptid}", "{4}"); body = body.replace("{title}", "{5}"); body = body.replace("{journalabbreviation}", "{6}"); body = body.replace("{fulljournalname}", "{7}"); body = body.replace("{prefixsender}", "{8}"); body = body.replace("{firstnamesender}", "{9}"); body = body.replace("{middlenamesender}", "{10}"); body = body.replace("{lastnamesender}", "{11}"); string **emailbody** = string.format(body, prefix, firstname, middlename, lastname, manuscriptid, title, journalabbreviation, fulljournalname, prefixsender, firstnamesender, middlenamesender, lastnamesender);

the print out is:

from: ieee < ieee@test.com> subject: review submitted ieee

manuscript id: 102-ieee-2013 title: text mining using biclustering method international electrical engineering science

dr john smith,

a review has been submitted above-mentioned manuscript.

kind regards, international electrical engineering science http://ieee.test.com

can body help me find the problem? thanks

i see in body have {journalfullname} , not alter number anywhere on replace, (and other this) give error.

to avoid error ether alter parameter {{journalfullname}} ether sure replace because symbols {} wait have number within reflect parameter on format.

asp.net replace string-formatting

angularjs - Why does using wrap inside directive compile function cause infinite loop? -



angularjs - Why does using wrap inside directive compile function cause infinite loop? -

i trying utilize wrap function within compile function of directive.

the next cause infinite loop , crash browser:

function compiler(telement, tattrs, transcludefn) { var wrapper = angular.element('<div />'); telement.wrap(wrapper); homecoming linker; }

why happening?

i'll guess... first time compiler function called, wraps element (i.e., element in html set directive attribute) within new <div></div>. angular treats new element , compiles it... finds directive, calls compiler function again, wraps again, , angular treats new element... advertisement infinitum.

angularjs angularjs-directive

Importing Text File in Java Constructor -



Importing Text File in Java Constructor -

i not sure problems spawning from. have 2 classes, 1 called testfriends class , called guiapp class. in each of classes, object import file use. in testfriends class, import file in main method, parses , works nicely. in guiapp class, tried doing same thing, importing in constructor method , tells me file doesn't exists. both of files classes reside in same src folder , using:

bufferedreader in = new bufferedreader(new filereader(inputfile));

where inputfile string "friends.txt".

here 2 classes:

//this class works public class temp { public static void main(string[] args) throws parseexception { seek { system.out.println("hey"); bufferedreader in = new bufferedreader(new filereader("friends.txt")); //create string buffer reading string line = in.readline(); //reading first line system.out.println(line); } grab (ioexception e) { system.out.println("fail import."); } } } //////////the 1 below doesn't... public class guiapp extends japplet{ //** panel **// private jpanel outerpanel; //** button **// private jbutton button1; /* * constructor getting friends set */ public guiapp() throws parseexception, filenotfoundexception{ bufferedreader in = new bufferedreader(new filereader("friends.txt"));//error line } /* * create stuff */ public void createstuff() { outerpanel = new jpanel(); //create outer panel button1 = new jbutton("click me"); outerpanel.add(button1,borderlayout.south); } /* * initialize stuff */ public void init(){ createstuff(); //initialize create stuff this.add (outerpanel); } }

any ideas why when both working in same directory, 1 can read while other can't?

thanks,

edit: below exception thrown when run guiapp class:

java.io.filenotfoundexception: friends.txt (no such file or directory) @ java.io.fileinputstream.open(native method) @ java.io.fileinputstream.<init>(fileinputstream.java:120) @ java.io.fileinputstream.<init>(fileinputstream.java:79) @ java.io.filereader.<init>(filereader.java:41) @ guiapp.<init>(guiapp.java:50) @ sun.reflect.nativeconstructoraccessorimpl.newinstance0(native method) @ sun.reflect.nativeconstructoraccessorimpl.newinstance(nativeconstructoraccessorimpl.java:39) @ sun.reflect.delegatingconstructoraccessorimpl.newinstance(delegatingconstructoraccessorimpl.java:27) @ java.lang.reflect.constructor.newinstance(constructor.java:513) @ java.lang.class.newinstance0(class.java:355) @ java.lang.class.newinstance(class.java:308) @ sun.applet.appletpanel.createapplet(appletpanel.java:807) @ sun.applet.appletpanel.runloader(appletpanel.java:714) @ sun.applet.appletpanel.run(appletpanel.java:368) @ java.lang.thread.run(thread.java:680)

at run time applet doesn't have file looking for. create sure file nowadays @ run time.

please add together method code can file

public void readfile(string filetoread){ string line; url url = null; try{ url = new url(getcodebase(), filetoread); } catch(malformedurlexception e){} try{ inputstream in = url.openstream(); bufferedreader bf = new bufferedreader(new inputstreamreader(in)); // business logic here } catch(ioexception e){ e.printstacktrace(); } }

/* * constructor getting friends set */

public guiapp() throws parseexception, filenotfoundexception{ readfile("friends.txt") }

for more details @ images javase

to create image object uses a.gif image file under imgdir, applet can utilize next code:

image image = getimage(getcodebase(), "imgdir/a.gif");

java

Is iOS removing the Content-MD5 HTTP header? -



Is iOS removing the Content-MD5 HTTP header? -

i utilize web application that's returning content-md5 header in ios app, cannot retrieve header using [nshttpurlresponse allheaderfields] (whereas can see when utilize curl).

does know if ios deliberately removing header?

so i've figured out what's happened.

our saas provider has activated gzip default on non-production instances. mentioned in other threads, nsurlconnection supports gzip compression transparently , automatically send accept-encoding: gzip http header. when response received, nsurlconnection decompresses content , removes content-md5 header (because content-md5 hash of compressed data), why i'm not seeing in list of received headers.

ios

objective c - subview from UIWindow and sending it back to UIwindow -



objective c - subview from UIWindow and sending it back to UIwindow -

i have uiwebview loaded div, deed editor write. adding uiwebview sub view on uiwindow set frame equal total screen , hide uikeyboard, @ button method, need uiwebview uiwindow , sent uikeyboard. here code not working:

keyboardwindowframe= nil; (uiwindow *testwindow in [[uiapplication sharedapplication] windows]) { if (![[testwindow class] isequal:[uiwindow class]]) { keyboardwindowframe = testwindow; [webviewforediting setframe:cgrectmake(5, 63, 310, 400)]; [webviewforediting.scrollview setcontentsize:cgsizemake(310, 400)]; [keyboardwindowframe addsubview:webviewforediting]; break; } } - (ibaction)keyboardbuttonselected:(id)sender { [keyboardwindowframe sendsubviewtoback:webviewforediting]; //need send uiwebview uiwindow can write }

i think trying same thing , although question not particularly clear reply help.

it seems have view 'webviewforediting' want add together , bring in front end of keyboard. when click button want set view behind keyboard again.

i have tried using sendsubviewtoback code no joy.

in end though managed work using:

[[self view] exchangesubviewatindex: withsubviewatindex: ];

(credit goes sunny adapted question here)

i used next code below, switch between uiview , keyboard:

- (ibaction)togglebuttonpressed:(id)sender { uiwindow * window = [uiapplication sharedapplication].windows.lastobject; if (window.subviews.count == 1) { [window addsubview:_menuview]; } else { [window exchangesubviewatindex: 0 withsubviewatindex: 1]; } }

i working 2 views (_menuview , keyboard) means check how many subviews window has create sure add together _menuview once.

then easy exchange 2 views.

even if had more subviews in window sure utilize modified version of this. long none of other views alter places exchanging them switch same 2 views.

note: aside. not sure if code works if called when keyboard not first responder. variable window using lastly object in window, keyboard if has been made first responder. might need tweaking working @ other times.

objective-c uiwebview uiwindow

excel - Top third, next third of items by sales -



excel - Top third, next third of items by sales -

i have excel sheet shown below. need top third/ next 3rd items sales count. there way done in excel?

item count 1 100 2 90 3 80 4 60 5 55 6 50 7 45 8 35 9 25

dividing 3 buckets, 540/3 = ~180 items in each –

bucket 1 – items 1 , 2 (count = 190) bucket 2 – items 3, 4 , 5 (count = 195) bucket 3 - items 6, 7, 8, 9 (count = 155)

there multiple ways accomplish this. assuming item , count info in columns , b, shortest path utilize next formula in cell c2:

=round(3*sum($b$2:$b2)/sum($b$2:$b$10),0)

after entering c2, select cell , drag downwards right-bottom corner of cell way lastly row. note $ sign "missing" on purpose before sec 2. takes care of auto-fill behavior needed when dragging downwards corner.

if allowed utilize helper column, can create computationally more efficient method using next layout:

if want to, can hide column c. contains cumulative values of different sales counts. cell c1 set 0, cell c2 contains formula =$c1+$b2. column d approximates buckets using formula =round(3*$c2/$c$10,0) in cell d2, , 1 time again dragging downwards bottom-right corner. might improve approach if have many rows on sheet.

note both solutions yield same results. value in 1 or more buckets become 0, not right. can avoided using roundup in stead of round, since have not indicated want boundaries of buckets fall in different situations, thought leave exercise :-).

excel

google chrome - @font-face fonts within bootstrap css not displaying in firefox -



google chrome - @font-face fonts within bootstrap css not displaying in firefox -

i able display fonts in chrome, not in firefox. i'm wondering if issue because i'm using bootstrap framework. here's code:

@font-face { font-family:"bodyfont"; src: url("http://caseymmiller.com/galapagos/fonts/museosans_300.otf"); } body { margin: 0; font-family: "bodyfont"; font-size: 15px; line-height: 20px; color: #333333; background-color: #ffffff; }

also, upon uploading server, 1 font appearing in chrome... , local sourcing wasn't working removed it. quite confused. http://caseymmiller.com/galapagos/bootstrapinvasive/invasive.html

this have in css now. tried listed before, when sourcing both urls each font, none of them appear. that's why commented out right now. these sources want utilize on.

@font-face { font-family:"headerfont"; src: url("http://livinggalapagos.org/static/fonts/qhyts__.ttf"); /*src: url("http://livinggalapagos.org/static/fonts/qhyts__.woff");*/ } @font-face{ font-family:"subheadfont"; src: url("http://livinggalapagos.org/static/fonts/museosans_500.ttf"); src: url("http://livinggalapagos.org/static/fonts/museosans_500.woff"); } @font-face{ font-family:"bodyfont"; src: url("http://livinggalapagos.org/static/fonts/museosans_300.ttf"); /*src: url("http://livinggalapagos.org/static/fonts/museosans_300.woff");*/ }

@font-face complicated property. here resources might help code "cross-browser" @font-face.

https://developer.mozilla.org/pt-br/docs/css/@font-face

http://www.fontsquirrel.com/tools/webfont-generator

css google-chrome firefox twitter-bootstrap fonts

Need help to grouping php arrays to make it better -



Need help to grouping php arrays to make it better -

first of all, grouping working sense dirty. need create looks clean , better. have next foreach

$data['new_array'] = array(); //i have utilize $data['new_array'] because need pass template. foreach ($get_topics $topic) { //is possible create these 4 lines shorter? $data['new_array'][$topic['tid']]['tid'] = $topic['tid']; $data['new_array'][$topic['tid']]['title'] = $topic['title']; $data['new_array'][$topic['tid']]['yes'] = $topic['yes']; $data['new_array'][$topic['tid']]['no'] = $topic['no']; //the belows subarray grouping, works need improve solutions //$new_array[$topic['tid']]['vid'][$topic['vid']][] = $topic['vid']; //$new_array[$topic['tid']]['vid'][$topic['vid']][] = $topic['yesno']; }

i wouldn't seek create shorter, here's code in looking version.

$data['new_array'] = array(); foreach ($get_topics $topic) { $data['new_array'][$topic['tid']] = array( 'tid' => $topic['tid'], 'title' => $topic['title'], 'yes' => $topic['yes'], 'no' => $topic['no'] ); }

not sure type $topic['tid'] should careful when using non-consecutive numbers array keys.

php arrays multidimensional-array

php - Matching pattern that is within brackets -



php - Matching pattern that is within brackets -

i trying create mobile detection class supposed strip user agent simple basic string this:

output: mozilla/5.0 (*linux x86_64*) applewebkit/* (khtml, gecko) chrome/* safari/*

from this:

input: (http_user_agent) mozilla/5.0 (x11; linux x86_64) applewebkit/537.17 (khtml, gecko) chrome/24.0.1312.69 safari/537.17

i using this: /[0-9.-]{4,}/i pattern strip numbers , get:

result of far above pattern: mozilla/5.0 (x11; linux x86_64) applewebkit/* (khtml, gecko) chrome/* safari/*

but problem how remove x11; want pattern remove everything after first opening bracket , till first empty space think right way. acceptable alternative able remove brackets @ pattern.

any suggestions?

ps: needing solve problem mobile detection , dependency on browscap. please no downvotes please!

ps2: main purpose of observe mobile clients , desktop. after tweak give info os, , etc..

replace x11; not khtml:

preg_replace('/\([^,)]*? ([^\)]+)/','(*\1*',$agent);

explained demo here: http://regex101.com/r/vl6gt1

php regex preg-match

ruby - Pretty print html output from Jekyll -



ruby - Pretty print html output from Jekyll -

is there way pretty print html output jekyll?

for example, below snippet of html jekyll generates. notice how <p> tags have no indentation , have unnecessary line breaks after them.

... <div id="content"> <p class="flush">post 1</p> <p class="flush">post 2</p> <p class="flush">post 3</p> </div> ...

i'm imagining alternative or plugin pretty print instead:

... <div id="content"> <p class="flush">post 1</p> <p class="flush">post 2</p> <p class="flush">post 3</p> </div> ...

i suggest take 1 of tidy-makers , write own :tidy task in end of jekyll-specific task chain. or, easier:

desc "tidy jekyll output" task :tidy `find _site -name "*.html" -exec tidy {} \;` end

please note, neither newly created task nor plugin may found on net not applied on github pages, since have restricted policies run jekyll.

ruby jekyll pretty-print

c# - Visual Studio autocomplete event handler with lambda format -



c# - Visual Studio autocomplete event handler with lambda format -

i'm on vs2012 , want utilize lambda format event handling, vs autocomplete tab key whenever type event subscrition via +=, e.g.:

vs autocompleted reference function inserts function:

txttitle.textchanged += txttitle_textchanged; void txttitle_textchanged(object sender, textchangedeventargs e) { .... }

is there way forcefulness autocomplete lambda format of:

txttitle.textchanged += (object sender, textchangedeventargs e) => { .... }

its huge pain have re-create , paste autocompleted non-lambda tighter lambda format.

you can create code snippet, have 1 creating lambda events.

here snippet if want seek (just save whatever.snippet) , import in vs (tools -> code snippet manager)

snippet:

<?xml version="1.0" encoding="utf-8"?> <codesnippets xmlns="http://schemas.microsoft.com/visualstudio/2005/codesnippet"> <codesnippet format="1.0.0"> <header> <snippettypes> <snippettype>expansion</snippettype> </snippettypes> <title>snippetfile1</title> <author>sa_ddam213</author> <description> </description> <helpurl> </helpurl> <shortcut>le</shortcut> </header> <snippet> <declarations> <literal editable="true"> <id>s</id> <tooltip>s</tooltip> <default>s</default> <function> </function> </literal> <literal editable="true"> <id>e</id> <tooltip>e</tooltip> <default>e</default> <function> </function> </literal> </declarations> <code language="csharp" kind="method body"><![cdata[($s$,$e$) => { };]]></code> </snippet> </codesnippet> </codesnippets>

then utilize type eventname += le tab

example

loaded += le tab

result

loaded += (s, e) => { };

c# visual-studio lambda event-handling intellisense

video capture - Android: Record Screen Activity -



video capture - Android: Record Screen Activity -

i planning record screen activity of user demo of 3 android applications created.

i think i've done research on google , play store , far, solutions saw either needed application not free, using google usb driver (which not compatible osx), or application required root.

i need application (either installed in android device or mac osx) can record screen activity of android device free, not require root, , not require intermediate hardware in order work.

thank you.

as of android 4.4, there screen recording feature accessible via adb.

http://developer.android.com/tools/help/adb.html#screenrecord

the screenrecord command shell utility recording display of devices running android 4.4 (api level 19) , higher. utility records screen activity mpeg-4 file, can download , utilize part of video presentation. utility useful developers want create promotional or training videos without using separate recording device.

android video-capture

java - Is there a way to open h2 console while some other application is also accessing the same db? -



java - Is there a way to open h2 console while some other application is also accessing the same db? -

i using h2 db in java application. using h2 console view contents of db, works when no other application accessing db. there way open h2 console while other application accessing same db?

to able connect multiple application can configure db take tcp connection. basically, can using jdbc:h2:tcp in db url.

read more here.

java h2

How to calculate moving average in Python 3? -



How to calculate moving average in Python 3? -

let's have list:

y = ['1', '2', '3', '4','5','6','7','8','9','10']

i want create function calculates moving n-day average. if n 5, want code calculate first 1-5, add together , find average, 3.0, go on 2-6, calculate average, 4.0, 3-7, 4-8, 5-9, 6-10.

i don't want calculate first n-1 days, starting nth day, it'll count previous days.

def moving_average(x:'list of prices', n): num in range(len(x)+1): print(x[num-n:num])

this seems print out want:

[] [] [] [] [] ['1', '2', '3', '4', '5'] ['2', '3', '4', '5', '6'] ['3', '4', '5', '6', '7'] ['4', '5', '6', '7', '8'] ['5', '6', '7', '8', '9'] ['6', '7', '8', '9', '10']

however, don't know how calculate numbers within lists. ideas?

there great sliding window generator in old version of python docs itertools examples:

from itertools import islice def window(seq, n=2): "returns sliding window (of width n) on info iterable" " s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... " = iter(seq) result = tuple(islice(it, n)) if len(result) == n: yield result elem in it: result = result[1:] + (elem,) yield result

using moving averages trivial:

from __future__ import partition # python 2 def moving_averages(values, size): selection in window(values, size): yield sum(selection) / size

running against input (mapping strings integers) gives:

>>> y= ['1', '2', '3', '4','5','6','7','8','9','10'] >>> avg in moving_averages(map(int, y), 5): ... print(avg) ... 3.0 4.0 5.0 6.0 7.0 8.0

to homecoming none first n - 1 iterations 'incomplete' sets, expand moving_averages function little:

def moving_averages(values, size): _ in range(size - 1): yield none selection in window(values, size): yield sum(selection) / size

python python-3.x

php - Handling an upload of collection of files with doctrine -



php - Handling an upload of collection of files with doctrine -

i've read part of symfony2 doc: http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html , made work me. if have collection of 'file' fields 'allow_add' attribute, don't know how many files user post via form? how handle them in same way?

you need tell form take multiple files this

{{ form_widget(form.file, { 'attr': { 'multiple': 'multiple' } }) }}

or this

{{ form_widget(yourform.file, { 'full_name': yourform.file.get('full_name') ~ '[]' }) }}

read here https://github.com/symfony/symfony/issues/1400

this way can select , upload multiple files @ once.

php symfony2

math - What does squaring a transformation mean? -



math - What does squaring a transformation mean? -

i trying understand solution read exercise defines logarithmic time procedure finding nth digit in fibonacci sequence. problem 1.19 in construction , interpretation of computer programs (sicp).

spoiler alert: solution problem discussed below.

fib(n) can calculated in linear time follows: start = 1 , b = 0. fib(n) equals value of b. initially, n = 0, fib(0) = 0. each time next transformation applied, n incremented 1 , fib(n) equals value of b.

<-- + b b <--

to in logarithmic time, problem description defines transformation t transformation

a' <-- bq + aq + ap b' <-- bp + aq

where p = 0 , q = 1, initially, transformation same 1 above.

then applying above transformation twice, exercise guides express new values a'' , b'' in terms of original values of , b.

a'' <-- b'q + a'q + a'p = (2pq + q^2)b + (2pq + q^2)a + (p^2 + q^2)a b' <-- b'p + a'q = (p^2 + q^2)b + (2pq + q^2)a

the exercise refers such application of applying transformation twice "squaring transformation". right in understanding?

the solution exercise applies technique of using value of squared transformations above produce solution runs in logarithmic time. how problem run in logarithmic time? seems me every time utilize result of applying squared transformation, need 1 transformation instead of two. how successively cutting number of steps in half every time?

the solution schemewiki.org posted below:

(define (fib n) (fib-iter 1 0 0 1 n)) (define (fib-iter b p q count) (cond ((= count 0) b) ((even? count) (fib-iter b (+ (square p) (square q)) (+ (* 2 p q) (square q)) (/ count 2))) (else (fib-iter (+ (* b q) (* q) (* p)) (+ (* b p) (* q)) p q (- count 1))))) (define (square x) (* x x))

the exercise refers such application of applying transformation twice "squaring transformation". right in understanding?

yes, squaring transformation means applying twice or (as case in solution exercise) finding transformation equivalent applying twice.

how problem run in logarithmic time? seems me every time utilize result of applying squared transformation, need 1 transformation instead of two. how successively cutting number of steps in half every time?

squaring given transformation enables cutting downwards number of steps because values of p , q grow much faster in squared transformation in original one. analogous way can compute exponents using successive squaring much faster repeated multiplication.

so how successively cutting number of steps in half every time?

this in code given. whenever count even, (/ count 2) passed count on next iteration. no matter value of n passed in on initial iteration, on alternating iterations (worst case).

you can read blog post on sicp exercise 1.19: computing fibonacci numbers if want see step-by-step derivation of squared transformation in exercise.

math sicp

sql - how to fix a double LEFT JOIN in a trac report -



sql - how to fix a double LEFT JOIN in a trac report -

we utilize customized version of trac people can give scores bugs based on 2 criteria, allow phone call them severity , importance.

for simplicity, allow database contains next tables:

table ticket

id | title | reporter 1 | sql injection | torvalds 2 | buffer overflow | linus 3 | localization | bofh

table votes

ticket_id | value | type | voter 1 | 4 | severity | linus 1 | 2 | severity | torvalds 1 | 3 | severity | bofh 1 | 4 | importance | linus 1 | 3 | importance | torvalds 2 | 4 | severity | linus 2 | 2 | severity | torvalds 2 | 1 | importance | linus 2 | 1 | importance | bofh 3 | 1 | importance | linus

so instance first row means user linus suggested 4 severity score of ticket #1.

now have next sql query in trac study utilize average scores:

select t.title, t.reporter, avg(vs.value), avg(vi.value), count(vs.value), count(vi.value) ticket t left bring together votes vs on vs.type = 'severity' , vs.ticket_id=t.id left bring together votes vi on vi.type = 'importance' , vi.ticket_id=t.id;

in hopes, should homecoming table next values:

title | reporter | severity avg | importance avg | number of sev. votes | number of imp. votes sql injection | torvalds | 3 | 3.5 | 3 | 2

thus telling me how many people voted ticket , votes are.

however, due way left join works, entries cartesian product of severity , importance votes, averages still valid, while both counts set 3x2=6 instead of right value.

is there simple way prepare query, returns want?

combine case statements aggregate functions:

select t.title, t.reporter, sum(case when v.type = 'importance' 1 else 0 end) count_imp, sum(case when v.type = 'severity' 1 else 0 end) count_sev, sum(case when v.type = 'importance' v.value else 0 end) / count_imp avg_imp, sum(case when v.type = 'severity' 1 else 0 end) / count_sev avg_sev ticket t left bring together votes v on v.ticket_id = t.id;

if trac sql doesn't allow re-use aliases count_imp , count_sev repeat statements in average calculation columns.

sql join trac

c# - REGEX character Set substitution -



c# - REGEX character Set substitution -

i need regex pattern allow me substitute characters 1 set corresponding characters in set. example: set [abcdefg], should replaced set [1234567]... in string of "bag", want replacement "217".

regex regx = new regex("([abcdefg])([1234567])"); string result = regx.replace("bag", "$1$2");

my result same source. should replace pattern be?

something work much improve regex:

var fromcharacters = "abcdefghijklmnopqrstuvwxyz"; var tocharacters = "12345678901234567890123456"; var mystring = "bag"; var sb = new stringbuilder(mystring.length); (int = 0; < mystring.length; ++i) { sb.append(tocharacters[fromcharacters.indexof(mystring[i])]); } sb.tostring().dump();

you similar if want, example, 'j' turn '10', need array of strings instead of beingness able utilize string array of chars.

i'm not sure how regex, know shouldn't.

c# regex

editor - How do I get line ending glyphs in Visual Studio 2012? -



editor - How do I get line ending glyphs in Visual Studio 2012? -

is there way line ending glyphs in visual studio 2012?

the next screen shot (from notepad++) show want (the cr lf part):

you might want check out extension: end of line rolf w. rasmussen. current binary version displays cr , lf identifiers @ end of line time, source version ties vs's "view whitespace" menu option.

it's visual studio 2013, it's open source , should straightforward recompile vs2012 compatible plugin

(you might need alter references - vssdk packages on nuget can useful here. you'd need vssdk.coreutility , vssdk.text. in fact, might worth pr regardless...)

visual-studio-2012 editor

c# - Regex to match string delimited with two types of delimiter -



c# - Regex to match string delimited with two types of delimiter -

i don't understand how regex expressions set together, here's question.

i have delimited string 1,3;5,1;6,4 , on. have here storing shopping cart products ids , volumes. 1,3 mean have product id "1" , quantity 3. products (with volumes) delimited ";".

what need set regex validate such string. positive numbers allowed limitation let's 1 10000.

does has solution that?

this regex pattern matches on semicolon-delimited number pairs, comma separates members of each pair, , each number between 1 , 10000:

^([1-9]\d{0,3}|10000),([1-9]\d{0,3}|10000)(;([1-9]\d{0,3}|10000),([1-9]\d{0,3}|10000))*$

there must @ to the lowest degree 1 pair. if there 1 pair, no semicolon follows it. semicolons should nowadays between neighboring pairs.

c# asp.net regex

iOS - How to check if UIDocument is open elsewhere on iCloud? -



iOS - How to check if UIDocument is open elsewhere on iCloud? -

is there way check if uidocument (that beingness synced icloud) has been opened elsewhere using icloud--other waiting conflict happen?

ios icloud uidocument

mod rewrite - mod_rewrite and .htaccess: Can my RewriteRule substitution be a subfolder in DocumentRoot's parent folder? -



mod rewrite - mod_rewrite and .htaccess: Can my RewriteRule substitution be a subfolder in DocumentRoot's parent folder? -

thanks help in advance.

here's , trying accomplish:

i have static files in /home/username/code/project/static/ my document root /home/username/public_html/ (which .htaccess file is).

i'm trying utilize next in .htaccess file (i have no access httpd.conf):

rewriterule ^(static/.*)$ /home/username/code/project/static/ [l]

but if understand mod_rewrite's documentation correctly (see below), "/home/username/code/project/static/" treated either file-system path relative document root or url path, not absolute file-system path intended.

i tried using "~/code/project/static/" , "../code/project/static/", got internal server error when trying visit page (yes, i'm bit of noob).

so question is: there way substitution of rewrite rule used in .htaccess context absolute file-system path rather path relative documentroot?

here's extract mod_rewrite documentation reference (can found in total here: http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewriterule):

for example, if specify substitution string of /www/file.html, treated url-path unless directory named www exists @ root or file-system (or, in case of using rewrites in .htaccess file, relative document root), in case treated file-system path.

any help much appreciated :)

thanks!

one way accomplish you're trying create symlink within public_html points static /home/username/code/project/static/. requires followsymlnks alternative detailed in options directive documentation may not allowed within total apache configuration, out of control.

a improve approach reverse link - create public_html/static maintain real files , create /home/username/code/project/static symlink public_html/static. avoids need specific .htaccess rules. since seems want create files under directory publicly-accessible anyways, it's improve security-wise since keeps publicly-accessible files under same directory construction , avoids potential security issues arise allowing symlinks go within web root other areas of file system.

.htaccess mod-rewrite

Adding some python flavor to C++ -



Adding some python flavor to C++ -

curly braces for(int i=0; i<10; i++) { line 1 line 2 } if (something) { line 3 line 4 } else if(something) { line 5 line 6 line 7 } else { line 8 line 9 line 10 }

i lazy typist , in recent years i've developed dislike curly braces in c++. not think unnecessary; can't live without them in long pieces of code. when branch of code contains 3 5 lines, increased indentation lone seems sufficient in making context clear, , curly braces don't seem much more taking precious screen space (especially when utilize vertical splits) , requiring me press more keys, which, owing not-so-convenient positions on keyboard, add together more strain fingers.

so, i'm thinking of doing preprocessor allow me utilize python-flavored c++, this:

for(int i=0; i<10; i++) line 1 line 2 if (something) line 3 line 4 else if(something) line 5 line 6 line 7 else line 8 line 9 line 10

so create curly braces optional in short branches of code, , doing code becomes cleaner. if have lot of functions consist of no more 8 lines, getting rid of curly braces create huge difference me. things seem more compact, clean; , beingness able see more useful code in 1 screen somehow makes me sense better. people kind of thing below thankful well:

void blahbalh(){ code... }

apparently people started doing decades ago sake of screen space. now, wouldn't improve if curly braces become optional? is, utilize them when code contained becomes relatively long.

symbols in general

to add together more python flavor c++. think braces surrounding conditions can done away with. looks really different c++, after got used python found quite elegant:

if something: line 3 line 4 elif something: line 5 line 6 line 7 else: line 8 line 9 line 10

generally, i've found python tends utilize far fewer symbols, thing:

symbols cause more finger strains plain text, because of relatively inconvenient positions on our keyboards , because of need press shift (qwerty , dvorak same here) since alphanumerical keys easier press, can type faster if avoid using symbols. , experience sense more natural flow when don't have press shift key.

so have more plain-text operators, using and in place of &&, , or in place of ||, etc. , can have python-styled loops, easier type

what guys think of python-flavored c++? suggestions?

i'm thinking of doing preprocessor simple source-to-source transformation. looks easiest way go without having define new language.

i lazy typist , in recent years i've developed dislike curly braces in c++ ... , curly braces don't seem much more taking precious screen space

write code this, , switch ide types braces you. can go on write code rest of understand.

for (int i=0; < 10; i++) { line 1 line 2 } if (something) { line 3 line 4 } else if (something) { line 5 line 6 line 7 } else { line 8 line 9 line 10 }

c++ python

ejb - How to migrate a JBoss Singleton Service from JBoss AS 6 to JBoss AS 7? -



ejb - How to migrate a JBoss Singleton Service from JBoss AS 6 to JBoss AS 7? -

we have services implemented on jboss 6 singleton services wish migrate jboss 7.

these services declared on jboss-service.xml file wich on ejb bundle in code below:

class="lang-xml prettyprint-override"><mbean name="some.cool.package:service=someservice-controller" code="org.jboss.ha.singleton.hasingletoncontroller"> <attribute name="hapartition"><inject bean="hapartition" /></attribute> <attribute name="targetname">scod:service=someservice</attribute> <attribute name="targetstartmethod">startwatcher</attribute> <attribute name="targetstopmethod">stopwatcher</attribute> </mbean>

well, when seek deploy on jboss 7, see huge classnotfoundexception telling class org.jboss.ha.singleton.hasingletoncontroller doesn't exists. , doesn't on jboss 7.

so here question: how can migrate newer version? class acts one?

there official example:

http://www.jboss.org/jdf/quickstarts/jboss-as-quickstart/cluster-ha-singleton/

https://github.com/jboss-jdf/jboss-as-quickstart/tree/jdf-2.1.0.final/cluster-ha-singleton

singleton ejb jboss7.x jboss6.x

glassfish - Spring Forum integration -



glassfish - Spring Forum integration -

my application uses spring security , spring mvc , hosted on glassfish 3.1.2.

i'm looking forum software (phpbb like) can integrate in app.

does know ?

i found jforum it's web app needs installed... maybe should install , re-create directory in application?

i tried jforum, , if seems project not continuing, fits application.

to working spring, had utilize sso (single sign-on) modifying jforum config.

in file systemglobals.properties, had alter property authentication.type = default authentication.type = sso.

jforum utilize remote user of request context.

see classes below more informations

net.jforum.jforum net.jforum.controllerutils net.jforum.sso.remoteusersso net.jforum.sso.ssoutils

spring glassfish forum

Android Foursquare API - How do I register a user for Foursquare in-app -



Android Foursquare API - How do I register a user for Foursquare in-app -

i developing android app require user login there foursquare account. plan through authenticate url.

i next illustration per oauth example: https://github.com/foursquare/android-oauth-example

however, there way can sign-up user foursquare in-app if not have account?

thanks

when utilize embedded webview pattern, embedded foursquare page has alternative user sign foursquare if don't have account.

android api authentication foursquare

c# - how to replace richtextbox.rtf if and only if the whole word match? -



c# - how to replace richtextbox.rtf if and only if the whole word match? -

my original replace code is.

rttextarea.rtf = rttextarea.rtf.replace(oldtext, newtext);

but problem replaces occurence of words instead of required word e.g origianl word :- hello name serak , in state of israel replace() -- whole word chages "are serak , in arereal"

is there anyway can include status or match whole word? working environment c#.

use regular expressions. in illustration \b represents word boundary.

var regexp = new system.text.regularexpressions.regex(@"\bis\b"); rttextarea.rtf = regexp.replace(rttextarea.rtf, "are");

c# .net

scala - Mapper versus Record/Squeryl -



scala - Mapper versus Record/Squeryl -

i start first project in lift framework , have decide persistence library choose. utilize relational backend both mapper , record may come in play.

in case of mapper - thing miss ability command queries beingness sent rdbms - when comes more complicated queries solved joins, aggregation etc in sql. take next illustration - let's have next 2 entities:

class baseproduct extends longkeyedmapper[baseproduct] idpk { // fields } object baseproduct extends baseproduct longkeyedmetamapper[baseproduct] class myproduct extends longkeyedmapper[myproduct] idpk { // fields object base of operations extends mappedlongforeignkey(this, baseproduct) } object myproduct extends myproduct longkeyedmetamapper[myproduct]

where myproduct 1 of specialization of baseproduct entity. there one-to-one relation between these entities. best possibility i've come query exact myproduct baseproduct query this:

myproduct.findall(precache(myproduct.base))

which issues 2 queries (moreover afraid not able command fields of myproduct entity want select.

enough bad mapper library. main concern record/squeryl api fact lacks proto-classes nowadays around mapper api. there close functionality of these classes record? possible access database specific features in squeryl (eg. geometrical queries in postgresql)?

are there other pros , cons either of these layers? or there other abstraction layer deserve attending if want have decent typesafe encapsulation of communication database , provide decent command on queries (i used issuing queries straight using pdo layer in php - don't want such direct querying interface possibility of having command on queries great) integration lift framework advantage.

thank you!

we've been using squeryl lift quite while , have been happy it. based on case above, in current release version of squeryl (0.9.5), like:

class baseproduct(id:long, more fields) extends keyedentity[long] { } class myproduct(id:long, more fields) extends keyedentity[long] { }

then, have schema defines relationships (i assuming joined on id field):

val baseproducts = table[baseproduct]("base_products") val myproducts = table[myproduct]("my_products") val myproductstobaseproducts = onetomanyrelation(myproducts, baseproducts).via((mp, bp) => mp.id === bp.id)

to query both records, like:

from(myproducts, baseproducts) ( (mp, bp) => where(mp.id === bp.id , mp.id === lookupval) select(bp, mp) )

the query above homecoming tuple of (baseproduct, marketproduct) single sql select.

you can utilize relationship retrieve related item, such adding method myproduct:

def baseproduct = myproductstobaseproducts.left(this)

however, illustration mapper, issue sec query. making database specific queries, there & operator allow evaluate expressions @ server. if function not available in squeryl can create custom functions.

overall, have found squeryl flexible , great hybrid between orm , straight sql. has performed remarkably , have not found many places squeryl prohibited me getting @ database functionality needed. gets easier next version, 0.9.6 have lot more flexibility custom types.

scala lift squeryl

sql - Proper populating of dropdown list in asp.net dynamically -



sql - Proper populating of dropdown list in asp.net dynamically -

i newbie in asp.net, want inquire more proper in terms of populating dropdown list in asp.net? using datasource or using sqldatareader , loop.

i using sqldatareader , loop, here sample code:

for = 1 20 etc.commandtext = "select classification schemaitemdetails.assetclassification ac_id = " & & "" dim dr sqldatareader = etc.executereader while (dr.read()) ddoneclassification.items.add(dr.getstring(0)) end while dr.close() next

is there difference in using sqldatasource , one?? never utilize sqldatasource populating dropdown.

from point of view easiest , best solution set dropdownlist's datasource property. in case, required job done behind scene , neednd't think of synchronization info between db server , web server.

also, if you, modify sql single request sent db server, i.e.

"select classification schemaitemdetails.assetclassification ac_id between 1 , 20"

asp.net sql sqldatasource sqldatareader

objective c - Clearing CoreData and all that inside -



objective c - Clearing CoreData and all that inside -

i'm pretty new coredata , app uses it. , i'm working on feature clears entire core info when log out in app.

i have 2 sqllite files (for reason thought handy)

how can clear both files of info , reset them dataless state?

i've tried lot of ways, next guides, on so.

how clear/reset coredata in one-to-many realationship

how remove objects core data

they seem fail me. i'm wondering do wrong? , perhaps can explain me how reset 2 coredata files proper way.

edit:

//should clear whole coredata database. used logout mechanism -(void)resetcoredata { (nspersistentstore *store in self.persistentstorecoordinator.persistentstores) { // nspersistentstore *store = self.persistentstorecoordinator.persistentstores[0]; nserror *error; nsurl *storeurl = store.url; dlog(@"storeurl: %@", storeurl); nspersistentstorecoordinator *storecoordinator = self.persistentstorecoordinator; [storecoordinator removepersistentstore:store error:&error]; [[nsfilemanager defaultmanager] removeitematpath:storeurl.path error:&error]; dlog(@"there erreurs: %@", error); // [self adddefaultdata]; } _persistentstorecoordinator = nil; _managedobjectcontext = nil; _managedobjectmodel = nil; }

this doesn't seem clear coredata me.

edit2:

- (nsmanagedobjectcontext *)managedobjectcontext {     if (_managedobjectcontext != nil) {         homecoming _managedobjectcontext;     }          nspersistentstorecoordinator *coordinator = [self persistentstorecoordinator];     if (coordinator != nil) {         _managedobjectcontext = [[nsmanagedobjectcontext alloc] init];         [_managedobjectcontext setpersistentstorecoordinator:coordinator];     }     homecoming _managedobjectcontext; } - (nsmanagedobjectmodel *)managedobjectmodel { if (__managedobjectmodel != nil) { homecoming __managedobjectmodel; } nsurl *modelurl = [[nsbundle mainbundle] urlforresource:@"myname" withextension:@"momd"]; __managedobjectmodel = [[nsmanagedobjectmodel alloc] initwithcontentsofurl:modelurl]; homecoming __managedobjectmodel; } - (nspersistentstorecoordinator *)persistentstorecoordinator { if (__persistentstorecoordinator != nil) { homecoming __persistentstorecoordinator; } nsstring *storepath = [[self applicationdocumentsdirectory] stringbyappendingpathcomponent:@"myname.sqlite"]; nsfilemanager *filemanager = [nsfilemanager defaultmanager]; // if expected store doesn't exist, re-create default store. if (![filemanager fileexistsatpath:storepath]) { nsstring *defaultstorepath = [[nsbundle mainbundle] pathforresource:@"myname" oftype:@"momd"]; if (defaultstorepath) { [filemanager copyitematpath:defaultstorepath topath:storepath error:null]; } } __persistentstorecoordinator = [[nspersistentstorecoordinator alloc] initwithmanagedobjectmodel: [self managedobjectmodel]]; //check see version of current model we're in. if it's >= 2.0, //then , check if migration has been performed... nsset *versionidentifiers = [[self managedobjectmodel] versionidentifiers]; dlog(@"which current version our .xcdatamodeld file set to? %@", versionidentifiers); if ([versionidentifiers containsobject:@"2.0"]) { bool hasmigrated = yes; if (hasmigrated==yes) { storepath = nil; storepath = [[self applicationdocumentsdirectory] stringbyappendingpathcomponent:@"myname2.sqlite"]; } } nsurl *storeurl = [nsurl fileurlwithpath:storepath]; nserror *error; nsdictionary *pscoptions = [nsdictionary dictionarywithobjectsandkeys:[nsnumber numberwithbool:yes], nsmigratepersistentstoresautomaticallyoption, [nsnumber numberwithbool:no], nsinfermappingmodelautomaticallyoption, nil]; if (![__persistentstorecoordinator addpersistentstorewithtype:nssqlitestoretype configuration:nil url:storeurl options:pscoptions error:&error]) { dlog(@"unresolved error %@, %@", error, [error userinfo]); abort(); } homecoming __persistentstorecoordinator; }

edit 3: i'm still looking way reset coredata if deleted entire app , started again. usual ways of doing not working case. , there 2 sqllite files. there hints of migration took place @ point in application i'm not sure when , how. error logs show nil useful.

i'm not looking efficient way. way.

help me out , bounty yours.

edit 4: final result: seemed legacy code had sec managedobjectcontext instantiated. moment retrieved , did flush-function it. both sqlite-files disappeared needed.

thanks set effort in problem.

try next method flush database, works perfect me.

-(void) flushdatabase{ [__managedobjectcontext lock]; nsarray *stores = [__persistentstorecoordinator persistentstores]; for(nspersistentstore *store in stores) { [__persistentstorecoordinator removepersistentstore:store error:nil]; [[nsfilemanager defaultmanager] removeitematpath:store.url.path error:nil]; } [__managedobjectcontext unlock]; __managedobjectmodel = nil; __managedobjectcontext = nil; __persistentstorecoordinator = nil; }

objective-c core-data reset

C# printing multiple pages -



C# printing multiple pages -

this code, works fine when print 1 page, when seek print doesn't fit onto 1 page doesn't start new page, accepts offset alter , starts writing on first page.

does know do?

private void printdocument_printpage(object sender, printpageeventargs e) { graphics graphic = e.graphics; font font = new font("courier new", 12); float fontheight = font.getheight(); int startx = 10; int starty = 10; int offset = 0; float pagewidth = e.pagesettings.printablearea.width; float pageheight = e.pagesettings.printablearea.height; foreach (string line in textrichtextbox.lines) { graphic.drawstring(line, font, new solidbrush(color.black), startx, starty + offset); offset += (int)fontheight;// + 5 if (offset >= pageheight - (int)fontheight) { e.hasmorepages = true; offset = 0; } } e.hasmorepages = false; }

you using api wrong, the doc says:

in printpage event handler, utilize graphics property of printpageeventargs class , document contents calculate line length , lines per page. after each page drawn, check see if lastly page, , set hasmorepages property of printpageeventargs accordingly. printpage event raised until hasmorepages false. also, create sure printpage event associated event-handling method.

you can't set hasmorepages in loop, on exit of callback. callback called until set hasmorepages false

c# printing

servicestack - Razor exceptions -



servicestack - Razor exceptions -

i have undoubtedly set wrong exceptions thrown razor templates though there no problem templates. these fixed doing build.

if have error in template popup asking me debug in vs, of course of study not allow me debug template.

errors in log not helpful (see below).

is possible both avoid spurious errors , improve info when there problem?

servicestack.razor.templating.templatecompilationexception: unable compile template. check errors list details. @ servicestack.razor.templating.templateservice.createtemplate(string template, type modeltype) @ servicestack.razor.templating.templateservice.compile(viewpageref viewpageref, string template, type modeltype, string name) @ servicestack.razor.templating.templateservice.compile(viewpageref viewpageref, string template, string name) @ servicestack.razor.viewpageref.compile(boolean force)

i having similar problems. found "easiest" way find out error was, download of service stack, build debug version of razor libary , link project. set break point in servicestack.razor.templating.templateservice.createtemplate method , able see total exception details. there learnt had included import in razor page not referenced in project.

since solved it's been reliable.

razor servicestack

.net - a procedure imported by c# -



.net - a procedure imported by c# -

i getting exception,

system.io.fileloadexception: procedure imported 'geometryutils.dll' not loaded

while trying phone call activator.createinstancefrom(geomutilsassemblypath, "geometryutils.ismregionfactory");

i can see geometryutils.dll gets loaded using process explorer along dependencies. dependency walker , reflector not study issue well.

fyi, geometryutils built using .net 4.0 , calling process built using .net 2.0. have specified,

<startup uselegacyv2runtimeactivationpolicy="true"> <supportedruntime version="v4.0" sku=".netframework,version=v4.0" /> </startup>

in executeable config file.

any ideas, may going on?

a 2.0 process can't back upwards 4.0 class library.

c# .net fileloadexception

php - CRUD Resource incl Sub-Resource in MANY_MANY relation with RESTfull JSON-API -



php - CRUD Resource incl Sub-Resource in MANY_MANY relation with RESTfull JSON-API -

i utilize yii framework web-application restfull json-api , crud operations. api utilize restfullyii extension. there alternative?

there 3 tables (user, event , event_participant) many_many relation. relation in event model:

public function relations() { homecoming array( 'participants' => array( self::many_many, 'user', 'event_participant(studiobooking, user)' ) ); }

i want utilize crud operations crud event user sub-resource in 1 request. works resource sub-resource. want save/update/delete resource incl. sub-resource, illustration post request data:

{ "event": "eventname", "start": "2013-02-17 14:30:00", "end": "2013-02-17 16:00:00", "participants": [ { "id": "2" },{ "id": "3" }] }

this should create new event in event table , new id event participant ids in "event_participant" table. possible yii framework?

you'll have come own code this, relatively straight forward. here's example. note: "coded" in stackoverflow editor, not production ready, tested code :)

//in event model public function associatewithparticipant(int $participantid) { //you may check if participant exists before inserting it, detail $sql="insert tbl_event_participant_pivot (event_id, participant_id) values(:event_id,:participant_id)"; $command=yii::app()->db->createcommand($sql); $command->bindparam(":event_id",$this->id,pdo::param_int); $command->bindparam(":participant_id",$participantid,pdo::param_int); $command->execute(); } //in event controller (or apicontroller or whatsoever using) public function actioncreateevent() { //if reason post not giving json seek file_get_contents('php://input') if(isset($_post['event'])) { $data = cjson::decode($_post['event']); //first, create sure transactional or error while adding participants leave //your db in inconsistent state $tx = yii::app()->db->begintransaction(); seek { //create event $event = new event(); $event->attributes = $data; //save , if works check if there in participants "array" if($event->save()) { if(isset($data['participants'])) { //check if right json array if(is_array($data['participants']) { foreach($data['participants'] $participantentry) { //add new row pivot table $event->associatewithparticipant($participantentry['id']); } } else { throw new chttpexception(400,'participants has json array'); } } } //commit transaction finished $tx->commit(); } grab (exception $e) { //roll tx if error occurred throw new cexception("i've seen horrors of bad coding") $tx->rollback(); } } }

php crud yii

ruby - Unable to use bourbon functions with sass (sass -r bourbon.rb fails) -



ruby - Unable to use bourbon functions with sass (sass -r bourbon.rb fails) -

i having problem compiling sass files functions such linear-gradient or box-shadow. getting same issue here https://github.com/thoughtbot/bourbon/issues/68 resulting css jumble of false's.

i not working on rails project, thought might have include bourbon.rb file library when doing sass --watch, not working me:

sass --watch .:.. --r ./bourbon/lib/bourbon.rb loaderror: cannot load such file -- bourbon/generator utilize --trace backtrace.

no such file load -- rubygems (loaderror) here says might indicate have several versions of ruby installed, , which -a ruby showed both rbenv 1.9.3-p327 /usr/bin/ruby (i stil unclear difference is). anyway, moved .rbenv backup , supposedly have 1 version of ruby. tried specifying rubygems path

echo $rubylib /usr/lib/ruby/1.9.1/rubygems

but still getting same error when trying include bourbon.rb file sass --watch.

elise, version of bourbon using? $bourbon -v

since bourbon 3.0, no longer required pass --r ./bourbon/lib/bourbon.rb flag sass --watch command.

please read new installation instructions here: http://bourbon.io/

ruby sass rbenv bourbon

Provide an HTML page with JS with node.js and express -



Provide an HTML page with JS with node.js and express -

i trying serve html page linked js script using node.js , express. server provide page:

var express = require("express"); var app2 = express(); app2.get('/', function(req, res) { res.sendfile('./index.html'); }); app2.listen(process.env.vcap_app_port || 3000);

and page:

<!doctype html> <html> <head> <title>demo</title> </head> <body> <h1>demo</h1> <script src="/js/socket.io.js"></script> <script src="/js/codice.js"></script> </body>

as can see have 2 js scripts in js folder not loaded when launch page. can do?

what place public resources (javascript files, css files, images etc) in directory (express names public default) , utilize express.static middleware in app.configure call:

app.configure(function () { // various other middleware functions... app.use(express.static(path.join(__dirname, "public"))); });

this runs static file server homecoming file within public directory. currently, browser making request js files, express server doesn't know them. time out.

if generate initial state of app global express executable (available if installed express via npm globally), set of you.

node.js express

operators - Precedence of cast in c# -



operators - Precedence of cast in c# -

this question has reply here:

cast operation precedence in c# 2 answers

what precedence of cast in c#? illustration in next code, z less or equal two?

double x = 4.5; double y = 2.1; double z = (int) x / y;

the cast beats binary operators binding. hence (int)x / y means ((int)x)/y.

on other hand, should prefer readable code clever code, since don't know should write next instead:

((int)x) / y

note brackets free, , create code more readable.

c# operators

ruby on rails - Forgot password Devise gem API -



ruby on rails - Forgot password Devise gem API -

i have been using devise gem in application. able configure devise sessions_controller respond both request web , mobile api call.

but trying see how can utilize forgot password alternative of devise gem mobile api call. can able utilize sign in api below

curl -x post 'http://localhost:3002/users/sign_in.json' -d 'user[email]=balan@test.com&user[password]=123456'

can same forgot password?

got answer.

1) create custom action recieves email input

2) add together below code

@user = user.find_by_email("email@email.com") if @user.present? @user.send_reset_password_instructions render :text => "updated" else render :text => "no such email" end

ruby-on-rails devise

One or two keyspaces in Cassandra for a different kind of data of the single application -



One or two keyspaces in Cassandra for a different kind of data of the single application -

in project utilize cassandra analytics , mysql store data. see cassandra fit info well.

my question is: should create new keyspace info or should utilize keyspace exists used analytical data? should take business relationship when making such decision?

my stack python (django) + pycassa, cassandra 1.2.

keyspace high level grouping of similar column families. there no hard , fast rules, , important implications of either decision relate specific client library's api. personally, create new keyspace when want separation of concerns data. it's analogous creating different database in relational db.

cassandra

java - ArrayAdapter for generic objects -



java - ArrayAdapter for generic objects -

is there way arrayadapter recieve kind of object? or maybe create multiple constructors?

java android generics android-listview android-arrayadapter

android - SherlockActionBar: Export signed apk, then Eclipse crashes :( -



android - SherlockActionBar: Export signed apk, then Eclipse crashes :( -

today finished testing new android app..

i utilize sherlockactionbar.

import /library

my os ubuntu 12.10 64bit..

i can build .apk eclipse , app runs on android 2.3.3(mobile) , android 4.0(tablet).

but when seek to: android tools -> export signed application package, eclipse crashes :(

i error:(before export/crash)

invalid zip archive: /home/voidcode/ubuntu one/workspace/jakewharton-actionbarsherlock-e5c2d1c/library/bin/library.jar

this error log find in eclipse-folder after crash: http://paste.ubuntu.com/1677938/

my androidmanifest.xml this:

<uses-sdk android:minsdkversion="4" android:targetsdkversion="15" />

and project.properties this:

# file automatically generated android tools. # not modify file -- changes erased! # # file must checked in version command systems. # # customize properties used ant build scheme edit # "ant.properties", , override values adapt script # project structure. # # enable proguard shrink , obfuscate code, uncomment (available properties: sdk.dir, user.home): #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt # project target. target=android-14 android.library.reference.1=../jakewharton-actionbarsherlock-e5c2d1c/library

you may want check couple of things in project.

your project.properties file targets android api14, manifest targets api15. these should same sherlock actionbar works on api7+. may issue actually. seek changing android:minsdkversion="4" android:minsdkversion="7" obviously not allow prior android 2.1, you'll still target 100% of ecosystem.

if doesn't work, i've had lots of problem , exporting packages solutions random.

my general solution disable auto build, clean , manually build library projects.

for example

under project menu uncheck build automatically then project > clean... on window, uncheck start build immediately choose clean projects , click ok select sherlock actionbar project do project > build project (not build all). this build 1 library do library projects have included. click now, export project signed apk.

that works me , stops lot of unexplained export issues.

android eclipse ubuntu actionbarsherlock

asp.net mvc 3 - Current user identity in ObjectContext.SavingChanges -



asp.net mvc 3 - Current user identity in ObjectContext.SavingChanges -

i using objectcontext.savingchanges event update createddate/updateddate columns based on object state this

partial void oncontextcreated() { //extension of command timeout avoid processing problems. commandtimeout = 600; //time in seconds this.savingchanges += new eventhandler(entities_savingchanges); } protected void entities_savingchanges(object sender, eventargs e) { var addedobjects = this.objectstatemanager.getobjectstateentries(system.data.entitystate.added); foreach (var addedobject in addedobjects) { var propertyinfo = addedobject.entity.gettype().getproperty("createddate"); if (propertyinfo != null) { propertyinfo.setvalue(addedobject.entity, datetime.utcnow, null); } } var modifiedobjects = this.objectstatemanager.getobjectstateentries(system.data.entitystate.modified); foreach (var modifiedobject in modifiedobjects) { var propertyinfo = modifiedobject.entity.gettype().getproperty("updateddate"); if (propertyinfo != null) { propertyinfo.setvalue(modifiedobject.entity, datetime.utcnow, null); } } }

i have 2 more columns createduser , updateduser.

is there way update using current user name context?

ofcource, system.httpcontext.current null here separate class library project, access through wcf service.

if code resides in wcf service consume asp.net mvc application send current username parameter method invoking.

asp.net-mvc-3 entity-framework httpcontext

android - ViewFlipper vs AdapterViewFlipper -



android - ViewFlipper vs AdapterViewFlipper -

could explain practical differences between viewflipper , adapterviewflipper. including when utilize 1 , not other.

i have been using viewflipper months in custom cursor adapter , origin think used wrong approach albeit works.

with viewflipper, typically declare children front, , there no recycling concept.

with adapterviewflipper, utilize adapter, listview, spinner, etc., children determined on fly , views representing children can recycled.

for small, static content, viewflipper simpler. also, adapterviewflipper added in api level 11 (iirc) , hence not work on older versions on android.

android

xaml - Windows Phone Context Menu -



xaml - Windows Phone Context Menu -

i want add together context menu listbox. when hold listbox item, nil happens. thanks..

this code definition of listbox. added context menu listbox.

<listbox grid.row="1" name="chlist" itemssource="{binding ch.texts}" selectionchanged="textchanged" style="{staticresource listoftext}"> <listbox.itemtemplate> <datatemplate> <toolkit:contextmenuservice.contextmenu> <toolkit:contextmenu name="contextmenu"> <toolkit:menuitem name="edit" header="edit" click="edit_click"/> <toolkit:menuitem name="delete" header="delete" click="delete_click"/> </toolkit:contextmenu> </toolkit:contextmenuservice.contextmenu> </datatemplate> </listbox.itemtemplate> </listbox>

in styles.xaml

<style x:key="listoftext" targettype="listboxitem"> <setter property="template"> <setter.value> <controltemplate targettype="listboxitem"> <border x:name="rootelement" padding="{staticresource phoneborderthickness}"> <grid> <grid.columndefinitions> <columndefinition width="10" /> <columndefinition width="*" /> </grid.columndefinitions> <border grid.column="0" background="{staticresource phoneaccentbrush}" opacity="{binding isread,converter={staticresource opacityconverter}}" /> <grid minheight="60" grid.column="1"> <grid.rowdefinitions> <rowdefinition height="auto" /> <rowdefinition height="auto" /> </grid.rowdefinitions> <textblock grid.row="0" text="{binding title}" textwrapping="wrap" style="{staticresource phonetexttitle3style}" /> <grid grid.row="1"> <grid.columndefinitions> <columndefinition width="auto" /> <columndefinition width="*" /> </grid.columndefinitions> <textblock grid.column="0" text="{binding pbdate, converter={staticresource dateconverter}}" verticalalignment="center" textwrapping="wrap" style="{staticresource phonetextsmallstyle}" /> <image grid.column="1" height="{staticresource phonefontsizenormal}" horizontalalignment="left" visibility="{binding isstared,converter={staticresource visibilityconverter}}" source="/toolkit.content/favs.png" /> </grid> </grid> </grid> </border> </controltemplate> </setter.value> </setter> </style>

styles.xaml in mysolution... can't solve problem..

thanks...

you setting item datatemplate contextmenuservice.contextmenu , there no actual content. need have content displayed there. also, have items in list?

move contextmenuservice.contextmenu in 1 main template - splitting (for unknown reason). remove datatemplate declaration in listbox command , utilize pre-defined style.

windows-phone-7 xaml contextmenu

.net - Multi threading Concept in Oracle pl/sql -



.net - Multi threading Concept in Oracle pl/sql -

i created procedure, takes input in form of array, beingness passed .net web application.

in procedure: open cursor containing info in table, fetching info cursor row row , apply validation rules on it.

for each row need multiple hits db (almost containing nested queries); if info validation fails update remarks field in same table (by using update query immediately), , if validation successful inserting/updating info in other table.

i tried on 0.25 1000000 records, , noticed takes more 1 hr process it.

i need improve performance of stored procedure. please allow me know how accomplish this.

i have thought this.

making multiple sets of record (10 k in each set) , process each set way utilize multi threading.

is possible? if yes how?

very likely, procedure can made faster utilize of pl/sql batch processing capabilities. run code in parallel, @ dbms_job , dbms_scheduler packages. also, check if parts of code can speed parallel query and/or parallel dml. line line slowest thing, if used explicit cursor.

.net multithreading oracle stored-procedures plsql

bash - Shell script to add extension on file -



bash - Shell script to add extension on file -

need help on please scrip receive parameters directories, browse thoses directories add together right extension on each file found, or if directory add together .aaa extension files doesnt have extension, , have utilize comand file determine file type (files not have extyension) thanks

#!/bin/sh dir in "$@"; file in "$dir"/*; if [[ -d $file ]] ext=dir else file -i * | egrep 'avi|txt|jpeg|pst' fi if [file eq avi] ext=avi else if [file eq txt] ext=txt else if [file eq jpeg] ext=jpeg fi done done

you mean this:

for dir in "$@" file in "$dir"/* ftype=$(file -i "$file") unset ext case $ftype in *directory*) ext=aaa ;; *avi*) ext=avi ;; *text*) ext=txt ;; *jpeg*) ext=jpeg ;; *ps*) ext=ps ;; *) echo "file '$ftype' not recognised file $file" >&2 go on ;; esac echo "renaming '$file' '$file.$ext'" mv "$file" "$file.$ext" done done

note there no need egrep, , file reports on directories well, no need -d test.

edit: egrep in original posted question. added unset

bash

java - cannot resolve error. Missing a jar file? -



java - cannot resolve error. Missing a jar file? -

import ca.uhn.hl7v2.defaulthapicontext; import ca.uhn.hl7v2.hapicontext;

i'm getting cannot resolve error above 2 lines. don't know why, when have jar files in project. i'm starting out using hapi api might missing pretty easy spot.

what version of hapi (intend to) use? hapicontext , implementation available starting of hapi 2.1-beta1. have older hapi version in classpath.

java hl7 hapi

perl - catalyst consistent url format with trailing slash -



perl - catalyst consistent url format with trailing slash -

i'm developing catalyst application , having problem way catalyst interprets urls.

let's in our catalyst application have controller account. if case, catalyst interpret

http://mydomain.com/account , http://mydomain.com/account/

as same url index action.

however, seo , linking purposes (and consistent overall) forcefulness catalyst recognize 1 format , stick it.

i've found 1 module seems built this: catalyst::plugin::sanitizeurl, it's documentation says should set

use catalyst 'sanitizeurl';

in myapp.pm , handle you.

however, whenever utilize error:

bad request

on every page load. know of simple way have catalyst utilize 1 format?

the simple way forcefulness catalyst utilize 1 format without trailing slash add together method myapp.pm:

sub begin :private { ($self, $c) = @_; @path = split "/", $c->req->path, -1; $c->detach('default') if @path , (pop @path eq ''); }

it redirect on 'default' method a.k.a page 404 if uri ends slash on request.

perl url catalyst trailing-slash

perl script for showing ssl certs -



perl script for showing ssl certs -

i view ssl certificate of 3rd party hosts using openssl, openssl s_client doesn't back upwards proxies (which have in environment).

i'm hoping can utilize perl doing equivalent of this:

openssl s_client -showcerts -connect www.domain.com:443

you should search around dump_peer_certificate() method net::ssleay module.

see http://www.perlmonks.org/?node_id=70620 , http://metacpan.org/pod/net::ssleay

perl ssl openssl

How do I include another PHP file that is stored as a variable? -



How do I include another PHP file that is stored as a variable? -

i'm trying load page using include statement maintain getting error:

warning: include(accountview.php?id=) [function.include]: failed open stream: no such file or directory in /home/public_html/insertaccount.php on line 62 $return = "accountview.php?id=".$id; include $return;

i'm not sure i'm missing create perform correctly. set of eyes great.

there's no file name:

accountview.php?id=

the ?id= part killing you. you're trying include url there, not filename.

php include

android - Fragment getView() always returning null for Fragments created by a FragmentStatePagerAdapter -



android - Fragment getView() always returning null for Fragments created by a FragmentStatePagerAdapter -

i have been reading lot fragments. have found other people having problems retrieving fragments view because null returned no reply solved problem. i'm trying create image gallery. have fragment holds image view. show fragments utilize android.support.v4.view.viewpager. , feed viewpager utilize android.support.v4.app.fragmentstatepageradapter.

the problem when build , images shown want save current shown image disk. need current fragment imageview can't because fragment.getview() null, activity associated fragment null , can't figure out why it. here code see if help here:

this fragment:

public class imageviewurlfragment extends fragment { string _url; @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { // lastly 2 arguments ensure layoutparams inflated // properly. view rootview = new imageviewurl(getactivity(), _url); homecoming rootview; } public void setimageurl(string imgurl) { _url=imgurl; } }

and adapter:

public class imageviewurlcustomadapter extends fragmentstatepageradapter { list<string> _urls=new arraylist<string>(); public imageviewurlcustomadapter(fragmentmanager fm) { super(fm); } @override public fragment getitem(int i) { imageviewurlfragment fragment = new imageviewurlfragment(); fragment.setimageurl(_urls.get(i)); homecoming fragment; } public string getitemurl(int i) { homecoming _urls.get(i); } @override public int getcount() { homecoming _urls.size(); } @override public charsequence getpagetitle(int position) { homecoming "object " + (position + 1); } public void addimageurl(string url) { _urls.add(url); } }

and main activity, notice comment get:

public class mainactivity extends fragmentactivity { imageviewurlcustomadapter _iva=null; viewpager _vp=null; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); _iva = new imageviewurlcustomadapter( getsupportfragmentmanager()); _iva.addimageurl("http://upload.wikimedia.org/wikipedia/commons/b/b4/saturn_(planet)_large.jpg"); _iva.addimageurl("http://planetthreesixty.com/sites/default/files/planet.jpg"); _vp = (viewpager) findviewbyid(r.id.viewpager); _vp.setadapter(_iva); } @override public boolean oncreateoptionsmenu(menu menu) { // inflate menu; adds items action bar if present. getmenuinflater().inflate(r.menu.activity_main, menu); homecoming true; } @override public boolean onoptionsitemselected(menuitem item) { if(item.getitemid()==r.id.savetosd) { int index= _vp.getcurrentitem(); fragment fragment=_iva.getitem(index); //this need fragment view, returns null view view= fragment.getview(); imageview iv=(imageview)view.findviewwithtag("imageview"); bitmap bmp=iv.getdrawingcache(); } homecoming super.onoptionsitemselected(item); } }

sorry long sources, have cleaned could, wanted nowadays playing parts. guess hapenning?

thanks in advance.

so need current fragment imageview can't because fragment.getview() null, activity associated fragment null , can't figure out why it.

that happening because you're expecting _iva.getitem(index); homecoming fragment viewpager uses page corresponding specified index. not happen viewpager has called getitem method fragments needs , after phone call getitem method new imageviewurlfragment instance. new instance isn't tied activity(getactivity() returns null) , view wasn't created.

as utilize fragmentstatepageradapter seek code below visible fragment:

if (item.getitemid()==r.id.savetosd) { int index = _vp.getcurrentitem(); fragment fragment = _vp.getadapter().instantiateitem(_vp, index); //...

android android-layout android-fragments fragmentstatepageradapter

php - Base64 Over HTTP POST losing data (Objective-C) -



php - Base64 Over HTTP POST losing data (Objective-C) -

i have http post request , base64 encoding library, encode image b64 send on http via post method.

i output base64 xcodes console, re-create , paste , works perfectly. although base64 store within database (mongodb, plain text file etc) comes out corrupt on other end.

working version (copied , pasted xcode): http://dontpanicrabbit.com/api/working.php broken version (from mongodb database): http://dontpanicrabbit.com/api/grabimage.php

if view source you'll notice same there added whitespace broken version.

the objective-c code using is:

myimage.image = [info objectforkey:uiimagepickercontrolleroriginalimage]; nsdata *imagedata = uiimagejpegrepresentation(myimage.image, 0); [base64 initialize]; nsstring *encoded = [base64 encode:imagedata]; nsstring *urlpost = encoded; //nslog(@"%@",encoded); nsstring *varyingstring1 = @"picture="; nsstring *varyingstring2 = urlpost; nsstring *post = [nsstring stringwithformat: @"%@%@", varyingstring1, varyingstring2]; nslog(@"%@", post); //nsstring *post = @"image=%@",urlpost; nsdata *postdata = [post datausingencoding:nsasciistringencoding allowlossyconversion:yes]; nsstring *postlength = [nsstring stringwithformat:@"%d", [postdata length]]; nsmutableurlrequest *request = [[nsmutableurlrequest alloc] init]; [request seturl:[nsurl urlwithstring:@"url/api/insertimage.php"]]; [request sethttpmethod:@"post"]; [request sethttpbody:postdata]; nsdata *returndata = [nsurlconnection sendsynchronousrequest: request returningresponse: nil error: nil]; nsstring *strresult = [[nsstring alloc] initwithdata:returndata encoding:nsutf8stringencoding];

php -> mongodb storage

<?php seek { // open connection mongodb server $conn = new mongo('localhost'); // access database $db = $conn->dablia; // access collection $collection = $db->images; // insert new document $item = array( 'picture' => $_post['picture'] ); $collection->insert($item); echo 'inserted document id: ' . $item['_id']; // disconnect server $conn->close(); } grab (mongoconnectionexception $e) { die('error connecting mongodb server'); } grab (mongoexception $e) { die('error: ' . $e->getmessage()); } ?>

output code:

<?php seek { // open connection mongodb server $conn = new mongo('localhost'); // access database $db = $conn->dablia; // access collection $collection = $db->images; // execute query // retrieve documents $cursor = $collection->find(); // iterate through result set // print each document foreach ($cursor $obj) { echo '<img src="data:image/jpeg;base64,'.trim($obj['picture']).'">'; } // disconnect server $conn->close(); } grab (mongoconnectionexception $e) { die('error connecting mongodb server'); } grab (mongoexception $e) { die('error: ' . $e->getmessage()); } ?>

i have no thought why seem corrupting on post?

the problem suggested in first comment. is, base64 encoded info can contain '+' characters. in x-www-form-urlencoded info receiver knows '+' encoding of space character. since aren't url encoding base64 value, instances of '+' cause info corrupted when received.

the '+' characters in initial info turning ' ' when received , stored. when output value, invalid base64 encoded data.

if examine source of working vs. non-working examples you'll see whitespace exists there '+' in original base64 encoded value. newlines you're seeing because whatever you're viewing source in wrapping lines @ ' ' character.

in ios code need encode base64 encoded value, in case need percent encode '+' characters.

edit add, in response comment:

post = [post stringbyreplacingoccurrencesofstring:@"+" withstring:@"%2b"];

php ios objective-c xcode http

Where to keep editable config file for Android application? -



Where to keep editable config file for Android application? -

i want config file similar config.xml in .net can edit manually device. have info can modified. 1 way figured out maintain file in sdcard in xml form , read that. question approach whether reading xml sdcard in android app slow downwards performance?

is there other way store config file can changed later?

you consider using sharedpreferences. not sure purpose of config.xml in .net is, if saving info can modified looking for, sharedpreferences sounds solution.

of course, mentioned above, not knowing config.xml for, taking stab suggestion. allow me know if not looking for. delete reply before down-vote barrage begins. ;-)

in case fits bill, here few tutorials started.

http://android-er.blogspot.in/2011/01/example-of-using-sharedpreferencesedito.html http://saigeethamn.blogspot.in/2009/10/shared-preferences-android-developer.html http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/ http://www.mybringback.com/tutorial-series/12260/android-sharedpreferences-example/

android app-config

ruby on rails 3.2 - ActiveAdmin member_action gives 401 Unauthorized response -



ruby on rails 3.2 - ActiveAdmin member_action gives 401 Unauthorized response -

i building rails app using active_admin 0.5.1.

in app/admin/plays.rb defined admin resource this:

activeadmin.register play member_action :upload, :method => :post ... end def index ... end end

note added non-standard upload-action described here: http://activeadmin.info/docs/8-custom-actions.html

now whenever phone call index action, works fine. when post fellow member action :upload though, 401 response:

started post "/admin/plays/1/upload.js" 127.0.0.1 @ 2013-02-13 18:46:36 +0100 processing admin::playscontroller#upload js parameters: {...} warning: can't verify csrf token authenticity adminuser load (0.4ms) select "admin_users".* "admin_users" "admin_users"."id" = 1 limit 1 (0.1ms) begin transaction (0.0ms) commit transaction completed 401 unauthorized in 7ms

furthermore after getting error, admin user logged out.

what missing here? expecting actions defined via member_action work standard actions.

found reason.

"warning: can't verify csrf token authenticity" kind of give-away.

you need add together authenticity_token param ajax upload request create devise happy.

i still wish devise have given more detailed hint on happened in detail.

ruby-on-rails-3.2 activeadmin

Dialogs don't pause thread - Android Logic -



Dialogs don't pause thread - Android Logic -

i'm having bit of confusion logic of code. i'm doing displaying dialog user using showdialog (which know depreciated) , select, drawing icon touched.

my question is: "how programme "pause" while user picking selection, next code doesn't called , drawing isn't done after press ok.

edit: forgot mention - on main ui thread, haven't got lot of experience dealing threads have couple of asynctasks in program. there point in making new thread handle touch , drawing functions?

private void touch_start(float x, float y) { // on finger touchdown // check touch mode if (addobjectmode == true) { //drawingareaview method add together edittext box @ position x,y ix = (int) (math.round(x)); iy = (int) (math.round(y)); mx = (int) (math.round(x)); = (int) (math.round(y)); myrect.set(ix, iy, mx, my); } else if (addappliancemode == true) { // code draw appliance icon @ mx, (with offset icon centered) maketoast("start drawing appliance @ x, y"); } } private void touch_move(float x, float y) { // on finger motion float dx = math.abs(x - mx); // difference between x , x float dy = math.abs(y - my); if (dx >= touch_tolerance || dy >= touch_tolerance) { // if coordinates outside screen? if touching hard enough? mx = (int) (math.round(x)); = (int) (math.round(y)); if (addobjectmode == true) { myrect.set(ix, iy, mx, my); } else if (addappliancemode == true) { // whatever here gets repeated loads if move (e.g. per pixel) maketoast("user moved appliance");// dont set myrect } } } @suppresswarnings("deprecation") private void touch_up() { // on finger release if (addobjectmode == true) { myrect.set(ix, iy, mx, my); mycanvas.drawrect(ix, iy, mx, my, mypaint); maketoast("touchup, phone call dialogs!"); dialogstarter(); } else if (addappliancemode == true) { // phone call add together appliance dialog maketoast("call appliance dialog"); showdialog(dialog_appliance_classification); //mycanvas.drawbitmap(bmp, mx, my, mybitmappaint); } }

its drawing bitmap fails have code choses bmp draw based on user chose gets called in wrong order.

here dialog onclicklistener code:

.setpositivebutton("ok", new dialoginterface.onclicklistener() { public void onclick(dialoginterface dialog, int whichbutton) { maketoast("user clicked ok"); if (islamp == true) { resources res = getresources(); bmp = bitmapfactory.decoderesource(res, r.drawable.lamp); // code draw lamp canvas here homerview.drawapplianceicon(); maketoast("lamp drawn canvas"); } } })

there error @ drawapplianceicon() cannot phone call method contained in custom view class if seek homerview.drawapplianceicon().

it returns error: "cannot create static reference non-static method drawapplianceicon() type drawnewplans.homerview"

heres hierarchy:

public class drawnewplans extends activity implements colorpickerdialog.oncolorchangedlistener { protected void oncreate(bundle savedinstancestate) { // on create method - initialises activity protected dialog oncreatedialog(int id) { // dialog creator code public void colorchanged(int color) { // implemented method when color changed public class homerview extends view { // custom view drawing on protected void ondraw(canvas canvas) { // method used when want draw our canvas protected void onsizechanged(int w, int h, int oldw, int oldh) { // if screen size changes, alter bitmap size private void touch_start(float x, float y) { // on finger touchdown private void touch_move(float x, float y) { // on finger motion private void touch_up() { // on finger release public boolean ontouchevent(motionevent event) { // on touch event public void drawapplianceicon() { // code im working on public boolean oncreateoptionsmenu(menu menu) { // on menu creation public void dialogstarter() { // starts dialogs gathering user submitted info public void checkstoredobjects() { // checks stored in object list public void resetvalues() { // resets values of object null, reuse public boolean onprepareoptionsmenu(menu menu) { // method needed inflate menu public boolean onoptionsitemselected(menuitem item) { // method containing code when menu item selected public void maketoast(string message) { // method display pop short duration public void makelongtoast(string message) { // method display pop long duration public void redrawmode() { // reenables drawing mode resetting mypaint public class getlocations extends asynctask<void, integer, jsonarray> { // asynctask class getting homer locations

edit: unfortunately reply accepted isn't calling piece of code want correctly! :(

here's revised code:

drawnewplans.this.myhomer.drawapplianceicon(200, 200); // should phone call method contained in custom view draws bmp coordinates provided.

the method code:

public void drawapplianceicon(float x, float y) { mycanvas.drawbitmap(bmp, x-50, y-50, mybitmappaint); }

this works when called touch_start() in custom view class not when called via phone call in oncreatedialog method. sorry pain , have massive long question - there improve way of discussing this? sense starting new question mean have repeat context of programme on again.

android dialog