Posts

Showing posts from May, 2015

MySQL Query Logs Truncating Queries -

i'm looking @ general log i've enabled in mysql , it's working nicely. however, queries appear truncated little on 1000 characters. what's deal that? you should change field type, 'argument' field medium text, should change 'longtext' following query. alter table `mysql`.`general_log` change `argument` `argument` longtext not null; what kind of query great 1000? maybe logging blob field?

makefile - Define compilation variables based on target for -

my c++ source file specific variable passed makefile. when making different target, variable definition different. how can define variable in makefile based on target. thanks you can use target-specific variable values , propagate target's prerequisites: all : foo bar foo : cxxflags += -dfoo bar : cxxflags += -dbar foo bar : @echo target=$@ cxxflags=${cxxflags} .phony :

Python: sorting an array with another array's elements as keys? -

import numpy np x = np.array(range(10 * 30)).reshape(100, 3) y = np.array(range(1010, 10, -10)) res = sorted(x, key = lambda y:y) #valueerror: truth value of array more 1 element ambiguous. use a.any() or a.all() res = sorted(x, key=y) #typeerror: 'tuple' object not callable try argsort: import numpy np x = np.array(range(10 * 30)).reshape(100, 3) y = np.array(range(1010, 10, -10)) args = y.argsort(axis = 0) print x[args]

python - numpy - pretty printing -

i have numpy array of strings. when value in array undefined, none printed expect. possible provide default value none values? e.g. in following want "_" instead of none [[none b c] [m none o] [x y none]] would become [[_ b c] [m _ o] [x y _]] a simple solution might transform array string first , replace string none afterwards, example if matrix a : print(str(a).replace('none','_')) you can define function: def printarray(a): print(str(a).replace('none','_'))

c++ - Using images in QListWidget, is this possible? -

i using qt create chat messenger client. display list of online users, i'm using qlistwidget , created this: listwidget = new qlistwidget(horizontallayoutwidget); listwidget->setobjectname("userlist"); qsizepolicy sizepolicy1(qsizepolicy::preferred, qsizepolicy::expanding); sizepolicy1.sethorizontalstretch(0); sizepolicy1.setverticalstretch(0); sizepolicy1.setheightforwidth(listwidget->sizepolicy().hasheightforwidth()); listwidget->setsizepolicy(sizepolicy1); listwidget->setminimumsize(qsize(30, 0)); listwidget->setmaximumsize(qsize(150, 16777215)); listwidget->setbasesize(qsize(100, 0)); listwidget->setcontextmenupolicy(qt::customcontextmenu); users shown refreshing list, this: (note: there different channels, different userlists, refreshing efficient thing do, far know.) void fmessenger::refreshuserlist() { if (currentpanel == 0) return; listwidget = this->findchild<qlistwidget *>(qstring("userlist")); ...

Netflix/Hulu system architecture -

