text
stringlengths
8
267k
meta
dict
Q: Python: Using CVXOPT for quadratic programming I'm using CVXOPT to do quadratic programming to compute the optimal weights of a potfolio using mean-variance optimization. There is a great example at http://abel.ee.ucla.edu/cvxopt/userguide/coneprog.html#quadratic-programming. However, the arguments are in a regularized form (according to the author). The example is a basic version. I am looking to do a bit of a more complex problem where: min: x'Sx s.t.: x'a >= g x'1 = 0 x >= -Wb x <= c1 - Wb where: x: active weights of assets (active weight = portfolio weight - benchmark weight) S: covariance matrix of asset returns a: expected stock excess returns g: target gain Wb: weights of assets in the benchmark c: upper limit (weight) of any asset in the portfolio Assume all the variables are computed or known. The basic example presented in the documentation: min: x'Sx s.t. p'x >= g 1'x = 1 Where p are the asset returns. What I do not know (referring to the code at http://abel.ee.ucla.edu/cvxopt/examples/book/portfolio.html and optimization problem above): 1.I think these arguments setup the constraints but I'm not entirely sure: G = matrix(0.0, (n,n)) G[::n+1] = -1.0 h = matrix(0.0, (n,1)) A = matrix(1.0, (1,n)) b = matrix(1.0) 2.I believe this is part of the minimization problem in "regulated form", which I'm not sure what means: mus = [ 10**(5.0*t/N-1.0) for t in xrange(N) ] 3.What the arguments to qp are (solver.qp is the quadratic optimizer): xs = [ qp(mu*S, -pbar, G, h, A, b)['x'] for mu in mus ] Looking at the documentation, I'm pretty sure that mu*S (the first argument) is the objective function to be minimzed and -pbar are the returns. This looks like a maximization problem however (maximizing negative returns). I do not know, however how the other arguments are used. I am looking for help using the optimizer given my minimization problem and constraints above. A: I read the docs and I think you have to use the function with the following parameters. I assume that x has size n: P = S q = (0,....0) A = (1, ...... 1) b = (0) G is vertically stacked from -a +I_n -I_n where I_n is the identity matrix of size n x n . And the corresponding right hand side h is -g Wb ... Wb C1-Wb ... C1-Wb That is: one -g, n times Wb and n times C1-Wb. HTH.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572698", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Switching back to Objective-C from MonoTouch I know I'm not the first and probably many people ask similar questions here regularly and this question probably another candidate for closing votes. I'm not trying to start another round of endless holywars and I'm not asking which language is better. It's not the question of "one vs. another" series. But I need your opinion. My company recently assigned me for mobile development for iOS. Although my first and favorite language is c# I don't mind to learn new languages. And apparently I don't have problems with Objective-C. Sure, some constructs don't look very readable for my eye right now, but after a week I don't feel that the language itself is very horrible comparing to c#. And at the very beginning I decided first to learn what's the people's opinion, and there I read: How to decide between MonoTouch and Objective-C? and also here: MonoTouch & C# VS Objective C for iphone app And of course my first choice was to use Monotouch. I got a book, I downloaded a tutorial. But then I realized that one way or another I'm gonna need to learn native iOS SDK essentials, and if after sometime I'm gonna need to go deeper I'm gonna need to study samples that written rather in objective-c. * *I know MonoTouch is much better now than even half a year ago, and Miguel and his crew improving it and everyday it's just getting better. The pay for such product absolutely fair and reasonable. I don't mind spending $400 for the licence. *I understand that the real problem is not in objective-c but in foundation and CocoaTouch libraries, which will take some time to learn. *As I understood, some stuff is really difficult to play through native libraries such as XML handling, REST calls and probably some other stuff and MonoTouch could be very handy here *It's not like the older days when people were afraid that Apple would reject their apps written in MonoDevelop. Quite a big amount of apps made in MD out there in AppStore today. Sure Apple is unpredictable but it's unlikely that they start removing apps anytime soon. And even then I believe Miguel and his team will come out with solution. So, my curiosity is: how many people after using MonoTouch for sometime switched back (or considering switching back) to Objective-C and Xcode from MonoTouch? And why? What could be the reason? Is there something that could force somebody to redesign an app created in MD and rewrite it using Xcode and Objective-C?
{ "language": "en", "url": "https://stackoverflow.com/questions/7572702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Multiple marker using android and google map In my application i want to add more than two markers in a Google map. Simply I can add one marker But i don't know how can i add multiple marker. Please tell me how can i do that. A: This is a matter of having your ItemizedOverlay handle more than one marker, in your size() and createItem() methods. The size() method should return the number of markers you want and createItem() should return each OverlayItem based on the index. Here is a sample project demonstrating a map with four markers. A: If you are using a low number of markers, you can also use the same overlay class multiple times. The basic map overlay is a lot easier to use, but after a certain point, it becomes very inefficient. I used two instances of a class for a current location and a flagged location as follows: overlayList = mapView.getOverlays(); overlayList.clear(); locationOverlay = new MapOverlay(); pushpinOverlay = new MapOverlay(); Set the marker id for the png, the x offset, and the y offset here. (Functions coded in the MapOverlay class.) overlayList.add(locationOverlay); overlayList.add(pushpinOverlay); Eventually invalidate map to force a redraw. For two markers, it worked very nicely. A: You can use ItemizedOverlay to add mutiple layout. here has a sample code of ItemizedOverlay `public class YourItemizedOverlay extends ItemizedOverlay { private ArrayList<OverlayItem> myOverlays ; public YourItemizedOverlay(Drawable defaultMarker) { super(boundCenterBottom(defaultMarker)); yourOverlays = new ArrayList<OverlayItem>(); populate(); } public void addOverlay(OverlayItem overlay){ yourOverlays.add(overlay); populate(); } @Override protected OverlayItem createItem(int i) { return yourOverlays.get(i); } // Removes overlay item i public void removeItem(int i){ yourOverlays.remove(i); populate(); } @Override public int size() { return yourOverlays.size(); } public void addOverlayItem(OverlayItem overlayItem) { yourOverlays.add(overlayItem); populate(); } public void addOverlayItem(int lat, int lon, String title) { try { GeoPoint point = new GeoPoint(lat, lon); OverlayItem overlayItem = new OverlayItem(point, title, null); addOverlayItem(overlayItem); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } @Override protected boolean onTap(int index) { // TODO Auto-generated method stub String title = yourOverlays.get(index).getTitle();//display message when you touch your marker Toast.makeText(YourMapActivity.context, title, Toast.LENGTH_LONG).show(); return super.onTap(index); } }`
{ "language": "en", "url": "https://stackoverflow.com/questions/7572703", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Separate "namespaces" in HTML I'm having problems with my application due the ID collision. The application basically uses AJAX to load code snippets on user demand. These snippets are very different, but sometimes, a code snippet uses the same ID than another in a HTML tag. Imagine user asks for snippet 1 and gets this: .... <input id="myvar" type="checkbox" name="myname" /> .... This snippet is added to the main page code through JQuery.load() Then, user ask for snippet 2 and gets: .... <div id="myvar">....</div> .... At this moment, there are 2 different HTML tags with the same ID, so when the app does: $("#myvar").something() the result is undefined. So, the problem is I don't know if it's possible to split code snippets in HTML using any javascript or HTML feature or trick. It's not an option to prefix all ID on load, due each snippet has an associated javascript code to process it and needs to have access to the snippet DOM. Good news: snippets are completly isolated on the page. The page structure is like this: <html> <head>...</head> <body> <div id="header">...</div> <div id="common_controls">...</div> <div id="snippets"> <div class="snippet" id="snippet-1"> // Snippet 1 code here </div> <div class="snippet" id="snippet-2"> // Snippet 2 code here </div> </div> </body> </html> Any idea? Edit: I can't control snippets content, so it's not an option force to use specific ID names. A: It is considered invalid in HTML to have the same ID multiple times, and as you've seen it can cause issues. If you have control over the output of the Ajax code, the best solution would be to prevent it from outputting the same ID multiple times. You haven't given enough information to allow me to give you much help with exactly how to achieve this, but it should certainly be possible. If the same IDs are coming from different Ajax calls, you could ensure that all IDs produced by each Ajax call are prefixed by a unique name (possibly the module name of the piece of code producing them?). If they're coming from the same code, the only reason you should be likely to produce the same ID is if you're outputting the same piece of data multiple times onto the page. Even here there will be solutions to this, but I would need to know more about the application to help much in this case. But in either case, the problem as described seems to be with accessing it via jQuery. The good news is that jQuery is actually very forgiving of duplicated IDs. If it's just a case of getting it to work with jQuery, then you should be able to get it working without having to fix the actual duplication. As long as you can run a selector that picks the one you want uniquely, then jQuery will be quite happy. If you want to do this, simply wrap each Ajax response in a <div> with a unique ID of its own, and then you can reference the two duplicates using a nested selector as follows: $("#ajaxblock1 #myvar").something() $("#ajaxblock2 #myvar").something() This will work just fine in jQuery. I can't vouch for the same thing working well in CSS, however, and the standard DOM getElementById() function will also freak out, so if you plan to use anything other than jQuery, then you will want to de-dup your IDs. A: The best solution is to embed each code snippet in a separate IFRAME, because the ID may not be the only conflict-causing item. * *Snippets that heavily rely on the document's default CSS/script attributes may fail due conflicting scripts. *Script snippets that throw variables in the global scope may interfere with the other snippets *Script snippets that refer to a specific class index (class="specific") will also break due conflicts *Snippets containing <script> will not be executed when inserted in the HTML, while it may be important for the appearance of the snippet. Et cetera. Just embed the snippets in a scripted iframe to circumvent these possible issues. EDIT Frames can easily communicate with the parent (even cross-domain) through postMessage. When you're in the same domain, communicating is even easier. You're probably looking for an easier method to communicate between child frames. Well, consider this example (same domain only): JS: //Snippet from frame 1 var othersnippet = parent.frames["othersnippet"].contentWindow; othersnippet.getspecialMethod(); //Custom function, EXAMPLE * *parent (within the frame) = top, which refers to the Window object *window.frames is an object which refers to all frames within one document, by name. Note: "Within a document" doen't include the frames in frames) HTML: <iframe name="othersnippet" /> <!-- No id needed, because you access frames through the window.frames[name] property--> A: Just a thought: If you know that the snippets will always be above (or below) the duplicate content #id, you might be able to do something like this: if ($('#myvar').length == 1) {run function} //no offending repeat #id else {$('#myvar').eq(1) . . . } //repeating #id, refer to the second instance
{ "language": "en", "url": "https://stackoverflow.com/questions/7572704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do I get a backgroundworker to report more than just an int? I want the backgroundworker to send back some custom information to the ProgressChanged event handler, but it seems that all it can send is an int. Is there a way around this? Thanks A: Use the UserState parameter. A: The ReportProgress has an overloaded method which takes in a UserState object which can be any object. You can pass anything that inherits the object class in and then parse it on your ProgressChanged event handler. http://msdn.microsoft.com/en-us/library/system.windows.forms.toolstripprogressbar.aspx A: Another approach I was successful with is by building my own Background Worker class with some extra properties. During the background worker "DOWORK" handler, as I'm doing things, I set other properties on the object... int, string, other objects, etc.. Then, issue the ReportProgress with whatever percentage I'm dealing with... Since the background worker is passed to whatever is listening for the feedback, you can then read the values of Properties on the background worker via "get/set"
{ "language": "en", "url": "https://stackoverflow.com/questions/7572708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: VB.NET RegEx to parse valid Paths from a text file Good day, I'm attempting to parse a text file containing several Windows paths; I'd like to use regular expressions if possible, and I'm using VB.NET. The file is formatted somewhat like so: M - Network Mode C:\Client\System\ - System Path C:\Client\Products\ - Product Path C:\Client\Util\ - Utility Path C:\PROG\ - Program Path Et cetera. The first line contains a single letter before the "description"-- that is, a space, a hyphen, a space, and then a description of the field. Each successive line in the file contains a Windows path (always with trailing backslash), and similarly followed by the hyphen and description. The entire file is usually no more than 30 lines. At first, I thought to read the text of the file line-by-line and use VB's Split() method to separate the path and the description, storing the paths in one array, and the descriptions in another. Ideally, though, I'd like to make use of a regular expression to simply parse the file for the paths, and then the text after the hyphen. I'm relatively inexperienced with regex, what would be the best way to go about it? Is there perhaps a way to have the Regex return a collection of all matches, e.g., all the matches for file paths, and another for all the matches of the text after the hyphen? Thanks. A: This seems to work on your test data (?<Path>.+\\)\s\-\s(?<Description>.+) Usage: Private oRegEx as RegEx = New RegEx("(?<Path>.+\\)\s\-\s(?<Description>.+)", RegExOptions.Compiled) Public Sub DoTheMatching() Dim tInputContent as String = String.Empty ' Fill this with your file contents Dim tPath as String = String.Empty Dim tDescription As String = Stringh.EMpty For Each tMatch as Match In oRegEx.Matches(tInputContent) tPath = tMatch.Groups("Path").Value tDescription = tMatch.Groups("Description").Value Next End Sub I did not compile this, there may be typos. A: This (very simple, and subject to enhancement) regex does what you want: ^(.+\\) - (.+)$ You can apply it to each line in your log file, and then use backreferences (\1 and \2) to capture the corresponding matches (path (including the trailing backslash) and the description). This should work correctly even with "strange" filename entries like this: C:\Some - \ - WeirdPath\ - Description (\1 returns "C:\Some - \ - Filename\" and \2 returns "Description").
{ "language": "en", "url": "https://stackoverflow.com/questions/7572709", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: No block given error when executing rails and rake commands I went to generate a new controller for my rails app today, and I was confronted with a rather disturbing error. When I run rails generate controller Matches I get the following error: rails generate controller Matches /Library/Ruby/Gems/1.8/gems/actionpack-3.0.8/lib/action_dispatch/routing/mapper.rb:1075:in `member': no block given (LocalJumpError) from /Library/Ruby/Gems/1.8/gems/actionpack-3.0.8/lib/action_dispatch/routing/mapper.rb:546:in `scope' from /Library/Ruby/Gems/1.8/gems/actionpack-3.0.8/lib/action_dispatch/routing/mapper.rb:1074:in `member' from /Library/Ruby/Gems/1.8/gems/actionpack-3.0.8/lib/action_dispatch/routing/mapper.rb:1260:in `with_scope_level' from /Library/Ruby/Gems/1.8/gems/actionpack-3.0.8/lib/action_dispatch/routing/mapper.rb:1073:in `member' from /Users/max/workplace/SummerGypsy/config/routes.rb:34 from /Library/Ruby/Gems/1.8/gems/actionpack-3.0.8/lib/action_dispatch/routing/mapper.rb:1011:in `resources' from /Library/Ruby/Gems/1.8/gems/actionpack-3.0.8/lib/action_dispatch/routing/mapper.rb:1269:in `resource_scope' from /Library/Ruby/Gems/1.8/gems/actionpack-3.0.8/lib/action_dispatch/routing/mapper.rb:546:in `scope' from /Library/Ruby/Gems/1.8/gems/actionpack-3.0.8/lib/action_dispatch/routing/mapper.rb:1268:in `resource_scope' from /Library/Ruby/Gems/1.8/gems/actionpack-3.0.8/lib/action_dispatch/routing/mapper.rb:1260:in `with_scope_level' from /Library/Ruby/Gems/1.8/gems/actionpack-3.0.8/lib/action_dispatch/routing/mapper.rb:1267:in `resource_scope' from /Library/Ruby/Gems/1.8/gems/actionpack-3.0.8/lib/action_dispatch/routing/mapper.rb:1010:in `resources' from /Users/max/workplace/SummerGypsy/config/routes.rb:33 from /Library/Ruby/Gems/1.8/gems/actionpack-3.0.8/lib/action_dispatch/routing/route_set.rb:233:in `instance_exec' from /Library/Ruby/Gems/1.8/gems/actionpack-3.0.8/lib/action_dispatch/routing/route_set.rb:233:in `draw' from /Users/max/workplace/SummerGypsy/config/routes.rb:1 from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.8/lib/active_support/dependencies.rb:235:in `load' from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.8/lib/active_support/dependencies.rb:235:in `load' from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.8/lib/active_support/dependencies.rb:225:in `load_dependency' from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.8/lib/active_support/dependencies.rb:596:in `new_constants_in' from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.8/lib/active_support/dependencies.rb:225:in `load_dependency' from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.8/lib/active_support/dependencies.rb:235:in `load' from /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/application.rb:127:in `reload_routes!' from /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/application.rb:127:in `each' from /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/application.rb:127:in `reload_routes!' from /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/application.rb:120:in `routes_reloader' from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.8/lib/active_support/file_update_checker.rb:32:in `call' from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.8/lib/active_support/file_update_checker.rb:32:in `execute_if_updated' from /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/application/finisher.rb:51 from /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/application/finisher.rb:52:in `call' from /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/application/finisher.rb:52 from /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/initializable.rb:25:in `instance_exec' from /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/initializable.rb:25:in `run' from /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/initializable.rb:50:in `run_initializers' from /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/initializable.rb:49:in `each' from /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/initializable.rb:49:in `run_initializers' from /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/application.rb:134:in `initialize!' from /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/application.rb:77:in `send' from /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/application.rb:77:in `method_missing' from /Users/max/workplace/SummerGypsy/config/environment.rb:5 from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.8/lib/active_support/dependencies.rb:239:in `require' from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.8/lib/active_support/dependencies.rb:239:in `require' from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.8/lib/active_support/dependencies.rb:225:in `load_dependency' from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.8/lib/active_support/dependencies.rb:596:in `new_constants_in' from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.8/lib/active_support/dependencies.rb:225:in `load_dependency' from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.8/lib/active_support/dependencies.rb:239:in `require' from /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/application.rb:103:in `require_environment!' from /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/commands.rb:16 from script/rails:6:in `require' from script/rails:6 I have absolutely no idea what this means. I get a similar error when running rake db:migrate rake db:migrate --trace ** Invoke db:migrate (first_time) ** Invoke environment (first_time) ** Execute environment rake aborted! no block given /Library/Ruby/Gems/1.8/gems/actionpack-3.0.8/lib/action_dispatch/routing/mapper.rb:1075:in `member' /Library/Ruby/Gems/1.8/gems/actionpack-3.0.8/lib/action_dispatch/routing/mapper.rb:546:in `scope' /Library/Ruby/Gems/1.8/gems/actionpack-3.0.8/lib/action_dispatch/routing/mapper.rb:1074:in `member' /Library/Ruby/Gems/1.8/gems/actionpack-3.0.8/lib/action_dispatch/routing/mapper.rb:1260:in `with_scope_level' /Library/Ruby/Gems/1.8/gems/actionpack-3.0.8/lib/action_dispatch/routing/mapper.rb:1073:in `member' /Users/max/workplace/SummerGypsy/config/routes.rb:34 /Library/Ruby/Gems/1.8/gems/actionpack-3.0.8/lib/action_dispatch/routing/mapper.rb:1011:in `resources' /Library/Ruby/Gems/1.8/gems/actionpack-3.0.8/lib/action_dispatch/routing/mapper.rb:1269:in `resource_scope' /Library/Ruby/Gems/1.8/gems/actionpack-3.0.8/lib/action_dispatch/routing/mapper.rb:546:in `scope' /Library/Ruby/Gems/1.8/gems/actionpack-3.0.8/lib/action_dispatch/routing/mapper.rb:1268:in `resource_scope' /Library/Ruby/Gems/1.8/gems/actionpack-3.0.8/lib/action_dispatch/routing/mapper.rb:1260:in `with_scope_level' /Library/Ruby/Gems/1.8/gems/actionpack-3.0.8/lib/action_dispatch/routing/mapper.rb:1267:in `resource_scope' /Library/Ruby/Gems/1.8/gems/actionpack-3.0.8/lib/action_dispatch/routing/mapper.rb:1010:in `resources' /Users/max/workplace/SummerGypsy/config/routes.rb:33 /Library/Ruby/Gems/1.8/gems/actionpack-3.0.8/lib/action_dispatch/routing/route_set.rb:233:in `instance_exec' /Library/Ruby/Gems/1.8/gems/actionpack-3.0.8/lib/action_dispatch/routing/route_set.rb:233:in `draw' /Users/max/workplace/SummerGypsy/config/routes.rb:1 /Library/Ruby/Gems/1.8/gems/activesupport-3.0.8/lib/active_support/dependencies.rb:235:in `load' /Library/Ruby/Gems/1.8/gems/activesupport-3.0.8/lib/active_support/dependencies.rb:235:in `load' /Library/Ruby/Gems/1.8/gems/activesupport-3.0.8/lib/active_support/dependencies.rb:225:in `load_dependency' /Library/Ruby/Gems/1.8/gems/activesupport-3.0.8/lib/active_support/dependencies.rb:596:in `new_constants_in' /Library/Ruby/Gems/1.8/gems/activesupport-3.0.8/lib/active_support/dependencies.rb:225:in `load_dependency' /Library/Ruby/Gems/1.8/gems/activesupport-3.0.8/lib/active_support/dependencies.rb:235:in `load' /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/application.rb:127:in `reload_routes!' /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/application.rb:127:in `each' /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/application.rb:127:in `reload_routes!' /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/application.rb:120:in `routes_reloader' /Library/Ruby/Gems/1.8/gems/activesupport-3.0.8/lib/active_support/file_update_checker.rb:32:in `call' /Library/Ruby/Gems/1.8/gems/activesupport-3.0.8/lib/active_support/file_update_checker.rb:32:in `execute_if_updated' /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/application/finisher.rb:51 /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/application/finisher.rb:52:in `call' /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/application/finisher.rb:52 /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/initializable.rb:25:in `instance_exec' /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/initializable.rb:25:in `run' /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/initializable.rb:50:in `run_initializers' /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/initializable.rb:49:in `each' /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/initializable.rb:49:in `run_initializers' /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/application.rb:134:in `initialize!' /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/application.rb:77:in `send' /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/application.rb:77:in `method_missing' /Users/max/workplace/SummerGypsy/config/environment.rb:5 /Library/Ruby/Gems/1.8/gems/activesupport-3.0.8/lib/active_support/dependencies.rb:239:in `require' /Library/Ruby/Gems/1.8/gems/activesupport-3.0.8/lib/active_support/dependencies.rb:239:in `require' /Library/Ruby/Gems/1.8/gems/activesupport-3.0.8/lib/active_support/dependencies.rb:225:in `load_dependency' /Library/Ruby/Gems/1.8/gems/activesupport-3.0.8/lib/active_support/dependencies.rb:596:in `new_constants_in' /Library/Ruby/Gems/1.8/gems/activesupport-3.0.8/lib/active_support/dependencies.rb:225:in `load_dependency' /Library/Ruby/Gems/1.8/gems/activesupport-3.0.8/lib/active_support/dependencies.rb:239:in `require' /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/application.rb:103:in `require_environment!' /Library/Ruby/Gems/1.8/gems/railties-3.0.8/lib/rails/application.rb:218:in `initialize_tasks' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/task.rb:205:in `call' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/task.rb:205:in `execute' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/task.rb:200:in `each' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/task.rb:200:in `execute' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/task.rb:158:in `invoke_with_call_chain' /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/monitor.rb:242:in `synchronize' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/task.rb:151:in `invoke_with_call_chain' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/task.rb:176:in `invoke_prerequisites' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/task.rb:174:in `each' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/task.rb:174:in `invoke_prerequisites' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/task.rb:157:in `invoke_with_call_chain' /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/monitor.rb:242:in `synchronize' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/task.rb:151:in `invoke_with_call_chain' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/task.rb:144:in `invoke' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/application.rb:112:in `invoke_task' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/application.rb:90:in `top_level' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/application.rb:90:in `each' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/application.rb:90:in `top_level' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/application.rb:129:in `standard_exception_handling' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/application.rb:84:in `top_level' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/application.rb:62:in `run' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/application.rb:129:in `standard_exception_handling' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/application.rb:59:in `run' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/bin/rake:32 /usr/bin/rake:19:in `load' /usr/bin/rake:19 Tasks: TOP => db:migrate => environment I am running rails 3.0.8 on top of Ruby 1.8.7 (patch level 249). Does anyone have any suggestions? Thank you for your help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wait for an NSURLConnection I have code that sends away a HTTP POST connection. I want the method to wait until I get a response from the server for it to continue. The reason I am doing it this way is because I am integrating new code (asynchronous post vs the old synchronous post) into our application and I am looking for minimal change throughout the application. The old method was as follows: -(NSData*) postData: (NSString*) strData; The application would call it and send it a strData object and it would lock the main thread until it got something back. This was inefficient but it worked well, but due to timeout constraints I have to change it. So my new method (posting the complete method here) is as follows: -(NSData*) postData: (NSString*) strData { //start http request code //postString is the STRING TO BE POSTED NSString *postString; //this is the string to send postString = @"data="; postString = [postString stringByAppendingString:strData]; NSURL *url = [NSURL URLWithString:@"MYSERVERURL"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; NSString *msgLength = [NSString stringWithFormat:@"%d", [postString length]]; //setting prarameters of the POST connection [request setHTTPMethod:@"POST"]; [request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request addValue:msgLength forHTTPHeaderField:@"Content-Length"]; [request addValue:@"en-US" forHTTPHeaderField:@"Content-Language"]; [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]]; [request setTimeoutInterval:20]; //one second for testing purposes NSLog(@"%@",postString); NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self]; [connection start]; //end http request code return receivedData; //this is set by a delegate somewhere else in the code } It sends the code fine, but of course (and as expected), it does not receive it fast enough to be returned correctly. What do you recommend I can do to "stop" that method to wait to return anything until something is received? I've tried setting a while loop that waited on a BOOL that would be set to YES when all data was received, but that loop prevented the code from sending at all. I also tried throwing the contents of this method into another method and calling it to performSelectorInBackground, but of course, that didn't work either. I'm running out of ideas and I'd really appreciate the help. A: Doing any sort of synchronous comms on the main thread is a bad idea, but if you can't re-architect at this point then take a look at: +[NSURLConnection sendSynchronousRequest:returningResponse:error:] The documentation can be found here. From the discussion: A synchronous load is built on top of the asynchronous loading code made available by the class. The calling thread is blocked while the asynchronous loading system performs the URL load on a thread spawned specifically for this load request. No special threading or run loop configuration is necessary in the calling thread in order to perform a synchronous load. But seriously, take a look and how much work would be involved in performing the request asynchronously and receiving a notification when the request is complete. The whole experience for the user is going to be much better. A: You are actually performing an asynchronous request there. In order to do a synchronous request, you should use + (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error in the NSURLConnection Class. It is indeed a bad idea though to block the app while you are doing this and therefore it is usually discouraged. Cheers
{ "language": "en", "url": "https://stackoverflow.com/questions/7572713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Which image class should I use from .net to make a library more generic as possible? I'm building a library that I would like to make it as generic as possible. Specifically, I would like that it will work both on Winform and WPF (ok WPF is more important by the way). This image class must support 4 byte colors (ARGB) because I must convert it in QVGA format (is used by Lg screen of my G19 keyboard). if it supports qvga format, this is always better. If it doesn't support QVGA natively, it must support "fast" operations to copy it (byte per byte) to an array of 320x240x4 where obviusly I'll reorganize bytes in correct order. So the only image class I've used so far from C# is Bitmap, and it worked so far. However I don't think that class is used in WPF. What should I use to support, if not both WPF and winforms, at least WPF (I think it's more important). Thanks A: The Bitmap and Image classes are supported and used in WPF. Don't hesitate to use them and base your class library on them. If you want to have a generic image manipulation library that would work in WPF, WinForms, ASP.NET, Silverlight, Console applications, that's exactly the kind of classes that you need.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use perl or awk to search for numbers in a file and increase them by constant amount from the command line I have a file that has a bunch of 3-digit numbers that I need to increase by a certain amount (actually, I need to increase all numbers that are greater than a certain value by a constant amount). How can I do this as simply as possible from the command line? EDIT: To clarify, there is more text in the file than just numbers, and it's not easy to extract them as fields in awk. A: Here is an example that will take every number (well, positive integer) in a file that is greater than 400 and add 13 to it. perl -pe 's/\d+/$& > 400 ? $&+13 : $&/ge' file \d+ is the regular expression that will match any integer in your text $& is a special Perl variable that contains the text that was matched by a regular expression. In this case, it would be a number. The /e modifier tells Perl to evaluate the replacement expression. In this case, it evaluates $& > 400 ? $&+13 : $& to get a different number. The '/g' modifier replaces all instances of the regular expression (the integer) on each line. A: How about: awk '$1>300{$1+=100;print $0}' file Turns: /home/sirch>cat file 313 233 133 413 into: /home/sirch>awk '$1>300{$1+=100}1' file 413 233 133 513 A: This is probably not optimally compact, but it's the first thing I thought of: perl -e 'my $file=$ARGV[0];my $amt_to_increase=$ARGV[1]; open(my $read,"<",$file) or die $!;my @lines=<$read>;close($read); open(my $write,">","temp") or die $!; foreach(@lines){print $write $_+$amt_to_increase . "\n";} close($write);system("mv temp $file")==0 or die $!;' <file to read> <amount to add to each line> A: Assuming file has 3 digit numbers separated by newlines: $ cat file|while read number;do if [ $number -gt $minvalue ]; then echo $(($number+$constant)) else echo $number fi
{ "language": "en", "url": "https://stackoverflow.com/questions/7572741", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java: JAXB: Marshelling of JAXBElement to xs:date not correct I have a problem using JAXB. I've created my Java Classes via xjc (using an xsd-schema) and has a global binding for the XML-Datatypes xs:date xs:dateTime and xs:time to java.util.Calendar with parse and print method. Everything works fine until I marked some xs:date fields as nillable. The xjc creates JAXBElement wrappers for those properties. If these fields get unmarshaled the date is printed out including the time information which leads to validation errors. Is there a possibilty to force the Marshaller to convert it to xs:date instead of xs:dateTime? Can I specify a binding for those fields which gets a special XMLAdapater ewhich converts those fields? The property inside the Java-Class looks like that: @XmlElementRef(name = "dateField", namespace = "namespace", type = JAXBElement.class) protected JAXBElement<Calendar> dateField; and the corresponding xsd-looks like <xs:element name="dateField" minOccurs="0" nillable="true" type="xs:date" /> Can someone help me please? Thanks and best regards, Arne A: Do you really need to map the Calendar inside a JAXBElement?, wouldn't be correct to use the legacy XMLGregorianCalendar instead (and then you can convert it to a Date)?
{ "language": "en", "url": "https://stackoverflow.com/questions/7572746", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: SVG2PDF compilation problems I'm trying to compile this and having no success (Win32) using CYGWIN... make gives me a load of unreferenced functions which appear to be part of the Cairo dependency (I have the source for this and still the errors persist) Is there a binary available that I can download? Thanks Martin A: Have you actually built Cairo, or just downloaded the source? You'll need to build it first. If you have, you're probably missing a -I or -L flag, which are used to tell GCC where to look for header files and libraries. Also, could be a missing -l which specifies a library to include in the link process. Could you copy & paste some error messages?
{ "language": "en", "url": "https://stackoverflow.com/questions/7572748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to return @@Identity or Scope_Identity into C# Possible Duplicate: Retrieving the value of RETURN @@IDENTITY in C# I have a class with different methods and constructors. In SaveDB() I select @@IDENTITY but I'm not sure how to return it into C#. I see there are some other posts about this on Stack, but I don't see any direct answers for C#. Any help is appreciated. The result I'm looking for looks something like this: int mySiteUserID; mySiteUserID = 4; //4 is the Identity of the last saved SiteUser public class SiteUser { #region Fields private int siteUserID; private string siteUserFirstName; private string siteUserLastName; private string siteUserTitle; private string siteUserEmail; private string siteUserPhone; private string siteUserPassword; private int siteUserType; private int companyID; private bool siteUserActive; #endregion #region Properties public int SiteUserID { get { return siteUserID; } set { siteUserID = value; } } public string SiteUserFirstName { get { return siteUserFirstName; } set { siteUserFirstName = value; } } public string SiteUserLastName { get { return siteUserLastName; } set { siteUserLastName = value; } } public string SiteUserTitle { get { return siteUserTitle; } set { siteUserTitle = value; } } public string SiteUserEmail { get { return siteUserEmail; } set { siteUserEmail = value; } } public string SiteUserPhone { get { return siteUserPhone; } set { siteUserPhone = value; } } public string SiteUserPassword { get { return siteUserPassword; } set { siteUserPassword = value; } } public int SiteUserType { get { return siteUserType; } set { siteUserType = value; } } public int CompanyID { get { return companyID; } set { companyID = value; } } public bool SiteUserActive { get { return siteUserActive; } set { siteUserActive = value; } } #endregion #region Constructors public SiteUser() { siteUserID = 0; siteUserFirstName = ""; siteUserLastName = ""; siteUserTitle = ""; siteUserEmail = ""; siteUserPhone = ""; siteUserPassword = ""; siteUserType = 0; companyID = 0; siteUserActive = false; } public SiteUser(int PrimaryKeyValue) { string sql = @" SELECT * FROM SiteUsers WHERE SiteUserID = @PrimaryKeyValue"; SqlParameter[] parms = new SqlParameter[1]; parms[0] = new SqlParameter("@PrimaryKeyValue", PrimaryKeyValue); SqlDataReader dr = DBUtil.FillDataReader(sql, parms); while (dr.Read()) { this.siteUserID = Convert.ToInt32(dr["siteUserID"].ToString()); this.siteUserFirstName = Convert.ToString(dr["siteUserFirstName"].ToString()); this.siteUserLastName = Convert.ToString(dr["siteUserLastName"].ToString()); this.siteUserTitle = Convert.ToString(dr["siteUserTitle"].ToString()); this.siteUserEmail = Convert.ToString(dr["siteUserEmail"].ToString()); this.siteUserPhone = Convert.ToString(dr["siteUserPhone"].ToString()); this.siteUserPassword = Convert.ToString(dr["siteUserPassword"].ToString()); this.siteUserType = Convert.ToInt32(dr["siteUserType"].ToString()); this.companyID = Convert.ToInt32(dr["companyID"].ToString()); this.siteUserActive = Convert.ToBoolean(dr["siteUserActive"].ToString()); } dr.Close(); } #endregion public int SaveDB() { //db code to write record SqlConnection conn = new SqlConnection(Config.ConnectionString); string sql = ""; if (SiteUserID == 0) { //this is an insert sql = @" INSERT SiteUsers( --SiteUserID, SiteUserFirstName, SiteUserLastName, SiteUserTitle, SiteUserEmail, SiteUserPhone, SiteUserPassword, SiteUserType, CompanyID, SiteUserActive )VALUES( --@SiteUserID, @SiteUserFirstName, @SiteUserLastName, @SiteUserTitle, @SiteUserEmail, @SiteUserPhone, @SiteUserPassword, @SiteUserType, @CompanyID, @SiteUserActive ); SELECT @@IDENTITY "; } else { //this is an update //siteUserID = @siteUserID //this is an update //siteUserFirstName = @siteUserFirstName //this is an update //siteUserLastName = @siteUserLastName //this is an update //siteUserTitle = @siteUserTitle //this is an update //siteUserEmail = @siteUserEmail //this is an update //siteUserPhone = @siteUserPhone //this is an update //siteUserPassword = @siteUserPassword //this is an update //siteUserType = @siteUserType //this is an update //companyID = @companyID //this is an update //siteUserActive = @siteUserActive sql = @" UPDATE SiteUsers SET --SiteUserID = @SiteUserID, SiteUserFirstName = @SiteUserFirstName, SiteUserLastName = @SiteUserLastName, SiteUserTitle = @SiteUserTitle, SiteUserEmail = @SiteUserEmail, SiteUserPhone = @SiteUserPhone, SiteUserPassword = @SiteUserPassword, SiteUserType = @SiteUserType, CompanyID = @CompanyID, SiteUserActive = @SiteUserActive WHERE SiteUserID = @SiteUserID "; } SqlCommand cmd = new SqlCommand(sql, conn); SqlParameter siteUserIDParam = new SqlParameter("@siteUserID", SqlDbType.Int); SqlParameter siteUserFirstNameParam = new SqlParameter("@siteUserFirstName", SqlDbType.VarChar); SqlParameter siteUserLastNameParam = new SqlParameter("@siteUserLastName", SqlDbType.VarChar); SqlParameter siteUserTitleParam = new SqlParameter("@siteUserTitle", SqlDbType.VarChar); SqlParameter siteUserEmailParam = new SqlParameter("@siteUserEmail", SqlDbType.VarChar); SqlParameter siteUserPhoneParam = new SqlParameter("@siteUserPhone", SqlDbType.VarChar); SqlParameter siteUserPasswordParam = new SqlParameter("@siteUserPassword", SqlDbType.VarChar); SqlParameter siteUserTypeParam = new SqlParameter("@siteUserType", SqlDbType.Int); SqlParameter companyIDParam = new SqlParameter("@companyID", SqlDbType.Int); SqlParameter siteUserActiveParam = new SqlParameter("@siteUserActive", SqlDbType.Bit); siteUserIDParam.Value = siteUserID; siteUserFirstNameParam.Value = siteUserFirstName; siteUserLastNameParam.Value = siteUserLastName; siteUserTitleParam.Value = siteUserTitle; siteUserEmailParam.Value = siteUserEmail; siteUserPhoneParam.Value = siteUserPhone; siteUserPasswordParam.Value = siteUserPassword; siteUserTypeParam.Value = siteUserType; companyIDParam.Value = companyID; siteUserActiveParam.Value = siteUserActive; cmd.Parameters.Add(siteUserIDParam); cmd.Parameters.Add(siteUserFirstNameParam); cmd.Parameters.Add(siteUserLastNameParam); cmd.Parameters.Add(siteUserTitleParam); cmd.Parameters.Add(siteUserEmailParam); cmd.Parameters.Add(siteUserPhoneParam); cmd.Parameters.Add(siteUserPasswordParam); cmd.Parameters.Add(siteUserTypeParam); cmd.Parameters.Add(companyIDParam); cmd.Parameters.Add(siteUserActiveParam); conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); return 0; } } A: When you execute your script, use ExecuteScalar instead of ExecuteNonQuery, and convert the result to an int. The script will still have the side-effect that a row gets inserted, but it's value will be the scope identity.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Accessing Returned Javascript Variable in another Script I've got script (a) that is a javascript script in which I've go this function: function csf_viewport_bounds() { var bounds = map.getBounds(); var ne = bounds.getNorthEast(); var sw = bounds.getSouthWest(); var maxLat = ne.lat(); var maxLong = ne.lng(); var minLat = sw.lat(); var minLong = sw.lng(); var the_maps_bounds = [maxLat, maxLong, minLat, minLong]; return(the_maps_bounds); } I've also got jQuery script (b). It has a line that calls the function in (a): google.maps.event.addListener(map, 'tilesloaded', csf_viewport_bounds); How can I access the what is returned by (a), the_maps_bounds, in script (b)? Thank you. A: Just call the function a second time, since it doesn't use any parameters, and assign the result to a variable. var myStuff = csf_viewport_bounds() A: I'm presuming you want to do something after tilesloaded that involves the_maps_bounds in which case you would do something like: google.maps.event.addListener(map, 'tilesloaded', function() { // This code will only execute after event `tilesloaded` happens var the_maps_bounds = csf_viewport_bounds() // now do something with the bounds // ... }); A: Change script (b) to: var bounds = csf_viewport_bounds(); google.maps.event.addListener(map, 'tilesloaded', bounds); // csf_viewport_bounds() return saved as local variable bounds.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How can I get jQuery or Javascript to change css based on the current url? I have a navigation area in a separate file from my content, and I pull together the two using a php include. I want the navigation area links to change color based on whatever page is active, i.e. the current URL. So I want jQuery or Javascript to read the current URL (actually just the filename, like home.html), then write CSS based on that. So like, if url=home.html, change-css for nav.home.background-> blue A: I think a much better solution would be to set a class on the html tag rather than swap out a css file per page. $("html").addClass(window.location.path.split(".")[0]); and then have any custom css styles based off of that class: html.home > .nav { background-color: blue; } html.about > .nav { background-color: green; } html.contact > .nav { background-color: red; } This would only work if each page had an extension to split, that is Since you're using PHP you could do this without jQuery at all: <html class="<?php $_SERVER['PHP_SELF'] ?>"> or something like that, I know little about PHP but I'm sure it would be something similar or built off of this A: In your situation, you could try something like this: $("A").each(function () { if (this.href == document.URL) { $(this).addClass('active'); } }); That checks for every link if the href attribute matches the current documents URL, and if it does add class 'active' to the elements CSS classes. A small caveat: this will only work if the absolute URL referred to in the menu and used in the actual document match exactly. So let's say the current URL is http://example.org/dir/, then <a href="index.html"> will not be highlighted, since it resolves to http://example.org/dir/index.html. <a href="/dir/"> will match. (Making sure the same URL is used for each page throughout the site is good practice anyway, e.g. for search engine optimization and caching proxies) The different parts used are: * *$("A") selects all A elements (anchors). You'll probably want to make it a bit more specific by selecting all A elements within your menu, e.g. $("#menu A"). [jQuery] *.each(func) executes the specified function on each of selected elements. Within that function this will refer to the selected element. [jQuery] *this.href returns the absolute URI of the linked resource, not, as you might expect, the possibly relative location specified in the HTML. [standard DOM] *$(this).addClass(clzName) is used to add a CSS-class to the specified element. [jQuery] To make sure $("A") finds all elements, execute it after the document is fully loaded (in the $(document).ready() jQuery event-handler, or using the onload attribute of the BODY tag). A: var url_arr = document.URL.split('/'), page = url_arr[url_arr.length - 1]; switch (page) { case 'home.html': $('your-element').addClass('your-class'); break; /* other cases here */ } That should do the trick. A: Something like this var url = $(location).attr('href'); //get the url if(url.indexOf('home.html') != -1){ //indeOf returns -1 if item not found in string //so if it is not -1 (that is, found) //then apply the styles $('#nav').css('background','blue'); } You probably need a switch or case statement, though, to deal with all the URLs/sections. Something like var url = $(location).attr('href'); var fileName = url.slice(url.lastIndexOf('/') + 1); switch (fileName){ case 'home.html': $('#nav').css('background','blue'); break; case 'about.html': $('#nav').css('background','red'); break; } A: To read the current url in javascript: var url = window.location.href; To change a css property on a given element: $('some_selector').css({ backgroundColor, 'blue' });
{ "language": "en", "url": "https://stackoverflow.com/questions/7572767", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Modify the bytes read by an InputStream while reading, not later I need to make a simple sort of encryption so that the normal end user can't access some files easily. The files that are read by an FileInputStream are html files, pngs, jpegs and different simple text files (javascript, xml, ...) What I currently do is this: public static byte[] toEncryptedByteArray(InputStream input) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); copy(input, output, true); return output.toByteArray(); } public synchronized static final int copy(final InputStream input, final OutputStream output, final boolean modify) throws IOException { if (input == null || output == null) { throw new IOException("One stream is null!"); } byte[] mBuffer = new byte[DEFAULT_BUFFER_SIZE]; int count = 0; int n; while ((n = input.read(mBuffer)) != -1) { if (modify) { for ( int i = 0 ; i < n ; i++ ) { mBuffer[i] = (byte) ~mBuffer[i]; // byte manipulation } } output.write(mBuffer, 0, n); output.flush(); count += n; } mBuffer = null; return count; } The memory footprint is huge as I have the complete byte array in my memory (we talk about bitmaps with >2mb in memory). I thought I could simple extend the FileInputStream class and do the byte manipulation while reading the content of the file. That would reduce the memory usage as I could use Bitmap.decodeStream(inputstream) instead of creating a byte array to get the bitmap from... but here I am stuck totally. The read() and the readBytes(...) methods are native, so I can't override them. Please spread the light in my darkness... A: Streams are designed to wrap. That's why you frequently see lines like: InputStream is=new BufferedInputStream(new FileInputStream(file)); So, create a DecryptingInputStream that does your decryption, wrapping around another InputStream. All that being said, this won't be tough to crack, as your decryption keys and algorithm will be easily determinable by anyone who decompiles your app. A: FileInputStream is not your problem. The read() function will not read in more than DEFAULT_BUFFER_SIZE on each call. It is your use of ByteArrayOutputStream which is using up a lot of memory as your are writing to it. If you want to reduce the amount of memory required then I suggest you write directly to a FileOutputStream instead of a ByteArrayOutputStream. So encrypt and write to disk as you read DEFAULT_BUFFER_SIZE from the InputStream.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: DirectShowLib Capture Device in .NET 4 error While using videocaptureelement in WPFMediaKit, I cannot run it with .net 4 VS2010 application, however the application runs fine in .NET 3.5 VS2010 environment. The application just pop out without error (Although i catch exception in domain and application). Debugging into WPFMediaKit leads to error at hr = graphBuilder.RenderStream(PinCategory.Preview, MediaType.Video, m_captureDevice, null, m_renderer); Removing the line above will make the application works fine in .NET 4 VS2010. I have try to debug in sampleapplication in WPFMediaKit and the result is the same that application will exit without error when the application is debug in .NET 4. Recompiling WPFMEdiakit and DirectShowLib with .NET 4 does not work as well. Searching in google leads to questions without answer. This lead me to suspect DirectShowLib problem rendering the capture pin in .NET 4... Any help please... A: Try this.. hr = graphBuilder.RenderStream(null, MediaType.Video, m_captureDevice, null, m_renderer);
{ "language": "en", "url": "https://stackoverflow.com/questions/7572771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rhino JS NativeArray types I've been experimenting with the Rhino -> Java interoperability and have run across something that I can't quite explain. I'm invoking a script from Java, coercing the result into a Java object, then retrieving the results. In my JS: this.objectmap.put("list", [1,1,2,3,5]); Setting a breakpoint on the NativeArray constructor, I see that the object array that gets passed in looks as follows: [1.0,1.0,2,3,5] Where 1.0 are of type Double and 2,3,5 are of type Integer. Any idea why this happens? I can't seem to track down the root cause. A: JavaScript (or rather ECMA Script) does not have a concept of an integer. It just has the concept of a "Number" this may happen to contain an integral value or a real value (floating point). Both are stored as a real value in a variable and therefore in memory. So in order for it to be converted to Java code it uses the "double" type to represent it as that is the closest representation it can make. http://www.ecma-international.org/publications/standards/Ecma-262.htm http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf (the specification and section 8.5 The Number Type, 9.3 toNumber) Note these specs relate to version 5 (of the ECMA standard) which is probably not what Rhino implements, so you may want to look on the website for the spec that matches your ECMA implemented version, but this matter has been the same since the language was invented. So knowing the above it is possible for integer values to be promoted to a "double" type when interoperating with any JavaScript/ECMA engine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Maximum number of queries by a single Facebook app Is there any limitations on the number of queries that a single Facebook app can make? A: It depends on the query and the access_token used. There are no documented limits and even if there were, it'd likely change depending on Facebook's need. Essentially you can make as many requests as you want until you get a request limit reached error message. Edit: Some methods will limit the number of queries per user.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Avoid overlap between multiple draggable canvas with jQuery I'm trying to make three canvas to be draggable and at the same time to avoid them from overlapping each other. I looked for similar questions about the topic and I found out about the library "jquery-ui-draggable-collision". These is the code that I have: $(document).ready(function(){ $(".cube").draggable({ obstacle: ".obstacle", preventCollision: true }); }); <body> <canvas class="cube obstacle" id="c"></canvas> <canvas class="cube obstacle" id="c2"></canvas> <canvas class="cube obstacle" id="c3"></canvas> </body> My problem is that being a canvas the object to drag and the obstacle at the same time makes it not to move at all. I wonder if you can help me out with this. A: You could try changing the obstacle selector to something like: "canvas.obstacle[id!=" + theIdYouDontWant + "]" It should select any other canvas of class obstacle. $(document).ready(function(){ // Everything that can be dragged around var $draggables = $("canvas.cube"); var id, $draggableItem; // Go through each item, get it's id, // and tell draggable() to collide with every obstacle but itself for (var i = 0; i < $draggables.length; i++) { $draggableItem = $draggables.eq(i); id = $draggableItem.attr("id"); $draggableItem.draggable({ obstacle: "canvas.obstacle[id!=\"" + id + "\"]", preventCollision: true }); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7572780", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to change the class of an anchor class when clicked with the mouse? This is my website. http://www.sarahjanetrading.com/js/j/index.html All the code+images+css is there with access to anyone I want the "listen" anchor class button to change(toggle) into the "stop listening" anchor class button when I(or someone else) clicks on it(onclick). All the CSS and HTML is done, I just want a script which can toggle the anchor classes when the mouse clicks on them. I am searching(googling) this for a while, with no luck whatsoever. And would really very much appreciate any help in the matter. Thanks Alot ! :) A: You just need to change the classes from listen to stop-listening etc. Something like this: $(".listen, .stop").click(function() { if ($(this).hasClass("listen")) { $(this).removeClass("listen").addClass("stop"); } else { $(this).removeClass("stop").addClass("listen"); } }); A: I can't understand your question well, if you mean 'how to toggle class when clicking the anchor' here's your answer: function changeClass(elem, cls1,cls2) { elem.className = (elem.className == cls1)?cls2:cls1; } By the way, good job on CSS, but still need to work a lot on scripts ;) A: var aButtons = document.getElementsByTagName('a'), // Retrieve all the buttons max, i; for (i = 0, max = aButtons.length; i < max; i += 1) { (function() { var bttn = aButtons[i]; // Handle the user click . bttn.onclick = function() { // If this is listen button, change it in a 'stop-listening button' if (bttn.className.indexOf('listen') !== -1) { bttn.className = 'stop-listening button'; } else { bttn.className = 'listen button'; // else change it in a 'listen button' } })(); } A: do it using jQuery which makes life easier and takes care of cross browser issue. Include the jquery library in your HTML page and give the below function which will take care of your requirement. $(function(){ $("a.button").click(function(){ which = $(this); if($(which).hasClass("listen")){ $(which) .text("custom text") // edited for changing text .removeClass("listen") .addClass("stop-listening"); } else if($(which).hasClass("stop-listening")){ $(which) .text("custom text") // edited for changing text .removeClass("stop-listening") .addClass("listen"); } }) })
{ "language": "en", "url": "https://stackoverflow.com/questions/7572788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Force Tomcat 3.3 compiler to compile JSPs as Java 1.5 I have a web application running on a (very old, I know, but I can't upgrade) Tomcat 3.3.2 Final servlet container and I had recently upgraded the VM that it's running on to Java 6. This went smoothly so then I tried to use a Java 5 feature (specifically generics) in a JSP of the application, but it fails, not liking the syntax. For what it's worth, I was putting something as simple as this: java.util.List<String> users= new java.util.Vector<String>(); into a JSP and letting Jasper compile it, but I'm getting a compilation error. I know that Tomcat is using the right JVM, but it seems to not be using the "-source 1.5" flag or equivalent. Does anyone know how I can force my Tomcat to compile as Java 5? A: You have to specify the VM version you want to use in your servlet config file (web.xml): <init-param> <param-name>compilerSourceVM</param-name> <param-value>1.5</param-value> </init-param> <init-param> <param-name>compilerTargetVM</param-name> <param-value>1.5</param-value> </init-param>
{ "language": "en", "url": "https://stackoverflow.com/questions/7572792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: TripleDES algorithm generates different outcome when called from android I have a simple java web application which is built by apache wicket. When I am registering users in the web app, I encrypt the password that they enter using tripledes and save it to the db. In the login page when they enter the same password, I encrypt it and pass the encrypted password to the db, to check if it is correct. Now I am working on building an android app which will have same login functionality. In the android app login page I am using same encryption library for encrypting password and I use the same key and initialization vector for both platforms, but if I try to enter for same password string in android, TripleDes algorithm generates completely different encrypted password(much longer). And therefore login fails from android device. What I also noticed is encrypted password that android generates can not be decrypted, it throws an exception. I am thinking that there might be a string encoding issue difference between two platforms, but can't figure out what causes that and how to fix it. Here's the algorithm that I use: public class TripleDES { private String key; private byte[] initializationVector; public TripleDES(String key, byte[] initializationVector) { this.key = key; this.initializationVector = initializationVector; } public String encryptText(String plainText) throws Exception{ //---- Use specified 3DES key and IV from other source ------------------------- byte[] plaintext = plainText.getBytes(); byte[] tdesKeyData = key.getBytes(); System.out.println("plain text length: " + plaintext.length); System.out.println("key length: " + tdesKeyData.length); Cipher c3des = Cipher.getInstance("DESede/CBC/PKCS5Padding"); SecretKeySpec myKey = new SecretKeySpec(tdesKeyData, "DESede"); IvParameterSpec ivspec = new IvParameterSpec(initializationVector); c3des.init(Cipher.ENCRYPT_MODE, myKey, ivspec); byte[] cipherText = c3des.doFinal(plaintext); return Base64Coder.encodeString(new String(cipherText)); } public String decryptText(String encryptedText) throws Exception{ //---- Use specified 3DES key and IV from other source ------------------- byte[] enctext = Base64Coder.decode(encryptedText); byte[] tdesKeyData = key.getBytes(); Cipher c3des = Cipher.getInstance("DESede/CBC/PKCS5Padding"); SecretKeySpec myKey = new SecretKeySpec(tdesKeyData, "DESede"); IvParameterSpec ivspec = new IvParameterSpec(initializationVector); c3des.init(Cipher.DECRYPT_MODE, myKey, ivspec); byte[] cipherText = c3des.doFinal(enctext); return new String(cipherText); } } A: (EDIT: As noted, storing passwords reversibly is a bad idea to start with, but for the sake of getting the encryption part right...) Here's the first issue: byte[] plaintext = plainText.getBytes(); byte[] tdesKeyData = key.getBytes(); That's using the default system character encoding. Is it the same on all Android phones? I don't know. Is it the same in Android as on your web server? I don't know. If one platform is using UTF-16 and another is using UTF-8 and plainText is all ASCII, that would certainly account for a factor-of-two difference in the size of the encrypted data. I would recommend always specifying the encoding - "UTF-8" is a good choice in many cases. EDIT: Okay, it looks like the problem was also what you then did later with cipherText. You need to convert the raw bytes into a base64 string. There's a base64 encoder built into Android, but this public domain code should work fine to. Instead of this line: return Base64Coder.encodeString(new String(cipherText)); you would use return Base64.encodeBytes(cipherText);
{ "language": "en", "url": "https://stackoverflow.com/questions/7572793", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I include the generated assemblies of Maven modules in a multi module build? I have a multimodule project, and I'm starting with just one child module: <modules> <module>x</module> </modules> When module x builds it too uses the assembly plugin to put together some of its artifacts into a tar.gz. However, it's main artifact type is not a tar.gz, it's a SWC (I'm using FlexMojos). The idea is to create an assembly from other child assemblies, basically unzipping multiple tars and zipping them into a single one. I want to pull out this tar.gz in my parent assembly, but using the moduleSet/binary combination below I only seem to be able to get the other SWC artifacts. <moduleSets> <moduleSet> <includes> <include>blah:x</include> </includes> <binaries> <outputDirectory>${module.artifactId}</outputDirectory> <unpack>true</unpack> </binaries> </moduleSet> </moduleSets> I know about the issues with using the assembly plugins with multimodule builds - I don't have them because my childs have a different parent to this POM. Any help appreciated!
{ "language": "en", "url": "https://stackoverflow.com/questions/7572798", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Type null character in terminal Is there a way to type the null character in the terminal? I would like to do something like: this is a sentence (null) test123 A: Apparently you can type this character with ^@ on some character sets. This wikipedia article on the null character may be helpful. A: As with the abort command (Ctrl-C), in most terminals just hit Ctrl-@ (with the use of Shift on my keyboard). A: In Linux, any special character can be literally inserted on the terminal by pressing Ctrl+v followed by the actual symbol. null is usually ^@ where ^ stands for Ctrl and @ for whatever combination on your keyboard layout that produces @. So on my keyboard I do: Ctrl+v followed by Ctrl+Shift+@ and I get a ^@ symbol with a distinguished background color. This means it's a special character and not just ^ and @ typed in. Edit: Several years later and a few input variations implemented by different terminals using keyboard layouts that require pressing Shift to access @. * *Ctrl+v followed by Ctrl+Shift+@ *Ctrl+v followed by Shift+@ without releasing Ctrl. *Ctrl+Shift+v followed by @ without releasing Ctrl+Shift. *Ctrl+Shift release Shift and re-press Shift keeping both Ctrl+Shift pressed followed by v and finally @. Seen in some terminals that implement a special input on Ctrl+Shift. A: $ echo -e "this is a sentence \0 test123" this is a sentence test123 The null here ^^ IS NOT visible $ echo -e "this is a sentence \0 test123" | cat --show-nonprinting this is a sentence ^@ test123 But it IS here ^^ But maybe you did not want this for a script?
{ "language": "en", "url": "https://stackoverflow.com/questions/7572801", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Proper way to use an url in the action attribute of a form in wordpress I have a custom form in one of my wordpress pages(this page uses a custom template)- <form action="www.mysite.com/custom-page-2" method="post"> . . . </form> Now the problem is that on submitting the browser shows the url "www.mysite.com/custom-page-2" in the address bar but shows a 404 page not found error. I read other solutions which ask to use action attribute for the same form page or use ajax or jquery. But my question is that why cant we use this method like normal php. What am I missing? A: Try changing the action to: http://www.mysite.com/custom-page-2 UPDATE After a little bit of digging it seems you need to set your action to an empty string, and redirect to the page you want during the form submission handler. Try following steps 1 - 3 of this answer but instead of redirecting back to the same page, redirect to the page you want to go to. Hope that helps A: The problem is if you use general values for your "name" attribute it surprisingly fails(example- name="name")...just prefix it with some unique name...maybe wordpress uses these names itself and causes clashes..
{ "language": "en", "url": "https://stackoverflow.com/questions/7572807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PrincipalContext not connecting I am attempting to use PrincipalContext for a webservice that I am developing. I have already been using forms authentication on the web server in a different application and it works fine. The error that I am recieving is : System.DirectoryServices.AccountManagement.PrincipalServerDownException: The server could not be contacted. ---> System.DirectoryServices.Protocols.LdapException: The LDAP server is unavailable. at System.DirectoryServices.Protocols.LdapConnection.Connect() at System.DirectoryServices.Protocols.LdapConnection.SendRequestHelper(DirectoryRequest request, Int32& messageID) at System.DirectoryServices.Protocols.LdapConnection.SendRequest(DirectoryRequest request, TimeSpan requestTimeout) at System.DirectoryServices.Protocols.LdapConnection.SendRequest(DirectoryRequest request) at System.DirectoryServices.AccountManagement.PrincipalContext.ReadServerConfig(String serverName, ServerProperties& properties) --- End of inner exception stack trace --- at System.DirectoryServices.AccountManagement.PrincipalContext.ReadServerConfig(String serverName, ServerProperties& properties) at System.DirectoryServices.AccountManagement.PrincipalContext.DoServerVerifyAndPropRetrieval() at System.DirectoryServices.AccountManagement.PrincipalContext..ctor(ContextType contextType, String name, String container, ContextOptions options, String userName, String password) at System.DirectoryServices.AccountManagement.PrincipalContext..ctor(ContextType contextType, String name, String container, String userName, String password) at webService.Service1.ValidUser(String sUserName) in E:\Development\CSharpApps\Desktop\OrgChart\webService\Service1.asmx.cs:line 158 Our webserver is in the DMZ and accesses the domain through the firewall. I am using the port information etc as below for an example. This works using the ip from my development box, however it is inside the firewall. The ip information that I am sending to it is the same as I am using inside the web forms authentication. PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "192.168.1.1:389", "dc=doodlie,dc=com",@"doodlie\admin","doodliesquat"); A: Maybe I'm missing something, but you don't actually have to specify the AD server, you can simply say: PrincipalContext ctx = new PrincipalContext(ContextType.Domain); And it should find whatever DC on the application's current domain that it can find. If it is a network with fault-tolerance, when one is down, the other should pick up. I'm not sure why there would be a reason to hit one, specifically, like the code in the original question does, unless it is on a different domain. If that is the case, you can try hosting your web service on that domain, instead, and use DNS and a forwarder to call/route over to your web service's new IP on the new domain, if needed, or use a Hosts file entry, or just refer to the web service by IP. A: Regardless of the issue, installing some of these invaluable tools for AD admin/troubleshooting have been a god send for me. If possible install Remote Server Administration Tools (RSAT) on your machine/ or the web server (if allowed) and then use Active Directory Users and computers client to determine the exact URL/ip of your DC. If you can't connect using these tools that might be a starting point to escalate to IT support/dev ops In addition to this the AD/service account the website application is running under may not have sufficient privileges to access the DC. I have had success with using (HostingEnvironment.Impersonate()) { // code in here. } The App Pool the website application is running under in IIS should be run under a user account which has appropriate privileges. (Doesn't just have to be network service) A: In my case removing port number from url worked
{ "language": "en", "url": "https://stackoverflow.com/questions/7572808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Replace all selected content with html in jQuery I have a set of selected elements using: $(selector).nextUntil('tr.some_class'); And I want to be able to replace the entire contents with new HTML. jQuery has replaceWith and replaceAll methods, which will replace each element with the selected html, but I'm not trying to insert html into each element, I'm trying to to a mass HTML replacement. A: How about: $(selector).nextUntil('tr.some_class').remove().append("<blah>"); UPDATE Assuming you want both the selector and tr.some_class TRs to remain (the behavior of nextUntil) AND that selector identifies a single row, you can do this like so: $("tr#id1").nextUntil('tr.some_class').remove(); $("tr#id1").after("<tr><td>g</td><td>g1</td></tr>"); http://jsfiddle.net/6WTNr/4/ A: var your_markup = "<div>hello world</div>"; $(selector).nextUntil('tr.some_class').html(your_markup);
{ "language": "en", "url": "https://stackoverflow.com/questions/7572810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: foreach with jquery element I would like each "p" element to show upon clicking the button. But it is not not working please help. <script> $(document).ready(function(){ $("p").hide(); $("button").click(function(){ $('p').each(function() { //alert($(this).text()); var abc = $(this).text(); abc.next().show(); }); }); }); </script> <button>Toggle</button> <p>Hello</p> <p>Good morning</p> <p>Good after noon</p> <p>Good evening</p> <p>Good night</p> <div></div> A: $("p").hide(); $("button").click(function(){ $('p').each(function () { if (!$(this).is(":visible")) { $(this).show(); return false; } }); }); A: Try using the below code: $('p').each(function() { $(this).show(); }); Or simply $('p').show(); Hope this Helps!! A: I would potentially extend it one step further: I assume your example is a reduced and simplified sample for easy conversation. If your application is to have a lot of DOM manipulation (ie. some elements could get destroyed and rebuilt) or if you run into timing issues surrounding the 'click' event being bound, I would use .delegate() to bind the click instead: $(document).ready(function(){ $("p").hide(); // there are other ways to hide depending on your needs or to avoid FOUC $("body").delegate("button", "click", function() { $("p").show(); } }); I chose "body" as the listener simply because I don't know your page contents. The best listener is the nearest parent that is at no risk of being destroyed, often a wrapper div of some sort. Swap out "body" for a more specific selector if you can. Here's the difference: .click() : "Grab this specific element and ask it to listen for clicks on itself." .delegate(): "Grab a parent-level object and ask it to listen for clicks on any element matching the designated selector." .delegate() might be "overkill" for some purposes, but I use it whenever I can because it is much more future-proof. A: Here is the javascript that will show one at a time with the HTML you have var hiddenP = $("p:hidden"); var howMany = hiddenP.length; var pIndex = 0; $("button").click(function(evt){ if (pIndex == howMany) return false; $(hiddenP[pIndex]).fadeIn(1000); pIndex +=1; }); look at the example on jsfiddle to view the HTML and CSS http://jsfiddle.net/Cvm68/
{ "language": "en", "url": "https://stackoverflow.com/questions/7572816", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sencha Touch: Passing data from the 'listeners' to the detail view panel I am using the onItemDisclosure: function(record, btn, index) {... but I require the whole list to be clicked, so now I am using the listeners: { itemtap: function (list, index, element, event) {... to goto my detailed view. BUT how would / could I pass the data that I have been passing using the 'onItemDisclosure' now using the 'listeners' method. Current: onItemDisclosure: function(record, btn, index) { btToolbar.setTitle(record.data.title); detailPanel.update(record.data); App.viewport.setActiveItem(detailPanel, {type: 'slide', direction: 'left'}); } Proposed: listeners: { itemtap: function (list, index, element, event) { btToolbar.setTitle(??????????????); detailPanel.update(???????????????); App.viewport.setActiveItem(detailPanel, {type: 'slide', direction: 'left'}); } } A: You need to retrieve the item from your data store using: itemtap: function (list, index, element, event) { var record = store.getAt(index); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7572817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: InvalidCastException when casting FrameworkElement.ToolTip to System.Windows.Controls.ToolTip I need to makes some changes to a ToolTip programmatically. That sounds simple enough. Well, apparently not really. :/ I have a ToolTip on a WindowsFormsHost object and I make the following cast to get to the IsOpen property: ((System.Windows.Controls.ToolTip)host.ToolTip).IsOpen = true; This line fails during runtime with an InvalidCastException. Unable to cast object of type 'System.String' to type 'System.Windows.Controls.ToolTip'. I don't understand why this is failing. I must be missing some thing terribly simple as this code apparently works just fine in this example. @_@ A: ToolTip is not by accident of Type object and not ToolTip. If you set the ToolTip in XAML like this ToolTip="Test" then your ToolTip is of type String. Have a look at this. To modify your tooltip, i would suggest not using it in code directly, instead use the power of XAML and DataBinding. If you insist doing it in code, create an actual ToolTip for the property.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Set Foreign key value in EF1 (asp.net 3.5) I have to down grade my app from .net 4 to 3.5 to get it to run on our server. :( Anyway EF "Independent Association" - http://blogs.msdn.com/b/efdesign/archive/2009/03/16/foreign-keys-in-the-entity-framework.aspx ...but now I can't figure out how to set the value of a foreign key because it no longer appears in my Entity. Can anyone advise how I can do this please? A: AFAIK, you cannot set the value directly, but must use the navigation property instead. So if you have a Parent row you would like to set the foreign key of to 15, it would look like this: var Child = (from c in context.Children where id = 15).Single(); Parent.Child = Child; context.SaveChanges();
{ "language": "en", "url": "https://stackoverflow.com/questions/7572830", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Magento (CE 1.3) - Filter productCollection where stock quantity is 0 Magento 1.3 I'm trying to filter out of stock items from the productCollection. Using: ->addAttributeToFilter('status',array('neq' => Mage_Catalog_Model_Product_Status::STATUS_DISABLED)) I can filter by status, but in this store , enabled products can still have 0 quantity. Using: ->addAttributeToFilter('qty', array('gt' => 0)) returns a 'qty' is not an attribute error. $this->_productCollection = $this->_productCollection->addAttributeToSelect('*') ->setStoreId($storeId) ->addStoreFilter($storeId) ->addAttributeToFilter('status',array('neq' => Mage_Catalog_Model_Product_Status::STATUS_DISABLED)) ->setPageSize($this->getToolbarBlock()->getLimit()); Any ideas? Thanks. A: You could use something like this: $oCollection = Mage::getModel('catalog/product') ->getCollection() ->joinField( 'qty', 'cataloginventory/stock_item', 'qty', 'product_id=entity_id', '{{table}}.stock_id=1', 'left' ) ->addAttributeToFilter('qty', array('eq' => 0)); In case you need no catalog/product data at all (except the product id), but only want to know which product ids have a quantity of zero in general, you also could use: $oCollection = Mage::getModel('cataloginventory/stock_item') ->getCollection() ->addQtyFilter('=', 0); A: If you wanna throw this in a simple module look below: app/code/local/Company/InStockOnly/etc/config.xml <?xml version="1.0"?> <config> <global> <models> <company_instockonly> <class>Company_InStockOnly_Model</class> </company_instockonly> </models> </global> <frontend> <events> <catalog_block_product_list_collection> <observers> <company_instockonly_list> <type>singleton</type> <class>company_instockonly/observer</class> <method>addInStockOnlyFilter</method> </company_instockonly_list> </observers> </catalog_block_product_list_collection> </events> </frontend> </config> app/code/local/Company/InStockOnly/Model/Observer.php <?php class Company_InStockOnly_Model_Observer { /** * Observes the catalog_block_product_list_collection event */ public function addInStockOnlyFilter($observer){ $observer->getEvent()->getCollection() ->joinField('stock_status','cataloginventory/stock_status','stock_status', 'product_id=entity_id', array( 'stock_status' => Mage_CatalogInventory_Model_Stock_Status::STATUS_IN_STOCK, 'website_id' => Mage::app()->getWebsite()->getWebsiteId(), )) ; } } Then make Magento discover your module: app/etc/modules/Company_InStockOnly.xml <config> <modules> <Company_InStockOnly> <active>true</active> <codePool>local</codePool> </Company_InStockOnly> </modules> </config> Enjoy ;) A: You could use if($_product->isSaleable()): on your products list output
{ "language": "en", "url": "https://stackoverflow.com/questions/7572837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Do I need any Rules Engine to build a service like ifttt.com ( if this then that )? I'm trying to build a web service like ifttt.com . Because I find that more than a half of the channels provided by ifttt is not available in China. So I decide to make a local one. I'm learning the Logs of ifttt trying to understand the process of how ifttt dealing with tasks. Now I know that I must have some method to deal with the rules. A scheduled task process can be activated by a specified event and then a engine resolve rules to call specified actions, passing parameters. I'm planing to use Java to develop this. And do you think I should use any open source Rules Engine here, or it's better to write one by myself? It will be great if you provide some hints about what I should be care for writing the rules engine or defining the structure of rules. Finally, welcome free discussions about what technology do you think ifttt might be using. Or what the Database Structure of ifttt might be like. Or.. any point about ifttt or Rules Engine or Scheduled Tasks will be helpful! A: I like drools or JBoss Rules, although it's the only one I've ever used. Anything you can distill down to a spreadsheet is especially cool. My vote would be that if you can make a spreadsheet out of it, there is nothing better than this. Debugging the rules is a pain in the butt. I hope its gotten better.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Implement a method on a specific instance? So I've got this javascript class called Car and I've defined an instance of it, a Prius. Car = function Car () { var mileage = 10; var maker = "Basic"; var model = "Model"; return { 'sellSelf' : function() { return "I am a "+ model+ " from " + maker + " with mpg "+ mileage;} , 'getMileage' : function() { return mileage; } , 'setMileage' : function(m) { mileage = m; } , 'getMaker' : function() { return maker; } , 'setMaker' : function(m) { maker = m; } , 'getModel' : function() { return model; } , 'setModel' : function(m) { model = m; } }; } Prius = new Car(); Prius.setMaker('Toyota'); Prius.setModel('Prius'); Prius.setMileage(500); alert(Prius.sellSelf()); alert(Prius.getMileage()); I'd like to be able to override sellSelf method for the Prius, to something like this: function sellPrius() { return "I'm a snooty car with "+getMileage()+ " mpg "; } Any suggestions, and am I right in saying that javascript is treating Car as 'abstract', Car.sellSelf() fails. Thanks for the help! A: You can just set the method for prius: Prius.sellSelf = function() { return "I'm a snooty car with " + this.getMileage() + " mpg "; } A: If you want to program in JS OOP, use prototype. The new prefix will only make sense for functions with a modified prototype, using this to access variables and methods. When you use new, the return value of a function is not returned. Instead, an instance of the class is returned, which equals to the this variable within that function. The advantage of prototypes is that the functions are static, and only defined once. Hundred instances of the Car class will only have one, shared set of methods. When you use Example: function Car(){ //Optional: Default values this.maker = "Unknown manufacture"; this.model = "Unknown model"; //NO return statement } Car.prototype.setMaker = function(maker){this.maker = maker} Car.prototype.setModel = function(model){this.model = model} //Et cetera Car.prototype.getMaker = function(){return this.maker} Car.prototype.getModel = function(){return this.model} //Etc Car.prototype.sellSelf = function(){return "Model: "+this.model+"\nMaker"+this.maker} var Prius = new Car(); Prius.setMaker("Toyota") Prius.setModel("Prius"); //Etc alert(Prius.sellSelf()); Adding a new method can easily be done through setting Car.prototype.newMethod = function(){}. A huge advantage is proved: All instances of Car will now have this method, so you will only have to define the function once, instead of Prius.newMethod = ..; BMW.newMethod = ... A: For JavaScript properties / functions to be inherited, you need to add them to the prototype and not to the object itself. Here's a simplified example. Car.prototype.sellSelf = function() { return "A";} var prius = new Car(); prius.selfSell(); // returns A //override prius.sellSelf = function() { return "B";} prius.sellSelf(); // returns B EDIT: Here's working sample.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Windows: What would be involved with creating our own firewall for distribution with our product? I am charged with determining what would be involved with creating our own firewall. Something that can intercept each and every connection, and decide whether to permit it based on which exe is initiating the connection. We would either block or hang the connection until the user said to permit or deny. I am interested in XP, Vista, Win7. I know how to program in Java, Perl and JavaScript. I am assuming that I am going to need to get Java to interface with some C or C# executable in order to make this work. I expect the GUI alerts will be Java based, but the big thing is knowing what interfaces with Windows would be needed, and if there is a major difference between XP and Vista/7. I assume there are certain decisions to make, perhaps some compatibility issues. Please describe what would be involved. I also posted a related question for the possibility of simply tapping into the built in Windows Firewall because I want to hear about both options separately. A: See this stackoverflow question. To paraphrase the answer given in that post, you would need to make use of the Windows Filtering Platform API. As it's OS based, you would need to either write or find API wrappers that translate the C/C++ into something Java could call if you want to go that route. If you need a network level firewall, you can start by looking at either ipcop or Symantec Endpoint for freebie and commercial solutions respectively. Endpoint does client side protection as well and other products exist such as Avast or ESET/NOD32 that offer firewall capabilities for free or at decent cost. Unless it's an absolute necessity, I would advise looking into commercially available options before diving into writing your own. A: Writing a driver in C, in other words, not Java. A: Are you really sure that your only two options are to code one or use the one from Microsoft? There are others, you know: http://lifehacker.com/5061933/five-best-windows-firewalls
{ "language": "en", "url": "https://stackoverflow.com/questions/7572852", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Optimizing a MySQL query with several joins One of the queries used by a web app we're running is as follows: SELECT p.id, r.id AS report_id, tr.result_id, r.report_date, r.department, r.reportStatus, rs.specimen, tr.name, tr.value, tr.flag, tr.unit, tr.reference_range FROM patients AS p INNER JOIN patients_reports AS pr ON pr.patient_id = p.id INNER JOIN reports AS r ON pr.report_id = r.id INNER JOIN results AS rs ON r.id = rs.report_id INNER JOIN test_results AS tr ON rs.id = tr.result_id WHERE pr.patient_id = 17548 ORDER BY rs.specimen, tr.name, r.report_date; The explain plan looks like this: +----+-------------+-------+--------+---------------+-----------+---------+-------------------+--------+----------------------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+--------+---------------+-----------+---------+-------------------+--------+----------------------------------------------+ | 1 | SIMPLE | p | const | PRIMARY | PRIMARY | 4 | const | 1 | Using index; Using temporary; Using filesort | | 1 | SIMPLE | rs | ALL | PRIMARY | NULL | NULL | NULL | 152817 | | | 1 | SIMPLE | r | eq_ref | PRIMARY | PRIMARY | 4 | demo.rs.report_id | 1 | | | 1 | SIMPLE | pr | eq_ref | PRIMARY | PRIMARY | 8 | const,demo.r.id | 1 | Using where; Using index | | 1 | SIMPLE | tr | ref | result_id | result_id | 5 | demo.rs.id | 1 | Using where | +----+-------------+-------+--------+---------------+-----------+---------+-------------------+--------+----------------------------------------------+ The query returns 27371 rows. There are 152730 rows in test_results at the moment. This is just a small amount of demo data. I've tried to get the query to be more efficient, but I'm having trouble getting it to execute more quickly. I've had a look at various articles on documentation and questions on stackoverflow, but have not been able to fix this. I tried removing one of the joins as follows: SELECT pr.patient_id, r.id AS report_id, tr.result_id, r.report_date, r.department, r.reportStatus, rs.specimen, tr.name, tr.value, tr.flag, tr.unit, tr.reference_range FROM patients_reports AS pr INNER JOIN reports AS r ON pr.report_id = r.id INNER JOIN results AS rs ON r.id = rs.report_id INNER JOIN test_results AS tr ON rs.id = tr.result_id WHERE pr.patient_id = 17548 ORDER BY rs.specimen, tr.name, r.report_date; The query plan is then as follows: +----+-------------+-------+--------+---------------+-----------+---------+-------------------+--------+---------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+--------+---------------+-----------+---------+-------------------+--------+---------------------------------+ | 1 | SIMPLE | rs | ALL | PRIMARY | NULL | NULL | NULL | 152817 | Using temporary; Using filesort | | 1 | SIMPLE | r | eq_ref | PRIMARY | PRIMARY | 4 | demo.rs.report_id | 1 | | | 1 | SIMPLE | pr | eq_ref | PRIMARY | PRIMARY | 8 | const,demo.r.id | 1 | Using where; Using index | | 1 | SIMPLE | tr | ref | result_id | result_id | 5 | demo.rs.id | 1 | Using where | +----+-------------+-------+--------+---------------+-----------+---------+-------------------+--------+---------------------------------+ So not much different. I've tried rearranging the query and using STRAIGHT_JOIN amongst other things, but I'm not getting anywhere. I'd appreciate some suggestions on how to optimize the query. Thanks. EDIT: Argh! I did not have an index on results.report_id, but it does not seem to have helped: +----+-------------+-------+--------+-------------------+-----------+---------+-------------------+--------+---------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+--------+-------------------+-----------+---------+-------------------+--------+---------------------------------+ | 1 | SIMPLE | rs | ALL | PRIMARY,report_id | NULL | NULL | NULL | 152817 | Using temporary; Using filesort | | 1 | SIMPLE | r | eq_ref | PRIMARY | PRIMARY | 4 | demo.rs.report_id | 1 | | | 1 | SIMPLE | pr | eq_ref | PRIMARY | PRIMARY | 8 | const,demo.r.id | 1 | Using where; Using index | | 1 | SIMPLE | tr | ref | result_id | result_id | 5 | demo.rs.id | 1 | Using where | +----+-------------+-------+--------+-------------------+-----------+---------+-------------------+--------+---------------------------------+ EDIT2: patients_reports looks like this: +------------+---------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +------------+---------+------+-----+---------+-------+ | patient_id | int(11) | NO | PRI | 0 | | | report_id | int(11) | NO | PRI | 0 | | +------------+---------+------+-----+---------+-------+ EDIT3: After adding the results.report_id index and trying the STRAIGHT_JOIN again as suggested by @DRapp: SELECT STRAIGHT_JOIN r.id AS report_id, tr.result_id, r.report_date, r.department, r.reportStatus, rs.specimen, tr.name, tr.value, tr.flag, tr.unit, tr.reference_range FROM patients_reports AS pr INNER JOIN reports AS r ON pr.report_id = r.id INNER JOIN results AS rs ON r.id = rs.report_id INNER JOIN test_results AS tr ON rs.id = tr.result_id WHERE pr.patient_id = 17548 ORDER BY rs.specimen, tr.name, r.report_date; the plan looks like this: +----+-------------+-------+--------+-------------------+-----------+---------+-------------------+------+----------------------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+--------+-------------------+-----------+---------+-------------------+------+----------------------------------------------+ | 1 | SIMPLE | pr | ref | PRIMARY | PRIMARY | 4 | const | 3646 | Using index; Using temporary; Using filesort | | 1 | SIMPLE | r | eq_ref | PRIMARY | PRIMARY | 4 | demo.pr.report_id | 1 | | | 1 | SIMPLE | rs | ref | PRIMARY,report_id | report_id | 5 | demo.r.id | 764 | Using where | | 1 | SIMPLE | tr | ref | result_id | result_id | 5 | demo.rs.id | 1 | Using where | +----+-------------+-------+--------+-------------------+-----------+---------+-------------------+------+----------------------------------------------+ So I think that looks much better, but I'm not sure exactly how to tell. Also the query still seems to take about the same about of time as before. A: I would use STRAIGHT_JOIN and go with your second query that has the patients_reports table first and secondarily join to the patient table for their name info. Additionally, if I didn't see it, was there an index on the patients_reports table by the PATIENT_ID column either by itself, or as first element of a compound index key? Additionally, ensure RESULTS has an index on Report_ID, same with TEST_RESULTS (index on Result_ID) A: Is results.report_id indexed? It's failing to find a key and doing a table scan it looks like. I'm assuming results.id is actually the primary key. Also, if it report_id was the primary key, and it's INNODB, it should be clustered on that index, so absolutely no clue why that isn't screaming fast if it is configured that way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572858", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Nokogiri Chokes on Document with unicode char (i think) in title attribute I have a document that looks similar to this (note the title): <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml"> <head> <title>Sã�ng Title</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <div id="container"> Some Text </div> </body> </html> When i get this document using Nokogiri using this code: require 'nokogiri' require 'open-uri' doc = Nokogiri::HTML(open(url).read) The result from Nokogiri is this: ruby-1.9.2-p290 :060 > pp doc #(Document:0x82e5ed2c { name = "document", children = [ #(DTD:0x82e5e994 { name = "HTML" }), #(Element:0x82e5e0c0 { name = "html", attributes = [ #(Attr:0x82e5e05c { name = "xmlns", value = "http://www.w3.org/1999/xhtml" }), #(Attr:0x82e5e048 { name = "xmlns:fb", value = "http://www.facebook.com/2008/fbml" })], children = [ #(Element:0x82e5d8dc { name = "head", children = [ #(Element:0x82e5d6d4 { name = "title", children = [ #(Text "Sã")] })] })] })] }) To me, it looks like the character AFTER "Sã" causes nokogiri to just choke and think the document has ended. As you can see the #content div is not included at all. Anyone know how to deal with this situation? This is killing me... Thank you!! Edit: Upon further research i've found the actual character causing the choke is a unicode null char "\u0000". Right now i'm thinking i can do something like this: page_content = open(url).read # Remove null character page_content.gsub!(/\u0000/, '') Nokogiri::HTML(page_content) A: Are you sure that the character after Sã is a valid UTF-8 character? Added There are illegal UTF-8 character sequences. To decode UTF-8 manually, try this decoder. You can enter the incoming hex and it will tell you what each individual byte means. A good overview of UTF-8. UTF-8 code chart Re: Removing the null character. Your code looks ok, try it out! But in addition, I'd investigate the source of the null in your incoming datastream. Also, the binary UTF-8 of your Original Post is, in fact, the unknown character symbol--not your original datastream. Here is what is in your post: 53 C3 A3 EF BF BD 6E 67 Here is the decoding: U+0053 LATIN CAPITAL LETTER S character U+00E3 LATIN SMALL LETTER A WITH TILDE character (&#x00E3;) U+FFFD REPLACEMENT CHARACTER character (&#xFFFD;) # this is the char used when # the orig is not understood. U+006E LATIN SMALL LETTER N character U+0067 LATIN SMALL LETTER G character
{ "language": "en", "url": "https://stackoverflow.com/questions/7572859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Difference between glOrthof and glViewPort On OpenGL-ES i'm confused on what the difference is between setting glOrthof() glViewPort() GLU.gluOrtho2D() with it's respective parameters. Since I believe it's all setting the part you can see to the specified coordinates (width, height). Which should I use? A: The glViewport determins the portion of the window to which OpenGL is drawing to. This may be the entire window, or a subsection (think console game's "split screen" mode- a different viewport for every player). glOrthof applies an orthographic projection to the current matrix, which is usually set to the projection matrix before this call. The projection matrix is combined with the modelview to produce a matrix that translates your OpenGL coordinates to screen coordinates. gluOrtho2D, This is equivalent to calling glOrtho with near = -1 and far = 1. I'd recommend this page for more details on how viewing and transformation works in OpenGL. Which should you use? Viewports and orthographic projections are different concerns, so you'll need a call for each. glOrthof and gluOrtho2D are roughly equivalent; know the difference and use one or the other.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: How to create x number of files with perl? I want to create a specified number of files ranging from 1..10000000, containing "some text", how do you do this in perl? Thanks in advance! A: You do this the same way you'd do it in any other language. Break down the job into a series of small steps that you can implement: * *A loop around: *Opening a file and writing the text to it. So you might have code like: my $count = 0; while( $count < 10000 ) { open(my $fh, '>', "output.$count") or die "Failed to open file: $!"; print $fh "sometext\n"; close( $fh ); $count += 1; } A: try this: my $count = 3; for (my $i = 0; $i < $count; $i++) { open(my $f, ">>file$i.txt") or die("couldn't open file$i.txt"); print $f "some text"; close($f); } A: Although you could create 10 million files in one directory, it is inadvisable since looking around that directory will prove troublesome. ls won't return for hours, bash auto-complete on file names will hang, and in general you will need to kill your terminal to use it again. Consider partitioning the files across multiple directories. You can use md5, sha1, modulo some number(s), groups of n-digits in the filename, etc. to achieve the partitioning. Keeping the total number of files in any directory less than a few thousand is preferable. Here's an example using md5: use File::Path qw( make_path ); use Digest::MD5 qw( md5_hex ); use constant DIRECTORY_ROOT => '/path/where/you/want/these/files'; use constant FILE_SEP => '/'; use constant MAX_FILES => 10; for my $count ( 1 .. MAX_FILES ) { my $subdir = substr( md5_hex($count), 0, 2 ); # First 2 characters my $dir = join FILE_SEP, DIRECTORY_ROOT, $subdir; make_path( $dir ); my $file = join FILE_SEP, $dir, $count; open( my $fh, '>', $file ) or die "Failed to open file $file : $!"; print $fh "some text\n"; close($fh); } This will create the following set of files: ./c9 ./c9/8 ./16 ./16/6 ./ec ./ec/3 ./c8 ./c8/2 ./e4 ./e4/5 ./a8 ./a8/4 ./d3 ./d3/10 ./8f ./8f/7 ./45 ./45/9 ./c4 ./c4/1
{ "language": "en", "url": "https://stackoverflow.com/questions/7572870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Changing a macro at runtime in C I have a macro defined. But I need to change this value at run time depending on a condition. How can I implement this? A: You can't. As a macro is resolved by the preprocessor before the compilation itself, its content is directly copied where you use it. You can still use parameters to insert a conditional statement depending on what you want, or use a call-scope accessible variable. If you want to change a single value, better use global scope variable, even if such behavior is discouraged. (as the intensive use of macro) A: Depending on what you want to do, you might do it several ways. Global variable instead of macro // someincludefile.h extern static int foo; // someincludefile.c static int foo = 5; // someotherfile.c #include "someincludefile.h" printf("%d\n", foo); // >> 5 foo = -5; printf("%d\n", foo); // >> -5 Condition you can toggle // someincludefile.h extern static int condition; #define FOO1 (5) #define FOO2 (-5) #define FOO (condition ? (FOO1) : (FOO2)) // someincludefile.c static int condition = 1; // someotherfile.c #include "someincludefile.h" printf("%d\n", FOO); // >> 5 condition = 0; printf("%d\n", FOO); // >> -5 Condition that's locally and dynamically evaluated // someincludefile.h #define CONDITION (bar >= 0) #define FOO1 (5) #define FOO2 (-5) #define FOO ((CONDITION) ? (FOO1) : (FOO2)) // someotherfile.c #include "someincludefile.h" int bar = 1; printf("%d\n", FOO); // >> 5 bar = -1; printf("%d\n", FOO); // >> -5 In that last one the CONDITION will be evaluated as if its code were in your local scope, so you can use local variables and/or parameters in it, but you can also use global variables if you want. A: Macros are replaced by the preprocessor by their value before your source file even compiles. There is no way you'd be able to change the value of the macro at runtime. If you could explain a little more about the goal you are trying to accomplish undoubtedly there is another way of solving your problem that doesn't include macros. A: You can't change the macro itself, i.e. what it expands to, but potentially you can change the value of an expression involving the macro. For a very silly example: #include <stdio.h> #define UNCHANGEABLE_VALUE 5 #define CHANGEABLE_VALUE foo int foo = 5; int main() { printf("%d %d\n", UNCHANGEABLE_VALUE, CHANGEABLE_VALUE); CHANGEABLE_VALUE = 10; printf("%d %d\n", UNCHANGEABLE_VALUE, CHANGEABLE_VALUE); } So the answer to your question depends on what kind of effect you want your change to have on code that uses the macro. Of course 5 is a compile-time constant, while foo isn't, so this doesn't work if you planned to use CHANGEABLE_VALUE as a case label or whatever. Remember there are two (actually more) stages of translation of C source. In the first (of the two we care about), macros are expanded. Once all that is done, the program is "syntactically and semantically analyzed", as 5.1.1.2/2 puts it. These two steps are often referred to as "preprocessing" and "compilation" (although ambiguously, the entire process of translation is also often referred to as "compilation"). They may even be implemented by separate programs, with the "compiler" running the "preprocessor" as required, before doing anything else. So runtime is way, way too late to try to go back and change what a macro expands to. A: You can't. Macros are expanded by the Preprocessor, which happens even before the code is compiled. It is a purely textual replacement. If you need to change something at runtime, just replace your macro with a real function call.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "33" }
Q: axis2 webservice EPR issue So, i've been been trying to deploy a very simple service, following this tutorial using maven3 and Java EE eclilpse http://maksim.sorokin.dk/it/2011/01/13/axis2-maven-servlets-tomcat/ But receive this exception. org.apache.axis2.AxisFault: The service cannot be found for the endpoint reference (EPR) /axis2Example/services/HelloWs/sayHello?name=Max at org.apache.axis2. ... I'm guessing the service mapping is wrong, and that the service doesn't actually exist at that url, but my understanding of web.xml and services.xml is just too shallow to see where the issue is. all my config xml's are exactly as described in the tutorial, and the deployed servlet in tomcat/webapps has a folder structure as follows: axis2Example | HelloWs.wsdl | +---META-INF (also a maven folder with the pom) | MANIFEST.MF \---WEB-INF | web.xml | +---classes | +---lib | +---services | +---HelloWs | +---META-INF services.xml I've uploaded my war to http://www.mediafire.com/?e8tchhtp4koc1t5 If anyone can take a look I would much appreciate it. The deadline to ship is actually thursday lawl, can't believe this is happening. A: you need to rename the folder under WEB-INF/classes/axis2example to axis2Example (this is how you have given in the services.xml) you can use WSO2 AS[1] to deploy your services. which gives you a lot of monitoring and administrative features. [1] http://wso2.org/library/application-server
{ "language": "en", "url": "https://stackoverflow.com/questions/7572874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Built-In Windows Firewall: Lock outgoing connections? By default, the Windows Firewall seems to block incoming (locally created listen sockets) connections by default. They can then be permitted per exe file. Is it possible to configure something similar for outgoing connections? So Windows would ask whether to allow or deny an exe's outgoing connections. We are considering creating a custom GUI to enable or disable this functionality, if available. It is a lower-cost option compared to creating our own firewall. I would like to know about XP and Vista/Win7. A: Are you trying to block one specific EXE (that you have control of the source for)? Or all programs on the computer from making outbound connections? Why would you want to do this? And if it's about admin policy control, why not control this on a central firewall? In any case, take a look at the Windows Firewall APIs. It lets you create all the crazy rules you want to block/allow traffic. http://msdn.microsoft.com/en-us/library/aa366449%28v=VS.85%29.aspx A: Which version of Windows are you asking about? I'm sure that control of outgoing connections wasn't available when Windows first introduced a built-in firewall. If you need to support WinXP RTM, I think you're s-o-l. Many third-party firewalls do provide this capability.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby, need to read the content of a file and split it on smaller new files I have a long file with tons of hostnames with options.. something like hostname { option 1 option 2 option 3 } the file has approximately 2000 hostnames. what I want to do in ruby is to: open the file start reading when I get to a hostname create a file with that hostname and put that same information from that hostname only then when it gets to } stop and continue to the next hostname/repeat A: One way to make this work, if you know that a { or } will not be in an option would be to use the scan method with multiline mode on the regexp: b.scan( /([^\{]*)(\{)([^\}]*\n)*(\})/m) => [["a ", "{", "\n b\n c \n d\n", "}"], ["\nB ", "{", "\n 1\n 2\n 3\n", "}"]] your re will need a bit of tweaking but it'll work, if you want to fit it all in memory for the parse. Writing to a file should be straightforward. A: For what you posted I guess something like this would do: str = <<EOF hostname1 { hi } hostname2 { how } hostname3 { are } EOF hostnames = str.scan(/^\w+ {.*?}/m) hostnames.each do |hostname| #here save it to a new file puts hostname end EDIT Here goes a full example, it will read hostnames.cfg and save individual files on a folder called hostnames hostnames.cfg hostname1 { hi } hostname2 { how } hostname3 { are } whatever.rb file = File.open('./hostnames.cfg', 'r') content = file.readlines.join file.close hostnames = content.scan(/^\w+ {.*?}/m) hostnames.each do |hostname| name = hostname.scan(/^\w+/m).first new = File.open("./hostnames/#{name}.cfg", "w+") new.write(hostname) new.close end A: My solution: actual_host = nil #~ inputfile = File.open(filename) inputfile = DATA #Only thi stestcase inputfile.each_line{|line| case line when /\A\s*(\S+)\s*\{/ filename = "#{$1}.txt" #write to <<hostname>>.txt raise "File already exist" if File.exist?(filename) actual_host = File.new(filename, 'w') when /\A\s*\}/ actual_host = nil else #copy data, if inside a host file actual_host << line if actual_host #Alternative without leading/trailing spaces #~ actual_host << line.strip if actual_host end } inputfile.close __END__ hostname { option 1 option 2 option 3 } It parses line by line and starts a new file for each hostname { and close it at }. Everything in between is stored to a new file. if the target file already exists, the script stopps with an exception.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: php paypal express checkout problem I'm trying to integrate paypal express checkout on my website. I was trying to check using sandbox. When I submit data from my site token is generated with no error but when redirected to paypal it's not showing payment amount. btw I'm using the code from paypal express checkout wizard. It will be helpful if some one points me to correct direction. require_once ("paypalfunctions.php"); $paymentAmount = 15; $currencyCodeType = "GBP"; $paymentType = "Sale"; $returnURL = "http://www.mysite.com/paypal/confirm.php"; $cancelURL = "http://www.mysite.com/paypal/index.php"; $resArray = CallShortcutExpressCheckout ($paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL); $ack = strtoupper($resArray["ACK"]); if($ack=="SUCCESS") { RedirectToPayPal ( $resArray["TOKEN"] ); } A: As you're not passing so called 'line item details' (product data), PayPal doesn't display the total amount. If you only want to show the amount for the current purchase, redirect buyers to https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-xxxxxx&useraction=commit (instead of https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-xxxxx) If you want to start sending line-item details to PayPal, include the following in your SetExpressCheckout API request: // Total amount of the purchase, incl shipping, tax, etc PAYMENTREQUEST_0_AMT=300.0 // Total amount of items purchased, excl shipping, tax, etc PAYMENTREQUEST_0_ITEMAMT=300.0 // Authorize the funds first (Authorization), or capture immediately (Sale)? PAYMENTREQUEST_0_PAYMENTACTION=Sale // First item L_PAYMENTREQUEST_0_NAME0=Item1 L_PAYMENTREQUEST_0_QTY0=1 L_PAYMENTREQUEST_0_AMT0=100.00 // Second item L_PAYMENTREQUEST_0_NAME1=Item2 L_PAYMENTREQUEST_0_QTY1=1 L_PAYMENTREQUEST_0_AMT1=200.00 If you want to see this in your own history as well, you'll also need to include this in DoExpressCheckoutPayment.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: display an Image i am a total c++ and opencv beginner, and i want to learn it. i am working with visual 2008.as a lesson i tried to display a .jpg picture but the program wont compile. when debugging, i get this error: 1>main.cpp 1>c:\users\ralf\documents\visual studio 2008\projects\3)\3)\main.cpp(1) : fatal error C1083: Cannot open include file: 'cv.h': No such file or directory 1>Build log was saved at "file://c:\Users\ralf\Documents\Visual Studio 2008\Projects\3)\3)\Debug\BuildLog.htm" 1>3) - 1 error(s), 0 warning(s) ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== i suppose it is something about the linker and which files i have to include, and how....^^ i wrote the following under project->properties->Linker->Input->Additional Dependencies (Active(Debug) on the left corner of the window): opencv_highgui230d.lib opencv_core230d.lib opencv_cv.lib in Release i wrote: opencv_highgui230.lib opencv_core230.lib last but not least, here is my code #include <cv.h> #include <highgui.h> int main(int argc, char* argv[]) { IplImage* img = cvLoadImage( "IMG_7321_.jpg" ); cvNamedWindow( "MyJPG", CV_WINDOW_AUTOSIZE ); cvShowImage("MyJPG", img); cvWaitKey(0); cvReleaseImage( &img ); cvDestroyWindow( "MyJPG" ); return 0; } A: Linux: g++ -o _test test.cpp -lcv -lhighgui Windows: @"C:\Program Files\CodeBlocks\MinGW\bin\g++.exe" -O3 -Wall -Iinclude \ -o test.exe test.cpp \ libopencv_core230.dll libopencv_highgui230.dll libopencv_imgproc230.dll source code, test.cpp: #include <opencv/cv.h> #include <opencv/highgui.h> int main (int argc, char **argv) { if (argc < 2) return -1; char *filename_i = argv[1]; IplImage* img = cvLoadImage(filename_i, CV_LOAD_IMAGE_COLOR); cvShowImage("Test Window", img); cvWaitKey(5*1000); return 0; } Needed DLLs: $ ls -1 *.dll libgcc_s_dw2-1.dll libopencv_calib3d230.dll libopencv_contrib230.dll libopencv_core230.dll libopencv_features2d230.dll libopencv_flann230.dll libopencv_gpu230.dll libopencv_highgui230.dll libopencv_imgproc230.dll libopencv_legacy230.dll libopencv_ml230.dll libopencv_objdetect230.dll libopencv_video230.dll libstdc++-6.dll You can get my package from URL: http://pacify.ru/download/opencv-showimage-test.tgz
{ "language": "en", "url": "https://stackoverflow.com/questions/7572882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: webkit-transform alternative for Firefox Is there any alternative to -webkit-transform CSS rules in Firefox? A: Yes, it's called -moz-transform. Check out this article http://www.zachstronaut.com/posts/2009/02/17/animate-css-transforms-firefox-webkit.html Here is the official documentation: https://developer.mozilla.org/en/CSS/-moz-transform
{ "language": "en", "url": "https://stackoverflow.com/questions/7572884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Best pratice to map a mixin in a Script# import library What's the raccomended way to map a Javascript Mixin in a Script# import library? For an example: this qooxdoo api http://demo.qooxdoo.org/1.5.x/apiviewer/#qx.core.Object Implements this mixin http://demo.qooxdoo.org/1.5.x/apiviewer/#qx.data.MBinding How should I map it in C#? Extensions methods? Interfaces? A: If you check out the script# sources on github, you'll see examples of how to do this in the jQuery world. The answer depends if you're simply trying to import existing script or if you want to use script# to author the mixin itself. If you want to simply import, I'll recommend you check out the jQuery and jQuery.History projects in the source code. jQuery.History represents a jQuery history mixin (but does so without any extension methods or interfaces). If you want to author the mixin in script#, read on... the high-level approach is to define a static class and annotate it with the [Mixin] attribute. In the future, the approach will change to use c# extension methods, but this custom approach is what you need for now. Back to sample - at https://github.com/nikhilk/scriptsharp/blob/master/samples/PhotoDemo/Gallery/GalleryPlugin.cs you'll see: [Mixin("$.fn")] public static class GalleryPlugin { public static jQueryObject Gallery(GalleryPluginOptions customOptions) { ... // Use jQuery.Current to access the "this" object at runtime pointing // to the object instance whose prototype now contains the mixin methods. } } This will get generated into script as: $.fn.gallery = function(customOptions) { } For reference, the way jQuery.Current was defined in the out-of-box jQuery library (see https://github.com/nikhilk/scriptsharp/blob/master/src/Libraries/jQuery/jQuery.Core/jQuery.cs for full source): [IgnoreNamespace] [Imported] [ScriptName("$")] public sealed class jQuery { private jQuery() { } [ScriptAlias("this")] [IntrinsicProperty] public static jQueryObject Current { get { return null; } } } A bit involved, but hopefully once you've tried it, it becomes straightforward. Out-of-box script# provides APIs and templates for jQuery scenarios which help simplify by removing the mechanics from the forefront, which you'll need to understand when working against a different script framework. Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7572888", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Firefox - Load texture cross-domain (WebGL) I'm having a problem loading images cross-domain in Firefox for WebGL and it works fine in Chrome. I've implemented CORS on the server that has "Access-Control-Allow-Origin: *" in the response header. The "Access-Control-Allow-Origin: *" response made Chrome satisfied with cross-domain images but Firefox is not. Is Firefox still implementing CORS or am I just doing something wrong? I'm using Firefox version 6.0.2 Any help would be appreciated. Thanks! A: CORS for WebGL textures is not supported until Firefox 8. Firefox 8 should be in the Beta channel very soon now, since Firefox 7 was released today.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572895", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python/html- Combine multiple html's into one I've written a python script to convert a text file to html file. But that is kind of useless if I can't put them all together. What I'm supposed to do is display all the reports onto the website (the server part is not my problem). Now I can convert each file to an html but I just realize it's a huge library of files. How do I combine them all? Here's what i'm thinking how to put them together, e.g: Say this is the homepage: Date: - Report 1 - Report 2 - Report 3 ... Some hyperlinks like that (the links here are just fake. Just showing you what i'm thinking of)...the user will click on it to see the report. Much more organized than all the html files laying around everywhere -- This is just what i'm thinking out loud. But the problem is how do I automatically have all the html reports combined under a certain date field. Is there a guide for this? I'm totally lost, I don't know where to start A: Create a list of tuples in Python. Then sort them in place. Then iterate over the list and produce your homepage HTML. Below an example. You need to fill in the URLs and the date for each report (either as a date object or as a string, example: '09-12-2011') report_tuples = [ ('http://www.myreport.com/report1', report1_date_object_or_string), ('http://www.myreport.com/report2', report2_date_object_or_string), ('http://www.myreport.com/report3', report3_date_object_or_string), ] sorted(report_tuples, key=lambda reports: reports[1]) # sort by date html = '<html><body>' #add anything else in here or even better #use a template that you read and complement lastDate = None for r in report_tuples: if not lastDate or not lastDate == r[1]: html += '<h3>%s</h3>' % (str(r[1])) html += '<a href="%s">Your Report Title</a>' % (r[0]) return html #or even better, write it to the disk. Here some URLs that might help: How to sort a list in place Python data structures in general
{ "language": "en", "url": "https://stackoverflow.com/questions/7572901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Parsing Web URL in iPhone Development I am trying to parse a HTML string in a iPhone app. Example: The URL is http://www.apple.com/developer I want to delete the "developer" part so all I have will be http://www.apple.com How could I do this? A: You can also bring it in to an NSURL and get the parts you want: NSURL *url = [NSURL URLWithString:@"http://www.apple.com/developer"]; [url host]; // @"www.apple.com" [url scheme]; // @"http" A: You can search for the third slash in the string and then substring it to get the part you want A: Have you considered the NSUrl method URLByDeletingLastPathComponent or the method pathComponents? URLByDeletingLastPathComponent Returns a new URL made by deleting the last path component from the original URL. pathComponents Returns the individual path components of a file URL in an array. Here is a good tutorial/example on NSURL methods.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calculating Min/Max Y-Axis values for a line chart I am attempting to replicate how 'right' Excel feels with regards to calculating the Y-Axis boundaries for a line chart. As an example, lets assume I currently have a chart with three datapoints on it. (0, 100), (1,500), (2,930). The simplistic code I currently have sets the Y-Axis min value to 100 and the Y-Axis max value to 930. The idea was to prevent datasets which have no 0 values from skewing the size of the chart. This works, but I feel that it could be much better. For the above example, Excel plots the datapoints on the range 0 through 1000. I am trying to create a general algorithm plotting the same 'feel good' range. It is proving to be slightly tricky, however. I feel that I need a few points of information: * *The order of magnitude for the upper and lower values (power of 10). *Always take the ceiling / floor of a data point -- it is not very clear when a data point shares the same value as max/min range plotted. From there I'm at a bit of a loss. If I take 930 as a max data point value, I know it's order of magnitude is 3. So, I add one to its largest value and zero the rest -- resulting in 1000. If I take 1030 as a max data point value, I know it's order of magnitude is 4. If I add one to it's largest value and zero the rest the result is 2000. Excel plots 1200 as the max range when graphing (0, 100), (1,500), (2,930), (3,1030). This problem quickly degrades at larger values -- it's just not quite right to always increase the largest value, but it is sometimes. Does anyone have any experience with this that could shed some insight into a better approach? A: A quite robust approach is as follows: * *take the range r = max - min *assume a padding of approx. five percent (adjust figure if necessary), pad = r * 0.05 *round pad up to the next (1,2,5)*10^n (e.g. 0.23 will be rounded to 0.5 while 5.5 will be rounded up to 10). *take axis_min = floor(min/pad-1)*pad *take axis_max = ceil(max/pad+1)*pad A: Why not just have the range going from something like: (1-padding) * minimum_value // minimum > 0 (1+padding) * minimum_value // minimum < 0 to (1+padding) * maximum_value // maximum > 0 (1-padding) * maximum_value // maximum < 0 where padding is a number between 0 and 1, e.g. 0.05.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572907", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get list of properties of an entity I'm using entity framework. I would like to get the property list of an entity when the EntityState of the object is "Added", and loop throught them. here is a sample code of what I'm doing. var newEntities = ObjectStateManager.GetObjectStateEntries(EntityState.Added); foreach (var entry in newEntities) { var entityName = entry.EntitySet.Name; var newProps = ObjectStateManager.GetObjectStateEntry(entry.EntityKey).GetModifiedProperties(); var currentNewValues = ObjectStateManager.GetObjectStateEntry(entry.EntityKey).CurrentValues; foreach (var propName in newProps) { var newValue = currentNewValues[propName]; } } As you can see, I use ObjectStateManager.GetObjectStateEntry(entry.EntityKey).GetModifiedProperties(); to get the property list, but It's working only when the State is EntityState.Modified. Thanks. Here is the way to perform my needs With that, I can get all the attribute for an entity and get his value too. var newEntities = ObjectStateManager.GetObjectStateEntries(EntityState.Added); foreach (var entry in newEntities) { if (entry.State == EntityState.Added) { var prop = entry.Entity.GetType().GetProperties(); var entityName = entry.EntitySet.Name; var currentNewValues = ObjectStateManager.GetObjectStateEntry(entry.EntityKey).CurrentValues; foreach (var propName in prop.Where(p => p.PropertyType.Namespace == "System")) { var newValue = currentNewValues[propName.Name]; } } } A: Each entry you are enumerating over should have a 'State' property which is the EntityState, so you can either filter them out with an if clause or use linq, foreach (var entry in newEntities) { if (entry.State == EntityState.Added) { // continue and get property list } } Or var addedEntities = newEntities.Where(x => x.State == EntityState.Added); Also I'm not sure if you need to look at 'Modified Properties' at all. If it is an entity which has only just been added then why would it have any modified properties and not simply new ones (ie CurrentValues)? A: foreach (var entry in newEntities) { if (entry.State == EntityState.Added) { // continue and get property list var currentValues = entry.CurrentValues; for (var i = 0; i < currentValues.FieldCount; i++) { var fName = currentValues.DataRecordInfo.FieldMetadata[i].FieldType.Name; var fCurrVal = currentValues[i]; } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7572912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to write a template expanding to multiple elements? I'd like to write a knockout.js template which should expand into a set of table cells. In other words, something like: <tr> <td>Cell one</td> <td>Cell two</td> <div data-bind="template: ..."></div> <td>Cell six</td> </tr> <script id="..." type="text/html"> <td>Cell three</td> <td>Cell four</td> <td>Cell five</td> </script> But the div tag isn't allowed in the tr, of course, and I can't figure out any way to coax knockout to replace the div tag with the template expansion, rather than nesting the expansion inside the div. Anybody know a way to accomplish this? A: You can do this with the new "containerless" templates like this: <tr> <td>Cell one</td> <td>Cell two</td> <!-- ko foreach: names --> <td>Cell three<span data-bind="text: name"></span></td> <td>Cell four</td> <td>Cell five</td> <!-- /ko --> <td>Cell six</td> with js like this: $(function() { var viewModel = { names: ko.observableArray([ { name: "Bob"}, {name: "John"}]) }; ko.applyBindings(viewModel); }); Here is a jsfiddle that shows it in action: jsfiddle Here is a jsfiddle that shows it without the foreach: jsfiddle
{ "language": "en", "url": "https://stackoverflow.com/questions/7572913", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Measure the time spent in each layer of a Web Service I have a WCF REST Web Service (.NET 4) which is design based on multitier architecture (i.e. presentation, logic, data access, etc.). At runtime and without instrumentation, I would like to measure how much time a single request takes for each layer (e.g. Presentation = 2 ms, Logic = 50 ms, Data = 250 ms). Considering that I cannot change the method signature to pass in a StopWatch (or anything similar), how would you accomplish such thing? Thanks! A: If you cannot add code to your solution, you will end up using profilers to examine what the code is doing, but I would only suggest that in an environment other than production unless you are only having issues in performance. There are plenty of ways to set up another environment and profile under load. Profilers will hook into your code and examine how long each method takes. There is no "this is the business layer performance" magic, as the profiler realizes physical boundaries (class, method) instead of logical boundaries, but you can examine the output and determine speed. If you can touch code there are other options you can add which can be turned on and off via configuration. Since you have stated you cannot change code, I would imagine this is a non-option. A: I've recently been working on performance-enhancements and looking at .NET performance tools. DotTrace seems to be the best candidate so far. In particular, the Performance Profiler can produce Tracing Profiles. These profiles detail how long each method is taking: Tracing profiling is a very accurate way of profiling that involves getting notifications from CLR whenever a function is entered or left. The time between these two notifications is taken as the execution time of the function. Tracing profiling helps you learn precise timing information and the number of calls on the function level. This screen-shot illustrates the useful stats that the tool can produce: You should be able to see exactly how much time a single request takes for each layer by inspection of the profiling data. A: There's a tracer in the MS Ent Libs, syntaxically you use a using statement and duration of everything that occurs inside the using statement is logged into the standard Ent Lib logging ecosystem. using(new Tracer()) { // Your code here. } More basic info on MSDN here, and see here for it's constructors; there are different constructors that allow you to pass in different identifiers to help you keep track of what's being recorded.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572916", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to write a JSP which renders a list of JSP fragments, without IF switching code I have a JSP which composes a List of Objects, then renders JSP fragments depending on the Class of each of the objects in the List. At the moment, this is done with a huge chain of if statements inside the 'parent' JSP: if( bean.getFilterChildByType( Level.class ) != null ) { %> <jsp:include page="filters/level.jsp"/> <% } if( bean.getFilterChildByType( Sources.class ) != null ) { %> <jsp:include page="filters/sources.jsp"/> <% } ... So, my question is, in JSP (Tomcat) is it possible to achieve this same functionality without an if chain, just by iterating the Objects in the list and perhaps taking advantage of the naming convention "Class name".jsp ? I've played with: <%@ include file="filename" %> but this doesn't seem to allow variables in the file-name either. A: Something like this should work <jsp:include page="filters/<%=filename%>.jsp"/> A: Resolve the appropriate jsp to be included (based on bean.getFilterChildByType) at the controller side and then just pass the name of the jsp to the container jsp. Now this can be easily included. A: This is a tough one! If the included jsp files (level.jsp, source.jsp, etc) are not too complex, what about shifting the HTML from those files over to a function call of the objects you are calling bean.getFilterChildByType(...) on? That way, instead of a large if/else tree, you could then just call: String html = bean.getHtmlForType(); ...would likely work out much cleaner in a loop too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: save the html once we call html through ajax I want to call one html through ajax. once i get the response, i need to save that response as html on the spefied location how can i do that? I am calling ajax function using jquery as like below. $.ajax({ type: "POST", url: "../../../project/html/TC_print.html", success: function(msg){ //once it success.. i need to save it as html on desktop } }); success call back, i need to save it as html on desktop A: //once it success.. i need to save it as html on desktop Forget about it. For security reasons, javascript that runs inside a browser doesn't have access to files on the client computer. Simply think of the consequences if this was possible. You probably wouldn't have been writing this question nor I have been writing this answer at the very moment as our computers would have been hacked badly. You visit a site and files start popping on your desktop. You visit a malicious site and viruses start popping everywhere, not only on your desktop. A: JavaScript prevents you from saving files to a users computer for security reasons, You'd need to write the file to a server and then prompt the user to download the file by putting it in a ZIP or something similar. A: I don't think that with javascript alone you will be able to save on the desktop but I might be mistaken. What I would do will to make another call from the success handler to a php script and pass in the html, then use PHP protocols to save file on desktop. Cheers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to filter AD with a concatenated variable in Powershell I'm using PowerShell v2 and Microsoft's AD module to search our AD for accounts whose EmployeeID match a particular ID. The ID is usually stored in AD as "00000123456" but the value i have to search with is only the "123456" part. problem is i cannot figure out how to do a -like search in AD. here's my current code $EmpInfo = Import-csv "PSfile.csv" $EmplID = EmpInfo.ID $EmpAD = get-aduser -Filter {employeeId -like "*$EmplID"} -Properties * -EA Stop At this point, EmpAD is always empty I can work around this by modifying EmpID to contain "*123456" before I call Get-ADUser and this works. But I can't help but think there is a syntax problem preventing the obvious approach. Research to resolve it has been fruitless. A: If your string is really in employeeID attribute you can test : $EmpAD = get-aduser -LDAPFilter "(employeeId=*$EmplID)" -SearchBase 'DC=dom,DC=fr' -Properties * you can use LDP.EXE (or ADSI.EXE) to verify what exactly exists your Directory. -----Edited----- For me it works, if I test with LDIF: C:\temp>ldifde -f eid.ldf -d "dc=dom,dc=fr" -r "(employeeId=*)" Connexion à « WM2008R2ENT.dom.fr » en cours Connexion en tant qu'utilisateur actuel en utilisant SSPI Exportation de l'annuaire dans le fichier eid.ldf Recherche des entrées... Création des entrées... 3 entrées exportées There are 3 objects In PowerShell with AD Cmdlets it gives the following : PS C:\> get-aduser -LDAPFilter "(employeeID=*)" | Measure-Object Count : 3 And $var = "123456" PS C:\> get-aduser -LDAPFilter "(employeeID=*$var)" -properties employeeID DistinguishedName : CN=user1 Users,OU=MonOu,DC=dom,DC=fr EmployeeID : 00000123456 Enabled : True GivenName : user1 Name : user1 Users ObjectClass : user ObjectGUID : b5e5ea59-93a6-4b24-9c3e-043a825c412e SamAccountName : user1 SID : S-1-5-21-3115856885-816991240-3296679909-1107 Surname : Users UserPrincipalName : user1@dom.fr Be carefull : I don't understand why, but it took some time between the modification in the directory with MMC and the result in the PowerShell prompt. I reload a new PowerShell interpreter and re import AD module. A: From a performance perspective, if you know that the IDs are always a certain number of digits (with leading zeroes), you're going to be WAY better off just formatting the ID ahead of time. If your ID is supposed to be 11 digits, do something like this $EmplID.ToString("D11") to get it padded out.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Launch shell scripts from Jenkins I'm a complete newbie to Jenkins. I'm trying to get Jenkins to monitor the execution of my shell script so i that i don't have to launch them manually each time but i can't figure out how to do it. I found out about the "monitor external job" option but i can't configure it correctly. I know that Jenkins can understand Shell script exit code so this is what i did : test1(){ ls /home/user1 | grep $2 case $? in 0) msg_error 0 "Okay." ;; *) msg_error 2 "Error." ;; esac } It's a simplified version of my functions. I execute them manually but i want to launch them from Jenkins with arguments and get the results of course. Can this be done ? Thanks. A: You might want to consider setting up an Ant build that executes your shell scripts by using Ant's Exec command: http://ant.apache.org/manual/Tasks/exec.html By setting the Exec task's failonerror parameter to true, you can have the build fail if your shell script returns an error code. A: To use parameters in your shell you can always send them directly. for example: * *Define string parameter in your job Param1=test_param *in your shell you can use $Param1 and it will send the value "test_param" Regarding the output, everything you do under the shell section will be only relevant to the session of the shell. you can try to return your output into a key=value txt file in the workspace and inject the results using EnvInject Plugin. Then you can access the value as if you defined it as a parameter for the job. In the example above, after injecting the file, executing shell echo $Param1 will print "test_param" Hope it's helpful!
{ "language": "en", "url": "https://stackoverflow.com/questions/7572931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to align div vertically in the center? Is there a way to align a div vertically in the center of my browser only with CSS usage? A: Here's one way to do it: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style> html { display: table; width: 100%; height: 100% } body { display: table-row; margin: 0; height: 100% } #foo { display: table-cell; height: 100%; vertical-align: middle } #test { margin: auto; background-color: #ccc } </style> </head> <body> <div id="foo"> <div id="test">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div> </div> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7572933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Handling multiple requests over a single connection using httpcomponents? I want to use a single connection to communicate with a client device. I am having problems keeping the connection alive. I'm using DefaultConnectionReuseStrategy() which returns false for keepAlive() after each request so the connection is always closed. I have set the Connection header to Keep-Alive but it still always closes the connection. My second problem is if I override keepAlive() to always return true, my client blocks while reading the input stream. How am I supposed to handle this? Should I be reading the content length header to find out how much to read? What if no content length is given?
{ "language": "en", "url": "https://stackoverflow.com/questions/7572935", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I re-create Actionscript's ColorTransform with php gd image library to colorize an image? I'm using a template of sorts, as you can see here: http://i.imgur.com/TtOHa.png In the game itself, you can choose any color to apply to that, and using actionscript's ColorTransform for red (255, 0, 0) you will get this: http://i.imgur.com/40FoO.png After searching and testing for a few days, I'm just getting nowhere with this. Using imagefilter with IMG_FILTER_COLORIZE just isn't cutting it. It just ends up tinting it basically, and it needs to fully change the color and keep intact all the different shades from the template. I thought the best solution would be to loop through each pixel and convert to HSV for the template and use the V value with the new color but it won't work well if you use a darker color to colorize the object with. I tried to come up with a formula on just how bright/dark the color should be according to the template but I just can't come up with anything.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572939", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Hg Merge specific commit from another branch I have two branches Dev and Feature1. I was working on Feature1, creating said feature, and committed it. I then wrote the code for Feature2 but committed it under Feature1 branch instead of a new branch (Feature2). So now i have two features in Feature1 branch as two separate commits, but I only want to include the second feature back into Dev. What is the mercurial way to do this? A: * *Supposed you have not yet published your commits: If you want to merge the commit Feature2 independent of commit Feature1, you should move it on its own branch. *If already published: Use the transplant extension to "duplicate" the Feature2 commit and put it on its own branch. Then backout Feature2 commit on the Feature1 branch. Now you merge Feature2 independent of Feature1 too. In any case, instead of putting Feature2 on its own branch, you could also put it directly onto your Dev branch if this is your actual intention. A: Use hg graft This command uses Mercurial's merge logic to copy individual changes from other branches without merging branches in the history graph. This is sometimes known as 'backporting' or 'cherry-picking'. Documentation: https://www.mercurial-scm.org/repo/hg/help/graft A: include the second feature back into Dev. Include to Dev and leave in Feature1 - translpant, as mentioned by @oben-sonne Move completely from Feature1 - rebase In case you want rebase into Feature2 you'll have to create this branch (Feature1) before rebase
{ "language": "en", "url": "https://stackoverflow.com/questions/7572942", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: jQuery pull currency without dollar sign I have a tag that has a price in it (ie. $150.00). I want to use jQuery to pull only the text values without the dollar sign ($). <div> $150.00 </div> I want to output the above as 150.00 A: Use of replace is better but I can suggest that you can remove any currency symbol from the string like $ 150.00 Fr. 150.00 € 689.00 I have tested for above three currency symbols .You can do it for others also. var price = $("div").text().replace(/[^\d\.]/g, ''); Above regular expression will remove everything that is not a digit or a period.So You can get the string without currency symbol but in case of " Fr. 150.00 " if you console for output then you will get price as console.log('price : '+price); output = price : .150.00 which is wrong so you check the index of "." then split that and get the proper result. if (price.indexOf('.') == 0) { price = parseFloat(price.split('.')[1]); }else{ price = parseFloat(price); } A: You can use replace to replace the $ character with an empty string: var price = $("div").text().replace("$", ""); Note that in the case of your exact example (with that spacing) the blank spaces will not be removed. If you're going on to use the string as a number (via parseFloat for example) that won't matter, but if you're wanting to use it as text somewhere else, you may want to remove white space with jQuery's .trim. Update - based on comments replace returns a String. Once you have that string, you can parse it into a Number with parseFloat (or parseInt, but you're working with floating point numbers): var convertedToNumber = parseFloat(price); Now that you've got a number, you can perform mathematical operations on it: var percentage = convertedToNumber * 0.95; A: Would $('div').text().replace('$', ''); work your purposes?
{ "language": "en", "url": "https://stackoverflow.com/questions/7572950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: QueryOver and ProjectionLists We are trying to use QueryOver and projects. Basically it works fine. But we are currently struggling with a projection which should contain multiple items. The problem is that we have pallets which can contain pallet items. Pallet items are the base classes for various subclasses. We need to be able to projects only one property of each subclass MagazinePlaceLoadingOverviewData. Any ideas how we could achieve this? Information: Magazine contains Levels, Levels contains Places, Places can have one Pallet assigned and a pallet can have multiple pallet items on it. Pallet items can be of various subtypes. We tried to get into the subtypes by implementing a visitor pattern on the pallet item but we can't even get the query below working. MagazinePlaceLoadingEntity magazineLoadingAlias = null; MagazinePlaceSettingsEntity magazinePlaceAlias = null; MagazineLevelSettingsEntity magazineLevelAlias = null; MagazineSettingsEntity magazineAlias = null; MagazinePlaceLoadingOverviewData overviewAlias = null; PalletEntity palletAlias = null; PalletTypeSettingsEntity palletTypeAlias = null; PalletItemEntity palletItemsAlias = null; return session.QueryOver(() => magazineLoadingAlias) .JoinAlias(x => x.Pallet, () => palletAlias) .JoinAlias(() => palletAlias.PalletType, () => palletTypeAlias) .JoinQueryOver(x => x.Place, () => magazinePlaceAlias) .JoinQueryOver(x => x.Level, () => magazineLevelAlias) .JoinQueryOver(x => x.Magazine, () => magazineAlias) .Where(x => x.Id == this.magazineId) .Select( Projections.Property(() => magazinePlaceAlias.Id).WithAlias(() => overviewAlias.MagazinePlaceId), Projections.Property(() => magazineLoadingAlias.PalletInProgress).WithAlias(() => overviewAlias.PalletInProgress), Projections.ProjectionList().Add(Projections.Property(() => palletAlias.PalletItems), () => overviewAlias.Items), Projections.Property(() => palletTypeAlias.Classification).WithAlias(() => overviewAlias.PalletTypeClassification)) .TransformUsing(Transformers.AliasToBean<MagazinePlaceLoadingOverviewData>()) .List<MagazinePlaceLoadingOverviewData>(); This leads to the following exception System.Data.SqlServerCe.SqlCeException: The column aliases must be unique. [ Name of duplicate alias = y2_ ] at System.Data.SqlServerCe.SqlCeCommand.ProcessResults(Int32 hr) at System.Data.SqlServerCe.SqlCeCommand.CompileQueryPlan() at System.Data.SqlServerCe.SqlCeCommand.ExecuteCommand(CommandBehavior behavior, String method, ResultSetOptions options) at System.Data.SqlServerCe.SqlCeCommand.ExecuteDbDataReader(CommandBehavior behavior) at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader() at NHibernate.AdoNet.AbstractBatcher.ExecuteReader(IDbCommand cmd) at NHibernate.Loader.Loader.GetResultSet(IDbCommand st, Boolean autoDiscoverTypes, Boolean callable, RowSelection selection, ISessionImplementor session) at NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) at NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) NHibernate.Exceptions.GenericADOException: could not execute query [ SELECT magazinepl3_.Id as y0_, this_.PalletInProgress as y1_, palletalia1_.Id as y2_, pallettype2_.Classification as y2_ FROM "MagazinePlaceLoading" this_ inner join "Pallet" palletalia1_ on this_.PalletId=palletalia1_.Id inner join "PalletTypeSettings" pallettype2_ on palletalia1_.PalletTypeSettingsId=pallettype2_.Id inner join "MagazinePlaceSettings" magazinepl3_ on this_.MagazinePlaceSettingsId=magazinepl3_.Id inner join "MagazineLevelSettings" magazinele4_ on magazinepl3_.MagazineLevelSettingsId=magazinele4_.Id inner join "MagazineSettings" magazineal5_ on magazinele4_.MagazineSettingsId=magazineal5_.Id WHERE magazineal5_.Id = @p0 ] Positional parameters: #0>cb9ff95a-58ca-4b2b-9aa6-9f6c008fc0b3 [SQL: SELECT magazinepl3_.Id as y0_, this_.PalletInProgress as y1_, palletalia1_.Id as y2_, pallettype2_.Classification as y2_ FROM "MagazinePlaceLoading" this_ inner join "Pallet" palletalia1_ on this_.PalletId=palletalia1_.Id inner join "PalletTypeSettings" pallettype2_ on palletalia1_.PalletTypeSettingsId=pallettype2_.Id inner join "MagazinePlaceSettings" magazinepl3_ on this_.MagazinePlaceSettingsId=magazinepl3_.Id inner join "MagazineLevelSettings" magazinele4_ on magazinepl3_.MagazineLevelSettingsId=magazinele4_.Id inner join "MagazineSettings" magazineal5_ on magazinele4_.MagazineSettingsId=magazineal5_.Id WHERE magazineal5_.Id = @p0] at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) at NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters) at NHibernate.Loader.Loader.List(ISessionImplementor session, QueryParameters queryParameters, ISet`1 querySpaces, IType[] resultTypes) at NHibernate.Impl.SessionImpl.List(CriteriaImpl criteria, IList results) at NHibernate.Impl.CriteriaImpl.List(IList results) at NHibernate.Impl.CriteriaImpl.List() at NHibernate.Impl.CriteriaImpl.Subcriteria.List() at NHibernate.Criterion.QueryOver`1.List() at NHibernate.Criterion.QueryOver`1.NHibernate.IQueryOver<TRoot>.List<U>() at .Domain.Queries.Magazines.GetLoadingOverviewByMagazineQuery.Find(ISession session) in GetLoadingOverviewByMagazineQuery.cs: line 41 at .Domain.Queries.QueryTestBase.Execute(IEnumerableQuery`1 query) in QueryTestBase.cs: line 39 at .Domain.Queries.Magazines.GetLoadingOverviewByMagazineQueryTest.Find_ShouldReturnOverviewData() in GetLoadingOverviewByMagazineQueryTest.cs: line 39 A: You can't do this: Projections.ProjectionList().Add(Projections.Property(() => palletAlias.PalletItems), () => overviewAlias.Items), AliasToBean Transformer means you are flattening your results set. You can't have a list inside your MagazinePlaceLoadingOverviewData. You will need to get your list of items as a second query and join them together using Linq To Objects if you want them in that format.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Return one attribute with XPath given multiple conditions I'm trying to retrieve one (and only one) occurrence of the element /Document/docOf/serviceEvent/effectiveTime/@value when the /Document/docOf/tempId/@root="1.3.5" The docOf elements can occur in any order, there is no guarantee that the ones with the sought after tempId are the first ones in the xml. I've been trying to use the position() function in combination with tempId/@root="1.3.5" but find that it is not working the way I intend it to. If I write tempId/@root="1.3.5" and position()=1 I get the correct result, but only when the tempId/@root="1.3.5" elements appear before the ones with other tempIds. How do I retrieve the effectiveTime/@value from an element with the correct tempId/@root and retrieve it just once? <Document> <docOf> <tempId root="1.3.2"codeSystem="11.2.3"/> <serviceEvent> <code code="UXZX0A"/> </serviceEvent> </docOf> <docOf> <tempId root="1.3.5"/> <serviceEvent classCode="ACT"> <effectiveTime value="20101122145613+0100"/> </serviceEvent> </docOf> <docOf> <tempId root="1.3.5"/> <serviceEvent classCode="ACT"> <effectiveTime value="20101122145613+0100"/> </serviceEvent> </docOf> <docOf> <tempId root="1.3.2"/> <serviceEvent> <code code="UXZX0A" codeSystem="11.2.3"/> </serviceEvent> </docOf> </Document> A: Try: /Document/docOf[tempId/@root='1.3.5'][1]/serviceEvent/effectiveTime/@value It first gets all docs with root=1.3.5 and then selects the first node from that set. It then extracts the value attribute from it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MPMusicPlayerController and setNowPlayingItem I'm using MPMusicPlayerController, specifically with setNowPlayingItem protocol and it's for cydia. But I have some issues and theos' warning when i make. It seems that some of the protocols and methods are not working and I receive some warning like this: Tweak.xm:177: warning: ‘MPMusicPlayerController’ may not respond to ‘-skipToPreviousItem’ Tweak.xm:188: warning: ‘MPMusicPlayerController’ may not respond to ‘-pause’ Tweak.xm:193: warning: ‘MPMusicPlayerController’ may not respond to ‘-play’ Tweak.xm:201: warning: ‘MPMusicPlayerController’ may not respond to ‘-skipToNextItem’ Tweak.xm:317: warning: ‘MPMusicPlayerController’ may not respond to ‘-setNowPlayingItem:’ Have anyone some ideas? I enter the protocol already in prototype A: I don't think it's because of cydia - it sounds like a compilation issue. Have you definitely got #import <MediaPlayer/MediaPlayer.h> in your file? A: have you added the MediaPlayer.framework to your project? * *select your project in the project navigator *select your target on the right side *select the "Build Phases" tab *open "Link Binary With Libraries" *add your framework A: I'm using MPMusicPlayerController, specifically with setNowPlayingItem. This is a complete online verses asset with an immense assortment of melody verses, data, what's more, MPMusicPlayerController *mp = [MPMusicPlayerController. downloadmp3music
{ "language": "en", "url": "https://stackoverflow.com/questions/7572960", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Make a general solver for the problem: undefined index in array for this program I'm making a program in a team of programmers and it has been decided that for a specific system we'll be using an array. In the majority of the uses, all indexes in the array will be properly set still, undefined indexes can happen. Using isset() or array_key_exists() will make the code too slow (because we will need lots of if's and and if is slow) and too "dirty" (too much code and repetitive code) so both are not an option. I already spotted the set_error_handler() function but I also don't know if it's the best option. Primary objective: When that specific array causes a undefined index it must be caught, solved (write situation to the logs) and the script must continue like nothing happened. What's the best way to do that? NOTE: If any other error or warning happens I want PHP to treat it like it's used to, I only want this stuff made to that specific array with that name. I hope I was clear enugh A: you should use Exception's try{ if(!isset($values[23])) throw new Exception("index not defined"); // do dangerous stuff here }catch(Exception $ex){ //handle error } however, the ideal solution would be to make sure this never happens in the first place. A: Consider putting your code into try-catch statements. Within the catch you can log the error. http://php.net/manual/en/language.exceptions.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7572961", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: what is the automatic variable name of an auto-implemented properties I'm trying to do this: public string LangofUser { get { return string.IsNullOrEmpty("how to get value?") ? "English" : "how to get value?"; } set; } do I have to do this? string _LangofUser public string LangofUser { get { return string.IsNullOrEmpty(_LangofUser) ? "English" : _LangofUser; } set { _LangofUser = value}; } A: As others have said, don't try to mix automatic and regular properties. Just write a regular property. If you want to know what secret names we generate behind the scenes for hidden compiler magic, see Where to learn about VS debugger 'magic names' but do not rely on that; it can change at any time at our whim. A: This mixing of auto-implement and not-auto-implemented properties in C# is not possible. A property must be fully auto-implemented or a normal property. Note: Even with a fully auto-implemented property there is no way to reference the backing field from C# source in a strongly typed manner. It is possible via reflection but that's depending on implementation details of the compiler. A: If you provide your own implementation of the property, it's not automatic any more. So yes, you need to do create the instance. A: Check this question What's the difference between encapsulating a private member as a property and defining a property without a private member? A: If you want to keep the automatic property and still have a default value, why don't you initialize it in your constructor? public class MyClass { public MyClass() { LangOfUser = "English"; } public string LangOfUser { get; set; } } Since C# 6, you can also set a default value for a property as follows: public class MyClass { public string LangOfUser { get; set; } = "English"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7572963", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Indexing PDF file by SOLR I'm using Solrj to index PDF files whith SOLR, but some files can't index and make an exception GRAVE: Error: Could not parse predefined CMAP file for 'Adobe-Identity-UCS' java.lang.NoSuchMethodError: org.apache.fontbox.cmap.CMap.lookup(II)Ljava/lang/String; can you tell me what's the problem? Thanks A: Seems some mismatch with the apache fontbox jars, which mentions the method not found. Can you confirm the jars for tika and all its dependencies are in sync and are the ones with the build. you can also check standalone if the parsing of documents work fine using the Apache Tika project jars.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: java.lang.ClassCastException: org.jersey.webservice.Login cannot be cast to javax.servlet.Servlet I already done a lot of search and I can't fix this. I'm bulding a Web Service with Tomcatv7.0, Jersey and Eclipse. This is the root cause: java.lang.ClassCastException: org.jersey.webservice.Login cannot be cast to javax.servlet.Servlet org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100) ... This is the exception: javax.servlet.ServletException: Class org.jersey.webservice.Login is not a Servlet org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100) ... I have a simple class: package org.jersey.webservice; import ... @Path("/login") public class Login { // This method is called if HTML is request @GET @Produces(MediaType.TEXT_HTML) public String sayHtmlHello() { return "<html> " + "<title>" + "Hello Andre" + "</title>" + "<body><h1>" + "Hello Andree" + "</body></h1>" + "</html> "; } } And this is my web.xml: `<?xml version="1.0" encoding="UTF-8"?> <display-name>org.jersey.andre</display-name> <servlet> <servlet-name>Andre Jersey REST Service</servlet-name> <servlet-class>org.jersey.webservice.Login</servlet-class> </servlet> <servlet-mapping> <servlet-name>Andre Jersey REST Service</servlet-name> <url-pattern>/rest</url-pattern> </servlet-mapping> </web-app>` The Login class is in the package org.jersey.webservice and in WEB-INF/lib I´ve imported the needed jars (jersey-api, jersey-core, etc...). Do you find anything wrong? I follow the documentation and this isn´t working. Damn! Thanks in advance. A: What tutorial were you reading? This is not the right way to declare a Jersey web service. It is indeed not directly a Servlet as the exception is trying to tell you. You need to declare the main Jersey servlet container with an init param pointing to the package containing the webservice classes. <servlet> <servlet-name>Andre Jersey REST Service</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <param-value>org.jersey.webservice</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>Andre Jersey REST Service</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> Also note that you should map it on the path /rest/* not the name /rest, otherwise you won't be able to use path information like http://example.com/context/rest/foo/bar and so on. See also: * *Jersey's own User Guide *Oracle's JAX-RS with Jersey tutorial (part of Java EE 6 tutorial) *Vogela's JAX-RS with Jersey tutorial Unrelated to the concrete problem, consider choosing something else than org.jersey as main package. E.g. org.andreelias.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572969", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Configuring SELinux permissions on (SVS-V) IPC Semaphores I have a bunch of programs which use IPC Semaphores to interact (semget). One of the programs is an Apache module, which runs in (some sort of) restricted SELinux context (which I don't understand too well). The module is capable of interacting with any regular files correctly, if of-course the files have their SELinux security context set appropriately. However - when my (Module) goes to access the IPC Semaphore, the semget call fails with a EPERM. When SELinux is turned off, I don't get this error. So - there is obviously something I need to do to set some sort of SELinux security context or something on the Semaphore for this to work. If it was a regular file, I could just call "chcon" on it. Since it's a System-V IPC Semaphore, I can't do that. What can I do to make this work?? A: The basic steps to get SELinux working with the changes you need are: * *Enable permissive mode *Capture denials *Add a new policy module or modify an existing policy module *Enable enforcing mode and test Exactly how to do these steps depends on what Linux distribution you are using; here are references for CentOS, Debian, Gentoo, RedHat and Ubuntu. You can also find SELinux information from NSA. The best documentation I found is from Gentoo: step 1, step 2, step 3, step 4. As @smassey noted, you most probably need to modify some IPC permission. A: SELinux has persmission setting for more than just regular files, but also device and special files. http://seedit.sourceforge.net/doc/access_vectors/access_vectors.html#SECTION00044000000000000000 is what you're looking for. Give read/write/etc permissions to the "sem" object. Cheers
{ "language": "en", "url": "https://stackoverflow.com/questions/7572974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Seeking an elegant, CSS-only method for hiding/showing auto-height content (with transitions) I'd like a method that uses only CSS transitions, to effectively (and attractively) hide/show content on hover. The caveat being that I wish to keep dynamic (auto) height. It seems that the optimal route would be to transition between a fixed height:0, to a height:auto, but alas this is not yet supported by transitions in browsers. A clarification in response to the comments :: This isn't so much a question of waiting until all living browsers are CSS3 compatible, but rather addressing a perceived shortcoming of CSS3 itself (eg. the lack of height:0 > height:auto) I've explored a few other ways, which can be viewed at the following fiddle (and elaborated below), but none of them satisfy me, and I'd love feedback/tips for other approaches. http://jsfiddle.net/leifparker/PWbXp/1/ Base CSS .content{ -webkit-transition:all 0.5s ease-in-out; -moz-transition:all 0.5s ease-in-out; transition:all 0.5s ease-in-out; overflow:hidden; } Variation #1 - The Max-Height Hack .content { max-height:0px; } .activator:hover +.content{ max-height:2000px; } Cons a. You'll need to arbitrarily set an upper max-height, which, with extensive dynamic content, could potentially cut off information. b. If, as a precaution to (a), you resort to setting a very high upper max-height, the delay on animation becomes awkward, and untenable, as the browser invisibly transitions the entire distance. Also makes easing less visually effective. Variation #2 - Padding and the Illusion of Growth .content { padding:0px; height:0px; opacity:0; } .activator:hover +.content { padding:10px 0px; height:auto; opacity:1; } Cons a. It's jarring. It's definitely slightly better than just popping the content out of nowhere, and the effect is further sold by transitioning the opacity, but overall it's not that visually slick. Variation #3 - The Faulty Width-Only Approach .content { width:0%; } .activator:hover +.content{ width:100%; } Cons a. As the width shrinks, the line-wrap forces any extra text onto subsequent lines, and we end up with a super tall invisible div that still demands the real-estate. Variation #4 - The Effective, but Jittery, Font-Size .content { font-size:0em; opacity:0; } .activator:hover +.content{ font-size:1em; opacity:1; } Cons a. While this has a nice, sweeping sort of effect, the shifting of the line-wrap as the font grows causes unappealing jitter. b. This only works for content consisting of text. Other transitions would need to be added to manage the scaling of inputs, and images, and while entirely viable, this would erode the simplicity. Variation #5 - The Butteriness of Line-Height .content { line-height:0em; opacity:0; } .activator:hover +.content{ line-height:1.2em; opacity:1; } Cons a. My favorite aesthetically, but as with #4, this works most simply with text-only content. Variation #6 - The Anti-Margin (as offered by @graphicdivine) .wrapper_6 { min-height: 20px } .wrapper_6 .activator {z-index:10; position: relative} .wrapper_6 .content { margin-top: -100%; } .wrapper_6 .activator:hover +.content{ margin-top: 0 } Cons a. There is a delay on hover which is not optimal. This is the result of the .content being tucked invisibly quite far up the screen, and taking time to animate downwards before appearing. b. The margin-top: -100% is relative to the containing element's width. So, with fluid designs there's the potential that when the window is shrunk quite small, the margin-top wont be sufficient to keep the .content hidden. As I said before, if only we could transition between height:0 and height:auto, this would all be moot. Until then, any suggestions? Thanks! Leif A: Try this, The anti-margin: .wrapper_6 { min-height: 20px } .wrapper_6 .activator {z-index:10; position: relative} .wrapper_6 .content { margin-top: -100%; } .wrapper_6 .activator:hover +.content{ margin-top: 0 } http://jsfiddle.net/PWbXp/ A: Well... I know it's been awhile, but I needed to use a height animation, and believe that a lot of other programmers still need or/and will need to do it. So, I fell here because I needed to show mode details of a product description inside a cell-table when user hovers the cell. Without user hovering, only the maximum of 2 lines of description are shown. Once user hovers it, all lines (text can be since 1 to 8 lines, dynamic and unpredictable length) must be show with some kind of height animation. I come to the same dilemma, and choose to use the max-height transition (setting a high max-height, which I was sure that will not cut my text), because this approach appears to me to be the cleanest solution to animate the height. But I couldn't be satisfied with the delay on the "slide up" animation, just like You. That's when I found a commentary about transition curve here: http://css3.bradshawenterprises.com/animating_height/ . The Idea of this guy is brilliant, but just this solution alone "cut-off" the effect of "slide down" animation. So thinking a little I just come to a final solution. So here is my solution using the Rhys's Idea (Guy of link above): Slide Down Animation (Hover), with a "smooth grow", and Slide Up Animation without (virtually) "delay": div { background-color: #ddd; width: 400px; overflow: hidden; -webkit-transition: max-height 1.5s cubic-bezier(0, 1.05, 0, 1); -moz-transition: max-height 1.5s cubic-bezier(0, 1.05, 0, 1); transition: max-height 1.5s cubic-bezier(0, 1.05, 0, 1); max-height: 38px; } div:hover { -webkit-transition: max-height 2s ease; -moz-transition: max-height 2s ease; transition: max-height 2s ease; max-height: 400px; } <div> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ac lorem ante. Vestibulum quis magna pretium, lacinia arcu at, condimentum odio. Ut ultrices tempor metus, sit amet tristique nibh vestibulum in. Pellentesque vel velit eget purus mollis placerat sed sit amet enim. Sed efficitur orci sapien, ac laoreet erat fringilla sodales. </div> Here is a Simple JsFiddle And Here is your JsFiddle updated (slice of it, indeed) This is a perfect (in my opinion) solution for menu, descriptions and everything that isn't extremely unpredictable, but as You pointed before, there is the need to set up a high max-height, and may cut-off a surprisingly tall dynamic content. In this specific situation, I'll use jQuery/JavaScript to animate the height instead. Since the update of the content will be done using some sort of JavaScript already, I can't see any harm using a Js approach to animation. Hope I helped somebody out there! A: You should use scaleY. HTML: <p>Here (scaleY(1))</p> <ul> <li>Coffee</li> <li>Tea</li> <li>Milk</li> </ul> CSS: ul { background-color: #eee; transform: scaleY(0); transform-origin: top; transition: transform 0.26s ease; } p:hover ~ ul { transform: scaleY(1); } I've made a vendor prefixed version of the above code on jsfiddle, http://jsfiddle.net/dotnetCarpenter/PhyQc/9/
{ "language": "en", "url": "https://stackoverflow.com/questions/7572979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "38" }
Q: Trouble styling data-bound WPF ComboBoxItem I have a ComboBox, bound to a DataTable. I'm trying to add an extra ComboBoxItem to the top of the list, where I can put a link to customize the list. Currently I am just inserting a dummy row to the top of my DataTable, and then using a DataTrigger on the ComboBox to make it appear correctly. However, I'm not quite getting the correct result. I've tried two methods. In the first, my DataTrigger replaces the dummy item with a ControlTemplate, which contains a TextBlock. <ComboBox IsEditable="True" Name="comboWell" ItemsSource="{Binding}" DisplayMemberPath="wellId"> <ComboBox.ItemContainerStyle> <Style TargetType="{x:Type ComboBoxItem}"> <Style.Triggers> <DataTrigger Binding="{Binding wellId}" Value="(settings)"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ComboBoxItem"> <TextBlock Text="Customize..." /> </ControlTemplate> </Setter.Value> </Setter> </DataTrigger> </Style.Triggers> </Style> </ComboBox.ItemContainerStyle> </ComboBox> The result looks right, but there is no mouseover highlight on that item. The rest of the list works fine, but that one item doesn't react at all when I mouse over it. I've tried adding extra triggers and styles to apply a mouseover effect, but I get no change. The second method I tried was just to alter the appearance of the item rather than completely replace it with a ControlTemplate. <ComboBox IsEditable="True" Name="comboWell" ItemsSource="{Binding}" DisplayMemberPath="wellId"> <ComboBox.ItemContainerStyle> <Style TargetType="{x:Type ComboBoxItem}"> <Style.Triggers> <DataTrigger Binding="{Binding wellId}" Value="(settings)"> <Setter Property="Content" Value="Customize..." /> </DataTrigger> </Style.Triggers> </Style> </ComboBox.ItemContainerStyle> </ComboBox> This one functions like a regular list item, mouseover works fine. However, the item is blank. Neither the original text, nor the text I try to set in the DataTrigger, are there. No errors, just an empty list item. Is there a better way to accomplish this? A: Remove the DisplayMemberPath and add the default Content to the Style <ComboBox IsEditable="True" Name="comboWell" ItemsSource="{Binding }"> <ComboBox.ItemContainerStyle> <Style TargetType="{x:Type ComboBoxItem}"> <Setter Property="Content" Value="{Binding wellId}" /> <Style.Triggers> <DataTrigger Binding="{Binding wellId}" Value="(settings)"> <Setter Property="Content" Value="Customize..." /> </DataTrigger> </Style.Triggers> </Style> </ComboBox.ItemContainerStyle> </ComboBox> DisplayMemberPath is actually a shortcut way of saying the item template should just be a TextBlock with it's Text bound to the DisplayMemberPath item, and I am guessing it was overwritting whatever you had in the Style.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: 2 UITableViewControllers vs 1 UIViewController that swaps two UITableViews I have a navigation controller that works with two UITableViewControllers. The first UITableViewController shows the user a list of their picture libraries, and when they tap a cell, the second UITableViewController gets pushed on the stack and displays the pictures in the library (much like a UIImagePicker). What I want to do is, when a user selects a photo library on the initial UITableViewController, I want the navigation title to not animate, while the transition of UITableViews does animate. Is there a way to accomplish this, or do I need to implement a UIViewController that swaps in two UITableViews (upon then I'm not sure if I'd be able to edit the back button after the second UITableView gets swapped in?). A: I'm pretty sure that the easiest way would be to add two UITableViews into a UINavigationController's view and just animate them with [UIView beginAnimation] in a didselectrowatindexpath. You should also have a flag to save a view state - either a library picker view is shown to user or an image picker. Then you'll be able to handle this properly in a back button selector. That's the easiest way IMO. A: I'd recommend one UIViewController and animating the frames of the table views to transition between them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Matplotlib: Using a colorbar in conjunction with the extent keyword produces off-center images in figure window I'm using matplotlib to do some plotting. I'd like to be able to use the extent keyword to control the aspect ratio of my plots as well as display the size of the image along the axis tick marks. My problem is that if I try to make an image that is longer in the row direction than it is in the column direction, and then I add in a colorbar the image shifts from the center of the figure canvas to the right side. Some example code would be: import numpy from matplotlib import pyplot pyplot.imshow(numpy.random.random( (100,100) ), extent = [0,50, 100, 0] ) pyplot.colorbar() pyplot.show() Is there a way to keep the image centered in the figure window? Is this a bug? I am using the latest version from the github repository and Python 2.7 on Ubuntu 11.04 A: I don't know why this happen, but you can use cax argument of colorbar() to set the axe which contain the colorbar. import numpy from matplotlib import pyplot pyplot.imshow(numpy.random.random( (100,100) ), extent = [0,50, 100, 0] ) cax = pyplot.axes([0.80, 0.1, 0.04, 0.8]) pyplot.colorbar(cax=cax) pyplot.show()
{ "language": "en", "url": "https://stackoverflow.com/questions/7572988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I get WinForms to stop silently ignoring unhandled exceptions? This is getting extremely irritating. Right now I have a winforms application, and things were not working right, but no exceptions were being thrown as far as I could tell. After stepping through almost all pieces of relevant code, it turns out that an exception was being thrown at the start of my application. Long story short, in WinForms, being as awesome as it is, if an exception occurs the WinForms library ignores it. No "an unhandled exception has occurred" JIT message is thrown, it just stops processing the current event and goes back to the GUI. This is causing random bugs, because code to load data isn't being called due to the exception occurring prior to this data being loaded. To see this in action I created a brand new WinForms application, and entered the following code: public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { string blah = null; blah.Trim(); } } Press F5 and the form loads without any errors showing, even though a null reference is being thrown. I then tried to go to my Program.cs main method and add Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException); to it. Still my form loads without causing any errors to be thrown. Even though I know that I can tell VS to break on all exceptions, I find this situation really bad. It causes really wierd issues that are hard to debug in production, and as this is an internal tool I really want to have it so it actually errors out when an exception occurs, and not silently disregards it. Does anyone know how to do this? Update: Just to update on things I have learned from the comments. This does appear to be a 64-bit issue with windows, as I learned from this question which I did not see before posting. In that question it pointed to a Microsoft bug report about this, which had this to say: Hello, This bug was closed as "External" because this behavior results from how x64 version of Windows handle exceptions. When a user mode exception crosses a kernel transition, x64 versions of Windows do not allow the exception to propagate. Therefore attached debuggers are unaware of the fact that an exception occured resulting in the debugger failing to break on the unhandled exception. Unfortunately where is nothing that the Visual Studo team can do to address this, it is the result of operating system design. All feedback regarding this issue should be addressed to the Windows team; however the Windows team considers this to be the "correct" operating system design, and considers the x86 behavior to be "incorrect". Best Regards, Visual Studio Debugger That being said, builds not run through visual studio (or using Ctrl+F5 to run) does seem to show the JIT exception message box EXCEPT if you have the following code in your Program.cs: Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException); That code will cause windows to ignore the exception. However, if you (instead) subscribe to the Application.ThreadException event, not only will your exceptions be caught, visual studio's debugger will break on unhandled exceptions! A: Try the following. * *Handle exceptions in your main application entry point. *Also, manage unhandled thread exceptions using a ThreadExceptionEventHandler This is the code snippet: [STAThread] public static void Main(string[] args) { try { Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException); //your program entry point } catch (Exception ex) { //manage also these exceptions } } private void Application_ThreadException(object sender, ThreadExceptionEventArgs e) { ProcessException(e.Exception); } A: An easy fix is not to run under the debugger. The debugger is masking the exception for some reason. If you run your app normally (Ctrl+F5), you'll get the usual "Unhandled exception has occurred in your application... Continue/Quit?" dialog. A: In your Program.cs' Main function you should also ensure that you've wrapped your call to open the form in a try/catch. Additionally use the AppDomain.UnhandledException to catch exceptions. We also add Application.ThreadException too. I believe the following will give you hooks into all the exceptions that can be thrown... static void Main() { try { System.Windows.Forms.Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); System.Windows.Forms.Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(OnGuiUnhandedException); AppDomain.CurrentDomain.UnhandledException += OnUnhandledException; var form = new MainForm(); form.ShowDialog(); } catch (Exception e) { HandleUnhandledException(e); } finally { // Do stuff } } private static void HandleUnhandledException(Object o) { // TODO: Log it! Exception e = o as Exception; if (e != null) { } } private static void OnUnhandledException(Object sender, UnhandledExceptionEventArgs e) { HandleUnhandledException(e.ExceptionObject); } private static void OnGuiUnhandedException(object sender, System.Threading.ThreadExceptionEventArgs e) { HandleUnhandledException(e.Exception); } A: Having experienced this often and identified the issue regarding 64 bit OS and the Form.Load event, I always just make a point of doing all my start up functions in the Form.Shown event. For all practical purposes this is the same thing (aside from a few rare, exceptional circumstances), and the JIT message is produced in the Shown event.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572995", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "33" }
Q: How to make jQuery objects from an array? anArray = ['thing1','thing2','thing3']; $.each(anArray, function (i,el) { var object = 'name.space.' + el; var selector = 'node-' + el; var object = $('#' + selector);//need object here to be interpreted as it's value //as if: var name.space.thing1 = $('#' + selector); }); such that these are usable jQuery objects: console.log(name.space.thing1); console.log(name.space.thing2); console.log(name.space.thing3); I feel like eval() is involved. I'm hydrating navigation selectors so as pages are added/removed, we just update the array. We could build the array from the nav nodes, but either way, we still need to be able to make these namespaced selectors... A: You will have to use bracket notation: var array = ['thing1', 'thing2']; var object = {}; object.space = {}; $.each(array, function () { object.space[this] = $('#node-' + this); }); console.log(object.space.thing1); // [<div id="node-1">]; A: I am not sure what are you trying to accomplish, but name.space[el] = $('#' + selector); might work. Object properties are always accessible with the bracket notation as well. This means that obj.xy is just the same as obj['xy'], but the latter is more flexible and can be used in situations like yours. A: var anArray = ['thing1','thing2','thing3']; var name = {space:new Array()}; $.each(anArray, function (i,el) { var selector = 'node-' + el; name.space[el] = $('#' + selector); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7572996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Read Excel data from C# I'm trying to read data from an Excel sheet using Office.Interoperability.Excel namespace. I'd like to get the first row of the sheet as the first row contains the headers, without specifying the start and end cells. Because I wouldn't know if a new column is added to the sheet. Microsoft.Office.Interop.Excel.Application excelObj = new Application(); Microsoft.Office.Interop.Excel.Workbook myBook = excelObj.Workbooks.Open(@"D:\myFile.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 0, 0); Microsoft.Office.Interop.Excel.Worksheet mySheet = (Worksheet)myBook.Sheets.get_Item(1); Range range = mySheet.Cells.EntireRow; Here, the range becomes the entire range and it doesn't get limited to the number of header columns. Also I've a huge data of about 10,000 rows to process. A: If you requirement doesnt involve writing back to the excel file I would suggest that you use Excel Data Reader (http://exceldatareader.codeplex.com/) its a lot easier to use, doesnt require excel on the server and its faster A: I think you're looking for this: Range headers = mySheet.UsedRange.Rows(1); A: I just answered another Excel reading question here: C# converting .xls to .csv without Excel The FileHelpers library is perfect for your task. I use it myself for those numbers of rows and above. I don't know what you are doing with the rows once they are read from Excel, but if you a looking at some processing that could be broken down into step, have a look at Rhino.Etl for that. It's a really powerful way to process large amounts of data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: My Rails application is only giving me a blank screen, with no HTML at all I have an app that I haven't worked with in a month or so. I just tried to pull it up, and it is giving me only a blank screen. I am running in dev mode, and monitoring the log. The log shows that everything is OK, in that it is processing the appropriate controller and views. The nginx log shows no errors. How can I troubleshoot what is happening? This is a Rails 3.0.9 application. This appears to be a Passenger issue. Unfortunately, Passenger isn't writing any errors that I can see in the logs. I'm getting 200's from nginx also. I have never see something return no HTML at all without errors before. Update: This is the output from curl -I http://mcp.com (note that I have mcp.com aliased to localhost) HTTP/1.1 200 OK Content-Type: text/html; charset=utf-8 Content-Length: 0 Connection: keep-alive Status: 200 X-Powered-By: Phusion Passenger (mod_rails/mod_rack) 3.0.7 ETag: "17676b3c3d3b322365c8d431f62f944b" X-UA-Compatible: IE=Edge,chrome=1 X-Runtime: 9.088870 Set-Cookie: _mcp5_session=BAh7CCIQX2NzcmZfdG9rZW4iMVNGRHZ1WVNLZFRIeTh1Sm1lNytyVEU3TkhmQU1pVWZSdXBud2htcFRHSGs9IhRlbnRyeV9zdWJkb21haW4iACIPc2Vzc2lvbl9pZCIlMjA1NGIxNTRmN2M2NTQyNDU1ZTVmZjExYzRjNDhlMTY%3D--c3d21d4bb07a4989243b655aff3d49863d8c81f7; domain=.mcp.com; path=/; HttpOnly Cache-Control: max-age=0, private, must-revalidate Server: nginx/1.1.4 + Phusion Passenger 3.0.7 (mod_rails/mod_rack) A: Usually that's caused by an exception in production mode, so to see it in dev mode might be an artifact of your server. Investigate if your launcher, like Passenger, is working correctly or not. If script/console or rails console starts up okay, and you can access it through script/server or rails server then you should be able to narrow it down to the web server level.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How do I update a table with rails using data from a form I have a table in a database with two columns, Name and ID. I have a rails model for it named FakeTable. I have a controller for the model: class FakeTablesController < ApplicationController def index @data = FakeTable.find(:all) end def to_index redirect_to( :action => "index" ) end def update redirect_to( :action => "index" ) end end I have a form to display the information in this table: <table> <thead> <tr> <th><%= "Name" %></th> </tr> </thead> <tbody> <% form_tag :action => "update" %> <% @data.each_with_index do |d, index| %> <% fields_for "d[#{index}]", d do |f| %> <tr> <td class="tn">Name: <%= f.text_field :name %></td> <td class="tn">Id: <%= f.text_field :id %></td> </tr> <% end %> <% end %> </tbody> </table> <%= submit_tag 'Update' %> <%= end_form_tag %> I have two questions. First, how do I use the ID to access each row in the table to display the data? Currently I use these two lines of code to access get each row in the table: <% @data.each_with_index do |d, index| %> <% fields_for "d[#{index}]", d do |f| %> I would like to change this so it uses the ID column instead. My second question is, when I click the "Update" button, I want the data in the table to be updated from text fields in the form. How would I do that? I am using ruby on rails 2.3.8. Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/7573006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Read a cell (or range of cells) directly from an open workbook in Excel using C#? Possible Duplicate: Reading Excel files from C# Is there a way to read a cell (or range of cells) directly from an open Excel or OpenOffice worksheet? I have a graphing app that can read .csv files but would like to read straight from Excel to make it more interactive.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573007", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to block a part of the level plot in R made using lattice package? I have made a level plot in R of a variable using the lattice package. This grid corresponds to South Asia. I am only interested in viewing the values of this variable (aerosol optical depth) for certain countries in South Asia. I have a dummy variable that takes the value 1 for the countries I am interested in and 0 otherwise. Is it possible for me to colour this part of the grid black or any other colour? I cannot show the level plot as I am low on reputation with stackoverflow. (The pdf that was attached to the crossposted message to rhelp should now appear:) Here is my R code: levelplot(aod ~ longitude + latitude | factor(day), data = aod_Jan, aspect="iso", contour = TRUE, layout=c(1,1)) A: Since you are using geographical data, maybe the raster package is useful for you. For example, let's display the altitude of France (download this zip file or use the raster::getData function). After you unzip the file: library(raster) fraAlt <- raster('FRA_alt') plot(fraAlt) ## Not only France is displayed... If you want to display only the altitude of France, you need the information of the boundaries: download this RData file (or use the raster::getData function). This RData contains a SpatialPolygonsDataFrame (named gadm) which can be converted to a Raster with: mk <- rasterize(gadm, fraAlt) Now you can mask the altitude raster with the boundaries: fraAltMask <- mask(fraAlt, x) plot(fraAltMask) ##Now only France is displayed Finally, if you want to use lattice methods you need the rasterVis package: library(rasterVis) levelplot(fraAlt) levelplot(fraAltMask) Now, all together with the boundaries superimposed: s <- stack(fraAlt, fraAltMask) layerNames(s) <- c('Alt', 'AltMask') boundaries <- as(gadm, 'SpatialLines') levelplot(s) + layer(sp.lines(boundaries)) A: Use the subset argument to levelplot. Perhaps: levelplot(aod ~ longitude + latitude | factor(day), data = aod_Jan, subset = dummy==1, aspect="iso", contour = TRUE, layout=c(1,1))
{ "language": "en", "url": "https://stackoverflow.com/questions/7573011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: VWD Express 2010 CommandType I just converted a website from Foxpro to asp.Net with VB. I'm now trying to convert to C# and maybe try a few new techniques. I've not used parameters with datareader before - I found some code that looks similar to what I want to do; however, Intellisense doesn't recognize the command. cmd.CommandType=CommandType.StoredProcedure; where cmd is of type SqlCommand. I have a line up top ... using System.Data.SqlClient; Is there something else I need to include? Intellisense is not recognize "CommandType" A: Add the following namespace. using System.Data;
{ "language": "en", "url": "https://stackoverflow.com/questions/7573012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MVC error - The model item passed into the dictionary is of type 'System.Collections.Generic.List` I can't figure out what's going on with this error: The model item passed into the dictionary is of type 'System.Collections.Generic.List1[RepositoryExample.Employee]', but this dictionary requires a model item of type 'RepositoryExample.Models.IEmployeeManagerRepository'.` I get the error when I go to the Index view. I added the Index View from the controller but there is no code in it. I'm using Linq to SQL. @model RepositoryExample.Models.IEmployeeManagerRepository @{ ViewBag.Title = "Index"; } <h2>Index</h2> This is my code: EmployeeController.cs // GET: /Employee/ public ActionResult Index() { return View(_repository.ListEmployees()); } LinqEmployeeManagerRepository.cs public class LinqEmployeeManagerRepository: RepositoryExample.Models.IEmployeeManagerRepository { private DeptDirectoryDataClassesDataContext _db = new DeptDirectoryDataClassesDataContext(); public Employee GetEmployee(string UserName) { return (from e in _db.Employees where e.UserName == UserName select e).FirstOrDefault(); } public IEnumerable<Employee> ListEmployees() { return _db.Employees.ToList(); } public Employee CreateEmployee(Employee employeeToCreate) { _db.Employees.InsertOnSubmit(employeeToCreate); _db.SubmitChanges(); return employeeToCreate; } public Employee EditEmployee(Employee employeeToEdit) { var OriginalEmployee = GetEmployee(employeeToEdit.UserName); _db.Employees.Attach(employeeToEdit, OriginalEmployee); _db.SubmitChanges(); return employeeToEdit; } public void DeleteEmployee(Employee employeeToDelete) { var OriginalEmployee = GetEmployee(employeeToDelete.UserName); _db.Employees.DeleteOnSubmit(OriginalEmployee); _db.SubmitChanges(); } } IEmployeeManagerRepository.cs namespace RepositoryExample.Models { public interface IEmployeeManagerRepository { Employee CreateEmployee(Employee employeeToCreate); void DeleteEmployee(Employee employeeToDelete); Employee EditEmployee(Employee employeeToUpdate); Employee GetEmployee(string UserName); IEnumerable<Employee> ListEmployees(); } } Any ideas what I'm doing wrong? I'm trying to follow the example on Repository pattern in this tutorial: http://www.asp.net/mvc/tutorials/iteration-4-make-the-application-loosely-coupled-cs. A: In the top of your Index.cshtml view replace: @model RepositoryExample.Models.IEmployeeManagerRepository with: @model IEnumerable<RepositoryExample.Employee> The _repository.ListEmployees() method returns IEnumerable<Employee> and that's what you are passing to the view here: return View(_repository.ListEmployees()); So that's the type you should be using in the @model directive in your view.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: What are some good resources for learning algorithm optimization? I've been tinkering around with code (Basic, Python, C++, PHP, JavaScript) on and off for almost two decades, but have only recently begun to get more "serious" about it (using Java). I can write code to do what I want, but now I want to learn to optimize my programs to run faster (looping through an array for every element in an array can get slow very quickly, etc). What I don't want is to be popping onto this site every 5 minutes for every little question I have. I want to learn to answer my own questions. That said, what are some good resources for learning algorithm analysis and optimization? I have a copy of Data Structures and Algorithms in Java (3rd edition) but I feel it's written to mostly be incorporated into a college curriculum and isn't very easy to use sans-professor. The book also has a tendency to over-use abbreviations, making it hard to flip to a particular chapter without having to skim back through the book to understand what each abbreviation stands for. I do have some knowledge of Calculus, but it's extremely rusty, so I would prefer resources that give more explanation and fewer formulas. Thank you in advance for all the help you can give! A: You might start with Skiena's Algorithm Design Manual. The same author also has a book on puzzle-solving called Programming Challenges, which gives you a more entertaining way to get practice with algorithms than slogging through a textbook. A: I can't recommend enough Michael Abrash's "The Zen of Code Optimization". It's easyto read and full of insights. The parts that focus on pre-pentium x86 are dated, but it's real value is the focus on how to think about making code faster. I believe it's out of print, but you may find a used copy online.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573021", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Work with authenticity token? Or disable it? My mini-web-appliance will submit data samples to a RoR app, which will add them to a MySQL table. I figured out how to form the POST data packet, but what I don't get is how to avoid the authenticity-token problem. Is there a way for my little dumb client to grab the right token and send it back? (I'm guessing not, or it wouldn't be much of a security feature). This is not a highly security-sensitive application, so should I just tell this page to ignore the authentity-token altogether? It will hopefully be authenticated by the fact that each client (web appliance) logs in with a unique user ID and password, so it would be protected by the session ID. If I'm using "loose" language, please feel free to correct me. I'm new to deploying sites. Keb'm A: If each client is authenticated then it's ok to disable the authenticity token, that said you should only disable it for that one action. skip_before_filter :verify_authenticity_token, :only => :create A: If each client is authenticated then it's ok to disable the authenticity token This is only true if you're using another authentication mechanism than http cookies. Because you've mentioned 'session_id', i assume this is not the case. With a standard rails session_id cookie, the user_id stored in a session and this action being accessible by a webbrowser, it will be exposed to csrf attacks. The best strategy for api's is implementing a custom authentication mechanism, some sort of authentication token, which is send with every http header. Then either change the csrf protection to null_session or if you are less paranoid disable csrf protection entirely for your api request as described here If you still want to stick with cookie based authentication for your api, you should set the csrf authenitcation token with the first GET request into an extra cookie. Then you read this cookie and send it's token as 'X-CSRF-Token' header. Rails will check for this header in the protect_from_forgery method and as cookies cannot be read by 3d parties an attacker will not be able to forge this request. #application_controller.rb protect_from_forgery with: :exception after_action :set_csrf def set_csrf cookies['X-CSRF-Token'] = form_authenticity_token if protect_against_forgery? end # request session and x-csrf-toke # the cookies will be stored into cookie.txt curl -c cookie.txt http://example.com #curl post command curl -H "X-CSRF-Token: <token>" -b cookie.txt -d '{"item":{"title":"test"}}' "http://example.com/items.json" See :verified_request? method to see how rails check for request forgery.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: implementing big5 over telnet protocol? I've implemented a telnet client and one of the feature requests is to support big5 encoding. How is Big5 implemented over telnet, when only 7-bit character codes are supported? The Big5 "lead bytes" (0x81 to 0xfe) are all in the range above 0x7f reserved by the telnet protocol. Of course, if I took out VT100 escape code parsing and treated non telnet-escape-sequence bytes as plain big5-encoded text, that would probably work, but I don't know if that's the standard (if there even is a standard). Also, is there an equivalent to the VT100 terminal protocol for Big5 encoding? FYI: This project is written in C# and runs on windows phone silverlight. A: I think you want RFC2066, which describes the TELNET CHARSET Option.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: When I use update() with tkinter my Label writes another line instead of rewriting the same text When I call the update() method using tkinter instead of rewriting the label it just writes the label under the previous call. I would like for this to rewrite over the previous line. For Example: root=Tk() while True: w=Label(root, text = (price, time)) w.pack() root.update() A: No. I suspect, without having seen it, that there are at least a couple of confusions in the code wDroter has written. In general, it is NOT necessary in well-structured Tkinter code to use update() at all. Here's a small example that illustrates updates to the text of a Label: import Tkinter import time def update_the_label(): updated_text = time.strftime("The GM time now is %H:%M:%S.", time.gmtime()) w.configure(text = updated_text) root = Tkinter.Tk() w = Tkinter.Label(root, text = "Hello, world!") b = Tkinter.Button(root, text = "Update the label", command = update_the_label) w.pack() b.pack() root.mainloop() Run this. Push the button. Each time you do so (as long as your pushes differ by at least a second), you'll see the text update. A: you want to use .configure insted while True: w.Configure(text = (price, time)) root.update() A: instead of w.pack() you can write w.grid(row=0, column=0) pack() in tkinter usually packs things in a single row/column. It lays things out along the sides of a box. Whereas, grid() has more of a table like structure. So when you write row=0 and column=0, it has no choice but to replace the previous if it exists. Because you have provided a very specific position instead of just pushing it to the window (which is hat pack() does) A: Your problem is simply this: when you do while True, you create an infinite loop. The code in that loop will run until you force the program to exit. In that loop you create a label. Thus, you will create an infinite number of labels. If you want to update a label on a regular basis, take advantage of the already running infinite loop - the event loop. You can use after to schedule a function to be called in the future. That function can reschedule itself to run again, guaranteeing it will run until the program quits. Here's a simple example: import Tkinter as tk import time class SampleApp(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.clock = tk.Label(self, text="") self.clock.pack() # start the clock "ticking" self.update_clock() def update_clock(self): now = time.strftime("%H:%M:%S" , time.gmtime()) self.clock.configure(text=now) # call this function again in one second self.after(1000, self.update_clock) if __name__== "__main__": app = SampleApp() app.mainloop() A: The BadRoot class should demonstrate the problem that you are having. You can comment out the call to the class to verify with a complete, working example. If you run the code as written, it will update the label in the GoodRoot class. The first line that is commented out shows an alternative syntax for changing the text in your label. from tkinter import Tk, Label from time import sleep from random import random class BadRoot(Tk): def __init__(self, price, time): super().__init__() self.labels = [] while True: self.labels.append(Label(self, text=(price, time))) self.labels[-1].pack() self.update() sleep(1) class GoodRoot(Tk): def __init__(self, callback): super().__init__() self.label = Label(self, text=str(callback())) self.label.pack() while True: ## self.label['text'] = str(callback()) self.label.configure(text=str(callback())) self.update() sleep(1) if __name__ == '__main__': ## BadRoot('$1.38', '2:37 PM') GoodRoot(random) The problem with your original code is that a new label is created and packed into the interface each time through the loop. What you actually want to do is just edit the text being displayed by the label instead replacing the label with a new one. There are others ways of doing this, but this method should work for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: future.get returning before finally executed in Callable on cancel I'm have a test that is failing intermittently where a future.get call is returning before the finally block is executed in the Callable, when the future is canceled. Here's the basic workflow: future.cancel(true); I see the InterrupedException thrown in the Callable The main thread catches CancellationException from the future.get call Now the Callable calls finally. The test is always successful on my notebook and fails most of the time on our build server. Both my notebook and the build server are running OpenJDK 1.7. Any ideas? A: The documentation of cancel() doesn't seem to specify that it waits for the interrupted thread to exit. If you want that guarantee, you'll have to set up a monitor or some other synchronization mechanism whereby the canceler can wait for the processor to say "I'm done with my finally-block".
{ "language": "en", "url": "https://stackoverflow.com/questions/7573033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Identifying and removing "NA"s and other errors Possible Duplicate: Test for NA and select values based on result Suppose you have a vector -- you do a calculation on the vector -- many of the elements return "NA" -- how do you identify these "NA"s and change them to some usable integer A: Assuming that your data is in dat (could be a vector, matrix, or data frame): dat[is.na(dat)]<-0 replaces all NA entries of dat with 0.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573035", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: IF Statement not working correctly I have these controls: chck1_amt through chck5_amt (1 though 5 check Amounts) And chckX is from chcknum1 through chcknum5 (1 through 5 check numbers What we are trying to do is if a checkX_amt box has is not blank or it has a value other than a 0 AND check number box (chcknumX) is blank, then inform a user that check number box must contain a check number. Stay focused on that box till the user has entered a checknumber. This appeared to have worked until today when it keeps asking for check number whether there is a value in checkamount box or not. Here's the code: if ((document.getElementById('chck1_amt').value != "" || document.getElementById('chck1_amt').value != "0") && (document.getElementById('fvEmp_chcknum1').value == "")) { alert("Please enter check # to continue"); document.getElementById('chcknum1').focus(); return false; } if (((document.getElementById('chck2_amt').value != "") || (document.getElementById('chck2_amt').value != "0")) && (document.getElementById('fvEmp_chcknum2').value == "")) { alert("Please enter check # to continue"); document.getElementById('chcknum2').focus(); return false; } if ((document.getElementById('chck3_amt').value != "0") && (document.getElementById('chcknum3').value == "")) { alert("Please enter check # to continue"); document.getElementById('chcknum3').focus(); return false; } if ((document.getElementById('chck4_amt').value != "0") && (document.getElementById('chcknum4').value == "")) { alert("Please enter check # to continue"); document.getElementById('chcknum4').focus(); return false; } if ((document.getElementById('chck5_amt').value != "0") && (document.getElementById('chcknum5').value == "")) { alert("Please enter check # to continue"); document.getElementById('chcknum5').focus(); return false; } <tr> <td><input name="chcknum1" type="text" id="chcknum1" style="width:90px;" /></td><td><input name="chck1_amt" type="text" id="chck1_amt" style="width:90px;" /></td><td> </tr><tr> <td><input name="chcknum2" type="text" id="chcknum2" style="width:90px;" /></td><td><input name="chck2_amt" type="text" id="chck2_amt" style="width:90px;" /></td><td> </tr><tr> <td><input name="chcknum3" type="text" id="chcknum3" style="width:90px;" /></td><td><input name="chck3_amt" type="text" id="chck3_amt" style="width:90px;" /></td><td> </tr><tr> <td><input name="chcknum4" type="text" id="chcknum4" style="width:90px;" /></td><td><input name="chck4_amt" type="text" id="chck4_amt" style="width:90px;" /></td><td> </tr><tr> <td><input name="chcknum5" type="text" id="chcknum5" style="width:90px;" /></td><td><input name="chck5_amt" type="text" id="chck5_amt" style="width:90px;" /></td><td> </tr> A: I might be missing something, but it looks like your logic is backwards, as anything other than "" or "0" will prompt the user to enter a check number. Shouldn't the condition be something like this?: EDIT Thanks for your comment. I understand your question now. I still think that there is an issue with your logic though. If the user should be prompted for input when the value is anything other than "" or 0, the logic should be like this: if (document.getElementById('chck5_amt').value.trim() != "0" && document.getElementById('chck5_amt').value.trim() != ""){ //prompt for check number } You might want to add some additional checks to make sure that the input boxes are being found: var input = document.getElementById('chck5_amt'); //uncomment the line below to validate that the input was found //alert(input); if (input){ if (input.value.trim() != "0" && input.value.trim() != ""){ //prompt for check number } } A: Something like this: if (document.getElementById('chck1_amt').value && Number(document.getElementById('chck1_amt').value) && !document.getElementById('chcknum1').value && !Number(document.getElementById('chcknum1').value)) { alert('Check 1 has an amount but does not have a valid check number'); document.getElementById('chcknum1').focus(); return false; } etc
{ "language": "en", "url": "https://stackoverflow.com/questions/7573045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Eclipse PDT: Syntax Errors with valid PHP Namespace Syntax I'm using Eclipse 3.6 (Helios) with PDT 2.2, and I'm getting syntax errors when trying to "use" namespaces. Is there something I can do to fix this? Example: use Tables\Exceptions\Exception as Exception; The PHP Parser recognizes "Tables" as a syntax error on this line and others like it. A: This is probably related to your interpreter settings in Eclipse. Go to the Project menu and select Properties. Once you have the Properties screen up you can go to PHP Interpreter and adjust the PHP Version, either at the project level or the Workspace level. Set the PHP Version to 5.3 or higher for proper highlighting. If your project is in PHP 5.2 than you won't be able to use namespaces. See here: Namespaces in php 5.2
{ "language": "en", "url": "https://stackoverflow.com/questions/7573050", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Implement equals with Set I have this class: private static class ClassA{ int id; String name; public ClassA(int id, String name){ this.id= id; this.name = name; } @Override public boolean equals(Object o) { return ((ClassA)o).name.equals(this.name); } } Why this main is printing 2 elements if I am overwriting the method equals in ClassA to compare only the name? public static void main(String[] args){ ClassA myObject = new ClassA(1, "testing 1 2 3"); ClassA myObject2 = new ClassA(2, "testing 1 2 3"); Set<ClassA> set = new HashSet<ClassA>(); set.add(myObject); set.add(myObject2); System.out.println(set.size()); //will print 2, but I want to be 1! } If I look into the Set Java documentation: A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction. So apparently I only have to override equals, however I heard that I have also to override the hashcode, but why? A: They have different hashes because you didn't override hashCode. This means they were put in two different buckets in the HashSet, so they never got compared with equals in the first place. I would add public int hashCode() { return name.hashCode(); } Notice id isn't used in the hashCode because it isn't used in equals either. (P.S. I'd also like to point out the irony of having an id that isn't used in equals. That's just funny. Usually it's the other way around: the id is the only thing in equals!) A: Because you didn't override hashCode() as well. programmers should take note that any class that overrides the Object.equals method must also override the Object.hashCode method in order to satisfy the general contract for the Object.hashCode method. In particular, c1.equals(c2) implies that c1.hashCode()==c2.hashCode(). http://download.oracle.com/javase/6/docs/api/java/util/Collection.html And: The general contract of hashCode is: * *Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application. *If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. *It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables. http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#hashCode()
{ "language": "en", "url": "https://stackoverflow.com/questions/7573055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Any existing RSS feed url validators? Before I dive into writing a validator to check if a URL is actually pointing to an RSS feed, I did a bit of searching for some validators that may exist out there but had little luck with any reliable ones. I just wanted to ask the community if any of you know of an RSS validator by URL? If I were to write my own, what do you suggest? I was thinking of just checking for the first instance of a line of text and making sure it defines <?xml version="1.0" encoding="UTF-8"?> and then perhaps checking that the next item is an <rss> node. What are your thoughts here? Could there ever be a case where a feed may not follow the syntax stated above? Also note, one method I attempted to use was the following: $valid = true; try{ $content = file_get_contents($feed); if (!simplexml_load_string($content)){ $valid = false; } } catch (Exception $e){ $valid = false; } Unfortunately it seems that I cannot suppress warnings (error_reporting(0) is not working..) so the just spams me with warnings. SOLUTION For anyone that is interested, I used the W3C Validator API $url = "http://feed_url.com"; $validator = "http://validator.w3.org/feed/check.cgi"; $validator .= "?url=".$url; $validator .= "&output=soap12"; $response = file_get_contents($validator); $a = strpos($response, '<m:validity>', 0)+12; $b = strpos($response, '</m:validity>', $a); $result = substr($response, $a, $b-$a); echo $result; This will return true or false accordingly. A: The W3C Feed Validation Service offers a SOAP interface. From the About page: Is there a Web Service with a public API for this service? Yes, there is a SOAP interface, accessible by using the query parameter output="soap12" on top of a regular query. The SOAP 1.2 Web Service API documentation has more details. A: I would do this: * *Is it valid XML? If so, continue. *Is the top-level element either rss or feed? If so, it's a feed. If not, it's not. That covers all versions of RSS except 1.0 and all versions of Atom. RSS 1.0 is more difficult since its top level element is RDF, and that's a more generic format than RSS, so you'd have to look deeper for indications of RSS-ness. But luckily there's not much RSS 1.0 out there these days, most of it is RSS 2.0 or Atom 1.0. Hope this helps, with the usual disclaimers, I am not a lawyer, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is it possible to have ruby 1.87 and ruby 1.9 installed and switch between them for different apps? How I'm using different books to learn rails and they're all using different versions of ruby and rails. I've got instructions on how to load/use different versions of rails, but I don't know how to do it with ruby. Can anyone tell me if this is possible and how to indicate which ruby I am using for each app? i'm using mac os snow leopard. ruby 1.87 is installed currently in usr/bin A: Use rvm. It manages different ruby versions and even different gemsets (e.g. per application). A: And if you are using Windows, you could use Pik instead. Does similar things, and allows to explicit switch between ruby versions. You then have to write batch files and switch there explicitly to the right version of ruby before starting the ruby application. It will ensure that the path, load-path, gems, ... are all setup correctly. A: The combination of rbenv and ruby-build are a lighter weight alternative to the aforementioned RVM, though I prefer RVM personally.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573067", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Django - Limit select field to queryset of foreign table? I have two models as follows: System_Contact first_name last_name isOwner = CharField ('Y'/'N') isMainContact = CharField ('Y'/'N') System mainContact = ForeignKey(System_Contact) owner = ForeignKey(System_Contact) billTo = ForeignKey(System_Contact) So, when I show the System form in a web page, the user can select the mainContact owner and billTo contacts from a drop down menu to save to the System model. However, I want to filter the select fields in the System form so that they are like this: mainContact Select box: -- only show System_Contacts that have isMainContact = 'Y' owner Select Box: -- only show Syste_Contacts that have isOwner = 'Y' As it is now, I know how to limit a select box by filtering the queryset, but I don't know how to filter the related Foreign Key querySet. Since the mainContact and owner fields are Foreign Keys, I need to filter the Foreign Table (System_Contact), not the table on which the form is built (System) I know how to filter a normal, non Foreign Key type select box as follows: form.fields["some_field"].queryset = Some_Model.objects.filter(some_field="Foo") How would I 'extend' this so that it filters the Foreign table? This is what I am trying currently, without success: form.fields["mainContact"].queryset = System_Contact.objects.filter(isMainContact = 'Y') Thanks A: This is what I am trying currently, without success: form.fields["mainContact"].queryset = System_Contact.objects.filter(isMainContact = 'Y') Can you include your model form and view? That looks OK to me. Another approach is to override the __init__ method of your model form and set the queryset there. class SystemForm(ModelForm): def __init__(self, *args, **kwargs): super(SystemForm, self).__init__(*args, **kwargs) self.fields["mainContact"].queryset = System_Contact.objects.filter(isMainContact = 'Y') class Meta: model = System As an aside, I would recommend using a BooleanField instead of a CharField with 'Y' and 'N' as choices. A: That syntax looks correct. Are you receiving an error or is it just not filtering and showing everybody? Try the System_Contact.objects.get(id=<some valid id>) to see if it gets only one or more. If it gets more, perhaps it is being populated from a different call than the one intended. A: Well this is embarrassing... As I was pasting in my view and model form as per Alasdair's request, I noticed my error. Here is my (incorrect) view: def system_contacts(request, systemID): sys = System.objects.get(pk=systemID) if request.method == 'POST': form = System_Contacts_Form(request.POST, instance=sys) form.fields["systemOwner"].queryset = System_Contact.objects.filter(systemOwner__exact='Y') form.fields["mainContact"].queryset = System_Contact.objects.filter(isMainContact__exact = 'Y') if form.is_valid(): form.save() return HttpResponseRedirect('/systems/') else: conts = Contact_List.objects.filter(systemID = sys.pk) form = System_Contacts_Form(instance=sys) return render_to_response('pages/systems/system_pages/contacts.html', {'sys':sys, 'form':form, 'conts':conts}, context_instance=RequestContext(request)) I had put the form.fields["systemOwner"]... part in the POST section of the view, not the GET section of the view. Here is my corrected view: def system_contacts(request, systemID): sys = System.objects.get(pk=systemID) if request.method == 'POST': form = System_Contacts_Form(request.POST, instance=sys) if form.is_valid(): form.save() return HttpResponseRedirect('/systems/') else: conts = Contact_List.objects.filter(systemID = sys.pk) form = System_Contacts_Form(instance=sys) form.fields["systemOwner"].queryset = System_Contact.objects.filter(systemOwner__exact='Y') form.fields["mainContact"].queryset = System_Contact.objects.filter(isMainContact__exact = 'Y') return render_to_response('pages/systems/system_pages/contacts.html', {'sys':sys, 'form':form, 'conts':conts}, context_instance=RequestContext(request)) Now my corrected view works and the filtering works on the select inputs on the form. I would not have thought to look at that without your help. Cheers :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7573074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Fortran: Read one value at a time from a line I am using FORTRAN to read in data from an ASCII text file. The file contains multiple data values per line but the number of values per line is not constant. 101.5 201.6 21.4 2145.5 45.6 21.2 478.5 ... Normally after a read statement, Fortran would go to the next line. What I want to be able to do is read one data value at a time. If it hits the end of the line, it should just continue reading on the next line. Is this possible? A: As pointed out by IRO-bot in their comment to your question, the answer has already been given by M.S.B. Below I have merely provided some code illustrating that answer (as M.S.B.'s post contained none): program test character(len=40) :: line integer :: success, i, indx, prev, beginning real :: value open(1,file='test.txt') do read(1,'(A)',iostat=success) line if (success.ne.0) exit prev = 1 beginning = 1 do i=1,len(line) ! is the current character one out of the desired set? (if you ! have got negative numbers as well, don't forget to add a '-') indx = index('0123456789.', line(i:i)) ! store value when you have reached a blank (or any other ! non-real number character) if (indx.eq.0 .and. prev.gt.0) then read(line(beginning:i-1), *) value print *, value else if (indx.gt.0 .and. prev.eq.0) then beginning = i end if prev = indx end do end do close(1) end program test When running this program using the sample lines you provided the output is 101.5000 201.6000 21.40000 2145.500 45.60000 21.20000 478.5000 I hope you will find this helpful.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why doesn't the Objective-c runtime set dealloc'd object instances to nil? Sometimes I set objects to nil after releasing them to avoid crashes due to unexpected messages sent to dealloc'd objects. Why doesn't the Objective-c runtime do this automatically when an object is finally dealloc'd? A: Because pointers are passed by value and not reference. All dealloc gets is a local copy of the pointer; any changes it makes are discarded. Same goes for C's free and C++'s delete. A: How would the runtime be able to track down all such references? MyClass* a = [MyClass new]; MyClass* aCopy = a; [a release]; a = nil; // Tidy up [aCopy crashNowPlease]; Sometimes you can catch this sort of thing with Build & Analyze. Also, you will be able to use zeroing weak references in the future (or, Mike Ash created such a facility). A: In objective-C, the objects are always accessed as pointer. Setting an object to nil simply change the pointer value, not the object value. In your method, you have only access to the object's value, not to the pointer pointing to it! As @David Dunham says, you can have more than one pointer to an object, so how would the compiler knows? And more than that, to make things easier, imagine the following code : int a; int* aPtr = &a; If you change a value, you can access the changed value via *aPtr right? But you can change a value as long as you want, it won't change aPtr value, as it is not the same variable! Thus, even if you only have one pointer to your object, if you modify the object's value, you pointer will still point to the same address value! A: What you are describing is called a zeroing weak reference. This feature is available in OS X 10.7's Automatic Reference Counting (ARC) runtime. Prior to 10.7, you can use Mike Ash's zeroing weak reference implementation. Without explicit runtime support (and some small but unavoidable overhead), standard C-style pointers (id in Objective-C is a pointer to a structure) are just a memory address (an integer) and not tracked by the runtime. There's nothing stopping you from making copies of this value elsewhere in memory or from storing the value in an integer of the appropriate size and casting to an id later on (of course if you do any of this, you kill a baby seal). Thus, when an object is dealloc'd there's no way to know where (or how many) references there are to that object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Page navigation with fixed header I have a horizontal fixed header on top of my site and when I use page navigation to scroll to an ID, it puts the content I'm trying to scroll to underneath the header. Is there a way I can offset where the page navigation shows up by 80 pixels (down)? Edit: I was actually able to fix it myself in the simplest and most acceptable manner possible. I put the solution in an answer below. A: Well, since no one else had an answer, I fixed it myself. Here is the fix: JSFiddle This was done by making a hidden div that is absolutely positoned 'x' amount of pixlels above the content I want to scroll to. I then scroll to that div instead of the content I originally wanted to scroll to. 'x' should be the height of your header, this way the content you want to scroll to appears directly below your header like it should. A: You can do that with CSS. HTML: <header>Your Header Here</header> <div id=main>Rest of Content</header> CSS: header { position: fixed; height: 80px; } #main { margin-top: 80px; } A: Try reading this artcle from Chris Coyier. He cleverly uses a pseudo-element to solve the "fixed header in page navigation" issue. Take a look: http://css-tricks.com/hash-tag-links-padding/. A: The example doesn't show how it works. I fixed it by adding: #header { opacity:0.5; } #content-scroller { height:120px; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7573089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }