text
stringlengths
8
267k
meta
dict
Q: count the status types and put totals in one row I have the following result set Status, Name 0, Type0 0, Type0 1, Type1 0, Type0 2, Type2 How do I sum the counts of types and make it look like Type0,Type1,Type2 3,1,1 A: SELECT COUNT(CASE WHEN Name='Type0' THEN 1 END) AS Type0, COUNT(CASE WHEN Name='Type1' THEN 1 END) AS Type1, COUNT(CASE WHEN Name='Type2' THEN 1 END) AS Type2 FROM YourTable
{ "language": "en", "url": "https://stackoverflow.com/questions/7539676", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: IE9+: poor performance while dealing with DOM Compared to other browsers, IE9 executes this script (for dynamic manipulation of DOM) with a very long running time. I am curious; in what ways would it impact the execution speed of next-generation rich applications? Other than this iterative test, is there any related real world webapp example, where we can observe the difference in performance? Also, is it the problem with their JS engine or the Layout engine? Update: The issue is resolved in IE10 RTM. A: Use: function testAppendFrag(div) { var docFrag=document.createDocumentFragment(),i=count; while(i--){ docFrag.appendChild(document.createElement("div")); } div.appendChild(docFrag.cloneNode(true)); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7539678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why does jsfiddle ignore gist css files? Adding a gist css-file to jsfiddle by "Add Resources" url does not seem to work. Am I missing something or is it not supported? Fiddle that does not load from url: http://jsfiddle.net/keffot/dpWWz/ Fiddle with css content copied to css-frame: http://jsfiddle.net/keffot/DTFfK/ A: Yep. The problem is in the https. I've added the same file but from my dropbox public folder and here is result: http://jsfiddle.net/dpWWz/3/ Link to the file is: http://dl.dropbox.com/u/18372729/page-layout.css
{ "language": "en", "url": "https://stackoverflow.com/questions/7539679", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mysql & group_concat_length Let say I have a table with million of rows. Does this sql query stop as soon as "group_concat_length" limit value is reached for all "id_list" or does it test all rows in the table? SELECT GROUP_CONCAT(id) AS id_list, type FROM table WHERE 1 GROUP BY type A: All rows and groups are processed Only an individual aggregation is truncated http://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7539683", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: crystal report in only one page I want to print a receipt of supermarket I designed it : section 1 header section 2 the head of table section 3 the table section 4 report footer section 1 has the total bill if number of rows more than 40 it print the report footer in new page with new head of table and new empty table I want to print the report footer at the end of the table and doesn't depend on number of rows in table how? A: You're basically asking if Crystal Reports can print an unlimited amount of records on a single page. The answer is no. To get around your issue, I guess you could dynamically reduce the font size the more records you have in the report, but this would not handle "unlimited" rows. Other than that, you may have a "paper size" issue. You can address that in your printer setup.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539687", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Accessing array declared inside a class via object of that class I have created a class named as MEMBERS. In this class I have declared an array as a member variable. class member { public $arr_connections; function connections($id) { $query = mysql_query("Select * from connections where user_id = '$id'"); while($info = mysql_fetch_array($query)) { $arr_connections[] = $info['connection_id']; } } } Then I have created an object of this class as follow $user = new member(); After this I am calling the function as $user->connections($user->id); Next I am displaying the array foreach($user->arr_connections as $mem_id) { echo $mem_id; $person = new member($mem_id); echo "<a href = 'profile.php?id=$person->id'><img src = '$person->display_picture'/ width = 30 height = 30></a>"; } This is not working. I guess my method is wrong. Some constructor was required. But I have to do this without constructor. Any suggestions? A: You're not assigning it to the class property, because you're missing $this->. Change it into this and it should work for you: $this->arr_connections[] = $info['connection_id'];
{ "language": "en", "url": "https://stackoverflow.com/questions/7539693", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: unix script - problem in making a text file - creating text file with some unicode character I am writing a simple unix script as follows: #!/bin/bash mkdir tmp/temp1 cd tmp/temp1 echo "ab bc cj nn mm" > output.txt grep 'ab' output.txt > newoutput.txt I got following error message: grep : No such file or directory found output.txt but when I looked into the directory the text is created output.txt...but the type of the file was TXT....I am not sure what it is any help?? Actually it creates the text file as "output" some unicode character or something...any help???? A: Try running the script without using '.txt'.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Yesod devel fails, thought cabal build succeeds I am relatively new to Haskell, coming from F# (a Microsoft language). I have created a Yesod project from the scaffolder, played with it a bit, tweaked stuff, but then it stopped working, with this error message (after all modules were built successfully): devel.hs: D:\yesod\projects\test101\dist\build\HStest101-0.0.0.o: unknown symbol `___stginit_test101zm0zi0zi0_HandlerziPage_' devel.hs: devel.hs: unable to load package `test101-0.0.0' Exit code: ExitFailure 1 By using cabal directly (cabal build, cabal install, dist\build\test101\test101) I was able to run the application, but this is really annoying. What can I do? Thanks! A: I think you need to add your new modules (Handler.Page in particular) to the cabal file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: drawing lines on top of UIImageView which has an image already I have a picture black and white of png format that is displayed with an UIImageView. It is a clock shape with no handles. so the background is white - and the circle is black. Then I would like to draw on top the handles for hours and minutes and I am struggling on how to do that although I am not far I can't make it to work... When I draw the handles I end up with a big black square (so I can't see through it to see my png behind it) and at least I see my 2 handles (in blue which I wanted). I guess the goal is to make that big black square to be white/transparent and so it should work... My code is like that below: - (void)drawRect:(CGRect)rect { ...... CGContextRef context = UIGraphicsGetCurrentContext(); CGContextClearRect(context, rect); CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor); CGContextSetRGBStrokeColor(context, 0.0, 0.0, 1.0, 1.0); [self drawLineForContext:context Width:10.0 angle:hAlpha length:self.frame.size.width/2.0 - 40]; [self drawLineForContext:context Width:5.0 angle:mAlpha length:self.frame.size.width/2.0 - 12]; } What do you think I am missing? For information, to set the image, I just do it like that, I guess it is correct as it works... UIImage *image = [UIImage imageNamed: [md objectForKey:Q_DIRECTION_PIC]]; [ivDirectionPic setImage: image]; ivDirectionPic.backgroundColor=[UIColor clearColor]; ivDirectionPic.contentMode = UIViewContentModeScaleAspectFit; Thanks for your help! Cheers, geebee EDIT1: I added the UIColor clearColor but it is still the same... and I do not understand your comment on how to add another subclass with same frame: how please? where? I am added also the extra function you asked me to post: - (void) drawLineForContext:(const CGContextRef)context Width:(float)_width angle:(double)_angle length:(double)radius { CGPoint c = CGPointMake(self.frame.size.width/2.0, self.frame.size.height/2.0); CGContextSetLineWidth(context, _width); CGContextMoveToPoint(context, self.center.x, self.center.y); CGPoint addLines[] = { CGPointMake(self.frame.size.width/2.0, self.frame.size.height/2.0), CGPointMake(radius*cos(_angle) +c.x, radius*sin(_angle) +c.y), }; CGContextAddLines(context, addLines, sizeof(addLines)/sizeof(addLines[0])); CGContextStrokePath(context); } A: Your UIImageView needs to have its backgroundColor set to [UIColor clearColor]. If this does not work, simply add add another subclass of UIView with the same frame on top of your image view. Another source of your error might be your drawLineForContext methods for which you did not post any code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Changing the projected value with MySQL How to change the projected value from select in MySQL? Is it possible with the following SQL? SELECT IF(situation=0,1,0) FROM users; Thanks in advance A: You can use MySQL's CASE Statement. SELECT CASE situation WHEN 0 THEN 1 ELSE 0 END CASE FROM users; HQL also has the CASE expression. Check this link. A: This depends highly on the DBMS. You can use Oracle NVL or CASE as Marcelo suggests. But I would go for a COALESCE SQL function. http://www.1keydata.com/sql/sql-coalesce.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7539707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# (Mono): Restarting process on program failure I'm fairly new with working in Mono and would like to know how I can force my console application to restart upon exception under a linux environment. How would I go about doing this? A: If the process dies, you can use something like Monit to keep it running. Brief description: Monit can start a process if it does not run, restart a process if it does not respond and stop a process if it uses too much resources. Typically, coding an application to "be able to restart itself" is never reliable enough. It someone were to terminate the application using kill -9, your application would have no ability to respond to that. Thus, the need of some type of daemon or watchdog is required. A: I'm not sure if this would work under Linux since I've never used Mono, but what I would try is to hook into the Process.Exited event. (I'm assuming you're starting your application with the Process class) Process.Exited http://msdn.microsoft.com/en-us/library/system.diagnostics.process.exited.aspx So you could do something like... -start process -hook into exited event -wait till exited event is called -start process -hook into exited event Good Luck! A: I'll recommend this get moved to superuser. There is nothing inherently in Mono you want to use. You could create a Watchdog application in Mono that will check and ensure your process is always running but there are plenty of Linux scripts and applications to already do this. Monit is an example. Or you can go into /etc/inittab and find the rows called respawn and add your daemon there. init will ensure that process is always running. Here is an example daemon startup script for Java which you can modify for mono. http://shrubbery.homeip.net/c/display/W/Java+Daemon+Startup+Script
{ "language": "en", "url": "https://stackoverflow.com/questions/7539708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C++ WM_NCCALCSIZE not being sent I'm trying to center the text in a edit control vertically, after some research I found I have to process the WM_NCCALCSIZE message. So i've subclassed my edit control, but the WM_NCCALCSIZE message is never sent. Am I doing something wrong? EDIT: So i'm processing the WM_NCCALCSIZE message fine, and I have a 3d border created by passing WS_EX_CLIENTEDGE to CreateWindowEx. But if I disable windows themes by killing the theme service, the border goes away on the control thats processing the WM_NCCALCSIZE message. Another control that doesnt process the WM_NCCALCSIZE message still has the border like normal. So i'm assuming I'm supposed to be doing somethign in WM_NCCALCSIZE that allows me to keep the border? If so what? if not any way to get the border back? A: Figured it out, WM_NCCALCSIZE is sent before the edit control is subclassed. So i had to superclass the EDIT class. EDIT: Another solution I just thought of would be to subclass it, then call SetWindowPos with SWP_FRAMECHANGED, this causes it to send the WM_NCCALCSIZE message. If anyone has any opinions why one method would be better then the other, please comment :) A: Instead of tinkering with WM_NCCALCSIZE (a very difficult message to manage), why not just reposition your edit control vertically so that the text is at the vertical position you prefer? You can put it inside a white box to provide the white space around it. Alternatively, you can use EM_SETRECT to put the text exactly where you want it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ASP classic logic issue I have recently taken over a website written in ASP Classic. It uses a MS access database for the back end. The website allows people to sign in and pay a membership fee in order to keep there account active. My Problem is when someones account expires I have no way to change the status of the account from active to inactive. All of the code uses that as a reference rather then the dates. Any suggestions on how I could automatically go through and deactivate accounts as they expire? Thanks A: You didn't provide details about how you store that information, but perhaps you are able to update account status with an UPDATE query similar to this: UPDATE tblMembership Set Active = False WHERE expiration_date < Date(); Since you can't connect to the the database directly. You can run the UPDATE statement from an ASP page. And open that page when you want to update membership status. Another possibility is to change the criteria for the query you use to display the membership list. WHERE Active = True And expiration_date >= Date(); That way you would filter out expired members whose [Active] status hasn't been updated yet. A: There's a number of ways to do this. One thing you can do is create a simple update function that goes through the database, checks dates and "deactivates" any expired accounts. I would put this function into the login proceedure so that it checks the user account and deactivates it if expired. So during login, when the user provides credentials and you take those credentials and compare against stored database values, at the same time you could check expiration dates and deactivate the account if expired. Hope that makes sense. A: If you have access to the server, maybe using the task scheduler to run a vb script to update the database as suggested by Damon.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539714", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Node.js as a JSON forwarder I'm new to Node.js but I wanted to use it as a quick web server which would simply take in a request uri and then run a query on an internal service which returns a JSON stream. I.e. something like this: http.createServer(function(request, response) { var uri = url.parse(request.url).pathname; if(uri === "/streamA") { //send get request to internal network server http://server:1234/db?someReqA -->Returns JSON ....? //send response to requestor of the JSON from the above get ....? } else if(uri === "/streamB") { //send get request to internal network server http://server:1234/db?someReqB -->Returns JSON ....? //send response to requestor of the JSON from the above get....? }.listen(8080); I'm using the newest stable version of node.js - version 0.4.12. I was hoping this would be very easy to do however, I havent been able to find some examples on the net as they all seem to use an old API version so I'm getting error after error. Would anyone be able to provide a code solution to the above that works with the new Node APIs? Thanks! A: here is a code that should explain your task: var http = require('http'); var url = require('url') var options = { host: 'www.google.com', port: 80, path: '/' //Make sure path is escaped }; //Options for getting the remote page http.createServer(function(request, response) { var uri = url.parse(request.url).pathname; if(uri === "/streamA") { http.get(options, function(res) { res.pipe( response ); //Everything from the remote page is written into the response //The connection is also auto closed }).on('error', function(e) { response.writeHead( 500 ); //Internal server error response.end( "Got error " + e); //End the request with this message }); } else { response.writeHead( 404 ); //Could not find it response.end("Invalid request"); } }).listen(8080); A: You should use express, it would make it a lot easier. var app = express.createServer(); app.get('/json1', function(req, res){ var json // = res.send(json); }); app.get('/json2', function(req, res){ var json // = res.send(json); }); app.listen(8000); A: Ok since this question has a number of up-votes it would seem others are interested in it as well. While Nican's answer was the most helpful for getting actual JSON, I decided that my solution would use both the http lib and express as suggested by 3on as I really like its simplicity... So for those interested my final solution was a combo of the two: var http = require("http"), url = require("url"); var app = require('express').createServer(); app.listen(9898); var query = {"SQL" : "SELECT * FROM classifier_results_summary"}; var options = { host: 'issa', port: 9090, path: '/db?'+ escape(JSON.stringify(query)) }; //Options for getting the remote page app.get('/stream/:id', function(req, res){ //console.log(options.path); http.get(options, function(response) { response.pipe( res ); //Everything from the remote page is written into the response //The connection is also auto closed }).on('error', function(e) { response.writeHead( 500 ); //Internal server error response.end( "Got error " + e); //End the request with this message }); }); Very nice and neat. Thanks for the help all.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Implementing meta-function zip in c++11 I am actually trying to see if I can get a minimal library that supports the very few operations I use from boost::fusion. Here is what I have so far... template < typename... Types > struct typelist { }; template < template < typename... > class F, typename... Args > struct apply { typedef typename F < Args... >::type type; }; template < typename, template < typename... > class > struct foreach; template < typename... Types, template < typename Arg > class F > struct foreach < typelist < Types... >, F > { typedef typelist < typename apply < F, Types >::type... > type; }; Since the meta-function foreach implementation is trivial, I thought zip would be easy too. Apparently, this is not the case. template < typename... > struct zip; template < typename... Types0, typename... Types1 > struct zip < typelist < Types0... >, typelist < Types1... > > { typedef typelist < typelist < Types0, Types1 >... > type; }; How can I generalize this zip meta-function to arbitrary number of typelists? What we need here seems to be a parameter pack of parameter packs. I am not sure how to do that. Edit 1: Implementation of is_equal... template < std::size_t... Nn > struct is_equal; template < std::size_t N0, std::size_t N1, std::size_t... Nn > struct is_equal < N0, N1, Nn... > : and_ < typename is_equal < N0, N1 >::type , typename is_equal < N1, Nn... >::type >::type { }; template < std::size_t M, std::size_t N > struct is_equal < M, N > : std::false_type { typedef std::false_type type; }; template < std::size_t N > struct is_equal < N, N > : std::true_type { typedef std::true_type type; }; A similar approach can be taken to zip as well I think... haven't tried with zip yet, but will do so when I get back home. Edit 2: Here is what I finally thought looked more elegant. This is basically a variation of Vaughn Cato's approach. namespace impl { template < typename Initial, template < typename, typename > class F, typename... Types > struct foldl; template < typename Initial, template < typename, typename > class F, typename First, typename... Rest > struct foldl < Initial, F, First, Rest... > { typedef typename foldl < typename F < Initial, First >::type, F, Rest... >::type type; }; template < typename Final, template < typename, typename > class F > struct foldl < Final, F > { typedef Final type; }; template < typename Type, typename TypeList > struct cons; template < typename Type, typename... Types > struct cons < Type, typelist < Types... > > { typedef typelist < Types..., Type > type; }; template < typename, typename > struct zip_accumulator; template < typename... Types0, typename... Types1 > struct zip_accumulator < typelist < Types0... >, typelist < Types1... > > { typedef typelist < typename cons < Types1, Types0 >::type... > type; }; template < typename... Types0 > struct zip_accumulator < typelist <>, typelist < Types0... > > { typedef typelist < typelist < Types0 >... > type; }; template < typename... TypeLists > struct zip { typedef typename foldl < typelist <>, zip_accumulator, TypeLists... >::type type; }; } template < typename... TypeLists > struct zip { static_assert(and_ < typename is_type_list < TypeLists >... >::value, "All parameters must be type lists for zip"); static_assert(is_equal < TypeLists::length... >::value, "Length of all parameter type lists must be same for zip"); typedef typename impl::zip < TypeLists... >::type type; }; template < typename... TypeLists > struct zip < typelist < TypeLists... > > : zip < TypeLists... > { }; This treats zip as a fold operation. A: This is the shortest implementation I've discovered: template <typename...> struct typelist { }; template <typename A,typename B> struct prepend; template <typename A,typename B> struct joincols; template <typename...> struct zip; template <typename A,typename... B> struct prepend<A,typelist<B...> > { typedef typelist<A,B...> type; }; template <> struct joincols<typelist<>,typelist<> > { typedef typelist<> type; }; template <typename A,typename... B> struct joincols<typelist<A,B...>,typelist<> > { typedef typename prepend< typelist<A>, typename joincols<typelist<B...>,typelist<> >::type >::type type; }; template <typename A,typename... B,typename C,typename... D> struct joincols<typelist<A,B...>,typelist<C,D...> > { typedef typename prepend< typename prepend<A,C>::type, typename joincols<typelist<B...>,typelist<D...> >::type >::type type; }; template <> struct zip<> { typedef typelist<> type; }; template <typename A,typename... B> struct zip<A,B...> { typedef typename joincols<A,typename zip<B...>::type>::type type; }; A: Seems to be doable with fully-fledged lists (that means head, tail and cons operations) and recursion. Tested with a snapshot of GCC 4.7, all the std stuff is from <type_traits>: struct nil {}; template<typename T> struct is_nil: std::is_same<T, nil> {}; template<typename... T> struct and_: std::true_type {}; template<typename First, typename... Rest> struct and_<First, Rest...> : std::integral_constant< bool , First::value && and_<Rest...>::value > {}; template<typename T> struct not_ : std::integral_constant<bool, !T::value> {}; template<typename... T> struct typelist; template<typename First, typename Second, typename... Rest> struct typelist<First, Second, Rest...> { typedef First head; typedef typelist<Second, Rest...> tail; }; template<typename Last> struct typelist<Last> { typedef Last head; typedef nil tail; }; template<typename T, typename List> struct cons; template<typename T, typename... Ts> struct cons<T, typelist<Ts...>> { typedef typelist<T, Ts...> type; }; // workaround for: // sorry, unimplemented: cannot expand '...' into a fixed-length argument list template<template<typename...> class Template, typename... T> struct gcc_workaround { typedef Template<T...> type; }; namespace detail { template<typename Sfinae, typename... Lists> struct zip; template<typename... Lists> struct zip< typename std::enable_if<and_<is_nil<typename Lists::tail>...>::value>::type , Lists... > { typedef typelist<typelist<typename Lists::head...>> type; }; template<typename... Lists> struct zip< typename std::enable_if<and_<not_<is_nil<typename Lists::tail>>...>::value>::type , Lists... > { typedef typename cons< typelist<typename Lists::head...> , typename gcc_workaround<zip, void, typename Lists::tail...>::type::type >::type type; }; } // detail template<typename... Lists> struct zip: detail::zip<void, Lists...> {}; You might want to add error checking to all this (I'm thinking of invalid instantiations that are currently simply left as incomplete types). Frankly given the amount of time it took me to figure this out, I'd suggest sticking with Boost.MPL. Things like lazy evaluation (with which I wouldn't have needed to do the SFINAE stuff) are a boon and I'd don't like reinventing them. Plus the day it's C++11 enabled you reap the best of both worlds. I forgot to mention that Boost.MPL also has the advantages of genericity. It can work on any type that satisfies one of its sequence concept (it's also possible to non-intrusively adapt a preexisting type), whereas you force the use of typelist.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539716", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Better way to handle multiple DropDown selection I have a menu with multiple DropDowns. I added code but at present, it entirely resides in the code-behind file. I want to use any design pattern to handle in an easy and uncluttered way the variety of choices. The report generation criteria is prepared as follows: Report Type DropDown options include: * *Scheme Type-wise *Scheme-wise *District-wise *Block-wise *All By default, only the first DropDown is enabled. Selecting an option from this DropDown, enables the respective DropDowns. Not only this, values of Scheme, District and Block DropDowns also change when an item is selected from any of these DropDowns or Scheme Type DropDown using AJAX. It involves a variety of SQL queries and Enabling/Disabling DropDowns often. My present code has become cluttered with many IF and EndIfs. I want to know whether Observer pattern or any approach using Classes be used to simplify this operation. Any way to make this multiple selections and filling of DropDowns manageable and simple? Edited below to clear requirements Let me clarify further. The first DropDown is the key DropDown which is enabled by default when the page opens. All the other DropDowns are disabled by default. But this does not mean that Cascading DropDown is the correct choice because, the selection from the child DropDowns is random. The whole plan is to simplify the code in an understandable form for each DropDown. There are many Ifs and ElseIfs involved to pick the correct query depending upon the selection. For example: The user selects, District-wise report from the Report Type primary DropDown. In this case, three child DropDowns are enabled, viz. Scheme Type Scheme District If user selects "ALL" from Scheme Types List, all types of schemes in all categories gets filled in the Scheme DropDown. If user selects a particular Scheme Type from the options: Urban, Rural or Other, the Scheme DropDown filters the name of the schemes. Now, Scheme DropDown also has an option ALL. The user can select ALL or pick any particular scheme. Same is with District. If ALL is selected, schemes in the Scheme DropDown takes all schemes in all districts, but if a particular district is selected, the Scheme DropDown must fill the filtered schemes of this district. Please note that in this case, we are now moving in a reverse order because District DropDown is again filtering the Scheme DropDown. The same is applicable with the Block DropDown. There are variety of conditions to be checked other the selected option. Suppose the user didn't select any option or the user selects ALL. I want to create separate classes with the names of each DropDown. These classes should keep hearing notifications (Observer) for any changes in the DropDown. I guess I was able to clarify. A: Using AJAX Control Toolkit is the solution that matches your requirements. In AJAX Control Toolkit, there is CascadingDropDown Control Tag Syntax: <ajaxToolkit:CascadingDropDown ID="ddlReportType" runat="server" TargetControlID="ddlSchemeType" Category="SchemeType" PromptText="Please select a ReportType" LoadingText="[Loading Report Types...]" ServicePath="ReportService.asmx" ServiceMethod="GetDropDownReportTypeContents" ParentControlID="DropDownList1" SelectedValue="SomeValue" /> And then you need to create an Web Service and few Web Method(s) for it having following method signature, [System.Web.Services.WebMethod] [System.Web.Script.Services.ScriptMethod] public CascadingDropDownNameValue[] GetDropDownReportTypeContents( string knownTypeValues, string typevalue) { ... } UPDATE You have do something like this using if-Else-If, Answer is given on assumptions and purely an example to the implementations. string query = "SELECT * FROM Reports"; List<string> filters = new List<string>(); bool ReportType = true; bool SchemeType = true; bool Scheme = true; bool District = true; bool Block = true; if (ReportType) filters.Add("ReportType = true"); if (SchemeType) filters.Add("SchemeType = true"); if (Scheme) filters.Add("Scheme = true"); if (District) filters.Add("District = true"); if (Block) filters.Add("Block = true"); if (filters.Count() > 0) { query = query + " WHERE " + string.Join(" AND ", filters.ToArray()); } I hope that my answer helps you Thanks and Regards Harsh Baid A: Since it seems you can do all of this client side using Javascript why are you querying your database so much? You should persist the data client side and server side. You could call all related drop-down data, cache it and from the client side call a WebMethod that would return a JSON with the data you need. For server side object persistence you should check out the Entity Framework 4.1 where each object is a representation of a table. I would use jQuery with Knockout JS or just jQuery for it, persisting the data on the client side using JSON, there is no need to go back and forward to the sql server. Here's a nice example of Knockout JS in action. http://knockoutjs.com/examples/cartEditor.html Of course unless that data changes extremely frequently. A: Not exactly what you are looking for, but you may want to check out how I resolved similar issue in mvc with jQuery. Same can be achieved in webforms using web methods instead of mvc actions. It is a story in 3 parts, and code is available on bitbucket. You may start form part 2 as first is creation of demo app and setup of database. http://blog.goranobradovic.com/2011/06/asp-net-mvc3-app-part-2-ajax-cascading-dropdown/ There is working example for 2 dropdowns, but I used same solution for 3 and 4 without problems. UPDATE As you have source available, I will put only relevant lines to change here. The adjustment to prevent multiple ajax calls would be putting values of options in first select to id's (or id's to values it does not matter), or you could use some attribute in dependent dropdown if you cannot change ids and values, but I will keep it simple for example. Then, in change event of master dropdown you check if target needs to be loaded: $('#' + target.attr('cascading-dependson')).change(function () { if($(this).find("option:selected").val() == $(target).attr("id")){ // this is added if $(target).removeAttr("disabled"); // added selectFromAjax($(target).attr('cascading-loadfrom'), { id: $(this).find("option:selected").val() }, target); } else { //added $(target).attr("disabled", "disabled"); } }); You can easily change this if to use some custom attribute of select if you don't want use id. UPDATE 2 I just saw that you updated question. As I see, there is a case where you need to refresh all dependent dropdowns. For this you need to have id-s of all dropdowns which need to be refreshed in last master select option's value, separeted i.e. with ",", so you can check if any of its val().split(",") is equal to id of dependent dropdown, or you can have attribute in dependend which contain values of all options for which it needs to refresh. You see in my code that options for selectFromAjax are selected value in dropdown and name of master field. As you probably need to have some your value in here to be handled by server code, I suggest that you use second way, that is - add custom attribute to dependend dropdown, in which you will put values of select options from master which are relevant for that field and dependent should load when selected. Do you understand what I suggest? A: If I'm understanding your paradigm correctly, really, you have one drop-down (Report Type) that determines whether to select by Scheme Type, Scheme, District, or Block (or all of the above). If you did not have the "All" option, I would suggest either having only two drop-downs (one for Report Type and one whose label changes to match) or eliminating the Report Type drop-down and putting a radio button next to each of the others to select which you want. When including the "All" option, you might not to complicate things much more; for instance, you could add one more radio button and enable all four drop-down lists. However, you ask about the Observer Pattern. From GoF, the Observer Pattern is useful when: * *An abstraction has two aspects, one dependent on the other; *A change to one object requires changing others, and you don't know how many objects need to be changed; or *An object should be able to notify other objects without making assumptions about who these objects are. I'm not entirely sure any of these situations applies here. The second situation has some similarities to your problem, but you do know what needs to be changed and how. If the only updating you are doing is by Report Type, it's just a matter of enabling or disabling the right drop-down menu. However, you say that the other drop-downs affect each other, probably in the "All" option. Even in this case, I'm not sure the Observer Pattern per se is the most helpful. Since you are populating the drop-downs using SQL, I'm guessing you might be using a number of different stored procedures (or ad-hoc queries) depending which parameters you need. What I might suggest instead is to have only one query per drop-down, making judicious use of NULL. For example, to populate Block from the other values, you might have: CREATE PROCEDURE GetBlocks ( @SchemeTypeId INT NULL, @SchemeId INT NULL, @DistrictId INT NULL ) AS SELECT b.BlockId, b.BlockName FROM Blocks b INNER JOIN SchemeTypeBlocks stb ON b.BlockId = stb.BlockId INNER JOIN SchemeBlocks sb ON b.BlockId = sb.BlockId INNER JOIN DistrictBlocks db ON b.BlockId = db.BlockId WHERE (@SchemeTypeId IS NULL OR stb.SchemeTypeId = @SchemeTypeId) AND (@SchemeId IS NULL OR sb.SchemeId = @SchemeId) AND (@DistrictId IS NULL OR db.DistrictId = @DistrictId) ORDER BY b.BlockName Without knowing your database, I do not know exactly what will work, but the idea is that you just pass NULL for anything you do not yet have selected. This could perhaps simplify your code a bit. If this doesn't answer your question, let me know what I can clarify. A: There is a Simple Way to Achieve this, follow this approach: First of All, just add an AjaxUpdatePanel... and then in drop down set AutoPostBack property to true, further just add the handler on OnSelectedIndexChanged event to enable second drop down.. <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate><asp:DropDownList id="firstDrpDown" AutoPostBack="true" OnSelectedIndexChanged="firstDropDown_SelectedIndexChanged"AppendDataBoundItems="true" name="firstDropDown" runat="server"> <asp:DropDownList id="scndDrpDown" **AutoPostBack="true"** OnSelectedIndexChanged="scndDropDown_SelectedIndexChanged" AppendDataBoundItems="true" name="scndDropDown" runat="server" > </ContentTemplate> <asp:UpdatePanel>
{ "language": "en", "url": "https://stackoverflow.com/questions/7539719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Android MapView not loading tiles on devices I am writing an Android application that uses Google Maps MapView to display maps. The application works fine in the emulator, but when I try to run it on an actual device it will not load any map tiles. I have already done the following: * *Checked that Eclipse ADT is configured with the default debug keystore *I have regenerated the Google Maps API key against the debug keystore *Checked that the application has access to the internet for the application also connects to a different server and that works ok. *I have checked and re-checked all the tips that are found in other similar question, but in case I have missed anything I have attached the res/layout file and the android manifest file. Layout file <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/mainlayout" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <com.google.android.maps.MapView android:id="@+id/mapview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:clickable="true" android:apiKey="0AVJ6OY3X1uWHCbkTOJx7ajC-TWI44phQofTSlg" /> </RelativeLayout> Android Manifest <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.android" android:versionCode="1" android:versionName="1.0"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-sdk android:minSdkVersion="7" /> <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true"> <uses-library android:name="com.google.android.maps" android:required="true"/> <activity android:name="DummyMap" android:label="@string/app_name"> </activity> <activity android:name="Dummy" android:label="@string/app_name" android:theme="@android:style/Theme.Light"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="ContactActivity" android:theme="@android:style/Theme.Light"></activity> <activity android:name="DummyPreferences"></activity> </application> </manifest> Any tips are welcome as I am now at the point where I have to randomly try to make changes to these file to see if anything works. A: I see in Android reference document (http://developer.android.com/reference/android/Manifest.permission.html#ACCESS_COARSE_LOCATION): ACCESS_COARSE_LOCATION Allows an application to access coarse (e.g., Cell-ID, WiFi) location But because you're running app on device, so you should add additional permission: ACCESS_FINE_LOCATION because with this permission, your device can get location by GPS ACCESS_FINE_LOCATION Allows an application to access fine (e.g., GPS) location A: I found the cause of the problem at last. In my subclass of MapActivity I had a onResume() method that called super.onStop()! Changing that to super.onResume() fixed the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the JSCC.get ... init? I want to build such a structure. Json data looked at Facebook.com. I face the following code in the output. JSCC.get here .... init how it works. Do not help me in this matter? "onload" :["JSCC.get('/j4e7daf70e8d78540345959110').init(HTML(\"\\u003cdiv ........ A: Solved! ..... JQuery Ajax Text Code ..... eval(json.onload) var JSCC = { get : function(){}, init: function(){} } $.extend(JSCC); A: JSCC appears to be some Facebook-internal API. There doesn't seem to be anything published about it, which means that it's most likely proprietary, and can't be legally used by anyone except Facebook.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539722", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Looking for references describing tail recursion optimization through exceptions I have implemented a small lisp interpretor (sapid lisp at google code) in python and sapid lisp itself. Perhaps its main characteristic is to implement tail and mutual recursion optimization through exceptions. Implementation details here https://sites.google.com/site/sapidlisp/recursion-optimization. The advantage over standard techniques is the limited changes to apply to a recursive interpretor to get tail recursion optimization. Disadvantage could be timing. I have found a similar technique used in a python decorator ( http://code.activestate.com/recipes/474088/ ). Now to put the technique in its context I am looking for references describing such a technique for lisp or other interpreted languages. Any information? A: See Eli's answer. But to add a little more context, Baker's Cheney on the M.T.A. technique was a well-known trick for implementing proper tail recursion that used the C stack as a nursery (as in generational GC) for continuation frames and other objects. Rather than keeping the stack small (as most implementations of tail recursion do), this technique allows the stack to grow for a while, then clears it with a big jump (longjmp, execption, whatever) every once in a while. And before you clear the stack, you copy all of the live stuff out of it onto the heap. That works fine as long as you're able and willing to trace the stack and copy objects out of the stack onto the heap. The paper Eli cited (Continuations from Generalized Stack Inspection) is about adapting the trick to "managed" platforms, where you can't inspect the stack directly. A: See Continuations from Generalized Stack Inspection by Pettyjohn et al, and a related addendum by Joe Marshall. ("interpreted", whatever that means these days, has nothing to do with the subject.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7539732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Stop WordPress from auto-formatting certain codes I have a small question for you. How can I stop WordPress from changing the & symbol to &#038;? I found the solution to stop formatiing the code with pharagraphs by remove_filter('the_content', 'wpautop'); but for this one I can't find it anywhere. Thank you! A: Typically, I do most of my editing in the "HTML" tab view. Then I know the characters I enter will not be altered. But there are times I want characters to be HTML-encoded. For example, I might mention some computer code in a post. I want the users to see those special characters, instead of the page interpreting my code example as HTML to be rendered. Then I go to the "Visual" tab to enter them. In this way I have quick access to enter literal characters or to have them HTML-encoded. If you really do want to prevent WordPress from ever encoding those characters, try some of these plugins. I haven't tried them, but they may help. http://wordpress.org/extend/plugins/raw-html/ http://wordpress.org/extend/plugins/preserve-code-formatting/ A: This caused me great headaches, so I created a shortcode to stop this behavior: function do_not_filter_content_shortcode( $atts, $content ) { return wp_specialchars_decode($content); } add_shortcode( 'do_not_filter', 'do_not_filter_content_shortcode' );
{ "language": "en", "url": "https://stackoverflow.com/questions/7539734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: IIS 7.5 w3wp.exe to run another process I have ASP.NET MVC3 application that runs on IIS. One of controllers actions starting the process "cmd /C git clone some-repo". I need to make sure that child process running under the user that already have git being setup. I use application pool with Identity == My Accout (admin + git is works). The processes starting up ok, but it hangs up. I think that because of wrong identity which runs it. Does anyone have experiece with starting up processes under IIS, have you seen something similar? What is the way to debug such issues? A: What I suspect is happening... On a per-user basis, you need to accept the public key of a remote SSH service. Your process is likely hung waiting for someone to accept the public key via keyboard input. In a console application, the user is you and you have already accepted it. As w3wp, the key has not been accepted - waiting forever for it to be accepted. You have a couple of options. * *If you control the identity of the AppPool of w3wc, you can login as that user, and permanently accept it yourself. You can use tools like PsExec to run a process as System or Network service as well. *Use a different overload of Process.Start to start it as a different user that has already accepted the public key. A: I think that your other question's solution works for this too. After setting impersonation to my username like this <identity impersonate="true" password="o1j2813n" userName="obrad" /> I have tried running processes from System.Diagnostics.Process.Start from mvc action and they appear under my username in windows task manager, so I think that this answer will be helpfull. EDIT The other part of problem - git not working is caused by wrong way to give git command. I have made some experiments and found a way how to clone a git repo from controller action: System.Diagnostics.Process.Start(@"C:\Program Files (x86)\Git\bin\git.exe", "clone git://github.com/goranobradovic/go.DB.JournalingBase.git " + @"C:\Users\obrad\Desktop\temp"); This command clones repo from git://github.com/goranobradovic/go.DB.JournalingBase.git to temp folder on my desktop.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error with Generate Scaffold Micropost I'm following the http://ruby.railstutorial.org/ From my application directory I run this command but receive the error below. I have searched around but can figure out how to fix. $ rails generate scaffold Micropost content:string user_id:integer This is the error: /Users/bryonthomas/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:235:in `load': /Users/bryonthomas/Code/demo_app/config/routes.rb:4: syntax error, unexpected '.' (SyntaxError) from /Users/bryonthomas/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:235:in `block in load' from /Users/bryonthomas/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:225:in `block in load_dependency' from /Users/bryonthomas/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:596:in `new_constants_in' from /Users/bryonthomas/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:225:in `load_dependency' from /Users/bryonthomas/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:235:in `load' from /Users/bryonthomas/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/railties-3.0.9/lib/rails/application.rb:127:in `block in reload_routes!' from /Users/bryonthomas/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/railties-3.0.9/lib/rails/application.rb:127:in `each' from /Users/bryonthomas/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/railties-3.0.9/lib/rails/application.rb:127:in `reload_routes!' from /Users/bryonthomas/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/railties-3.0.9/lib/rails/application.rb:120:in `block in routes_reloader' from /Users/bryonthomas/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/activesupport-3.0.9/lib/active_support/file_update_checker.rb:32:in `call' from /Users/bryonthomas/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/activesupport-3.0.9/lib/active_support/file_update_checker.rb:32:in `execute_if_updated' from /Users/bryonthomas/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/railties-3.0.9/lib/rails/application/finisher.rb:51:in `block (2 levels) in <module:Finisher>' from /Users/bryonthomas/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/railties-3.0.9/lib/rails/application/finisher.rb:52:in `call' from /Users/bryonthomas/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/railties-3.0.9/lib/rails/application/finisher.rb:52:in `block in <module:Finisher>' from /Users/bryonthomas/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/railties-3.0.9/lib/rails/initializable.rb:25:in `instance_exec' from /Users/bryonthomas/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/railties-3.0.9/lib/rails/initializable.rb:25:in `run' from /Users/bryonthomas/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/railties-3.0.9/lib/rails/initializable.rb:50:in `block in run_initializers' from /Users/bryonthomas/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/railties-3.0.9/lib/rails/initializable.rb:49:in `each' from /Users/bryonthomas/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/railties-3.0.9/lib/rails/initializable.rb:49:in `run_initializers' from /Users/bryonthomas/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/railties-3.0.9/lib/rails/application.rb:134:in `initialize!' from /Users/bryonthomas/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/railties-3.0.9/lib/rails/application.rb:77:in `method_missing' from /Users/bryonthomas/Code/demo_app/config/environment.rb:5:in `<top (required)>' from /Users/bryonthomas/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/railties-3.0.9/lib/rails/application.rb:103:in `require' from /Users/bryonthomas/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/railties-3.0.9/lib/rails/application.rb:103:in `require_environment!' from /Users/bryonthomas/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/railties-3.0.9/lib/rails/commands.rb:16:in `<top (required)>' from script/rails:6:in `require' from script/rails:6:in `<main>' My routes.rb is: DemoApp::Application.routes.draw do resources :users . . . end A: The key is in the first line of the error message. /config/routes.rb:4: syntax error, unexpected '.' (SyntaxError) Then in your routes file, notice that you have those periods, which do not belong. DemoApp::Application.routes.draw do resources :users . . . end Remove the periods. DemoApp::Application.routes.draw do resources :users end
{ "language": "en", "url": "https://stackoverflow.com/questions/7539737", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: partial class templates specialization, c++ I'm trying to figure it out, so I have this attempt of specializing a class template: template <class T, int size> class arr{ public: arr(T* in):_in(in){}; void print() { for (int i = 0; i < size; i++) { cout << _in[i]; } cout << endl; } private: T* _in; }; I want to create a special template for arr<char>. Before I added int size as a type parameter it was easy and the class declaretion was template<> class arr<double>. Now I have this template <> class arr<double,size> which results in this error: template argument 2 is invalid Any ideas of how to do it? thanks! A: template <int size> class arr<char, size> Also, you may want to change the type for size to an unsigned int or size_t (assuming size cannot be negative). A: You need to add int size to the first list- that is, the compiler has no source for size- you didn't declare it as a template argument and it's not a constant. template<int size> class arr<double, size> { ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7539738", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Get first and last word in element's text In JavaScript, how can I get the first and last words from an element's text? For example: <div class="content">this is a test</div>// output 'this' 'test' <p>This is another test</p>// output 'this' 'test' How can I do that? I am not sure how to use RegExp to match them. A: You should try to avoid parsing html with regex. Look at this SO answer RegEx match open tags except XHTML self-contained tags You can use this regex var x = '<p>test test1</p>'.replace(/(<[^>]*>)/g,'').split(' ') x[0] will be first word, x[x.length-1] will be last element A: getFirstAndLastWords("this is a test"); // Outputs: "this test" function getFirstAndLastWords(text) { var text_arr = text.split(" "); return text_arr[0] + " " + text_arr[text_arr.length-1]; } A: You can use the following regex with combined with replace() in Javascript /([a-z]+) .* ([a-z]+)/i Working demo: http://jsfiddle.net/e8yZd/2/ A: Better with elements than html. var text=(element.textContent || element.innerText).match(/\w+/g) ||[]; alert(text[0]+'\n'+text.pop());
{ "language": "en", "url": "https://stackoverflow.com/questions/7539747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Add SVNKit libraries in a NetBeans project I need to use SVNKit in a NetBeans project. I downloaded the stand-alone binaries but I don't know which JAR file I should add. The SVNKit wiki say's that I need to build the directory with Ant, but when doing that it gives me an error: build.xml does not exist! Any suggestions?
{ "language": "en", "url": "https://stackoverflow.com/questions/7539749", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Where to use CodeIgniter HTML table? I'm having a bit of difficulty understanding where this would go in CodeIgniter's application. I want to pull down some data from MySQL and display it in an HTML table. I know how to define models and how to write views ... my only question is: Should I create the HTML (call $this->table->generate();) in my View or my Controller? A: I would definitely generate the table in the view. $this->table->generate() returns HTML so I would pass the database result to the view and work with it there with the rest of your HTML.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to refresh only a part of the page when F5 or refresh button is pressed I'm designing a web application that has a shared menu for all pages. Due to this i decided to load the contents linked by the menu buttons inside a div, using jquery. So, I have this: $("#AddNewProductBtn").click(function() { $("#content").load("addproduct.html"); }); I want to keep track of the page displayed inside the "#content" div. If the users refreshes the page I want to load the same page in "#content". Is there any way to do this, or is there any workaround? I saw some websites that use an iframe to load the pages, but when a user clicks a button in the menu the url is also changed. I didn't find any info on how to do that. Thanks A: Here's a solution for the F5 and CTRL+R $(document).keydown(function(e) { if (e.which == 116 || e.keyCode == 82 && e.ctrlKey) { //116 = F5 $("#content").load("addproduct.html"); return false; } }); A: You should append parameter to the hash part of the url (after #), for example domain.com/index.php#addproduct Then on document.ready check the value after # and load the corresponding content. Some plugins like jQuery history use this technique. Additionally, you can leverage the local storage and cache parts of the code at the browser, so you won't load the content with AJAX call the second time. A: Alternatively, instead of using a hash, you can use the HTML5 history API (pushState, replaceState, and popstate). Basically, it's a hash with some improvements (for one, indexable by search engines). https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history http://www.w3.org/TR/html5/history.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7539752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Add external product images to opencart I need to use externally hosted product images as the product image for the desired items. The Items are hosted on our CDN and the full URL is known. All products are imported via a csv file which also includes those url's. The problem is that after adding the product image url to both the image column of the product table and adding a row in the product_images table with this url, there still doesn't appear any product image. Is there any option that needs to be set in order to upload products with images to opencart which I forgot to implement? A: in model/comon/image.php, there should be the resize function. after declaring the function, just check to see if http:// is present at the begging of the url, if it is, dont attept to resize it. A: Did you modify the product code or just change the database? In OpenCart the images are resized by the tool/image model and the first check in the resize() function is that the file exists. Unless you've modified either the product model/view/controller and/or the tool/image model you're not going to be able to reference external images.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Trying to understand margins in LinearLayout inside a ScrollView I need to have a LinearLayout inside a SrollView and that LinearLayout must have a margin from the ScrollView. At first, the only way I could think of to solve that issue was having a LinearLayout inside another LinearLayout with the margins set on the this last layout. They wouldn't work if they were set in the outer LinearLayout. Example: <?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:fillViewport="true" android:background="@color/layout_color_green"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="@color/layout_color_yellow"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="10dp" android:orientation="vertical" android:background="@color/layout_color_blue"> </LinearLayout> </LinearLayout> </ScrollView> My question is: Why do I need to do this? If I had only one LinearLayout there would be no margins... Example: <?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:fillViewport="true" android:background="@color/layout_color_green"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="10dp" android:orientation="vertical" android:background="@color/layout_color_blue"> </LinearLayout> </ScrollView> Then, searching for some similar issue, I found a few layouts which gave me the idea of using padding in the ScrollView instead of margin in the LinearLayout. This also solves my problem and I don't need a LinearLayout inside another one. It's a more elegant solution. Still, I would like to understand why the simple margin inside the LinearLayout doesn't work when inside a ScrollView. Because it does work fine if it's not inside a ScrollView. Anyone knows why? A: I digged a little bit into the source code: ScrollView extends FrameLayout. This one has some margin issues itself and ScrollView is not even trying to solve that. The margins are basically ignored while measuaring. But in the end it doesn't matter since you should be able to define a padding on the ScrollView itself (it's an affirmation, didn't try that). There should be no need for margin for a single child view. A: Hello Knickedi and Ricardo Amaral, Though this answer is marked as solved but I want to put some lights on the issue. As Knickedi said, ScrollView extends FrameLayout. So My answer is that You can set the layout_gravity of LinearLayout within scrollView and then layout_margin will work in LinearLayout as case with linearLayout within FrameLayout. I had same issue and I've applied this and it worked for me. :) Example : <ScrollView android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="top" android:layout_marginTop="30dp" android:orientation="vertical" > </ScrollView>
{ "language": "en", "url": "https://stackoverflow.com/questions/7539755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: How do I view the parent view model MVC3 C#? I want to use two models in one view and have looked at parent view model. I have two models: public class Blogg { public int ID { get; set; } public string Blogg_name { get; set; } public string Message { get; set; } public string Blogg_subject { get; set; } private DateTime _Blogg_date = DateTime.Now; public DateTime Blogg_date { get { return _Blogg_date; } set { _Blogg_date = value; } } } And public class Dish { public int ID { get; set; } public string Title { get; set; } public string MainIngredient { get; set; } public string Cooking { get; set; } public string Drink { get; set; } public string Ingredient { get; set; } public string Type { get; set; } } This is my parent view model: public class DishBlogg { public Blogg Blogging { get; set; } public Dish Dishing { get; set; } } How do I show the result in my view (Home/index.cshtml)? This is not working: @model IEnumerable<XXXXXX.Models.DishBlogg> @foreach (var item in Model) { @Html.DisplayFor(modelItem => item.Blogging.Blogg_date) @Html.DisplayFor(modelItem => item.Blogging.Blogg_subject) @Html.DisplayFor(modelItem => item.Blogging.Blogg_name) @Html.DisplayFor(modelItem => item.Blogging.Message) } I can show one model with this (of course): @model IEnumerable<XXXXXX.Models.Blogg> @foreach (var item in Model) { @Html.DisplayFor(modelItem => item.Blogg_date) @Html.DisplayFor(modelItem => item.Blogg_subject) @Html.DisplayFor(modelItem => item.Blogg_name) @Html.DisplayFor(modelItem => item.Message) } But how do I show both (with DishBlogg)? I get this error: The model item passed into the dictionary is of type 'System.Data.Entity.Infrastructure.DbQuery1[XXXX.Models.Blogg]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[XXXX.Models.DishBlogg]' Edit: Here is the Index of HomeController where I pick out the last post from the database. I want to do the same with the dish and present both at the same view public ActionResult Index() { var lastblogg = db.Bloggs.OrderByDescending(o => o.ID).Take(1); return View(lastblogg); } A: You need to adapt your view model: public class DishBlogg { public IEnumerable<Blogg> Blogging { get; set; } public IEnumerable<Dish> Dishing { get; set; } } and then try adding a .ToList() call to eagerly execute the queries in the controller: public ActionResult Index() { var model = new DishBlogg { Blogging = db.Bloggs.OrderByDescending(o => o.ID).Take(1).ToList(), Dishing = db.Dishes.OrderByDescending(o => o.ID).Take(1).ToList(), } return View(model); } and then in your view: @model XXXXXX.Models.DishBlogg @foreach (var blog in Model.Blogging) { ... } @foreach (var blog in Model.Dishing) { ... } A: I think your problem is rather clear. Your model is a DishBlog but you are passing a Blogg Try this: public ActionResult Index() { var lastblogg = db.Bloggs.OrderByDescending(o => o.ID).Take(1).FirstOrDefault(); var list = new List<DishBlogg>(); list.Add(new DishBlogg(){Blog = lastblog}); return View(list); } A: if you want to pass the viewmodel "DishBlogg" to your view , you need to remove the IEnumerable from the model declaration in your view In your view you are using @model IEnumerable<XXXXXX.Models.DishBlogg> which indicates that the model expected by the View is of type IEnumerable of DishBlogg. However in the controller you are passing an object of type DishBlogg as a model return View(viewModel); hence the error. Either change the view to have @model XXXXXX.Models.DishBlogg or change your view model to return a list and pass a IEnumerable of DishBlogg as model to the view in controller so instead of this @model IEnumerable<XXXXXX.Models.DishBlogg> use this @model <XXXXXX.Models.DishBlogg> change your viewmodel class to this public class DishBlogg(Blogg blogg, Dish dish) { this.LastBlogg = blogg; this.LastDish = dish; } public Blogg LastBlogg { get; private set; } public Dish LastDish { get; private set; } Fill and pass the view model to your view public ActionResult Index() { var lastblogg = db.Bloggs.OrderByDescending(o => o.ID).Take(1); var lastdish = db.Bloggs.OrderByDescending(o => o.ID).Take(1); var viewModel = new DishBlogg(lastblogg , lastdish ); return View("Index", viewModel); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7539757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Interchange data between TabActivity and its sub-Activities. Possible? I have a list of locations saved in the TabActivity. The TabActivity has 2 sub-activities: a map and a list. So i want to get the location-list to the sub-activities to show them there. I know that i can commit some data with the intent, but i always want to commit the data to the current showing sub-activity if the list changes. Is there a possiblity to do this? For further details, please ask me. Thanks a lot, joe A: Yes it is possible, You can have access to the sub activities of TabActivity. You can get the current active Activity like this way: say you have a Button(typically other than TabIndicators) somewhere in TabActivity which call doSomeAction() in its onClick() to refresh or change your Sub-Activity contents. You will do it this way: //this method is in TabActivity public void doSomeAction(View button) { Activity currentAct = this.getLocalActivityManager().getCurrentActivity(); int index = getTabHost().getCurrentTab(); if(index == 0) { MyListAct listAct = (MyListAct)currentAct; //MyListAct or any other Sub Activity listAct.refreshList(); // refreshList() may be a method to refresh Activity } //else you can check for the other Activity } A: I would suggest to create a static global data container and commit your changes into that object (you could clear and setup it with the aid of the main activity life cycle). But make sure you don't leak any heavy resources, especially a context reference.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What's the expression equivalent of the Assignment statement called? In imperative programming, using statements, you do stuff like: a = 10 b = a * 2 print a # 20 I have been thinking that the equivalent, in expressions, should be something like this: print with(a=10){with(b=a*2){return b}} This being written in butchered python, but it shouldn't matter, it should illustrate what i mean. Rather than changing the state of the variable in the program (which then remains changed forever), it changes it in the block scope, for any expressions within that scope. There probably is a name for this sort of thing. I don't know any pure-functional languages, but I imagine this sort of thing would be rather very useful for calculating temporary values when assignment-statements don't exist. Does anyone know what it's called, what languages have this inbuilt, and where I can find more information about it? A: Well, there are let-bindings: let a = 10 in let b = a * 2 in b Those are present in most functional languages, although sometimes with different syntax (the most obvious deviant I know of being lisp, which uses (let ((a 10)) (let ((b (* a 2))) b)); there's also letrec and let* which place different restrictions on what the expressions being assigned can refer to). One can also create multiple bindings in a single let. Note that formally, it doesn't change the variable for a brief period of time but introduces a new scope, with new variables.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Porting existing console application to Windows Azure I have some console applications that communicate using WCF over TCP. Is it possible/easy to port a console application to Windows Azure, or must the application be hosted in IIS/asp .net? A: Since you do not really log into a Windows Azure machine and see the screen as you could do with a local server in your network I guess you should only develop server side components or IIS Hosted services and web applications exactly as you said. you could get the Windows Azure SDK: Windows Azure SDK and explorer the available templates and alternatives locally in your machine. A: A console application can be started from a role - web or worker - and communication to that app can be via the InputEndpoint (HTTP, HTTPS or TCP). I worked on a project that spawned a console app from a worker role, the role fed workloads read from storage queues direct to a WCF service hosted in the console application - using tcp. A: I found that you can use startup tasks in the config file for Azure. That works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I am having abc.mdf database in D drive and i want to use in my website using web.config? I am having abc.mdf database in D drive and i want to use in my website and i have tried as in web.config and i got following error An attempt to attach an auto-named database for file D:\abc.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share. I am sure database doesn't exists anywhere else.Please help A: Please make sure "vik.mdf" file is not already placed in MSSQL Data folder (C:\Program Files (x86)\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA) or database is not already attached in Microsoft SQL server Management Studio. A: When you report that "If I am using User Instance=true with above it raises error... The user instance login flag is not supported on this version of SQL Server" it sounds like you aren't using SQLEXPRESS. Only SQLEXPRESS supports user instances.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What does it mean "add a Copy Files phase" to add a Framework to a project I'm reading this answer about adding a plugin into xCode 3 Hi, I did a few things to correct (I do not know which steps solved the problem) 1) downloaded a fresh copy 2) linked link against the framework 3) added a copy phase to include the framework into the application What does "copy phase" mean ? I've solved by adding the framework to the MAC OSX Library, but I would like to add it to my project instead. I've been told how to add it in xCode4, but how to add it to xCode3 ? A: You get to it from here You want the copy files. If you want to see an example of it - have a look at this example Xcode Project on GitHub which has a Copy Files phase to copy a Framework - and also some explanation in the Readme.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP XML DOM getElementById I need to pick one tag from xml file and insert another tag before this tag. I'm doing this with method insertBefore in DOM, but the problem is, that if I want pick the tag before I want to add the another tag by method getElementById, it doesn't work. It writes "using non-object". This is how the tag looks: <item id="Flow_0" href="Flow_0.html" media-type="application/xhtml+xml"/> Somewhere I read that it must look like this, but I can't edit all files: <item xml:id="Flow_0" href="Flow_0.html" media-type="application/xhtml+xml"/> Have you got any idea how to do that? A: A common workaround is to use XPath to get the element. $item = $xpath->query('//item[@id="Flow_0"]')->item(0);
{ "language": "en", "url": "https://stackoverflow.com/questions/7539779", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: XAML Binding to the opposite of another element I am developing a simple exercise and want to know if there is a way to bind to the opposite of another element using only XAML. For example. I have two buttons on a form, Start and Stop perhaps for a timer. I dont want both to be enables at the same time. When the program starts, the stop button should be disabled. When the start button is clicked, it should be disabled and the stop button enabled. Then vice versa until the user quits. I know there are better controls for exactly this, and I know it is easy to do in code. I just wanted to know if there is some sort of NOT operator in XAML that could look like this: <Button Content="_Start" Name="btnStart"/> <Button Content="_Stop" Name="btnStop" IsEnabled="{Binding ElementName=btnStart, Path=Not(IsEnabled)}"/> Or something like: Path != IsEnabled}"/> Or even something like: Path=IsEnabled.Not()}"/> I know I can bind directly to the start button, but when one is enabled so is the other, and likewise when it is disabled. See where I am comming from. I would be even willing to entertain some sort of XAML Validation thehnique which will first check the state of the start button and force the state of the stop one to be the opposite. Or any other similar hacks or workarounds that dont require codebehind. Thanks for any help on this. EDITS: Remember the key point for this is NO code behind. If I have to write a single line of code behind I might as well just use the onclick event handler and a simple ?: operator. So I want only something that will work directly in XAML. A: If i know it right then you can't bind to !Property, but you can Write a IValueConverter and use it in your binding. And here it is explained in detail how you can set up an IValueConverter which returns a Negated Boolean value. IValueConverter to negate a property A: There isn't a Not operation out of the box. However, it's pretty easy to achieve this yourself using a custom converter: public class NotConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return !(bool) value; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return !(bool)value; } } Then you can specify it as a converter on your binding. <Button Content="_Stop" Name="btnStop" IsEnabled="{Binding ElementName=btnStart, Converter={StaticResource NotConverter} Path=IsEnabled}"/> And finally create a resource on your Window / Page called NotConverter: <Window.Resources> <ns:NotConverter x:Key="NotConverter" /> </Window.Resources> You can get a more information about IValueConverter from MSDN. Then use can use this value converter anywhere you'd like. You could pull it out of the Window resources and make it a application-level resource so you don't have to specify it in every window.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539797", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: MySQL optimization - prevent subqueries Is it possible for me to change this query so I can do like COUNT(WHERE type_id = 2) AS success, COUNT(WHERE type_id = 1) AS error to prevent using subqueries? SELECT (SELECT COUNT(id) FROM log AS success_log WHERE type_id = 2 AND site_id = site.id AND DAYOFYEAR(success_log.created)) AS success, (SELECT COUNT(id) FROM log AS success_log WHERE type_id = 1 AND site_id = site.id AND DAYOFYEAR(success_log.created)) AS error, (SELECT COUNT(id) FROM log AS success_log WHERE site_id = site.id AND DAYOFYEAR(success_log.created)) AS total, DATE_FORMAT(log.created, "%m-%d-%y") AS `day` FROM log WHERE site_id = ? GROUP BY DAYOFYEAR(created)` A: You can use single count with GroupBy TypeId and insert them in the temp table and then select the way you want it. A: since they were all querying from the log table for the same site, you can just run through the table ONCE and just apply and IMMEDIATE IF() test inside a sum.... If the record is of a given type, count as 1, otherwise 0... Gets a sum of each of type 1 or type 2 and simple count(*) gets the overall count for the day in question. SELECT DATE_FORMAT(log.created, "%m-%d-%y") AS `day`, sum( if( type_id = 2, 1, 0 )) as NumberSuccess, sum( if( type_id = 1, 1, 0 )) as NumberError, count(*) as TotalRecords from log where site_id = ? group by DAYOFYEAR(created)
{ "language": "en", "url": "https://stackoverflow.com/questions/7539800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Open Graph Beta: Adding units to actions or objects for publish_action? I've been reviewing the Open Graph Beta docs, and I'm interested in how to add measurement units to action or object properties. The classic example is "User Ran a Route". Is there a way I can say that Route is '5 km' and '3.1 miles'? Further, I'd like to choose the right property to aggregate as one big number for the user. User A may work in 'miles' and User B may work in 'km'. Ideas? A: We don't have locale aware units for the Open Graph. Even on Facebook we don't change status updates from "I ran 5km" to "I ran 3mi". The best I can recommend is to attach two properties onto your Object. Distance and Distance (in miles). Then build 2 aggregations, one for the Distance and one for the Distance in miles. Then when a user runs a route, you only have to publish one property based on their locale and only 1 aggregation will show up. You have to be careful to be consistent for the same user otherwise they'll end up with 2 aggregations fracturing their distance. A: maybe you can use this system: if locale US: <meta property="CANVASNAME:distance" content="3.0" /> <meta property="CANVASNAME:distance:units" content="miles" /> if locale DE, FR, ...: <meta property="CANVASNAME:distance" content="5.0" /> <meta property="CANVASNAME:distance:units" content="km" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7539809", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Saving a vector as a single number? I was wondering if it would be possible to get a vector with an X and a Y value as a single number, knowing that both X and Y can range from -65000 to +65000. Is this possible in any way? Code examples on how to convert from this kind of number and to it would be nice. A: Store it in a ulong: ulong rslt = (uint)x; rslt = rslt << 32; rslt |= ((uint)y); To get it out: int x = (int)(rslt >> 32); int y = (int)(rslt & 0xFFFFFFFF); A: To combine: var limit = 65000; var x = 1; var y = 2; var single = x * (limit + 1) + y; And then: y = single % (limit + 1); x = single - y / (limit + 1); See it in action. Of course, you have to assume that the maximum value for single fits within the size of the data type that stores it (which in this case it does). A: Assuming X and Y are both integer values and there is no overflow (32bit values is not enough) you can use e.g. (pseudocode) V = fromXY(X, Y) = (y+65000)*130001+(x+65000) (X,Y) = toXY(V) = (V%130001-65000,V/130001-65000) // <= / is integer division (130001 is the number of distinct values for X or Y) A: the union does what you want very easily. See also: http://www.cplusplus.com/doc/tutorial/other_data_types/ typedef long int64; typedef int int32; union { struct { int32 a, b; }; int64 a_and_b; } stacker; int main () { stacker.a = -1000; stacker.b = 2000; cout << stacker.a << ", " << stacker.b << endl; cout << stacker.a_and_b << endl; } this will output: -1000, 2000 <-- a and b read as two int32 8594229558296 <-- a and b interprested as a single int64
{ "language": "en", "url": "https://stackoverflow.com/questions/7539810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using DwmIsCompositionEnabled (JwaDwmApi) on pre-vista causes error Been trying to use the following code in order to check if Windows Aero is enabled: function AeroEnabled: boolean; var enabled: bool; begin // Function from the JwaDwmapi unit (JEDI Windows Api Library) DwmIsCompositionEnabled(enabled); Result := enabled; end; ... if (CheckWin32Version(5,4)) and (AeroEnabled) then CampaignTabs.ColorBackground := clBlack else begin GlassFrame.Enabled := False; CampaignTabs.ColorBackground := clWhite; end; However, doing so on a pre-vista machine causes the app to crash because the DWMApi.dll is missing. I've also tried this code however it produces 2 AV's in a row. How can I do this ? I am using Delphi 2010. :) A: You've got your versions wrong. Vista/2008 server are version 6.0. Your test should be: CheckWin32Version(6,0) I believe that you are using Delphi 2010 or later in which case you should simply call the DwmCompositionEnabled function from the built-in Dwmapi unit. This organises the version check and the delayed binding for you. No need for JEDI. Edit: Text below was written before the question was edited. Probably the easiest approach is to check the Windows version. You need Win32MajorVersion>=6 (i.e. Vista or 2008 server) in order to call DwmIsCompositionEnabled. If you were binding yourself then you would call LoadLibrary with DWMApi.dll and if that succeeded you would then call GetProcAddress to bind. If that succeeded you are good. But, as I said, since you aren't handling the binding yourself then a version check is probably the simplest. So the function would be: function AeroEnabled: boolean; var enabled: bool; begin if Win32MajorVersion>=6 then begin DwmIsCompositionEnabled(enabled); Result := enabled; end else begin Result := False; end; end; Note, I'm assuming that your library is doing late binding, i.e. explicit linking. If not then you'll need LoadLibrary/GetProcAddress, exactly as is done in @RRUZ's code to which you link.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: VS2010 C++ Win32 API intellisense Is where any extension, for visual studio, to support intellisense for c++: win32api,mfc,atl whatever. Or its supported, and only i can not see it? Or any workaround or other IDE? For example: int main(){ Set } And here i want to see all available winapi functions, which starts from "Set". Is it possible? A: That type of C++ intellisense only appears after you hit ctrl+space. The commercial extension Visual Assist X gives an experience that may be more what you are looking for (note that it is not supported in express editions of Visual Studio). A: In the following snippet: #include <Windows.h> int main () { ::Set } I get all completions for Win32 API functions starting with Set. If you don't like having all those references to the global namespace, you can hit Control-Space to force intellisense to show completions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539813", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Extract set of repeated pattern from String literal in Java What would be a convenient and reliable way to extract all the "{...}" tags from a given string? (Using Java). So, to give an example: Say I have: http://www.something.com/{tag1}/path/{tag2}/else/{tag3}.html I want to get all the "{}” tags; I was thinking about using the Java .split() functions, but not sure what the correct regex would be for this. Note also: tags can be called anything, not just tagX! A: I would use regular expressions to match this. Something like this could work for your expression: String regex = "\\{.*?\\}"; As this will "reluctantly" match any sub string that has { and } surrounding it. The .*? makes it find any character between the { and }, but reluctantly, so it doesn't match the bigger String: {tag1}/path/{tag2}/else/{tag3} which would be a "greedy" match. Note that the curly braces in the regex need to be escaped with double backslashes since curly braces have a separate meaning inside a regular expression, and if you want to indicate the curly brace String, you need to escape it. e.g., public static void main(String[] args) { String test = "http://www.something.com/{tag1}/path/{tag2}/else/{tag3}.html"; String regex = "\\{.*?\\}"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(test); while (matcher.find()) { System.out.println(matcher.group()); } } With an output of: {tag1} {tag2} {tag3} You can read more about regular expressions here: Oracle Regular Expressions Tutorial and for greater detail, here: www.regular-expressions.info/tutorial
{ "language": "en", "url": "https://stackoverflow.com/questions/7539818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: I need help in iphone memory management I am developing application which is using many photos so definitely it crashes though i released the images as some part is shown in following code -(void)addScrollView{ [self selectData]; scrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(5, 0, 300, 160)]; int counter=10; float y=10.0f; int fullLength=[photoArray count]; int horizontal=(fullLength/2)*80; int vertical=160; int c1=1; for(int c=0;c<[photoArray count];c++){ PhotoData *d=[photoArray objectAtIndex:c]; //NSLog(d.photoPath); if(c==fullLength/2 &&c1<3){ counter=10; y=y+80.0f; c1++; } UIImage *img1=[[UIImage alloc]initWithContentsOfFile:d.photoPath]; UIButton* button = [[UIButton alloc] init]; [button setTitle:@"Delete" forState:UIControlStateNormal]; [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal]; button.tag=d.photoId; //set the button states you want the image to show up for [button setBackgroundImage:img1 forState:UIControlStateNormal]; [button setFrame:CGRectMake(counter, y, 70.0, 70.0)]; //create the touch event target, i am calling the 'productImagePressed' method [button addTarget:self action:@selector(deleteImage:) forControlEvents:UIControlEventTouchUpInside]; [scrollView addSubview:button]; counter=counter+80.0f; [img1 release]; [button release]; } [scrollView setContentSize:CGSizeMake(horizontal, vertical)]; [self.view addSubview:scrollView]; [scrollView release]; } Dealloc is also not called because i am using tabbased application. So please help how can solve this memory management issue. A: The only issue is what you mentioned—that you might have too many images or objects loaded. In that case, you may want to save some data to a file behind the scenes, and do fetches as needed. Maybe instead of storing all the objects in photoArray, write to a file (you could even just write the file path to a file) and batch load ten or so at a time, rather than all of them. Without more info though, there's not much more I can say.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539819", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript code reloads each page one extra time on each request About a month ago or something i encountered this behaviour on code that has been working this far. Whenever someone log-in via facebook, each page will reload extra one time. For example user loads up index.php page then after javascript code fires page reloads once more, then after that it won't. So basically when you click link or refresh current page it reloads 2 times in total (1 from natural load and another from FB javascript) The javascript code that has been giving problem i belive is: FB.Event.subscribe('auth.login', function() { window.location.reload(); }); Why this reloads on each page refresh? Before it worked perfectly only on user login 1 time. I have regular additional code in html: xmlns:fb="http://www.facebook.com/2008/fbml" xmlns:og="http://opengraphprotocol.org/schema/" And javascript include right under body: <div id="fb-root"><script src="http://connect.facebook.net/en_US/all.js"></script></div> A: Fixed - by following this post FB.Event.subscribe('auth.login', function(response) { }) issue Reference to working example - http://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/ Note: Make sure you include oauth : true in your FB.init settings.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: overwrite 0x00 into a file C #include <stdio.h> #include <string.h> #include <stdlib.h> int main(){ int size; FILE *fp; fp=fopen("prova" , "rb"); if(fp == NULL){ printf("%s",strerror(2)); return EXIT_FAILURE; } /* Controllo lunghezza file */ fseek(fp, 0, SEEK_END); size=ftell(fp); fseek(fp, 0, SEEK_SET); /* --- */ for(i=1; i<=size; i++){ qualcosa } fclose(fp); return EXIT_SUCCESS; } I want to "secure delete" a file by overwriting it with 0x00...like what /dev/zero do! How can i do it? I've opened the file, i've check his lenght...and now? A: First, you're only opening it for reading: fp=fopen("prova" , "rb"); You need: fp=fopen("prova" , "w+"); After that, you just need to write zeroes to the file until you've hit the length you've already determined using fputc() or fwrite() It occurs to me though that this really may not solve your actual problem depending on the OS. It may end up writing the file to a different area on the disk (thus leaving your original data untouched)
{ "language": "en", "url": "https://stackoverflow.com/questions/7539827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Scala: Draw table to console I need to display a table in a console. My simple solution, if you would call it a "solution", is as follows: override def toString() = { var res = "\n" var counter = 1; res += stateDb._1 + "\n" res += " +----------------------------+\n" res += " + State Table +\n" res += " +----------------------------+\n" for (entry <- stateDb._2) { res += " | " + counter + "\t | " + entry._1 + " | " + entry._2 + " |\n" counter += 1; } res += " +----------------------------+\n" res += "\n" res } We don't have to argue this * *a is looking bad when displayed *b code looks kinda messed up Actually, such a question was asked for C# but I would like to know a nice solution for Scala as well. So what is a (nice/good/simple/whatever) way to draw such a table in Scala to the console? ------------------------------------------------------------------------- | Column 1 | Column 2 | Column 3 | Column 4 | ------------------------------------------------------------------------- | | | | | | | | | | | | | | | ------------------------------------------------------------------------- A: If you want it somewhat more compact. Bonus: left aligned and padded with 1 char on both sides. Based on the answer by Duncan McGregor (https://stackoverflow.com/a/7542476/8547501): def formatTable(table: Seq[Seq[Any]]): String = { if (table.isEmpty) "" else { // Get column widths based on the maximum cell width in each column (+2 for a one character padding on each side) val colWidths = table.transpose.map(_.map(cell => if (cell == null) 0 else cell.toString.length).max + 2) // Format each row val rows = table.map(_.zip(colWidths).map { case (item, size) => (" %-" + (size - 1) + "s").format(item) } .mkString("|", "|", "|")) // Formatted separator row, used to separate the header and draw table borders val separator = colWidths.map("-" * _).mkString("+", "+", "+") // Put the table together and return (separator +: rows.head +: separator +: rows.tail :+ separator).mkString("\n") } } scala> formatTable(Seq(Seq("head1", "head2", "head3"), Seq("one", "two", "three"), Seq("four", "five", "six"))) res0: String = +-------+-------+-------+ | head1 | head2 | head3 | +-------+-------+-------+ | one | two | three | | four | five | six | +-------+-------+-------+ A: I've pulled the following from my current project: object Tabulator { def format(table: Seq[Seq[Any]]) = table match { case Seq() => "" case _ => val sizes = for (row <- table) yield (for (cell <- row) yield if (cell == null) 0 else cell.toString.length) val colSizes = for (col <- sizes.transpose) yield col.max val rows = for (row <- table) yield formatRow(row, colSizes) formatRows(rowSeparator(colSizes), rows) } def formatRows(rowSeparator: String, rows: Seq[String]): String = ( rowSeparator :: rows.head :: rowSeparator :: rows.tail.toList ::: rowSeparator :: List()).mkString("\n") def formatRow(row: Seq[Any], colSizes: Seq[Int]) = { val cells = (for ((item, size) <- row.zip(colSizes)) yield if (size == 0) "" else ("%" + size + "s").format(item)) cells.mkString("|", "|", "|") } def rowSeparator(colSizes: Seq[Int]) = colSizes map { "-" * _ } mkString("+", "+", "+") } scala> Tabulator.format(List(List("head1", "head2", "head3"), List("one", "two", "three"), List("four", "five", "six"))) res1: java.lang.String = +-----+-----+-----+ |head1|head2|head3| +-----+-----+-----+ | one| two|three| | four| five| six| +-----+-----+-----+ A: Ton of thanks for the Tabulator code! There is a modification for Spark dataset tabular printing. I mean you can print DataFrame content or pulled result set, like Tabulator(hiveContext.sql("SELECT * FROM stat")) Tabulator(hiveContext.sql("SELECT * FROM stat").take(20)) The second one will be without header of course, for DF implementation you can set how many rows to pull from Spark data frame for printing and do you need header or not. /** * Tabular representation of Spark dataset. * Usage: * 1. Import source to spark-shell: * spark-shell.cmd --master local[2] --packages com.databricks:spark-csv_2.10:1.3.0 -i /path/to/Tabulator.scala * 2. Tabulator usage: * import org.apache.spark.sql.hive.HiveContext * val hiveContext = new HiveContext(sc) * val stat = hiveContext.read.format("com.databricks.spark.csv").option("header", "true").option("inferSchema", "true").option("delimiter", "\t").load("D:\\data\\stats-belablotski.tsv") * stat.registerTempTable("stat") * Tabulator(hiveContext.sql("SELECT * FROM stat").take(20)) * Tabulator(hiveContext.sql("SELECT * FROM stat")) */ object Tabulator { def format(table: Seq[Seq[Any]], isHeaderNeeded: Boolean) : String = table match { case Seq() => "" case _ => val sizes = for (row <- table) yield (for (cell <- row) yield if (cell == null) 0 else cell.toString.length) val colSizes = for (col <- sizes.transpose) yield col.max val rows = for (row <- table) yield formatRow(row, colSizes) formatRows(rowSeparator(colSizes), rows, isHeaderNeeded) } def formatRes(table: Array[org.apache.spark.sql.Row]): String = { val res: Seq[Seq[Any]] = (for { r <- table } yield r.toSeq).toSeq format(res, false) } def formatDf(df: org.apache.spark.sql.DataFrame, n: Int = 20, isHeaderNeeded: Boolean = true): String = { val res: Seq[Seq[Any]] = (for { r <- df.take(n) } yield r.toSeq).toSeq format(List(df.schema.map(_.name).toSeq) ++ res, isHeaderNeeded) } def apply(table: Array[org.apache.spark.sql.Row]): Unit = println(formatRes(table)) /** * Print DataFrame in a formatted manner. * @param df Data frame * @param n How many row to take for tabular printing */ def apply(df: org.apache.spark.sql.DataFrame, n: Int = 20, isHeaderNeeded: Boolean = true): Unit = println(formatDf(df, n, isHeaderNeeded)) def formatRows(rowSeparator: String, rows: Seq[String], isHeaderNeeded: Boolean): String = ( rowSeparator :: (rows.head + { if (isHeaderNeeded) "\n" + rowSeparator else "" }) :: rows.tail.toList ::: rowSeparator :: List()).mkString("\n") def formatRow(row: Seq[Any], colSizes: Seq[Int]) = { val cells = (for ((item, size) <- row.zip(colSizes)) yield if (size == 0) "" else ("%" + size + "s").format(item)) cells.mkString("|", "|", "|") } def rowSeparator(colSizes: Seq[Int]) = colSizes map { "-" * _ } mkString("+", "+", "+") } A: Tokenize it. I'd start with looking at making a few case objects and classes so that you produce a tokenized list which can be operated on for display purposes: sealed trait TableTokens{ val width: Int } case class Entry(value: String) extends TableTokens{ val width = value.length } case object LineBreak extends TableTokens{ val width = 0 } case object Div extends TableTokens{ val width = 1 } So then you can form certain constraints with some sort of row object: case class Row(contents: List[TableTokens]) extends TableTokens{ val width = contents.foldLeft(0)((x,y) => x = y.width) } Then you can check for constraits and things like that in an immutable fashion. Perhaps creating methods for appending tables and alignment... case class Table(contents: List[TableTokens]) That means you could have several different variants of tables where your style is different from your structure, a la HTML and CSS. A: Here's some modifications of @Duncan McGregor answer to accept unicode's box drawing or custom characters using Scala 3. First we define a class to host the custom separators: type ColumnSep = (Char, Char, Char) case class TableSeparator(horizontal: Char, vertical: Char, upLeft: Char, upMiddle: Char, upRight: Char, middleLeft: Char, middleMiddle: Char, middleRight: Char, downLeft: Char, downMiddle: Char, downRight: Char): def separate(sep: TableSeparator => ColumnSep)(seq: Seq[Any]): String = val (a, b, c) = sep(this) seq.mkString(a.toString, b.toString, c.toString) def separateRows(posicao: TableSeparator => ColumnSep)(colSizes: Seq[Int]): String = separate(posicao)(colSizes.map(horizontal.toString * _)) def up: ColumnSep = (upLeft, upMiddle, upRight) def middle: ColumnSep = (middleLeft, middleMiddle, middleRight) def down: ColumnSep = (downLeft, downMiddle, downRight) def verticals: ColumnSep = (vertical, vertical, vertical) then we define the separators on the companion object object TableSeparator: lazy val simple = TableSeparator( '-', '|', '+', '+', '+', '+', '+', '+', '+', '+', '+' ) lazy val light = TableSeparator( '─', '│', '┌', '┬', '┐', '├', '┼', '┤', '└', '┴', '┘' ) lazy val heavy = TableSeparator( '━', '┃', '┏', '┳', '┓', '┣', '╋', '┫', '┗', '┻', '┛' ) lazy val dottedLight = TableSeparator( '┄', '┆', '┌', '┬', '┐', '├', '┼', '┤', '└', '┴', '┘' ) lazy val dottedHeavy = TableSeparator( '┅', '┇', '┏', '┳', '┓', '┣', '╋', '┫', '┗', '┻', '┛' ) lazy val double = TableSeparator( '═', '║', '╔', '╦', '╗', '╠', '╬', '╣', '╚', '╩', '╝' ) And finally the Tabulator: class Tabulator(val separators: TableSeparator): def format(table: Seq[Seq[Any]]): String = table match case Seq() => "" case _ => val sizes = for (row <- table) yield for (cell <- row) yield if cell == null then 0 else cell.toString.length val colSizes = for (col <- sizes.transpose) yield col.max val rows = for (row <- table) yield formatRow(row, colSizes) formatRows(colSizes, rows) private def centralize(text: String, width: Int): String = val space: Int = width - text.length val prefix: Int = space / 2 val suffix: Int = (space + 1) / 2 if width > text.length then " ".repeat(prefix) + text + " ".repeat(suffix) else text def formatRows(colSizes: Seq[Int], rows: Seq[String]): String = (separators.separateRows(_.up)(colSizes) :: rows.head :: separators.separateRows(_.middle)(colSizes) :: rows.tail.toList :: separators.separateRows(_.down)(colSizes) :: List()).mkString("\n") def formatRow(row: Seq[Any], colSizes: Seq[Int]): String = val cells = for (item, size) <- row zip colSizes yield if size == 0 then "" else centralize(item.toString, size) separators.separate(_.verticals)(cells) Some output examples: +---+-----+----+ | a | b | c | +---+-----+----+ |abc|true |242 | |xyz|false|1231| |ijk|true |312 | +---+-----+----+ ┌───┬─────┬────┐ │ a │ b │ c │ ├───┼─────┼────┤ │abc│true │242 │ │xyz│false│1231│ │ijk│true │312 │ └───┴─────┴────┘ ┏━━━┳━━━━━┳━━━━┓ ┃ a ┃ b ┃ c ┃ ┣━━━╋━━━━━╋━━━━┫ ┃abc┃true ┃242 ┃ ┃xyz┃false┃1231┃ ┃ijk┃true ┃312 ┃ ┗━━━┻━━━━━┻━━━━┛ ╔═══╦═════╦════╗ ║ a ║ b ║ c ║ ╠═══╬═════╬════╣ ║abc║true ║242 ║ ║xyz║false║1231║ ║ijk║true ║312 ║ ╚═══╩═════╩════╝
{ "language": "en", "url": "https://stackoverflow.com/questions/7539831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: How to load Underscore library with RequireJS? require(['underscore'], function ($, _) { ... }); Doesnt work! (_ is not a function) How to manage it? A: Note that underscore.js doesn't register itself as an AMD module (though it did for a brief time in earlier versions), thus it can't be used in a require() call without some configuration using "shim:" like so: require.config({ paths: { jquery: 'lib/jquery.min', underscore: 'lib/underscore-min' } shim: { "underscore": { exports: "_" } } }); See the docs at: http://requirejs.org/docs/api.html#config-shim Before shim: was added to require.js, you could do something similar with the plugin use.js (in case you need to use an older version of require.js). As of this writing, the current version of require.js is 2.1.8. Alternatively, you can use lodash.js as a drop-in replacement for underscore.js - it does register itself as an AMD module, so you can use it with no extra config: http://lodash.com/ A: I think the problem is the order of args passed in to your callback. Should be: require(['underscore'], function (_, $) { ... }); Also you need to be using underscore version 1.2.1 which added this functionality. A: require(["underscore"], function() { console.log(_ === window._); }); A: it all depends where the script is based. since i don't see you specified a baseUrl, the baseUrl will be the default, that means, either 2 things: * *your script is directly inside a html file, and in your case it will thus look for underscore.js in the same directory of the html file *your script is in a javascript file referenced by your html file, it will now search for underscore.js in the directory of your custom javascript file. check if the underscore.js is actually there. A: Here are the checkpoints for you to make sure what you need works * *Get require-jquery.js and put it to your /js-root dir *Add to your HTML, right before the closing </body> tag: <script data-main="/js-root/main-js-file-name" src="/js-root/require-jquery.js"></script> *Get underscore adapted for AMD, and put it to /js-root dir as well *In main-js-file-name.js write: require(["jquery", "underscore"], function ($, _) { ... }); Similarly, in your non-main AMD JS files, when defining a module, to use _, write: define(["jquery", "underscore"], function ($, _) { ... return theModuleObjectOrFunction; });
{ "language": "en", "url": "https://stackoverflow.com/questions/7539836", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Why the model can not be added to collection in BackboneJS window.NCollection = Backbone.Collection.extend({ url: '/api/all', model: N, parse: function(data){ var that = this; _.each(data, function(item){ switch(item.cat){ case 't1': console.log(new Note(item)); that.add(new Type1(item)); break; case 't2': that.add(new Type2(item)); break; default: that.add(new T(item)); } }); }, nextOrder: function() { if (!this.length) return 1; return this.last().get('id') + 1; }, }); I fetch the data of the collection when the page loading. But the collection length also be 0. A: And my own question, the return should be added. parse : function(data) { ............. return data; },
{ "language": "en", "url": "https://stackoverflow.com/questions/7539839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use resources from ResourceManager in WPF binding Is there any good tutorial on how to use ResourceManager in WPF binding ? I know how to use it with the GetString function to retrieve a specific resource, but I also would like to use in in binding. something like <TextBlock Text="{Binding Resource.EnterName}"/> thanks A: A binding would not do much except getting the value once as the resources do not provide any notifications as far as i know. You can get the values using x:Static, e.g.: <TextBlock xmlns:prop="clr-namespace:AppAssemblyName.Properties" Text="{x:Static prop:Resources.ResourceName}"/> (The resource's accessors need to be set to public)
{ "language": "en", "url": "https://stackoverflow.com/questions/7539844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is it possible to access java class libraries from a python program in Google App Engine? I am using Python in Google App Engine and I have a Java class library that I want to use in my program... Is there a way to import that library and use it in a python program? I have searched the net and found something like this: from jpype import * import re import string startJVM("/opt/sun-jre/lib/i386/client/libjvm.so", "-Djava.class.path=/home/talat/zemberek-0.6.4.jar", "-ea") zerisim = JPackage('net').zemberek.erisim.Zemberek But I am not sure whether "jpype" can be used in Google App Engine... Thank you, A: If the java functionality is critical to your application and not easy to rewrite in python, then you could write a simple web app in java that uses the library, and run that on appengine as a separate version than your main python app. You could then call the java app from the python app using HTTP. This is not an elegant solution, but if you really need the functionality, it should get the job done. The key here is that app engine will let you run more than one "version" of your app at a time, including different runtimes. A: There is no way at present on App Engine to import or otherwise access Java libraries from Python. Jython might be an approach worth trying (using the Java GAE SDK), though I'm not aware of anyone having gone that route before.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery position element based on window resize If you look at this page: http://dev.driz.co.uk/tips/ I'm doing some experimentation to learn more about jQuery and how to develop things similar to what we've seen on Facebook. You will see I have a tooltip that is positioned relative to the redbox. However if you resize the window it doesn't adjust the tip in relation to it. How do I fix this? Also considering that the element is quite tall if the user resizes the window height then I would want the tip to move upwards so it appears within the screen viewport in other words always having about 20px away from the bottom of the page BUT keeping the arrow in the same place it is now so it's only the box that adjusts itself. Can anyone help me to achieve those two things? Much appreciated. Thanks A: you'll need to calculate the position in the window resize event: $(window).resize(function() { // your positioning code here }); $(document).ready(function() { calculation(); $(window).resize(calculation); function calculation() { var location = $("#link").offset(); var top = location.top; var left = location.left; left = left - $('#tip').width(); left = left - 15; $("#tip").css({ 'position': 'absolute', 'top': top + 'px', 'left': left + 'px' }); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7539856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Reflections on C++ Variadic Templated Versions of std::min() and std::max() I need reflections on my implementations of the C++11 variadic versions of std::min, std::max. Here are my two alternatives for std::min, where std::max is implemented analogously by just replacing std::min with std::max: /*! Multi-Type Minimum of \p a. */ template <LessThanComparable T> const T & multi_type_min (const T & a) { return a; } // template termination /*! Multi-Type Minimum of \p a and \p args. */ template <class T, class ... R > //requires SameType <T , Args >... T multi_type_min(const T & a, const R &... b) { return std::min(a, multi_type_min(b...)); } /*! Minimum of \p a. */ template <LessThanComparable T> const T & common_type_min(const T & a) { return a; } // template termination /*! Minimum of \p a and \p args. */ template <class T, class ... R, class C = typename boost::common_type<T, R...>::type > C common_type_min(const T & a, const R &... b) { return std::min(static_cast<C>(a), static_cast<C>(common_type_min(b...))); } The key question is if we need common_type_min at all? Note that this allows min() to be called with one arguments. Could this cause confusions or problems? A: Can't you just write it such that it recurses until you stop at two parameters? Here's a (untested) snippet: /*! Multi-Type Minimum of \p a and \p args. */ template <class T, class U > //requires SameType <T , U >... T multi_type_min(const T & a, const U & b) { return std::min(a, b); } /*! Multi-Type Minimum of \p a and \p args. */ template <class T, class U, class ... R > //requires SameType <T , U, Args >... T multi_type_min(const T & a, const U & b, const R &... c) { return std::min(a, multi_type_min(b, c...)); } I'm guessing the common_type_min variant is necessary when there are multiple common types. Consider comparing short and long values. Because of type promotion, the short will be converted to long for comparison. However, some application constraint or invariant might let you know that both values can be represented by a short. In this case, you may want to have common_type_min<short>(a,b).
{ "language": "en", "url": "https://stackoverflow.com/questions/7539857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Identifying the name of a class during run time So I have run into a fairly complex problem with my application. I have about 40 UIImageView objects that need to be displayed at different locations when different ones are stacked (EX img 1 needs to take img 2 place if img2 ==NO). What I am trying to do is use a "for loop" and run through all my Boolean values that check if the image is selected. I was curious if it is at all possible to call variable like this -(IBAction) button:(id) sender{ scrollView.hidden = YES; NSInteger i = 1; (@"imagenumber%d", i) = [[UIImageView alloc] initWithFrame: CGRectMake (28, 230, 86, 26)]; [[imagenumber(@"%d", i)] setImage:[UIImage imageNamed:@"csa.jpg"]]; [self.view addSubview: [imagenumber(@"%d", i)]];} } where @"imagenumber%d" is my NSImageView and i is a number ranging from 1-40. I'm sorry if this is confusing, I really would appreciate any help at all on the subject because I can’t seem to get any idea and have been working on this problem for several weeks. A: Put the views in a NSMutableArray - you can access elements in those by index, use fast enumeration, ... E.g.: UIImageView *image = [[UIImageView alloc] ... [myMutableArray addObject:image]; // ... A: For the sake of hilarity you could also put them in a intrinsic array and use pointer arithmetic. (Which is probably what happens behind the scenes with faster enumeration for those interested) UIImageView * imageArray[40]; ... for(UIImageView * this = imageArray; this; this++) { this = [[UIImageView alloc] initWithFrame: CGRectMake (28, 230, 86, 26)]; ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7539858", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: graph component in GTK/Qt (like in blueJ) I'm about to make a program (qt/gtk) where I need to display some kind of UML diagrams (like in BlueJ), I wanted to ask you if there is such a component in GTK It must work with new version of Gtk - gi.repository The name of library is enough for me, I'll read docs, but if somebody post here some simple demo, it'll be appreciated. Thank you A: Dia (Old homepage) is a GTK based UML drawing tool. It is a very good tool with a lot of options. It is available on a number distros from their repositories. It has both application & library (libdia) components. There are python bindings available as well. If you have not checked it out, you should. Hope this helps! A: I found gaphas A: You should checkout GooCanvas, I think is the more complete library for that kind of work. A: I use python and pygtk, and use matplotlib to draw graphs in the GUI. See a sample here : http://www.serpia.org/blog/2007/nov/03/matplotlib-and-pygtk-app/
{ "language": "en", "url": "https://stackoverflow.com/questions/7539867", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to add new TextView with new data in cycle? How to add new TextView with new data(name), from Data Base? And add to tableRow in TableLayout? My table: _id name 1 Said 2 Bill etc Cursor cursor = database.query(TABLE_NAME, new String[] {STUDENT_NAME}, null, null,null,null,null); cursor.moveToFirst(); String text = cursor.getString(0); TextView name1 = (TextView) findViewById(R.id.edit); name1.setText(text); cursor.close(); A: If you want do add TextViews dynamically: ViewGroup group = (ViewGroup) findViewById(R.id.group_you_want_to_add_to); try { if (!cursor.moveToFirst()) { return; } do { TextView textView = new TextView(this); textView.setText(cursor.getString(0)); group.addView(textView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); } while (cursor.moveToNext()); } finally { cursor.close(); } If you want to create a TableRow, you'd better define it in an XML file and inflate it on every iteration: LayoutInflater inflater = LayoutInflater.from(this); // then you query a database and obtain a cursor... try { if (!cursor.moveToFirst()) { return; } do { TableRow row = inflater.inflate(R.id_table_row, table, null); ((TextView) row.findViewById(R.id.text)).setText(cursor.getString(0)); table.addView(row); } while (cursor.moveToNext()); } finally { cursor.close(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7539874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Play video from a byte array I am using visual basic .NET and I want to play a video from a byte array that I have, but without saving it first at the disk. Directly from that array. I tried the directshow lib for a while but didn't managed to find a way to play it. WMP didn't worked either. Any ideas? A: There is no stock component to stream from memory, however the task has more or less good generic solution. A number of files/formats are playable starting from so called File Source (Async) Filter, which is a generic file/data accessor. If you could provide a similar/compatible source filter which streams from memory, it would wokd great and cover a number of formats at a time. Provided that you are going to have hard time doing it in VB.NET, and in managed code in general, you will perhaps need a third party solution for this. So you might eventually end up with a much easier workaround to save data into temporary file and play it from there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: I see the error but the account is valid SQL> CREATE or REPLACE FUNCTION custord (custNo IN number) 2 RETURN NUMBER 3 IS cust_tot NUMBER(11,2); 4 BEGIN 5 SELECT sum(cust_total_field) 6 INTO cust_tot 7 FROM ord 8 WHERE cust_number_field=custNo; 9 RETURN(cust_tot); 10 END; 11 / Warning: Function created with compilation errors. SQL> begin 2 dbms_output.put_line('customer 102 total is ' || custord(102)); 3 end; 4 / dbms_output.put_line('customer 102 total is ' || custord(102)); * ERROR at line 2: ORA-06550: line 2, column 52: PLS-00905: object CIS605.CUSTORD is invalid ORA-06550: line 2, column 3: PL/SQL: Statement ignored SQL> I see the error but object cis605 is valid. Any ideas what I am missing? Using the ORD table create a stored function called custord that will use a customer id (CUSTID) that will return the sum of the specified customer id TOTAL field. When your function has been stored run the following SQL: begin dbms_output.put_line('customer 102 total is ' || custord(102)); end; Your output should look like: Results Explain Describe Saved SQL History customer 102 total is 27775.5 Statement processed. A: Try SHOW ERRORS FUNCTION custord Your custord function was created with compilation errors, so there is something wrong with it. This is why you're getting the object CIS605.CUSTORD is invalid error.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539879", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android KeyboardView throws Nullpointer I want to make my own keyboard. I have the following code When I ran the code, it throws NullPointerException. My RKeyboardView that extends KeyboardView package com.glenn.droid; // MY package import android.content.Context; import android.inputmethodservice.KeyboardView; import android.util.AttributeSet; public class RKeyboardView extends KeyboardView { public RKeyboardView(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub } } My main activity MobileActivity.java public class MobileActivity extends ListActivity { private RKeyboardView r; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); r = (RKeyboardView) findViewById(R.id.rKeyboardView1); r.setKeyboard(new Keyboard(this,R.xml.qwerty)); setContentView(R.layout.main); } } What should I do? Please help me. A: Move the line setContentView(R.layout.main); to directly after super.onCreate(savedInstanceState); The findViewById() method searches the tree of Views (the View hierarchy) in your activity for one with the specified id, and returns that View object. If you have not called setContentView before you call findViewById(), then the particular View object has neither been created nor added to the View hierarchy.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Protect ASP.MVC controller action using OAUTH I need to protect MVC action methods via OAUTH. Ultimately, I think I need to create two action filters - one to parse the OAUTH data and another to send back data with appropriate headers. Unfortunately, I can't find any example of this. Does anyone have pointers or samples they can provide which can get me started? EDIT - I've already looked at DotNetOpenAuth and the sample they have is for WCF and seems rather complex for this need. I found https://github.com/bittercoder/DevDefined.OAuth and it does seem promising. Hopefully, others have found additional userful resources.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: HTML Coloring Help? I really need help :) I have to put multiple words in a line, each with a different color, I tried wrapping each word in a <div> </div> and styling, but it seems it makes a new line between words. A: Try using <span>. <div>s are used for block-level elements. <span> is used for inline elements, such as text enclosed in a <p> element. Further reading: Span and div A: That's because <div> is a block element. Try <span> (an inline element) instead. A: Use a Span tag instead, like This <span style="color:red;">text</span> is red, but <span style="color:blue;">THIS</span> text is blue! A: Use <span> </span> It is what it is mean to. Then you can set css classes. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html> <head> <title>My web</title> <style type="text/css"> yellow { color: yellow; } </style> </head> <body> Span is not at the <span class="yellow">yellow level</span>. </body> </html> A: <div> is a block-level element. This means you either need to apply a display: inline style to it or better yet, use an inline tag such as <span> A: use <span>Text Here</span> And style it in your css.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Static files are being processed by Windsor and throwing errors if not found I just noticed that static files are being processed (I guess that is normal) but the problem is if a file doesn't exist it seems to be causing an exception here: public class WindsorControllerFactory : DefaultControllerFactory { private readonly IKernel _kernel; public WindsorControllerFactory(IKernel kernel) { this._kernel = kernel; } public override void ReleaseController(IController controller) { _kernel.ReleaseComponent(controller); } protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { if (controllerType == null) { throw new HttpException(404, string.Format("The controller for path '{0}' could not be found.", requestContext.HttpContext.Request.Path)); } return (IController)_kernel.Resolve(controllerType); } } Specifically the GetControllerInstance. Does this make sense? Should I put extra checks in there to make sure it is a class being processed? The error: The controller for path '/Assets/img/logo.png' could not be found. A: You may try excluding static files from being processed by ASP.NET MVC engine to improve performance. A: If controllerType is null, pass it to the base class or return null public class WindsorControllerFactory : DefaultControllerFactory { private readonly IKernel _kernel; public WindsorControllerFactory(IKernel kernel) { this._kernel = kernel; } public override void ReleaseController(IController controller) { _kernel.ReleaseComponent(controller); } protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { if (controllerType == null) return base.GetControllerInstance(requestContext, controllerType); return (IController)_kernel.Resolve(controllerType); } } Ninjet sample: https://github.com/ninject/ninject.web.mvc/blob/master/mvc2/src/Ninject.Web.Mvc/NinjectControllerFactory.cs
{ "language": "en", "url": "https://stackoverflow.com/questions/7539908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: what are the possible UDP data transfer errors? we're going to develop a game with internet multiplayer support. since it's an interactive game I know I have to use UDP to reduce connection latency, but I'm wondering what are the possible errors that may occur in a package delivered using UDP connection? everywhere I looked they say UDP provides "Best effort delivery", but no one does give a complete explanation what does it mean. after reading some article there are two questions that I still have: * *Is it possible to send a package and receive part of it at the other end of connection? *if your answer to first quesiton is true what would happen to the next packages? should I wait for the rest of package or can I assume next package start with my next recv call? for our game I think we will need to send 4 packages of around 20 byte each second. A: The most common thing that can happen is: one side sends a message, the other receives nothing. Is it possible to send a package and receive part of it at the other end of connection? Not really, not even when the message is huge and it gets fragmented. Unlike in TCP, in UDP every message is independent. You either get it entirely or nothing at all. So what you should do it just recvfrom things in a loop and process them. Obviously you should make your application impervious to message loss such that a missing message doesn't crash it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539916", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Incorrect values from GetProcessHandleCount I faced with strange behavior of function GetProcessHandleCount(). At first I take a snapshot of all processes in the system as it is described in msdn: HANDLE hProcessSnap; HANDLE hProcess; PROCESSENTRY32 pe32; hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ); pe32.dwSize = sizeof( PROCESSENTRY32 ); if( !Process32First( hProcessSnap, &pe32 ) ) { CloseHandle( hProcessSnap ); return 0; } Then I walk the snapshot of processes, and count up open handles by using function GetProcessHandleCount: int count_of_handles=0; DWORD dwHandleCount=0; do { hProcess = OpenProcess( PROCESS_QUERY_INFORMATION,FALSE,pe32.th32ProcessID); GetProcessHandleCount(hProcess,&dwHandleCount); count_of_handles+=dwHandleCount; if( hProcess != NULL ) CloseHandle( hProcess ); } while( Process32Next( hProcessSnap, &pe32 ) ); I checked this program in Windows 7 x64. Program displayed count_of_handles ~16000, but really this value was ~100 000 (if believe in Windows Task Manager). Then I executed this program in Windows XP x32 (by VMWare), and count_of_handles was ~9000 (but in real it was ~8000). What is wrong with my code? Thank you. A: For one thing, GetProcessHandleCount might return zero (which signifies an error). This could explain coming to a result lower than what you expect. This might be caused in turn by OpenProcess failing (you don't check for that either). A: As well as Jon's reason, the value from Task Manager1 includes handles open in the kernel – these will not be included in your total across processes. 1 For this kind of thing Process Explorer is far more effective. Including being able to list open handles per process and in the kernel, the system pseudo-process in Process Explorer's listing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jquery bind stoppropagation callback context I am trying to prevent multiple events firing. I'm using a callback function to pass an object, like this: function init() { var myObj = this.someObject; $('#id').bind("blur keyup change", function (e, obj) { return function () { SomeFunction(e, obj); } } (this, myObj)); } function SomeFunction(e, obj) { e.stopPropagation(); //do something with the object } The error is that it can't find the function stopPropagation. This is because I am assigning 'this' to e in the calling function. How can I get access to the 'event' in SomeFunction? A: I think you'll want to do something like this: http://jsfiddle.net/W47Ky/
{ "language": "en", "url": "https://stackoverflow.com/questions/7539918", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Spring 3.x configuration for multiple login pages I'm using Spring 3.1 for authentication purpose. My requirement: * *Two different login pages. One for Customer and other for Employee. *Each after successful authentication, will be forwarded to respective successful URL. My spring security configuration: <sec:http pattern="/resources/**" security="none" /> <sec:http auto-config="true"> <sec:intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" /> <sec:intercept-url pattern="/customer/**" access="ROLE_CUSTOMER" /> <sec:intercept-url pattern="/employee/**" access="ROLE_EMPLOYEE" /> </sec:http> <bean id="springSecurityFilterChain" class="org.springframework.security.web.FilterChainProxy"> <sec:filter-chain-map path-type="ant"> <sec:filter-chain pattern="/**" filters="authenticationProcessingFilterForCustomer,authenticationProcessingFilterForEmployee" /> </sec:filter-chain-map> </bean> <bean id="authenticationProcessingFilterForCustomer" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter"> <property name="authenticationManager" ref="authenticationManagerForCustomer" /> <property name="filterProcessesUrl" value="/j_spring_security_check_for_customer" /> <property name="authenticationSuccessHandler" ref="customerSuccessHandler" /> <property name="authenticationFailureHandler" ref="customerFailureHandler" /> </bean> <bean id="customerSuccessHandler" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler"> <property name="defaultTargetUrl" value="/customer/index.html" /> </bean> <bean id="customerFailureHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"> <property name="defaultFailureUrl" value="/customer.html?login_error=1" /> </bean> <bean id="authenticationManagerForCustomer" class="org.springframework.security.authentication.ProviderManager"> <property name="providers"> <list> <ref bean="customCustomerAuthenticationProvider" /> </list> </property> </bean> <bean id="customCustomerAuthenticationProvider" class="com.edu.CustomerCustomAuthenticationProvider"> <property name="userDetailsService"> <bean class="com.edu.CustomerUserDetailsService" /> </property> </bean> <bean id="authenticationProcessingFilterForEmployee" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter"> <property name="authenticationManager" ref="authenticationManagerForEmployee" /> <property name="filterProcessesUrl" value="/j_spring_security_check_for_employee" /> <property name="authenticationSuccessHandler" ref="employeeSuccessHandler" /> <property name="authenticationFailureHandler" ref="employeeFailureHandler" /> </bean> <bean id="employeeSuccessHandler" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler"> <property name="defaultTargetUrl" value="/employee/index.html" /> </bean> <bean id="employeeFailureHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"> <property name="defaultFailureUrl" value="/employee.html?login_error=1" /> </bean> <bean id="authenticationManagerForEmployee" class="org.springframework.security.authentication.ProviderManager"> <property name="providers"> <list> <ref bean="customEmployeeAuthenticationProvider" /> </list> </property> </bean> <bean id="customEmployeeAuthenticationProvider" class="com.edu.EmployeeCustomAuthenticationProvider"> <property name="userDetailsService"> <bean class="com.edu.EmployeeUserDetailsService" /> </property> </bean> <sec:authentication-manager alias="authenticationManager"> <sec:authentication-provider ref="customCustomerAuthenticationProvider" /> <sec:authentication-provider ref="customEmployeeAuthenticationProvider" /> </sec:authentication-manager> Both CustomAuthenticationProvider have implemented Support method as follows: public boolean supports(Class<? extends Object> authentication) { return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication); } After launching application, while trying to authenticate, the message displayed in login pages are: Your login attempt was not successful, try again. Reason: No AuthenticationProvider found for org.springframework.security.authentication.UsernamePasswordAuthenticationToken I'm using Spring 3.1. Any help appreciated. Thank You A: I have done similar things in grails, what you need is: * *extend UsernamePasswordAuthenticationToken, create two sub-class for employee and customer, say EmployeeUsernamePasswordAuthenticationToken and CustomerUsernamePasswordAuthenticationToken *extend UsernamePasswordAuthenticationFilter, to create different instance of EmployeeUsernamePasswordAuthenticationToken or CustomerUsernamePasswordAuthenticationToken based on current auth request *extend AuthenticationProvider for employee and custoner, create two class say EmployeeAuthenticationProvider and CustomerAuthenticationProvider, overwrite each class' supports method to support its target UsernamePasswordAuthenticationToken *you only need one authenticationManager, register both provide into it *only need one AuthenticationSuccessHandler, you can decide which url want to go in it *I also create a my own instance of AuthenticationEntryPoint to support multi entrypoint A: Beginning from Spring 3.1 you have as many configuration as you want : https://jira.springsource.org/browse/SEC-1171 A: You should point the authenticationManager ref in 'authenticationProcessingFilterForCustomer' and 'authenticationProcessingFilterForEmployee' beans to correct bean i.e. 'authenticationManager' which has providers. No need to define 'authenticationManagerForCustomer' and 'authenticationManagerForEmployee' beans.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Why do mutable and immutable ListMaps have different orders in Scala? Why does the immutable version of the ListMap store in ascending order, while mutable version stores in descending order? Here is a test that you can use if you got scalatest-1.6.1.jar and junit-4.9.jar @Test def StackoverflowQuestion() { val map = Map("A" -> 5, "B" -> 12, "C" -> 2, "D" -> 9, "E" -> 18) val sortedIMMUTABLEMap = collection.immutable.ListMap[String, Int](map.toList.sortBy[Int](_._2): _*) println("head : " + sortedIMMUTABLEMap.head._2) println("last : " + sortedIMMUTABLEMap.last._2) sortedIMMUTABLEMap.foreach(X => println(X)) assert(sortedIMMUTABLEMap.head._2 < sortedIMMUTABLEMap.last._2) val sortedMUTABLEMap = collection.mutable.ListMap[String, Int](map.toList.sortBy[Int](_._2): _*) println("head : " + sortedMUTABLEMap.head._2) println("last : " + sortedMUTABLEMap.last._2) sortedMUTABLEMap.foreach(X => println(X)) assert(sortedMUTABLEMap.head._2 > sortedMUTABLEMap.last._2) } Heres the output of the PASSING test : head : 2 last : 18 (C,2) (A,5) (D,9) (B,12) (E,18) head : 18 last : 2 (E,18) (B,12) (D,9) (A,5) (C,2) A: As I see it neither ListMap claims to be a sorted map, just a map implemented with a List. In fact I don't see anything in their contract that says anything about preserving the insertion order. Programming in Scala explains that ListMap may be of use if the early elements are more likely to be accessed, but that otherwise it has little advantage over Map. A: The symptoms can be simplified to: scala> collection.mutable.ListMap(1 -> "one", 2 -> "two").foreach(println) (2,two) (1,one) scala> collection.immutable.ListMap(1 -> "one", 2 -> "two").foreach(println) (1,one) (2,two) The "sorting" in your code is not the core of the issue, your call to ListMap is using the ListMap.apply call from the companion object that constructs a list map backed by a mutable or immutable list. The rule is that the insertion order will be preserved. The difference seems to be that mutable list is backed by an immutable list and insert happens at the front. So that's why when iterating you get LIFO behavior. I'm still looking at the immutable one but I bet the inserts are effectively at the back. Edit, I'm changing my mind: insert are probably at the front, but it seems the immutable.ListMap.iterator method decides to reverse the result with a toList.reverseIterator on the returned iterator. I think it worth bringing it in the mailing list. Could the documentation be better? Certainly. Is there pain? Not really, I don't let it happen. If the documentation is incomplete, it's wise to test the behavior or go look up at the source before picking a structure versus another one. Actually, there can be pain if the Scala team decides to change behavior at a later time and feel they can because the behavior is effectively undocumented and there is no contract. To address your use case explained in the the comment, say you've collected the string frequency count in a map (mutable or immutable): val map = Map("A" -> 5, "B" -> 12, "C" -> 2, "D" -> 9, "E" -> 18, "B" -> 5) Since you only need to sort once at the end, you can convert the tuples from the map to a seq and then sort: map.toSeq.sortBy(_._2) // Seq[(java.lang.String, Int)] = ArrayBuffer((C,2), (A,5), (B,5), (D,9), (E,18)) A: Don't build any expectations on order, it is not declared and it will vary between Scala versions. For example: import scala.collection.mutable.{ListMap => MutableListMap} MutableListMap("A" -> 5, "B" -> 12, "C" -> 2, "D" -> 9, "E" -> 18).foreach(println) On 2.9.1 gives: (E,18) (D,9) (C,2) (B,12) (A,5) but on 2.11.6 gives: (E,18) (C,2) (A,5) (B,12) (D,9)
{ "language": "en", "url": "https://stackoverflow.com/questions/7539924", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Why is my WPF suddenly rebelling? I've recently completed a fairly large (for one man) WPF project, and started coding something for fun. I was almost done with an app worthy of showing off to friends and colleagues, and I started playing with window sizes - manually resizing the window - just to see what would happen on various screens. And what happened was - my window got corrupted for certain window sizes, especially at about 100x100 range. I got very confused, and started to remove parts from XAML, my code, everything. But the problem persisted. Lastly, I created a brand new WPF project - I didn't even change the name - WpfApplication1 it's called. Surely, same artifacts appear. They are more subtle than those of the app, but still clearly visible. So, what's going on? I realize that the most obvious answer is to check my graphics card drivers, and I will try downgrading to an earlier release; but meanwhile note that my fairly large for one man-project works flawlessly, and it even uses DirectX shaders! And that I've installed the latest drivers just the week before, when I also reinstalled Windows. I'm running Windows Server 2008 R2 with all patches, and vanilla Visual Studio with SP1 - no experimental compilers, or anything. EDIT * *The problem only happens on my machine, if I compile on my machine and run on another the problem is not evident. *The XAML of the bran new project is simply: <Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> </Grid> </Window> EDIT 2 It seems that there's some kind of problem with the Latest Catalyst Driver - 11.8. Installing 11.7 fixed the issue as a workaround, as, well, expected. Mystery kinda solved, except for the why... So does anyone know why the latest catalysts cause havoc with WPF? A: Looks like this is a problem with Catalyst 11.8 - see: http://forums.amd.com/game/messageview.cfm?catid=279&threadid=154834&enterthread=y and WPF: can't resize window without horrible visual effects I notice it in VS 2010 as well as our own WPF apps. It's pretty horrible. Seems as though rolling back to Catalyst 11.7 fixes the problem. A: It is probably a hardware problem with your graphics card.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539929", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Possible to use PEAR SearchReplace to replace text within a .php file? I came across this simple pear tutorial over here: http://www.codediesel.com/php/search-replace-in-files-using-php/ include 'File/SearchReplace.php' ; $files_to_search = array("fruits.txt") ; $search_string = "apples"; $replace_string = "oranges"; $snr = new File_SearchReplace($search_string, $replace_string, $files_to_search, '', // directorie(s) to search false) ; $snr->doSearch(); echo "The number of replaces done : " . $snr->getNumOccurences(); The writer uses the fruits.txt file as an example. I would like to do a search and replace on a .php file. Basically what I am trying to achieve would be this: On a user interaction, index.php is opened, $promoChange = "%VARYINGTEXT%"; is searched for and replaced with $promoChange = "$currentYear/$currentPromotion"; The $current variables will vary, hence the need to change the words inbetween the "" only. Does anyone have any input on how this type of task could be accomplished? If anyone knows of any tutorials relating to this subject, that too would be greatly appreciated. Thank you! * *I do have everything else figured out, regarding the template and user interaction, I am just having trouble trying to work out how to accomplish this type of search and replace. I have an understand of how it should be done as I have made something similiar using visual basic. But I am starting to this that my answer for this would be perl? I hope that this is not so... Okay, my problem is partly solved with this: // Define result of Activate click if (isset($_POST['action']) and $_POST['action'] == 'Activate') { include ''.$docRoot.'/includes/pear/SearchReplace.php' ; $files = array( "$docRoot/promotions/index.php" ) ; $snr = new File_SearchReplace( '$promoChange = "";', '$promoChange = "'.$currentYear.'/'.$currentPromotion.'";', $files) ; $snr -> doSearch() ; } but how do i get it to search and replace something like $promoChange = "%VARYINGTEXT%"; It found and replaced "" with the current session values. But now that is has changed, I need it to replace and text inbetween "AND". Any ideas anyone? A: If you only need to adapt a single file, then do it manually: $src = file_get_contents($fn = "script.php"); $src = str_replace('"%VARYINGTEXT%"', '"$currentYear/$currentPromotion"', $src); file_put_contents($fn, $src); str_replace is sufficient for your case. A: Why on earth do you want to do something like that? Frameworks like PHP do exist solely on the base of not having to write a page for each different view of the same interaction. What's wrong with just including the PHP page you now want to change, and set the variables accordingly before calling it? Ontopic: I don't see why what you're doing is a problem, purely technically speaking. This can be done using PHP. But really, you shouldn't.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: f:verbatim tag stops working when inside a dataTable I posted this to the PrimeFaces user forum but I think they are too busy to look into it, so I thought I would try here. I have server-side string that has markup in it, so when I want it rendered I do this: <p:panel> <f:verbatim> #{daBean.markedUpString} </f:verbatim> </p:panel> This works fine, but not if the same tag is used inside a p:dataTable -- either with or without the p:panel enclosure. What gets rendered is a div class="ui-dt-c" element with nothing in it. To test, if I take out the f:verbatim tag the marked-up text gets escaped and rendered. I don't know if this should be considered a bug or not, but does anyone know of a work-around for this? This is with PrimeFaces 3.0.M3. A: The <f:verbatim> tag is intented to hold plain text/HTML, not JSF components nor EL expressions. The tag is a leftover from JSF 1.0/1.1 ages when it was not possible to inline plain text/HTML between JSF components. The tag is deprecated in JSF2. You do not need it anymore. Your concrete functional requirement is thus displaying some HTML string from a managed bean unescaped. For that you should use <h:outputText> with escape="false". <h:outputText value="#{daBean.markedUpString}" escape="false" /> See also: * *Getters inside f:verbatim called before form submission *JSF/Facelets: why is it not a good idea to mix JSF/Facelets with HTML tags? *What are the main disadvantages of Java Server Faces 2.0?
{ "language": "en", "url": "https://stackoverflow.com/questions/7539935", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Trying to set up Orchard Multi-Tenancy on IIS Server I am very new to Orchard, and am having a most difficult time setting up IIS bindings. I am not proficient at IIS, and am new to web development in general. Say I have domain1.com which is the main Orchard site (landlord). I properly set up domain2.com in the Multi-Tenant module. My DNS records on the server work properly if I have domain1.com and domain2.com as separate sites (i.e., I can type in domain1.com and see the Orchard landlord site, I can type domain2.com and see the default page used by my control panel). I guess I am just having a hard time binding. I fiddled around with DNS settings using my servers control panel - no luck. I then tried using IIS to "bind" domain2.com to domain1.com but am pretty sure I have made a mess of it. :) I've searched around for an answer, but nothing seems to work or otherwise I am unable to fully grasp the concept. The Orchard documentation doesn't really deal with IIS bindings (it deals with using the development machine to host the multi-tenant sites, but I am dealing with a live server - all my "development", such as it is, is done). Any suggestions? Thanks. A: To get bindings working for multi-tennancy working you can do one of two things. Set a catch all domain binding: Create a site in IIS with the binding set to all unassigned IP addresses and no host name. Any domain pointing at the IP of your server will point at this site and Orchard multi-tennancy will decide which of your Orchard sites to point it at. Only one IIS site can have this setting or they will clash. Add multiple domain bindings: In ISS create a site for bound to domain1.com, then under edit site click bindings and add a new binding for domain2.com.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539941", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: restful POST in Play I have been following some Play! framework tutorials, but I cannot get the simplest of examples to work. String xml = "<thing><foo>first</foo><bar>second</bar></thing>"; Response response = POST("/thing", "application/xml", xml); In my /thing method in the controller, the Thing object that is passed in is always null. Does anyone have a code snippet that successfully POSTs a xml document to a controller action, and then ends up with a deserialised object at the end that can be persisted to the database? A: It seems that there is an error in the book. The code Request.current().params.get("body") in the method ApiPlugin.getXml(Class) returns String object. There is no overloaded method unmarshal(String) in the interface javax.xml.bind.Unmarshaller. To make it works wrap that string into java.io.StringReader: String body = Request.current().params.get("body"); return um.unmarshal(new StringReader(body));
{ "language": "en", "url": "https://stackoverflow.com/questions/7539944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: php json encode outputting invalid json from mysql results Possible Duplicate: encode json using php? $hello_world = $this->session->all_userdata(); foreach($hello_world as $key=>$product_id) { $query['products'] = $this->Global_products->globalFindProductsViewed($product_id); foreach($query['products'] as $product) { $ryan[] = $product->name; } } foreach($ryan as $r) { echo json_encode(array($r)); } The output then looks like this: ["Alpine 50W x 4 Apple® iPod®-Ready In-Dash CD Deck"] I know I cant access this with JavaScript. Can someone suggest how I can make this work? A: JSON encoding every array element separately doesn't make sense. Remove the foreach, and just do a echo json_encode($ryan);
{ "language": "en", "url": "https://stackoverflow.com/questions/7539946", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-5" }
Q: How to make an array of images specifically in the same *? I am trying to make an image switcher for my portfolio site that is unique. To do this I think I need to be able to have an array of images that matches with the corresponding array of list items with the names of the projects they belong to, like this: <ul> <li><img src="1.png"></li> <li><img src="2.png"></li> <li><img src="3.png"></li> </ul> <ul> <li>Project 1</li> <li>Project 2</li> <li>Project 3</li> </ul> So I guess I want the javascript to "think" like this: "Oh, img 2 is the second list item, if project 2 is clicked which is also the second list item, I should display img 2" Ya digg? Here is what I have so far, if you need a visual: http://addproxy.net/sites/img_switcher/index.html A: In jQuery, you could do it like this: HTML: <ul id="images"> <li><img src="http://photos.smugmug.com/photos/344291068_HdnTo-Ti.jpg"></li> <li><img src="http://photos.smugmug.com/photos/344290962_h6JjS-Ti.jpg"></li> <li><img src="http://photos.smugmug.com/photos/344290837_ypsKL-Ti.jpg"></li> </ul> <ul id="projects"> <li>Project 1</li> <li>Project 2</li> <li>Project 3</li> </ul> javascript: $("#projects li").click(function() { var pos = $(this).parent().children().index(this); var $images = $("#images li"); $images.hide(); // hide previous images $images.eq(pos).show(); }); And, you can see it work here: http://jsfiddle.net/jfriend00/gV2NH/. If you can't use jQuery, then the general idea is that you set up a click handler for each project. When one of them is clicked on, you get the parent and get it's children (which will be a list of all the project li tags). You then see which one the click happened on so now you have the sequence number. You can then use that sequence number to show just the right image from the other list.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Problems with pinch zoom on Android I recently discovered a bit of code to keep the backgrounds stable, when pinch zooming on iphone/ipad. However I am running test on my website on my Android, and when I pinch zoom, the background image, which covers the whole site in the body tag, jumps all over the place. So is there any code that can counteract this on Android devices, so my website can behave at an acceptable standard?
{ "language": "en", "url": "https://stackoverflow.com/questions/7539950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I give this time-critical procedure priority over other threads? In order to write a MIDI sequencer I need a steady pulse that calls a timing routine that has absolute priority over anything else in the program and preferrably over anything in the computer. I do this by using TimeSetEvent like this: TimeSetEvent (FInterval, 0, TimerUpdate, uInt32 (Self), TIME_PERIODIC); where TimerUpdate is a callback that resumes a separate thread with priority tpTimeCritical and that one calls a routine (FOnTimer) in which to handle all MIDI events. procedure TThreaded_Timer.Execute; begin if Assigned (FOnTimer) then begin while not Terminated do begin FOnTimer (Self); if not Terminated then Suspend; end; // while end; // if Terminate; end; // Execute // Although this construction is much better than some things I tried before it is still very sensitive to some events. To my surprise it stutters at each display of a hint. Why can a simple hint cause such an interruption of a time critical thread? Of course I can switch it off but which nasty surprises are still waiting for me? A: Use the multimedia timer which is designed for this purpose. Delphi timers are awful and really only get attention during idle time. A thread-based timer is only useful when that thread gets attention. The MMTimer operates at kernel level and provides a callback that is really quite accutate. We use it for hardware sequencing automation control it is so good. Here is my unit that implements an MMTimer as a more easy to use TTimer. Use 'Repeat' to make it single-shot or repetetive. unit UArtMMTimer; interface uses Classes, SysUtils, ExtCtrls, MMSystem; type TArtMMTimer = class( TObject ) constructor Create; destructor Destroy; override; PRIVATE FHandle : MMResult; FRepeat : boolean; FIntervalMS : integer; FOnTimer : TNotifyEvent; FEnabled : boolean; procedure RemoveEvent; procedure InstallEvent; procedure DoOnCallback; procedure SetEnabled( AState : boolean ); procedure SetIntervalMS( AValue : integer ); PUBLIC property Enabled : boolean read FEnabled write SetEnabled; property OnTimer : TNotifyEvent read FOnTimer write FOnTimer; property IntervalMS : integer read FIntervalMS write SetIntervalMS; end; implementation uses Windows; // TArtMMTimer // -------------------------------------------------------------------- procedure MMTCallBack(uTimerID, uMessage: UINT; dwUser, dw1, dw2: DWORD) stdcall; var Timer : TArtMMTimer; begin Timer := TArtMMTimer( dwUser ); Timer.DoOnCallback; end; constructor TArtMMTimer.Create; begin Inherited Create; FIntervalMS := 100; FRepeat := True; end; destructor TArtMMTimer.Destroy; begin FOnTimer := nil; RemoveEvent; Inherited Destroy; end; procedure TArtMMTimer.RemoveEvent; begin If FHandle <> 0 then begin timeKillEvent( FHandle ); FHandle := 0; end; end; procedure TArtMMTimer.InstallEvent; var iFlags : integer; begin RemoveEvent; If FRepeat then iFlags := TIME_PERIODIC Or TIME_CALLBACK_FUNCTION else iFlags := TIME_CALLBACK_FUNCTION; FHandle := timeSetEvent( FIntervalMS, 0, @MMTCallBack, DWord(Self), iFlags ); end; procedure TArtMMTimer.SetEnabled( AState : boolean ); begin If AState <> FEnabled then begin FEnabled := AState; If FEnabled then InstallEvent else RemoveEvent; end; end; procedure TArtMMTimer.DoOnCallback; var NowHRCount, WaitHRCount,IntervalHRCount : THRCount; begin If Assigned( FOnTimer ) then FOnTimer( Self ); end; procedure TArtMMTimer.SetIntervalMS( AValue : integer ); begin If AValue <> FIntervalMS then begin FIntervalMS := AValue; If Enabled then begin Enabled := False; Enabled := True; end; end; end; // End TArtMMTimer // -------------------------------------------------------------------- end. A: The accuracy of the multimedia timers is not that great.Here is an article that explains why. Instead of relying on a timer to wake up your thread why don't you manage your sleep and wake times all within the thread itself? Maybe something like this (in pseudo-code, sorry I don't know Delphi): my_critical_thread() { while (true) { time = get_current_time() do_work(); time = interval - (get_current_time() - time) if (time > 0) sleep(time) } } This should get you very close to your target interval if the thread is set to critical priority, assuming the work you do on each iteration leaves time for your other threads and the rest of the system to do their thing. Good luck. A: Set a timer to a slightly shorter time than required (10 ms less, for example). When the timer occurs, raise thread priority to "above normal". Calculate the remaining time to wait and execute Sleep with a slightly shorter interval (1 ms less, for example). Now start waiting in a loop for the correct time. In each loop occurrence execute at least one asm pause; end; instruction to not push a core to the 100% usage. When the time occurs, lower thread priority to "normal". I think that's the best you can do without writing a device driver. A: Thanks for all the suggestions. In order to test them I developed a small Delphi program in order to test the suggested algorithms. Four algorithms are tested * *Simple (by Brian Frost) - Uses the Multimedia timer (TimeSetEvent), which calls a callback that performs the timed task. *Threaded (by Brian Pedersen) - As with simple, but the callback is called in a separate thread. The thread receives the highest priority possible (TimeCritical). *Looping (by Miguel) - In this algorithm we don't trust the timer at all and write one ourselves. The callback is performed in a loop, after each call we examine how much time is still left until the next tick and wait until the next has to take place. The thread has highest priority. I used the asm pause; end suggestion from Gabr as a fast way of event processing. *Fire & Forget (by myself) - The multimedia timer at each tick creates a separate thread with the highest priority, assigns it the callback and forgets about it. This has the advantage that even when a previous thread has not yet finished, a new one can start already and if you are lucky - on a new processor. You can find the results here. Most timers run correct with a normal workload, though the simple multimedia timer shows the most variability. The looping timer is the most precise. All timers except the fire & forget run into problems when the workload results in work that lasts longer than the Interval. The best performance comes from the fire & forget algorithm. However, one should take care that no shared resources are used in the callback because the callback can be invoked multiple times when the workload increases. In fact in the current implementation MIDIOut can be invoked simultaneously so it should be surrounded by a critical section. When another programs is run the timers show a greater variability. The looping timer still performs best. When I add the timer to my original MIDI sequencer the original question remains als. Hints keep interrupting the timer as before though they did not so in the test version which you can download. Parameters Constancy of Beat Workload Timer N Interval Resolution WorkLoad Mean s.d. Min Max Mean s.d. Min Max Simple 226 22 30 1000 22.001 0.001 21.996 22.009 0.093 0.036 0.079 0.302 Threaded 226 22 30 1000 22.001 0.004 21.964 22.031 0.091 0.032 0.079 0.253 Looping 227 22 30 1000 22.000 0.002 21.999 22.025 0.093 0.034 0.079 0.197 Fire & Forget 226 22 30 1000 22.001 0.008 21.964 22.042 0.091 0.031 0.079 0.186 Simple 226 22 15 1000 22.001 0.002 21.989 22.011 0.091 0.031 0.079 0.224 Threaded 226 22 15 1000 22.001 0.003 21.978 22.031 0.091 0.032 0.079 0.185 Looping 227 22 15 1000 22.000 0.001 21.999 22.015 0.092 0.034 0.079 0.209 Fire & Forget 226 22 15 1000 22.001 0.015 21.861 22.146 0.091 0.031 0.079 0.173 Simple 226 22 0 1000 22.001 0.001 21.997 22.005 0.091 0.030 0.079 0.190 Threaded 226 22 0 1000 22.001 0.003 21.979 22.029 0.091 0.031 0.079 0.182 Looping 227 22 0 1000 22.000 0.000 21.999 22.002 0.092 0.034 0.079 0.194 Fire & Forget 226 22 0 1000 22.001 0.026 21.747 22.256 0.090 0.030 0.079 0.180 Simple 226 22 30 10000 22.001 0.002 21.992 22.012 0.801 0.034 0.787 1.001 Threaded 226 22 30 10000 22.001 0.002 21.994 22.008 0.800 0.031 0.787 0.898 Looping 227 22 30 10000 22.000 0.000 21.999 22.000 0.802 0.034 0.787 0.919 Fire & Forget 226 22 30 10000 22.001 0.010 21.952 22.087 0.903 0.230 0.788 1.551 Simple 226 22 15 10000 22.001 0.002 21.984 22.020 0.810 0.081 0.788 1.417 Threaded 226 22 15 10000 22.001 0.006 21.981 22.073 0.800 0.031 0.788 0.889 Looping 227 22 15 10000 22.000 0.000 21.999 22.000 0.802 0.036 0.787 0.969 Fire & Forget 226 22 15 10000 22.001 0.009 21.914 22.055 0.799 0.030 0.788 0.885 Simple 226 22 0 10000 22.001 0.002 21.994 22.006 0.799 0.030 0.788 0.894 Threaded 226 22 0 10000 22.001 0.005 21.953 22.048 0.799 0.030 0.787 0.890 Looping 227 22 0 10000 22.000 0.000 21.999 22.002 0.801 0.034 0.787 0.954 Fire & Forget 226 22 0 10000 22.001 0.007 21.977 22.029 0.799 0.030 0.788 0.891 Simple 226 22 30 100000 22.001 0.002 21.988 22.017 7.900 0.052 7.879 8.289 Threaded 226 22 30 100000 22.001 0.003 21.967 22.035 7.897 0.036 7.879 8.185 Looping 227 22 30 100000 22.000 0.001 21.999 22.015 7.908 0.098 7.879 9.165 Fire & Forget 225 22 30 100000 22.001 0.007 21.960 22.027 7.901 0.038 7.880 8.061 Simple 227 22 15 100000 22.014 0.195 21.996 24.934 7.902 0.056 7.879 8.351 Threaded 226 22 15 100000 22.001 0.002 21.997 22.008 7.900 0.049 7.879 8.362 Looping 227 22 15 100000 22.000 0.000 22.000 22.000 7.900 0.046 7.879 8.229 Fire & Forget 225 22 15 100000 22.001 0.008 21.962 22.065 7.906 0.082 7.880 8.891 Simple 227 22 0 100000 22.018 0.261 21.937 25.936 7.901 0.050 7.879 8.239 Threaded 226 22 0 100000 22.001 0.001 21.998 22.005 7.897 0.031 7.879 7.987 Looping 227 22 0 100000 22.000 0.000 21.999 22.000 7.901 0.053 7.879 8.263 Fire & Forget 225 22 0 100000 22.001 0.007 21.967 22.032 7.900 0.044 7.880 8.308 Simple 63 22 30 1000000 78.027 6.801 24.938 80.730 77.754 8.947 7.890 80.726 Threaded 56 22 30 1000000 87.908 1.334 78.832 91.787 78.897 0.219 78.819 80.430 Looping 62 22 30 1000000 78.923 0.320 78.808 80.749 78.923 0.320 78.808 80.748 Fire & Forget 222 22 30 1000000 22.001 0.009 21.956 22.038 84.212 3.431 78.825 91.812 Simple 66 22 15 1000000 75.656 13.090 21.994 80.714 79.183 1.559 78.811 90.950 Threaded 56 22 15 1000000 87.841 1.204 78.991 88.011 78.849 0.043 78.812 79.003 Looping 62 22 15 1000000 78.880 0.207 78.807 80.442 78.880 0.207 78.807 80.441 Fire & Forget 222 22 15 1000000 22.001 0.978 11.975 32.042 84.915 3.569 78.816 90.917 Simple 66 22 0 1000000 75.681 12.992 21.991 80.778 79.213 1.400 78.807 87.766 Threaded 56 22 0 1000000 87.868 1.238 78.889 89.515 78.954 0.597 78.813 83.164 Looping 62 22 0 1000000 78.942 0.307 78.806 80.380 78.942 0.307 78.806 80.379 Fire & Forget 222 22 0 1000000 22.001 0.011 21.926 22.076 83.953 3.103 78.821 91.145
{ "language": "en", "url": "https://stackoverflow.com/questions/7539952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Java JSON serialization - best practice I need to implement JSON serialization for some objects, and I've encountered a problem when it came to integration with generic collections. All serializable classes implement this interface (JSONObject comes from this library): interface JSONSerializable{ public JSONObject dump() throws JSONException //serializes object public void load(JSONObject obj) throws JSONException //deserializes object } Code for my collection based on java.util.list looks more or less like this: class AwesomeList<T extends JSONSerializable> implements JSONSerializable{ private LinkedList<T> items = new LinkedList<T>(); ... ... public JSONObject dump() throws JSONException { JSONObject result = new JSONObject(); JSONArray a = new JSONArray(); for(T i : items){ a.put(i.dump()); } result.put("items", a); return result; } public void load(JSONObject obj) throws JSONException{ //here is my problem } } My problem is: When I load AwesomeList from JSONObject, I need to create its elements but it's impossible since java forbids me to write T newItem = new T(); newItem.load(obj); How should I modify my approach to this task? A: As others have hinted, you should consider dumping org.json's library. It's pretty much obsolete these days, and trying to work around its problems is waste of time. But to specific question; type variable T just does not have any information to help you, as it is little more than compile-time information. Instead you need to pass actual class (as 'Class cls' argument), and you can then create an instance with 'cls.newInstance()'. A: Are you tied to this library? Google Gson is very popular. I have myself not used it with Generics but their front page says Gson considers support for Generics very important. A: Well, when writing it out to file, you do know what class T is, so you can store that in dump. Then, when reading it back in, you can dynamically call it using reflection. public JSONObject dump() throws JSONException { JSONObject result = new JSONObject(); JSONArray a = new JSONArray(); for(T i : items){ a.put(i.dump()); // inside this i.dump(), store "class-name" } result.put("items", a); return result; } public void load(JSONObject obj) throws JSONException { JSONArray arrayItems = obj.getJSONArray("items"); for (int i = 0; i < arrayItems.length(); i++) { JSONObject item = arrayItems.getJSONObject(i); String className = item.getString("class-name"); try { Class<?> clazzy = Class.forName(className); T newItem = (T) clazzy.newInstance(); newItem.load(obj); items.add(newItem); } catch (InstantiationException e) { // whatever } catch (IllegalAccessException e) { // whatever } catch (ClassNotFoundException e) { // whatever } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7539954", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "33" }
Q: small problem with django-tinymce and django-filebrowser integration I am trying to integrate django-tinymce with django-filebrowser for my django admin site. Everything (almost) works fine. * *manage.py test filebrowser, works ok *http://localhost:8000/admin/filebrowser/browse/ works, too however when I press the browse button on the windows popup of insert/edit image of tinymce button panel nothing happens. in my firefox debug window I get an error like this (when pressing browse): f is undefined code: http://localhost:8000/static/js/tiny_mce/tiny_mce_src.js line: 11981 and on my dev-server output window I get a 500 error like this: GET /tinymce/filebrowser/ HTTP/1.1" 500 when admin page tries to load the tinymce_models.HTMLField() text area. Any ideas what am I doing wrong? PS: I also use grappelli and this is my settings.py part that loads the apps: INSTALLED_APPS = ( #... usual django standard apps.. # 'django.contrib.staticfiles', 'grappelli', 'filebrowser', 'tinymce', 'django.contrib.admin', 'expedeat.dbadmin', ) A: I finally managed to find the answer to my problem. I had to modify the tinymce/views.py file like this: fb_url = "%s://%s%s" % (request.is_secure() and 'https' or 'http', #request.get_host(), urlresolvers.reverse('filebrowser-index')) request.get_host(), urlresolvers.reverse('fb_browse')) I found the answer in this post: http://www.mail-archive.com/django-users@googlegroups.com/msg100388.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7539957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Finding whether a string starts with one of a list's variable-length prefixes I need to find out whether a name starts with any of a list's prefixes and then remove it, like: if name[:2] in ["i_", "c_", "m_", "l_", "d_", "t_", "e_", "b_"]: name = name[2:] The above only works for list prefixes with a length of two. I need the same functionality for variable-length prefixes. How is it done efficiently (little code and good performance)? A for loop iterating over each prefix and then checking name.startswith(prefix) to finally slice the name according to the length of the prefix works, but it's a lot of code, probably inefficient, and "non-Pythonic". Does anybody have a nice solution? A: for prefix in prefixes: if name.startswith(prefix): name=name[len(prefix):] break A: str.startswith(prefix[, start[, end]])¶ Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position. $ ipython Python 3.5.2 (default, Nov 23 2017, 16:37:01) Type 'copyright', 'credits' or 'license' for more information IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help. In [1]: prefixes = ("i_", "c_", "m_", "l_", "d_", "t_", "e_", "b_") In [2]: 'test'.startswith(prefixes) Out[2]: False In [3]: 'i_'.startswith(prefixes) Out[3]: True In [4]: 'd_a'.startswith(prefixes) Out[4]: True A: Regexes will likely give you the best speed: prefixes = ["i_", "c_", "m_", "l_", "d_", "t_", "e_", "b_", "also_longer_"] re_prefixes = "|".join(re.escape(p) for p in prefixes) m = re.match(re_prefixes, my_string) if m: my_string = my_string[m.end()-m.start():] A: If you define prefix to be the characters before an underscore, then you can check for if name.partition("_")[0] in ["i", "c", "m", "l", "d", "t", "e", "b", "foo"] and name.partition("_")[1] == "_": name = name.partition("_")[2] A: What about using filter? prefs = ["i_", "c_", "m_", "l_", "d_", "t_", "e_", "b_"] name = list(filter(lambda item: not any(item.startswith(prefix) for prefix in prefs), name)) Note that the comparison of each list item against the prefixes efficiently halts on the first match. This behaviour is guaranteed by the any function that returns as soon as it finds a True value, eg: def gen(): print("yielding False") yield False print("yielding True") yield True print("yielding False again") yield False >>> any(gen()) # last two lines of gen() are not performed yielding False yielding True True Or, using re.match instead of startswith: import re patt = '|'.join(["i_", "c_", "m_", "l_", "d_", "t_", "e_", "b_"]) name = list(filter(lambda item: not re.match(patt, item), name)) A: Regex, tested: import re def make_multi_prefix_matcher(prefixes): regex_text = "|".join(re.escape(p) for p in prefixes) print repr(regex_text) return re.compile(regex_text).match pfxs = "x ya foobar foo a|b z.".split() names = "xenon yadda yeti food foob foobarre foo a|b a b z.yx zebra".split() matcher = make_multi_prefix_matcher(pfxs) for name in names: m = matcher(name) if not m: print repr(name), "no match" continue n = m.end() print repr(name), n, repr(name[n:]) Output: 'x|ya|foobar|foo|a\\|b|z\\.' 'xenon' 1 'enon' 'yadda' 2 'dda' 'yeti' no match 'food' 3 'd' 'foob' 3 'b' 'foobarre' 6 're' 'foo' 3 '' 'a|b' 3 '' 'a' no match 'b' no match 'z.yx' 2 'yx' 'zebra' no match A: A bit hard to read, but this works: name=name[len(filter(name.startswith,prefixes+[''])[0]):] A: When it comes to search and efficiency always thinks of indexing techniques to improve your algorithms. If you have a long list of prefixes you can use an in-memory index by simple indexing the prefixes by the first character into a dict. This solution is only worth if you had a long list of prefixes and performance becomes an issue. pref = ["i_", "c_", "m_", "l_", "d_", "t_", "e_", "b_"] #indexing prefixes in a dict. Do this only once. d = dict() for x in pref: if not x[0] in d: d[x[0]] = list() d[x[0]].append(x) name = "c_abcdf" #lookup in d to only check elements with the same first character. result = filter(lambda x: name.startswith(x),\ [] if name[0] not in d else d[name[0]]) print result A: This edits the list on the fly, removing prefixes. The break skips the rest of the prefixes once one is found for a particular item. items = ['this', 'that', 'i_blah', 'joe_cool', 'what_this'] prefixes = ['i_', 'c_', 'a_', 'joe_', 'mark_'] for i,item in enumerate(items): for p in prefixes: if item.startswith(p): items[i] = item[len(p):] break print items Output ['this', 'that', 'blah', 'cool', 'what_this'] A: Could use a simple regex. import re prefixes = ("i_", "c_", "longer_") re.sub(r'^(%s)' % '|'.join(prefixes), '', name) Or if anything preceding an underscore is a valid prefix: name.split('_', 1)[-1] This removes any number of characters before the first underscore. A: import re def make_multi_prefix_replacer(prefixes): if isinstance(prefixes,str): prefixes = prefixes.split() prefixes.sort(key = len, reverse=True) pat = r'\b(%s)' % "|".join(map(re.escape, prefixes)) print 'regex patern :',repr(pat),'\n' def suber(x, reg = re.compile(pat)): return reg.sub('',x) return suber pfxs = "x ya foobar yaku foo a|b z." replacer = make_multi_prefix_replacer(pfxs) names = "xenon yadda yeti yakute food foob foobarre foo a|b a b z.yx zebra".split() for name in names: print repr(name),'\n',repr(replacer(name)),'\n' ss = 'the yakute xenon is a|bcdf in the barfoobaratu foobarii' print '\n',repr(ss),'\n',repr(replacer(ss)),'\n'
{ "language": "en", "url": "https://stackoverflow.com/questions/7539959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: Sencha Touch Store With Date Field I have a Model with Date field and Store which loads from XML with same date field as string. Would the sencha parse it to Date automatically or I would need to do that manually? Ext.regModel('News', { idProperty: 'Id', fields: [ { name: 'Id', type: 'int' }, { name: 'Title', type: 'string' }, { name: 'PostedOn', type: 'date' }, { name: 'PostedBy', type: 'string' }, { name: 'Details', type: 'string' } ] }); var newsRemoteStore = new Ext.data.Store({ model: 'News', sorters: [{ property: 'PostedOn', direction: 'DESC' }], proxy: { type: 'ajax', url: BaseURL + 'News.php', reader: { type: 'xml', root: 'News', record: 'New' } }, getGroupString: function(record) { if (record && record.data.PostedOn) { return record.get('PostedOn').toDateString(); } else { return ''; } } }); I am asking because the Date field is empty even though there is date in xml response e,g. <PostedOn>2011-07-04 16:00:19</PostedOn> A: Version 1.1 of Sencha Touch supports auto, string, int, float, boolean & date (refer to the Sencha Touch 1.1 API Docs A: No, sencha only support 4 data types: int, float, string and auto. You should set the date field as string and then have it converted in to a date object in the getGroupString to compare it to another date object. Read all about it here: http://www.sencha.com/blog/ext-js-4-anatomy-of-a-model
{ "language": "en", "url": "https://stackoverflow.com/questions/7539960", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting protection bits for the whole address space OK, what I want to do here is to only give read access to all the pages in an address space in Linux. Whenever a page would be written, I will give write access to it in a SIGSEGV signal handler. For 32 bit, this is easy as the address space is of only 4GB, therefore it wouldn't take alot of time to set bits for each page, but how do I approach this problem for a 64 bit process as the address space is almost infinite in this case. Its no problem for me if I limit the address space size with ulimit -v, but people told me the address would not be linear. Now my head is aching thinking how can I solve this problem. Any help in this regard would be highly appreciated. Please tell me the most efficient way possible to set read access of all pages for a 64 bit program. A: To avoid protecting the entire address space, only protect the pages in use. And, trap the system calls that change the address space (mmap, brk, possibly thread creation, etc) so you can protect those pages. Note that your signal handler cannot run without being able to write to its stack (nor being able to execute its code), so there are some fundamental problems beyond just 64-bits being large.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539966", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cannot construct org.apache.maven.plugin.war.util.WebappStructure as it does not have a no-args constructor [INFO] [war:war {execution: default-war}] [INFO] Packaging webapp [INFO] ------------------------------------------------------------------------ [ERROR] FATAL ERROR [INFO] ------------------------------------------------------------------------ [INFO] Cannot construct org.apache.maven.plugin.war.util.WebappStructure as it does not have a no-args constructor ---- Debugging information ---- message : Cannot construct org.apache.maven.plugin.war.util.WebappStructure as it does not have a no-args constructor cause-exception : com.thoughtworks.xstream.converters.reflection.ObjectAccessException cause-message : Cannot construct org.apache.maven.plugin.war.util.WebappStructure as it does not have a no-args constructor class : org.apache.maven.plugin.war.util.WebappStructure required-type : org.apache.maven.plugin.war.util.WebappStructure path : /webapp-structure line number : 1 ------------------------------- [INFO] ------------------------------------------------------------------------ [INFO] Trace com.thoughtworks.xstream.converters.ConversionException: Cannot construct org.apache.maven.plugin.war.util.WebappStructure as it does not have a no-args constructor ---- Debugging information ---- message : Cannot construct org.apache.maven.plugin.war.util.WebappStructure as it does not have a no-args constructor cause-exception : com.thoughtworks.xstream.converters.reflection.ObjectAccessException cause-message : Cannot construct org.apache.maven.plugin.war.util.WebappStructure as it does not have a no-args constructor class : org.apache.maven.plugin.war.util.WebappStructure required-type : org.apache.maven.plugin.war.util.WebappStructure path : /webapp-structure line number : 1 ------------------------------- at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:63) at com.thoughtworks.xstream.core.AbstractReferenceUnmarshaller.convert(AbstractReferenceUnmarshaller.java:45) at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:46) at com.thoughtworks.xstream.core.TreeUnmarshaller.start(TreeUnmarshaller.java:117) at com.thoughtworks.xstream.core.ReferenceByXPathMarshallingStrategy.unmarshal(ReferenceByXPathMarshallingStrategy.java:29) at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:846) at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:833) at com.thoughtworks.xstream.XStream.fromXML(XStream.java:781) at org.apache.maven.plugin.war.util.WebappStructureSerializer.fromXml(WebappStructureSerializer.java:73) at org.apache.maven.plugin.war.AbstractWarMojo.buildWebapp(AbstractWarMojo.java:404) at org.apache.maven.plugin.war.AbstractWarMojo.buildExplodedWebapp(AbstractWarMojo.java:375) at org.apache.maven.plugin.war.WarMojo.performPackaging(WarMojo.java:181) at org.apache.maven.plugin.war.WarMojo.execute(WarMojo.java:143) at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:490) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:694) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalWithLifecycle(DefaultLifecycleExecutor.java:556) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:535) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:387) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:348) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:180) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:328) at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:138) at org.apache.maven.cli.MavenCli.main(MavenCli.java:362) at org.apache.maven.cli.compat.CompatibleMain.main(CompatibleMain.java:60) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315) at org.codehaus.classworlds.Launcher.launch(Launcher.java:255) at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430) at org.codehaus.classworlds.Launcher.main(Launcher.java:375) Caused by: com.thoughtworks.xstream.converters.reflection.ObjectAccessException: Cannot construct org.apache.maven.plugin.war.util.WebappStructure as it does not have a no-args constructor at com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider.newInstance(PureJavaReflectionProvider.java:59) at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.instantiateNewInstance(AbstractReflectionConverter.java:257) at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.unmarshal(AbstractReflectionConverter.java:124) at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:56) ... 31 more [INFO] ------------------------------------------------------------------------ [INFO] Total time: 4 seconds [INFO] Finished at: Sat Sep 24 17:25:45 CEST 2011 [INFO] Final Memory: 15M/37M [INFO] ------------------------------------------------------------------------ JDK: 1.7 Maven compiler Plugin: <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> </plugin> When I run install target above error occurs, how can I resolve it? A: Instead of changing JDK versions and Maven versions, try this: <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.7</source> <target>1.7</target> </configuration> <version>2.3.2</version> </plugin> A: Confirmed, I ran into the same issue with maven 3.0.2 and jdk 1.7.0_02. After running against jdk 1.6.0_30 it compiled just fine. A: I don't think the version was the problem. I solved deleting my target folder (because it contains webapp-cache.xml) and doing Maven install again. A: Apache Maven WAR Plugin 3.0.0 resolved all issues: <artifactId>maven-war-plugin</artifactId> <version>3.0.0</version> It doesn't matter if you use jdk 1.6, 1.7 or 1.8 A: This definitely seems to be related to incompatible plugin, library and language versions. Two years, and two Java versions later, I had this same error while doing a sample project from an older book on Spring and Hibernate. I was able to resolve the error by commenting out all of the version tags for the apache.maven.plugins and setting the Java version to 1.8. This let me know what was the latest and greatest version of the libraries, with the cost of some warnings from Maven about missing the version tags. If you care about the warnings, you can set the version tags to be latest version and the warnings from Maven should go away. I executed mvn clean package and then just mvn package. <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <!-- <version>2.1-beta-1</version> --> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <!-- <version>2.1</version> --> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> A: if your using jdk 1.6 kindly add this plugin entry to your pom.xml <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.0.2</version> <configuration> <source>1.6</source> <target>1.6</target> <compilerArgument>-Xlint:all</compilerArgument> <showWarnings>true</showWarnings> <showDeprecation>true</showDeprecation> </configuration> </plugin> A: I had this problem with my eclipse Kepler. As soon as I moved to 4.4 (Luna) , all gone. Must be an issue with eclipse + maven embedded I tried both JDK 1.7 and 1.8. No difference. A: I had this problem when doing a mvn install. I resolved it by doing a mvn clean first, followed by a mvn install. Using maven 2.1.1, JDK 1.7.0.45. A: Perhaps a version of maven war plugin is being used, which does not work with Java 7? As per this issue (which describes a similar problem), 2.1.1 version of maven war plugin should work. Include the following in your pom.xml <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.1.1</version> </plugin> A: It's confirmed: JDK7 with Maven 2.x will produce this error. I am using Maven 2.2.1 and JDK7 and got this error. I changed the JDK to version 1.6 and it's working fine. A: For me changing plugin version could not solve problme and changing JDK version is not in my control. However running mvn clean before mvn tomcat6:deploy solved this problem. A: Make sure to have the JDK version in your Build path and the version specified in the source tag match the same. <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.1</version> <configuration> **<source>1.7</source>** <target>1.7</target> <debug>true</debug> </configuration> </plugin> ` I had the build path pointing to jdk 1.7 and "1.6" in the source tag, when I corrected the version to 1.7 in source tag the issue got resolved. Execute mnv clean and mvn package. A: Try to delete all your cache. When i deleted target folder, it works fine. (Target folder is where maven puts all compiled code) A: I was getting the same error after i upgraded my java version from 8 to some 8.x, i fixed it by going to pom then 1. right click > maven > add plugin 2. type in org.apache.maven and then look for war plugin add it and save, then just clean and install. It should work. A: use this plugin <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> </plugin> Example pom.xml pom.xml screenshot` A: Use this below plugin to get rid of this issue ( Latest ) and refer this <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.10.1</version> <configuration> <source>11</source> <target>11</target> </configuration> </plugin> </plugins> <finalName>SampleProject</finalName> </build>
{ "language": "en", "url": "https://stackoverflow.com/questions/7539970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "96" }
Q: How to use gnomevfs.get_mime_type()? Python gnome binding have gnomevfs module that theoretically can get MIME types. But calling gnomevfs.get_mime_type() with any name other than "/dev/null" raises error "RuntimeError: there was an error reading the file". For example: import gnomevfs gnomevfs.get_mime_type( "/tmp/a.py" ) gnomevfs.get_mime_type( "file://tmp/a.py" ) gnomevfs.get_mime_type( "file:///tmp/a.py" ) gnomevfs.get_mime_type( "file://./tmp/a.py" ) This all fails. With any file / folder name except "/dev/null" :(. /tmp/a.py exists and acessible. Any suggestions? A: It works for me. Have you tried with other files in other directories? Are you sure that the user under which Python is being run has access to /tmp/a.py?
{ "language": "en", "url": "https://stackoverflow.com/questions/7539971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: linq changing order of columns I have an IQueryable that's returned from a query. The columns are Article, Id, Lot. What's a simple linq way to have the columns Id, Article, Lot. A: You are working with objects that have named properties corresponding to the columns in the database. The order shouldn't matter. A: The simplest way I found is from t in table select new{ Id = t.Id, Article = t.Article, Lot = t.Lot } as @driis says order doesnt matter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Asymmetric cryptography example in C# I need to send confidential data to a server over a TCP connection. I have done a lot of researching and I understand the theoretical part. Based on what I have researched I want to do the following: Note there is a server and a client: (we assume that public keys of either the client or server can be obtain by anyone) * *client creates his public and private key. He is able to encrypt with his private key and decrypt with his public key. *server creates his public and private keys. private key is used to decrypt messages and public key is used to encrypt messages. (note is the other way around as with the client) *the client get's the server's public key. client then will be able to encrypt messages with that key and the only one that will be able to decrypt that message would be the server's private key. *since the server needs to be certain that the message comes from that specific client then the client will encrypt his name (signature) with his private key. *so the client message will contain: data to be send, client's public key, client name encrypted with the client's private key. *the client will encrypt the message with the public key from the server. client will then send that message to the server. *the server will decrypt the message it just received with his private key. *once the message is decrypted it will contain the data (info), encrypted signature, public key from client. *finally, the server will decrypt the client signature with the public key that was contained on the message to verify that the message is from that client. OK so this is how asymmetric cryptography works. I have also researched about the classes that enable you to create this key pairs with the .NET framework. The classes that I researched that enable you do create this public and private key pairs are: System.Security.Cryptography.DES System.Security.Cryptography.DSACryptoServiceProvider System.Security.Cryptography.ECDsa System.Security.Cryptography.ECDsaCng System.Security.Cryptography.ECDiffieHellman System.Security.Cryptography.ECDiffieHellmanCng System.Security.Cryptography.RSA System.Security.Cryptography.RSACryptoServiceProvider so now my problems comes on how do I use one of this classes to do it with C#? I understand how the theoretical part works but how do I do what I just described with code. I have researched for some examples but I am having a hard time understanding them. here is one example that I found that I believe does what I described: using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace Example { class Program { static CngKey aliceKey; static CngKey bobKey; static byte[] alicePubKeyBlob; static byte[] bobPubKeyBlob; static void Main() { CreateKeys(); byte[] encrytpedData = AliceSendsData("secret message"); BobReceivesData(encrytpedData); Console.Read(); } private static void CreateKeys() { aliceKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256); bobKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256); alicePubKeyBlob = aliceKey.Export(CngKeyBlobFormat.EccPublicBlob); bobPubKeyBlob = bobKey.Export(CngKeyBlobFormat.EccPublicBlob); } private static byte[] AliceSendsData(string message) { Console.WriteLine("Alice sends message: {0}", message); byte[] rawData = Encoding.UTF8.GetBytes(message); byte[] encryptedData = null; using (var aliceAlgorithm = new ECDiffieHellmanCng(aliceKey)) using (CngKey bobPubKey = CngKey.Import(bobPubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { byte[] symmKey = aliceAlgorithm.DeriveKeyMaterial(bobPubKey); Console.WriteLine("Alice creates this symmetric key with " + "Bobs public key information: {0}", Convert.ToBase64String(symmKey)); using (var aes = new AesCryptoServiceProvider()) { aes.Key = symmKey; aes.GenerateIV(); using (ICryptoTransform encryptor = aes.CreateEncryptor()) using (MemoryStream ms = new MemoryStream()) { // create CryptoStream and encrypt data to send var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); // write initialization vector not encrypted ms.Write(aes.IV, 0, aes.IV.Length); cs.Write(rawData, 0, rawData.Length); cs.Close(); encryptedData = ms.ToArray(); } aes.Clear(); } } Console.WriteLine("Alice: message is encrypted: {0}", Convert.ToBase64String(encryptedData)); ; Console.WriteLine(); return encryptedData; } private static void BobReceivesData(byte[] encryptedData) { Console.WriteLine("Bob receives encrypted data"); byte[] rawData = null; var aes = new AesCryptoServiceProvider(); int nBytes = aes.BlockSize >> 3; byte[] iv = new byte[nBytes]; for (int i = 0; i < iv.Length; i++) iv[i] = encryptedData[i]; using (var bobAlgorithm = new ECDiffieHellmanCng(bobKey)) using (CngKey alicePubKey = CngKey.Import(alicePubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { byte[] symmKey = bobAlgorithm.DeriveKeyMaterial(alicePubKey); Console.WriteLine("Bob creates this symmetric key with " + "Alices public key information: {0}", Convert.ToBase64String(symmKey)); aes.Key = symmKey; aes.IV = iv; using (ICryptoTransform decryptor = aes.CreateDecryptor()) using (MemoryStream ms = new MemoryStream()) { var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write); cs.Write(encryptedData, nBytes, encryptedData.Length - nBytes); cs.Close(); rawData = ms.ToArray(); Console.WriteLine("Bob decrypts message to: {0}", Encoding.UTF8.GetString(rawData)); } aes.Clear(); } } } } In this program I believe the client is Alice and the server is Bob. I have to split this program into two parts. I am having a hard time understanding it and if I give it a try most likely I will make it work. Anyways how can I split this program into a server side code and client side code. I know how to send bytes between server and client. But I don't want to make it work without understanding what is going on. maybe you guys can show me an easier example. EDIT I managed to separate the code: here is the server code (the ip address of my computer happened to be 192.168.0.120) : using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Sockets; using System.Net; using System.Security.Cryptography; using System.IO; namespace ServerListener { class Program { static TcpListener server; //static CngKey aliceKey; static CngKey bobKey; static byte[] alicePubKeyBlob; static byte[] bobPubKeyBlob; static void Main(string[] args) { CreateKeys(); IPAddress ipAddress = IPAddress.Parse("192.168.0.120"); server = new TcpListener(ipAddress, 54540); server.Start(); var client = server.AcceptTcpClient(); var stream = client.GetStream(); alicePubKeyBlob = new byte[bobPubKeyBlob.Length]; stream.Read(alicePubKeyBlob, 0, alicePubKeyBlob.Length); stream.Write(bobPubKeyBlob, 0, bobPubKeyBlob.Length); byte[] encrytpedData = new byte[32]; stream.Read(encrytpedData, 0, encrytpedData.Length); BobReceivesData(encrytpedData); } private static void CreateKeys() { //aliceKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256); bobKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256); //alicePubKeyBlob = aliceKey.Export(CngKeyBlobFormat.EccPublicBlob); bobPubKeyBlob = bobKey.Export(CngKeyBlobFormat.EccPublicBlob); } private static void BobReceivesData(byte[] encryptedData) { Console.WriteLine("Bob receives encrypted data"); byte[] rawData = null; var aes = new AesCryptoServiceProvider(); int nBytes = aes.BlockSize >> 3; byte[] iv = new byte[nBytes]; for (int i = 0; i < iv.Length; i++) iv[i] = encryptedData[i]; using (var bobAlgorithm = new ECDiffieHellmanCng(bobKey)) using (CngKey alicePubKey = CngKey.Import(alicePubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { byte[] symmKey = bobAlgorithm.DeriveKeyMaterial(alicePubKey); Console.WriteLine("Bob creates this symmetric key with " + "Alices public key information: {0}", Convert.ToBase64String(symmKey)); aes.Key = symmKey; aes.IV = iv; using (ICryptoTransform decryptor = aes.CreateDecryptor()) using (MemoryStream ms = new MemoryStream()) { var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write); cs.Write(encryptedData, nBytes, encryptedData.Length - nBytes); cs.Close(); rawData = ms.ToArray(); Console.WriteLine("Bob decrypts message to: {0}", Encoding.UTF8.GetString(rawData)); } aes.Clear(); } } } } and here is the client code: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Sockets; using System.Net; using System.Security.Cryptography; using System.IO; namespace ClientAlice { class Program { static CngKey aliceKey; //static CngKey bobKey; static byte[] alicePubKeyBlob; static byte[] bobPubKeyBlob; static void Main(string[] args) { CreateKeys(); bobPubKeyBlob = new byte[alicePubKeyBlob.Length]; TcpClient alice = new TcpClient("192.168.0.120", 54540); var stream = alice.GetStream(); stream.Write(alicePubKeyBlob, 0, alicePubKeyBlob.Length); stream.Read(bobPubKeyBlob, 0, bobPubKeyBlob.Length); byte[] encrytpedData = AliceSendsData(":)"); stream.Write(encrytpedData, 0, encrytpedData.Length); } private static void CreateKeys() { aliceKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256); //bobKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256); alicePubKeyBlob = aliceKey.Export(CngKeyBlobFormat.EccPublicBlob); //bobPubKeyBlob = bobKey.Export(CngKeyBlobFormat.EccPublicBlob); } private static byte[] AliceSendsData(string message) { Console.WriteLine("Alice sends message: {0}", message); byte[] rawData = Encoding.UTF8.GetBytes(message); byte[] encryptedData = null; using (var aliceAlgorithm = new ECDiffieHellmanCng(aliceKey)) using (CngKey bobPubKey = CngKey.Import(bobPubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { byte[] symmKey = aliceAlgorithm.DeriveKeyMaterial(bobPubKey); Console.WriteLine("Alice creates this symmetric key with " + "Bobs public key information: {0}", Convert.ToBase64String(symmKey)); using (var aes = new AesCryptoServiceProvider()) { aes.Key = symmKey; aes.GenerateIV(); using (ICryptoTransform encryptor = aes.CreateEncryptor()) using (MemoryStream ms = new MemoryStream()) { // create CryptoStream and encrypt data to send var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); // write initialization vector not encrypted ms.Write(aes.IV, 0, aes.IV.Length); cs.Write(rawData, 0, rawData.Length); cs.Close(); encryptedData = ms.ToArray(); } aes.Clear(); } } Console.WriteLine("Alice: message is encrypted: {0}", Convert.ToBase64String(encryptedData)); ; Console.WriteLine(); return encryptedData; } } } I thinks it is pretty secure. Every time it sends a different byte array although sending the same info! A: Posting as an answer since it would be too long for a comment - it isn't specifically answering your question though. As mentionned in the comment by driis, you should really rely on existing solutions which are regarded as being secure. That said, your protocol does have security issues: * *Communication is usually two-way, you however only seem to address one-way communication (client to server). This doesn't make much sense, since you say that you're going to use TCP, which is a two-way protocol in itself. *Steps 4 and 5 are buggy: since you send the public key of the client inside the message, anyone could create a pair and encrypt the client identification using this pair. From your description the server has no forward knowledge of the client's keys, which makes this signature do nothing but ensure the integrity of the message - specifically is does not in any way make the client identification trustworthy. For proper identification, you do have additional prerequisites; the server has to know the client's public key in advance or it has to be able to trust the client's claim to be himself by using a trusted 3rd party. This is what certificates and the certificate trust chains are about: if that client presents a certificate issued by the 3rd party X and the server trusts X, then he can assume that the client is who he pretends to be. SSL basically supports two modes: * *Either only the server identity is verified and any client can communicate with it; the client's identity is not verified, only that (after the connection has been negotiated) it always is the same client which communicates to the server. This is the typical usage for online shopping etc. - you (as the client) trust the server and create a trusted connection, but the server does not know who you are. *Two-way authentification can be done as well by using client certificates. The server has to know and trust either the client certificate directly or the issuer of the client certificate in order to negotiate the connection successfully. In this scenario, the server does indeed know who the client is, but the prerequisite as mentioned above has to be met. A: As you note, you are a beginner at crypto. If this is a fun toy project to learn about crypto, great. If this is real production code you are going to implement it insecurely. You should be using off-the-shelf tools like SSL/HTTPS/whatever to solve this problem rather than doing it wrong yourself. I'll take this opportunity to point out areas where your sketch is fatally weak. 3) the client get's the server's public key. OK. How? This is the most important step. The security of the entire system relies upon this step, and you have completely glossed over how it works. How does the client obtain the public key of the server? What stops an evil person from calling up the client and saying "hey client, I'm the server. Here's my public key!" And now the client is encrypting messages that can only be decrypted by the evildoer. The evildoer has the real server's public key, so the evildoer re-encrypts the message with the real public key and sends it on. Your whole system is thereby compromised. The public key cryptosystem is only secure if there is a secure key exchange mechanism. (And a reasonable question then is: if you have a secure key exchange mechanism, why not simply use it to exchange the message in the first place?) 4) since the server needs to be certain that the message comes from that specific client then the client will encrypt his name (signature) with his private key. The client should encrypt a hash of the entire message as the signature, not just a part of the message. That way the server has evidence that the whole message was from the client. 6) the client will encrypt the message with the public key from the server. client will then send that message to the server. This is extremely inefficient. Better is for the server and client to agree upon a key to a symmetric cryptosystem. The key can be transmitted between the server and the client using the public key cryptosystem. The server and client now have a shared secret key that they can use for this communication session. 9) lastly, the server will decrypt the client signature with the public key that was contained on the message to verify that the message is from that client. How on earth does that help anything? I want to send you a message. You want to know who it comes from. So I send you a photocopy of my drivers license, so you can compare the signature on the license with the signature on the message. How do you know I sent you my drivers license and not a photocopy of someone else's? This doesn't solve the client authentication problem at all. Again, you need to solve the key distribution problem. The system depends on there being a secure key distribution infrastructure, which you have not specified.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539984", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How to get value in a textbox from a JSF page to a Java Class? I already created the bean, and it gets the value from the textbox, my problem is how can i pass it to another java class? A: Just pass it as method argument the usual Java way. You can do it in the action method. E.g. <h:form> <h:inputText value="#{bean.input}" /> <h:commandButton value="Submit" action="#{bean.submit}" /> </h:form> with private String input; // +getter +setter public void submit() { YourAnotherClass yourAnotherClass = new YourAnotherClass(); yourAnotherClass.process(input); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7539985", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Howto define a buffer for IA32 sys_read call I'm having trouble using the sys_read system call from an IA32 Assembler program on Linux. What is the correct way to define a buffer? This is the relevant part of what I have so far: movl $(SYS_read), %eax movl $(STDIN), %ebx movl BUFFADDR, %ecx movl 2, %edx int $0x80 movl $eax, $ebp // number of read bytes where SYS_read and STDIN are defined at the beginning. Where is the correct place to set up the buffer? (BUFFADDR in the pasted code). Are there any I/O libraries for IA32 Assembler? Or is that the easiest way to read a value from Stdin? I couldn't find a working example performing such an operation, I hope someone can help. A: A "BUFFADDR" is just the address of some region of memory that is large enough to hold the data being read (so two bytes in your case). There are basically two places you can get memory from: the current stack or the heap. For a small buffer you can probably allocate off the stack (just bump the stack pointer to reserve some space), for the heap, see the 'brk' system call. Here's some details about stack frames (includes stuff about argument passing that you don't need yet, though): http://www.cs.mun.ca/~rod/winter2004/cs3724/notes/frame.html If you want IO libraries, then pretty much by definition you don't want assembler. The IO library you're looking for is the C library.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to see core data tables and how to delete the data from a real device Two questions about Core Data: 1. Is it possible to see the actual data(the db tables) that is stored when using core data? 2. When using the iPhone simulator i can delete the core data db by resetting the simulator. But how can i delete the core data db when using a real device? A: Your Mac comes with a command line tool sqlite3. You can use it to do queries against the core data database. Not sure if that violates any rules against reverse engineering that might exist in any license agreements. You can delete the db for convenience during development by deleting your app from the device and reinstalling it. If you don't want to do it by deleting the app, you will have to write some code in your app to delete it I think. A: You can directly view an sqlite store using any sqlite tool including the command line sqlite3 tool. However, (1) Core Data uses a custom undocumented schema so looking at the store doesn't tell you much and (2) the structure of the sqlite store file itself has little relationship to how the managed objects behave in memory. Core Data isn't an sql wrapper. It just takes the managed objects apart to store them in SQL. SQL is just an option and Core Data works fine without it. To "delete the core data db" you simply delete the persistent store file. Look where you initialize the persistentStoreCoordinator (in the Xcode templates, it's in the app delegate.) The URL for the persistent store/s will be there. Just close down the Core Data stack and then delete the store file with NSFileManager. Then restart the Core Data stack.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539994", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ray Tracing using k-d trees for stanford bunny model I am trying to ray trace the Stanford bunny model which is PLY format. I have a parser which parses the PLY file and gives me the value of co-ordinates of triangles and also their vertices. Now I am confused as to how to proceed ahead. Should I put these triangle vertices in a vector and then pass them to build a k-d tree? Also does someone have a tutorial or a sample source code where a ply model is passed to the k-d tree and the k-d tree is then traversed to ray trace the scene? If anybody has a sample code which they can share, pls let me know. Thanks. A: PLY is a file format for objects described as a collection of polygons. A KD Tree is an optimisation structure designed to speed up rendering times by eliminating unnecessary intersection tests. So you need to: * *Define your own data structures for representing objects as a collection of points and a collection of polygons (which refer to the points). *Write a loader which uses the parser to read an object in PLY format, and constructs an instance of your polygon type. *Define a KD Tree data structure. *Write a KD Tree builder which iterates through the polygons which comprise your object and constructs a KD Tree. *Extend your ray-tracer to use the KD Tree. Use google to find more info and sample code for KD Trees. The standard paper is by Vlastimil Havran which is available on-line.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539995", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Handling max(ID) in a concurrent environment I am new to web application programming and handling concurrency using an RDBMS like SQL Server. I am using SQL Server 2005 Express Edition. I am generating employee code in which the last four digits come from this query: SELECT max(ID) FROM employees WHERE district = "XYZ"; I am not following how to handle issues that might arise due to concurrent connections. Many users can pick same max(ID) and while one user clicks "Save Record", the ID might have already been occupied by another user. How to handle this issue? A: Here are two ways of doing what you want. The fact that you might end up with unique constraint violation on EmpCode I will leave you to worry about :). 1. Use scope_identity() to get the last inserted ID and use that to calculate EmpCode. Table definition: create table Employees ( ID int identity primary key, Created datetime not null default getdate(), DistrictCode char(2) not null, EmpCode char(10) not null default left(newid(), 10) unique ) Add one row to Employees. Should be done in a transaction to be sure that you will not be left with the default random value from left(newid(), 10) in EmpCode: declare @ID int insert into Employees (DistrictCode) values ('AB') set @ID = scope_identity() update Employees set EmpCode = cast(year(Created) as char(4))+DistrictCode+right(10000+@ID, 4) where ID = @ID 2. Make EmpCode a computed column. Table definition: create table Employees ( ID int identity primary key, Created datetime not null default getdate(), DistrictCode char(2) not null, EmpCode as cast(year(Created) as char(4))+DistrictCode+right(10000+ID, 4) unique ) Add one row to Employees: insert into Employees (DistrictCode) values ('AB') A: It is a bad idea to use MAX, because with a proper locking mechanism, you will not be able to insert rows in multiple threads for the same district. If it is OK for you that you can only create one user at a time, and if your tests show that the MAX scales up even with a lot of users per district, it may be ok to use it. Long story short, dealing with identies, as much as possible, you should rely on IDENTITY. Really. But if it is not possible, one solution is to handle IDs in a separate table. Create Table DistrictID ( DistrictCode char(2), LastID Int, Constraint PK_DistrictCode Primary Key Clustered (DistrictCode) ); Then you increment the LastID counter. It is important that incrementing IDs is a transaction separated to the user creation transaction if you want to create many users in parallel threads. You can limit to have only the ID generation in sequence. The code can look like this: Create Procedure usp_GetNewId(@DistrictCode char(2), @NewId Int Output) As Set NoCount On; Set Transaction Isolation Level Repeatable Read; Begin Tran; Select @NewId = LastID From DistrictID With (XLock) Where DistrictCode = @DistrictCode; Update DistrictID Set LastID = LastID + 1 Where DistrictCode = @DistrictCode; Commit Tran; The Repeatable Read and XLOCK keywords are the minimum that you need to avoid two threads to get the same ID. If the table does not have all districts, you will need to change the Repeatable Read into a Serializable, and fork the Update with a Insert. A: This can be done through Transaction Isolation Levels. For instance, if you specify SERIALIZABLE as the level then other transactions will be blocked so that you aren't running into this problem. If I did not understand your question correctly, please let me know.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to prevent an application from being uninstalled? I'm developing an application for parents to watch out for their children. So this application cannot be removed by the child. I need to know how to make it uninstallable or the user need password to remove that application. A: I've only seen one app that does this, its called Prey and is used to track lost phones and computers. The project is open source so you could go through their code and see how they do it or contact the developer and maybe they'll tell you how they do it. A: Ankur, I think the closest thing to what your looking for is the Device Administration feature introduced in 2.2. Once the application is registered as a Device Administrator, it can't be uninstalled unless its unregistered. This will prevent the app from being uninstalled. While the Device Admin API doesn't allow for password protection of this particular feature, you can password protect your application to prevent someone from tampering with the Device Admin features in the app. I use an app called SeekDroid that has a similar functionality.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "37" }
Q: How to highlight occurrences of a search term in text in Visual Studio editor for C++? hello I have Visual Studio 2008 Express edition, I found some add-ins like metalscroll and rockscroll and even installed, but I can't find how to use those add-ins, I thought it might be automatically, I mean highlighting, but it doesn't work for my version, any ideas why? thanks in advance A: Quote from metalscroll's home page: The add-in works with Visual Studio 2005 and 2008 (Express versions not supported, since they don't allow add-ins). VS 2010 will not be supported, but Microsoft has released an add-in pack called Productivity Power Tools which provides the same functionality. You can forget about installing add-ins in Express editions of Visual Studio. They simply are not supported. Money spending time :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7540005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: delete a node or triple using dotenetrdf librery? I have an n3 file formate and i want to delete a node or triple from it how can i do it? should i use sparql query?please help me i want to have an n3 file and want to delete a node from it. i pass a graph that use in my parent form to this delete form and want to work with this graph that i create from an n3 file i mean i read this n3 file and convert it to a graph and send it to this form. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using VDS.RDF; using VDS.RDF.Parsing; using VDS.RDF.Query; using System.IO; using System.Windows; using System.Runtime.InteropServices; using VDS.RDF.Writing; namespace WindowsFormsApplication2 { public partial class delete : Form { Graph gra = new Graph(); public delete(Graph initialValue) { InitializeComponent(); ValueFromParent = initialValue; } private void delete_Load(object sender, EventArgs e) { } public Graph ValueFromParent { set { this.gra = value; } } } } A: From the documentation on Working with Graphs please see the section titled Asserting and Retracting triples which makes mention of the Assert() and Retract() methods which can be used to do what you've asked. For example to delete a specific Triple: //Assuming you already have the triple to delete in a variable t g.Retract(t); Or perhaps more usefully deleting all Triples that match a specific Node: g.Retract(g.GetTriplesWithSubject(g.CreateUriNode(new Uri("http://example.org")))); If you aren't sure whether a specific Node exists you can do something like the following: INode n = g.GetUriNode(new Uri("http://example.org")); //If n is null then the specified Node does not exist in the Graph if (n != null) { g.Retract(g.GetTriplesWithSubject(n)); } Note that you can't directly delete a Node from the Graph other than by removing all Triples that have it in the Subject/Object position. Also note that this does not remove it from the collection provided by the Nodes property of the Graph currently. Yes you can also do this via SPARQL but for just removing a few triples that is very much overkill unless you need to remove triples based on some complex criteria which is not easily expressed directly using API selection and retraction methods.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: any way to detect iPads or iPhones on wireless network? bonjour? I am trying to detect Apple devices connected to a wireless network. This is relatively simple using Bonjour, however I am also trying to detect what kind of device it is. Like, a MacBook Air, a MacBook Pro, a MacPro, an iPhone, iPod, or an iPad. I have found that Bonjour requests to MacBook's and MacPros include an "ADDITIONAL SECTION" response to the query which includes the model: ;; ADDITIONAL SECTION: Q9550._device-info._tcp.local. 10 IN TXT "model=MacPro3,1" and ;; ADDITIONAL SECTION: Air._device-info._tcp.local. 10 IN TXT "model=MacBookAir4,2" From testing an iPhone (3GS and 4), an iPod touch, and an iPad2, all of the iDevices only respond with their name: ;; ANSWER SECTION: 111.1.168.192.in-addr.arpa. 10 IN PTR gmPad2.local. Clearly, the name may not reflect the device. So, I would not like to try to extrapolate the type of device from the name. Does anyone know any other ways to detect iDevice types? Edit: just to be clear, the command I am using is: dig @224.0.0.251 -p5353 -x 192.168.1.111 ... substituting the IP address of the Apple device A: Use port 62078 The most reliable indicator I have seen is whether you can connect to IP port 62078. Port 62078 is used for the "iphone-sync" service, and I don't think MacBooks use it. This port always appears to be open for the iPhones and iPads on our (very small) network. Possibly (but not probably) there are messages you can send to the port to sniff out more details... I think the official xml list of port assignements is here, although it wasn't working for me just now: http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xml MAC address In theory the MAC addresses might help - but probably not much use unless you can find somewhere that maintains a reliable list of ranges (e.g. a network security firm, or hardware provider). MAC addresses do depend on the actual chips used (or a flashed MAC). The database is at the organisation level (although organisations sometimes choose to use specific ranges for specific devices). http://standards.ieee.org/develop/regauth/oui/public.html allows you to download the database of "Organizationally Unique Identifiers", or you can look up "Apple", or the first three bytes of a MAC address e.g. 00264A. Anecdotally, the MAC lookup doesn't work... First three digits of my iPad MAC are 28-68-BA and that comes up with nothing. User agent Probably not useful, but if you can watch the network traffic or have an http proxy, then the user-agent string could help (see http://developer.apple.com/library/IOS/documentation/AppleApplications/Reference/SafariWebContent/OptimizingforSafarioniPhone/OptimizingforSafarioniPhone.html#//apple_ref/doc/uid/TP40006517-SW3). Edit (added): Apple’s Bonjour protocol relies on Multicast DNS (mDNS) operating at UDP port 5353 and sends to these reserved group addresses: IPv4 Group Address - 224.0.0.251, IPv6 Group Address - FF02::FB - reference. This would help get push notification when Apple devices connect to a local network (link-local) by listening for multicast messages on 5353 UDP. Perhaps sniff the packet and see if it has any extra information in it :) Although I presume that Bonjour API also allows for seeing this... A: You can also use the airport utility to do this manually : 1) open AirportUtility 2) Go to "Wireless Clients" (hover mouse by the arrow and click it) 3) Go to DHCP Clients, and you will see iPad,iPhone, computer name, etc.... as the Client ID column.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: C# Getting List of Directories Using TreeView Node Information I have couple of nodes in a Tree-view that user can drag to create child nodes etc. I am using couple of methods to retrieve the parent node list: private static IList<Node> BuildParentNodeList(AdvTree treeView) { IList<Node> nodesWithChildren = new List<Node>(); foreach (Node node in treeView.Nodes) AddParentNodes(nodesWithChildren, node); return nodesWithChildren; } private static void AddParentNodes(IList<Node> nodesWithChildren, Node parentNode) { if (parentNode.Nodes.Count > 0) { nodesWithChildren.Add(parentNode); foreach (Node node in parentNode.Nodes) AddParentNodes(nodesWithChildren, node); } } Then, on the parent node I use an extension method to get all the descendant nodes: public static IEnumerable<Node> DescendantNodes(this Node input) { foreach (Node node in input.Nodes) { yield return node; foreach (var subnode in node.DescendantNodes()) yield return subnode; } } Here's a typical arrangement of my nodes: Computer Drive F Movies Music Enrique Michael Jackson Videos I need a string representation of the path of every node that has child nodes. E.g: Computer\DriveF Computer\DriveF\Movies\ Computer\DriveF\Music\ Computer\DriveF\Music\Enrique Computer\DriveF\Music\Michael Jackson Computer\DriveF\Music\Michael Jackson\Videos I am having problem getting this exact representation using the above methods. Any help will be much appreciated. Thanks. A: This worked for me: private void button1_Click(object sender, EventArgs e) { List<string> listPath = new List<string>(); GetAllPaths(treeView1.Nodes[0], listPath); StringBuilder sb = new StringBuilder(); foreach (string item in listPath) sb.AppendLine(item); MessageBox.Show(sb.ToString()); } private void GetAllPaths(TreeNode startNode, List<string> listPath) { listPath.Add(startNode.FullPath); foreach (TreeNode tn in startNode.Nodes) GetAllPaths(tn, listPath); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7540020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Modify array with jQuery to get sequenced indexes This javascript array contains coordinates that I send to Google Maps API to draw a path in the map. Sometimes coordinates[0] is empty because it depends on a previous route that might exist or not (using Google Maps). This is my code: coordinates = []; (between here I look for a previous path (coordinates[0]). In this case we are asuming that it is null. So we have these values: coordinates[1] = '50,20'; //route 1 coordinates[2] = '10,18'; //route 2 coordinates[3] = '27,34'; //route 3 After that, I draw the path in the map like this: travel_path = new google.maps.Polyline({ path: coordinates }); travel_path.setMap(map); The problem: When there is no coordinates[0] (that happens when there is no previous segment of the travel path) the .Polyline method throws an error because it needs to receive an array with sequenced indexes starting from 0. The question: How can I convert my original array to this (compare indexes): coordinates[0] = '50,20'; //route 1 coordinates[1] = '10,18'; //route 2 coordinates[2] = '27,34'; //route 3 A: coordinates.shift() removes the first element from the array. var coordinates = []; //coordinates[0] = undefined; coordinates[1] = '50,20'; //route 1 coordinates[2] = '10,18'; //route 2 coordinates[3] = '27,34'; //route 3 coordinates.shift(); coordinates.shift() causes this to happen: coordinates[0] = coordinates[1]; coordinates[1] = coordinates[2]; coordinates[2] = coordinates[3]; //coordinates[3] is removed. A: Like rob said, use shift(), you can do a check to see if coordinates[0] is undefined first. if( !coordinates[0] ) coordinates.shift(); A: You can do it by using slice: coordinates.slice(1); See it in action. A: Use: travel_path = new google.maps.Polyline({ path:(function(){ var arrayCoord=[],k=0; for(var key in coordinates){ arrayCoord[k]=coordinates[key]; ++k; } return arrayCoord; })() }); travel_path.setMap(map);
{ "language": "en", "url": "https://stackoverflow.com/questions/7540021", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: wprintw: In ncurses, when writing a newline-terminated line of exactly the same width as the window, two newlines are printed I've just finished working through the code of a CLI program, converting it into a TUI program using ncurses. It tests the user on a collection of questions and answers in a flash card-like way. All went relatively smoothly except that I have replaced many printf() calls with a popupinfo(int colour,char * title, char * body) function to pop up a window. This function uses these functions: int textwidth (char * text);//returns the width of a given string (which may include newlines) in chars when displayed without wrapping (for purposes of determining optimum window width) int textheight (char * text, int width);//returns the height of a given string (which may include newlines) in lines when displayed wrapped to the given width (for purposes of determining optimum window width) to calculate the size of the window before using wprintw() to print to that window. The problem I have is that when the length of a line other than the last line is exactly equal to the window width (or a multiple of the window width), one or more lines of text will be omitted from the window. For example: Answer: Foobarbaz. will print correctly, but in: Answer: Foo. The 'Foo.' is not printed. I believe this is because the wprintw() function moves the cursor to a new line after printing (window_width) chars, but then encounters the newline character that was at the end of the line it just printed as well. Does anyone know of a way (short of writing an entire function to handle output myself) to stop this happening? Useful details: I'm replacing: printf("\nSorry, the correct answer is:\n\n\t%s\n\n",currententry->answer); with: sprintf(passingstring,"The correct answer is:\n\n%s",currententry->answer); popupinfo(3,"Sorry!",passingstring); popupinfo is defined as: void popupinfo(int colour,char * title,char * message)//pops up a window with the given colour, title and text { WINDOW * wbpopup = NULL, * wpopup = NULL; PANEL * ppopup = NULL; int width, height; width=textwidth(message); getmaxyx(stdscr,nlines,ncols); if (width>ncols-16)width=ncols-16; height=textheight(message,width)+4; width+=8; if (!(wbpopup = newwin(height,width,(nlines-height)/2,(ncols-width)/2))) outofmemory(); ppopup = new_panel(wbpopup); wattrset(wbpopup,COLOR_PAIR(colour)); werase(wbpopup); wbkgd(wbpopup,COLOR_PAIR(colour)); box(wbpopup,0,0); windowtitle(wbpopup,title); wpopup = innerwindow(wbpopup); wprintw(wpopup,message); update_panels(); doupdate(); wgetch(wpopup); delwin(wpopup); del_panel(ppopup); delwin(wbpopup); update_panels(); doupdate(); } Also useful: int textwidth (char * text)//returns the width of a given string (which may include newlines) in chars when displayed without wrapping (for purposes of determining optimum window width) { int i=0,j=0,k=0; while (text[i]!='\0') { if (text[i]=='\n') { k=j>k?j:k; j=0; } else j++; i++; } k=j>k?j:k; return k; } and int textheight (char * text, int width)//returns the height of a given string (which may include newlines) in lines when displayed wrapped to the given width (for purposes of determining optimum window width) { int i=0,j=0,k=1; while (text[i]!='\0') { if (text[i]=='\n') { k++; j=0; } else j++; if (j>width) { k++; j=1; } i++; } return k; } Other functions: WINDOW * innerwindow(WINDOW * outerwindow);//creates an area within another window for purposes of displaying text with a margin void windowtitle(WINDOW * window, char * title);//writes the given string to the given window (top centre) For anything further, see full source for the CLI and ncurses versions, which can be found at http://github.com/megamasha A: You are absolutely right when you say: I believe this is because the wprintw() function moves the cursor to a new line after printing (window_width) chars, but then encounters the newline character that was at the end of the line it just printed as well. Regarding your question Does anyone know of a way (short of writing an entire function to handle output myself) to stop this happening? - there is no such way, because what you observe is how line wrapping works in ncurses. What you could do is making the popup window one character wider, thus avoiding the wrapping that is due to reaching the width of the window, for example by changing the line width+=8; to width+=8+1; in popupinfo.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: File Descriptors and System Calls I am doing merging k-sorted streams using read write system calls. After having read the first integers out of the files and sorting them, the file having the smallest element should be accessed again. I am not sure how to do this. I thought I can use a structure like: struct filePointer { int ptr; int num; }fptr[5]; Can someone tell me how to do this. Thanks A: Although reading integers one-by-one is not an efficient way of doing this, I will try to write the solution that you are looking for. however this is not a real implementation, just the idea. Your structure should be like this: struct filePointer { FILE * fp; int num; } fptr[k]; /* I assume k is constant, known at compile time */ You need to have an priority queue ( http://en.wikipedia.org/wiki/Priority_queue ) and prioities are determined accourding to num. First read the first numbers from all files and insert them to priority queue (pq). Then while pq is not empty, pop the first element which holds the smallest integer compared to other elements in the pq. Write the integer that first element holds to file. Using the file pointer (fp) try to read new integer from the input file. If EOF (end of file), then do nothing else insert the new element to pq by setting num to the read one. When the loop is finished, close all files and you will have a new file that contains all the elements from the input files and it will be sorted. I hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cannot download to Hard Drive using ftp_get() Is it possible to download to my Hard Drive (as opposted to my remote server) using PHP's ftp_get? The download using ftp_get() is successful, however, the file that I downloaded from my remote server is being downloaded to the directory of my php script. I'm not surprised by any means,but I would like to know how I can change the download directory to a specific location on my hard drive - say, the "C:\" drive for example. The below code was take from php.net but this is exactly how my code is setup as well: <?php // define some variables $local_file = 'local.rar'; $server_file = 'server.rar'; // set up basic connection $conn_id = ftp_connect($ftp_server); // login with username and password $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); // try to download $server_file and save to $local_file if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) { echo "Successfully written to $local_file\n"; } else { echo "There was a problem\n"; } // close the connection ftp_close($conn_id); ?> Thank you for any help, Evan A: To download the file locally, your PHP script needs to send the appropriate headers and then echo out the file's contents. However, this can only happen if you have not yet caused any other output from the PHP script (via echo or otherwise). This code should cause your browser to open a file save window or download it to the default location. // try to download $server_file and save to $local_file if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) { // Don't echo output here... //echo "Successfully written to $local_file\n"; // You've downloaded the file into `$local_file` on your server. // Now send it to the browser: header("Content-type: application/x-rar-compressed"); // Also helps to send Content-length header("Content-length: " . filesize($local_file)); // Dump out the file contents echo file_get_contents($local_file); // Delete it from the server unlink($local_file); // Always exit when you're done exit(); } else { echo "There was a problem\n"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7540031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# Little library with DataGrid control I need to create a little library that has the DataGrid control as frontend. In fact this library will have just 2 columns: Filename;FileProperty The filenames will be scanned again on each application start, the FileProperty column will be filled at runtime (if my application did an action the file) and should then be also be shown. Futhermore i also need a filtering possiblity by the Filename column. Sorting by both columns should also be possible. There will be around 10.000 datarows in the library. Persisiting / saveing data to the harddisk is not needed => everything should happen in RAM. How to do this in easiest / best / fastest way? Which structure (DataSet, DataTable, ..) gives best performance? A: The DataGrid does not need a DataSet/Table. In your case the best would be to create a DataGrid and set VirtualMode = true and handle the events from CellValueNeeded. Then you can have alle the filenames in a SortedDictionary. Use a FileSystemWatcher to update the grid with changes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }