Posts

Showing posts from September, 2015

razor - Is this a bug in WebMatrix PageData? -

i think may have found bug in webmatrix's pagedata, not sure. concerns how pass data partial page calling page. in webmatrix documentation (tutorials, e.g. " 3 - creating consistent look ", , example code), pagedata recommended mechanism pass data between pages (e.g. content page layout page, or partial page). however have found not work other way, pass data partial page calling page. modifying or adding entries in pagedata in partial page, not seem calling page. cutting right down simplest possible example, in test page may have this: @{ pagedata["test"] = "initial entry"; } <p>before calling partial page, test value @pagedata["test"]</p> @renderpage("_testpartial.cshtml") <p>after returning calling page, test value @pagedata["test"]</p> and in _testpartial.cshtml page might have this: @{ pagedata["test"] = "modified entry"; } <p>in partial page...

iphone - Requiring the presence of a method in an id -

the situation my custom controller class has following method: - (void)requestviewcontrollerwithidentifier:(nsstring *)identifier fromobject:(id)object; this causes object receive message: - (uiviewcontroller *)viewcontrollerwithidentifier:(nsstring *)identifier; the problem right now, object id there's no guarantee implements method, , compiler warning when send message. the solution i came 2 solutions myself: use protocol. make id nsobject , create category nsobject . they both fine solutions , don't mind choosing 1 of them, but... the question ...i noticed apple doing odd in gamekit api. gksession has following method: - (void)setdatareceivehandler:(id)handler withcontext:(void *)context handler id , apple requires implement method: - (void) receivedata:(nsdata *)data frompeer:(nsstring *)peer insession: (gksession *)session context:(void *)context; without making use of protocol or category! i'm wondering how , why thi...

Bug Silverlight Intelliscence in VS 2010 does not recognize new controls on page -

silverlight intelliscence in vs 2010 not recognize new controls on page. solution needs built intelliscense recognized newly placed control (textbox label extra) is bug? edit: controls not custom, siple label , textbox , button controls. edit: button toolbox dragged designer, switched home.xml.cs types button1 error, intelliscence doesnot recognize button1 added. must build each time. what solution problem its not bug, feature. custom controls must compiled before can use it.

c++ - Template metaprogramming rules of thumb -

what rules of thumb should considered whenever might use template metaprogramming accomplish goal? , good example using template metaprogramming more efficient plain old code other libraries boost ? one helpful rule can think of have compilation error thrown close "true" problem possible. ways it's easier not deduce issue easier others use library deduce issue. here's contrived version of mean: template<typename type> struct convert{}; template<> struct convert<double>{ static const int value = d_coord; }; template<> struct convert<degree>{ static const int value = angle_coord; }; template<> struct convert<radian>{ static const int value = radian_coord; }; for you'll not salient description of compiler error attempting convert<int> when if had made first declaration forward declaration tell there no type defined "convert." as far example, i'm afraid i'll have defer else. how...

xslt - Is it possible to select a node that just includes a subset of the child nodes? -

i have xpath: //tbody/tr[2]/td/div/table/tbody/tr[2]/td[position() > 1] which gives me first child node. however, gives me nodelist of td notes result. want select parent tr node, first child td node removed. is possible using xpath? xpath query language xml documents. such cannot modify structure source xml document or create new xml document. the task of creating new, modified document cannot done xpath only. this easy accomplish xslt : <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/xsl/transform" xmlns:xs="http://www.w3.org/2001/xmlschema"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <xsl:template match="tr[2]/td[1]"/> </xsl:...

Suppressing sign-extension when upcasting or shifting in Java -

i have feeling rather trivial question, i'm stumped. in application i'm keying things in lookup table pair of ints. thought easier concatenate 2 ints 1 long , use single long key instead. coming c background, hoping work: int a, b; long l = (long)a << 32 | b; my attempts replicate in java have frustrated me. in particular, because there no unsigned integral types, can't seem avoid automatic sign-extension of b (a gets left-shifted irrelevant). i've tried using b & 0x00000000ffffffff surprisingly has no effect. tried rather ugly (long)b << 32 >> 32 , seemed optimized out compiler. i hoping strictly using bit manipulation primitives, i'm starting wonder if need use sort of buffer object achieve this. i use utility class with public static long compose(int hi, int lo) { return (((long) hi << 32) + unsigned(lo)); } public static long unsigned(int x) { return x & 0xffffffffl; } public static int high(long x)...

Android json parsing -

how parse type of json arrary [{'name':'john', 'age': 44}, {'name':'alex','age':11}] where can't this: jsonarray datalistarray = jobject.getjsonarray("???"); you can use string initialize json array. string json = "[{'name':'john', 'age': 44}, {'name':'alex','age':11}]"; jsonarray json = new jsonarray(json);

Java open-source web framework -

