Posts

Showing posts from July, 2012

php - how to use $this->request->param of Kohana to get request variables -

i have written sample controller in kohana <?php defined('syspath') or die('no direct access allowed.'); class controller_album extends controller { public function action_index() { $content=$this->request->param('id','value null'); $this->response->body($content); } } but when trying hit url http://localhost/k/album?id=4 getting null value. how can access request variable in kohana using request->param , without using $_get , $_post method ? in kohana v3.1+ request class has query() , post() methods. work both getter , setter: // $_post data $data = $this->request->post(); // returns $_get['foo'] or null if not exists $foo = $this->request->query('foo'); // set $_post['foo'] value executing request $request->post('foo', 'bar'); // or put array of vars. existing data deleted! $request->query(array('foo' => 'bar')...

javascript - HTML5 "Canvas is null" -

can me? i'm putting infographic within sliding carousel , i'm getting error "canvas null". think may have few bits of code in wrong place, i'm having trouble working out bits. think it's causing svg that's supposed appear in background of each sliding <li> not displayed. can work out what's causing these problems? page here: http://weaver-wp.weavertest.com/radiation-infographic/ thanks, david you looping 1 32, there 31 canvas elements on page. in 32nd iteration, document.getelementbyid('mycanvas_32') returning null , hence error.

wcf - open firewall popup to unlock C# app -

i want unlock c# on windows firewall(win7/vista), opening windows security alert add firewall execption exception list. i'am using servicehost running wcf service on console app. thanks use netsh advfirewall open ports want or allow program in/out: see here documentation on netsh advfirewall: http://technet.microsoft.com/en-us/library/dd734783(ws.10).aspx http://support.microsoft.com/kb/947709 some samples: enable program netsh advfirewall firewall add rule name=”my application” dir=in action=allow program=”c:\myapp\myapp.exe” enable=yes open tcp port 16240 netsh advfirewall firewall add rule name="myopenport" protocol=tcp dir=out localport=16240 action=allow

security - Legal Issues Regarding Deletion of Records in SQL Server 2008 -

possible duplicate: how can securely destroy data using sql server 2008 ? (using dod secure wipe or equivalent) we have requirement feature has legal implications. when delete records sql server (2008 in our case), deleted records need irrecoverable sql server disk. i'm not concerned sql server side, i'm more concerned @ disk level. i know there tools secure erasing on disk, how can tie in deleting records in database? my guess periodically or @ night, task have run secure erase tool. any thoughts, suggestions? maybe putting sql data on encrypted disk help? after shutting down server machine no 1 able recover disk given encryption securely implemented. if have enough cpu power software encryption. otherwise there classical hdds , ssds offer encryption in hardware. your description doesn't include enough details know whether option you. suggestion case apply encryption.

c# - Variables with function scope -

