Posts

Showing posts from January, 2013

javascript - Ajax call does not assign a value in the done promise -

this question has answer here: how return response asynchronous call? 21 answers i have method this: var isnameunique = false; function validatename() { var url = "/somerules/checkifnameexists/"; var request = $.ajax({ url: url, method: "get", data: { sname: name}, datatype: "json" }); request.done(function (result) { if (result.doesnameexists) { alert("name exists!"); console.log("name exists!"); } else { isnameunique = true; console.log("name unique!"); } }); request.fail(function (jqxhr, textstatus) { console.log(textstatus); alert("request failed."); }

python - Raspberry Pi Bottle webserver, change webpage when button is pressed -

i have raspberry pi bottle webserver running. i've connected several reed switches pi. idea when switch activated, server automatic "push" webpage clients. now, when activate switch. first have refresh page before i'm redirected. i've written script 1 switch far. see below script: from bottle import route, run, template, error bottle import redirect, request, response switch1 = 38 led1 = 40 gpio.setmode(gpio.board) gpio.setup(switch1, gpio.in, pull_up_down=gpio.pud_up) gpio.setup(led1, gpio.out) @route("/") def hello(): if not gpio.input(switch1): gpio.output(led1, true) return template("video1.html") else: gpio.output(led1, false) return template("index.html") @error(404) def error404(error): return("nothing here, keep searching!") run(host='0.0.0.0', port=80)

linux - can not yum package , it pops strang error -

i use centos 6.5 server , openldap installed in server . i want install vsftpd server following command , pops error . yum install vsftpd there problem importing 1 of python modules required run yum. error leading problem was: libldap-2.4.so.2: cannot open shared object file: no such file or directory please install package provides module, or verify module installed correctly. it's possible above module doesn't match current version of python, is: 2.6.6 (r266:84292, nov 22 2013, 12:11:10) [gcc 4.4.7 20120313 (red hat 4.4.7-4)] if cannot solve problem yourself, please go yum faq at: http://yum.baseurl.org/wiki/faq i checked , openldap installed . rpm -qa |grep openldap openldap-2.4.39-8.el6.i686 would advise why pops error seems related libldap-2.4.so.2 ? openldap have problem ? thanks basically, yum provides libldap-2.4.so.2 then install reccomends e.g. [user@localhost ~]$ yum provides libldap-2.4.so.2 loaded plugins: fastestmirror, la

matlab - Lowest starting row indices for minimum 2 consecutive non-zero values per column -

considering sample matrix: a = 0 0 0 0 -4 3 0 2 1 0 0 0 0 5 0 8 7 0 0 9 10 3 1 2 i want find lowest starting locations (row indices) each column of a minimum 2 consecutive non-zero values found. output this: output = [0, 2, 0, 3, 3, 0] the 0 's in output indicate condition of minimum 2 consecutive non-zero values doesn't stand. also, generalized case of finding starting indices of minimum n consecutive non-zero values? minimum 2 consecutive non-zero values case %// mask of non-zeros in input, mask = a~=0 %// find starting row indices alongwith boolean valid flags minimum 2 %// consecutive nonzeros in each column [valid,idx] = max(mask(1:end-1,:) & mask(2:end,:),[],1) %// use valid flags set invalid row indices zeros out = idx.*valid sample run - a = 0 0 0 0 -4 3 0 2 1 0 0 0 0 5 0

sql - sum of ltree children per level -

i have properties table ltree path , name columns. ltree path contains ids of parent nodes, i.e. "7968.7969.7987.8000". each tree node have reports numeric value. need find sum of children nodes values each node in ltree. path in round brackets (1) | __________________________________ | | | (1.2)b (1.3)c (1.4)d | |________________________ | | (1.2.5) e (1.2.6) f reports property_id | value 1 | 1 2 | 4 3 | 19 4 | 21 5 | 9 6 | 11 i need find smth like full_path | subtree_sum | 60 (1 + 4 + 19 + 21 + 9 + 11) a.b | 24 (4 + 9 + 11) a.c | 19 (19) a.d | 21 (21) a.b.e | 9 (9) a.b.f | 11 (11) here are: select p.path, sum(r.value) properties p left join properties sub on sub.path::text

sql - Get all tables creation scripts from Oracle database -

i have oracle db lot of tables , lot of properties like: primary key,unique key, foreign key,indexes, privileges , partitions. i need create same tables same properties in new oracle db. there way generate single creation script tables in database? thanks yes. can execute below query , content in 'definition' column clob contains ddl corresponding object select object_type, object_name, dbms_metadata.get_ddl(object_type, object_name) definition dba_objects owner = 'owner_name' , object_type in ('function', 'package', 'procedure', 'sequence', 'table', 'trigger', 'view') order object_type, object_name below quick vb script helps extract clobs folder = "folder_name" connstr="<your connection string here>" if fetch

html - Center number with 1 and 2 digit -

i have shape heart , have number inside. problem can have number 1 digit , number 2 digit , not able center them heart. https://jsfiddle.net/b7ggddqy/ .description{ position:relative; height:100px; } .heart{ z-index:-500; position: absolute; top:70%; right:20%; width: 30px; height: 30px; -webkit-transform: rotate(45deg); -moz-transform: rotate(45deg); -ms-transform: rotate(45deg); -o-transform: rotate(45deg); transform: rotate(45deg); background-color: #bf4139; } .heart:before, .heart:after{ position: absolute; width: 30px; height: 30px; content: ''; -webkit-border-radius: 50%; -moz-border-radius: 50%; -o-border-radius: 50%; border-radius: 50%; background-color: #bf4139; } .heart:before{ bottom: 0px; left: -15px; } .heart:after{ top: -15px; right: 0px; } .heart p{ -webkit-transform: rotate(-45deg); -moz-transform

lotus notes - Disable a form field in LotusScript or using Input Enabled formula -

using domino designer 8.5. if have form radio button field, possible disable field in lotusscript, possibly in postopen of form? the way can, far, see of achieving using input enabled formula of field itself, struggling understand when triggered... if try put @statusbar or @prompt formula call in there there never notification of input enabled being triggered. if input enabled way achieve this, not lotusscript, there way can have a) formula sets input enabled condition plus b) way of getting visual output, either status bar or message box, either indicate formula has been triggered or - better - let me know value of variable i'd check? the input enabled formula triggered on every refresh of document (f9, save, notesuidocument.refresh, etc.), can not contain code "interacting" user. but this: create field "inputenabled" best way have "controlling" field make "computed display". way not stored in document. formula ente