i'm working on project front-end has mobile application or website.i want back-end in java.i want use rest communication between front-end , back-end. question : there java web framework has kind of user management (with maybe webservices login , signup users). example login details can send front-end webservice , see if it's correct etc.. i suggest using grails has rich catalog of plugins, including spring security plugin should require without having write code. if must use java only, spring mvc spring security option.

Java try catch blocks -

here simple question : what think of code use try catch every instruction ? void myfunction() { try { instruction1(); } catch (exceptiontype1 e) { // code } try { instruction2(); } catch (exceptiontype2 e) { // code } try { instruction3(); } catch (exceptiontype3 e) { // code } try { instruction4(); } catch (exceptiontype4 e) { // code } // etc } i know that's horrible, want know if decreases performance. try this: (i know doesn't answer question, it's cleaner) void myfunction() { try { instruction1(); instruction2(); instruction3(); instruction4(); } catch (exceptiontype1 e) { // code } catch (exceptiontype2 e) { // code } catch (exceptiontype3 e) { // code } catch (exceptiontype4 e) { // code } // etc }

Google Maps Save Polygon and points in MySQL using PHP -

right have application allows users draw polygon on google maps. need save polygon using php , mysql i'm unsure of best practices. should enable spatial extensions , save geometry? should save each vertical (lat/lng pair) in array? approach i'm unaware of? i'm wondering best practices are. using mysql spatial extensions seem daunting. returns things in wkt , have parse text make else. seems convoluted. it's best think of usage scenarios when planning out storage layer. this figure out queries you'll want persistence layer optimize for. if you're going handle lot's of queries like, "find me objects within space". may want @ using spatial extensions. however, if of time you're drawing object given id, saving polygons json blob in db may do. create table polygons ( polygon_id int not null, vertices_json varchar(4096) )

How to know which version of ASP.net it is? -

how can know version of asp.net built in looking asp.net project. please list different ways identify version? thank you you need careful approach use here because updates .net framework under asp.net seemingly run under previous version numbers. example; asp.net 2.0 websites might running v2.0 or v3.5 frameworks and asp.net 4.0 websites might running v4.0 or v4.5 frameworks there couple of ways check exact version running, on web page add: <%= system.environment.version.tostring() %> as example; if have v4.0 installed you'll see v4.0.30319.1008 if have v4.5 installed you'll see v4.0.30319.34209 that running version. can check registry installed versions at: hkey_local_machine\software\microsoft\net framework setup\ndp\v4\full within location @ version node. if have v4.0 installated see v4.0.30319 if have v4.5 installated see v4.5.51209

python - Why does os.path.getsize() return a negative number for a 10gb file? -

i using function os.path.getsize() gives size of file in bytes. as 1 file size 10gb give me size in negative(bytes). so can give me idea why happen? this code: import os ospathsize = os.path.getsize('/home/user/desktop/test1.nrg') print (ospathsize) your linux kernel has large file support, since ls -l works correctly. thus, it's python installation lacking support. (are using distribution's python package? distribution it?) the documentation on posix large file support in python states python should typically make use of large file support if available on linux. suggests try , configure python command line cflags='-d_largefile64_source -d_file_offset_bits=64' opt="-g -o2 $cflags" \ ./configure and finally, quoting man page of stat system call : this can occur when application compiled on 32-bit platform without -d_file_offset_bits=64 calls stat() on file size exceeds (1<<31)-1 bits. (i believe l...

algorithm - chain of events analysis and reasoning -

my boss said logs in current state not acceptable customer. if there fault, dozen of different modules of device report own errors , land in logs. original reason of fault may buried somewhere in middle of list, may not appear on list (given module being damaged report), or appear way late after else finished reporting problems result original fault. anyway, there few people outside system developers can interprete logs , come happened. my current task writing module customer-friendly fault-reporting. is, gather events reported on last ~3 seconds (which max interval between origin of fault occurring , last resulting after-effects), magic processing of data, , come 1 clear, friendly line broken , needs fixed. the problem magic part: how, given number of fault reports, come original source of fault. there no simple list of cause-effect list. there commonly occurring chains of events displaying regularities. examples: short circuit detected, resulting in limited operation mod...

redirect - nginx - can't figure out location for / only -

i struggled lot how redirects , stuff when enter www.example.com or www.example.com/ couldn't. location / {} takes cases tried: location ~ ^/?$ {} or location ~ ^/$ {} and many others none worked www.example.com or www.example.com/. please help... need match exact location when enter www.example.com or www.example.com/. thanks! have tried: location = / {}

Finding circular references in VB6 -

i'm trying compile code in vb6, , tells me "circular dependencies between modules." doesn't deign tell me modules have these dependencies. is there way can find more information problem? you have projects form circular chain of references. use menu project , references see other projects references. other projects part of application. draw rough graph of links , @ point find references loop 1 of projects. you need focus on references projects created yourself. need check projects created includes custom activex controls. found under menu project->components. likely find there handful of classes referencing. in case can separate them out activex dll/library , have original projects reference instead of each other. the reason issue arises because com relies type libraries embedded in library call classes , methods. referenced libraries included in typelib in manner similar include file in c. circular references have no "bottom" com can...

c++ - Creating an object on the heap without new -

in c++, possible create object on heap without using new or malloc ? i think if use stl container vector put on heap. if do: vector<object> listobjs = vector<object>(); object x = object(...); ... listobjs.push_back(x); where objects created here reside? the object denoted x resides on stack. vector::push_back copy heap. the allocator object inside vector implemented using new or malloc , although possible uses another, low-level api. instance, both unix , windows offer memory mapping apis, in turn may used implement malloc , new , allocators.

What else i can use instead of class for Jquery selector? -

for buttons using class assigning css classes. have define selector those. know can use class jquery selector else can use , how ? they rendered input not buttons. <asp:button id="imgbtnturkish" onmouseover="this.style.cursor='pointer';" class="defaulttitle" title="turkish spoken chat section" runat="server" onclick="btnturkishchat_click" causesvalidation="false" /> there many jquery selectors choose from. 1 possibility select button wrap in div element given class: <div class="defaulttitle"> <asp:button id="imgbtnturkish" onmouseover="this.style.cursor='pointer';" title="turkish spoken chat section" runat="server" onclick="btnturkishchat_click" causesvalidation="false" /> </div> and use following selector: $('.defaultti...

Key to maxima of dictionary in python -

i have dictionary, "scores", of integers , want find key(s) of highest value. used code: key = max(scores, key=scores.get) however, gives 1 key. how deal ties in highest value? 1 number back. in case of tie? how can keys highest value? help. you run following, example: max_value = max(scores.values()) keys = [ (i,v) in scores.iteritems() if v == max_value ] "keys" hold keys correspond maximum value.

formatting - Enable grow of cross tab in crystal report -

i using cross-tab object in crystal report. having problem making data column (field row) increase dynamically in height when data size increases. since "can grow" property in format editor disabled, not let me set "can grow" true enable function. how enable "can grow" function can set true? i ran similar problem row labels did not wrap. sadly, think best solution increase height of "data" row field (probably bottom row). fix height rows means text in rows able wrap @ same height. i going post image don't have rep.

php - Website with optimal cache control -

my goal let browsers cache whole website, download static content when have changed 1 or more files. my situation after research have found way this. add far future expires header htaccess file , add querystring files using filemtime() function. the problem when click on address bar , type in website address in firefox, firebug displays 38.3 kb (36.4 kb cache) when press f5 in firefox, firebug displays: 241.1 kb (10.9 kb cache) now have tried same google , sending http header 304 back. have read lot etag , last modified header, have heard lot of people saying not reliable. my question best solution if send http header 304 static content if user presses on f5, google? i asking question because visiting website , using f5 see if there new information available. not reload images etcetera. update seems firefox controlling way cache used , use cache when user presses f5. the purpose of reload reload page. there no server-side header magic if browser witten...

design - Why does the java.util.Set<V> interface not provide a get(Object o) method? -

i understand 1 instance of object according .equals() allowed in set , shouldn't "need to" object set if have equivalent object, still have .get() method returns actual instance of object in set (or null) given equivalent object parameter. any ideas/theories why designed this? i have hack around using map , making key , value same, or that. edit: don't think people understand question far. want exact object instance in set, not possibly different object instance .equals() returns true. as why want behavior, typically .equals() not take account properties of object. want provide dummy lookup object , actual object instance in set. while purity argument make method get(object) suspect, underlying intent not moot. there various class , interface families redefine equals(object) . 1 need no further collections interfaces. example, arraylist , linkedlist can equal; respective contents merely need same , in same order. consequently, there reasons f...

c# - Separate threadPool for each task -

i've got application has 2 main task: encoding, processing video. these tasks independant. each task run configurable number of threads. reason 1 task use threadpool , setmaxthreads. i've got 2 tasks , "two configurable(number of threads) threapool each task". well, threadpool static class. how can implement strategy(easy configurable number of threads each task). thanks you want own thread pool. if using .net 4.0 easy roll own if use blockingcollection class. public class customthreadpool { private blockingcollection<action> m_workitems = new blockingcollection<action>(); public customthreadpool(int numberofthreads) { (int = 0; < numberofthreads; i++) { var thread = new thread( () => { while (true) { action action = m_workitems.take(); action(); } }); thread.isbackground = true; thread.start(); } } public void q...

objective c - How to remove the repeated data in the pickerview in iphone? -

i have array 10 data. i'm showing value of array in pickerview. out of 10 values in array 4 data same example there apple 4 times. how remove repeated data , show 1 time apple in picker. you can remove duplicate data array like: nsarray *cleanedarray = [[nsset setwitharray:yourarray] allobjects];

Can I use WCF for communicating (sending message) between 2 applications? -

i have problem regarding wcf .can that:- i want create wcf service,window service & silverlight application.and want send message(data) window service silverlight application through wcf service. and vice-versa.is possible. thanks & regards, vipin kumar it possible, if receiving side has listener listen messages reply needed messages. think looking pub/sub solution communicated between 2 different processes.

iphone - AVCaptureSession for Audio and Video combined - Audio part gives EXC_BAD_ACCESS -

i've made wonderful little app called night cam can record night vision effect videos. i'm in process of updating @ moment. the video capture works absolutely fine audio not. there problem occurs turn on application when no recording file taking place (i change activate audio when recording later). here relevant code: session = [[avcapturesession alloc] init]; session.sessionpreset = avcapturesessionpresetmedium; camera = [avcapturedevice defaultdevicewithmediatype:avmediatypevideo]; microphone = [avcapturedevice defaultdevicewithmediatype:avmediatypeaudio]; avcapturedeviceinput * camera_input = [avcapturedeviceinput deviceinputwithdevice:camera error:nil]; [session addinput:camera_input]; avcapturedeviceinput * microphone_input = [avcapturedeviceinput deviceinputwithdevice:microphone error:nil]; [session addinput:microphone_input]; avcapturevideodataoutput * output = [[avcapturevideodataoutput alloc] init]; output.videosettings = [nsdictionary dictionarywithobject: [...

java - How to "crossover" two strings (1234 & abcd -> 12cd & ab34) -

Image
am developing genetic algorithm in java, of them, requires crossover of 2 parent chromosomes. these chromosomes can quite long, anywhere 30 500 (but whatever length have, same size, if length 80, in ga run 80). i thought of developing in different ways seem me inefficient, thought might ask new, different points of view , suggestions. for example, 1 of ways thought of converting string array of characters , iterating start point end of crossover locus (ie s1 & s2[25] s1 & s2[40] ) copying temporal arrays each of arrays characters between points , iterating again , swapping them characters temporal array of "partner". said seems program have population of 1000 chromosomes , around 1000 generations extremely slow. here illustration of two-point crossover looks like: there easier 1 point crossover: as not advanced @ in java advice me on approach take, maybe java function unaware of, or algorithm implement? // chromosomes string s1; strin...

c# - how to transfer a files one system to another system -

how transfer files folder of 1 system system in particular folder in c#.net can me on topic if have unc proper permissions can this: file.copy(sourcefile, uncdestinationfile); you can find out more reading documentation here . if not familiar unc paths suggest read on here . usually unc looks like: \\machine\destinationfolder

asp.net mvc - Razor - Render without Render() and without Encoding -

can please explain how following following achieved. telerik grid component generate non-encoded html following code: @(html.telerik().grid(model) .name("grid") .datakeys(keys => keys.add(c => c.productid)) .databinding(databinding => databinding.server() .select("columnsettings", "grid") .update("columnsettings_save", "grid") .delete("columnsettings_delete", "grid")) .columns(columns =>columns.loadsettings((ienumerable<gridcolumnsettings>)viewdata["columns"])) .sortable() ) presumably happens because method call wrapped in "@(....)". whenever try own components result encoded html. know can use render() output mvchtmlstring , html not encoded telerik grid seems achieve without .render(). can explain secret me? the @( ) syntax allows command span multiple lines (otherwise line break int...

c# 3.0 - What is difference between ArrayList and Hashtable in C#? -

i want store collection of data in arraylist or hastable data retrival should efficient , fast. want know data structure hides between arraylist , hastable (i.e linked list,double linked list) an arraylist dynamic array grows new items added go beyond current capacity of list. items in arraylist accessed index, array. the hashtable hashtable behind scenes. underlying data structure typically array instead of accessing via index, access via key field maps location in hashtable calling key object's gethashcode() method. in general, arraylist , hashtable discouraged in .net 2.0 , above in favor of list<t> , dictionary<tkey, tvalue> better generic versions perform better , don't have boxing costs value types. i've got blog post compares various benefits of each of generic containers here may useful: http://geekswithblogs.net/blackrabbitcoder/archive/2011/06/16/c.net-fundamentals-choosing-the-right-collection-class.aspx while talks ge...

algorithm - Doubts in Python code -

i'm reading book of algorithms in python, , i'm new python. i can't understand example: class bunch(dict): def __init__(self, *args, **kwds): super(bunch, self).__init__(*args, **kwds) self.__dict__ = self x = bunch(name="jayne cobb", position="public relations") print x.name some questions: what meaning of * , ** in parameters "args" , "kwds"? what meaning of "super"? in classe extending "dict" class? built-in class? best regards, *args means: collect parameters without name in list: def x(a, *args): pass x(1, 2, 3) assigns a=1 , args=[2,3] . **kwargs assigns parameters name dict kawrgs : def x(a, **kw): pass x(1, b=2, c=3) assigns a=1 , kw={b=2, c=3} . the code super(bunch, self).__init__(*args, **kwds) reads: call method __init__ of bunch instance self , parameters *args, **kwds . it's standard pattern initialize superclasses ( docs super )...

ms access - SQL query to calculate the difference between current and previous day's value -

i have access .mdb database table looks similar to: +---------+------+--------+ | date | value | +---------+------+--------+ |2011-05-04 12:00 | 45.9 | |2011-05-05 12:00 | 21.2 | |2011-05-06 12:00 | 32.2 | |2011-05-07 12:00 | 30.4 | |2011-05-08 12:00 | 40.4 | |2011-05-09 12:00 | 19.8 | |2011-05-10 12:00 | 29.7 | +-------+---------+-------+ i create query return values derived subtracting 1 value previous day value. for example: query calculate (21.2-45.9) , return -24.7 (32.2-21.2) , return -11.0 (30.4-32.2) , return -1.8 etc how can accomplish in select statement? you can use query employs self-join on table in question: select t.datevalue , t.singlevalue - iif(isnull(tnext.singlevalue), 0, tnext.singlevalue) test t left join test tnext on t.datevalue = dateadd("d", -1, tnext.datevalue) t.datevalue = #2011-05-08 12:00#; outputs datevalue expr1001 ---------------------- ---------------- 05/08/2011 12:...

c# - SQL Server Analysis Service 2008 R2 LONG CONTINUOUS Data Type -

i've been seraching data type of long continuous in sql server analysis services 2008 r2. can point me documentation? i found description of data types , said nothing on actual data. what c# equivalent? i using adomddatareader.getint32() , increased predictions , few records came data either "too small" or "too large". okay figured out. int64 retrieving adomddatareader.getint32() or adomddatareader.getint64() work. long int64, should've been answer start. problem in past i've had other data types , had had problems not putting specific data type, guess in case putting lower data type (int32 intsead of int64) , allowed me that. in past had tried getting int16 calling int32 , gave me problems. yes problem resolved. next issues why analysis service generating such huge number, guess that's not question heh.

jquery - Using JavaScript to "Create" a Microsoft Word Document -

i dynamically create document using javascript , open document in microsoft word. possible? here current code: <html> <head> <title></title> <script src="js/jquery-1.4.4.js" type="text/javascript"></script> </head> <body> <div id="mydiv">the quick brown fox jumped lazly on dead log.</div> <script type="text/jscript"> var printwindow = window.open("", "print", "width=800,height=400,scrollbar=0"); var printareahtml = $("#mydiv").attr("outerhtml"); printwindow.document.open("text/html", "replace"); printwindow.document.writeln("<html><head>") printwindow.document.writeln("<meta http-equiv='content-type' content='application/vnd.ms-word'>"); printwindow.document.writeln("<meta http-equiv=...

php - Receipt printer - print automatically when someone placed an order? -

i have bought receipt printer , connected serial com1 on computer. want print receipt automatically when placed order online. how can done? i developed shopping cart website in php / mysql; server located @ data center. ok website in datacenter, , printer @ home, kind of sounds it's not going work... here's need: - network printer or printer server allows add jobs via web api - api must reachable outside (from datacenter) need static ip or service dyndns... - need extend website send receipt printer queue but if you, wouldn't start on making happen... a better solution might program runs on local computer , connects database of website check wether orders placed, , creates receipt , sends printer...

asp.net mvc 3 - CQRS Commands as Models for POST actions -

i'm getting started cqrs, , thought make sense use command object model on forms. can take advantage of of client-side validation commands using dataannotations, client-side validation, makes pretty clean... my question... raise problems? if command not have default constructor, make process impossible? need create own commandmodelbinder can constructor inject aggregate id? your thoughts, can't find technique anywhere , im assuming because doesn't work. i'd recommend take @ greg young's article on task-based ui's on how dtos , messages interact system (both client-side , server-side). i agree sebastian commands match user interface like. result, you'll need have separate dto/model classes , commands. that's not bad thing model result of query-side of system , shouldn't exact duplicate of messages you're sending system. also, keeping commands separate model, concern command constructors goes away. controller collects in...

Comprehensive Silverlight rendering resource? -

is there reference available gives comprehensive @ how silverlight renders controls in application? kinds of things need know: what bounding rectangle of control x? point p inside control x? control x visible user? how manually replicate silverlight's hit testing? rendering , hit testing behavior seem governed large numbers of properties both on control x , on of containers visual tree root. there comprehensive reference me figure out how of works? silverlight spy great tool can use see going on in xaml. i've read parts of silverlight in action has in depth information, don't know if answers questions.

java - How do you calculate the number of connected graphs? -

given array of node , array of edges, how calculate number of connected graphs? you can use union find (you can search up). start of nodes separate sets, each edge join 2 nodes edge connects same set. check how many different sets there going through nodes , finding how many different representatives there are.

php - displaying the result of a database query on change without refreshing the browser -

i have php script writes data file every 5 seconds , have second php script opens file , queries database based on value in file.. so display result of query need run php script on browser..since data in file keeps changing,so result of query keep changing,but can see new result when refresh browser.. i want way in can see new result of query without refreshing browser.. new hope explained problem best..waiting solution..thanks you'll need use ajax function retrieve data, , javascript update browser. check out http://api.jquery.com/jquery.ajax place start.

Python API design pattern question -

i find have class instances descendants of other class instances, in tree fashion. example i'm making cms platform in python. might have realm, , under blog, , under post. each constructor takes it's parent first parameter knows belongs to. might this: class realm(object): def __init__(self, username, password) class blog(object): def __init__(self, realm, name) class post(object); def __init__(self, blog, title, body) i typically add create method parent class, linkage bit more automatic. realm class might this: class realm(object): def __init__(self, username, password): ... def createblog(self, name): return blog(self, name) that allows user of api not import every single module, top level one. might like: realm = realm("admin", "fds$#%") blog = realm.createblog("kittens!") post = blog.createpost("cute kitten", "some html blah blah") the problem create methods redundant , ...

iphone - Byte size of an NSDictionary -

this may sound stupid question, how can size in bytes of nsdictionary? can convert nsdata, , length of that? help! you should more why care size of dictionary in bytes, because answer might different depending. in general, "size" of nsdictionary's footprint in memory not can see or care about. abstracts storage mechanism programmer, , uses form of overhead beyond actual data it's storing. you can, however, serialize dictionary nsdata. if contents of dictionary "primitive" types nsnumber, nsstring, nsarray, nsdata, nsdictionary, can use nspropertylistserialization class turn binary property list, compact byte representation of contents can get: nsdictionary * mydictionary = /* ... */; nsdata * data = [nspropertylistserialization datafrompropertylist:mydictionary format:nspropertylistbinaryformat_v1_0 errordescription:null]; nslog(@"size: %d", [data length]); if contains other custom objects, use nskeyedarchiver archive...

java - Implementation of Projectile Motion -

Image
i have created projectile motion simulation in java user interface. program allows user enter in initial values calculate projectile of object. don't have set draw projectile onto screen. i have separate spring worker thread handling simulation code in background. i have added in collision detection when object hits ground bounce , continue doing until loop exits. the equations have in place not correct trying achieve. with following initial conditions, here plot of outputted data yields: initial conditions: angle: 30 degrees; initial speed 8.66 m/s; height: 50 m; elasticity of object: .5 coefficient of restitution in y direction; acceleration: -9.8 m/s^2; no acceleration in x direction it appears once simulation begins, y gets bigger , bigger, loop never exit itself. here code: //this class handle time consuming activities class simulation extends swingworker<void, void> { //execute time consuming task protected void doinbackground() throws ...

iphone - How do I assign a delegate to multiple classes -

i have custom delegate, , want 2 classes respond it's events. how can assign both classes. ie: viewcontroller.delegate = firstclass && self; if need event called multiple places should use nsnotificationcenter.

java - VIEWSTATE value in the HttpPost -

here case, want post website, before must retrieve viewstate value , make post using value, problem viewstate value changing every time make posts, little confused how can use it's value in second post if value on server different. there solution or doing wrong? main httppost try { httpclient client = new defaulthttpclient(); httppost request = new httppost( "www.website.com/login.aspx"); string viewstate = getviewstate(client, request, "www.website.com/login.aspx"); system.out.println(viewstate); request.getparams().setbooleanparameter( coreprotocolpnames.use_expect_continue, false); request.setheader("content-type", "text/html; charset=utf-8"); list<namevaluepair> postparameters = new arraylist<namevaluepair>(); postparameters.add(new basicnamevaluepair("__viewstate", viewsta...

asp.net - Relaying Party application not working when shifted to another machine -

i have asp.net relaying party application configured authenticate through acs. web site runs fine on local host. problem when copy website machine, doesn't work , throws following exception: **server error in '/website' application. access denied. description: error occurred while accessing resources required serve request. server may not configured access requested url. error message 401.2.: unauthorized: logon failed due server configuration. verify have permission view directory or page based on credentials supplied , authentication methods enabled on web server. contact web server's administrator additional assistance.** another interesting point when running on new machine url of website has changed,for example on machine "http://localhost/website/" while on new machine "http://localhost:51975/website/". any ideas?? is acs v2 configuration? you should change realm , return address in relying party application match ur...

How many 'CUDA cores' does each multiprocessor of a GPU have? -

i know devices before fermi architecture had 8 sps in single multiprocessor. count same in fermi architecture? the number of multiprocessors (mp) , number of cores per mp can found executing devicequery.exe . found in %nvsdkcompute_root%/c/bin directory of gpu computing sdk installation. a @ code of devicequery (found in %nvsdkcompute_root%/c/src/devicequery ) reveals number of cores calculated passing x.y cuda capability numbers convertsmver2cores utility function. from code of convertsmver2cores relationship between capability , core count can seen: capability: cores 10: 8 11: 8 12: 8 13: 8 20: 32 21: 48

c# - how to check the click event handler for ms chart control -

hi using ms chart control in win-forms application. i have problem mouse click event handler chart control. need check if mouse click event chart control true have done code bool this.kpichartcontrol.mouseclick = false; if (this.kpichartcontrol.mouseclick != true) { //do something..... } error : event system.windows.forms.control.mouseclick can appear on left hand side of += or -= would 1 pls on this....... i need check if mouse click event mschart true " ".... modified code : this.kpichartcontrol.mouseclick+= new mouseeventhandler(void (object , mouseeventargs e)) still giving error can me on this... modified code : if( this.kpichartcontrol.mouseclick+= new mouseeventhandler(void (object sender , mouseeventargs e)) == true) { // } error :invalid term void you need register event; such: this.kpichartcontrol.mouseclick += (obj, sender) =...

Android Spinner OnItemSelectedListener not working accurately -

i have created spinner , activated listener: customerlistspinner.setonitemselectedlistener(new onitemselectedlistener(){ public void onitemselected(adapterview<?> adapter, view view, int position, long id) { // work here } public void onnothingselected(adapterview<?> arg0) { isinitradiogroup = false; } ); i have added 3 values in spinner initially: "search", "employee", "company". if user selects "search", new listactivity shown , selected value added above spinner result. this, performing action on selection of spinner item. now, when screen shown @ first time, default "search" shown. trigger processing of listactivity, user has select "search" again. time, on itemselected callback not called. mean say, if value in spinner selected, on selection of same value again, not trigger listener. whereas: when screen shown @ first time, default "search" shown. user sele...

php - Jquery tabify with form (Multiple Instances problem ?) -

i'm using jquery tabify 4 tabs , each content same form calling via ajax.(assume form.php) 1st tab works fine form. 2nd,3rd , 4th tab failed input type="text" value tabify field (4 tabs here make short code long): $(document).ready(function () { $('#general_information_tab').tabify(); }); function recp(refer,id,plan){ if(plan == 0) { $('.stgcontent').load('stage/stage_procedure1.php?plan_id=' + id + '&t_referid=' + refer ); }else{ $('.stgcontent').load('stage/new_taskstg.php?plan_id=' + id + '&t_id=' + refer); } <div id="general_tab_content"> <ul id="general_information_tab" class="general_information_tab"> <li class="active"><a href="#one" onclick="recp('1','<?php echo $plan_id; ?>','0')" >immediate response steps</a>...

android - What's a reasonable way to make this layout? -

Image
in image below, yellow square represents relativelayout that's within overall layout. the top row "status message" viewflipper responds togglebuttons (a, b) user can press. buttons c, d, , e other stuff reload entire view. our client requesting buttons a, b, c, d, , e arranged in fashion below. (vertical alignment isn't important horizontal alignment.) edit a, b, c, d, , e images 20x20 dip; being aligned within width of 300dip. want buttons maintain aspect ratio. i've created extension of linearlayout inflates buttons , b (from xml file), , linearlayout inflates buttons c, d, , e in xml file. buttons , b (are togglebuttons): <relativelayout android:layout_width="match_parent" android:layout_height="match_parent" android:baselinealigned="true" > <linearlayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_ce...

oop - Is there a way to initialize a S4 object so that another object will be returned? -

i have class hierarchy superclass fb of no objects should exist (i tried virtual classes ran in problem can not initialize objects virtual classes). further, have 2 sub classes ( foo , bar ) same slots. want make new object, using initialize method superclass returns object of 1 of subclasses based on value: setclass("fb", representation( x = "numeric")) setclass("foo", contains = "fb") setclass("bar", contains = "fb") setmethod("initialize", "fb", function(.object, x) { if (x < 5) class(.object) <- "foo" else class(.object) <- "bar" .object@x <- x .object }) > new("fb", x = 3) error in initialize(value, ...) : initialize method returned object of class "foo" instead of required class "fb" obviously (and reasons) r disallows that. there way achieve want within method , not using if-else construct when create new ...

html - Convert &apos; to an apostrophe in PHP -

my data has many html entities in ( &bull; ...etc) including &apos; . want convert character equivalent. i assumed htmlspecialchars_decode() work, - no luck. thoughts? i tried this: echo htmlspecialchars_decode('they&apos;re here.'); but returns: they&apos;re here. edit: i've tried html_entity_decode(), doesn't seem work: echo html_entity_decode('they&apos;re here.') also returns: they&apos;re here. since &apos; not part of html 4.01, it's not converted ' default. in php 5.4.0, extra flags introduced handle different languages, each of includes &apos; entity. this means can this: echo html_entity_decode('they&apos;re here.', ent_quotes | ent_html5); you need both ent_quotes (convert single , double quotes) , ent_html5 (or language flag other ent_html401 , choose appropriate situation). prior php 5.4.0, you'll need use str_replace : echo str_replace('...

extjs - How can I have only one chart rendered upon an AJAX request? -

i using extjs 4 create charts. charts instantiated every time make ajax call. this: $("#maincontent").getjson("path/to/jsondata",function(data) { _chart.chart = ext.create("ext.chart.chart", { axes : _chart.axes() , style : 'background:#fff' , series : _chart.series() , store : _chart.store() , renderto : $("#chart").get(0) , width : sybus.utils.mainwidth() , height : sybus.utils.mainheight() }); }); the more invoke ajax call, more charts have on page. how can prevent happening , have 1 chart? thank you. similar this question , have adapted answer suit context. the answer issue out of extjs' responsability. code sample above missing cause of problem. i have built class binds event function builds chart. everytime invoked ajax call retrieved data chart, function stacked binding on top, hence multiple charts. the solution either check if have bound event or unbind() event , re bind() ag...

java - Why does a dialog seemingly have its one thread? -

i'm new advanced programming - i've read, android programs on 1 thread. this means, 1 line of code or method/function can executed @ time before moving on next line (that's thought anyway). however, i'm using custom dialog develop application , yet, program continues after dialog has ran. i'd program wait dialog close can receive input , manipulate it. this seems straightforward when programming in java (e.g. scanner tool waits user input before proceeding opposed running code following while waits user input). how can this? everything happen on 1 thread unless explicitly tell not to. however, showing dialog happens asynchronously. basically, when ask dialog show, adds information list of ui events waiting happen, , happen @ later time. this has effect code after asking dialog show execute right away. to have execute after dialog choice made, add ondismisslistener dialog , whatever want in ondismiss .

javascript - Why is my code fully compatible in Chrome/Safari, somewhat in FireFox, but hardly at all in Internet Explorer 8? -

i wrote jquery code works in chrome/safari, in firefox, , hardly @ in ie8. why , how can fix it? here's code in case you're curious see might cause problems in ie or firefox (you can see code in action on @ http://keepskatinbro.com/ ): jquery(".wrap").append("<img src='" + base + "/wp-content/themes/shaken-grid/images/ajax-loader.gif' id='ajax-loader' style='position: fixed; margin-left: 50%; left:-154px; top: 30%; display: none;' />", function() { jquery("#ajax-loader").hide(); }); var $maincontent = jquery("#grid"), $ajaxspinner = jquery("#ajax-loader"), $clicked_item, $target_open, $target_close, $element; jquery('a.ajax_trigger_title, a.more-link, a.ajax_trigger_thumbnail').live('click', function(event) { var $element = jquery(this); if ( $element.hasclass('ajax_trigger_title') ) { var $post_box = $ele...

Paperclip Giving Required field error -

in project have form in there file field upload file , using paperclip gem , add validation 'validates_attachment_content_type' when submit form without file selected gives error of 'validates_attachment_content_type', should not give error not add validation 'validates_attachment_presence'. confused giving error of 'validates_attachment_content_type' when submit form without file uploaded. after googling same got answer prob have add :allow_nil => true in validation for eg. validates_attachment_content_type :logo, :content_type => ['image/jpeg','image/png','image /jpg','image/gif'], :message=>"image file must of .jpeg,'.jpg', '.gif' or .png type",:allow_nil => true

command line - How to print vertical progress bar in console using Java? -

how can print vertical progress bar in terminal console or command prompt using java? horizontal bar looks this: user#java printhorizontalprogressbar 5%##### i want print same progress bar vertically. did try use system.out.println("*") ? sort of vertical progress bar.

python - beautiful soup malformed start tag error -

>>> soup = beautifulsoup( data ) traceback (most recent call last): file "<stdin>", line 1, in <module> file "/usr/lib/pymodules/python2.6/beautifulsoup.py", line 1499, in __init__ beautifulstonesoup.__init__(self, *args, **kwargs) file "/usr/lib/pymodules/python2.6/beautifulsoup.py", line 1230, in __init__ self._feed(ishtml=ishtml) file "/usr/lib/pymodules/python2.6/beautifulsoup.py", line 1263, in _feed self.builder.feed(markup) file "/usr/lib/python2.6/htmlparser.py", line 108, in feed self.goahead(0) file "/usr/lib/python2.6/htmlparser.py", line 148, in goahead k = self.parse_starttag(i) file "/usr/lib/python2.6/htmlparser.py", line 226, in parse_starttag endpos = self.check_for_whole_start_tag(i) file "/usr/lib/python2.6/htmlparser.py", line 301, in check_for_whole_start_tag ...