how clr handles local variables function scope in case exception thrown. must use block or variable disposed once flow leaves function below small example protected void functionx() { list<employee> lstemployees; try { lstemployees= new list<employee>(); int s = lstemployees[1].id; // code intended throw exception } catch (exception ex) { manageexception(ex, showmessage); //exception thrown here } { lstemployees= null; } // block required make sure list cleaned } to answer specific question, no, finally block you've listed not required. assigning null reference variable not do anything, garbage collection non-deterministic. simplistic explanation, time time, garbage collector examine objects within heap determine if there active references them (this called being "rooted"). if there no active references, these references eligible...

jquery - Creating a dynamic javascript countdown timer -

i'm looking create dynamic javascript countdown timer, want pass datetime variable sql server database , have count down date display message, i've tried every jquery plugin can find , havent been able edit them need, need able have multiple countdown timers on same page, any appriciated cheers scott =======edit======= after trial , error able modify js http://andrewu.co.uk/clj/countdown/pro/ to needed try this: function thick(startin) { startin--; document.getelementbyid('timer').innerhtml = startin; if(startin > 0) settimeout('thick(' + startin + ')', 1000); } call function in body onload like: <body onload="thick(20);"> hope :)

arrays - How can I avoid this error produced while using 'strict'? -

i have couple of lines of code work if use strict; commented out. however, don't want have disabled entire script because of 1 small section. i need either recode it, or somehow disable use strict; temporarily , re-enable it. first option more realistic, don't know how change code work in strict mode. my ($ctc_rec_ref) = get_expected_contacts($ctc,$fy); @expected_ctc_rec = @$ctc_rec_ref; print $expected_ctc_rec[0][0]."\n"; print $expected_ctc_rec[0][1]."\n"; print $expected_ctc_rec[0][2]."\n"; sub get_expected_contacts { (@ctc_rec,$i) = ((),0); $stmt = "select distinct field1, field2, field3 table field4 = ? , field5 = ? , field6 = 'e'"; $sth = $db1->prepare($stmt); $sth->execute(@_); while(@results = $sth->fetchrow_array()) { push @{ $ctc_rec[$i] }, $results[0]; push @{ $ctc_rec[$i] }, $results[1]; push @{ $ctc_rec[$i] }, $results[2]; $i++; } ...

tomcat - Is connection pooling the best way for running many instances of an applications on a single server (with MySQL)? -

i want config tomcat server mysql 5.1 community edition (on win server 2008 x64) run big project on single machine. i've gwt application , need run more 300 instances of on single hp server. each instance uses separate mysql db (db1 db300) & need separate connection pool, part of connection pool configuration db1 (similar other dbs): <resource name="jdbc/mysql/db1" auth="container" type="javax.sql.datasource" initialsize="5" maxactive="100" maxidle="20" maxwait="30000" removeabandoned="true" removeabandonedtimeout="5" validationquery="select now();" .../> for 300 instances number of active connection 300*100 = 30000 active connections! now want know if possible open such huge number of connections 300 mysql databases on single server. if no, what's solution , if yes how resources (ram , cpu) used? is connection pooling best way or there way? if connect...

apache 400 error -

today find 400 error in apache. bad request browser sent request server not understand. apache/2.0.63 (win32) php/5.2.10 server @ localhost port 80 i cannot visit apache in localhost or lan. know how solve?

razor - ASP.Net MVC3 Parent Child Model Binding -

i have partial template uses user object model. user has collection of accounts. on partial template have loop follows. _account partial template bound account class @foreach (var item in model.accounts) { <tr> <td colspan="6"> <div> @html.partial("_account", item) </div> </td> </tr> } in controller method tried [acceptverbs(httpverbs.post)] public actionresult userdetails(user user, string actiontype) but user.accounts collection empty. tried this. still accounts collection empty. [acceptverbs(httpverbs.post)] public actionresult userdetails(user user, [bind(prefix="user.accounts")] fixupcollection<account> accounts, string actiontype) c...

javascript - Is it bad practice to place an if/else inside of another else? -

if() { }else { if (isalternaterow=='true') isalternaterow = 'false'; else isalternaterow = 'true'; } can place if , else statement inside of else statement? try isalternaterow = !isalternaterow; (updated show in code) var isalternaterow = false; if(/* -- insert equation here -- */) { // } else { isalternaterow = !isalternaterow; }

datetime - php 32bit date parsing for dates before 13Dec 1901 -

i happily using strtotime() on development machine parse dates of in 1800s, extreme example in 1500s. but development machine 64 bit , server 32 bit. on 32 bit machine date before fri, 13 dec 1901 20:45:54 utc out of range (see notes on strtotime). i happy write custom code this, thought ask if of php inbuilt functions manage this. dates in iso 8601 format. for worth server centos 5.4 php 5.2.10 1901-12-12t05:00:00z example i can't test right now, datetime 's constructor may able accept format without needing createfromformat . can't tell documentation. try try { $date = new datetime('1901-12-12t05:00:00z'); } catch (exception $e) { echo "arggh! ".$e->getmessage(); die(); } echo $date->format('y-m-d h:i:s'); and see happens, paying special attention whether understands z (i.e. makes utc time). datetime uses 64 bit numbers internally on system, , has no range limitations. as said, 5.3 on, ab...

java - Little trouble with hibernate autowire in a spring project, bean not found error -

i wanted try <context:component-scan base-package /> feature of spring 3.0.5. i have entry in applicationcontext : <context:component-scan base-package="com.project.personal.admin.model"/> <context:annotation-config /> i have manager class knows how create pojo , dao. @component("manager") public class managerimpl implements applicationcontextaware, manager { applicationcontext applicationcontext; public void setapplicationcontext(applicationcontext applicationcontext) throws beansexception { this.applicationcontext = applicationcontext; } public user createuser(){ return (user) getinstance("user", user.class); } public userdao createuserdao(){ return (userdao) getinstance("userdao", userdao.class); } //.... } a pojo : @entity @table(name = "user", uniqueconstraints = { @uniqueconstraint(columnnames = {"email"})}) @component("user") public class user ...

is there a way to generate input fields in ascx from sharepoint 2010 list -

i'm developing custom aspx form sharepoint list in visual studio, add new item list (that's business requirement). i'm wondering if there's way generate input controls list in design time used database in asp.net. if you're doing straight match sp list web form take @ sharepoint form generator web part just add web part page , identify list build form for.

redirect - google analytics receiving data vs. redirecting that causes NS_BINDING_ABORTED -

okay first off, sorry if title doesn't make sense...i'm not sure how else summarize it! so here's issue: i using jquery attach click event form's submit button. jquery click event triggers ga code track virtual page view can use step in goal funnel. but happens there's no delay between ga code executing , submit, i'm concerned ga isn't getting data. when @ what's happening in firebug or httpfox (browser addons @ requests/response) vs. charles proxy (external sniffer, separate browser) seeing 2 different things. with firebug/httpfox see request ga status of 0 , showing (aborted) ns_binding_aborted ...though show bytes having been sent etc.. nothing response. but charles proxy, seeing same request status of 200 , 1x1 pixel response. so theory here ga is receiving data, browser moving on before gets actual response - i'm okay with, long ga getting data, i'm okay this. theory , don't know... i know can write code del...

java - Why isn't this creating an object? -

could @ portion of code i'm trying void , close account? want achieve: "2. add method void close() account class. method should close current account appending “closed” account name , setting balance 0. (the account number should remain unchanged.) decrement total number of accounts." when tried compile it, program gave me error identifier being expected. missing? //*******************************************************/ // account.java // // bank account class methods deposit to, withdraw from, // change name on, , string representation // of account. //*******************************************************/ public class account { private double balance; private string name; private long acctnum; //---------------------------------------------- //constructor -- initializes balance, owner, , account number //---------------------------------------------- public account(double initbal, string owner, long number) { balance = initbal...

PHP array keys in a constant -

i have quick question. have placed array in constant when add array keys craps out. code below. <?php define("my_const_arr", serialize(array("page_ids" => array("1234", "4123")))); ?> <?php $page_id = "4123"; ?> <?php if(in_array($page_id, unserialize(my_const_arr["page_ids"]))): ?> <h1>hello stackoverflow</h1> <?php endif; ?> you can't my_const_arr["page_ids"] @ point because it's still string. should unserialize first , access $arr = unserialize(my_const_arr); if(in_array($page_id, $arr["page_ids"])):

Limit "each" list in Rails -

we have this: <% @shops.each |shop| %> <li><%= shop.name %></li> <% end %> the code yield total result of 50 entries (in case). how can limit view 20? yeah, limit it, don't want pagination or what. thanks. change code in controller @shops being set, or change above code @shops.take(20).each .

spam - hotmail marking valid emails as junk -

i'm sending notification emails customers explicitly ask information, of messages being marked junk. in cases same email same content marked junk user , not marked user. i've tried using different accounts names sender, mi_name@my_enterprise, or your_news@my_enterprise or random_123@my_enterprise same erratic behavior; in same case works, in other doesn't. i've changed content (adding or deleting images, external links, etc) didn't work either. does have experience similar problems , can please me come solution? thanks microsoft provides following page email senders sort of issues having: http://mail.live.com/mail/troubleshooting.aspx

Generating python data structures from parsed text without eval() -

i'm trying build tool generate datastructures text config. use pyparsing parse commands... config file: add iteration name = "cisco 10m/half" append observation name = "packet loss" assign observation results_text = 0.0 assign observation results_bool = true append datapoint assign datapoint metric = txpackets assign datapoint units = packets pyparsing commands ['add', 'iteration', ['name', 'cisco 10m/half']] ['append', 'observation', ['name', 'packet loss']] ['assign', 'observation', ['results_text', '0']] ['assign', 'observation', ['results_bool', 'true']] ['append', 'datapoint'] ['assign', 'datapoint', ['metric', 'txpackets']] ['assign', 'datapoint', ['units', 'packets']] the first column...

c# - Visualizing differences in 2+ plain text strings -

i'm looking way show differences between 2 or more texts (side side). don't need able create patch or that--just show differences line line. are there existing open-source c# libraries this? if not, there variation of diff algorithm works more 2 strings? here 2 implementations of levenshtein distance algorithm in c# link 1 link 2 the larger result, bigger difference. edit : copying code in case links go dead future use example 1: using system; /// <summary> /// contains approximate string matching /// </summary> static class levenshteindistance { /// <summary> /// compute distance between 2 strings. /// </summary> public static int compute(string s, string t) { int n = s.length; int m = t.length; int[,] d = new int[n + 1, m + 1]; // step 1 if (n == 0) { return m; } if (m == 0) { return n; } // step 2 (int = 0; <= n; d[i, 0] = i++) ...

php - while loop does not increment -

there weird problem while loop not incrementing displaying first category not rest this: class temp { var $file; function new_list($forum_list) { foreach($forum_list $key => $value) { $this->file = str_replace('{'.$key.'}', $value, $this->file); } return $this->file; } function display() { echo $this->file; } } $temp = new temp(); // mysql query while ($row_cat = mysql_fetch_array($cat)){ $temp->new_list(array( 'cat_title' => $row_cat['title'], 'cat_description' => $row_cat['description'] )); $cid = $row_cat['id']; // mysql query while ($row_forum = mysql_fetch_array($forum)){ $temp->new_list(array( 'forum_title' => $row_forum['title'], 'forum_description' => $row_forum['description'] )); } } $temp->display(); now have made template engine ...

java - When to use a web framework? -

we need code online web journal management system in java. it's not amazon, more hello world. should use framework? if yes, why? java web frameworks out there simple? yes. a web framework should used applications more complex "hello, world!". there's no need reinvent wheel. web frameworks contain many useful tested components need on site. organize code, mvc or similar paradigm, make code more maintainable. some java web frameworks (in no particular order): javaserver faces grails struts tapestry spring mvc apache wicket play framework stripes

What is a good way to handle exceptions when trying to read a file in python? -

i want read .csv file in python. i don't know if file exists. my current solution below. feels sloppy me because 2 separate exception tests awkwardly juxtaposed. is there prettier way it? import csv fname = "afile.csv" try: open(fname, 'rb') f: reader = csv.reader(f) row in reader: pass #do stuff here except ioerror: print "could not read file:", fname i guess misunderstood being asked. re-re-reading, looks tim's answer want. let me add this, however: if want catch exception open , open has wrapped in try . if call open in header of with , with has in try catch exception. there's no way around that. so answer either: "tim's way" or "no, you're doing correctly.". previous unhelpful answer comments refer: import os if os.path.exists(fname): open(fname, 'rb') f: try: # stuff except : # whatever reader errors ca...

c# - Are there any tools which can report on commented-out .NET code? -

has come across tool report on commented-out code in .net app? i'm talking patterns like: //var foo = "this dead"; and /* var foo = "this dead"; */ this won't found tools resharper or fxcop unreferenced code. there obvious implications around distinguishing commented code commented text doesn't seem great task. is there existing tool out there can pick up? if reporting of occurrences file rather full ide integration. edit 1: i've logged stylecop feature request . seems fit tool. edit 2: yes, there's reason why i'd , relates code quality. see comment below. you can approximate answer using regexp recognizes comments, end ";" or "}". for more precise scheme, see answer: tool find commented out vhdl code

SQL Server 2008 SET QUOTED_IDENTIFIER OFF problem -

i have stored procedure, , inside have query paging, returns me set of results depending on page am. i have declare @products table()... insert @products select row_number()... everything works fine, when have product single or double quotation marks in it's name, doesn't show in results. set quoted_identifier off. when remove quotation marks works, when add them again doesn't show up. what's solution here? is proc calling indexed view chance? indexed views depend on set quoted_identifier being set on. proc backfire in case used explicitly using (noexpand), otherwise can grind down halt since it'll treat normal view. see following article on msdn . stored procedures , triggers should written work 6 set options required support indexes on views , computed columns. query optimizer not use index on view or computed column in select statements executed stored procedure or trigger when set options incorrectly set. insert, up...

jquery - Spring Security Core authAjax, How do I ignore the Referer -

i'm using grails 1.3.7 , latest spring-security-core plugin. i've implemented following method in logincontroller: def authajax = { response.setheader 'location', springsecurityutils.securityconfig.auth.ajaxloginformurl response.senderror httpservletresponse.sc_unauthorized } and in global javascript file, have following: $.ajaxsetup({ error: function(xhr, status, err) { if (xhr.status == 401) { // display login form in dialog } } }); the login form standard login form directly plugin documentation. difference submit form using jquery so: var params = $('#ajaxloginform').serialize(); $.post($('#ajaxloginform').attr('action'), params, function(jsondata) { if (jsondata.success) { $('#login-dialog').dialog('close'); } else { alert('todo: display errors'); } }, 'json'); the problem first time click login button, seem authenticating ok, response com...

javascript - <script> src replacement - sandbox breaker - will it last? -

hey people, working on web do-dad allows has embed code. in particular embed, iframe added page in place of embed code via javascript. have control of user's page, and, since writing content of iframe javascript well, control of iframed page. doing (as opposed sourcing iframe our server) lets talk iframe cool trick. the problem: iframed page still needs ajax stuff our server. sandbox issues! solution, seemed me <script> src replacement - replacing our ajax procedure sandbox-breaker version. i have been told ability of browsers on chopping block. true? terrible! can't find anythign effect in (admittedly brief) research, , though i'd go experts is <script> src replacement viable mechanism pull off sandbox-breaker type effects? is <script> src replacement viable @ all? how adwords work? need call home, right? how that? i understand soon-to-be available cross site xhr stuff pop security dialogs - true? can recommend , other sandbox...

C# predictive coding for image compression -

Image
i've been playing huffman compression on images reduce size while maintaining lossless image, i've read can use predictive coding further compress image data reducing entropy. from understand, in lossless jpeg standard, each pixel predicted weighted average of adjacent 4 pixels encountered in raster order (three above , 1 left). e.g., trying predict value of pixel based on preceding pixels, x, left above : x x x x then calculate , encode residual (difference between predicted , actual value). but don't if average 4 neighbor pixels aren't multiple of 4, you'd fraction right? should fraction ignored? if so, proper encoding of 8 bit image (saved in byte[] ) like: public static void encode(byte[] buffer, int width, int height) { var tempbuff = new byte[buffer.length]; (int = 0; < buffer.length; i++) { tempbuff[i] = buffer[i]; } (int = 1; < height; i++) { (int j = 1; j < width - 1; j++) { ...

hosting - Google Code vs. Google App Engine? -

i confused. thought these both hosting solutions google sells or makes free. difference between two? thanks, alex google code sourceforge-style hosting solution open source projects: can host code in supplied subversion or mercurial repository , document project in wiki. cannot run code on google code, upload source code share others. it's free. google app engine general cloud application host. can host web sites written in python or java, running code on google's servers, cost proportional usage (it's free amount).

.NET library for typesetting documents (PDF or similar)? -

edit: better explanation: before setting bounty question want state clearer need: i need .net library generating printable documents. users should able print same document see either using application or using external tool (like adobe acrobat reader). not have library generating pdf documents, document format satisfies above condition do. i need library support following scenarios: scenario 1: i create text in font , color. i ask library width if text if printed. i compute position([x,y] coordinates on page) of text based on information 2. , have library print in @ position on page. scenario 2: i create text parts of in superscript. parts of text (normal , superscript) in same (but variable) font. i ask library width if text when printed. correct answer takes kerning between normal text , superscript account. i compute position([x,y] coordinates) on page text should printed (using width step 2.). let library print @ position. printed on page has width returned...

visual c++ - Text color with DrawText in vc++ mfc -

i'm using drawtext print message in application form. how can change text color rgb(255,0,0) ? even change in background usefull. thank all cdc::settextcolor , if memory serves.

How can I make Android application data persistent? -

i new android development , creating "todolist" app in android. i used sqllite database save list in database table, , saved data perfectly. i don't have android phone, can check application using emulator. after saving tasks in database, if user restarts phone task list in database deleted or not? if deleted how can make data in table persistent? the table stays if user reboots phone. off top of head, think way rid of table either: delete (programmatically or via sql command line) uninstall application simply upgrading application new version not delete existing tables (so long use same keystore when making apk.) -- dan

ruby on rails - Weird object issue when trying to render partial from mailer view -

using rails 3. per first snippet of code below, it's hard google search error means when trying render partial mailer view. this error: actionview::template::error (undefined method `long_date' #<#<class:0x00000102452ab0>:0x00000102440b30>): here's mailer view (email_note.html.erb) <div style="width:500px;"> <%= render :partial => "shared/note", :object => @note %> </div> this call i'm making in partial throwing error <%= long_date(note.created_at) %> long_date has worked when have given partial @note objects other actions (e.g. 'show' in notes_controller). method def long_date(date) date.strftime('%a %b %e, %g') end here actionmailer class (address , note_id sent 'email' action in notes_controller) class usermailer < actionmailer::base default :from => "gminett@gmail.com" def email_note(address,note_id) @note = note.find(note_id) ...

Question about Visual Studio *.sln file format -

i using text editor manually edit *.sln file. confused following lines: project("{fae04ec0-301f-11d3-bf4b-00c04f79efbc}") = "test2008", "tools\test2008\test2008\test2008.csproj", "{00b5ebb2-fda5-4b23-bdc5-27e9f82e7c69}" projectsection(projectdependencies) = postproject {82b9bec0-c9cc-4423-b54f-61e3c4af53d8} = {82b9bec0-c9cc-4423-b54f-61e3c4af53d8} endprojectsection endproject what's point of {82b9bec0-c9cc-4423-b54f-61e3c4af53d8} = {82b9bec0-c9cc-4423-b54f-61e3c4af53d8} statement? looks totally superfluous. it seems redundant syntax 1 of quirks required msbuild recognize project's dependency: it appears visual studio keeps dependencies in 2 ways, 1 of read msbuild. see because still can specify dependencies in gui, copy solution other machine , build vs in correct order. - victor sergienko as why "superfluous equation statement" required, seems assigning project's ...

ruby - How to handle new browser pop up after clicking a js button in Watir? -

i trying using watir in ruby, able open browser, enter values username/password form, press enter, click submit button (actually pressing enter, easiler code), pop new browser windows our application, found have no control new browser. can do? in addition problem, new browser window got no menubar, no toolbar, no navigation bar, cannot open ie developer toolbar find name of element in webpage in new browser. by way, app can support ie. i tried attach method, work: c:/ruby187/lib/ruby/gems/1.8/gems/watir-1.8.1/lib/watir/ie-class.rb:302: in `attach_browser_window': unable locate window title of (?-mix:new browser title) (watir::exception::nomatchingwindowfoundexception) c:/ruby187/lib/ruby/gems/1.8/gems/watir-1.8.1/lib/watir/ie-class.rb :150:in `_attach_init' c:/ruby187/lib/ruby/gems/1.8/gems/watir-1.8.1/lib/watir/ie-class.rb :144:in `attach' test1.rb:36 attach method able handle new window. http://rdoc.info/gems/watir/1.8.1/w...

svn - Avoiding ASP.NET passwords in github? -

i understand question can general but, regards asp.net mvc, what's best way keep passwords locally not in git/svn? database connection string in web.config -- best somehow include file in web.config isn't in git? folks do? i use windows auth databases, connection string contains server name not username/password. for machines can't use windows auth, use web.config transforms , add web.dev.config .gitignore.

sql - splitting a single row into multi rows -

possible duplicate: query display row data column hi have single row holding data 1,2,10,4,5,6,7,8,13,16,17,3. need query split them sequence row. such 1 should appear in 1st row, 2 in second row, 10 in third row................ use replace make comma separated string xml. can use cross apply nodes() of xml rows , use value() function node value. declare @str varchar(100) = '1,2,10,4,5,6,7,8,13,16,17,3' select r.value('.', 'int') val (select cast('<r>'+replace(@str, ',', '</r><r>')+'</r>' xml)) x(x) cross apply x.nodes('r') r(r) if need use table instead of variable can have here. how split repeating string delimated commas in t-sql

Use of System.err.println() in Java -

on standard console things printed in white whether have written in system.out or system.err . in ide(for me eclipse) can see different color output on console both. i.e. black system.out , red system.err . is system.err provided use in ides? cause on cmd can not distinguish system.out , system.err . both printed in same color. these 2 different output streams available in of os's. don't have them color coded due settings of terminal/command line environment. on other hand ide provides different visualization different streams. if wanted color them, consider using ansi escape sequences.

How to record a call in android? -

recorder = new mediarecorder(); recorder.setaudiosource(mediarecorder.audiosource.mic); recorder.setoutputformat(mediarecorder.outputformat.raw_amr); recorder.setoutputfile(filename); recorder.setaudioencoder(mediarecorder.audioencoder.amr_nb); this code , not able record voice of other person.so should use instead of audiosorce.mic. plz me sorry disappoint you, can't, not in general case. android running phones have wiring in hardware/firmware media of call not pass through application processor @ - goes audio dsp , vice versa, cannot access it. you can catch audio of person using phone, not other way around, disregarding silly hacks asking person use speakers , recording sound there via phone mic...

iphone - Core Data `deleteObject:` problem! -

Image
i have following entities in core data shown in figure below. the delete rule relationship cascade. questions: when ever delete 1 of entity object @ level 2 , [context save:&error]; other objects in table entity1 gets data fault , app crashes due not able read entity1 object more, giving exc_bad_access error. i using code for(entity1 *entity in listofentitys) { if(entity.relation1) [context deleteobject:entity.relation1]; if(entity.relation2) [context deleteobject:entity.relation2]; if(entity.relation3) [context deleteobject:entity.relation3]; } [context save:&error]; its not have never deleted object core data place problem occurring. can help. thanks. ps. have seen other questions on none has same kind of situation do. edit: my problem when try delete 1 object level 2 objects in entity1 getting data fault. thing this. printing description of listofentitys: ( "<entity1: 0x4dc3d80> (entity: entity1; ...

Cannot set the window icon in android -

how can set window icon activities. have gone through window features , relative methods set features. here code have used set icon: requestwindowfeature(window.feature_left_icon); setcontentview(r.layout.main); setfeaturedrawableresource(window.feature_left_icon, r.drawable.icon); i have called code in 'oncreate' method of activity. icon set main activity. whenever go other activities, no icon set in window. cannot see errors in logcat. please me. it cache problem :) i have uninstalled application emulator , deleted following files 'bin' folder: classes.dex applicationname.apk resources.ap_ deleted r.java file. worked after reinstalling application.

c - 2D array on CUDA -

i want dynamically allocate global 2d array in cuda . how can achieve this? in main calling kernel in loop. before call kernel need allocate memory on gpu . after kernel call single integer send gpu cpu inform whether problem solved or not. if problem not solved, not free old memory , since there further need of it, , should allocate new memory gpu , call kernel again. a sudocode shown: int n=0,i=0; while(n==0) { //allocate 2d memory mem[i++] //call kernel(mem,i) // n kernel } __global__ void kernerl(mem,int i) { mem[0][5]=1; mem[1][0]=mem[0][5]+23;//can use when mem[1] allocated before kernel call } any suggestions? thank you. two opening comments - using dynamically allocated 2d array bad idea in cuda, , doing repetitive memory allocations in loop not idea. both incur needless performance penalties. for host code, this: size_t allocsize = 16000 * sizeof(float); int n_allocations = 16; float * dpointer cudamalloc((void **)...

data structures - Red-black trees, relation between black and red nodes -

one of questions homework find exact lower bound of (#black nodes)/(#red nodes) in rb-tree. bound must not asymptotic. suggestions? your appreciated. assuming homework: let's review properties of redblack trees wikipedia : ... the root black. all leaves black. both children of every red node black. ... to lower bound on #b/#r want construct tree has many red nodes possible. (unfortunately, due 2,3,4 cannot construct red tree) some questions worth thinking about: can fit more red nodes in balanced or not-so-balanced trees? does or odd maximal height make difference? given tree contains 3, 7, ..., (2^n)-1 nodes how many red ones can fit in?

javascript events - cross-browser element onresize (HTML / JS) -

i know ie supports onresize event element while firefox suporty for window object only . since need functionality modern browser using (fairly fast) interval timer continously checks clientwidth/clientheight of element emulate onresize. of course inefficient , i'd know if there cross-browser way this. or, alternatively, different methods work in ff/webkit/ie timer-method can used fallback remaining browsers. targeting @ plain javascript, instead of jquery / prototype etc. if don't want use jquery must check browser sends your's script, so: if(!element.onresize != null) element.onresize += event; if(!element.onresizeanotherhandler != null) element.onresizeanotherhandler += event; i don't know easy, general concept. edit: looks there not event handler firefox. there trick: if changing width in your's js create function update function update(var nx, var ny){ // nx , ny } if added resize handle using css using javascript if using 80...

Lotus notes email in multiple folders -

is possible place email multiple lotus notes folders without creating copy of email? essitiantly, looking way create shortcut same email in different folder. example, have many emails relating expenses. place email in folder created called 'airport expenses', in folder created called 'business travel dd/mm/yyyy', without duplicating physical storage of file. placing email multiple folders, in notes, not create copy of email - adds reference email each folder. (deleting email delete 1 , copy of email, , remove references folders).

ruby - Difficulty installing RSpec on Windows -

i'm trying started rspec. had ruby 1.8.7 installed on windows 7 machine. so typed gem install rspec , seemed work. if type spec in command line, command not found. path includes bin folder in ruby_home . if c:\users\eric\.gem\specs\rubygems.org%80\quick\marshal.4.8 directory, see 4 rspec files such rspec-core-2.5.0.gemspec . nevertheless, spec command fails in directory. what needs done install rspec correctly? seem path issue, have been unable find directory spec command works, can't figure add path. there's no spec command in rspec 2. try rake spec or rspec spec .

html - how i can make a function that they update the content when user on the bottom of page ? jQuery -

like google reader , many other applicaton want make function update page using ajax request. means when user on bottom of page send request , append response exisitng content of page. how can in jquery what looking "infinite scrolling". http://www.infinite-scroll.com/infinite-scroll-jquery-plugin/

python - Mechanize not working for automating gmail login in Google Appengine -

i have used mechanize , deployed app on gae , works fine. but, app making, trying automate login gmail through mechanize. doesn't work in development environment on local machine after deploying on appengine. i have been able use same script run on server through mod_python using psp. i found lot of solutions here, none of them seem work me. here snippet of code: <snip> br = mechanize.browser() response = br.open("http://www.gmail.com") loginform = br.forms().next() loginform["email"] = self.request.get('user') loginform["passwd"] = self.request.get('password') response = br.open(loginform.click()) response2 = br.open("http://mail.google.com/mail/h/") result = response2.read() <snip> when @ result, login page when used appengine. mod_python hosted on own server, page user's inbox. the problem due how google crippled urllib2 module on gae. internally uses urlfetch module (which google wrot...

objective c - How to check whether data or object already exist in PList, iPhone? -

i can add , remove object or data in plist wanna know data or object exist in plist. code nsuinteger countobjectsfromplist; countobjectsfromplist = [[mdict allkeys] count]; nslog(@"objects in plist %d", countobjectsfromplist); for(int i=0; <= countlawsfromplist; i++){ nslog(@"\n\n\n%d\n\n\n", i); //if([objectname isequaltostring:[[mdict allkeys] objectatindex:i]]) if(objectname ==[[mdict allkeys] objectatindex:i]){ nslog(@"already exists"); //nslog("string equal"); } else { nslog(@"added favorites"); } } please 1 me on come this. thanks id object = [mdict objectforkey:key]; bool exists = (object != nil); edit: apparently wasn't clear enough. objectforkey you're telling dictionary "could please give me object key key "? if object there key, returning value non-nil. otherwise nil. that's why check object != nil in order know if object exists in dictionary key. goes take more coffee

Android Facebook SSO for server side authentication -

i using fb sso android app , use facebook id authenticate users when upload data server. imagine should send oauth token when making call server. examples out there me started? thanks pointers. i have faced same problem while ago. in end, did using following way: i token via facebook android sdk , pass server users email address , facebook id. server tries users email address using token. if email addresses match, user has authenticated.

google app engine favicon.ico does not update -

i'm developing gae app. i have favicon.ico in static folder, recommended , explained everywhere. now changed picture in favicon.ico. in local host can see new favicon.ico, when try open webpage url (on server) see old favicon.ico . it persist when uploaded newer version of app gae. try looking @ favicon directly, e.g., go http://mysite.com/favicon.ico . if looks right there, caching issue resolve soon.

c# - determine jpeg filesize without actually saving the jpeg -

i have image in png or bmp format. find out filesize of image after compressing jpeg without saving jpeg . up did following way: framenormal.save("temp.jpg", imageformat.jpeg); tempfile = new fileinfo("temp.jpg"); filesizejpg = tempfile.length; but because of slow disk access, program takes long. there way calculate filesize of newly created jpeg? converting png in memory , read size... any appreciated :-) you can write image data stream instead of supplying filename: using (memorystream mem = new memorystream()) { framenormal.save(mem, imageformat.jpeg); filesizejpg = mem.length; }

C++ macros with define or inline? -

possible duplicate: inline functions vs preprocessor macros inline functions introduced in c++ replace c style macros (#define macroname...), still, see lots of c++ code using old c style macros rather inlined functions, inlined function inferior old c style macros? i macros inferior inlined functions. inlined functions type safe , macros not. that's big advantage of them. compiler helping make better code. with said, there few things macros can functions cannot. there not many of these things though... i believe c programmers used macros , continue habits c++.

Android Keyevent injection requires system permissions -

hi using key event injection using window manager when tested application gives me error 04-12 18:19:35.794: warn/windowmanager(58): permission denied: injecting key event pid 6290 uid 10039 window window{45034880 com.android.launcher/com.android.launcher2.launcher paused=false} owned uid 10020 04-12 18:19:35.794: warn/system.err(6290): java.lang.securityexception: injecting application requires inject_events permission 04-12 18:19:35.854: debug/phonedata(6290): 04-12 18:19:36.048: warn/system.err(6290): @ android.os.parcel.readexception(parcel.java:1247) 04-12 18:19:36.048: warn/system.err(6290): @ android.os.parcel.readexception(parcel.java:1235) i give inject event permission there way give application system permissions. only applications part of firmware (i.e., signed firmware signing key) can hold inject_events permission. if making own device or firmware, relevant. if creating ordinary sdk application, cannot inj...

eclipse - Using Ant with Flex -

i'm having problems setting ant use flex. install fine error when try , check install: unable locate tools.jar. from i've read, need point java_home directory contains jdk. unfortunately, i'm not sure know jre i'm using in eclipse , also, search tools.jar on machine , it's not there??? i have c:\program files\java directory , there in there: j2re1.4.2_05 jdk1.6.0_03 jre1.6.0.23 in eclipse --> windows --> preferences --java --> installed jres, it's pointing here: eclipse-host-distro, c:\program files\adobe\adobe flash builder plug-in\eclipse-host-distro am not working full jre? any tips appreciated. thank in advance. just specify java_home path c:\program files\java\jdk1.6.0_03\ , should long jdk installed. if doesn't work, get latest , try again.

SSH connection with python from a device (not computer) -

i'm using digi 3g router can programmed python, , want make periodic ssh connections device. i've read paramiko, don't know how install in router. want know if there other way of including paramiko device, apart installing (i.e. including library), or if exist possibility apart paramiko particular case. thanks in advance. the description digi 3g states capable of python scripting, using custom development environment. make work, have use python source code paramiko; executable not installable directly on router (since executable designed run on computer, not router). the source code have modified, since apis sort of thing different in computer, , router have capable of asking of it.

c# - Edit parameters in Settings file -

i have dataclasses.dbml file in c# winforms project. automatically adds setting of type connectionstring settings file of project. connection string throughout project accessed using setting. now when work on pc, connects database , works fine. how set new connection string depending on client's host , instance names in settings file permanently , once (during setup). i tried doing: settings.default.connectionstring = "sqlconnectionstring"; settings.default.save(); but gives compile-time error read-only. my aim set connectionstrings according clients setting. dont want make hard coded. add partial class definition following public partial class dataclasses { partial void oncreated() { connection.connectionstring = sqlhelpers.getconnectionstr(); } } where sqlhelpers.getconnectionstr should lookup settings users app.config file. remember put in separate file auto-generated dbml file.

c++ - Enumerating the available keyboard layouts in Windows -

is possible enumerate available keyboard layouts. available mean user can switch them pressing alt+shift (or whatever chosen shortcut is), i.e. in language bar's menu. alternatively, checking if specific layout available in language bar useful. edit: many @oleg, made function works: bool isactivekeyboardlayout(dword dwprimarylangid) { tchar buf[kl_namelength]; getkeyboardlayoutname(buf); dword dwactivelangid = 0; _stscanf(buf, _t("%x"), &dwactivelangid); if (dwprimarylangid == primarylangid(dwactivelangid)) return true; return false; } bool iskeyboardlayoutpresent(dword dwprimarylangid) { if (isactivekeyboardlayout(dwprimarylangid)) return true; dword dwthreadid = getcurrentthreadid(); hkl hold = getkeyboardlayout(dwthreadid); (;;) { activatekeyboardlayout((hkl) hkl_next, 0); if (hold == getkeyboardlayout(dwthreadid)) return false; if (isactivekeyboardl...

JQuery Form success callback not being called -

i have searched , can't find answer matches exact situation first off, apologies if duplicate. i using asp.net mvc 3, , submitting form using jquery form plugin. form submits correctly , able step through code behind etc success callback never called - i've stripped code simple possible: $(document).ready(function () { bindform(); }); function bindform() { $('#paydayform').ajaxform({ error: function() { alert("error");}, success: function() { alert("success");}, }); } the form submits neither error or success called! are submitting cross-domain ajax? that's 1 reason can think receive data on server javascript code either not receive success callback @ (firefox) or call never response data (chrome).

php - CodeIgniter/jQuery - Ajax call returns full html page instead of my echo -

in view have ajax call: $(".previous").click(function() { $.ajax({ type: "post", url: "planner/get_cal", data: {current_month: current_month}, success: function(msg){ alert(msg); } }); the get_cal function in planner controller: function get_cal() { echo "dinosaurs"; } however, instead of returning "dinosaurs", returns full html page. can't figure out why. thoughts? lot. i solved using leading slash suggested in comments question. $.ajax({ type: "post", url: "/planner/get_cal", datatype: "text", data: {current_month: current_month}, success: function(msg){ alert(msg); } });

css - Div with margin-left and width:100% overflowing on the right side -

i have 2 nested div's should 100% wide. unfortunately inner div textbox overflows , larger outer div. has left margin , overflows size of margin. how can fix that? <div style="width:100%;"> <div style="margin-left:45px; width:100%;"> <asp:textbox id="txttitle" runat="server" width="100%"></asp:textbox><br /> </div> </div> if don't 100%, textbox not 100% wide. just remove width both divs. a div block level element , use available space (unless start floating or positioning them) outer div automatically 100% wide , inner div use remaining space after setting left margin. i have added example textarea on jsfiddle . updated example input.

apache - XSL FO - Respect the padding -

on except page-1 table not pad tell to. have "first" , "rest" defined as <!-- layout first page --> <fo:simple-page-master master-name="first" page-height="11in" page-width="8.5in" margin-top="1cm" margin-bottom="2cm" margin-left="2.5cm" margin-right="2.5cm"> <fo:region-body margin-top="3cm"/> <fo:region-before extent="2cm"/> <fo:region-after extent=".1cm"/> </fo:simple-page-master> <!-- layout other pages --> <fo:simple-page-master master-name="rest" page-height="11in" page-width="8.5in" margin-top="1cm" margin-bottom="2cm" ...

JSF: Hide input when typing in the text box -

i want hide first 6 characters of ssn when user types in text box. *- -1234 there built in tag can achieve this. in advance. the "built in" components of standard jsf implementation represents standard html elements. functional requirement not covered of html elements, standard jsf implementation won't have well. closest 1 html <input type="password"> provided jsf <h:inputsecret> component, mask all characters instead of specified subset. also no 3rd party jsf component libraries comes mind able this. have 2 options, easy 1 , harder one. split ssn on 2 input fields. 1 <h:inputsecret> , 1 <h:inputtext> . add if necessary onkeyup javascript helper code auto-tabs next field when 6 characters entered. in server side glue 2 parts together. use <h:inputhidden> value , normal <input type="text"> onkeydown javascript helper code fills hidden input , returns masked character visible input first 6 ch...

java ee - Change parent layout by child button on that layout -

i have problem change of tab panel layout click event on buton located on panel. main idea have custom menu (new, open, del) on smal panel on every tab panel. when click button, tab panel layout change form (for example). don't want use modal window or new window, change tab panel layout (content) else button click. it, wrong specified question - should ask how notify parent component. bellow have 2 examples show how achive goals. first implementation jens janssons suggest on vaadin forum, pass clicklistener second panel constructor parameter. note able remove component outer panel, need both reference outer panel , inner panel. in example kim lappanen stored references in class variables. note ther used horizontallayout called "panel", can change it. public class testcaseapplication extends application implements clicklistener { private static final long serialversionuid = 75232258896642392l; private final horizontallayout mainlayout = new horizon...