Posts

Showing posts from March, 2011

php - how to set path for uploaded files using zend framework? -

i trying upload video , convert in php using zend framework , have bit of problem logic. i have directory, locally, needs hold uploaded files: c:/xampp/htdocs/zend/videos/ fist need convert video move in directory. for conversion im using this: exec("ffmpeg -i video.avi -ar 22050 -ab 32 -f flv -s 320x240 video.flv", $out); here part of form: $file = new zend_form_element_file('file'); $file->setlabel('file') ->setrequired(true) //->setdestination('/var/www/tmp') use in real life ->setdestination('c:/xampp/htdocs/zend/tmp') ->addvalidator('size', false, array('min' => '10kb', 'max' => '100mb')); when upload file goes directory fine. do need convert file in tmp directory , move other main one, delete original one? isn't there way hold original file in temp directory temporary until gets conv

pdf - Creating a long TCPDF document without timeout (so long running php process) -

i'm building feature of site generate pdf (using tcpdf) booklet of 500+ pages. layout simple due number of records think qualifies "long running php process". need done handful of times per year , if have run in background , email admin when done, perfect. considered cron user-generated type of feature. what can keep pdf rendering long takes? "good" php not *nix. tutorial link helpful. what need change allowed maximum execution time php scripts. can several means script (you should prefer if work) or changing php.ini. beware - changing execution time might lower performance of server. script allowed run time (30sec default) before terminated parser. helps prevent poorly written scripts tying server. should know doing before this. you can find more info about: setting max-execution-time in php.ini here http://www.php.net/manual/en/info.configuration.php#ini.max-execution-time limiting maximum execution time set_time_limit() here http://ph

model view controller - When does Javascript break the MVC pattern -

i having argument colleague other day. building our javascript video player. i wanted pass xml annotations file player , have parsed file, have displayed annotations in configurable ways. thought it'd easier embed everywhere way. myplayer("divid").setup({ videofile: "/video.mp4", annotationfile: "/annotations.rdf", annotationstyle: "overlay" }); my colleague argued break pure mvc pattern have been following. rather parse annotation file server side , display through view. what think? keep in mind intend let other projects use player we'd make reusable possible. you colleague confusing mvc one-m, one-v , one-c. model, view , controller can structured in number of arbitrary layers want. , being here cpu involved in browser, might use (so @ least 2 layers of view). might decide parse on server many reasons, "not breaking mvc" wouldn't 1 of them.

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -

import pyodbc,nltk,array cnxn = pyodbc.connect('driver={mysql odbc 5.1 driver};server=127.0.0.1;port=3306;database=information_schema;user=root; password=1234;option=3;') cursor = cnxn.cursor() cursor.execute("use collegedatabase ;") cursor.execute("select * sampledata ; ") cnxn.commit() s=[] j=[] x=[] words = [] w = [] sfq = [] pos=[] entry in cursor: s.append(entry.injury_type),j.append(entry.injury_desc) nltk.tokenize import punktwordtokenizer nltk.corpus import stopwords tokenizer = punktwordtokenizer() english_stops = set(stopwords.words('english')) in range(0,26): # filter stop words tokenizer.tokenize(j[i]) w.append([word word in tokenizer.tokenize(j[i]) if word not in english_stops]) in range(0 , 26):#converting tokenzied text ito string sfq.append(" ".join(w[a])) replacers import regexpreplacer replacer = regexpreplacer() in range (0,26):#pos tagging replacer.repl

Function and data format for doing vector-based clustering in R -

i need run clustering on correlations of data row vectors, is, instead of using individual variables clustering predictor variables, intend use correlations between vector of variables between data rows. is there function in r vector-based clustering. if not , need manually, right data format feed in function such cmeans or kmeans? say, have m variables , n data rows, m variables constitute 1 vector each data row. have n x n matrix correlation or cosine. can matrix plugged in clustering function directly or processing required? many thanks. you can transform correlation matrix dissimilarity matrix, instance 1-cor(x) (or 2-cor(x) or 1-abs(cor(x)) ). # sample data n <- 200 k <- 10 x <- matrix( rnorm(n*k), nr=k ) x <- x * row(x) # 10 dimensions, less information in of them # clustering library(cluster) r <- pam(1-cor(x), diss=true, k=5) # check results plot(prcomp(t(x))$x[,1:2], col=r$clustering, pch=16, cex=3)

Google maps api v3 LatLng conversion error -

i'm doing ajax call request position , move marker relative position is. problem latlng command returns (nan,nan) though variable "data" contains position. doing wrong here? function marker() { $.get("ajax.php", { do: "getpos" }, function(data){ var latlng = new google.maps.latlng(data); alert(latlng); beachmarker.setposition(latlng); }); //settimeout( "marker()", 10000); } as documentation says, latlng constructor should have 2 parameters, both must numbers. ajax response can't of number type. string, should split , parse numbers passing latlng constructor.

c# - Capturing javascript popups -

in webbrowser, there anyway capture stupid popups generated javascript? the ones "success" or watever , have "ok" button. i tried webbrowser "newwindow" event, not being fired. any tips? you redefine global javascript alert function this: function alert() {} then nothing happen when other code calls alert. update: to add following page code: <script> function alert() {} </script> if injecting pages may wish @ greasemonkey , add script using that: https://addons.mozilla.org/en-us/firefox/addon/greasemonkey/ there similar addons browsers.

