Sunday 15 April 2012

sql - query using SOME in mysql not giving expected results.? -



sql - query using SOME in mysql not giving expected results.? -

suppose have table :

start_range end_range 1 4 4 8

i want result true if greater of value of start_range , less of corresponding end_range.

eg.

value 2 should homecoming true , 2>1 , 2<4 value 4 should homecoming false in case 4>1 4<4 becomes false, 4>4 becomes false sec case.

i cannot utilize query

select sumthing xyz value> some(start_range) , value < some(end_range)

the problem above query allow value = 4.

now 4> some(start_range) become true 4>1. and

4< some(end_range) become true 4<8.

but in actual comparing should (((4>1)and(4<4)) or ((4>4)and(4<8))) . should homecoming false.

one more thing , above table not persistent , i have been creating in subquery.thats why have been using some. if still question isn't clear, mention in comments.

assuming xyz table:

select (count(*) > 0) hasmatch xyz value > start_range , value < end_range;

i'm not sure why using some.

edit:

it occurs me want utilize subqueries, , xyz not table in question. perhaps want:

select xyz.* xyz exists (select 1 (<your query here>) t xyz.value > t.start_range , xyz.value < t.end_range );

mysql sql

javascript - Unable to connect to websocket -



javascript - Unable to connect to websocket -

i have cordova/phonegap app supposed connect websocket server. works fine on ios & android 4.4 not on samsung galaxy tab 2 running android 4.2.

i know webview in 4.2 doesn't have native implementation of websockets loaded phonegap plugin this. plugin loads , waited deviceready event before attempting connection. when seek illustration provided plugin, onerror event trigered have no additionnal details.

running app using google chrome on same device works, exclude network issue. application has internet permission. i'm little out of clues @ point, ideas welcome :-)

ok, after taking @ adb log @nicholas suggested (thanks!) had exec() phone call unknown plugin. next this reply solved problem.

javascript android cordova websocket

Using SharePoint REST to add list item using C# -



Using SharePoint REST to add list item using C# -

i have application hosted on 1 server that's not part of sharepoint farm. need to post new list item sharepoint list. default sharepoint zone (where posted to) configured utilize claims authentication, integrated windows authentication.

the identity application running under has total administrative access on list i'm trying post to. every time post "403 forbidden" error. if remove endpointrequest.credentials line 401 error.

var info = "{'__metadata':{'type':'sp.data.speciallistitem'}, 'special':'" + txtspecial + "'}"; httpwebrequest endpointrequest = (httpwebrequest)httpwebrequest.create("http://portal/_api/web/list/getbytitle('special')"); endpointrequest.credentials = credentialcache.defaultnetworkcredentials; endpointrequest.method = "post"; endpointrequest.accept = "application/json;odata=verbose"; endpointrequest.contenttype = "application/json;odata=verbose"; endpointrequest.contentlength = data.length; streamwriter author = new streamwriter(endpointrequest.getrequeststream()); writer.write(data); writer.flush(); using (httpwebresponse endpointresponse = (httpwebresponse)endpointrequest.getresponse()) { using (streamreader reader = new streamreader(endpointresponse.getresponsestream())) { string result = reader.readtoend(); } }

c# rest sharepoint-2013

format - SAS convert numeric variable to time -



format - SAS convert numeric variable to time -

i have numeric variable numbers of form 924 1045 1742 etc. these times.

i want convert them time format 09:24:00.

i can't seem find way of doing this.

informat used hhmmss , format see time want time5:

data have; informat time hhmmss4.; format time time5.; input time; cards; 924 1045 1742 ; run;

if field number in dataset work:

data have; input time; cards; 924 1045 1742 ; run; info want; set have; time_num=input(put(time, 4. -l), hhmmss4.); format time_num time5.; run; proc print;run;

time format sas

c++ - Can a lambda that captures "this" to call a mutating member function be used to initialize a local thread? -



c++ - Can a lambda that captures "this" to call a mutating member function be used to initialize a local thread? -

i'm new concurrency, next code might troubling more experienced. question is, implementation create info races, or other problems?

the background have number crunching work do, , utilize 2 threads. while 1 thread computing intermediate results used later second, other uses generated intermediate results.

details: in phone call operator of class a, used lambda initialize first thread. lambda captures "this" pointer, in order phone call fellow member function of a, happens alter state of info members of a. captures functor, generating intermediate results.

the sec thread constructed functor, uses intermediate results producing final results.

both functors passed in via non-const references because modify own respective info members.

a 2nd question is, can move definitions of lambda functions out of loop, , utilize them build 2 threads (then join) within loop.