c# - Web api access controller method from another controller method -

i have 2 different controller --> controller a,controller b and have different methods each controller , return values ihttpactionresult (method controller ,method b , controller b) how can access controller method , take content controller controller b ,and inside method b ihttpactionresult result = controllera.methoda() and want read result.content inside controller b i consider using common base class 2 controllers (if there method want use on both) for example public class abstract mybasecontroller { public void commonmethod() { // here } } then use them like public class controllera : mybasecontroller { public void methoda() { base.commonmethod(); // else } } public class controllerb : mybasecontroller { public void methodb() { base.commonmethod(); // else } }

java - Correct use of log4j and Exceptions -

i have doubt use of log4j exceptions. log messages logfile , don't know how deal exceptions. have use exception (because print in log file) or this: try { configurations.getinstance().getproperty("dynamodbprofilecredentials"); credentials = new profilecredentialsprovider( configurations.getinstance().getproperty("dynamodbprofilecredentials")).getcredentials(); } catch (exception e) { log.error(new amazonclientexception("cannot load credentials credential profiles file. " + "please make sure credentials file @ correct " + "location (c:\\users\\your username\\credentials), , in valid format.",e)); or this try { configurations.getinstance().getproperty("dynamodbprofilecredentials"); credentials = new profilecredentialsprovider( configurations.getinstance().getproperty("dynamodbprofilecredentials")).getcredentials(); } catch (

Ruby on Rails : twitter-bootstrap-rails generate a controller -

hi in rails app im using twitter-bootstrap framework. i've generate controller rails g controller controller_name action1 action2 how can add bootstrap views? can use generator? assuming installed gem 'twitter-bootstrap-rails' gem. you need run generator rails generate bootstrap:install static install related files application. once done this, can generate layout , theme, example rails g bootstrap:themed posts you can find more details twitter-bootstrap-rails you can view video tutorial railscasts twitter bootstrap basics

PHP To google spreadsheet (docs api) with zend - DOMDocument cannot parse XML -

i using zend publish data form google spreadsheet, year now. yesterday of sudden stopped working. highly believe got changed on google api can't address. my code taken link: http://www.farinspace.com/saving-form-data-to-google-spreadsheets/ explaining , professional, made life easier. this error showing when submit form now: fatal error: uncaught exception 'zend_gdata_app_exception' message 'domdocument cannot parse xml: domdocument::loadxml(): empty string supplied input' in /fake/path/zend/library/zend/gdata/app.php:830 stack trace: #0 /fake/path/zend/library/zend/gdata/app.php(789): zend_gdata_app::importstring('', 'zend_gdata_spre...', null, null) #1 /fake/path/zend/library/zend/gdata/app.php(210): zend_gdata_app->importurl('https://spreads...', 'zend_gdata_spre...', null) #2 /fake/path/zend/library/zend/gdata.php(162): zend_gdata_app->getfeed('https://spreads...', 'zend_gdata_spre...') #3 /fake/pa

tomcat - Binding Low Port to Java Program on Ubuntu Server -

i have mini listener/daemon catch snmp trap. listener executed while running main project (spring web) on tomcat7. got error java.net.bindexception: permission denied i have try use authbind ( http://java-notes.com/ ), problem not solved. had tried change port greater one, got error java.net.bindexception: cannot assign requested address this application/trap-receiver code: @component public class trapreceiver extends thread implements commandresponder { @inject private applicationcontext applicationcontext; @inject private executor executor; public trapreceiver(){ } list<pduv1> listpdu = new arraylist<pduv1>(); string message = ""; long totreceivedtrap = 0; @postconstruct public void init() { system.out.println("running trap listener"); this.start(); } public synchronized void processpdu(commandresponderevent cmdrespevent) { pduv1 pdu = (pduv1) cmdrespevent.getp

r - data.table fast acces to column by expression -

i trying column data.table given expression. receive caseid expression. expr_caseid <- expression(caseid) . how column expression in fastest possible way? library(data.table) dt_fcst <- data.table(caseid = as.integer(runif(1e8)*100)) expr_caseid <- expression(caseid) testexpr = function(dt_, expr_){ dt_[[deparse(substitute(expr_))]] } testgetelement = function(dt_, expr_){ getelement(dt_, deparse(substitute(expr_))) } library(microbenchmark) microbenchmark( ## by_char = dt_fcst[['caseid']], by_deparse = testexpr(dt_fcst, caseid), ## by_expr = dt_fcst[, list(caseid)], ## by_dollar = dt_fcst$caseid, by_eval = eval( expr_caseid, envir = as.environment(dt_fcst) ), by_getelement = testgetelement(dt_fcst, caseid) # ,by_index = dt_fcst@.data[[1]] , times = 1000l) results of performance measurements: unit: microseconds expr min lq mean median uq max neval cld by_deparse 37.2 41.35 55.0700

php - integrating xampp to run Java Bridge applications -

i installed php/java bridge , it's running in tomcat port 8080. when i'm running php files in tomcat, gives me many errors. errors not coming when run in xampp. possible run application in xampp , use java bridge? errors: warning: require_once( http://localhost:8080/javabridge/java/java.inc ): failed open stream: no suitable wrapper found in c:\xampp\xampp\xampp\htdocs\gg.php on line 1 fatal error: require_once(): failed opening required ' http://localhost:8080/javabridge/java/java.inc ' (include_path='.;c:\xampp\xampp\xampp\php\pear') in c:\xampp\xampp\xampp\htdocs\gg.php on line 1

ios - Autolayout with 3 labels equally width -

i need display 3 labels : "|-15-[label1]-0-[label2]-0-[label3]-15|".the label1,label2,label3 should have equal widths.how acthieve using autolayout coding.any suggestion appreciated. i've tried below,but couldn't see on headerview. nsdictionary *views2 = nsdictionaryofvariablebindings(label1, label2, label3); [headerview addconstraints:[nslayoutconstraint constraintswithvisualformat:@"h:|-leftpadding-[label1]-0-[label2]-0-[label3]-rightpadding-|" options:0 metrics:@{@"leftpadding":[nsnumber numberwithint:15],@"rightpadding":[nsnumber numberwithint:15]} views:views2]]; [headerview addconstraint:[nslayoutconstraint constraintwithitem:label1 attribute:nslayoutattributewidth relatedby:nslayoutrelationequal toitem:label2

ios - Only use Automatch in Gamecenter -

how remove invite friend button gkmatchmakerviewcontroller ? when printing of subviews in see navigation bar. i presenting this: gkmatchmakerviewcontroller *mmvc = [[gkmatchmakerviewcontroller alloc] initwithmatchrequest:request]; mmvc.matchmakerdelegate = self; [viewcontroller presentviewcontroller:mmvc animated:yes completion:nil]; unfortunately isn't possible, looked removing quick match button myself , found couldn't done. you can set own custom invite screen, check out 'implementing custom match user interface' section in 'real time matches' section of ios documentation. there many code examples show here i'll have supply description , link: https://developer.apple.com/library/ios/documentation/networkinginternet/conceptual/gamekit_guide/matchmaking/matchmaking.html description implementing complete custom match interface can simple displaying network progress indicator until auto-matching completes, or sophisticated

Using sqrt function in c++ -

so, using sqrt function in c++ , problem facing is, when input sqrt 40000000001 , returns 200000. #include <iostream> #include <cmath> using namespace std; int main (void) { long long int a; cin>>a; double b = sqrt(a); cout<<b<<"\n"; return 0; } why happening? it should return 200000.0000025 , need exact value. getting 200000 produces wrong answer. thanks! adding cout << "a=" << << endl; will reveal when enter 40000000001 value of a 46341. because represent 40000000001 in int you'll need 36 bits, while on platform, int has 32 bits (31 plus 1 sign). using long instead, 200000 result. the fact don't 200000.0000025 must have fact doubles have limited amount of precision. though wikipedia says 64 bit double has precision of typically 15-17 decimal digits , number looking has 13 significant digits, suspect there roundoff errors in intermediate steps of calculatio

php - Add Engraving options for products with different font in Magento -

i running e-commerce website on magento. add engraving option different font styles every product. similar like: http://www.knife-depot.com/knife-570711.html on “preview knife” can see product like. so, want know that, there inbuilt magento option available or how customize option every product. or, there magento extension available that.

c# - TextBoxInputMaskBehavior covers the value -

Image
i have textboxinputmaskbehavior ip address looks follow: , xaml code: <usercontrol x:class="customizing.views.iprangefields" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:ig="http://schemas.infragistics.com/xaml" xmlns:local="clr-namespace:customizing.views" xmlns:net="clr-namespace:system.net;assembly=system" xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:behaviors="clr-namespace:customizing.behaviors" xmlns:system="clr-namespace:system;assembly=mscorlib" mc:ignorable="d"

java - Using a local Repository in Maven for ElasticSearch -

when using elastic search, module compiles , runs properly. in pom.xml , have included following dependency, <dependency> <groupid>org.elasticsearch</groupid> <artifactid>elasticsearch</artifactid> <version>1.4.5</version> </dependency> but needed changes(implement timer in 1 of methods of es), forked code, made jar , saved in local repository:- mvn install:install-file -dfile=/users/mike/desktop/myelastic/elasticsearch/target/elasticsearch-1.4.6-snapshot.jar -dgroupid=org.elasticsearch -dartifactid=elasticsearch -dversion=1.4.6-snapshot -dpackaging=jar -dgeneratepom=true now trying use locally saved repository instead of remote repository. made following changes pom.xml <dependency> <groupid>org.elasticsearch</groupid> <artifactid>elasticsearch</artifactid> <version>1.4.6-snapshot</version> </dependency> but when compile module, strange error being th

tomcat - How to deploy a java web app to have a specific path? -

i have tomcat server , wrote simple java web app. when deploy on server, can access localhost:8080/myapp path. can change path localhost:8080/apps/myapp ? in server.xml change <context path="/myapp" .../>

linux - cannot delete /var/log/acpid file -

i owner of file, , have right permission think. why can't operations below: (i have delete it. / full.) [root@dbsvr log]# ll -ah acpid -rw-r----- 1 root root 84g jun 1 14:14 acpid [root@dbsvr ~]# rm -rf /var/log/acpid rm: cannot remove `/var/log/acpid': operation not permitted [root@dbsvr ~]# > /var/log/acpid -bash: /var/log/acpid: operation not permitted [root@dbsvr ~]# chmod 660 /var/log/acpid chmod: changing permissions of `/var/log/acpid': operation not permitted in order change permissions , / or delete file need write permissions parent directory of file. also, file's attributes might come play (see man chattr ). please note deleting file while process still has file open won't free disk space occupied file. case if remove example log file while syslogd still tries write it. edit: please explain downvotes?

javascript - How to get the difference of arrays in UnderscoreJS or angularJS -

i have 2 array of objects: 1) [{id:1}{id:2}{id:3}{id:4}{id:5}] 2) [{id:1}{id:2}{id:3}] is there in build function in underscorejs or angularjs give me output : [{id:4}{id:5}] i tried using _.difference , _.without not working work on simple arrays not on array of objects thanks in advance. function diff(a, b) { return _.filter(a, function(val) { return !_.findwhere(b, val); }); } diff[{id:1}, {id:2}, {id:3}, {id:4}, {id:5}], [{id:1}, {id:2}, {id:3}]); // [{id:4}, {id:5}] this solution specific data structure , not work any array of objects.

Avoid Google country specific redirect when searching in the url bar in Chrome -

this question has answer here: url www.google.com / google getting redirected different url www.google.co.in [closed] 1 answer i want avoid chrome redirecting me country specific landing page google whenever search through url bar. there setting this? can seem find setting home button / default page. can quite annoying when using vpn , need more english relevant search results. see this comment (and answers) also there way permanent solution (firefox on other hand needs a plugin ), see example here: http://dottech.org/158839/prevent-google-from-redirecting-you-to-its-local-homepage-tip/ (note, site claims trick works on firefox too, might outdated, google other solutions)

matlab - Problems with matrix indexing using for loop and if condition -

i indexing, follows: for c=1:size(params,1) d=1:size(data,2) if params(c,8)==1 value1(c,d)=data(params(c,11),d); elseif params(c,8)==2 value2(c,d)=data(params(c,11),d); elseif params(c,8)==3 value3(c,d)=data(params(c,11),d); end end end the problems if have params(:,8)=1,3,1,3,2,3,1... value1 contain zeros in rows 2, 4, 5, 6, etc. these rows not have 1 in column 8 in params . similarly, value2 contains zeros in rows 1, 2, 3, 4, 6, 7... , value3 contain zeros in row 1, 3, 5, 7, .... tell me how index don't have 'gaps' of zeros in between rows? thanks! edit; below sample dataset: data (1080x15 double) 168 432 45 86 170 437 54 82 163 423 52 83 178 434 50 84 177 444 42 87 177 444 58 85 175 447 48 77 184 451 59 86 168 455 52 104 174 437 62 88 175 443 55 85 179 456 51 92 168 450 73 82 175 454 60 68 params (72x12 double - interested in column 8 , 11 ) i'm showing co

jquery - jqgrid - Disable Header Check box (multiselect = true) if all rows are disable -

using jqgrid multiselect="true" option. disabling rows , prevent selection based on flag status mentioned below disable row(s) based on is_flagged = 1 //disable row flagged rowattr: function (item) { if (parseint(item.is_flagged) == 1) { return {"class": "ui-state-disabled ui-jqgrid-disablepointerevents"}; } }, //prevent selection of disabled rows beforeselectrow: function (rowid, e) { if ($(e.target).closest("tr.jqgrow").hasclass("ui-state-disabled")) { return false; // not allow select row } return true; // allow select row } to disable header checkbox, implemented below code, disables header check box if 1 row disabled. //disable header checkbox if rows disabled loadcomplete: function() { var grid = $("#grid"); var ids = gri

c - fwrite() not working to write integer in binary file -

can tell why won't function work? can't it... void writeregister(file *arq, book *l){ //writes in actual file position char c = '|'; int sizeregwrite = reglen(l); //reglen() returns size of book fwrite(&sizeregwrite, sizeof(int), 1, arq); fwrite(l->title, sizeof(char), strlen(l->title), arq); fwrite(&c, sizeof(char), 1, arq); //writing delimiter fwrite(l->author, sizeof(char), strlen(l->author), arq); fwrite(&c, sizeof(char), 1, arq); //writing delimiter fwrite(l->publisher, sizeof(char), strlen(l->publisher), arq); fwrite(&c, sizeof(char), 1, arq); //writing delimiter fwrite(l->year, sizeof(int), 1, arq); fwrite(&c, sizeof(char), 1, arq); //writing delimiter fwrite(l->language, sizeof(char), strlen(l->language), arq); fwrite(&c, sizeof(char), 1, arq); //writing delimiter fwrite(l->pages, sizeof(int), 1, arq); fwrite(&c, sizeof(char), 1, arq); //writing delimiter fwri

Windows bat file remove all file and folder excluding some file and folder -

Image
i want delete files , folder in directory excluding file , folder in bat file. i need keep these file, update.bat foldername.zip foldername , other should deleted directory, i wrote .bat file seems foldername deleted directory, rest working fine. can tell wrong below script? attrib +r update.bat attrib +r foldername.zip attrib +r foldername /f "delims=" %%i in ('dir /b') (rmdir "%%i" /s/q || del "%%i" /s/q) attrib -r update.bat attrib -r foldername.zip attrib -r foldername thanks haris you misunderstanding how "read only" works folders in windows. it's not fault. it's misleading label. "read only" on folder makes files within folder read only, but not folder itself . note setting folder read-only makes files in folder read-only. not affect folder itself. my apologies quoting vista documentation, wasn't able find similar page folders windows 7. mentioned in ui though: ho

ubuntu - Cannot connect to svn server via Tortoise -

Image
i have run svn server on ubuntu server , created repository following tutorial: http://odyniec.net/articles/ubuntu-subversion-server/ i tried checkout repository follows: $ svn checkout file:///usr/local/svn/repos/test checked out revision 0. it works , got above message cannot access svn repository via tortoisesvn on windows , error bellow occurred while trying access: it sounds svn server not listen port 3690! is blocking port 3690? that's port svnserve uses default. i had firewall blocking it. so, disabled , called svnserve "--listen-host 0.0.0.0" , worked fine.

sql - Adding values between range of values in SSRS -

i creating ssrs report , having 1 dimension table , contain 1 field "no_of_stories" , 1 fact table column "total_tiv" . want output in following format. range | tiv 1 | 1000 2 3 | 20000 4 7 | 30000 is there method solve using sql query or there expression in ssrs resolve ? select case when no_of_stories = 1 '1' when no_of_stories >= 2 , no_of_stories < 4 '2 3' when no_of_stories >= 4 , no_of_stories < 8 '4 7' -- add other ranges here else 'more 7' -- or whatever maximum range end range, sum(tiv) total_tiv mytable group case when no_of_stories = 1 '1' when no_of_stories >= 2 , no_of_stories < 4 '2 3' when no_of_stories >= 4 , no_of_stories < 8 '4 7' -- add other ranges here else 'more 7' -- or whatever maximum range end order max(no_of_stories)

How To Remove Quotes From String in Python -

currently have list of strings, lets say: list1 = [1,2,3,4] i want convert list of numbers corresponding letters, using: output = [chr(ord((str(x+96)))) x in list1] when this, error saying program expects string length of one, in code gives string length of 3 because of '' around each number after converted string. conversion string necessary because has in string format in order ord work. so question guys how can fix and/or rid of these quotes? in case wondering, supposed come out as output = [a,b,c,d] printing list prints string representation of elements includes single quotes around string elements inside list. instead format string yourself: >>> '[{}]'.format(','.join([chr((x+96)) x in list1])) '[a,b,c,d]' or in printed form: >>> print '[{}]'.format(','.join([chr((x+96)) x in list1])) [a,b,c,d] the format method allows format string. in case, curly braces used placeholder value

constructor - Retrieving filename used to create Bitmap object (C#) -

is there method/property can obtain filename used create bitmap object? for instance if bitmap created somewhere in main code passed method bitmap myimage = new bitmap("c:\\images\\myimage.bmp"); mymethod(myimage); how mymethod determine name of file used create myimage public void mymethod(bitmap myimage) { string imagefilename = // put here? } just clear value of imagefilename in mymethod should "c:\\images\\myimage.bmp". avoid creating global variable. thanks. you can't original file name bitmap object. since bitmap class sealed , can't derive it. create own wrapper class , hold bitmap member: class mybitmap { bitmap thebitmap; public mybitmap (string image) { imagefilename = image; //remember later. thebitmap = new bitmap(image); } public string imagefilename {get; set;} } then pass mybitmap instance mymethod , can file name easily. if need access properties of contained bitmap have create acces

c - How can I print a date using the current locale settings? -

i'm trying write c program on linux prints current date. here in brazil want print in dd/mm/yyyy format , in print in mm/dd/yyyy format. i thought "%x" specifier strftime supposed trick printing in mm/dd/yyyy format. #include <stdio.h> #include <time.h> int main(){ struct tm local_now; { time_t now; time(&now); struct tm *tmp = localtime(&now); local_now = *tmp; } char buf[20]; strftime(buf, sizeof buf, "%x", &local_now); printf("%s\n", buf); return 0; } and here output running locale command: lang=en_us.utf-8 language=en_us lc_ctype="en_us.utf-8" lc_numeric=pt_br.utf-8 lc_time=pt_br.utf-8 lc_collate="en_us.utf-8" lc_monetary=pt_br.utf-8 lc_messages="en_us.utf-8" lc_paper=pt_br.utf-8 lc_name=pt_br.utf-8 lc_address=pt_br.utf-8 lc_telephone=pt_br.utf-8 lc_measurement=pt_br.utf-8 lc_identification=pt_br.utf-8 lc_all= apparently lc_time=pt_br.utf-8 se

java - From Json To ViewPager -

i'm trying pass data json file viewpager. have followed of advice given me here returns blank, without crashing. the 4 files involved in this: 1. main fragment: public class fashionfeed extends fragment { viewpager viewpager; pageradapter adapter; thepageradapter newdapter; public static final string url = "http://celebirious.com/bey/data/space.json"; @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view v = inflater.inflate(r.layout.fragment_whats_hot, null); // locate viewpager in viewpager_main.xml viewpager = (viewpager) v.findviewbyid(r.id.pager); viewpager.setcliptopadding(false); viewpager.setpadding(4, 0, 4, 0); int margin = (int) typedvalue.applydimension(typedvalue.complex_unit_dip, 20 * 2, getresources().getdisplaymetrics()); viewpager.setpagemargin(-margin); new simpletask().execute(url); return v; } p

indentation - How I can indent generated java code java? -

i work in small learning program generates java code picture. hold code in stringbuilder. wonder can give text normal java code indentation. use library, not format source code, string has generated java code. attention. how following code: import java.io.bytearrayinputstream; import com.github.javaparser.javaparser; import com.github.javaparser.parseexception; import com.github.javaparser.ast.compilationunit; public static void main(string[] args) throws parseexception { string java = new string("public class thisisanonwellformattedjavaclass {public static void main(string[] args){}}"); compilationunit cu = javaparser.parse(new bytearrayinputstream(java.getbytes())); system.out.println(cu.tostring()); } it uses great java parser library called javaparser

Join predicates in Prolog with different size -

i'm trying write program swi-prolog. have predicate converts english words spanish. listtran([],[]). listtran([head|tail],[trans|spanish]) :- diccionario(head,trans), listtran(tail,spanish). and have predicate verifies sentence structure. sentence(w1,w2,w3) :- word(noun,w1), word(verb,w2), word(adjective,w3). now want join them in same predicate, ideas? translatedsentence(w1,w2,w3) :- sentence(v1,v2,v3), listtran([v1,v2,v3], [w1,w2,w3]).

c# - Owin OAuth localhost/Token returns 404 -

firstly, works when run visual studio using iis express . i have asp.net web api running owin oauth. configuration part of startup class: private static void configureauth(iappbuilder app) { var oauthoptions = new oauthauthorizationserveroptions { #if debug allowinsecurehttp = true, #endif tokenendpointpath = new pathstring("/token"), accesstokenexpiretimespan = timespan.fromdays(30), provider = new applicationoauthprovider() }; app.useoauthauthorizationserver(oauthoptions); app.useoauthbearerauthentication(new oauthbearerauthenticationoptions()); } this register part of webapiconfig.cs public static void register(httpconfiguration config) { // web api configuration , services config.suppressdefaulthostauthentication(); config.filters.add(new hostauthenticationfilter(oauthdefaults.authenticationtype)); var cors = new enablecorsattribute("*", "*", "*");

Simple Matlab/Simulink Model, adding 2 signals -

Image
i have created simple simulink model adds 2 signals: the code control model following: clear x y result data=ones(1,5); x=timeseries(data); y=timeseries(data); output = sim('model_test','stoptime',stop_time); result = output.get('res'); obviously, wish following result, matrix containing [2 2 2 2 2]. however, result looks this: result 1x1x27 double , not 1x5 double hoped for. know have change? code wrong or have change settings in simulink model? thank in advance! the problem how constructing input data. the syntax using timeseries constructs x , y such have scalar value of 2 @ time equal 0,1,2,3 , 4 seconds. can see looking @ x.time , x.data . from expecting looks wanting define them being 5 element vectors @ each time step. involve using >> x = timeseries(ones(1,5),0); or similar depending on how many time points want define. above defines data @ time = 0 seconds. again, @ variable in matlab workspace confirm this. (

plot - How to make 3D histogram in R -

Image
this goal: plot frequency of y according x in z axis. these problems: have 2 columns array ( x , y ) , need divide x classes (p.ex. 0.2 ou 0.5) , calculate frequency of y each class of x . plot should appear x-y plot in "ground" plan , frequency in z axis. surface or 3d histogram. tried make using hist3d function of plot3d package don't know doing wrong. this example of trying do: https://www.safaribooksonline.com/library/view/r-data-visualization/9781783989508/ch06s05.html thanks!! using simulated data, should want. key have create bivariate bins, accomplished using cut() function. treating binned factors levels can count combinations of each factor level using table() function below: library(plot3d) ## simulate data: set.seed(2002) x <- rnorm(1000) y <- rnorm(1000) ## create cuts: x_c <- cut(x, 20) y_c <- cut(y, 20) ## calculate joint counts @ cut levels: z <- table(x_c, y_c) ## plot 3d histogram: hist3d(z=z, bo

loops - Android SQLite Display all records in Listview -

i have been on weekend , im @ wits end how return records in query listview the following code works perfectly public void displaycontact(string sitename) { final dbadapter db = new dbadapter(this); db.open(); cursor c = db.getasset6(sitename); int mx=0; string[] lvdata = new string[c.getcount()-1]; while (c.movetonext()) { lvdata[mx]=c.getstring(2) + "-" + c.getstring(1) + "-" + c.getstring(6); mx++; } getactionbar().settitle("number of records = " + mx); arrayadapter<string> adapter = new arrayadapter<string>(this, r.layout.rowlayout, r.id.label, lvdata); setlistadapter(adapter); } public cursor getasset6(string strname) throws sqlexception { cursor mcursor = db.query(true, database_table, new string[] {key_rowid,key_faultref,key_worknum,key_orignum,key_repby,key_repdattim,key_description}, key_repby + " ?", new string[] { &qu

ios - Program skips NSURLRequest used to download txt file, if placed in IB action with other code -

i using nsurl request in objective -c in order download webpage , place in text file. similar curl function used in unix. here code: nsstring *documentdir = [nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes) firstobject]; nsstring *filepath = [documentdir stringbyappendingpathcomponent:@"data.txt"]; nsurlrequest *request = [nsurlrequest requestwithurl:[nsurl urlwithstring:@"https://ca.finance.yahoo.com/q?s=jnj"]]; [nsurlconnection sendasynchronousrequest:request queue:[nsoperationqueue currentqueue] completionhandler:^(nsurlresponse *response, nsdata *data, nserror *error) { if (error) { nslog(@"download error:%@",error.description); } if (data) { [data writetofile:filepath atomically:yes]; nslog(@"file saved %@",filepath); } }]; i finding if execute code in own ib action (no other code) linked test button working no