ssrs 2008 - Reporting Services - Inverse Logarithmic scale for gauge -

we using ssrs 2008 r2 enterprise , create gauge scale between 0 , 100% halfway mark @ 90% increasing interval there. deal high targets in 98, 99, or 99.85% range. does know if possible out of box ssrs 2008r2 gauges? thanks in advance, dan

asp.net mvc 3 - Pass Complex JSON Object to an MVC 3 Action -

i getting weird results while trying pass complex json object action in mvc 3. the locations populated on action parameter model, name , location not. if ko.tojs(testviewmodel) , name , location there, locations blank??? i using knockout.js: var testviewmodel = { name: ko.observable("joe bob"), locations: ko.observablearray([ { id: 1, name: "salem, or" }, { id: 2, name: "big bear lake, ca" }, { id: 3, name: "big bear city, ca" } ]), position: ko.observable("manager") } sending via jquery ajax: $.ajax({ url: "/claimsauthority/home/testit", type: "post", data: ko.tojson(testviewmodel), success: function (data, status, xhr) { //ko.applybindings(data); } }); mvc action: <httppost()> public function testit(model testmodel) actionresul

How to get value from XML string with Node.js -

let's have xml: <yyy:response xmlns:xxx='http://domain.com'> <yyy:success> <yyy:data>some-value</yyy:data> </yyy:success> </yyy:response> how retrieve value in between <yyy:data> using node.js? thanks. node-xml2js library you. var xml2js = require('xml2js'); var parser = new xml2js.parser(); var xml = '\ <yyy:response xmlns:xxx="http://domain.com">\ <yyy:success>\ <yyy:data>some-value</yyy:data>\ </yyy:success>\ </yyy:response>'; parser.parsestring(xml, function (err, result) { console.dir(result['yyy:success']['yyy:data']); });

osx - Clozure CL on Mac OS X: get rid of the GUI? -

i want run ccl repl command line. should prevent ccl starting gui thing (the menu , listener window)? thanks. homebrew has recipe clozure cl, , set you'd expect. $ brew install clozure-cl now type ccl or ccl64 @ command line.

Modifying PHP function to accept different types of arrays -

i have small function below accepts associative arrays , i'm struggling find way modify accept simpler arrays. easy create separate function , remove foreach loop, i'm trying see if there more efficient way achieve this. insights appreciated. function: public function set_content($file, $data, $section_name) { $jobs = new template_engine(); $jobs->set_file($file); $jobs_output = ''; static $section_title = 0; foreach($data $job) { //print_r($job); foreach($job $key=>$value) { $jobs->set($key,$value); } if ($section_title === 0) { $jobs->set("section_title",$section_name); } else { $jobs->clear_set("section_title"); } ++$section_title; $jobs_output .= $jobs->output(); } $section_title = 0; return $jobs_output; } array sample 1: array ( [0] => array ( [custom_id] => 78 [name] => title

php phpmailer always go to hotmail junk folder anyone can solve -

<?php $to=$_post['email']; $pwd=$_post['pwd']; $activate_code = md5($_post['pwd'] . $_post['email'] . time()); $subject = "卓能脹戶啟動程序" ; $body ="親愛的 [$username] : <br />" . "歡迎加入卓能會員網站! <br />" . "請利用以下網址啟動您的帳號,才能完成註冊程序," . "<a href=http://www.domain.com/activate.php?code=$gencode>http://www.domain.com/activate.php?code=$gencode</a> " . "勿直接回覆此信 。 <br />" . "<br /> 開啟動成功後您會員帳號即可立即使用。"; include("phpmailer/class.phpmailer.php"); $mail= new phpmailer(); $mail->issmtp(); $mail->smtpauth = true; $mail->host = "smtp.domain.com"; $mail->port = 25; $mail->charset = "utf-8"; $mail->username = "minniekwok223@domain.com"; $mail->password = "123456"; $mail->from = "mi

cordova - PhoneGap app crashes with "unrecognized selector" error -

i have basic phonegap project, 100% auto-generated code. app starts, , crashes on second line: int main(int args, char* argv[]) { nsautoreleasepool* pool = [[nsautoreleasepool alloc] init]; int retval = uiapplicationmain(argc, argv, nil, @"appdelegate"); // exception [pool release]; return retval; } the exception [__nscfstring count] unrecognized selector sent instance . seems expected string, , got nil instead. there configuration setting supposed set? edit: using xcode 4.2.1. thanks. i figured out. fault. my app needs communicate web service, changed externalhosts setting in .plist file * . problem instead of adding item array, had changed type string. after changing array, started working.

c# - Using InProc and Azure AppFabric Cache together -

just bit of background first. have site hosted windows azure, multiple instances , appfabric sole caching provider. everything going great until traffic spiked earlier morning. after instances became overloaded , stopped responding came again once new instances started. however started getting messages appfabric saying being throttled because there many requests in given hour. fair enough, giving hell. in order avoid these messages in future planning on implementing inproc cache short lifespan. checks inproc first, if not goes appfabric, if not goes db. objectcache cache = memorycache.default; cacheitempolicy policy = new cacheitempolicy(); policy.absoluteexpiration = datetimeoffset.now.addminutes(5); the questions have are is best way handle situation? is going interfere appfabric caching? any issues overlooking? update wanted chose above method , works well. using general data storage , not session state. memorycache session state not work on azure due no s

java - Relationship between JDBC sessions and Oracle processes -

we having problem many oracle processes being created (over 2,000) when connections limited 1,100 (using c3p0) two questions: what's relationship between oracle process , jdbc connection? 1 oracle process created each session? 1 created every jdbc statement ? no relationship @ all? did ever face scenario, creating more processes jdbc connections? any comment appreciated. there 1 session per connection. sounds have connection leak, somewhere you're opening new connection , not closing properly. 1 possibility open, use , close connection inside try block , handling exception in catch , or returning someother reason. if need make sure connection close done in finally or may not happen, leaving connection (and session) hanging. opening 2 connections in same scope without explicit close in between can this. i'm not familiar c3po don't know how connections handled, or , how 1100 limit imposed; if (or you) have connection pool , 1100 refer maximm pool

Uninstall MySQL completely from Ubuntu -

i have trouble in uninstalling mysql ubuntu. used following commands, doesn't seem still find mysql folder in \etc directory 1.aptitude remove mysql-client 2.aptitude remove mysql-server 3.aptitude remove mysql-common please suggest way uninstall , command check if uninstallation successful. thank you! sudo apt-get remove --purge mysql-client mysql-server

ruby - passing array as a command argument -

i trying pass array ruby script command line , facing issue. here problem: require 'pp' def foo(arr1, var, arr2, var2) puts arr1.class pp arr1 pp arr1[0] puts arr2.class pp arr2 pp arr2[0] end foo [1, 2], 3, [5, 6], 8 here output: array [1, 2] 1 array [5, 6] 5 all fine far. change script accept argument command line: require 'pp' def foo(arr1,var) puts arr1.class pp arr1 pp arr1[0] end foo argv[0],3 here output: jruby test.rb [1, 2], 3, [5, 6], 8 string "[1," 91 string "2]," 50 as can see, array gets passed string , arr[0] prints ascii value. so question how pass array command line , in 1 line. believe question related shell invocations ruby ? i using bash shell. update: updated question indicate there can multiple arrays @ different positions you can use eval although might open security hole: require 'pp' def foo(arr1, var, arr2, var2) puts arr1.class pp arr1 pp arr1[0] p

java me - LWUIT J2ME Using VirtualKeyboard -

is possible use virtual keyboard without assign textfield / textarea ? in doc said vk must linked component ( bindvirtualkeyboard() ). i have label , button . after clicking on button woud show virtual keybord numbers. after typing finished change text in label component. of course can able show keyboard can't value keyboard because not assigned textfield . is possible described ? if can explain how or maybe there's example ? best regards, mel i suggest take @ virtualkeyboard code, technically dialog can subclass , show/used see fit. want won't work via standard show api because that's generic (for native vkb support) should work actual lwuit virtualkeyboard implementation.

What Scala feature implements factory patterns and persistent (singleton?) objects? -

what scala feature can class become factory? , return persistent objects database connections? i familiar python, less familiar java , spent few hours scala (tutorials). working counter-intuitive ideas scala classes head; thinking in terms of more intuitive features. see companion object in scala: class example(val string:string) {   private var extradata = ""   override def tostring = string+extradata } object example {   def apply(base:string, extras:string) = {     val s = new example(base)     s.extradata = extras     s   }   def apply(base:string) = new example(base) } println(example("hello"," world")) println(example("hello")) there connected class same name. for persistence objects scala use same stuff java - jpa hibernate openlink see using jpa scala

ruby on rails - NoMethodError? Counting Records -

i have following models: class label < activerecord::base has_many :releases end class release < activerecord::base belongs_to :label has_many :products has_and_belongs_to_many :tracks def self.releases_count self.count(:all) end end class product < activerecord::base belongs_to :release has_many :releases_tracks, :through => :release, :source => :tracks has_and_belongs_to_many :tracks def self.products_count self.count(:all) end end on label/index view i'm able display count of releases absolutely fine using: <%= label.releases.releases_count %> i'm trying same products using: <%= label.releases.products.products_count %> but nomethoderror: undefined method `products' #<label:0x10ff59690> any ideas? i have lots of other aggregations want perform (track counts etc) guidance on i'm going wrong appreciated. you need define production/label association class label &

asp.net mvc - RavenDb - The remote server returned an error: (403) Forbidden -

Image
when try create database people collection on ravendb, following error: the remote server returned error: (403) forbidden. i hots raven on iis , not sure going on. on raven management studio, when try create database, below result: could not authenticate against server message: remote server returned error: notfound. uri: /databases?database=default server uri: http://localhost:8888/docs/raven/databases/people -- error information -- system.net.webexception: remote server returned error: notfound. @ system.net.browser.clienthttpwebrequest.endgetresponse(iasyncresult asyncresult) @ system.func 2.invoke(t arg) @ system.threading.tasks.taskfactory 1.fromasynccorelogic(iasyncresult iar, func 2 endmethod, taskcompletionsource 1 tcs) when looked process monitor, see getting bunch of not found errors: under c:\utils\ravendb\web directory, there bin , data folders, nothing more. should create necessary folders myself? created docs f

Python: garbage collection fails? -

consider following script: l = [i in range(int(1e8))] l = [] import gc gc.collect() # 0 gc.get_referrers(l) # [{'__builtins__': <module '__builtin__' (built-in)>, 'l': [], '__package__': none, 'i': 99999999, 'gc': <module 'gc' (built-in)>, '__name__': '__main__', '__doc__': none}] del l gc.collect() # 0 the point is, after these steps memory usage of python process around 30 % on machine (python 2.6.5, more details on request?). here's excerpt of output of top: pid user pr ni virt res shr s %cpu %mem time+ command 5478 moooeeeep 20 0 2397m 2.3g 3428 s 0 29.8 0:09.15 ipython resp. ps aux : moooeeeep 5478 1.0 29.7 2454720 2413516 pts/2 s+ 12:39 0:09 /usr/bin/python /usr/bin/ipython gctest.py according the docs gc.collect : not items in free lists may freed due particular implementation, in particular int , float . does mean, if (temporari

sql - How to combine GROUP BY and ROW_NUMBER? -

i hope following sample code self-explanatory: declare @t1 table (id int,price money, name varchar(10)) declare @t2 table (id int,orders int, name varchar(10)) declare @relation table (t1id int,t2id int) insert @t1 values(1, 200, 'aaa'); insert @t1 values(2, 150, 'bbb'); insert @t1 values(3, 100, 'ccc'); insert @t2 values(1,25,'aaa'); insert @t2 values(2,35,'bbb'); insert @relation values(1,1); insert @relation values(2,1); insert @relation values(3,2); select t2.id t2id ,t2.name t2name ,t2.orders ,t1.id t1id ,t1.name t1name ,t1sum.price @t2 t2 inner join ( select rel.t2id ,max(rel.t1id)as t1id -- max returns arbitrary id, need is: -- ,row_number()over(partition rel.t2id order price desc)as pricelist ,sum(price)as price @t1 t1 inner join @relation rel on rel.t1id=t1.id group rel.t2id )as t1sum on t1sum.t2id = t2.id inner join @t1 t1 on t1sum.t1id=t1.id result: t2id t2name order

c - Printing out a char[] -

i cannot life of me remember how this. program opens file reads file. print out contents has read. int main(int argc, char *argv[]) { char memory[1000]; //declare memory buffer size int fd = 0; int count = 1000; if ((fd = open(argv[1], o_rdonly)) == -1) { fprintf(stderr, "cannot open.\n"); exit(1); } read(fd, memory, count); //printf buffered memory contents return 0; } printf accepts %s format print c-string. however, default requires string have null-terminator (0x0 ascii code). if sure read call read can this: printf("%s\n", memory); however, cannot sure. because don't check how many bytes read... or error code. have fix code first. once done checking errors , know how many bytes read, can this: printf("%.*s\n", (int)bytes_that_were_read, memory); good luck!

Classic ASP: I'm getting a type mismatch error when I shouldn't -

i have function turning html encoded text html. works great normally, reason, try use on text today, , following error: microsoft vbscript runtime error '800a000d' type mismatch: 'unchkstring' /manage/solutions_delete.asp, line 22 the line using function on is: <%= unchkstring(solution_desc) %> the solution_desc variable is: &lt;p&gt;here description of solution about.&lt;/p&gt; the field database pulling solution_desc text field. my unchkstring function is: function unchkstring(string) unchkstring = replace(string,"[%]","%") unchkstring = htmldecode(unchkstring) end function the htmldecode function is: function htmldecode(stext) dim stext = replace(stext, "&amp;" , chr(38)) stext = replace(stext, "&amp;" , "&") stext = replace(stext, "&quot;", chr(34)) stext = replace(stext, "&rsquo;", chr(39)) stex

How do I make calls to a REST api using c#? -

this code have far: using system; using system.collections.generic; using system.linq; using system.text; using system; using system.net.http; using system.web; using system.net; using system.io; namespace consoleprogram { public class class1 { private const string url = "https://sub.domain.com/objects.json?api_key=123"; private const string data = @"{""object"":{""name"":""name""}}"; static void main(string[] args) { class1.createobject(); } private static void createobject() { httpwebrequest request = (httpwebrequest)webrequest.create(url); request.method = "post"; request.contenttype = "application/json"; request.contentlength = data.length; streamwriter requestwriter = new streamwriter(request.getrequeststream(), system.text.encoding.ascii)

How Jump automatically to another report according to a value. Reporting Services -

reporting services i need jump specific report according value takes variable data set. for example: if variable has value = 2, go report 'informe_1' if value = 4, go report 'informe_2', automatically without having click anything. generic type of report determines of 2 reports must charged according value of variable. currently have in properties of variable, in action, go report, need specify condition 'informe_1' or 'informe_2' according value of variable (2 or 4). i'm not aware of way automatically go specific report without user clicking something; however, can specify expression action on , way user report specified variable when click. in design view, right-click text box, image, or chart want add link , click properties. in item's properties dialog box, click action. select go report. additional sections appear in dialog box option. in specify report, click browse locate report want jump to, or type name of report

Magento - Product Collection with the current user's Wishlist -

within magento php controller, how can product collection containing products listed in logged in user's (ie current user's) wishlist. i getting wishlist using: $wishlist = mage::getmodel('wishlist/wishlist')->loadbycustomer(mage::getsingleton('customer/session')->getcustomer()); and contains correct number of items. but product collection. have tried: $productcollection = $wishlist->getproductcollection(); and $productcollection = $wishlist->getproductcollection()->addattributetoselect('id')->load(); but product collection has length of 0. how product collection? you can use getwishlistitemcollection (see link more details) off wishlist helper return collection of items, need product item. i have been using following code create associative array of products, use determine if product displaying in list page in wishlist...hopefully help: public function getwishlist() { $_itemcollection = mage::hel

asp.net mvc 3 - JSON object passing back to view from controller in a mix application of MVC2 and MVC3 -

to give background, application mix application containing both aspx , razorview engine. have controller extension class, public static class controllerextensions { public static viewresult razorview(this controller controller) { return razorview(controller, null, null); } public static viewresult razorview(this controller controller, object model) { return razorview(controller, null, model); } public static viewresult razorview(this controller controller, string viewname) { return razorview(controller, viewname, null); } public static viewresult razorview(this controller controller, string viewname, object model) { if (model != null) controller.viewdata.model = model; controller.viewbag._viewname = getviewname(controller, viewname); return new viewresult { viewname = &q

How do I sort a List of Dictionaries based off of a value in a key within the Dictionary in C# .NET Silverlight? -

so have list of dictionary<string, string> dict , want sort list alphabetically off dict["title"] value. how go doing that? and, if want take value of dict["title"] , modify string title = dict["title"] + "xyz"; , , use modified title sorting value of dict (without changing dict["title"] )... how go doing well? thanks. linq it: var dicts = new list<dictionary<string, string>>(); var sort = dicts.orderby(x => x.containskey("title") ? x["title"] : string.empty); var sort2 = dicts.orderby(x => x.containskey("title") ? x["title"] + "xyz" : string.empty);

raytracing - Optimal way to record ray intersection data for ray tracing using OpenCL -

i developing monte carlo ray tracer in opencl calculating 'view factors' radiative heat transfer analysis , wish know optimal way collate number of times object x intersected rays fired object i. now basic algorithm follows : fire random ray, r, off surface of object i test intersection of ray r objects 0 - n determine first object intersected r, let object x record first intersection incrementing array of int's such array[i][x] +=1 repeat total number of rays divide each value in ith row of array total number of arrays fired object i. now typically in parallel implementation on cpu each thread maintain own copy of array[n] , when rays have been fired object i, master thread sum individual arrays results. in opencl on gpu not practical solution when n increases there becomes shortage of local memory , using single array barriers cripple performance. what best practical preforming reduction of results array or a memory barrier practical solution?

c++ - Address of pass-by-value variable causing seg-fault -

i'm working legacy code cannot edit compiled , tested on powerpc. attempting create build system build generic linux box (ubuntu 11.10 x64). it has custom interface similar cblas wraps f2c version of generic blas library included in clapack (ver. 3.2.1). i.e. compile liblapack, libblas , libf2c on linux machine clapack source , link following example code: int main() { double a[3] = {100,200,300}; // scale elements of 0.1 // uses custom wrapper seg. faults mycblas_dscal(3,0.1,a,1); } void mycblas_dscal(int n, double scale, double* data, int inc) { dscal_((int*) &n, (double*) &scale, data, (int*) &inc); } mycblas_dscal calls blas library implementation dscal_ . library expects pointers data , wrapper passes address of n , scale , inc directly. scares me since passed value , literals. when executed mycblas_dscal nothing, i.e. a unchanged or seg. faults. higher compiler optimizations (e.g. gcc -o3) ever seg. faults. to test blas

android - Google maps Pushpin Error -

i want show particular location on map , on perticular location want put pushpin notification. have tried below code showing nullpointer exception please me add markers. public class mapdemoactivity extends mapactivity { mapview mapview; mapcontroller mc; geopoint p; class mapoverlay extends com.google.android.maps.overlay { @override public boolean draw(canvas canvas, mapview mapview, boolean shadow, long when) { super.draw(canvas, mapview, shadow); //---translate geopoint screen pixels--- point screenpts = new point(); mapview.getprojection().topixels(p, screenpts); //---add marker--- bitmap bmp = bitmapfactory.decoderesource( getresources(), r.drawable.pushpin); canvas.drawbitmap(bmp, screenpts.x, screenpts.y-50, null); return true; } } public void oncreate(bundle save

ASP.Net MVC varying required fields -

i have single form used create similar items. simplify scenario demonstration. you can create 1 of many "content types". can choose add "file", "folder", "announcement", etc. use /home/addcontent?contenttype=file determine options show in view. each content item has following. name description (optional) a "file" has: list item filepath an announcement has: priority displayhomepageflg (optional) i add of these 1 viewmodel of data annotations modelstate.isvalid never true since each "content type" has unique properties. is there programatic way add or exclude specific data annotations or should have separate viewmodel , controller each content type? the way can think of use remotevalidationattribute . look here sample then in controller, not use modelstate.isvalid, validation in business logic layer you can think of using jquery.validation own scripts check fields

how to get cell tower location in android -

i want find nearest cell tower location. tried private class servicestatehandler extends handler { public void handlemessage(message msg) { switch (msg.what) { case my_notification_id: servicestate state = mphonestatereceiver.getservicestate(); system.out.println(state.getcid()); system.out.println(state.getlac()); system.out.println(mphonestatereceiver.getsignalstrength()); break; } } } i tried link not working me how find user location using cell tower? i think doing wrong. because link answer working other person did same code shown in link using 2,2 google api create project not able cell tower location the code have doesn't wait intent in activity oncreate fetches reference telephony service , when displaying calls getcelllocation() when required. m_manager = (telephonymanager)getsystemservice(context.telephony_service); gsmcelllocation l

Facebook Page Load Concept -

i know page reload concept via ajax without page refresh. facebook pages reload through normal page load. sidebar's not loading reload content area. how possible? advance friends facebook uses bigpipe the general idea decompose web pages small chunks called pagelets, , pipeline them through several execution stages inside web servers , browsers. implemented entirely in php , javascript. clicking , taking action on webpage initialize/executes pagelet, response generates iframe or ajax well. read response , show small chunk, not refresh page.

c# - Error XmlSiteMapProvider does not exist -

/// this agent.sitemap <sitemapnode url="default.aspx#" title="start" description="start"> <sitemapnode url="~/dircommon/default.aspx" title="home" description="home" /> <sitemapnode url="diragent/profile.aspx#" title="agent" description="agent"> <sitemapnode url="diragent/profile.aspx" title="my profile" description="agent:my profile" /> <sitemapnode url="diruser/account.aspx" title="my account" description="agent:my account" /> <!--<sitemapnode url="diruser/downloads.aspx" title="downloads" description="agent:downloads" />--> </sitemapnode> <sitemapnode url="diragent/default.aspx" title="calls" description="calls"> <sitemapnode url="diragent/callqueue.asp

php - Google Map v3 Shortcode WP Plugin - Generate new Map over old? get Current Location? -

i using google map v3 shortcode plugin each post have own google map (for ex: [map address="new york, usa" z="15" marker=”yes” ]) i want users type in location (or not) , direction - should cause create new google map direction route. so wrote: <form class="searchform" action="<?php the_permalink(); ?>" method="post" > <input type="text" value="<?php echo $address; ?>" name="directions_search" class="field s"> <input type="submit" value="get directions" name="submit" class="submit button"> </form> <?php if(isset($_post['directions_search'])){ $address = htmlspecialchars($_post['directions_search']); echo do_shortcode('[map address="queens, new york" z="15" marker=”yes” start= "'. $address .

c# - Unit Test existing UI code -

i browsing while internet , site , instead of finding ways unit test existing code finding separate logic , interaction user (mvc approach). although great new projects time-consuming , result expensive invest existing ones. there way create specific unit tests, ideally automated, existing gui projects unfortunately connect directly databases or other systems data , data manipulated before shown? have 2 projects 1 being mfc, other c# .net 2.0 lot. unit testing won't cut in here considering can't change existing code (not mention don't unit test ui). should kind of gui testing automation/scripting tools. sikuli . quoting literally first paragraph website: sikuli visual technology automate , test graphical user interfaces (gui) using images (screenshots). it doesn't simplier that. "tell" tool parts of ui should observe/interact, records , replays it. skimming through this presentation give idea of can (might check video). won't solve pr

c# - .net Parallel and Serial looping -

we build pattern around loops in our solution, allow them run in serial, or parallel, depending on factors. below general form of it. since concurrent collections dont share common interface regular collections, need sort of adapter write general code. specifically around usage of addfunc delegate in loop body, there there end causing problems in long term might miss? runs fine of now, but....? action<sometype> addfunc; if(runinparallel) { addfunc = concurrentbag.add; loopdelegate = parallel.foreach; } else { addfunc = ilist.add; loopdelegate = serial.foreach; // wrapper delegate foreach } loopdelegate(source, item => { sometype result = longrunningtask(item); ... addfunc(result); // }); curious why not use tpl in .net 4.0? http://msdn.microsoft.com/en-us/library/dd537609.aspx there excellent white paper of considerations have taken when developing tpl, if can't use .net 4, should @ paper , consider of gotcha's in there.

javascript - DropDownList Dependencies and Selections Using jQuery -

i have 6 dropdownlist shown below: option1 option2 option3 option4 option5 option6 when change option1 want change option3 , option5. when change option2 want change option4 , option6. these list can in number. here example: option1 option2 option3 option4 option5 option6 option7 option8 option9 now when change option1 option4 , option7 change. when chanage option5 option2 , option8 change. when change option9 option6 , option3 change. think u can see pattern. i solved part of problem assigning same classes related options. data coming database , cannot assign classes since don't know options in group. if move these options in array how can make dependencies between them? you can assign function each option triggered "change" event , change other options.

c++ - What changed in the driver signature requirements for Windows 8? -

i've got passthrough ndis intermediate driver, consisting of 2 .inf files (one standard , 1 miniport) , .sys file. because of windows 7 driver signing requirements, had code-signing certificate , sign .sys file in order driver install on 64-bit system. works fine, , have many successful windows 7 installs. however, same installer fails on windows 8 consumer preview (64-bit). if boot windows signature enforcement turned off, installs correctly, it's signature issue. new requirements added between windows 7 & windows 8 need follow in order driver install? regenerate cat file(s) comply signing requirements new window os. for example, in build script had add 8_x86,8_x64 inf2cat command: inf2cat /driver:"%cd%" /os:xp_x86,xp_x64,vista_x86,vista_x64,7_x86,7_x64,8_x86,8_x64 for windows 8.1, need inf2cat included in windows driver kit (wdk) 8.1 , depending on target(s) add 6_3_x64 , 6_3_x86 , or 6_3_arm /os:windowsversionlist. reference, inf2c

php - How to speed up AJAX? -

i have custom ajax survey script. want improve efficiency of how handles information speed users. css needed style subsequent ajax view located in website's main css shares many similar selectors, , cached on load using.. <filesmatch "(?i)^.*\.(ico|flv|jpg|jpeg|png|gif|js|css)$"> header set last-modified "tue, 31 aug 2010 00:00:00 gmt" header set expires "thu, 15 apr 2014 20:00:00 gmt" header set cache-control "public, no-transform" </filesmatch> will ajax use cached information reduce round trip request time? html markup each subsequent ajax view different understand info have fetched, parsed, , returned. if setting caching headers can't job, seems client side scripting directed check cache information first, if needs more information go server (such html markup.) any appreciated. hope can set me on right path here. those directives won't affect php script being requested via ajax. 1 thing should

objective c - Issues with changing UINavigationBar background when presenting modal view controller -

i using this method change backgrounds of uiviewcontrollers. works when push view controller. however, if viewcontroller presented using [self presentmodalviewcontroller:customviewcontroller animated:yes]; then, code doesnt work. can kindly suggest whats wrong ? code used: to have image in navigation bar, have draw yourself, isn't hard. save uinavigationbar+custombackground.m (it adds custom category uinavigationbar): @implementation uinavigationbar (custombackground) - (void)drawrect:(cgrect)rect { uiimage *image = [uiimage imagenamed:@"navmain.png"]; [image drawinrect:cgrectmake(0, 0, self.frame.size.width, self.frame.size.height)]; } @end if running on ios 5, drawrect: no longer called you need either use uiappearance or subclass uinavigationcontroller , use change image. a tutorial uiappearance can found here ( drawrect: still work on versions below ios 5)

javascript - How to force a script reload and re-execute? -

i have page loading script third party (news feed). src url script assigned dynamically on load (per third party code). <div id="div1287"> <!-- dynamically-generated elements go here. --> </div> <script id="script0348710783" type="javascript/text"> </script> <script type="javascript/text"> document.getelementbyid('script0348710783').src='http://onebighairyurl'; </script> the script loaded http://onebighairyurl creates , loads elements various stuff news feed, pretty formatting, etc. div1287 (the id "div1287" passed in http://onebighairyurl script knows load content). the problem is, loads once. i'd reload (and display new content) every n seconds. so, thought i'd try this: <div id="div1287"> <!-- dynamically-generated elements go here. --> </div> <script id="script0348710783" type="javascript/t

forms - Google Chrome creates history item on redirect? -

when following redirect after form submission goes page you're on, experience has been clicking on browser button take page on before page, before form submission. for example, enter site and: 1. (click) /home 2. (click) /user/view 3. (click) post /user/save_changes 4. (redirect) /user/view the behavior in firefox after form submission , redirect (#4), clicking "back" take #1 (get /home) #4. in chrome, clicking after redirect takes #2 (get /user/view). i don't recall being behavior in past... , appears happen on chrome. happens both 301 , 302 redirects. is there way avoid behavior? i've done way because behavior has been acceptable (goes #1 upon clicking after form submission). did avoid ever clicking , getting horrible "do want resubmit form" message. html5 provides cool option control browser behavior - html5 history api. guess, instead of depending on browser handle on own, better instruct browser how handle it.

facebook - Best practice for handling secondary page requests -

when building facebook tab application first page receives signed request, question best practice handle secondary requests. save related information in cookie have on secondary requests seems little unsecured me. i curious recommend way handle basic situation. thanks. the signed request intermediate step getting access_token , userid. i put access token session, , encrypt , save in cookie. facebook app development has taught me go belt-and-suspenders when comes authentication.

tsql - SQL function from Latin to Cyrillic -

i looking ms sql function make translit latin cyrillic. have completed solution? (for example, 'spasibo' -> 'спасибо') create function dbo.tocyrillic ( @str nvarchar(max) ) returns nvarchar(max) begin -- declare return variable here declare @inputlength int declare @i int declare @latinsymbol nvarchar(2) declare @cyrillicsymbol nvarchar(2) declare @outputvalue nvarchar(max) set @outputvalue=n'' set @inputlength=len(@str) set @i=1 declare @transtable table (uppercyr nvarchar(2) collate cyrillic_general_ci_as, lowercyr nvarchar(2) collate cyrillic_general_ci_as, lowerlat nvarchar(2), cid int primary key identity(1,1)) insert @transtable values (n'А', n'а', n'a') insert @transtable values (n'Б', n'б', n'b') insert @transtable values (n'В', n'в', n'v')

OpenCL force buffer to stay on the GPU -

is there way force opencl keep data in global memory buffer on chip (i.e. never gets swapped out system memory)? want reserve portion of gpu's memory own needs, , want data put there remain on gpu regardless of whether other applications start saturating gpu's memory. thanks! gpu's aren't linked cpus memory management unit, don't page faults cpu. block device peripherals controlled device drivers. for opencl when allocate memory on gpu creating cl_mem object , enqueueing (writing) gpu stick around until explicitly release clreleasememobject. reuse buffer need not release , keep track of cl_mem object.

How to read input from STDIN in x86_64 assembly? -

i trying learn x86_64 assembly , trying standard input output today , stumbled upon post learning assembly - echo program name how same reading input stdin (using syscall instruction)? if know input integer , want read register? edit: @daniel kozar's answer below helped me understand how stdin , stdout stuff work syscall instruction on linux. attempted write small program, reads number console input , prints ascii character corresponding number. if type 65 input, should output. , new line character. if @ all, helps 1 else :-) section .text global _start _start: mov rdi, 0x0 ; file descriptor = stdin = 0 lea rsi, [rsp+8] ; buffer = address store bytes read mov rdx, 0x2 ; number of bytes read mov rax, 0x0 ; syscall number reading stdin syscall ; make syscall xor rax, rax ; clear off rax mov rbx, [rsp+8] ; read first byte read rsp+8 stdin call rbp sub rbx, 0x30 ; since read character, obtained ascii va

ruby on rails 3 - Stubbing :find on a Model Class -

given model method self.fetch_payment_method : def self.fetch_payment_method name = "omnikassa" pm = spree::paymentmethod.find(:first, :conditions => [ "lower(name) = ?", name.downcase ]) || raise(activerecord::recordnotfound) end and rspec test test this: it 'should find payment_method' spree::paymentmethod.new(:name => "omnikassa").save @omnikassa.class.fetch_payment_method.should be_a_kind_of(spree::paymentmethod) end i'd improve this, not test entire stack , database. that, i'd want stub ":find" when called on class spree::paymentmethod . however: it 'should find payment_method' spree::paymentmethod.any_instance.stub(:find).and_return(spree::paymentmethod.new) @omnikassa.class.fetch_payment_method.should be_a_kind_of(spree::paymentmethod) end does not work. rather new whole bdd/tdd thing , stubbing , mocking still magical me; misunderstand stubbing , returning doing exactly. how shou

c++ - How to delete this 2-dimensional array of pointers? Making a destructor -

malla = new celula**[n + 2]; for(int = 0 ; < n + 2 ; ++i){ malla[i] = new celula*[m + 2]; for(int j = 0 ; j < m + 2 ; ++j){ malla[i][j] = new celula[m]; } } i'm making code , allocate memory (i want n*m array of pointers celula, okay? need destructor. now don't know how access object in array and: malla[i][j].setestado(true); doesn't work. seriously consider advice of @konrad's . if anyhow want go raw array's , can : to deallocate : for(int = 0 ; < n + 2 ; ++i) { for(int j = 0 ; j < m + 2 ; ++j) delete[] malla[i][j] ; delete[] malla[i]; } delete[] malla; to access object : malla[i][j][_m].setestado(true); edit : if malla[i][j] pointer object destructor/deallocation : for(int = 0 ; < n + 2 ; ++i) { for(int j = 0 ; j < m + 2 ; ++j) delete malla[i][j] ; delete[] malla[i]; } delete[] malla; access object/member can done : (*malla[i][j]).setestado(true); or malla[i][j]->

CUDA memset in Compute Visual Profiler -

Image
i use compute visual profiler measure performance of cuda programs. the result of profiler shows 2 different results cudamemset function. memset32_post memset128 i want know difference between these 2? i guess memset128 kernel bulk of work , memset32_post kernel cleans remainder since used size not multiple of 128. there's nothing worry about, it's trying implement memset in efficient manner possible, although i'd try avoid memset in inner-loop (on processor). if you're worried over-allocate.

swing - Java - Screen turns black, when setting a JFrame to Fullscreen -

i'm trying draw on canvas, add jframe , set jframe fullscreen. problem is: in fullscreenmode see black screen. before screen turns black shortly can see pink background of canvas. drawing directly on jframe , setting fullscreen works fine , can see testtext. assume there problem displaying canvas properly. here code: public class fullscreentest extends canvas { private jframe mainframe; public fullscreentest(){ this.mainframe = new jframe(); jpanel contentpane = (jpanel) mainframe.getcontentpane(); contentpane.add(this); } public void run(displaymode dm){ setbackground(color.pink); setforeground(color.white); setfont(new font("arial", font.plain, 24)); screen s = new screen(); s.setfullscreen(dm, this.mainframe); try { thread.sleep(5000); } catch (interruptedexception exc) { exc.printstacktrace(); } s.closefullscreenwindow(); } publ