does know system architecture of hulu or netflix? how protect content? how deal scalability multi-million concurrent subscribers while maintaining content security? block diagram appreciated. i add though article dated (2011) nosql approach has been spoken of (and datastax's use case on cassandra) still relevant today. http://techblog.netflix.com/2011/01/nosql-at-netflix.html our cloud-based infrastructure has many different use cases requiring structured storage access. netflix using right tool job. in post, i’d touch on reasons behind our choice of 3 such nosql tools: simpledb, hadoop/hbase , cassandra. interesting read

c++ - member variable as a reference -

what advantage of declaring member variable reference? saw people doing that, , can't understand why. one useful case when don't have access constructor of object, yet don't want work indirection through pointer. example, if class a not have public constructor , class wants accept a instance in constructor, want store a& . guarantees reference initialized.

c# - How can I call a base class's parameterized constructor from a derived class if the derived class has no parameterized constructor? -

i have base class 2 constructors: default constructor , parameterized constructor. class inherits base class , has default constructor. how can call base class's parameterized constructor derived class? it's not entirely clear question is, suspect either want add explicit parameterless constructor child class: // parameterless child constructor calling parameterized base constructor public child() : base("foo", "bar") { } or add both parameterized , parameterless one: public child() { } public child(string foo, string bar) : base(foo, bar) { } note constructors aren't inherited - because base class has particular constructor signature doesn't mean can instantiate class using signature. child class has provide itself. any compiler-provided parameterless constructor call parameterless constructor of base class.

json - Class Doctrine_Event could not be loaded -

i trying use apc in zend framework (1.10) application + doctrine (1.2). when enabled apc got error: fatal error: spl_autoload(): class doctrine_event not loaded in /var/www/myapp/vendor/doctrine/record.php on line 801 i registered function writeclose shutdown function mentioned in: opcode (apc/xcache), zend, doctrine, , autoloaders fixed issue still getting error json data, same error appended json response. ideas?

c# - How to unit test the heartbeat pattern? -

i writing client sends "heartbeat signal" server every second. client calls wcf service in background thread report activity. how unit test this? need wait couple of seconds , check if appropriate method called several times? should sort of scenario test instead? maybe shouldn't worried calling service continuously through whole clients lifetime cycle? i can test single call wcf service doesn't test "heartbeat pattern". i using tdd approach. (c#, nunit, moq) any suggestions or examples? edit: i think wasn't clear enough. this simpler version of have: public class feedservice { private timer t; public feedservice() { t.interval = 1000; t.elapsed += timerelapsed; t.start(); } private void timerelapsed(object sender, elapsedeventargs e) { t.stop(); sendheartbeat(); t.start(); } } ...and test: [test] public void heartbeat_called_twice_after_2_seconds() { var mockfeedservic...

css - How to center text inside a li element inside an unordered list -

this list working great me text within <li> elements not centering. the <li> s must auto resize content. #nav-menu { font-family: verdana, arial, helvetica, sans-serif; height: 30px; background-image: url(../img/menu_bg.png); background-repeat: repeat-x; border-bottom: dotted thin #666666; border-top: dotted thin #666666; text-align: center; width: 800px; } #nav-menu ul { list-style: none; padding: 0; margin: auto 0; } #nav-menu li { float: left; border-right: dotted thin #666666; list-style: none; padding: 0.5em 2em 0.5em 0.75em; } #nav-menu li { line-height: 1.5em; color: #333333; text-decoration: none; font-size: 12px; font-weight: bold; display: block; } <div id="nav-menu"> <ul> <li class="current_page_item"><a href="#" title="home">home</a> <li...

Optional belongs_to relationship in Ruby -

i'm migrating application on ror php defines object, let's call document can created user either registered user of application, or anonymous user gives email address (in case without associated user account). there no requirement visitor create user account, should still have ability create document. in model, first led create document model references user belongs_to association. not case. in pure sql , php not hard, although comes it's own challenges, model in "purest" ruby/rails way. if visitor not have associated user, email address stored directly against document object. to start discussion, here snippets each model. # user.rb class user < activerecord::base has_many :documents end # document.rb class document < activerecord::base attr_accessible :title, :description, :email_address belongs_to :user end my goal able retrieve user documents using standard dot notation: user.documents and check reverse relationship see if docum...

passing filename as arguments in c++ -

i have pass 4 different text files in argument in c++ program. how pass?? int main(int argc, char ** argv) { std::vector<std::string> args(argv, argv+argc); (size_t = 1; < args.size(); ++i) { std::string const & afilename = args[i]; // afilename } }

perl - How can I convert a date to epoch time? -

i have huge formatted file of form: 29/01/2010 18:00 string1 string2 ..... 30/01/2010 18:30 string3 string4 ..... ... ... dd/mm/yyyy hh:mm strings strings.... i need perform statistics based on dates. so substitute string dd/mm/yyyy hh:mm epoch time in file in order perform simple manipulations. i suppose best way use perl, don't know start. hints? just that? quick-and-dirty one-liner should do: perl -mposix -pwe 's{^(\d{2})/(\d{2})/(\d{4}) (\d{2}):(\d{2}) }{mktime(0,$5,$4,$1,$2-1,$3-1900)." "}e;' feed file on standard input , output changed version standard output. lines have "dd/mm/yyyy hh:mm " @ start, , feed date components mktime function posix module unix timestamp.

.htaccess - how to redirect in php using htaccess -

i need redirect page www.someone.com/2011/03/05 sample.php?dt=2011/03/05 using htaccess , php, thanks. rewriteengine on rewriterule ^(\d{4}\/\d{2}\/\d{2})/?$ sample.php?dt=$1 [l]

Does Ecma-334 have an incorrect description for next line (C# ECMA Standard)? -

in ecma-334 (c# language specification 4th edition), annex a. grammar, section a.1.1 line terminators: new-line:: carriage return character (u+000d) line feed character (u+000a) carriage return character (u+000d) followed line feed character (u+000a) next line character (u+2085) line separator character (u+2028) paragraph separator character (u+2029) but u+2085 not next line character; subscript five . does ecma-334 have incorrect description next line? http://www.ecma-international.org/publications/standards/ecma-334.htm http://www.fileformat.info/info/unicode/char/2085/index.htm edit : (u+0085) next line character. yes, appears error in standard. the microsoft c# language specification (the version shipped vs2010) has correct item: next line character (u+0085)

Can a PHP script talk to a C program? -

i have potential new project, it's embedded linux device needs web interface. code application running single process in c. web interface needs able configure various variables in c program. there mechanism in php communicating values php script c process? ty, fred yes have done before. you need use tcp connections between web server , c application , 2 can communicate different messages , commands each other

c++ - Is there a quick way to switch the solution platform in Visual Studio 2010? -

i want compile c++ projects in 32-bit , 64-bit mode. until now, created solution configurations: in addition pre-configured "debug" , "release" configurations, had "debug x64" , "release x64" configurations set compile project x64 architecture. however, latest project can changed in number of dimensions: not "release" vs "debug" "xp", "server03" , "newer" "exe" vs "dll" (it can compiled in both formats). because gives 2*2*3=12 configurations, adding "x64" configuration each of give whole thing absurd proportions. that's why want use solution platform setting on. unfortunately, way change seems to click configuration dropdown list, open configuration manager there, change solution platform , click ok. takes rather long time (more doubling number of clicks). there quicker way? or alternatively, better way manage dimensions in project can change (which involv...

iphone - objective c - Release a singleton property -

i have singleton class has mutabledictionary. initialise dictionary in root viewcontroller. later on empty dictionary , release memory. though retain count 1 release causes crash: -[cfdictionary release]: message sent deallocated instance is possible release singleton property? thanks first i'll reiterate has been said ton of times on here: don't call -retaincount !! implementation detail. see: stackoverflow | when use retaincount excellent recount of why don't use retaincount. beyond that, i'd recommend looking more information of invariants shoot in writing singletons . dave delong has great recap of how (and more importantly why singletons) way. article includes links other developers , outlooks. i'd recommend familiarizing tenets , re-evaluating implementation. finally, 1 more time: please go http://bugreport.apple.com , request -retaincount deprecated. more people ask it, better.

ios - UIKit: how to loop number increment of UILabel text -

could give me advice how show smooth number increment in uilabel ? code have used performs such increment fast human eye :) for (int = 1; i<=self.score; i++) { self.levelcompletescorelabel.text = [nsstring stringwithformat:@"%d", i]; } i can't use sleep() function because have concurrent animations going on screen. seems nstimer work trying do. you can set fire every 1 or 0.5 seconds users can see , appreciate change. here find easy way implement it. additionally can @ answers question wich has lot of information on nstimer: how use nstimer?

How to recheck primary/foreign key constraint for data already in the table in sql server? -

i have table in sql server 2005 foreign key , disable huge data loading, , re-enabled: example: alter table table1 nocheck constraint fk_1 go lots of inserts... go alter table table1 check constraint fk_1 go now, question: there way re-check inserted data? the syntax looks little silly word "check" repeated, want is: alter table table1 check check constraint fk_1 go adding "with check" option validate existing data against constraint. doing prevent constraint becoming untrusted . if existing data violates constraint, you'll error this: the alter table statement conflicted check constraint "fk_1".

security - Why do links in gmail redirect? -

i've noticed email services (like gmail or school's webmail) redirect links (or used to) in email body. when put "www.google.com" in body of email, , check email in gmail or something, link says "gmail.com/redirect?www.google.com". this confusing me , people emailed (like parents, not familiar computers). clicked on link anyway, why service used? (i'm worried maybe information being sent somewhere... have worry about? being stored before redirect?) sorry if unwarranted paranoia. curious why things work way do. this redirection dereferrer avoid disclosure of url in http referer field third party sites url can contain sensitive data session id.

visual studio 2010 - Updating a SilverLight 4.0RC application to 4.0 RTM -

i downloaded source code project: silvervnc - vnc viewer silverlight 4.0 rc it builds fine when run message (when browser launches , presumably browser's silverlight runtime): this application created expired beta release of silverlight. please contact owner of application , have them upgrade application using official release of silverlight. i have requisite silverlight 4.0 rtm bits installed (i've never installed silverlight beta or rc on machine before), items should in project update run? i noticed 2 of projects in solution reference version 3 silverlight assemblies. updated these 4.0 (both projects , references 4.0) still error. i've guessing there's in project file needs tweaking. having never written line of code silverlight i'm bit lost. the project file may have references pre-built assemblies may built sl4 rc. project may reference silverlight 4 rc assemblies. there 2 things can try. either can remove reference...

c# - Moq confusion - Setup() v Setup<>() -

i have mock being created this: var mock = new mock<ipacket>(mockbehavior.strict); mock.setup(p => p.getbytes()).returns(new byte[] { }).verifiable(); the intellisense setup method says this: "specifies setup on mocked type call void returning method." but mocked method p.getbytes() not return void, returns byte array. alternatively setup method defined setup<>, , can create mock this: var mock = new mock<ipacket>(mockbehavior.strict); mock.setup<byte[]>(p => p.getbytes()).returns(new byte[] { }).verifiable(); the intellisense of setup method states: "specifies setup on mocked type call value returning method." . . whichever method choose, compiles , tests ok. so, i'm confused way should doing this. difference between .setup() , .setup<>(), , doing right? the docs moq lacking, shall say. :) the compiler inferring lambda passed setup() meant call generic version, , happily infe...

c - How does a server distinguish multiple connections from a single client? -

i doing c programming on client server socket examples. lets server listens on port80, client on port 4321. tuple used distinguish between multiple connections. how server distinguish between connections same client? mean there multiple apps client accessing same server on same port. can please explain? thanks two clients cannot use same port. if 1 client uses port 4321 other has use different port.

How to find out the adjacent word pairs from a string in java? -

i have string good , want find out word pairs string such oo , if string success out put should cc ss without using string's built in functions in java. possible? without any built-in method - no. 1 or 2 - can char previous = 0; char[] chars = str.tochararray(); (int = 0; < chars.length(); i++) { if (chars[i] == previous) { system.out.println(previous + "" + previous); } previous = chars[i]; } i prefer i < str.length() , str.charat(i) , uses more string methods.

gnuplot - How to get a radial(polar) plot using gnu plot? -

Image
i want radial(polar) plot using gnuplot (i.e in circular co-ordinate system(r,theta). here have used values: theta max-strain 0 3400 60 5300 120 4700 180 3800 240 4100 300 3100 360 3400 how such plot using gnu-plot? i tried recreate plot of question , came with: unset border set polar set angles degrees #set gnuplot on degrees instead of radians set style line 10 lt 1 lc 0 lw 0.3 #redefine new line style grid set grid polar 60 #set grid displayed every 60 degrees set grid ls 10 set xrange [-6000:6000] #make gnuplot go until 6000 set yrange [-6000:6000] set xtics axis #disply xtics on axis instead of on border set ytics axis set xtics scale 0 #"remove" tics y tics displayed set xtics ("" 1000, "" 2000, "" 3000, "" 4000, "" 5000, "" 6000) #set xtics go 0 6000 increment of1000 not display anything. has done otherwise grid not displayed correctly. set ytics 0, 1000, 6000 #make y...

jquery table offsetWidth question -

i have been looking hours , can't figure out. trying write code align table headers , table columns, trying figure out overall width of header cell , width of column. strange reason tdoffset gets value , thoffset nan . $("#tbltasks tbody tr:eq(0) td").each(function(index) { tdoffset = parseint(this.offsetwidth); thel = $('#tbltasks thead tr:eq(0) th:eq(' + index.tostring() + ')').first(); thoffset = parseint(thel.offsetwidth); alert('tdoffset' + tdoffset + ' thoffset:' + thoffset); } can point out doing wrong? thanks , happy. the reason this.offsetwidth works , thel.offsetwidth not this refers dom element , thel refers jquery object. you can access dom element "behind" thoffset doing following thel[0].offsetwidth

Chrome Extension: Open New Popup Window -

could shed light on code incorrect please <script> chrome.browseraction.onclicked.addlistener(function(window) { chrome.windows.oncreated.addlistener(function(enumerated string ["popup"]) { chrome.windows.create({'url': chrome.extension.geturl('redirect.html')}, function(window) { }); }); }); </script> i'm trying achieve when extension clicked on new popup window load. you don't need listener, create right away: chrome.browseraction.onclicked.addlistener(function() { chrome.windows.create({'url': 'redirect.html', 'type': 'popup'}, function(window) { }); });

c# - Equivalent to 'app.config' for a library (DLL) -

Image
is there equivalent app.config libraries (dlls)? if not, easiest way store configuration settings specific library? please consider library might used in different applications. you can have separate configuration file, you'll have read "manually", configurationmanager.appsettings["key"] read config of running assembly. assuming you're using visual studio ide, can right click desired project → add → new item → application configuration file this add app.config project folder, put settings in there under <appsettings> section. now read file have such function: string getappsetting(configuration config, string key) { keyvalueconfigurationelement element = config.appsettings.settings[key]; if (element != null) { string value = element.value; if (!string.isnullorempty(value)) return value; } return string.empty; } and use it: configuration config = null; string execonfigpath =...

asp.net mvc - Upload a file and destory it after session is completed -

i want upload file through asp.net mvc , delete file after session destroyed ? check out link has code in c#. tell how find file , delete it, must handle checking session , associated logic. link

java - How can we make Tab layout auto hide? -

generally can hide particular tabs @ runtime. need make make whole tab layout hideable. when click screen once appears , other time disappear. can possible. have seen in motorola droid x phone's camera application. please me. in advance you can use setvisibility(8); :) you put id in linearlayout , manage in code with: linearlayout l=(lynearlayout) findviewbyid(r.id.myid); l.setonclicklistener(this); public void onclick(view v){ mytab.setvisibility(view.gone); }

Advanced friendship model and queries in Rails 3 -

i have friendship model, , every new friendship, create 2 new records: user1 , friend1 friend1 , user1 i can retrieve standard staffs like: friends, friendships, pending_friends... situation becomes complicated when try common friends, friends of friends... for common friendships, use like: has_many :common_friendships, :class_name => 'friendship', :conditions=>'friendships.user_id = #{self.id}' def common_with(friend) joins("inner join friendships fl2 on friendships.friend_id = fl2.user_id").where("fl2.friend_id = #{friend.id}") end end also can use full query finder_sql like: select distinct * friendships fl1 inner join friendships fl2 on fl1.friend_id = fl2.user_id fl1.user_id = 1 , fl2.friend_id = 2 how can in elegant way in rails 3? check out answer on question: how implement friendship model in rails 3 social networking application?

PaaS (Platform as a service) for PHP -

i have walked long road, finding out possible 'appengine' php solutions , still not be. here have seen far: pagodabox.com i love these guys. have built best looking admin interface have ever seen, combined great ideas in mind memcache, mongodb support (both coming) , seamless github deployment. unfortunately learned not support concurrent requests on single server. support staffer literally told me need additional server each concurrent request get. ( update : in oct 2011 apparently changed , say: " app instances can process concurrent requests. ") phpfog.com did play little it. not support github , tied git server -you might or not. have pay boxes. shouldn't cloud service give me opportunity use multiple machines, one? here can see 1 instance. benefit? less administration? cloudcontrol.com correct me if wrong, seem pretty same phpfog. scalarium.com looks great, costs lot. if promisses, 1 seams make sense me. did not chance try out yet. i dyin...

Archiving data in Sybase IQ from Sybase ASE -

what best means of solving following problem: i have sybase ase database used oltp server. there lot of data inserted database each day , result 'live' tables hold last n days of data (n can vary table table). i introduce sybase iq server decision support server holding of previous days data reporting purposes. i nightly job "sync" sybase iq tables in ase i.e. insert new rows, update changed rows not delete of rows outside of n days live table represents. all ideas welcome!!! you have develop etl (extract transform load) process. there lot commercial , free etl products. think best way in case create rs ase -> ase replication (direct ase -> iq have bad performance) modify delete function string separate delete operations periodically truncate insert iq tables second ase db (update poor in iq) via linked server connection

sql server - SQL Statement DATEPART Help -

what wrong sql statement? keep getting selmonth , curmonth invalid columns, doing clause wrong? datepart causing problem here? select top (5) ename, edate, edateend, datepart(month, edate) selmonth, datepart(month, { fn curdate() }) curmonth events (edate >= { fn curdate() }) , (selmonth = curmonth) thanks you can't use selmonth , curmonth in clause: select top (5) ename, edate, edateend, datepart(month, edate) selmonth, datepart(month, { fn curdate() }) curmonth events (edate >= { fn curdate() }) , (datepart(month, edate) = datepart(month, { fn curdate() }))

c++ - Windows Message for User Locking Screen -

i'm working old-school windows programming in c++, , need capture event in wndproc indicates user has logged off or locked screen. update (thanks david hefernan) i've searched everywhere, thing i've found wm_endsession message - not handle screen lock events. anyone know how done? need apply windows 2000 through windows xp flavors. the solution register wm_wtssession_change , respond in wndproc. according documentation of wm_wtssession_change , minimum supported os xp. now, since windows 2000 no longer supported, documentation says xp minumum when in fact functionality available on earlier versions. in case, quick web search suggests may disappointed. to notified session logoff (rather screen lock), should able use lparam value of wm_endsession message. presence of endsession_logoff flag.

security - Best Practices on Storing Login Info on Android -

i'm kinda of noob @ android , i'm writing simple app, own personal learning, hookup external api (flickr or netflix). want ask user login info either site can view pictures or dvd queue. question what's best practice store user data that? i thinking of encrypting login/pwd , store onto sd card. thoughts using method? there better method? i'm interested in reading other developer's perspective. i'm sure there numerous methods out there. don't want break "#1 rule" of storing user info. thanks. as mentioned in this answer : if using apilevel >= 5 read accountmanager . the samplesyncadapter tutorial uses accountmanager. might place start.

php - Display specific line or record of a recordset -

say have recordset, lets call $rsrecordset. lets has data in so: 1 2 3 4 5 6 7 8 9 now want display, example, 5. how might that? i've read lot seems structured so: echo $rsrecordset[1][1]; but life of me can't make work. suggestions? since jk hasn't returned, guess i'm answering myself. the following boy: <?php echo mysql_result($rsrecordset, 1, 2); ?> again, if jk returns happily give him tick. if not i'll apply myself tomorrow, since technically joint effort anyway.

sql server 2008 - Microsoft Access ODBC Connection Strings Limited to 255 Characters? -

microsoft access 2003 database (.mdb) containing linked table connects via odbc backend microsoft sql server 2008 table. when enter design view linked table, view properties field, can see first 255 characters (specific fields replaced hyphens): odbc;description=------------------------------------;driver=sql server;server=----;app=--------------------------------;wsid=---------;database=------------------;statslog_on=yes;statslogfile=-------------------------------------------------------------- when print dao field using vba immediate window (table name ommitted: "print currentdb.tabledefs("-----------").connect"), see prefix plus 254 characters (prefix "odbc;description=" plus 254 characters, plus, presumably, one-byte null character): odbc;description=------------------------------------;driver=sql server;server=----;app=--------------------------------;wsid=---------;database=------------------;statslog_on=yes;statslogfile=----------------...

sql - I need to get NULL values in Columns if Intermediate table doesn't apply -

i joining tables there 2 separate relationship schemes so: tablea1 -> tablea2 -> tableb -> tablec : <<< relationship enter code here and output needs so: a1columnid a2columnid bcolumnid ccolumnid 1 1 1 1 2 null 2 2 3 null 3 3 4 2 4 4 5 null 5 5 if there exists these 2 relationship & b , need see a2colid null below relationship: and 2nd relationship scheme looks so: tablea1->tableb-tablec <<<< relationship b (this scheme has no clue tablea2) how join result set nulls in a2columnid depicted above? left join instead of regular join force table join if no data exists in right table, filling in null in place. when join a1 , a2 so: select * a1 left join a2 on a1.idlink = a2.idlink join b on a1.id = ...

c# - Entity Framework And Business Objects -

Image
i have never used entity framework before , try personal projects implementing feet wet. i see entities can exposed presentation layer. don't want fields exposed, fields modified dates , created dates , various other database fields. how implement business objects , expose properties need still keep objects serializable? also advantages have on linqtosql? when define entity in edmx model can specify visibility of each property's setter , getter, if don't want modifieddate visible in other layers, can specify internal. if requirements more complicated modifieddate should accessible in entities assembly , business logic assembly not in ui assembly, need create object exchanged between business logic , ui logic layers.

jquery tabs - what am I doing wrong? -

html code is: <div id="questions"> <ul> <li class="selected"><a href="#fly">fly</a></li> <li><a href="#fly1">fly 1</a></li> </ul> <div id="fly" style="display: block;"> <div id="question141"> <div id="question104"> <div id="question80"> <div id="question79"> </div> <div id="fly1"> <div id="question141"> <div id="question104"> <div id="question80" > <div id="question79" > </div> </div> jquery: <script> jquery(document).ready(function(){ jquery('#questions div').hide(); jquery('#questions div:first').show(); jquery('#questions ul li:first').addclass('active'); jquery('#questio...

Removing html entities in parsed text - Php -

how remove/convert characters "’" parsed html text? whether there function remove this?? if you're using html_entity_decode or similar php function check if there's parameter define character set used example. html_entity_decode ( string $string [, int $quote_style = ent_compat [, string $charset = 'utf-8' ]] ) http://www.php.net/manual/en/function.html-entity-decode.php utf-8 display characters correctly assuming source isn't weird.

Reasons for a 409/Conflict HTTP error when uploading a file to sharepoint using a .NET WebRequest? -

i've got method uses webrequest upload file sharepoint 2010 list/folder, using put request, overwrite header set t (overwrite). when several files uploaded (method called several times), requests fail 409 conflict http error. i've googled, , seems common reason trying affect/update file not exist (like setting request url path without file name). however, not case. in case conflict had file existing, added code physically delete file before uploading it, , i'm still getting 409's. has received type of error, , if so, can tell me how fixed , root cause? appreciated. thanks since no answers posted, found following here : the web server (running web site) thinks request submitted client (e.g. web browser or our checkupdown robot) can not completed because conflicts rule established. example, may 409 error if try upload file web server older 1 there - resulting in version control conflict. someone on similar question right here on stackoverflow , ...

dns - Why do people hide their nameservers? -

sometimes when whois information domains, see nameservers forwarded service zoneedit or domain control. i've never understood purpose doing have feeling has hiding nameserver whois on domain can't figure out service site hosted under. can please explain me? there sorts of reasons may use service this: their webhost doesn't provide dns. true people running own vps (you'd need 2, backup dns). their webhost provides dns, bad; slow, drops out, whatever may be. they use multiple webhosts , want keep dns in 1 place. i'm sure there's many more, these obvious ones. on related note, many web hosts can owner of ip range web server in if want know company hosting website. turn info, though company owns ip may not person being paid directly site owner hosting on ip.

how to access the super class from a child class in php -

i have 3 classes following inheritance structure: <?php class admin { function __construct($module){ echo $module; } } class user_admin extends admin { function __construct(){ parent::__construct('user'); } } class sales_admin extends user_admin { function __construct(){ parent::__construct('sales'); } } you'll notice sales_admin extends user_admin, nescessary step. when run code, $a = new sales_admin; it echo "user", because passes "sales" string user_admin doesn't accept constructor. is there way access constructor of parent above without changing user_admin, don't have control over? just reference class directly: class sales_admin extends user_admin { function __construct() { admin::__construct('sales'); } } $a = new sales_admin; // outputs 'sales' since user_admin ex...

c++ - linkedlist with class in the struct can't get bool operation working -

i can't seem boolean operation working thought works. /////.h file class linkd { private: struct listnode{ driver driver; ////class listnode *next; }; listnode *head; ///.cpp file void linkd::deletenode(driver d){ listnode *nodeptr; listnode *previousnode; listnode *newnode; newnode=new listnode; newnode->next=null; newnode->driver=d; if(!head) return; if(head->driver==d) //the problem right here. { nodeptr=head->next; delete head; head=nodeptr; } head->driver==d gives redline ( no operator "==" matches these operands ) i think because head->driver uninitialized might wrong , not sure how initialize since it's inside uninitialized struct. that's because driver class object. you have define equality operator class. are expecting class object pointer (as in java i.e. can null) if want test driver objects equality define this: class driver { public: bool operator==(driver...

HAML - style block helpers are deprecated -

i have following view used render without warnings: #listing -if flash[:notice] .success =flash[:notice] .input-container -form_for @user |f| =f.error_messages =render :partial => 'form', :locals => {:f => f} but when render view running functional test, following warning: deprecation warning: - style block helpers deprecated. please use =. does know warning means? yeah, instead of: -form_for @user |f| use =form_for @user |f| in other words, suggests. flip dash equals. new in rails 3. http://edgeguides.rubyonrails.org/3_0_release_notes.html#action-view (section 7.4.2)

How to disable other providers (yahoo, aol, hotmail) from facebook comments plugin -

i using facebook comment social plugin support facebook comment in site. using following code - <div id="fb-root"></div> <script src="http://connect.facebook.net/en_us/all.js#xfbml=1"> </script> <fb:comments href="example.com" num_posts="2" width="500"></fb:comments> note that: i'm using no facebook application commenting. facebook comment box has support comment using other providers (yahoo,aol , hotmail). don't want this. want remove select box. possible remove that. if possible how? facebook has option subscribe, unsubscribe comments. possible disable or remove that? if possible how? fb:comments has several options num_posts, colorscheme, width. there option disable select box, subscribe/unsubscribe option? it helpful me if guys me regarding that. thanks in advance. its facebook bug. please follow link below further details. thanks. http://developers.facebook.com...

sqlite - retrieve summed amounts from sql -

what problem following query: select wbcode||yr, cast(coalesce(cons,0) float), wbcode commodities ccode in (2611,2513,2961) group wbcode||yr i want query above return sums every wbcode in given yr (usa1990), example; code above not summing up; retrieving same data as: select wbcode||yr, cast(coalesce(cons,0) float), wbcode commodities ccode in (2611) group wbcode||yr select wbcode||yr, cast(coalesce(cons,0) float), wbcode commodities ccode in (2513,2961) group wbcode||yr how can sum? thank help. why || ? group them separately select wbcode, yr, sum(cast(coalesce(cons,0) float)), wbcode commodities ccode in (2611,2513,2961) group wbcode, yr or select wbcode||yr, sum(cast(coalesce(cons,0) float)), wbcode commodities ccode in (2611,2513,2961) group wbcode, yr

php - CakePhp: Avoid XSS attack keeping the ease of use of cake -

one of things cakephp, can have generated edited form allows save. e.g. in controller: function add() { if (!empty($this->data)) { $this->post->create(); if ($this->post->save($this->data)) { $this->session->setflash(__('the post has been saved', true)); $this->redirect(array('action' => 'index')); } else { $this->session->setflash(__('the post not saved. please, try again.', true)); } } $users = $this->post->user->find('list'); $this->set(compact('users')); } the problem our fields vulnerable xss (cross site scripting). i'm aware of "sanitize::clean" way, i've problem that: it's mean have on fields before save object. , if once add 1 field? should go on our code check sanitize it?? there way "sanitize object before save it...

python - RegEx Tokenizer to split a text into words, digits and punctuation marks -

what want split text ultimate elements. for example: from nltk.tokenize import * txt = "a sample sentences digits 2.119,99 or 2,99 awesome." regexp_tokenize(txt, pattern='(?:(?!\d)\w)+|\s+') ['a','sample','sentences','with','digits','like','2.199,99','or','2,99','are','awesome','.'] you can see works fine. problem is: happens if digit @ end of text? txt = "today it's 07.may 2011. or 2.999." regexp_tokenize(txt, pattern='(?:(?!\d)\w)+|\s+') ['today', 'it', "'s", '07.may', '2011.', 'or', '2.999.'] the result should be: ['today', 'it', "'s", '07.may', '2011','.', 'or', '2.999','.'] what have result above? i created pattern try include periods , commas occurring inside words, numbers. hope h...

javascript - In Node.js how can I tell the path of `this` module? -

in node.js module i'm writing open file--i.e, fs.readfile() --that contained in same directory module. mean in same directory ./node_modules/<module_name>/index.js file. it looks relative path operations performed fs module take place relative directory in node.js started. such, think need know how path of current node.js module executing. thanks. as david van brink mentioned in comments, correct solution use __dirname . global variable return path of executing script (i.e. might need use ../ reach root of module). for example: var path = require("path"); require(path.join(__dirname, '/models')); just save headache.

windows phone 7 - navigate to a page from a popup menu? -

while working on pop menu, not able navigate different page, other parent of pop up. how achieve in wp7 app? if popup element, did popup.isopen=false ; popup object of popup; after navigating??

javascript - Updating Selectbox options -

i have 2 selectbox countrynames airports and select countryname in first selectbox ajax request sent , returns list of airposts options " <option value='1'>abc <option value='3'>lmn <option value='2'>xyz " now have replace options of select tag. trying like var country_select = document.getelementbyid("country_select"); country_select.options.length = 0; country_select.options = response.responsetext but assignment not working how may done! try var country_select = document.getelementbyid("country_select"); country_select.innerhtml = response.responsetext;

Best way to map objects differently in different situations (AutoMapper) -

i'm using automapper , want know way best approach map objects differently in different situations (for example, ignore 1 field in methoda, include field in methdob etc.). can create own mappingengine wonderign if there better way achieve that. you can map 1 source multiple destinations automapper. example can have source object with person id firstname lastname phonenumber and view models contactinfoviewmodel firstname phonenumber bioviewmodel firstname lastname phonenumber mapper.map<person, contactviewmodel>(); mapper.map<person, bioviewmodel>();

c# 3.0 - Problems writing C# method parameter validation that supports fluent interface (call chaining) -

i'm trying write generic method parameter validation functionality can chained (fluent interface) attach more , more validations/checks like: public void somemethod(user user, string description) { parameterhelper .create(() => user) .rejectnull(); parameterhelper .create(() => description) .rejectnull() .rejectemptystring(); // luxurious parameterhelper .create(() => new { user = user, desc = description }) .rejectnull(o => o.user) .rejectnull(o => o.desc) .rejectemptystring(o => o.desc); } i use helper class test method parameters values before using them (most of time null tested). current state of affairs i first started writing static helper class without create() method like: public static class parameterhelper { public static void rejectnull(expression<func<t>> expr) { if (expr.compile()().equals(default(t))) { ...

java - If you pass another object a current object's Graphics2D, would it paint on the current object? -

for example have class extends jpanel, , want pass it's graphics2d class b. if operations on graphics2d instance in class b paint on class a? public void paintcomponent(graphics g){ super.paintcomponent(g); graphics2d g2d = (graphics2d)g; ... b.dosomepainting(g2d); ... } yes . make think otherwise? you're doing delegating painting of graphics2d object of class a class b . it's simple.

Delay jQuery Mobile transition in order to hide embedded Youtube video -

i'm using jquery mobile create site display embedded youtube clip on 1 of pages. my problem when user tries navigate page, embedded object remains "over" page whilst transition plays. result video appears on 2nd page split second , doesn't good. i've tried using .hide() on video when link clicked , tried creating timeout no avail - can recommend solution? you have remove actual video page; happens on every browser, because flash appears on other content.

android - How to make a click on an item in the global search provider (Quick Search Box) go to the correct Activity -

i have application has structure: activity a activity b activity c in activity b call startactivityforresult on activity c. in activity c have search provider user can search addresses , return them activity b. this works great, when introduce search results in quick search box ( reference link ) click on suggestion go straight activity c. calling finish on activity not want (returning b result). so suggestions on how rewrite work in both scenarios? you need pass result between activities activity c --> send result ---> activity b. how use onactivityresult(..) if activity called menu see answer here. same, mind comments below.

Rails Model Naming: Fix or Leave As-Is -

this more of philosophical question technical one. i'm 40 hours working on new rails app. it's retail-related, , on chose name "item" describe single available product sale. as time has gone on it's become obvious me mistake - word "item" generic, , "product" perhaps have been better choice. so decision i'm faced is, refactor / rename models, erb code , tables before build more poorly chosen name, or leave as-is, save time , move on? worry it's choosing latter repeatedly results in ridiculous technical debt i've seen on other projects, think might form of premature optimization. thoughts? naming convention absolutely necessary mid-to-large projects. go in , refactor make naming specific possible. generic identifiers out of hand new functionality gets introduced (i once on project had class named userreportreportreportparameters ). the quicker done, less painful be. edit : should add if impossible due deadlin...

javascript - How to limit display of iframe from an external site to specific domains only -

i operate service client's content prepared , displayed in iframe. client copies rudimentary iframe html tag , pastes web page. clients complain other websites copying iframe tag , pasting sites. is possible restrict display of iframe's content specific domain or domains? perhaps programmatically telling iframe parent must some-domain.com or else don't display. does make sense? can verbose. you can use .htaccess (assuming original content on apache server) limit access specific ip. or, if page php, limit specific domain, this: <?php $continue = 0; if(isset($_server['http_referer'])) { //correct domain: $ar=parse_url($_server['http_referer']); if( strpos($ar['host'], 'yourdomain.com') === false ){ } else { $continue = 1; } } if($continue == 0){ header('http/1.0 403 forbidden'); exit('forbidden'); } ?>

html - How to get an element's padding value using JavaScript? -

i have textarea in html. need padding numerical value in pixels either integer or float. how can using javascript? not using jquery, i'm looking pure javascript solutions. this return padding-left value: window.getcomputedstyle(txt, null).getpropertyvalue('padding-left') where txt reference textarea element. the above works in modern browsers , in ie9. however, not work in ie8 , below. live demo: http://jsfiddle.net/simevidas/yp6xx/ further reading: https://developer.mozilla.org/en/dom:window.getcomputedstyle btw, comparison, how same job done using jquery: $(txt).css('padding-left') the above work in ie6-8.

opencv - iPhone Photo Smile Manipulation Applications -

i'm trying create iphone application allows user take photo of smile, drag , drop new smiles, small predefined list. i know there lot of photo manipulation apps , have seen similar concepts allow smile manipulation, not quite looking for. problem knowing start. how can create effect? opencv iphone port best way go? or perhaps using opengl? willing research, find experience goes long way, advice or insight appreciated. that's pretty cool application. i'd recommend type of dense optical flow type alignment method strike balance between global consistency , local consistency. in short, you'll want generic mouth shapes in gallery. then, can crop user's mouth region , warp gallery shape show smile in shape like. ce liu's optical flow implementation might interesting point start. should able port reasonably easily.

ios - CGContextDrawPDFPage memory leak -

hello here code drawing pdf in catiledlayer - (void)drawlayer:(calayer *)layer incontext:(cgcontextref)ctx { cgcontextsetrgbfillcolor(ctx, 1.0, 1.0, 1.0, 1.0); cgcontextfillrect(ctx, cgcontextgetclipboundingbox(ctx)); cgcontexttranslatectm(ctx, 0.0, layer.bounds.size.height); cgcontextscalectm(ctx, 1.0, -1.0); cgcontextconcatctm(ctx, cgpdfpagegetdrawingtransform(mypageref, kcgpdfcropbox, layer.bounds, 0, true)); cgcontextdrawpdfpage(ctx, mypageref); } all got memory leak warning in following line cgcontextdrawpdfpage(ctx, mypageref); here mypageref cgpdfpageref i had download code github , make r&d , found that, i forgot release cgpdfpagerelease(mypageref) in dealloc method of tiledview.. and after writing code memory leak solved.... // clean up. - (void)dealloc { cgpdfpagerelease(mypageref); [super dealloc]; }

c# - How to re write Office Automation Code -

Image
vs 2008 / c# / ms 2007 i have saved import feature in access database invokes odbc connection. instead of depending on in-built saved import feature, trying rewrite feature in c# call odbc connection import data ms access database. i not able call connection string saved in access database calls odbc drivers. keep failing .. !! access.application access1 = new access.application(); try { string ssalisburyaccessdb = server.mappath("app_data/database1.mdb"); access1.opencurrentdatabase(ssalisburyaccessdb, true, null); // drop existing table data access1.docmd.deleteobject(access.acobjecttype.actable, "plans"); access1.docmd.deleteobject(access.acobjecttype.actable, "price"); // run saved import access1.docmd.runsavedimportexport("testodbc"); // close database access1.closecurrentdatabase(); // quit ms access access1.quit(access.acqui...

c# - Generic method to type casting -

i'm trying write generic method cast types. want write cast.to<type>(variable) instead of (type) variable . wrong version of method: public class cast { public static t to<t>(object o) { return (t) o; } } and simple test: public class { public static explicit operator b(a a) { return new b(); } } public class b { } a = new a(); b b = cast.to<b>(a); as guessed, code fail invalidcastexception . is code fail because virtual machine doesn't know how cast variable of type object type b @ run-time? exception message says: "unable cast object of type type b". clr knows real type of variable o , why cannot perform casting? and here main question: how should rewrite method t to<t>(object o) fix problem? if can use c# 4.0 works: namespace casttest { internal class program { private static void main(string[] args) { a = new a(); b b = ...

How to update an object with nhibernate + fluent nhibernate? -

i query through nhibernate record database. var result = session.query<tablea>().where(x => x.id == 10).firstordefault(); result.where = "hi"; session.update(result) session.commit(); so result , update property , try update , commit it. crash because have forigen key table b(table can has 1 table b , table b has many table a's) so reference cannot null. when tries update crashes. so have var result = session.query<tablea>().where(x => x.id == 10).firstordefault(); result.where = "hi"; result.tableb = session.load<tableb>(1); session.update(result) session.commit(); then happy. how can update without having load tableb in? set update value of tableb property mapping false. i'm not sure how you'd using fluent nhibernate, looks setattribute method you. something along lines of: .setattribute("update", "false");

windows - How to create a game save file format in c++ using STL -

i learned i/o part of stl, more fstream. although can save binary info , classes i've made hard drive, not sure how define how info should read. i saw answer making file format this post: typically define lot of records/structures, such bitmapinfoheader, , specify in order should come, how should nestled, , might need write lot of indices , look-up tables. such files consists of number of records (maybe nestled), look-up tables, magic words (indicating structure begin, structures end, etc.) , strings in custom-defined format. what want know how the stl , c++... since format meant use of game think easier though. format should: be traversable (i can through , find start of structure , maybe check name be able hold multiple classes , data in single file have identifiable starts , ends sections: such space in text files maybe have it's own icon represent it?? how do in c++ ? the first stage in determining how structure save-file determin...

.htaccess - Rewrite url with query string in htaccess -

today try rewrite ugly url in order cache browser! problem have multiparameters inside url. example better long text : the actual url ? , & : http://images.mydomain.com/lib/simple-thumb.php?src=http://google.com&l=180&h=135&zc=1 and want use instead : http://images.mydomain.com/lib/http://google.com/180/135/1 should use rule below in .htaccess? options +followsymlinks rewriteengine on rewritecond %{query_string} ^(.*)$ rewriterule simple-thumb\.php /lib/%1/? [r=301,l] but not seams work... thanks kind help try options +followsymlinks rewriteengine on rewriterule ^/lib/http\:\/\/google.com/([0-9]+)/([0-9]+)/([0-9]+)$ /lib/simple-thumb.php?src=http://google.com&l=$1&h=$2&zc=$3

customization - Custom overlay over normal Android usage -

i want build android app educational purpose , don't know if idea feasible. i want display bar text on bottom of screen , allow user keep using operating system. example browsing web , been able seen text bar @ same time. you can't overlay view , allow user interact background activities @ same time.

iphone - iOS4.3 Entitlements.plist for Ad Hoc Distribution -

Image
ok, i've done 3 ad hoc distributions , each 1 has had own problems in 1 way or other, 1 has me perplexed. i've set do, after distributing dreaded "entitlements invalid" error appears after attempting install. i'm using ios4.3 , xcode 4 gm 2. i have entitlements set follows: (source view): <?xml version="1.0" encoding="utf-8"?> <!doctype plist public "-//apple//dtd plist 1.0//en" "http://www.apple.com/dtds/propertylist-1.0.dtd"> <plist version="1.0"> <dict> <key>get-task-allow</key> <false/> <key>application-identifier</key> <string>$(appidentifierprefix)$(cfbundleidentifier)</string> <key>keychain-access-groups</key> <array> <string>$(appidentifierprefix)$(cfbundleidentifier)</string> </array> </dict> </plist> same every entitlement i've ever used....

java - Socket transferring -

i have several classes running @ same time input server. both have sockets set up. the problem that, though transfer same data between classes, when data arrives, not same. here sending method: private boolean transferbroadcastdata() { boolean success = false; try { vector<client> clientslist = onlinelist.getclientslist(); (client client : clientslist) { objectoutputstream objectoutputstream = client.getobjectoutputstream(); objectoutputstream.writeobject(clientslist); objectoutputstream.flush(); } success = true; } catch (exception ioexception) { ioexception.printstacktrace(); } return success; } and here receiving-method: while (true) { try { ...

c - undefined reference to sqrt (or other mathematical functions) -

i have simple code: max = (int) sqrt (number); and in header have: #include <math.h> but application still says undefined reference sqrt . see problem here? looks should okay. you may find have link math libraries on whatever system you're using, like: gcc -o myprog myprog.c -l/path/to/libs -lm ^^^ - bit here. including headers lets compiler know function declarations not automatically link code required perform function. failing that, you'll need show code, compile command , platform you're running on (operating system, compiler, etc). the following code compiles , links fine: #include <math.h> int main (void) { int max = sqrt (9); return 0; } just aware some compilation systems depend on order in libraries given on command line. that, mean may process libraries in sequence , use them satisfy unresolved symbols at point in sequence. so, example, given commands: gcc -o plugh ...

osx - c++ #ifdef Mac OS X question -

i new c++. working on group project , want make our classes compatible both lab computers (windows) , computer (mac os x). here have been putting @ top of our files: #ifdef target_os_x # include <glut/glut.h> # include <opengl/opengl.h> #elif defined _win32 || defined _win64 # include <gl\glut.h> #endif i realize question has been asked before searches have been giving me conflicting answers such "_mac", "target_mac_os", "macintosh", etc. current , correct declaration put in #ifdef statement make compatible mac? right not working. thank you! according this answer : #ifdef __apple__ #include "targetconditionals.h" #ifdef target_os_iphone // ios #elif target_iphone_simulator // ios simulator #elif target_os_mac // other kinds of mac os #else // unsupported platform #endif #endif so in short: #ifdef __apple__ #include "targetcon...