Posts

Showing posts from August, 2014

Why isn't my JavaScript function able to access global-scope functions/variables defined in my other .js files? -

i wrote script that: ns.load = function(src) { var script = document.createelement("script").setattribute("src", src); document.getelementsbytagname("head")[0].appendchild(script); } it loads files can't reach functions , variables defiened in other files. //js/main.js var qux = {name: "name"}; ns.load("js/foo.js"); //js/foo.js alert(qux.name); //undefined variable but if define qux this: window.qux = {name: "name"}; i can reach qux variable in other modules. far know globals member of window object. why have define variables this. offer method? thanks. it looks tried shortcut code calling createelement , setattribute on 1 line, setattribute doesn't return anything, can't go calling appendchild on it's return value, because there none.this fix it: ns.load = function(src) { var script = document.createelement("script"); script.setattribute("src...

iphone - presentModalViewController not working? -

i coded in button action like [uiview beginanimations:nil context:null]; [uiview setanimationduration:1.0]; [uiview setanimationtransition:uiviewanimationtransitionflipfromright forview:maindelegate.window cache:no]; [maindelegate.window addsubview:[self.calcentrycontroller view]]; [uiview commitanimations]; it works fine,but when use in calcentrycontroller.m in 1 action [self presentmodalviewcontroller:self.weeklyscorecontroller animated:yes]; to go viewcontroller , not working pls? is there reason aren't using presentmodalviewcontroller calcentrycontroller ? can set modaltransitionstyle on calcentrycontroller uimodaltransitionstylefliphorizontal , use presentmodalviewcontroller:animated instead of doing manual animations. the reason may because code not calling functions viewwillappear: , viewdidappear: , etc., whereas presentmodalviewcontroller:animated calls right functions presenting new views.

android - Cursor go to first place after period operator(.) in EditText -

hi using edittext in app.when enter .(period ) after cursor go first position in edittext.but want display characters after . when enter . can give me suggestions. , want enter numbers in edittext if no character displayed when type special character keyboard can do? give me suggestions .thanks in advance you should take textwatcher

c++ - What is the meaning of "difference of memory address?" -

consider #include <cstdio> int main() { char a[10]; char *begin = &a[0]; char *end = &a[9]; int = end - begin; printf("%i\n", i); getchar(); } #include <cstdio> int main() { int a[10]; int *begin = &a[0]; int *end = &a[9]; int = end - begin; printf("%i\n", i); getchar(); } #include <cstdio> int main() { double a[10]; double *begin = &a[0]; double *end = &a[9]; int = end - begin; printf("%i\n", i); getchar(); } all above 3 examples print 9 may know, how should interpret meaning of 9. mean? the compiler automatically calculate pointer arithmetic based on type of pointer, why cant perform operation using void* (no type information) or mixed pointer type (ambiguous type). in msvc2008 (and in other compiler believe), syntax interpreted calculate amount of element difference between 2 pointer. int = end - begin; 004...

c# - Why isn't my Route.Ignore working on this static file in my ASP.NET MVC application? -

Image
background i have pdf file located (under project) in assets > documents folder: when application gets deployed, gets deployed particular folder on domain. example, http://www.domain.com/myappfolder . want able access pdf file linking http://www.domain.com/myappfolder/assets/documents/eztrac_userguide_newsys.pdf problem i can't seem routing correct this, keeps trying route request controller. here modification made routing: routes.ignoreroute("myappfolder/assets/documents/eztrac_userguide_newsys.pdf"); but result get: the icontrollerfactory 'eztrac.dependencyresolution.controllerfactory' did not return controller controller named 'assets'. try removing myappfolder routes. routes.ignoreroute("assets/documents/eztrac_userguide_newsys.pdf");

java - How to detect links in a text? -

greetings have text may contain links like: " hello..... visit on http://www.google.com.eg , , more info, please contact on http://www.myweb.com/help " and want find , replace link following link anyone knows how ? and have question how website stackoverflow detects links in posts 1 , highlights them 1 can click them , visit link? using java.util.regex can urls finding matches regexp: https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\s+)?)?)? . import java.util.regex.*; pattern pattern = pattern.compile("https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\s+)?)?)?", pattern.case_insensitive | pattern.dotall | pattern.multiline); matcher mymatcher = pattern.matcher(mystringwithurls); while (mymatcher.find()) { ... }

meta tags - how to know the currently online user in .net -

i want know online users using website. know can using session variables not working. when user logs in, write database. if using asp.net membership provider, info written in aspnet_users table. can query database check logged in users.

actionscript 3 - Flex 3: Determine if scroll panel child is visible -

let's have canvas fixed height , vertical scroll bar. , canvas has 10 children in vertical line (like vbox) combined height exceeds height of canvas. based on scroll bar position, of children visible @ time. is possible determine children visible? or whether or not specific child visible on screen? i’m not sure on timeliness of answer, had similar question , following code worked me: if (item.y < container.verticalscrollposition || item.y + item.height - container.verticalscrollposition > container.height) { // item not (completely) visible } basically checking against following criteria: 1) item’s y position above container’s current vertical scroll position (i.e. outside of container’s top boundary)? 2) item’s bottom position scrolled outside of container’s bottom boundary? calculated using item’s bottom position (i.e. item’s y position plus height) minus current vertical scroll position. if want check of items in container, you’d have loop ...

arrays - php recursion level -