class a{ private: data_type m_data; void m_fun(){ // mutate m_data } public: a() = default; // functor_1 , 2 different types void operator()(functor_1&, functor_2&); }; void a::operator()(functor_1& f_1, functor_2& f_2){ t intermediate_copy_1, intermediate_copy_2; // both big, matrix structures // initial content of intermediate_copy_1 generated functor_2 // then, for(int i=0; i<100000; ++i){ auto foo = [this, &f_2, &intermediate_copy_2]{ m_fun(); f_2(intermediate_copy_2); }; auto bar = [&f_1, &intermediate_copy_1]{ f_1(intermediate_copy_1); }; std::thread t_foo(foo); std::thread t_bar(bar); t_foo.join(); t_bar.join(); // after both threads finished, pass copy_2 copy_1 utilize in next round. // copying relatively inexpensive intermediate_copy_1 = intermediate_copy_2; } // little more work }

c++ multithreading c++11 lambda

java - Error in Regular expression for find File according a Pattern -



java - Error in Regular expression for find File according a Pattern -

i need develop pattern in regular expression:

pattern:

201410021600(12 numbers)-only 2 options or b_(zz same)616048(6 numbers)_bbbb(4 characters)-123456abcdef(12 alfanumeric)_out(always same).pdf(always same)

real example:

201410021600-a_zz123456_bbbb-123456abcdef_out.pdf.

this attempt, didn,t work :(:

\d{12}-{1}a_{1}\bzz\b\d{6}_{1}\d{4}-{1}\w{12}_{1}\bout.pdf\b

somebody can help me, please?

you don't need specify quantity 1, i.e. instead of -{1} or _{1} - or _ sufficient.

additionally, you're specifying quantity twice here: \d{6}{1} not necessary.

third, \b marks word boundary means there needs @ to the lowest degree whitespace. \bzz\b won't match input.

applying this, regex looks , should work: \d{12}-[ab]_zz\d{6}_[a-z]{4}-[a-z0-9]{12}_out\.pdf

to break down:

201410021600(12 numbers) -> \d{12} -only 2 options or b -> -[ab] update: comment seems if a , b words , not characters, can't utilize character class here need utilize grouping instead, e.g. -(?>a|b) ((?>...) means grouping non-capturing, i.e. can't retrieve using matcher.group(x) etc.) _(zz same) -> _zz 616048(6 numbers)-> \d{6} _bbbb(4 characters) -> _[a-z]{4} (i assume upper case chars allowed) -123456abcdef(12 alfanumeric) -> -[a-z0-9]{12} (in case upper case characters allowed) _out(always same) - > _out .pdf(always same) -> \.pdf (the dot matches character needs escaped)

if case not matter, i.e. if 201410021600-a_zz123456_bbbb-123456abcdef_out.pdf. should match well, either add together a-z character classes should allow lower case (e.g. [a-za-z] instead of [a-z]) or add together (?i) @ front end of look if lower case allowed.

java regex

android - How to remove hidden fragments -



android - How to remove hidden fragments -

i'm trying switch layout total view double pane view following:

....... ....... . . . . . . --> ....... . . . . ....... .......

now issue i'm going 1 container fragment 2 containers fragment in each. in order i'm removing old fragment , adding new ones. when remove fragment in big 1 old fragment appears instead. i've set tag on old fragment , search after getfragmentmanager().findfragmentbytag() returns null.

for hack utilize largeview.setvisibility(view.gone); there improve way handle this?

edit:

it seems bug isn't reproduced longer. means replace should have done along. why did glitch? eclipse? android?

edit2

this how replace fragments:

fragment fragment = new simplescannerfragment();

fragmenttransaction ft = getfragmentmanager().begintransaction(); ft.replace(r.id.main_container, fragment, scan_fragment_tag); ft.commit();

before switching double pane layout pop stack this:

getfragmentmanager().popbackstack(null, fragmentmanager.pop_back_stack_inclusive);

i remove fragments using this:

removefragment = getfragmentmanager().findfragmentbytag(scan_fragment_tag); if(removefragment != null) { getfragmentmanager().begintransaction().remove(removefragment).commit(); }

i'm switching views visiblity when go single double pane:

// hide main layout well, hacks in case again... framelayout frame = (framelayout) this.findviewbyid(r.id.main_container); frame.setvisibility(view.gone); // add together new layout fragmenttransaction ft = getfragmentmanager().begintransaction(); custommapfragment fragment = custommapfragment.newinstance(); scorefragment scorefragment = new scorefragment(); ft.replace(r.id.main_narrow_bot_container, fragment); ft.replace(r.id.main_narrow_top_container, scorefragment); ft.commit();

how trying clear entire stack?

private void clearbackstack(){ fragmentmanager fragmentmanager = getfragmentmanager(); fragmentmanager.popbackstack(null, fragmentmanager.pop_back_stack_inclusive); fragmentmanager.popbackstackimmediate(); }

android fragment

javascript - Mechanism of Recursive Callbacks -



javascript - Mechanism of Recursive Callbacks -

see fiddle: http://jsfiddle.net/ym1alk25/9/

var s = $('#shake'); var randomtran = function (flag) { flag = flag || 0; if (flag < 6) { var rh = math.floor((math.random() * 10) - 5), rv = math.floor((math.random() * 10) - 5); s.transit({x: rh,y: rv}, 50, randomtran.bind(this, ++flag)) }; }; randomtran(); s.transit({x: 0,y: 0});

i'm trying create element shake few seconds , homecoming original position. doesn't work expected, problem callback function. according question: if jquery function calls in completion callback, recursive danger stack?, seems while callback still looping, codes come after callback function beingness executed. how accomplish goal, other setting timeout? , can find more detailed explanation mechanism?

your fiddle working expected, , animations queued (they queued if .transit() called multiple times repeatedly, plugin uses jquery's internal animation queue). thing 50 milliseconds animation on 5 pixels much fast. i've increased time , printed counter in revision of fiddle.

it seems while callback still looping, codes come after callback function beingness executed.

there no "looping callback". callback passed function returns before callback called - , code called .transit() continues (which, in case, closing } brace if, end of randomtran() call, , s.transit({x: 0,y: 0}); initialisation.

once code has finished executing, other code can executed - asynchronously. callback stored somewhere - in future, 50ms after transit() phone call - beingness called; start transition, schedule callback, , ends.

javascript recursion callback

android - Google in-app billing: Removing ads with a subscription -



android - Google in-app billing: Removing ads with a subscription -

this more general question google's in-app billing mechanics. i've read documentation, there 1 thing bothering me, sort out before coding.

i remove admob ads in android application via subscription. means user pays subscription , long he/she chooses maintain subscription active, there no ads in application.

now far apple goes, forbid removal of ads via renewable subscription. i've been browsing webs google's view of this, have yet find any. if has had experience this, please no hesitate share thoughts. allowed remove admob ads via subscription.

yes, can remove admob ads whenever like. using admob 100% voluntarily , can stop showing them in app whenever like.

android admob ads

reporting services - Column visibility based on 2 parameters in SSRS -



reporting services - Column visibility based on 2 parameters in SSRS -

i have parameter 'section' has values a,b,c , parameter 'field' has values x,y,z. requirement need create column visibility based on both parameters,if parameter 'section' , parameter 'field' x column should shown else hidden.both multi-valued parameters. have written next look not allowing me run

=iif(instr(join(parameters!sections.label,", "),"a"),instr(join(parameters!fields.label,", "),"x", false,true),true)

error getting while running study "input string not in right format. can help me in correcting format?

try this:

=iif(instr(join(parameters!sections.label,", "),"a") , instr(join(parameters!fields.label,", "),"x"), true,false)

reporting-services ssrs-2008 ssrs-2008-r2 ssrs-tablix ssrs-grouping

github - Getting Git Clone history -



github - Getting Git Clone history -

i'm trying figure out how has made clones git or git hub. there git command can this?

git hub reports clones made not made them.

cheers

git github

jQuery-UI's .dialog with jQuery Mobile? -



jQuery-UI's .dialog with jQuery Mobile? -

i'm working on retrofitting large, existing webapp makes extensive utilize of jquery ui work acceptably on mobile devices. had been hoping able utilize jquery mobile library this, since takes care of much of headache of making form elements behave nicely on touch screen devices, , seems working plenty - except jquery ui dialogs, not respond in way, nor produce console errors.

i'm guessing happening because jquery mobile has .dialog method, functionally incompatible jquery ui style of creating dialogs.

without jquery mobile, jquery ui dialogs work great on every mobile device i've tested, that, of course, leaves me important amount of work making custom mobile styles of buttons , inputs site-wide. there upwards of 100 instances of jquery ui's dialog widget in app, rewriting of hand utilize jquery mobile method not great solution either.

ideally, i'd able go on utilize jquery ui's dialog widget instead of jquery mobile's, maintain rest of jquery mobile functionality intact. i've been looking quite time , have yet find resource offers solution problem, i'm wondering if here knows of way resolve conflict.

the jquery ui version on site 1.11.1, , jquery mobile version 1.4.3 - site makes utilize of google hosted libraries , should ideally remain way, editing libraries last-ditch effort.

edit: create verify assumptions, i've tested customized jquery mobile version built the download builder removes dialog widget, , jquery ui 1 works that. however, still preferable if work using google hosted library somehow.

dialogs deprecated of jquery mobile 1.4.0 , removed in 1.5.0. dialog alternative provided page.dialog extension of page widget allows style page dialog, however, special navigational handling removed. may consider implementing dialogs using popup widgets.

maybe want utilize popup instead of dialog needs http://api.jquerymobile.com/popup/

jquery jquery-ui jquery-mobile jquery-ui-dialog jquery-mobile-dialog

mysql - How to update the values of a single column with the result of a query? -



mysql - How to update the values of a single column with the result of a query? -

i'm having problem getting query work in mysql:

update proyects_c set director=(select users.keyid users,proyects users.username=proyects.director );

now problem subquery returns more 1 row. thing is, want. number of rows returns same number of rows in proyects_c, hence expected update every row in column director result of query.

however error:

error 1242 (21000) @ line 23: subquery returns more 1 row

which makes sense, can't want. doing wrong?

as secondary question, how can split 2 queries? clarity's sake.

maybe :

update proyects_c p inner bring together users u on u.username = p.director set p.director = u.keyid

mysql sql

Window width hard limit in Opera and Firefox? -



Window width hard limit in Opera and Firefox? -

okay... hey guys, hope can help me solve one, or maybe able provide comprehensible reasoning following.

the newer versions of opera , firefox browser forcing reduced available width onto websites. assume that's in order fit content improve (with less unused space).

however, if website's content exceeds width of 1536 px (and screen resolution 1920 px in width), available width still capped @ 1536 (a horizontal scrollbar appears).

i've prepared demo well: http://r00t.li/test/opera_fittowidth_fckup.html

so think it's nice feature of browsers fit website content available width improves readability, on earth can if want/need utilize total screen width?

i've toyed around different meta tag viewport settings, hadn't have effect. guess that's mobile devices only.

ok, after more searching found culprit: dpi setting of windows affects how these browsers display websites. instance dpi of 125%, opera , firefox browser seek apply not ui, websites rendering content bigger (even though website zoom in browser set 100%), decreasing available pixel width.

as web designer, 1 has apparently absolutely no command on this. , if user takes time alter windows dpi 100%, it's not acceptable solution. granted, websites normal again, font-size of windows ui tiny - hard read.

but don't want become rant, again; solution alter windows dpi setting 100%. can done this:

right click on desktop , select screen resolution click on "make text , other items larger , smaller" choose 100% , save settings

very sad browser developers made decision... if 100 milliseconds takes user hold ctrl , tick mouse wheel 1 or 2 times much.

firefox width opera

c# - Custom probes for Windows Azure Load-balancer -



c# - Custom probes for Windows Azure Load-balancer -

we trying create custom probes loadbalanced sets in windows azure. created windows communication foundation service probe, listening port 1001 (added inbound rule port in firewall - tcp, allow connection everyone).

this service homecoming 200 (ok) if conditions met, otherwise homecoming 404 (notfound).

the endpoint configured:

protocol - tcp public port - 50655 private port - 50655

we configured in loadbalanced set properties:

probe protocol - http probe path - probe probe port - 1001 probe interval - 15 number of probes - 2

the problem if probe service returning 404 vm, load balancer still choosing vm process request.

if configure endpoints have private , public port 1001 (the same probe port) working expected. need have endpoints listening port 50655. how can accomplish this?

i notice configured endpoint type tcp instead of http. think problem!

think logically , you'll see consequence load balancer can not assume should see http 200 success verify endpoint - because doesn't know if http response @ all!

so instead fall doing tcp style 'are up' test, send syn port, , check gets ack back.

c# wcf azure azure-virtual-machine azure-vm-role

fscanf in C with a text file with no spaces -



fscanf in C with a text file with no spaces -

i have text file names looks follows:

"mary","patricia","linda","barbara","elizabeth","jennifer","maria","susan","margaret",

i have used next code effort set names array:

char * names[9]; int = 0; file * fp = fopen("names.txt", "r"); (i=0; < 9; i++) { fscanf(fp, "\"%s\",", names[i]); }

the programme comes segmentation fault when seek run it. have debugged carefully, , notice fault comes when seek , read in sec name.

does know why code isn't working, , why segmentation fault happening?

you have undefined behavior in code, because don't allocate memory pointers write in fscanf call.

you have array of 9 uninitialized pointers, , part of local variable have indeterminate value, i.e. point seemingly random locations. writing random locations in memory (which happen when phone call fscanf) bad things.

the simplest way solve problem utilize array of arrays, e.g.

char names[9][20];

this gives array of 9 arrays, each sub-array beingness 20 characters (which allows have names 19 characters long).

to not write out of bounds, should modify phone call don't read many characters:

fscanf(fp, "\"%19s\",", names[i]);

there problem utilize of fscanf function, , format read string, "%s", reads until finds whitespace in input (or until limit reached, if field width provided).

in short: can't utilize fscanf read input.

instead suggest read whole line memory @ once, using fgets, , split string on comma using e.g. strtok.

one way of handling arbitrarily long lines input file (pseudoish-code):

#define size 256 size_t current_size = size; char *buffer = malloc(current_size); buffer[0] = '\0'; // terminator @ first character, makes string empty (;;) { // read temporary buffer char temp[size]; fgets(temp, sizeof(temp), file_pointer); // append actual buffer strcat(buffer, temp); // if lastly character newline (which `fgets` append // if reaches end of line) whole line have // been read , done if (last_character_is_newline(buffer)) break; // still more info read line // allocate larger buffer current_size += size; buffer = realloc(buffer, current_size); // continues loop seek , read next part of line } // after loop pointer `buffer` points memory containing whole line

[note: above code snippet doesn't contain error handling.]

c fscanf

angularjs - Adding an optional href to anchor tab using Angular -



angularjs - Adding an optional href to anchor tab using Angular -

i have hyperlink on template conditionally available. in case when it's not available, want still display inactive.

this first attempt:

<a ng-class="{denied: !data.canmanageleadfields }"> lead fields </a>

ng-class works appropriately. denied class changes pointer default on link. hoping same principle apply href attribute, have eliminate attribute itself, not set blank string. can't seem find out of box. ideas?

angularjs

c++ - Convert html string to pdf using wkhtmltopdf C library (wkhtmltox) -



c++ - Convert html string to pdf using wkhtmltopdf C library (wkhtmltox) -

i trying convert html string pdf using wkhtmltopdf c library. checked sample comes installer , compiled , converted page. here code used reference.

wkhtmltopdf_global_settings * gs; wkhtmltopdf_object_settings * os; wkhtmltopdf_converter * c; wkhtmltopdf_init(false); gs = wkhtmltopdf_create_global_settings(); wkhtmltopdf_set_global_setting(gs, "out", "test.pdf"); os = wkhtmltopdf_create_object_settings(); wkhtmltopdf_set_object_setting(os, "page", "https://www.google.com.ph"); c = wkhtmltopdf_create_converter(gs); wkhtmltopdf_set_progress_changed_callback(c, progress_changed); wkhtmltopdf_set_phase_changed_callback(c, phase_changed); wkhtmltopdf_set_error_callback(c, error); wkhtmltopdf_set_warning_callback(c, warning); wkhtmltopdf_add_object(c, os, null); if (!wkhtmltopdf_convert(c)) fprintf(stderr, "convertion failed!"); printf("httperrorcode: %d\n", wkhtmltopdf_http_error_code(c)); wkhtmltopdf_destroy_converter(c); wkhtmltopdf_deinit();

i suspecting changing parameters of function

wkhtmltopdf_set_object_setting(os, "page", "https://www.google.com.ph");

to

wkhtmltopdf_set_object_setting(os, [name of setting], [html string]);

will job, documentation didn't specify name particular setting aside 1 included in sample "page".

maybe missed in documentation or maybe not right way it. suggestion much appreciated.

thanks time looking this. ended workaround. instead of string passed local path of generated html file. not solution looking same thing. again.

html c++ c pdf wkhtmltopdf

webpage - Is there some local code that can substitute Facebook's Like button code? -



webpage - Is there some local code that can substitute Facebook's Like button code? -

i have on website twitter tweet , facebook buttons, configured on developer websites. generate 7 times more bytes (in scripts, images , iframes) downloading actual site does.

when analyse pages with, e.g. google pagespeed, pingdomcome or webpagetest, main complaints redirects, render-blocking javascript, , uncompressed/uncachable resources, , originate twitter , facebook (and google, e.g. jquery).

i found can serve bare-bones replacement twitter button code:

<a href="http://twitter.com/share?text=mygreatexample&url=http://www.example.com"></a>

but have no facebook replacement, , no thought google search term find one. displaying number of "likes" not necessary.

update: found this: http://simplesharingbuttons.com/ question answered.

facebook webpage pagespeed

r - Objects aren't recognized unless manually created -



r - Objects aren't recognized unless manually created -

my server.r file begins:

library(shiny) source("scripts/0-prepare-inputs.r") source("scripts/1-analysis-functions.r") shinyserver(function(input, output) {})

if manually execute 2 helper scripts, runapp() works desired. however, if start clearing environment , allowing source() commands run scripts, 2 objects created in 0-prepare-inputs.r aren't found. error appears such:

> shiny::runapp() listening on http://127.0.0.1:5591 error in lapply(obj, function(val) { : object 'stabletypes' not found

stabletypes generated in next manner within 0-prepare-inputs.r:

stabletypes <- list(races = c("all", "white", "black", "hispanic", "nhwhite", "nhblack"), genders = c("total", "male", "female"))

running line allows runapp() function properly.

i need solve problem in order create utilize of shinyapps.io.

things i've tried don't work:

changing local parameter in source(). replacing source() command lines of source files. wrapping creation of stabletypes in function called in script file. wrapping creation of stabletypes in function called reactive object. saving stabletypes robject , loading in source scripts , @ top of server.r. saving stabletypes using super-assignment. saving stabletypes using assign() , specifying envir = .globalenv. running scripts, saving environment using save.image() , loading environment using load(..., envir = .globalenv)

all packages date per update.packages(), , i'm running r version 3.1.1.

based on comment suggestion source file in global.r. can create file in same directory ui.r , server.r files. in file avialable both ui , server.

r shiny

node.js - How to access koa context in another generator function? -



node.js - How to access koa context in another generator function? -

in koa can accesss koa context in first generator function via this:

app.use(function *(){ this; // context }

but if yield generator function can't access context via this anymore.

app.use(function *(){ yield mygenerator(); } function* mygenerator() { this.request; // undefined }

i've been able pass context sec generator function, wondering whether there's cleaner way access context.

any ideas?

either pass this argument said:

app.use(function *(){ yield mygenerator(this); }); function *mygenerator(context) { context.request; }

or utilize apply():

app.use(function *(){ yield mygenerator.apply(this); }); function *mygenerator() { this.request; }

node.js koa

android - how to display a listview when clicked on the item of spinner using onitemselected listener? -



android - how to display a listview when clicked on the item of spinner using onitemselected listener? -

i have written programme displays spinner want display listview within same activity when select item of spinner , have written code custom adapter display items within listview , the listviews row has 6 textviews of info comes string-array defined within strings.xml file , need help

result_date.java has spinner , resources , dont know phone call within "onitemselected" method

public class result_date extends activity { imageview iv; string[] years = { "select year", "2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009", "2010", "2011", "2012", "2013", "2014" }; arrayadapter<string> adapter; listview lv; string[] name; string[] mobile; string[] gender; string[] age; string[] disease; string[] day; string[] month; string[] year; int[] images = { r.drawable.photo_bg, r.drawable.photo_bg, r.drawable.photo_bg, r.drawable.photo_bg, r.drawable.photo_bg, r.drawable.photo_bg, r.drawable.photo_bg, r.drawable.photo_bg }; spinner spinner; @override protected void oncreate(bundle savedinstancestate) { // todo auto-generated method stub super.oncreate(savedinstancestate); setcontentview(r.layout.result_list_year); spinner = (spinner) findviewbyid(r.id.btnshowyear); iv = (imageview) findviewbyid(r.id.imgbackreuslt); adapter = new arrayadapter<string>(getbasecontext(), r.layout.spinner_item, r.id.textview1, years) { @override //this method used hide default text "select year" repeats twice public view getdropdownview(int position, view convertview, viewgroup parent) { view v = null; if (position == 0) { textview tv = new textview(getcontext()); tv.setheight(0); tv.setvisibility(view.gone); v = tv; } else { v = super.getdropdownview(position, null, parent); } parent.setverticalscrollbarenabled(false); homecoming v; } }; adapter.setdropdownviewresource(r.layout.spinner_item); spinner.setadapter(adapter); resources res = getresources(); name = res.getstringarray(r.array.name); mobile = res.getstringarray(r.array.mobile); gender = res.getstringarray(r.array.gender); age = res.getstringarray(r.array.age); disease = res.getstringarray(r.array.diagnosisname); day = res.getstringarray(r.array.day_array); month = res.getstringarray(r.array.month_year); year = res.getstringarray(r.array.year_array); lv = (listview) findviewbyid(r.id.lstshowyear); myadapter adapter = new myadapter(getbasecontext(), name, mobile, gender, age, images, day, month, year, disease); lv.setadapter(adapter); spinner.setonitemselectedlistener(new onitemselectedlistener() { @override public void onitemselected(adapterview<?> parent, view view, int position, long id) { // todo auto-generated method stub } @override public void onnothingselected(adapterview<?> parent) { // todo auto-generated method stub } }); } public void onclick(view v) { super.onbackpressed(); finish(); }

my customadapter myadapter.java

public class myadapter extends arrayadapter<string> { context context; int[] images; string[] namearray; string[] mobilearray; string[] genderarray; string[] agearray; string[] diseasearray; string[] dayarray; string[] montharray; string[] yeararray; public myadapter(context c, string[] name, string[] mobile, string[] gender, string[] age, int[] img, string[] disease, string[] day, string[] month, string[] year) { super(c, r.layout.row_layout, r.id.textview1, name); // todo auto-generated constructor stub this.context = c; this.namearray = name; this.mobilearray = mobile; this.genderarray = gender; this.agearray = age; this.diseasearray = disease; this.dayarray = day; this.montharray = month; this.yeararray = year; } @override public view getview(int position, view convertview, viewgroup parent) { // todo auto-generated method stub listview lv; layoutinflater inflater = (layoutinflater) context .getsystemservice(context.layout_inflater_service); view row = inflater.inflate(r.layout.row_layout, parent, false); imageview image = (imageview) row.findviewbyid(r.id.imgview); textview text1 = (textview) row.findviewbyid(r.id.txtname); textview text2 = (textview) row.findviewbyid(r.id.txtmobile); textview text3 = (textview) row.findviewbyid(r.id.txtgender); textview text4 = (textview) row.findviewbyid(r.id.txtage); textview text5 = (textview) row.findviewbyid(r.id.txtdesease); textview text6 = (textview) row.findviewbyid(r.id.txtdate); lv = (listview) row.findviewbyid(r.id.listview1); image.setimageresource(images[position]); text1.settext(namearray[position]); text2.settext(mobilearray[position]); text3.settext(genderarray[position]); text4.settext(agearray[position]); text5.settext(diseasearray[position]); text6.settext(dayarray[position]); text6.settext(montharray[position]); text6.settext(yeararray[position]); homecoming row; }

}

do need write code defining resources obj till setting adapter within onitemselected method ?? suggestions welcomed

i'll next thing:

create method within listadapter named illustration "refreshlist" take parameter info selected spinner item need "get" info need fill list spinner's value selected. illustration if info alter list year function this:

public void refreshlist(string year) { //fill arrays info according year namearray = getresources().getstringarray(r.array.name); //do loas info need according year here //and refresh adapter this.notifydatasetchanged(); }

then in onitemselected phone call of spinner phone call function of listadapter adapter.refreshlist(years[position]) or that. it's thought there many ways this, point have function in adapters called notifydatasetchanged() load 1 time again list info in list/array of info handle within adapter. if spinner selected value alter list info should utilize refresh list when spinner value selected. hope helps

android android-listview

json - Scala - Instantiate classes dynamically from a String -



json - Scala - Instantiate classes dynamically from a String -

i trying create dynamic parser allows me parse json content different classes depending on class name.

i json , class name (as string) , this:

val thecaseclassname = "com.ardlema.jdbcdataproviderproperties" val mycaseclass = class.forname(thecaseclassname) val jsonjdbcproperties = """{"url":"myurl","username":"theuser","password":"thepassword"}""" val json = json.parse(jsonjdbcproperties) val value = try(json.as[myclass])

the above code not compile because json.as[] method tries convert node "t" (i have implicit reads[t] defined case class)

what best way proper "t" pass in json.as[] method original string?

a great solution might work polymorphic deserialization. allows add together field (like "type") json , allow jackson (assuming you're using awesome json parser jackson) figure out proper type on behalf. looks might not using jackson; promise it's worth using.

this post gives great introduction polymorphic types. covers many useful cases including case can't modify 3rd party code (here add together mixin annotate type hierarchy).

the simplest case ends looking (and of works great scala objects -- jackson has great scala module):

object test { @jsontypeinfo( utilize = jsontypeinfo.id.name, include = jsontypeinfo.as.property, property = "type" ) @jsonsubtypes(array( new type(value = classof[cat], name = "cat"), new type(value = classof[dog], name = "dog") )) trait animal case class dog(name: string, breed: string, leash_color: string) extends animal case class cat(name: string, favorite_toy: string) extends animal def main(args: array[string]): unit = { val objectmapper = new objectmapper scalaobjectmapper objectmapper.registermodule(defaultscalamodule) val dogstr = """{"type": "dog", "name": "spike", "breed": "mutt", "leash_color": "red"}""" val catstr = """{"type": "cat", "name": "fluffy", "favorite_toy": "spider ring"}""" val animal1 = objectmapper.readvalue[animal](dogstr) val animal2 = objectmapper.readvalue[animal](catstr) println(animal1) println(animal2) } }

this generates output:

// dog(spike,mutt,red) // cat(fluffy,spider ring)

you can avoid listing subtype mapping, requires json "type" field bit more complex. experiment it; might it. define animal this:

@jsontypeinfo( utilize = jsontypeinfo.id.class, include = jsontypeinfo.as.property, property = "type" ) trait animal

and produces (and consumes) json this:

/* { "breed": "mutt", "leash_color": "red", "name": "spike", "type": "classpath.to.test$dog" } { "favorite_toy": "spider ring", "name": "fluffy", "type": "classpath.to.test$cat" } */

json scala reflection

monotouch - Modify the Frame of UIButton -



monotouch - Modify the Frame of UIButton -

i'm trying resize uibutton referenced xib file.

this i've tried without success:

rectanglef frame = actionbtn.frame; frame.width = 140; actionbtn.frame = frame;

what doing wrong?

you can't modify existing rectanglef. seek instead

rectanglef frame = actionbtn.frame; actionbtn.frame = new rectanglef(frame.x, frame.y, 140, frame.height);

monotouch xamarin

Serializing arrays as documents in MongoDB C# driver -



Serializing arrays as documents in MongoDB C# driver -

i have class implements icollection<t> interface:

class test : icollection<string> { [bsonelement("items")] private list<string> _items; [bsonelement("someotherprop")] public bool someotherproperty { get; set; } // ...icollection<string> impl }

by default (de-)serialized using arrayserializer class, other properties or fields (even public & decorated bsonelement attribute) ignored.

does know how can enforce class deserialized regular one?

ok, seems found solution. can @ application startup:

bsonserializer.registerserializer( typeof(test), new bsonclassmapserializer(bsonclassmap.lookupclassmap(typeof(test))));

i'm not sure, might conflict bsonclassmap.registerclassmap(...) method phone call (i.e. methods phone call order might important) - didn't check out. note, such registration global whole app domain. if inappropriate, things little more tricky, cause can't decorate class property bsonclassmapserializer attribute. stopped little research, cause achieved goal.

i hope find reply helpful!

c# mongodb

Bootstrap requires JQuery (using Express with Parse) -



Bootstrap requires JQuery (using Express with Parse) -

i working on writing little website. hosting site parse , using express , bootstrap. top of app.js file looks this:

var express = require('express'); var _ = require('underscore'); var jquery = require('cloud/libs/jquery-2.1.1.min.js'); var bootstrap = require('cloud/libs/bootstrap.min.js');

when go deploy (parse deploy) app, comes next error:

uploading source files finished uploading files update failed not load triggers. error error: bootstrap's javascript requires jquery @ libs/bootstrap.min.js:6:37 @ app.js:6:17 @ main.js:1:1

i cannot figure out how include bootstrap , jquery in app without getting error. i've followed setup instructions parse has here. serving files myself.

does know how include bootstrap , jquery in type of web app?

i new this, if have clarifying questions please inquire kindly.

since serving myself moved bootstrap , jquery files public folder , included these tags in _header.ejs.

<script src="/bootstrap/js/jquery-2.1.1.min.js"></script> <script src="/bootstrap/js/bootstrap.min.js"></script>

my error not putting bootstrap files in public folder.

i looking using bootstrap cdn or hosted bootstrap. unless of course of study improve serve them statically?

jquery twitter-bootstrap express parse.com

java - Comparing two unordered lists of objects based on a closure -



java - Comparing two unordered lists of objects based on a closure -

i have 2 unordered lists. want compare these 2 lists based on conditions can specify through closure/ pointer function.

what having problem construction of objects in these lists may different , want compare attributes in cases other attributes in other case.

e.g.

class sampleobj{ string attribute1; list attribute2; string attribute3; } list obj1-> attribute1 = "test",attribute2 = ["a","b","c"] obj2 -> attribute1 = "optionalarg test 2",attribute3 = "optionalarg" list b obj1 -> attribute3 = "test4", attribute2 = [1,2,3] obj2 -> attribute3 = "optionalarg" obj3 -> attribute1 = "test",attribute2 = ["a","b","c"]

in case object 1 in list equal object 3 in list b (both required attributes of object equal) , object 2 in list equal object 2 in list b (the value of attribute 3 substring of attribute 1).

so, status based on cross product of attribute 1 , attribute 2 or on attribute 3. meaning if attribute1 , attribute2 equal object 1 lista , object 3 listb, can these 2 objects equal, otherwise if attribute 3 matches status attribute 1 can objects equal meaning object 2 listb can equal object2 list (condition beingness substring check in case)

in general trying write library method take 2 lists , closure , based on closure passed lets me know whether objects in list match list b or vice-versa.

let me know if there questions/clarifications needed here or/and if can guide me in right direction.

if want know whether or not matches exist between 2 lists according arbitrary criteria need following:

def hasmatches(list a, list b, closure<boolean> matchcriteria) { && b && a.any{ aa -> b.any { bb -> matchcriteria(aa, bb) || matchcriteria(bb, aa) } } }

then next assertions homecoming true:

class sampleobj{ string attribute1 list attribute2 string attribute3 string name @override string tostring() { name } } list<sampleobj> lista = [ [name: "obja1", attribute1: "test", attribute2: ["a","b","c"]] sampleobj, [name: "obja2", attribute1: "optionalarg test 2", attribute3: "optionalarg"] sampleobj ] list<sampleobj> listb = [ [name: "objb1", attribute3: "test4", attribute2: [1,2,3]] sampleobj, [name: "objb2", attribute3: "optionalarg"] sampleobj, [name: "objb3", attribute1: "test", attribute2: ["a","b","c"]] sampleobj ] // there exists @ to the lowest degree 1 object in list attribute 1 value matches of @ to the lowest degree 1 object in list b (or vice versa) assert hasmatches(lista, listb) { sampleobj aa, sampleobj bb -> aa?.attribute1 == bb?.attribute1 } // there exists @ to the lowest degree 1 object in list b attribute 3 value substring of attribute 1 value of @ to the lowest degree 1 object in list (or vice versa) assert hasmatches(lista, listb) { sampleobj aa, sampleobj bb -> bb?.attribute3 && aa?.attribute1?.contains(bb.attribute3) } // there not exist object in list attribute 1 value contained in attribute 2 list of object in list b (or vice versa) assert !hasmatches(lista, listb) { sampleobj aa, sampleobj bb -> aa?.attribute1 && bb?.attribute2?.contains(aa.attribute1) }

if, on other hand, want see matching pairs, need bit more extensive:

def findequivalentpairs(list a, list b, closure<boolean> matchcriteria) { && b \ ? a.sum { aa -> def ab = b.findresults { bb -> matchcriteria(aa, bb) ? [aa, bb] : null } ?: [] def ba = b.findresults { bb -> matchcriteria(bb, aa) ? [bb, aa] : null } ?: [] ab + ba } : [] }

then, printing out results using same 3 criteria closures...

println findequivalentpairs(lista, listb) { sampleobj aa, sampleobj bb -> aa?.attribute1 == bb?.attribute1 } println findequivalentpairs(lista, listb) { sampleobj aa, sampleobj bb -> bb?.attribute3 && aa?.attribute1?.contains(bb.attribute3) } println findequivalentpairs(lista, listb) { sampleobj aa, sampleobj bb -> aa?.attribute1 && bb?.attribute2?.contains(aa.attribute1) }

... yields following:

[[obja1, objb3], [objb3, obja1]] [[obja2, objb2]] []

java list groovy

python - Am I cheating on this AI challenge? -



python - Am I cheating on this AI challenge? -

so on hackerrank under ai section, solution "bot saves princess - 2" problem reads input princess's position. solution supposed that? don't see how else can solved efficiently.

problem:

https://www.hackerrank.com/challenges/saveprincess2

solution def nextmove(r,c, pr, pc): if r < pr: r += 1 return("down") elif r > pr: r -= 1 return("up") if c < pc: c += 1 return("right") elif c > pc: c -= 1 return("left") n = int(input()) r,c = [int(i) in input().strip().split()] grid = [] pr = 0 pc = 0 in range(0, n): inp = input() if inp.find('p') >= 0: pr = pc = inp.find('p') grid.append(inp) print(nextmove(r,c,pr, pc))

forgive me if mistaken, can not find princesses position finding index of 'p' in grid, not seem specified input:

def find_princess(grid): n = len(grid) in range(grid): j in range(grid): if grid[i][j] == 'p' homecoming i,j

python algorithm artificial-intelligence

c# - Adding element to Webbrowser -



c# - Adding element to Webbrowser -

i have table id="table1" loaded in webbrowser webbsppagina. need add together row. code can add together row table element isnt shown on webbrowser. need alter webbrowser?

htmlelement element = webbsppagina.document.getelementbyid("table1"); htmlelement mtbody = element.firstchild; htmlelement mtr = webbsppagina.document.createelement("tr"); htmlelement mtd1 = webbsppagina.document.createelement("td"); htmlelement mtd2 = webbsppagina.document.createelement("td"); htmlelement mtd3 = webbsppagina.document.createelement("td"); mtd1.style = "vertical-align: top"; mtd2.style = "vertical-align: top"; mtd3.style = "vertical-align: top"; mtd1.setattribute("class", "ms-rtetablecells"); mtd2.setattribute("class", "ms-rtetablecells"); mtd3.setattribute("class", "ms-rtetablecells"); mtd1.innertext = "teamviewer id"; mtd2.setattribute("id", "teamviewerid"); mtd3.setattribute("id", "teamvieweridextra"); mtr.appendchild(mtd1); mtr.appendchild(mtd2); mtr.appendchild(mtd3); mtbody.appendchild(mtr);

i tried code, working me if in next way

//add table in form load event private void form1_load(object sender, eventargs e) { webbsppagina.documenttext = "<table id='table1'><tr><td>hello</td></tr></table>"; } //added code in button click event private void button1_click(object sender, eventargs e) { htmlelement element = webbsppagina.document.getelementbyid("table1"); htmlelement mtbody = element.firstchild; htmlelement mtr = webbsppagina.document.createelement("tr"); htmlelement mtd1 = webbsppagina.document.createelement("td"); htmlelement mtd2 = webbsppagina.document.createelement("td"); htmlelement mtd3 = webbsppagina.document.createelement("td"); mtd1.style = "vertical-align: top"; mtd2.style = "vertical-align: top"; mtd3.style = "vertical-align: top"; mtd1.setattribute("class", "ms-rtetablecells"); mtd2.setattribute("class", "ms-rtetablecells"); mtd3.setattribute("class", "ms-rtetablecells"); mtd1.innertext = "teamviewer id"; mtd2.setattribute("id", "teamviewerid"); mtd3.setattribute("id", "teamvieweridextra"); mtr.appendchild(mtd1); mtr.appendchild(mtd2); mtr.appendchild(mtd3); mtbody.appendchild(mtr); }

c# .net webbrowser-control

python - Using two counters in a loop -



python - Using two counters in a loop -

i have been making text based game @ home using python , have been having problem creating little section of combat between player , foe. combat supposed include 2 random rolls; 1 player , 1 alien. if alien rolls higher player +1 should added alien_wins counter , if player wins +1 should added player_wins counter.

what want happen when player_wins counter reaches 3 loop stop , produce message, same should happen when alien_ wins reaches 3 have had problem making work. help appreciated, thanks!

import random tkinter import * def fight(): player_wins = 0 alien_wins = 0 while player_wins <= 3: player_roll = random.randint(0, 10) alien_roll = random.randint(0, 7) if player_roll > alien_roll: contents.set("you manage fire shot of laser pistol , alien backs off.") player_wins += 1 homecoming elif alien_roll > player_roll: contents.set("the alien reaches out , strikes claws.") alien_wins += 1 homecoming elif alien_roll == player_roll: contents.set("you both grapple eachother , off.") homecoming if player_wins == 3: contents.set("you manage overcome alien. leaps wall wall , crawls vents.") win = true break elif alien_wins == 3: contents.set("you lose fighting alien. game over!") break base of operations = tk() contents = stringvar() display = message(base, textvariable = contents, relief=raised) display.pack() enterbutton = button(base, text = 'try again', command = fight).pack() base.mainloop()

you want go on fighting (looping) while either status (points <= 3) true. need add together status while loop.

you want homecoming function after fighting on remove of returns , add together 1 outside of loop after fighting over. also, want create messages after fighting over.

def fight(): player_wins = 0 alien_wins = 0 while player_wins <= 3 , alien_wins <= 3: player_roll = random.randint(0, 10) alien_roll = random.randint(0, 7) if player_roll > alien_roll: contents.set("you manage fire shot of laser pistol , alien backs off.") player_wins += 1 elif alien_roll > player_roll: contents.set("the alien reaches out , strikes claws.") alien_wins += 1 elif alien_roll == player_roll: contents.set("you both grapple eachother , off.") if player_wins == 3: contents.set("you manage overcome alien. leaps wall wall , crawls vents.") win = true elif alien_wins == 3: contents.set("you lose fighting alien. game over!") homecoming

python if-statement while-loop tkinter

objective c - Preprocessor macro check when defining a class's interface declaration -



objective c - Preprocessor macro check when defining a class's interface declaration -

i have nswindowcontroller has window subclass in xib. until 10.10 had window subclass (we phone call windowsubclassb) subclass of nswindow , did fancy ui stuff

now yosemite, no longer need subclass window on yosemite, still previous os x versions.

i though of few different options, such setting different .xib yosemite , other version, xib has lot of pieces , mean have maintain 2 different xibs prepare this.

so i've attempted utilize preprocessor macros @ build time determine class subclass

i tried:

#if mac_os_x_version_min_required >= mac_os_x_version_10_10 @interface gfmosxmainwindow : nswindow #else @interface gfmosxmainwindow : inappstorewindow #endif

but code not executed on yosemite because it's not minimum requirement

what accomplish below:

#if current_osx_version == osx_version_10_10 @interface windowsubclassa : nswindow #else @interface windowsubclassa : windowsubclassb #endif

i not, however, see such macro @ build time tell me current version of os x app built on is.

also, if knows how tell uiwindowcontroller programmatically class it's @property window should initialized as, solve whole issue :)

thanks in advance!

the problem trying in that, code not compiled multiple times different scheme versions. if anything, it'd compiled differently different processors (like 32/64 bit on osx, or armv7, armv7s , arm64 on ios). think it's not possible accomplish in way.

i don't have thought alternative solution yet, isn't wild dynamic method setting using objc runtime.

objective-c osx

c# - Find a panel in a asp page with panel id -



c# - Find a panel in a asp page with panel id -

in app fetch panel id database , in webpage need find panel id need create visible false. code behind

protected sub page_load(byval sender object, byval e system.eventargs) handles me.load seek dim kioskxml string = "pnlfindid" dim mycontrol1 command = page.findcontrol(kioskxml) if (not mycontrol1 nothing) mycontrol1.visible = false end if grab ex exception end seek end sub

but above code snippet, cannot fetch panel works fine controls textbox , other. need way find panel id on page load

my html page

<asp:content id="content1" contentplaceholderid="contentplaceholder1" runat="server"> <ajaxtoolkit:toolkitscriptmanager id="toolkitscriptmanager1" runat="server"> </ajaxtoolkit:toolkitscriptmanager> <div onload="disablebackbutton();"> <table align="center" width="100%" cellpadding="0" cellspacing="0"> <tr> <td> <asp:panel id="pnlfindid" runat="server"> <table align="center" width="100%" cellpadding="0" cellspacing="0"> <tr> <td> <asp:panel id="pane3" runat="server"> </asp:panel> </td> </tr> </table> </asp:panel> </td> </tr> </table>

</asp:content>

thanks

i assuming trying find command in content pages's load event opposed master page's load event.

you need first find contentplaceholder , find panel within contentplaceholder not familiar vb.net syntax, providing c# syntax:

contentplaceholder cont = (contentplaceholder)this.master.findcontrol("contentplaceholder1"); panel mypanel = cont.findcontrol(kioskxml);

ofcourse, else, if doing on master page's page load event,

contentplaceholder cont = (contentplaceholder)this.findcontrol("contentplaceholder1"); panel mypanel = cont.findcontrol(kioskxml);

c# asp.net vb.net

angularjs - My filter does not work -



angularjs - My filter does not work -

im trying alter status value numbers 'text'

i wonder how can solve it, , did wrong? give thanks in advance

<table> <tr ng-repeat="x in id"> <td>{{ x.id }}</td> <td>{{ x.status | status}}</td> </tr> </table>

when write | status <- crashes whole ng repeat , nil displays.

var app = angular.module('customerscontroller', []); function customerscontroller($scope, $http) { $http.get("localhost") .success(function (response) { $scope.id = response; }); app.filter('status', function () { homecoming function (input) { var statu; switch (input) { case 10: statu = 'bronze'; break; case 20: statu = 'silver'; break; case 30: statu = 'gold'; break; case 40: statu = 'elite'; break; } homecoming statu; }; });

you're defining filter within controller. not valid. may add together filters module during configuration phase, before app started , controller instantiated. code should be:

var app = angular.module('customerscontroller', []); app.filter('status', function () { homecoming function (input) { var statu; switch (input) { case 10: statu = 'bronze'; break; case 20: statu = 'silver'; break; case 30: statu = 'gold'; break; case 40: statu = 'elite'; break; } homecoming statu; }; }); app.controller('customerscontroller', function($scope, $http) { $http.get("localhost") .success(function (response) { $scope.id = response; }); });

angularjs angularjs-filter

hadoop - why eclipse is not able to import package for hbase? -



hadoop - why eclipse is not able to import package for hbase? -

i using cloudera hadoop vmware 4.7.0. while writting hbase code in eclipse getting error @ import line. so, please tell me need utilize jar or plugin resolve issue? how import packages hbase program? tried find out solution on net not thing. please help me friends.

i have got reply of above problem. added jar hbase classpath , issue resolved. got jar file form next link:- link

eclipse hadoop hbase bigdata cloudera

How to do FFMPEG live transcoding to HTML5 video from file(.MP4, .MKV) in PHP? -



How to do FFMPEG live transcoding to HTML5 video from file(.MP4, .MKV) in PHP? -

i'm using windows, tried follow tutorial , downloaded code: blog page http://sixserv.org/2010/11/30/live-transcoding-for-video-and-audio-streaming/ , github https://github.com/4poc/php-live-transcode. doesn't work, i'm getting errors in mplayer saying "mplayer has not identified file provided".

i need simple working live media transcoder can work on browsers in mobile devices (html5) using ffmpeg in php. i've been searching entire time, found nothing.

php html5 video ffmpeg transcoding

How to avoid iterating twice in the template with Django -



How to avoid iterating twice in the template with Django -

so lets assume have 2 div containers in view. in first div: div1, need create list of items while div2 content of items. means have through same variables twice. there way loop 1 time , somehow utilize info both divs @ once? or best practice twice illustration illustrates?

e.g.:

<div id="div1"> {% if blah1|length > 0 %} blah1 {% endif %} {% if blah2|length > 0 %} blah1 {% endif %} </div> <div id="div2> {% if blah1|length > 0 %} {{ blah1 }} {% endif %} {% if blah2|length > 0 %} {{ blah2 }} {% endif %} </div>

django

angularjs - Sending params with angular's $http to a HttpPost action method in ASP.NET MVC -



angularjs - Sending params with angular's $http to a HttpPost action method in ASP.NET MVC -

my serverside (asp.net mvc) has action:

[httppost] public jsonnetresult myaction(long param1, string param2, string stringifiedjson) { ... }

with jquery can utilize action easily, this:

$.ajax({ async: true, type: 'post', url: '/bla/myaction', data: { "param1": 123, "param2": "blah", "stringifiedjson": json.stringify(somejson), }, success: function (data) { ... } });

but angularjs, haven't been able request. i'm trying:

var httprequest = $http({ method: "post", url: "/bla/myaction", params: { param1: 123, param2: "blah", stringifiedjson: json.stringify(somejson) }, data: { } }); httprequest.success(function(response) { ... });

in fact, angularjs isn't doing http post.. doing options request i'm getting 404 not found.

question is... how can post request params? know utilize "data" then, how create asp.net mvc map request each method parameter?

the info sending should have same names asp.net mvc method parameters. f.e if u have method

public actionresult dosomethingmethod(string name, string surname) { //code }

from angularjs:

$http({ url: "your url", method: "post", data: { name: "jon", surname: "doe" } })

there quicker way

var datatosend = {name:"jon",surname:"doe"}; $http.post("your url",datatosend);

asp.net-mvc angularjs

html - Django "if request.method == 'POST':" fails -



html - Django "if request.method == 'POST':" fails -

hi have unusual problem in new django project.

i'm testing nameform illustration django documentation working froms. seems easy 1 somehow when seek submit name nil happens not page reload.

form.py

from django import forms class nameform(forms.form): your_name = forms.charfield(label='your name', max_length=100)

views.py

from django.shortcuts import render django.http import httpresponseredirect groupbuilder import forms def groupbuilder(request): if request.method == 'post': form = forms.nameform(request.post) if form.is_valid(): homecoming httpresponseredirect('/thanks/') else: form = forms.nameform() homecoming render(request, 'groupbuilder.html', {'form': form})

the template:

<form action="/your-name/" method="post"> {% csrf_token %} { form.as_p }} <input type="submit" value="submit" /> </form>

setting.py

""" django settings crosslfg project. more info on file, see https://docs.djangoproject.com/en/1.6/topics/settings/ total list of settings , values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # build paths within project this: os.path.join(base_dir, ...) import os django.utils.translation import ugettext_lazy _ template_context_processors = ( "django.contrib.auth.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.static", "django.core.context_processors.tz", "django.contrib.messages.context_processors.messages", #"frontpage.context_processors.contactform", ) debug = true template_debug = debug admins = ( # ('your name', 'your_email@example.com'), ) managers = admins base_dir = os.path.dirname(os.path.dirname(__file__)) project_path = '/home/kbrothers/crosslfg/' template_path = os.path.join(project_path, 'templates') static_path = os.path.join(project_path,'static') static_url = '/static/' database_path = os.path.join(project_path,'users.db') #locale_paths = os.path.join(project_path, 'locale',) locale_paths = ('/home/kbrothers/crosslfg/locale',) # quick-start development settings - unsuitable production # see https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/ # security warning: maintain secret key used in production secret! secret_key = **** # security warning: don't run debug turned on in production! debug = true crispy_template_pack = 'bootstrap3' allowed_hosts = [] # application definition installed_apps = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'main_app', 'groupbuilder', 'crispy_forms', ) template_loaders = ( 'django.template.loaders.filesystem.loader', 'django.template.loaders.app_directories.loader', # 'django.template.loaders.eggs.loader', ) template_dirs = ( os.path.join(project_path, 'templates'), os.path.join(project_path, 'main_app/templates'), os.path.join(project_path, 'accounts/templates'), os.path.join(project_path, 'groupbuilder/templates'), ) middleware_classes = ( 'django.contrib.sessions.middleware.sessionmiddleware', 'django.middleware.locale.localemiddleware', 'django.middleware.common.commonmiddleware', 'django.middleware.csrf.csrfviewmiddleware', 'django.contrib.auth.middleware.authenticationmiddleware', 'django.contrib.messages.middleware.messagemiddleware', 'django.middleware.clickjacking.xframeoptionsmiddleware', # uncomment next line simple clickjacking protection: 'django.middleware.clickjacking.xframeoptionsmiddleware', ) root_urlconf = 'crosslfg.urls' wsgi_application = 'crosslfg.wsgi.application' # database # https://docs.djangoproject.com/en/1.6/ref/settings/#databases mail_use_tls = true email_host = '****' email_port = **** email_host_user = '********' email_host_password = '********' #crispy_template_pack = 'bootstrap3' databases = { 'default': { 'engine': 'django.db.backends.sqlite3', # add together 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'name': database_path, # or path database file if using sqlite3. # next settings not used sqlite3: 'user': '', 'password': '', 'host': '', # empty localhost through domain sockets or '127.0.0.1' localhost through tcp. 'port': '', # set empty string default. } } # internationalization # https://docs.djangoproject.com/en/1.6/topics/i18n/ language_code = 'en' #language_code = 'de' #language_code = 'fr' language_cookie_name = 'wm_lang' time_zone = 'utc' languages = ( ('en', _('english')), #('de', _('german')), #('fr', _('french')), ) use_i18n = true use_l10n = true use_tz = true # static files (css, javascript, images) # https://docs.djangoproject.com/en/1.6/howto/static-files/

the unusual thing if set

return httpresponseredirect('/thanks/')

right after "else" in

if request.method == 'post':

statement, can't fill out form when seek visit form url. takes straight /thanks/. request.method check fails.

what miss??

problem solved:

<script src="{{static_url}}js/plugins/jqbootstrapvalidation.js"></script>

from jqbootstrapvalidation caused problem. i'm not sure why there must have been interference form functionalities.

anyway help

html django post

jquery - Insert a paragraph from an external HTML page to another HTML page with Javascript -



jquery - Insert a paragraph from an external HTML page to another HTML page with Javascript -

i'm new javascript excuse me if want doesn't create sense. want import paragraph , header external html page html page, possible javascript? if yes can point me can find right info.

page imports going done.

<ul> <li> <h3>header imported form page 1</h3> <p>paragraph imported page 1</p> </li> <li> <h3>header imported form page 2</h3> <p>paragraph imported page 2</p> </li> </ul>

external page 1

<h3>header in page 1</h3> <p>paragraph in page 1</p>

external page 2

<h3>header in page 2</h3> <p>paragraph in page 2</p>

i searched of posts found import finish html pages.

fyi - cannot utilize php since don't have access server.

thanks

you utilize jquery load() method.

the .load() method, unlike $.get(), allows specify portion of remote document inserted. achieved special syntax url parameter. if 1 or more space characters included in string, portion of string next first space assumed jquery selector determines content loaded.

for example:

$( "#result" ).load( "ajax/test.html #container" );

when method executes, retrieves content of ajax/test.html, jquery parses returned document find element id of container. element, along contents, inserted element id of result, , rest of retrieved document discarded.

javascript jquery html ajax json

How To Get Twig Template Engine Header Tags in PHP Function -



How To Get Twig Template Engine Header Tags in PHP Function -

i trying extend pico navigation plugin exclude items navigation tree page's utilizes twig template engine header tags.

my question how specific header tags .md files in below php function , filter them excluded in navigation tree?

the plugin implements ability omit items (pages , folders) tree next settings in config.php file:

// exclude pages and/or folders navigation header $config['navigation']['hide_page'] = array('a title', 'another title'); $config['navigation']['hide_folder'] = array('a folder', 'another folder');

the current function in plugs' file uses above config.php follows:

private function at_exclude($page) { $exclude = $this->settings['navigation']; $url = substr($page['url'], strlen($this->settings['base_url'])+1); $url = (substr($url, -1) == '/') ? $url : $url.'/'; foreach ($exclude['hide_page'] $p) { $p = (substr($p, -1*strlen('index')) == 'index') ? substr($p, 0, -1*strlen('index')) : $p; $p = (substr($p, -1) == '/') ? $p : $p.'/'; if ($url == $p) { homecoming true; } } foreach ($exclude['hide_folder'] $f) { $f = (substr($f, -1) == '/') ? $f : $f.'/'; $is_index = ($f == '' || $f == '/') ? true : false; if (substr($url, 0, strlen($f)) == $f || $is_index) { homecoming true; } } homecoming false; }

i need add together ability of omitting items (or pages) tree using twig header tags 'type' , 'status' in .md files:

/* title: post01 in cat01 description: post01 in cat01 date: 2013-10-28 category: type: post // options: page, post, event, hidden status: draft // options: published, draft, review author: me template: */ ... markdown content . . .

so if user wants remove items tagged "post" in 'type' tag and/or "draft" 'draft' tag (see header above), add together linked tags in array below added config.php:

// exclude taged items: $config['navigation']['hide_status'] = array('draft', 'maybe other status tag'); $config['navigation']['hide_type'] = array('post', 'etc');

i added next bottom of at_exclude() function:

private function at_exclude($page) { . . . foreach ($exclude['hide_staus'] $s) { $s = $headers['status']; if ($s == 'draft' || 'review') { homecoming true; } } foreach ($exclude['hide_type'] $t) { $t = $headers['type']; if ($t == 'post' || 'hidden') { homecoming true; } homecoming true; } . . .

this not working me (because php knowledge limited). help missing, doing wrong or how can add together functionality appreciated.

i dived (not beautiful) pico code , findings.

first of all, pico doesn't read every custom field add together content header. instead, has internal array of fields parse. luckily, hook called before_read_file_meta provided modify array. in at_navigation.php we'll add:

/** * hook add together custom file meta array of fields pico read */ public function before_read_file_meta(&$headers) { $headers['status'] = 'status'; $headers['type'] = 'type'; }

this result in pico reading headers, won't add together fields page info yet. need hook, get_page_data. in same file:

/** * hook add together custom fields page info */ public function get_page_data(&$data, $page_meta) { $data['status'] = isset($page_meta['status']) ? $page_meta['status'] : ''; $data['type'] = isset($page_meta['type']) ? $page_meta['type'] : ''; }

now, in at_exclude function, can add together new logic. (instead of cycling, configure array of status , types want exclude, , we'll check if there match current page status/type)

private function at_exclude($page) { [...] if(in_array($page['status'], $exclude['status'])) { homecoming true; } if(in_array($page['type'], $exclude['type'])) { homecoming true; }; homecoming false; }

now let's customize our config.php (i standardized configuration plugin standards):

$config['at_navigation']['exclude']['status'] = array('draft', 'review'); $config['at_navigation']['exclude']['type'] = array('post');

all done! if starting out, i'd advise utilize more mature , recent flat file cms. unless stuck php5.3

php twig

android - "java.lang.IllegalStateException: Can not be called to deliver a result" -



android - "java.lang.IllegalStateException: Can not be called to deliver a result" -

i got exception: "java.lang.illegalstateexception: can not called deliver result", , didn't understand why. below reply why happened, maybe helps someone.

i had called finishaffinity() after having set result code. android complaining never able deliver result when calling finishaffinity().

solution: either don't set result before calling finishaffinity(), or set result 1 time again before calling finishaffinity() time activity.result_canceled result code:

setresult(activity.result_canceled); finishaffinity();

android illegalstateexception result activity-finish

map - Brightness of chartplotter (Dynamic Data Display) C# -



map - Brightness of chartplotter (Dynamic Data Display) C# -

i'm using microsoft visual studio 2010, including reference dynamic info display. i'm want create scroll bar command of brightness of map . i'm tried find property brightness or without success. give thanks help friends. :)

you can command brightness of plotter setting background different rgb values. each value has range 0 (darkest) 255 (brightest). first set brightest color, illustration

byte r = 255; byte g = 255; byte b = 255;

and define factor (range 0.5 1.0) controlled slider.(0.0 total blackness, set lower range 0.5 gray).

double minfactor = 0.5; double maxfactor = 1.0; double factor = maxfactor; //initially, brightest

then background of plotter

color color = color.fromrgb((byte)(factor*r), (byte)(factor*g), (byte)(factor*b)); plotter.background = new solidcolorbrush(color);

and how slider controls brightness.

slider slider = new slider(); slider.value = factor; slider.maximum = maxfactor; slider.minimum = minfactor; slider.valuechanged += (s, e) => { var newfactor = e.newvalue; color newcolor = color.fromrgb((byte)(newfactor * r), (byte)(newfactor * g), (byte)(newfactor * b)); plotter.background = new solidcolorbrush(newcolor); };

brightness of map

a. set dark background plotter

plotter.background = new solidcolorbrush(colors.black);

b. hide grid

plotter.axisgrid.visibility = system.windows.visibility.collapsed;

c. adjust map's opacity slider

slider.valuechanged += (s, e) => { var newfactor = e.newvalue; map.opacity = newfactor; //color newcolor = color.fromrgb((byte)(newfactor * r), (byte)(newfactor * g), (byte)(newfactor * b)); //plotter.background = new solidcolorbrush(newcolor); }

c# map brightness dynamic-data-display

sql - Hiearchical Join takes long time -



sql - Hiearchical Join takes long time -

i have tree hierarchical construction representing product structure. on each product level (6 levels), have salesprice linked it. using 2 tables joined each other link prices on lower levels prices on level above. want don't take business relationship cost more once. done next code (notice utilize level 0, 1 , 2 show idea):

select l0_salesprice ,l1_salesprice ,l2_salesprice (select distinct a.* bct bring together quotationline ql on a.pricecalcid = ql.pricecalcid a.levels = 0) l0 bring together (select distinct a.* bct bring together quotationline ql on a.pricecalcid = ql.pricecalcid a.levels = 1) l1 on l0.itemid = l1.parentitemid bring together (select distinct a.* bct bring together quotationline ql on a.pricecalcid = ql.pricecalcid a.levels = 2) l2 on l1.itemid = l2.parentitemid

the problem query never finishes executing, , out of memory error.

table bct 750 000 rows , table quotationline 22000 rows.

any advice appreciated.

to demonstrate how troubleshoot issue, here sample table definitions.

create table [description] ( [descriptionid] int identity not null constraint [pk_description] primary key, [descriptiontext] nvarchar(50) not null ) go create table [hierarchy] ( [hierarchyid] int not null constraint [pk_hierarchy] primary key, [parenthierarchyid] int null constraint [fk_hierarchy_parenthierarchyid] references [hierarchy] ([hierarchyid]) on delete no action on update no action, [price] money not null, [descriptionid] int null constraint [fk_hierarchy_description] references [description] ([descriptionid]) on delete set null on update cascade ) go create index [ix_hierarchy_parenthierarchyid] on [hierarchy] ([parenthierarchyid]) include ([hierarchyid], [price], [descriptionid]) go

a naive way hierarchy -- is, 1 unlikely solve performance issue -- might be:

;with rowends ( select h.[hierarchyid], h.[parenthierarchyid], h.[price], h.[descriptionid], h.[hierarchyid] [rowendhierarchyid], 0 [reverselevel] [hierarchy] h not exists (select 1 [hierarchy] i.[parenthierarchyid] = h.[hierarchyid]) union select h.[hierarchyid], h.[parenthierarchyid], h.[price], h.[descriptionid], r.[rowendhierarchyid], r.[reverselevel] + 1 [reverselevel] [hierarchy] h inner bring together rowends r on h.[hierarchyid] = r.[parenthierarchyid] ), inorder ( select r.rowendhierarchyid, r.[hierarchyid], r.price, d.descriptiontext, rank() on (partition r.[rowendhierarchyid] order r.[reverselevel] desc) [level] rowends r left bring together [description] d on r.descriptionid = d.descriptionid ) select distinct o.rowendhierarchyid, p.[1] price1, d.[1] description1, p.[2] price2, d.[2] description2, p.[3] price3, d.[3] description3, p.[4] price4, d.[4] description4, p.[5] price5, d.[5] description5, p.[6] price6, d.[6] description6, p.[7] price7, d.[7] description7 inorder o inner bring together (select projp.rowendhierarchyid, projp.[level], projp.[price] inorder projp) ppre pivot (min([price]) [level] in ([1], [2], [3], [4], [5], [6], [7])) p on o.rowendhierarchyid = p.rowendhierarchyid left bring together (select projd.rowendhierarchyid, projd.[level], projd.descriptiontext inorder projd) dpre pivot (min(descriptiontext) [level] in ([1], [2], [3], [4], [5], [6], [7])) d on o.rowendhierarchyid = d.rowendhierarchyid order o.rowendhierarchyid

this example, of course, uses recursive mutual table look hierarchy. rather starting @ root of tree , working toward leaves, query takes opposite approach. advantage doing each row in output corresponds leaf node in tree.

performance, however, may still unsatisfactory approach because have no chance index mutual table expressions, result sets may quite large. provided tempdb has sufficient space , performance, following, more-verbose query may improve performance.

create table #rowend ( [rowendhierarchyid] int not null, [hierarchyid] int not null, [parenthierarchyid] int null, [price] money not null, [descriptionid] int null, [reverselevel] int not null, primary key ([rowendhierarchyid], [reverselevel] desc) ) create index [ix_rowend_parenthierarchyid] on #rowend ([parenthierarchyid], [rowendhierarchyid], [reverselevel]) create index [ix_rowend_reverselevel] on #rowend ([reverselevel] desc, [parenthierarchyid], [rowendhierarchyid]) insert #rowend ([hierarchyid], [parenthierarchyid], [price], [descriptionid], [rowendhierarchyid], [reverselevel]) select h.[hierarchyid], h.[parenthierarchyid], h.[price], h.[descriptionid], h.[hierarchyid], 1 [hierarchy] h not exists (select 1 [hierarchy] i.parenthierarchyid = h.[hierarchyid]) declare @reverselevel int set @reverselevel = 0 while exists (select 1 #rowend re re.reverselevel > @reverselevel) begin set @reverselevel = @reverselevel + 1 insert #rowend ([hierarchyid], [parenthierarchyid], [price], [descriptionid], [rowendhierarchyid], [reverselevel]) select h.[hierarchyid], h.[parenthierarchyid], h.[price], h.[descriptionid], re.[rowendhierarchyid], @reverselevel + 1 [hierarchy] h inner bring together #rowend re on re.parenthierarchyid = h.[hierarchyid] , re.reverselevel = @reverselevel end create table #price ( rowendhierarchyid int not null primary key, [1] money null, [2] money null, [3] money null, [4] money null, [5] money null, [6] money null, [7] money null ) insert #price (rowendhierarchyid, [1], [2], [3], [4], [5], [6], [7]) select p.rowendhierarchyid, p.[1], p.[2], p.[3], p.[4], p.[5], p.[6], p.[7] (select re.rowendhierarchyid, re.price, rank() on (partition re.rowendhierarchyid order re.reverselevel desc) [level] #rowend re) ppre pivot (min([price]) [level] in ([1], [2], [3], [4], [5], [6], [7])) p create table #description ( rowendhierarchyid int not null primary key, [1] nvarchar(50) null, [2] nvarchar(50) null, [3] nvarchar(50) null, [4] nvarchar(50) null, [5] nvarchar(50) null, [6] nvarchar(50) null, [7] nvarchar(50) null ) insert #description (rowendhierarchyid, [1], [2], [3], [4], [5], [6], [7]) select d.rowendhierarchyid, d.[1], d.[2], d.[3], d.[4], d.[5], d.[6], d.[7] (select re.rowendhierarchyid, dt.descriptiontext, rank() on (partition re.rowendhierarchyid order re.reverselevel desc) [level] #rowend re left bring together [description] dt on re.descriptionid = dt.descriptionid) dpre pivot (min([descriptiontext]) [level] in ([1], [2], [3], [4], [5], [6], [7])) d select p.rowendhierarchyid, p.[1] price1, d.[1] description1, p.[2] price2, d.[2] description2, p.[3] price3, d.[3] description3, p.[4] price4, d.[4] description4, p.[5] price5, d.[5] description5, p.[6] price6, d.[6] description6, p.[7] price7, d.[7] description7 #price p inner bring together #description d on p.rowendhierarchyid = d.rowendhierarchyid order p.rowendhierarchyid drop table #description drop table #price drop table #rowend

the basic logic of obtaining hierarchy similar prior version. indexing temp tables in manner, however, improve query performance considerably.

sql sql-server tree structure

javascript - Toggle-only sidenav with Angular-Material? -



javascript - Toggle-only sidenav with Angular-Material? -

i want side menu closed default on screen size, , open on top of other content. no matter seek though, switches @ widths on 960px.

this menu looks now:

<md-sidenav is-locked-open="false" class="md-sidenav-right md-whiteframe-z2" component-id="right"> <md-toolbar class="md-theme-dark"> <div class="md-toolbar-tools"> <md-button ng-click="togglemenu()" class="md-button-colored"><core-icon icon="polymer"></core-icon></md-button> <span flex></span> </div> </md-toolbar> <md-content class="md-content-padding"> <md-button ng-click="togglemenu()" class="md-button-colored">stuff</md-button> </md-content> </md-sidenav>

and controller:

.controller('homectrl', function ($scope, $mdsidenav) { $scope.togglemenu = function() { $mdsidenav('right').toggle(); }; })

i got is-locked-open website can't find anywhere in javascript.

you can utilize is-locked-open attribute in md-sidenav command locking open of sidenav. lock sidenav when browser width 1000px.

<md-sidenav is-locked-open="$media('min-width: 1000px')"></md-sidenav>

to have forever unlocked, worked me:

<md-sidenav is-locked-open="$media('')"></md-sidenav>

javascript angularjs

android - Switch Statement using a loop in Java -



android - Switch Statement using a loop in Java -

i have switch statement alter image resourceid:

int imageid = 0; switch (i) { case 0: imageid = r.drawable.image0; break; case 1: imageid = r.drawable.image1; break; case 2: imageid = r.drawable.image2; break; case 3: imageid = r.drawable.image3; break; case 4: imageid = r.drawable.image4; break; case 5: imageid = r.drawable.image5; break; case 6: imageid = r.drawable.image6; break; case 7: imageid = r.drawable.image7; break; }

but have been trying find out how using loop, since case number , number @ end of each image matches. tried loop without success.

can help?

thx!!

why not give r.drawable array of images , can below ?

imageid = r.drawable.images[i];

here's the oracle tutorial. alternatives include java.util.list of particular implementation e.g. arraylist

java android loops for-loop switch-statement

php - HTML5 accept attribute for image uploader - get value through POST -



php - HTML5 accept attribute for image uploader - get value through POST -

i've been trying find out how utilise html5 file type accept attribute have been struggling find details best way utilize it.

at nowadays can understand gets name of file. how data? how store on server?

<input type="file" id="feature" name="feature" accept="image/*">

this php after post submission:

$pic = $_post["feature"]; echo $pic; // outputs filename

the post value of file input ever show filename. file uploaded temp file. it's move want move_uploaded_file()

http://php.net/manual/en/function.move-uploaded-file.php

from manual:

$tmp_name = $_files["feature"]["tmp_name"]; //the temporary file $name = $_files["feature"]["name"]; // it's name move_uploaded_file($tmp_name, "$uploads_dir/$name"); //put there

when working files, utilize $_files not $_post

important

none of work if not add together enctype attribute upload form.

<form ... enctype="multipart/form-data">

php html5 file-upload image-uploading

java - dynamically adding views in a particular position -



java - dynamically adding views in a particular position -

i adding dynamically views on button click.in views there imageview.after clicking on imageview adding photos gallery.it's working till now.now problem photo set in wrong position.it means adding @ lastly view .how can solved.thanks in advance.

buttonadd.setonclicklistener(new onclicklistener() { @override public void onclick(view arg0) { layoutinflater layoutinflater = (layoutinflater) getbasecontext().getsystemservice(context.layout_inflater_service); addview = layoutinflater.inflate(r.layout.add, null); edittext textout = (edittext) addview.findviewbyid(r.id.text); // textout.settext(textin.gettext().tostring()); img = (imageview) addview.findviewbyid(r.id.takephoto); img.setonclicklistener(new onclicklistener() { @override public void onclick(view v) { img.setimagebitmap(photo); } }); } });

here add.xml

<relativelayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <linearlayout android:id="@+id/l1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margintop="20dp" android:weightsum="2"> <imageview android:id="@+id/takephoto" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginleft="20dp" android:layout_weight=".75" android:src="@drawable/ic" /> <edittext android:id="@+id/text" android:layout_width="0dp" android:imeoptions="actionnext" android:singleline="true" android:background="#0000" android:hint="enter option" android:layout_height="wrap_content" android:layout_weight="1" android:maxlength="40" /> </linearlayout> </relativelayout>

java android

Add title to a SAS dataset -



Add title to a SAS dataset -

i hope can help me out question.

after creating summarizing table (using proc summary, proc means etc.), add together title dataset. it's not easiest thing remember sample restrictions etc. help lot able add together title, example: "mean income (note: incomes < $1000 have been excluded)".

an obvious way of doing create dataset...

data title; length title $100; title = "mean income (note: incomes < $1000 have been excluded)"; run;

...and combine summarizing table. there standard procedure add together title while creating table?

if understood correctly, want accomplish called label of sas dataset. can add together label dataset when creating using dataset alternative label. should able utilize anywhere can utilize dataset options , you're creating dataset, e.g.:

data title (label="mean income (note: incomes < $1000 have been excluded)"); length var1 8; run; proc sql; create table title2 (label="title in sql") select * title ; quit; proc sort data=title out = title_sorted (label="title sorted"); var1; run;

or add/modify title later via proc datasets:

proc datasets lib=work nodetails nolist; modify title (label="new title"); quit;

sas

php - check value exists in database using general function Codeigniter -



php - check value exists in database using general function Codeigniter -

i studying codeigniter developing website locally. uncertainty is, added fields in table unique.

when seek add together duplicate values, shows internal server error

i overcome add together function check if duplicate entry. need add together function on each table insertion.

my question is, is there way write function @ my_model.php check table , unique field value , phone call in my_controller.php passing table name , unique field value

you can utilize codeigniter's default form validation check if new value beingness added unique field exists in db or not.

refer this:

is_unique | returns false | if form element not unique table , field name in parameter. is_unique[table.field]

this->form_validation->set_rules('email', 'email', 'required|is_unique[users.email]');

php codeigniter model controller

c++ - QTableView column width -



c++ - QTableView column width -

i'm struggling set column width manually in qtableview. why doesn't piece of code work?

tabb = new qtableview; tabb->resizecolumnstocontents(); (int col=0; col<20; col++) { tabb->setcolumnwidth(col,80); }

if omit tabb->resizecolumnstocontents(); still doesn't work.

you should set model first , after able alter columnwidth:

tabb = new qtableview; tabb->setmodel(somemodel); (int col=0; col<20; col++) { tabb->setcolumnwidth(col,80); }

c++ qt qtableview

html - iFrame/Object is not expanding to 100% height -



html - iFrame/Object is not expanding to 100% height -

so, on website, decided set phase beam thingy picture. couldn't utilize <img> tag because isn't actual image. iframed it. set width , height 100%, height not going 100%.

my website

as can see, phase beam starts first <div class="page-header page-banner"></div>, , goes halfway, , doesn't reach sec <div class="page-header page-banner">.

example of proper image placement

how create iframe expand way sec <div class="page-header page-banner"></div>?

fix iframe parent div 390px :

<div style="height:390px" class="col-md-8">

and you'll perfect alignment <div class="page-header page-banner"> div.

note :

there typo in iframe tag specified height height:100%px.

html iframe twitter-bootstrap-3

PHP FORM navigation with Hidden values -



PHP FORM navigation with Hidden values -

i developing form in php. there variables prepare displayed in link of web page. variable passed other page in hidden , not fixed.

eg.

http://editform.php?var1=23&var2=34 have hidden variables hidvar=23

http://editform.php?var1=23 not have hidden variable , var2 not there

i have checked variable in link isset function. if(isset($_get['var2']))

now how variables values in page combination of hidden variables , variable in link.

i farther adding code allow thought need. below web page saved webform.php

<?php if(isset($_get['yid'])) { $yrid=$_get["yid"]; } else { $yrid=0; echo "variable missing. programme terminated."; } ?> // value of $pass; //get value of sessionid; //get value of yid. <form action="webform.php?pass=<?php echo $pass;?>" name="form1" method="post"> <?php //statement operation using $yrid; ?> <input type="hidden" name="sessionid" value="<?php echo $sesid; ?>" /> </form>

while (list($key, $value) = each($_request)) { echo ($key.' '.$value); }

where $key variable name, $value variable value

php forms navigation isset

vb.net - Random Letter Choosing for Textbox -



vb.net - Random Letter Choosing for Textbox -

so code neethu soman,

dim input string = textbox2.text '<--- should input "hello greg" textbox2.text = "" '<--- clear textbox store output dim rnd new random '<---- generating new random number each c char in input '<--- iterate through each character if rnd.next() mod 2 = 0 textbox2.text &= ucase(c) '<--- if true print particular letter in uppercase else textbox2.text &= lcase(c) '<--- if true print particular letter in lowercase end if next

basically supposed to, converts random letter lower, , upper case 50/50 chance. although, 1 problem is clears text, , rewrites in new converted form, problem. there way create work without having clear text?

thanks create seek answer, can convert random letter lower, or upper case 50/50 chance using next code without using textbox2.text = ""

private sub textbox2_keypress(byval sender object, byval e system.windows.forms.keypresseventargs) handles textbox2.keypress dim rnd new random'<--- generating random number if rnd.next() mod 2 = 0 e.keychar = ucase(e.keychar) '<--- if true alter key char uppercase else e.keychar &= lcase(e.keychar) '<--- if true alter key char lowercase end if end sub

if want in button click means:

private sub button1_click(byval sender system.object, byval e system.eventargs) handles button1.click dim randomstring string = "" dim rnd new random each c char in textbox2.text if rnd.next() mod 2 = 0 randomstring &= ucase(c) else randomstring &= lcase(c) end if next textbox2.text = randomstring end sub

vb.net