i have recursion function. there hierarchy users structure. send user id function , should find user under this. function returns array of associates users. task find levels of users. for example: user1 / \ user2 user3 / \ \ user4 user5 user6 user1 have level 0. user2, user3 have level 1. user4, user5, user6 have level 2. how can find in recursion? code: private function getassociates($userid) { global $generation; global $usersunder; if (!isset($generation)) { $generation = 1; } $userdb = new lyf_db_table('user'); $associatesselect = $userdb->select(); $associatesselect -> from('user', array('id'))->where('enroller_id = ?', $userid); $associates = $userdb->fetchall($associatesselect)->toarray(); if (!empty($associates)) { foreach ($associates $associate) { $usersunder[$generation] = $associ...

c# - why won't WebProxy BypassProxyOnLocal work for me? -

i'm trying http calls i'm making c# .net local address (localhost:3000) use proxy set (so can go through fiddler). using below webproxy approach works if point target url non-local address, need point local web-server have (at localhost:3000), , when request not going through proxy. i have inlcuded "proxyobject.bypassproxyonlocal = false". should make work no? suggestions re how force request go through webproxy http calls targetting local address? webproxy proxyobject = new webproxy("http://localhost:8888/", false); proxyobject.credentials = new networkcredential(); proxyobject.bypassproxyonlocal = false; webrequest.defaultwebproxy = proxyobject; var request = (httpwebrequest)webrequest.create(targeturi); // included line double check request.proxy = proxyobject; subsequent calls not go through proxy however, such when do: var res = (httpwebresponse)req.getresponse(); thanks i around appending "...

How to catch an exception in python and get a reference to the exception, WITHOUT knowing the type? -

i'm wondering how can catch any raised object (i.e. type not extend exception ), , still reference it. i came across desire when using jython. when calling java method, if method raises exception, not extend python's exception class, block not catch it: try: # call java lib raises exception here except exception, e: # never entered i can this, have no access exception object raised. try: # call java lib raises exception here except: # enter here, there's no reference exception raised i can solve importing java exception type , catching explicitly, makes difficult/impossible write generic exception handling wrappers/decorators. is there way catch arbitrary exception , still reference in except block? i should note i'm hoping exception handling decorator making usable python projects, not jython projects. i'd avoid importing java.lang.exception because makes jython-only. example, figure can (but haven't tried it), i'd...

php - Mysql - Simple select query returns dublicate values? -

this how query looks like: (simplified) select * posts user='37' order date desc i ave 1 row in table, still reason returns 2 rows same. @ first thought messed loop, tried printing returned array out print_r() , returns 2 rows. i tried searching, didn't find similar issues. remember friend of mine had same issue @ school, i'm sure aint ones. didn't use right search terms, heh. any ideas? are sure have 1 row in table? if so, seems problem must happening outside of sql. what doing outside of query? seems source of issue. mention loop: adding query result array twice? or array persisting between calls without being reinitialized (in other words, result of previous query remaining in array when don't expect to)?

c# - I want my memory back! How can I truly dispose a control? -

i have application making creates large number of windows controls (buttons , labels etc). being made dynamically through functions. problem i'm having is, when remove controls , dispose them, not removed memory. void loadaloadofstuff() { while(tabcontroltoclear.controls.count > 0) tabcontroltoclear.controls[0].dispose(); //i put in: gc.collect(); gc.waitforpendingfinalizers(); foreach(string pagename in globallist) tabcontroltoclear.controls.add(makeatab(pagename)); } tabpage makeatab(string tabtext) { tabpage newt = new makeatab(); newt.text = tabtext; //fill page controls methods return newt; } now reason, ain't giving me memory back, when process runs 5 times, end out of memory violation. new object , control disposal looking through vast net still hasn't given me indications, if of have idea, i'd grateful hear it. update: i've been watching user objects creation , destruction (taskmanager) , noti...

active directory - How to use Python to get local admins from a computer on the Network? -

i need list of people in company have local admin rights on computers. have group on each machine called "administrators." can list of computers active directory with: import active_directory computer in active_directory.search ("objectcategory='computer'"): print computer.displayname now think need take each computer name , feed in. thinking maybe reading remote registry on each computer , looking sid -- supposedly sid 's-1-5-domain-500' give me list of people on computer local admins. did: import _winreg computer_name = "fakecomputername" key_path = r"system\currentcontrolset\control\computername\computername" hklm_remote = _winreg.connectregistry (r"\\%s" % computer_name, _winreg.hkey_local_machine) hkeyremote = _winreg.openkey (hklm_remote, key_path, 0, _winreg.key_read) value, type = _winreg.queryvalueex (hkeyremote, "computername") print "remote computer name is", value remote compu...

python - Django, where to import your modules -

i thought ok import of modules @ top of view file. if ever change model name can edit import @ top , not go digging through every view function need imported in. well, ran instance had imported model @ top of view file, , used in function, reason django threw unbound variable error when tried use model query, leads me believe need imports each function? so, question is, proper way it? import @ top of file or in each function needed. thanks there no requirement in django import modules @ function scope. can, true of python generally. i'd see code , error message. don't think problem due cause attribute to.

c# - Using a WCF Service with Complex Data Types -

i'm trying pass dto 1 navidation property ienumerable<> inside of it, when pass object without child lists works well, but, when i'm passing objects childs , grandchilds wcf services not respond , gives me no error. have make work type of object specificly? here's data contract [servicecontract] public interface iprodutoservice { [operationcontract] categoriaresponse getcategoria(categoriarequest request); [operationcontract] produtoresponse getproduto(produtorequest request); [operationcontract] categoriaresponse managecategoria(categoriarequest request); [operationcontract] produtoresponse manageproduto(produtorequest request); } //and dto class public class produtodto { #region primitive properties [datamember] public int32 codigo { get; set; } [datamember] public int32 codigocategori...

Netbeans C/C++ JavaDoc code-completion -

i developing c++ in netbeans 6.7.1. when press ctrl + space autocomplete there shown method's signature. using javadoc commenting code netbeans doesn't show it. have installed doxygen plugin generating complete documentation. is there way how force ide show signature , javadoc c++ please? i think should not problem because functionality implemented java. thanks lot. so asked on netbeans forum question ( using friend's account because don't have own ) , there conclusion: impossible , in requests.

c# - How to receive Plug & Play device notifications without a windows form -

i trying write class library can catch windows messages notify me if device has been attached or removed. normally, in windows forms app override wndproc method there not wndproc method in case. there way can messages? you'll need window, there's no way around that. here's sample implementation. implement event handler devicechangenotifier.devicenotify event notifications. call devicechangenotifier.start() method @ start of program. call devicechangenotifier.stop() @ end of program. beware devicenotify event raised on background thread, sure lock needed keep code thread-safe. using system; using system.windows.forms; using system.threading; class devicechangenotifier : form { public delegate void devicenotifydelegate(message msg); public static event devicenotifydelegate devicenotify; private static devicechangenotifier minstance; public static void start() { thread t = new thread(runform); t.setapartmentstate(apartmentstate.sta); t...

c# - Determine Declaring Order of Python/IronPython Functions -

i'm trying take python class (in ironpython), apply data , display in grid. results of functions become columns on grid, , order of functions order of columns. there way determine order of python functions of class in order declared in source code? i'll take answers use either ironpython or regular python. so instance, if have class: class foo: def c(self): return 3 def a(self): return 2 def b(self): return 1 i (without parsing source code myself) list of [c, a, b] . ideas? as caveat, ironpython used keep references of functions in order declared them. in .net 4, changed behavior match python (which lists them in alphabetical order). in python 2.x (ironpython on python 2) answer unfortunately no. python builds dictionary of class members before creating class object. once class created there no 'record' of order . in python 3 metaclasses (which used create classes) improved , can use custom object instead o...

mysql - Find avg of rating for each item -

i have table feilds : file_id, rating, user_id there 1 rating per user_id, there many rating (in scale of 0-5) single file_id. i want find avg of ratings every file_id , display 5 file_id highest avg rating. actually sql query looks like: select m.server_domain, m.original_name, m.type, m.title, m.views, m.description, m.hash, avg(mr.rating_scale5) avg_rating_scale5 c7_media m, c7_storage s, c7_media_ratings mr s.public=1 , m.storage_hash = s.hash , m.hash = mr.media_hash group mr.media_hash how should this? zeeshan group file_id , order average. cut off records fall below top 5. select file_id, avg(rating) avg_rating table group file_id order avg_rating desc limit 5

java - The Jar of this class file blongs to container Android 2.0.1 which does not allow modifications -

Image
can 1 provide me solution error have searched alot problem failed i using eclipse adt with android sdk 2.0.1 os microsoft windows vista x86 does article "making eclipse show android’s source" (from malcolm rowe) help ? (for sdk1.5, adapt 2.0) once have source jar, you’d expect attach directly library in eclipse, doesn’t work android sdk. eclipse says: “the jar of class file belongs container ‘android 1.5’ not allow modifications source attachments on entries.” which roundabout way of saying source path fixed. if open eclipse project properties dialog, change java build path page , libraries tab, expand ‘ android 1.5 ’ library container , android.jar file (phew!), you’ll see ‘ source attachment ’ option, shows source expected be. for android 1.5 sdk, sdk location/platforms/android-1.5/sources (and presumably android 1.1 target), sdk location path set in ‘ workspace preferences ’ android page. note 1.0 sdk (which supp...

catching exceptions in Javascript thrown from ActiveX control written in C++ -

i've written activex control in c++ throws (c++) exceptions out when error conditions occur within control. javascript code invokes object representing instance of control surrounded try - catch block: try { var controlinstance = window.controlinstance; ... perform operations on controlinstance ... } catch (e) { alert("something bad happened"); } now, when run code under ie8 (or 7 or 6) visual studio (2008) debugger attached it, works expected - whether control compiled or without debug on. however, when running browser without debugger attached, ie crashes (really) when exception crosses boundary between control , jscript. does have suggestions around how solve problem? realize can change control's interface pass exception argument rather not make such change. any appreciated. you need atlreporterror . throws javascript exception description string: stdmethodimp cmyctrl::mymethod() { ... if (bsucceeded) return s_ok; ...

How can I build Qt Application in Qt creator with static links on Windows with VS2008 runtime? -

i have downloaded qt-win-opensource-4.7.0-vs2008.exe nokia site , use when build application. application realy use vs2008 runtime not mingw, has dynamic linkage qtcore4.dll , others qt libs. how can create application static linkage qt libs? you must build static version of qt. see http://doc.qt.io/archives/qt-4.7/deployment-windows.html

objective c - Exception handling in iphone -

hi new programmer.. presently working on iphone.... i know in iphone device if application encounters error iphone os closes automatically. other exceptions can handled user enterance of numbers, check internet connection ..and many more my question why exception handling required? because know app close surely... is tell user why app closed? i need help... know stupid type question but....? please answer whatever want....comments accepted also(good or bad both)... thank you. because not expected. if users in application , doing , suddenly, forced quit, feel frustruated. telling them reason app closed has no use. users not understand , not care it. apple wants keep user experience time apps in app store. reason have restricted process see if app gives ux or not

mysql - mysql_real_escape_string ISSUE -

if type ' into search bar mysql error "sting" has not been escaped- think. but reason why cant escape because dont think string. the search box generates search results dynamically ajax type , finds results error: have error in sql syntax; check manual corresponds mysql server version right syntax use near '%' or location '%'%' or map '%'%' limit 0, 16' @ line 2 this mysql query: <?php if($_post['q']!=""){ include $_server['document_root'] . "/include/datebasecon.php"; $result = mysql_query(" select id, name, location, map accommodation name '%".$_post['q']."%' or location '%".$_post['q']."%' or map '%".$_post['q']."%' limit 0, 16") or die(mysql_error()); $output = ""; while($row = mysql_fetch_array($result)){ ...

SQL Server Cell Level Encryption -

i want implement cell level encryption , users odbc able connect database , use it. what suggest it? is possible? if yes, resource, source code, samples, documentations on it? if it's not possible, please tell me why. thank you! kind regards sql server can control encrypting column - can read how here . a "cell" excel/spreadsheet terminology; encrypting column value specific row have encrypted prior being inserted or updated. if after, need @ using these functions when adding/updating data: encryptbykey decryptbykey

java - Store and retrieve word documents with MySQL -

i need store , retrieve ms word documents mysql 5.1 servlets. i've code upload file, don't know can feed table. i've used blob field i've insert .doc files. here's code snippet upload files: protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { response.setcontenttype("text/html;charset=utf-8"); printwriter out = response.getwriter(); try { // access file uploaded client part p1 = request.getpart("file"); string type=p1.getcontenttype(); string name=p1.getname(); long size = p1.getsize(); inputstream = p1.getinputstream(); //fileinputstream fis = is. // read filename sent part part p2 = request.getpart("name"); scanner s = new scanner(p2.getinputstream()); string filename = s.nextline(); // read filename stream // filename use on server string o...

How can I store PHP code inside of a mysql table -

i working on building small php/mysql script act wordpress blog small site eyes store php code snippets. have categories , pages sample code write javascript syntax highlighter. instead of storing php code snippets in file wanting save them mysql db. best way save php mysql , out of mysql show on page? my end result this alt text http://img2.pict.com/c1/c4/69/2516419/0/800/screenshot2b193.png update: i wasn't sure if needed special code before sending mysql since has different kinds of characters in it if you're not using kind of database abstraction layer, call mysql_real_escape_string on text.

java - For some reason JSP documents output XML instead of HTML -

ok, trying set simple jsf application. i'm using netbeans 6.8, glassfishv3 , maven2. made jsp document so: <?xml version="1.0" encoding="utf-8"?> <html xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html"> <f:view> <head> <title><h:outputtext value="#{welcome.title}"/></title> </head> <body> <h:outputtext value="welcome"/> </body> </f:view> </html> problem is, if navigate page ( http://myhost/myapp/faces/welcome.jspx ), returned xml document, ${welcome.title} value populated: <?xml version="1.0" encoding="utf-8"?> <html><head><title>gymix - welcome</title></head><body>welcome</body></html> in internet explorer looks have opened xml document. in google chrome title printed next text welcome , instead...

vb.net - Receiving 'The input is not a complete block' error, tried everything I can find on google. Rjindael Encryption in .NET -

mornin', i'm trying basic encryption working using system.security.cryptography.rjindaelmanaged. have google error , cannot find problem, or doing wrong. attempting encrypt string, , decrypt string. following code, , appreciated. imports system.security.cryptography imports system.text public rj new rijndaelmanaged try rj.padding = paddingmode.none rj.generatekey() rj.generateiv() dim curprovider new aescryptoserviceprovider dim curencryptor icryptotransform dim memencstream new memorystream dim cryptoencstream cryptostream curencryptor = curprovider.createencryptor(rj.key, rj.iv) cryptoencstream = new cryptostream(memencstream, curencryptor, cryptostreammode.write) dim startingbytes() byte = encoding.ascii.getbytes("this test") debug.print("before length: " & startingbytes.length) debug.print("before text: " & encoding.ascii.getstrin...

orm - How to make an optimal hibernate query with three objects? -

i have query don't know how make optimal. have 3 objects. scp question : has field points scp (scp_id) answer : has field points question (question_id) how can make query counts number of answer within given scp what this: select count(a) answer a.question.scp.id = :id which generates following sql: select count(answer0_.id) col_0_0_ answer answer0_, question question1_ answer0_.question_id=question1_.id , question1_.scp_id=? seems pretty efficient.

iphone - NSTimeInterval memory leak -

i have weird memory leak nstimeintervall , nsdate. here code: nstimeinterval interval = 60*60*[[[config alloc] getcachelifetime] integervalue]; nsdate *maxcacheage = [[nsdate alloc] initwithtimeintervalsincenow:-interval]; if ([date compare:maxcacheage] == nsordereddescending) { return yes; } else { return no; } date nsdate object, should fine. instruments tells me "interval" leaks, yet not quite understand this, how can release non-object? function ends after code snippet posted here, understanding interval should automatically deallocated then. thanks lot! it telling leak happening on line. the expression [[[config alloc] getcachelifetime] integervalue] problem. first of all, care creating object (calling alloc ) lose reference before calling release or autorelease , leaking. also, ought call init method after allocating object. if config class doesn't special, nsobject 's init method need called. if replace line with confi...

c# - Custom Asymmetric Cryptography Algorithm -

i want use asymmetric cryptography algorithm, need have short key size(not rsa @ least 384). need around 20. possible? there several ways have short key size. 1. rsa a rsa public key consists in big number n (the "modulus") , (usually small) number e (the public exponent). e can small 3, , in closed setup (where control key generation) can force use of conventional e , same everybody. typical size n 1024 bits (i.e. 128 bytes). n product of 2 prime numbers ( n = p*q ). knowledge of p , q sufficient rebuild private key (nominally value d multiplicative inverse of e modulo p-1 , q-1 ). assuming n known, knowledge of p alone sufficient (if know n , p , can compute q simple division). proper security, p , q should have similar sizes, taking smaller of two, still need store 512 bits or -- that's 64 bytes). it has been suggested select small d (the "private exponent"). makes e random, hence large; can no longer use conventional sm...

how to call alert box using jsp -

i facing problem while calling alert box. can know procedure call box in jsp? my function is <script type="text/javascript" src="js/ufo.js"></script> <script type="text/javascript"> function foon() { alert("sorry! not valid user!! click here go login!!!"); history.back(1); } </script> now how call foon() function inside if statement? probably want like: <c:if test="something"><script type="text/javascript">foon()</script></c:if> alternately embed alert right there, depends on need reuse.

language agnostic - Delete and return in a single verb? -

imagine function deletes cookie , returns value. what call if have use single verb? i called clear i'm not fond of name. it sounds similar pop , except pop typically acts on last element in collection. perhaps extract suitable name?

ruby on rails - Capistrano does not copy Gemfile using SVN -

gemfile checked in repo , server able checkout rails application gemfile in right place (rails.root). when run 'cap deploy' capistrano copies except gemfile, bundler error 'could not locate gemfile'. whey svn able checkout gemfile , capistrano not? i not able see output of svn executed on server capistrano. my capistrano version is: capistrano v2.5.19

java - Why is a junit test that is skipped because of an assumption failure is not reported as skipped? -

i use junit assumptions decide whether run test or not. tests assumption fails ignored/skipped junit framework. i wonder why skipped tests not reported 'skipped'? please have @ example: import static org.junit.assert.fail; import org.junit.assume; import org.junit.test; public class assumptiontest { @test public void skipassumptionfailuretest() { assume.assumetrue("foo".equals("bar")); fail("this should not reached!"); } } running test in maven project results in: running assumptiontest tests run: 1, failures: 0, errors: 0, skipped: 0, time elapsed: 0.015 sec i prefer have test reported 'skipped'. there chance achieve this? (junit 4.8.1; maven 2.2.1; java 1.6.0_21) you can't out-of-the-box way skip tests @ignore annotation. however, found blog post might looking for:

shell - Using nohup or setsid in PHP as Fast CGI -

i'm trying potentially long background process in response incoming ajax request, using nohup or setsid via shell_exec causes server fork bomb. use suexec , fastcgi, , when bombs took entire server crawl. shell_exec("nohup /home/me/myscript.php"); the script doesn't lengthy right now, outputs non-existant file (which never happens, because blows first) thanks! i've seen warnings @ http://php.net/manual/en/intro.pcntl.php (although you're using nohup , knoẁ) warning forking webserver processes not safe way go. if background process needs starting, i'll create daemon / running job process can receive such requests (and hasn't got webserver), forks/nohups @ will.

ruby on rails - if a value from controller is nil, how do I display 0? -

i creating report looks number of emails sent during period of time: i display in view follows: <td><%= @emails_sent.size %></td> and generated in controller follows: @sent_emails = contactemail.all(:conditions => ['date_sent >= ? , date_sent <= ?', @monday, @friday]) but emails have been sent, makes nil, causes view bonk. what way address "nil" when .find method comes nothing goes 0 instead of thinking 'nil? when using @neutrino solution might give error (if select null) in view call <%= @emails_sent.size %> reason if selection nil, returns '0' , in view expecting array you have 2 options 1 - modify @neutrino code slightly @sent_emails = contactemail.all(:conditions => ['date_sent >= ? , date_sent <= ?', @monday, @friday]) || [] ** note [] instead of 0 2 - count sql , rid of .size in view cheers sameera update - changed array.new [] #thanks @gertas

cakePHP: Overload Sanitize -

in recent cakephp 1.3.4 version discovered sanitize::html returns double encoded html entities - because of newly added fourth parameter of htmlentities 'double_encode'. here corresponding ticket on cakephp: http://cakephp.lighthouseapp.com/projects/42648/tickets/1152-sanitizehtml-needs-double_encode-parameter-in-htmlentities since need use cakephp 1.3.4 on php 5.2.14 need change double_encode parameter. there way overload sanitize::html method in cake don't have fiddle core? you can subclass in /app/libs directory: app::import('sanitize'); class mysanitize extends sanitize { public static function html(...) { ... } } you'll have switch use mysanitize instead of sanitize , shouldn't big problem. text find/replace can take care of if you're using lot already.

ps3 applications development -

can tell develop ps3 applications (or) games after install linux on ps3. and other thing can develop ps3 games on window platform tools needed,its little bit of confusing. can clarify this? currently, legitimate way develop play station 3 buy development kit , license sony. recent hacks enable homebrew applications there's sony's leaked sdk - building applications illegal. a homebrew sdk in works, not able distribute applications or games through official methods using sdk. to compile homebrew on windows, need use cygwin , available ps3 tool chain . it's unlikely compiler exist or made windows, cygwin should allow emulate linux tools available. in summary, if want legit need license , dev kit sony. if you're doing fun suggest use google find more information on ps3 homebrew development.

sql server 2008 - SQL Job: How to start with? -

can me create sql job in sql server agent (sql 2008) ,which run in purticular time interval(ex: daily) , select records table status=1 (select name,age student)and pass stored procedure accepts student name , age here approach take: create script create sql script cursor in (the reason cursor because passing student name , age different stored procedure) read studentname , age @variables execute stored proc appropriate parameters fetch next row , loop imp : test script save script in sql file further reference. in sql server agent create new job point appropriate database paste sql script (from above) script area of job create appropriate schedule (daily, @ 3:15 am) if operators , sql mail setup, add can email notifications save job imp : test job

Is it possible to extract Meta information from MS office files and/or PDFs with PHP? -

so have files.... .doc .docx .xls .xlsx , .pdf that on server. is possible (and if is, how) extract meta data files using php? i'm looking things author, keywords, title, etc... in office documents it's information stored along document properties (file...properties...summary 2003, prepare...properties 2007). in pdfs it's information found in document properties. this not on windows server. i have managed extract lot of meta information using xpdf on linux system few years back. nowadays, though, zend_pdf best bet. haven't used myself looks , promises need. seems have no library dependencies, either. for word .docs, if don't find better way, plug openoffice server instance / command line , convert files odt, xml , parseable. if it's not possible extract meta data per macro - should be, don't know how work is. this openoffice forum entry gives ton of starting points automated conversion. the ...x formats sort of xml, should p...

gdi+ - WxWidgets draw a bitmap with opacity -

how can draw wximage, or wxbitmap dc opacity? looks not possible standard dc or wxgraphicscontext. beginlayer/endlayer not yet implemented in wxgraphicscontext have been 1 solution. gdi+ doesn't seem support layers, non-trivial add this. the solution seems to programmatically alter alpha channel pixel-by-pixel? void yourcustomwindow::onpaint( wxpaintevent& event ) { wxpaintdc dc(this); wximage image( width, height ); image.initalpha(); unsigned char* imgdata = img.getdata(); unsigned char* imgalpha = img.getalpha(); // manipulate raw memory buffers populate // them whatever image like. // putting zeros everywhere create // transparent image. // done, not quite... // wxdc can draw wxbitmaps, not wximage, // 1 last step required // wxbitmap bmp( image ); dc.drawbitmap( bmp, 0, 0 ); }

php - Join two mysql tables -

i have 2 databases - 1 articles , articles' meta information (like author, date, category , atc.). have following columns in meta table: id, article id, meta type , meta value. wonder how can join these 2 tables both - article , meta information - 1 mysql query. article id isn't unique in meta table, why can't figure out how access specific meta type , according value article. select * article_table right join meta_table on article_table.article_id = meta_table.article_id; you repeats article table, gets meta data in single query. believe otherwise need use multiple.

indexing - How MongoDB manage secondary indexes scans? -

by default mongodb creates index on _id key in document. when ensure additional index (secondary in innodb mysql?) , query after, engine scans , selective scan _id index documments offsets? i'm confused because when sharding comes i'm right every chunk have own indexes , there many random reads per query? every shard have own index (containing documents in shard), accessed in parallel (every shard reads own local index shard) , results merged. not random reads, multiple parallel index reads. perspective of single shard, looks normal index access. this index sharding reason why secondary indexes cannot unique in sharding environment (there no single global index ensure uniqueness).

java - XStream Alias of List root elements -

i want able alias root list element depending upon type of objects contained in list. example, current output: <list> <coin>gold</coin> <coin>silver</coin> <coin>bronze</coin> </list> and want like: <coins> <coin>gold</coin> <coin>silver</coin> <coin>bronze</coin> </coins> i can @ global level saying lists should aliased coins, have lot of different lists , won't work. ideas on how this? seems should simple, of course, isn't. edit: should specify, trying serialize objects xml. using spring 3 mvc web framework. let's have coin class type attribute, follows: @xstreamalias("coin") public class coin { string type; } and have coins class constains list of coin: @xstreamalias("coins") public class coins{ @xstreamimplicit list<coin> coins = new arraylist<coin>(); } pay attention annotations. list implicit ,...

java - Designing a service interface to allow both synchronous and asynchronous implementations -

not sure how describe sure, think i've boiled down want in title. elaborate, i'm looking design pattern let me have implementation of service in 1 situation return result of call synchronously in case return details on how complete call asynchronously (say job id). maybe defining problem it's clear i'm trying breaks idea of designing interface contract. headed in wrong direction entirely. what thinking of possibly this: public class data { private int id; /* getter/setter */ } public class queueddata extends data { private int jobid; /* getter/setter */ } public interface myservice { public data fetchdata(int id); } public class syncedmyservice implements myservice { private syncdao syncdao; public data fetchdata(int id) { return syncdao.getdata(id); } } public class queuedmyservice implements myservice { private jobqueue queue; public queueddata fetchdata(int id) { int jobid = queue.startgetdata(id); queueddata queueddata =...

asp.net - Some issuing banks refusing 3D Secure requests -

we have commerce site we're attempting 3d secure (verified visa/mastercard securecode) set with. we using datacash our payment provider. we seeing following issue: some cards enrolled in these schemes being shown 3d secure pages, others failing, , talking issuing banks hasn't helped telling haven't seen transaction. we getting messages servers "cap.securecode.com" stating: your authentication not completed because of system error. if happens consistently, please contact csr". or "www.securesuite.co.uk": you cannot access page. this may due 1 of 2 reasons: the fi trying access deactivated the access fi restricted specific ip addresses, , address not 1 of them has else seen these errors returned verifying banks, , how can resolve it? i'm trying further details of pattern successes , failures. it looks there issue form using submit request 3d secure servers: <form method="post...

c - Help! strcmp is lying to me when fed strtok results -

strcmp, when fed results of strtok, in following code seems blatantly lying me. int fsize; char * buffer=null; char * jobtoken = "job"; char * nexttoken=null; job * curjob=null; struct node * head=null; struct node * parselist(file* file){ fseek(file,0,seek_end); fsize=ftell(file); buffer = (char*)malloc(fsize+1); printf("%d chars: reading buffer now:\n",fsize); fseek(file,0,seek_set); fread (buffer,1,fsize,file); nexttoken = strtok(buffer, " \n"); while (nexttoken!=null){ printf("**running token: %s**\n",nexttoken); if (strcmp(nexttoken,jobtoken)){ printf("accepted %s %s\n",nexttoken,jobtoken); }else{ printf("not %s, %s\n",jobtoken,nexttoken); } printf("end of state - %s\n",nexttoken); nexttoken = strtok(null, " \n"); } free (buffe...

mysql - how can i retrieve the child table data from master table in a string value -

this master table structure create table if not exists `gf_film` ( `film_id` bigint(20) not null auto_increment, `user_id` int(20) not null, `film_name` varchar(100) default null, `film_cat` varchar(30) character set latin1 default null, `film_plot` longtext, `film_release_date` date default null, `film_post_date` date default null, `film_type` enum('movie','tv') character set latin1 default 'movie', `film_feature` enum('y','n') character set latin1 not null default 'n', `film_status` enum('active','inactive') character set latin1 not null default 'active', `film_modify` timestamp not null default current_timestamp on update current_timestamp, `film_link_value` varchar(200) not null, `film_post_link` varchar(255) not null, primary key (`film_id`) ) engine=myisam default charset=utf8 auto_increment=21435 ; this child table through map between above gf_film table , l...

datetime - SQL Server function to return minimum date (January 1, 1753) -

i looking sql server function return minimum value datetime, namely january 1, 1753. i'd rather not hardcode date value script. does exist? (for comparison, in c#, datetime.minvalue) or have write myself? i using microsoft sql server 2008 express. you write user defined function returns min date value this: select cast(-53690 datetime) then use function in scripts, , if ever need change it, there 1 place that. alternately, use query if prefer better readability: select cast('1753-1-1' datetime) example function create function dbo.datetimeminvalue() returns datetime begin return (select cast(-53690 datetime)) end usage select dbo.datetimeminvalue() datetimeminvalue datetimeminvalue ----------------------- 1753-01-01 00:00:00.000

internet explorer - Apache Rewrite Override Mime and Proxy Request? -

i trying implement apache rewrite rules set mime type (in)correctly xhtml in internet explorer. have found these rewrite rules in many place, , seem work people: rewritecond %{http_user_agent} .*msie.* rewriterule .* - [t=text/html] however, site using rewrite rules [p] flag proxy requests local tomcat instance. no matter do, above rules seem overridden mime type returned tomcat. apache docs [p] flag: this flag forces substitution part internally sent proxy request , (rewrite processing stops here) ...so can't put mime rules after proxy rules. if put them before proxy rules, mime type overridden proxy. is there way set mime type ie if using proxy rules? or option change mime type in tomcat (requiring code change, unfortunately). thanks, jeff i'm not sure if work, can try it. apply 2 rules, 1 ie , 1 non ie. rewritecond %{http_user_agent} .*msie.* rewriterule ^(.*)$ http://localhost-tomcat:8080/$1 [t=text/html,p,l] second rule without br...

iphone - Dropdown menu within a UITableView -

Image
i'm looking build or incorporate dropdown menu system app i'm building need figureing out how it's accomplished. best guess i'd have use uiactionsheet, doesn't seem customizable. best example i've come accross within appshopper ios application: drop down active: notice how pushed table down, did not overlay menu uiactionsheet might. if that's model want follow, looks me expanding view in between selector , table itself. it's not part of table. from top down: there's nav bar, selector tool bar, "menu" view", table view. menu view of height 0, , expanded necessary (pushing down table view in process).

.net - Lucene PorterStemmer question -

given following code: dim stemmer new lucene.net.analysis.porterstemmer() response.write(stemmer.stem("mattress table") & "<br />") // outputs: mattress t response.write(stemmer.stem("mattress") & "<br />") // outputs: mattress response.write(stemmer.stem("table") & "<br />") // outputs: tabl could explain why porterstemmer produces different results when there space in word? expecting 'mattress table' stemmed 'mattress tabl'. also, further confusing following code: dim parser lucene.net.queryparsers.queryparser = new lucene.net.queryparsers.queryparser("myfield", new porterstemmeranalyzer) dim q lucene.net.search.query = parser.parse("mattress table") response.write(q.tostring & "<br />") // outputs: myfield:mattress myfield: tabl q = parser.parse("""mattress table""") response.write(q.tostring ...

c++ - Does this program show the four card suits (♠♣♥♦) on all standard-ish systems? -

the following shows ♠♣♥♦ on windows xp, systems?? #include <stdio.h> int main(int argc, char *argv[]) { (int = 3; <= 6; ++i) printf("%c", (char)i); getchar(); return 0; } nope. character encoding platform dependent, in experience. consider, in ascii characters don't exist . , have no clue in unicode. , ever are, depending on how platform outputs unicode.

android - Clickable item with clickable urls in ListView -

i have custom listview item imageview , textview. textview contains html string urls , regular text. im adapter have code similar tv.settext(html.fromhtml("<a href='http://google.com'>google</a>")); tv.setmovementmethod(linkmovementmethod.getinstance()); and works great onlistitemclick isn't executed when click on item outside url, whole item looks inactive. when click on url want fire default action form urls , when click on regular text or on imageview want execute onlistitemclick possible? second question, possible start activity using <a href="...">start activity</a> ? you can't make intent form anchor. it's ok , recommended use onlistitemclick (it saves lot of work), , if want open link in browser (without using webview ) can use intent, example: intent myintent = new intent(intent.action_view,contenturi.create("http://www.google.com")); startactivity(myintent); hope helps. ...

Flex 3: How do I remove a Component Using a Button in the Component -

i'd use button within component remove it. so, click , component gone. but, haven't figured out how reference component within component. should put in click=""? my component: popcanvas <mx:canvas xmlns:mx="http://www.adobe.com/2006/mxml"> <mx:panel width="200" height="200" title="hello" click="remove="> </mx:panel> </mx:canvas> in main app: var popcanvas:popcanvas= new popcanvas; popcanvas.x = 20; popcanvas.y = 30; this.addchild(popcanvas); any suggestions? thank you. -laxmidi okay, this came with: <?xml version="1.0" encoding="utf-8"?> <mx:canvas xmlns:mx="http://www.adobe.com/2006/mxml"> <mx:script> <![cdata[ public function removeme(event:mouseevent):void { this.removechild(event.currenttarget displayobject); } ]]> </mx:scr...

How can I restart a thread in java/Android from a button? -

i have thread in java/android this: handler handler = new handler() { @override public void handlemessage(message msg) { // todo auto-generated method stub update_i(); } }; @override protected void onstart() { // todo auto-generated method stub super.onstart(); thread mythread = new thread(new runnable() { public void run() { while (true) { try { handler.sendmessage(handler.obtainmessage()); thread.sleep(timer); } catch (throwable t) { } } } }); mythread.start(); } the thread works fine when run application. want start/restart thread button. button.onclicklistener startbuttononclicklistener = new button.onclicklistener() { @override public void onclick(view v) { //start/restart thread } }; if copy thread button make new thread every time user clicks on button. want run threa...

localization - iPhone: Update Localizable.strings files using genstrings? -

i have generated strings file correctly using genstrings. have changed localized strings different languages. now, have added few more nslocalizedstring() occurrences , want generate of localized strings files. but, running genstrings again not seem update strings files. doing wrong? usually because you've got genstrings looking in wrong folder, or in wrong files. had problem wasn't picking of strings, , realized searching *.m files (not *.mm) , wasn't parsing files in classes folder. small change fixed that: genstrings -o classes/en.lproj classes/*.{m,mm} the first parameter tells genstrings want .strings file. -o classes/en.lprog the second parameter tells genstrings look. remember i'm running genstrings project root, needed specify classes/ .m, or more classes/ .{m,mm} parse .m , .mm files.

entity framework - How do I clear object context -

if ran several queries , objectcontext populated entities how clear context if don't need entities anymore. know need dispose context possible, in case not possible. there way can remove objects context? you can try detach each entity in context.

math - Simple MATLAB/Octave simulation -

this should simple question has experience in area, i'm still new this. i have following system (or here image better resolution ): alt text http://img199.imageshack.us/img199/2140/equation1.png given following input: u = min(2 - t/7.5, 2*(mod(t, 2) < 1)); i need plot output of system y . i describing system following function: function xprime = func(t, x) u = min(2 - t/7.5, 2*(mod(t, 2) < 1)); xprime = [ x(2); x(3); 0.45*u - 4*x(3)^2 - x(2)*x(1) - 4*x(2) - 2*x(1); x(5); sin(t) - 3*x(5)*x(1); ]; and simulating ode23 , this: [tout, xout] = ode23(@func, [0 15], [1.5; 3; -0.5; 0; -1]) after simulation, xout have 5 columns. question is: how know 1 output of y system? edit: ok, put simple, i'd plot solution this: a = 1 % goes here? 1, 2, 3, 4 or 5? plot(tout, xout(:,a)) the 1 corresponds y, appears x(1), of course. if compare code equations, can see x(1) appears in code every place y ...

ruby - Playing with Scrapi in Rails 3.. getting Segmentation Fault error / Abort Trap -

what i've done far.. sudo gem install scrapi sudo gem install tidy this didn't work because didn't have libtidy.dylib so did : sudo port install tidy sudo cp libtidy.dylib /library/ruby/gems/1.8/gems/scrapi-1.2.0/lib/tidy/libtidy.dylib then started following simple railscast @ : http://media.railscasts.com/videos/173_screen_scraping_with_scrapi.mov right after mr. bates finished first save scrapitest.rb , tried run code : require 'rubygems' require 'scrapi' scraper = scraper.define process "title", :page_name => :text result :page_name end uri = uri.parse("http://www.walmart.com/search/search-ng.do?search_query=lost+season+3&ic=48_0&search_constraint=0") p scraper.scrape(uri) with code : ruby scrapitest.rb and returned error : /library/ruby/gems/1.8/gems/tidy-1.1.2/lib/tidy/tidybuf.rb:39: [bug] segmentation fault ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0] abort trap compl...

python - Android.mk debug output -

i building froyo, possible during building, make/python can output file , command calling right now. for example, in 1 of android.mk, there line, says, echo build success. on monitor show "build success", want in addition, shows "android.mk line 20: echo build success". is possible? the message parser of android make comment accepts info , warning tags in android.mk. for example, if want print value of internal variable: local_cflags := -dhave_errno_h -g $(info value of local_cflags is: $(local_cflags)) the info tells compiler print info debug output. you can same warning , error $(warning value of local_cflags is: $(local_cflags)) would print highlighted warning message and $(error value of local_cflags is: $(local_cflags)) would print message , stop build.

winapi - .NET wrapper for Windows API functionality -

does know of .net managed wrapper around windows api functionality not available in .net framework itself? areas such window creation , display styles, common ui control manipulation, keyboard/mouse input, file , disk information, memory mapped files etc i have been regular visitor http://www.pinvoke.net/ , find great resource. having directly use dllimport of functions , locate required structures , enumerations every time slow , prone error. (i realize doing things in 100% managed code possible better approach, there many things, particularly in windows forms can't using managed code only.) focusing on windows xp now, possibly moving windows 7 in future. a project on sourceforge called managed windows api looks might provide required functionality. it appears not have been updated year or still looks quite promising. wrapped winapi functionality include: general window settings. listview , treeview controls. sounds , audio. accessibility. keybo...