text
stringlengths
8
267k
meta
dict
Q: gmaps4rails trigger side bar click event I'm using gmaps4rails sidebar function to allow jumping to individual marker on the map. My question is: how can I trigger the click event on the first sidebar item so the 1st marker's info window will be display by default? A: You should just add a callback: Gmaps.map.callback = function() { var firstMarker = Gmaps.map.markers[0]; var map = Gmaps.map.map; firstMarker.infowindow.open(map, firstMarker.serviceObject); } Be sure to put this callback after the gmaps helper in your view.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585924", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What do people think of the new HTML5Boilerplate with the Normalizer.css Hello fellow designer/developers! So I have just been updating my HTML5 template and I have been trying to incorporate all the latest tips and tricks but in the end settled on combining HTML5Boilerplate with Grid960. One big change to the HTML5Boilerplate is the use of Normalizer.css - This is a little weird for me because I am used to seeing the classic resets floating around the net. Has anyone used the new Boilerplate? What do you think of it? What do you think of Normalizer.css!? I kind of like its simplicity and so far I have not had any issues with using it. My basic mockup seems to work fine in all browsers I have loaded on my laptop. Anyway I would really like to get some feedback on this just to get a glimpse of what others are doing with it and whether they like it or not. I guess considering HTML5Boilerplate is so popular Normalizer.css will become the next "classic HTML5 reset" for most of us. Looking forward to some replies! Richard A: I have tried 2.0 out on a few sites and quite frankly, I never even thought about it. I think that might be the goal - a sensible accross-the-board starting point from which you build your design. For me, the big plus with the HTML5boilerplate is the aggregation of best practices. Depending on client sensitivity, the window opening to download chrome frame for IE6 users might be a little heavy, but I certainly understand and applaud that worthy goal (and I hope the same applies to IE 7 & 8 - see Paul Irish's recent post on our Future IE Hell to Come)
{ "language": "en", "url": "https://stackoverflow.com/questions/7585928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What causes Lucene.Net to be unable to find one of its files? We're getting random, sporadic issues on our Lucene.Net-based application. They look like this: System.IO.FileNotFoundException: Could not find file 'G:\Site\App_Data\Model Index\index\_2y0.fnm'. Is this symptomatic of something we're doing wrong? We close all readers and all searchers. I optimize regularly. What would cause something like this? A: I don't think you are doing something wrong. If you are using a very old version of Lucene.Net like 2.0.0.4, upgrade to 2.9.2 or newer
{ "language": "en", "url": "https://stackoverflow.com/questions/7585929", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting a POST requests require a Content-length header response(411 error) I have been trying to upload video on video on you tube using my own code. During one step when i try to upload videos meta data on you tube to get the token and url for the video to upload i get a POST requests require a Content-length header. That’s all we know. (411) My code is as follows: $xml = '<?xml version="1.0"?> <entry xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xmlns:yt="http://gdata.youtube.com/schemas/2007"> <media:group> <media:title type="plain">Video.loc</media:title> <media:description type="plain"> Video.loc first vid </media:description> <media:category scheme="http://gdata.youtube.com/schemas/2007/categories.cat">People </media:category> <media:keywords>Video.loc</media:keywords> </media:group> </entry>'; $headers = array('Authorization: AuthSub token="'.$_SESSION['AuthSubSessToken'], 'GData-Version: 2', 'X-GData-Key: key='.$key, 'Content-length:'.strlen($xml), 'Content-Type:application/atom+xml; charset=UTF-8' ); $curl = curl_init('http://gdata.youtube.com/action/GetUploadToken'); curl_setopt($curl, CURLOPT_HTTPHEADER,$headers); curl_setopt($curl, CURLOPT_POSTFIELDS, $xml); curl_setopt($curl, CURLOPT_HEADER, 0); $response = simplexml_load_string(curl_exec($curl)); $response = curl_exec($curl); $arrToken = explode('=',$response); print('<pre>');print_r($arrToken);die(); curl_close($curl) Does any one knows that if it is error on my side or on the google?. Regards Himanshu Sharma A: You are missing a closing " after AuthSub token="'.$_SESSION['AuthSubSessToken'], that might be messing up the headers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: why do I need a cast in this situation? if i have a method defined. public static <T> T getSomeTea(Class<T> returnType) { //do stuff and return a T } public static <T> T getSomeSpecialTea(T someVal) { T someTea = (T) getSomeTea(someVal.getClass()); } in getSomeSpecialTea, why do I need to cast the return from getSomeTea. it would seem to me the cast is unneccesary, but perhaps i'm missing something important. A: Object.getClass() isn't generic, so your code is effectively: public static <T> T getSomeSpecialTea(T someVal) { Class<?> clazz = someVal.getClass(); T someTea = (T) getSomeTea(clazz); } At that point is it clearer why you need the cast? (Not that the cast will really anything at execution time, of course...) You're not calling <T>getSomeTea() which is what you really want to be doing, effectively. It's just another case of Java generics being a bit of a pain :( A: An unfortunate erasure on the return type of getClass() that bugs many people. You can have a utility method that returns the unerased type public static <T> Class<? extends T> myGetClass(T instance) return (Class<? extends T>)instance.getClass(); public static <T> T getSomeSpecialTea(T someVal) T someTea = getSomeTea( myGetClass(someVal) );
{ "language": "en", "url": "https://stackoverflow.com/questions/7585934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Galleria - Fatal Error - No Theme Found IE8 I have built a site using Galleria that works beautifully until it meets IE8 http://milroyandmcaleer.com/Architecture/index.html Then occasionally throws the no theme found error. I have scoured the web trying different solutions. No better. The link above is where it all began. Any help would be very appreciated. A: * *Use the latest version of the program *Read this: http://galleria.aino.se/docs/1.2/references/optimize/ (especially point 4)
{ "language": "en", "url": "https://stackoverflow.com/questions/7585937", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to install HttpClient library from Apache? import org.apache.http.client.*; I want to import this java package it says that it doesn't exist, so where should I download this package from, and where to install it ? A: You can download the jar file from the Maven Repository. You just need to place the jar on the classpath, no need to install anything. A: ypu can download it from here . http://hc.apache.org/httpclient-3.x/ You will need to add it to the build path (if you are using eclipse).
{ "language": "en", "url": "https://stackoverflow.com/questions/7585942", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: programatically set auto refresh on a SSRS report I'm developing a dashboard report in SSRS 2008R2, and I need to refresh it ever 1 minute or so, Is there's any way to do that other than pressing the refresh button on the browser! Thanks A: Set AutoRefresh property of the report to whatever no. of seconds you want the report to be refreshed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Does Sitecore.Context.Item make use of HttpContext? Does Sitecore make use of the HttpContext to save needless calls to the DB? Specifically for the context item and database? Thanks A: Yes. Take a look at Sitecore.Caching.ItemsContext. It uses HttpContext.Current.Items to save the context Item. The context database is in there as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585945", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery index of the object in array I'm trying to get the index of the trigger element in the array. The html looks like this: <ul> <li><a href="#" rel="group">Link 1</a></li> <li><a href="#" rel="group">Link 2</a></li> <li><a href="#" rel="group">Link 3</a></li> </ul> Then on click I'm calling the run() method of the obJ object: var obJ = { run : function(obj) { var att = obj.attr('rel'); var arr = jQuery.find('a[rel='+att+']'); alert(obj.indexOf(arr)); } }; $(function() { $('a.click').click(function() { obJ.run($(this)); return false; }); }); The above however doesn't give me the index of the trigger in the collected array. Any thoughts? A: You want jQuery.index(). var obj = { run: function(obj) { var att = obj.attr('rel'); var index = $('a[rel='+att+']').index(obj); } }; A: Don't you mean this? alert(arr.indexOf(obj)); A: Mike Haboustak's answer is probably the best way of doing it but you could also do something like $('a.click').each(function(index, o){ $(o).click(function () { obj.run($(o), index); return false; }); }); Similar result slightly different approach.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585946", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the best way to represent a category hierarchy using term prefixes in Xapian? Assume I have the following example hierarchy: * *US * *Michigan * *Detroit *Grand Rapids *Lansing *Minnesota * *Grand Rapids *Minneapolis *St Paul *Ohio * *Columbus *Grand Rapids *Sandusky I see two ways that I could index a “Grand Rapids, Michigan” document with prefixed terms: XFIRSTLEVELus XSECONDLEVELmichigan XTHIRDLEVELgrandrapids or XFIRSTLEVELus XSECONDLEVELus_michigan XTHIRDLEVELus_michigan_grandrapids I’m inclined to use the second approach thinking that it will return more intuitive results. That is, a search that includes Grand Rapids, Michigan search criteria is less likely to include documents from Minnesota and Ohio. However, two aspects of this approach bother me. First, the creation and maintenance of term prefixes for each level of the hierarchy feels wrong. Second, the concatenation of values seems like a surrogate for using weights. So, what is the best way to represent a hierarchy with term prefixes? A: As with all these things, It might be best to think about how you want to use the data, rather than what the 'best' way of storing it is. In the past, I have stored location data like you describe as if they were URL paths, converting the place name in to a slug, so your example above would look something like: us us/michigan us/michigan/detroit us/michigan/grand-rapids us/michigan/lansing us/minnesota us/minnesota/grand-rapids us/minnesota/minneapolis us/minnesota/st-paul us/ohio us/ohio/columbus us/ohio/grand-rapids us/ohio/sandusky Give each document a prefixed term with one of those paths, and use an exact term search to get all documents only in a place (location:us/minnesota/minneapolis) or a wildcard search to get all children of a location (location:us/minnesota/*) This may or may not be the 'best' solution, but it might work for some applications :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7585948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MEF vs Unity mostly for Composition I'm creating a multi layer project with a lot of different assemblies and using dependency injection. I was thinking about using some tool for composition but not sure which one to use. MEF and Unity are strong candidates. I think that MEF could perhaps help if I change the web part to multi tennant type. So which one in your opinion would be good for composition mainly if I know neither of them and please include argument if able. A: It depends. In my opinion, I prefer MEF than Unity as MEF based on declare composition and don't need many configuration. If you don't have the requirements which need to control components strictly such as dependency, you can try MEF.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585954", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I retrieve all applicable facet fields for a Solr search I'm trying to use Solr for faceted-seaarch on a website. When a user fires off a search query, I query Solr and retrieve the search results which can then be displayed. My question is - how do I find out which facet fields and terms are applicable to the search results? To be clear - different categories of products have different facet fields and I want to find a way to bring back the most relevant facet fields for the search results that have been returned. I don't want to have to specify the fields - I'd like Solr to identify the relevant ones for me. Thanks in advance! A: I would recommend looking over all of the Simple Facet Parameters on the Solr Wiki, especially the examples at the bottom as they will show you all of the possible ways that you can configure the faceting results for your queries. If I am understanding your question correctly... by default faceting will only bring back facets/counts based on the documents in the result set. However to make those more relevant to the search, you should set the facet.mincount to something other than the default value of 0. eg. &facet.mincount=1. But, again please refer to the documentation on how this works and can be applied to your scenario. A: Im having the same problem. What I eventually did was to query Solr for the top 50 hits for a given query and then collect the names of the properties set on those products. I then do another query with the facet fields set to the product properties I found first time around.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: UI refresh, NSOutlineView reloadData and recursive methods I populate a NSOutlineView reading a directory recursively. After a directory and its subdirectories are read I refresh the outline calling reloadData inside a dispatch like shown below -(void)readDir:(NSString*)path { dispatch_async(dispatch_get_main_queue(), ^{ \ [outlineView reloadData]; }); ////////// //// some internal stuff ////////// NSArray* subs = [self getSubDirs:path]; for (NSString* p in subs) { [self readDir:p]; } } The method above is called from inside a dispatch to have the UI reactive - (void)startAll { dispatch_queue_t queue = dispatch_get_global_queue(0, 0); dispatch_async(queue, ^{ [self readDir:@"/"]; }); } The problem is that sometimes dispatch_async(dispatch_get_main_queue(), ...) is called while subdirectories is reading (it's async at all!) and app crashes If I use dispatch_sync(dispatch_get_main_queue(), ...) (note the sync version) the outline is drawn always correctly but it is very very slooooow so the question is: how can I rearrange the code to be as fast as possible and wait that dispatch_[a]sync(dispatch_get_main_queue(), ...) has finished? A: It sounds like the problem is that while some internal stuff is executing in one thread, your model is in an inconsistent state which reloadData can't properly handle. Are you adding directory entries to their parent directory before they're sufficiently set up? A: Late to this one, but it seems like it would make a lot more sense to write your readDir: like this: -(void)readDir:(NSString*)path { ////////// //// some internal stuff ////////// NSArray* subs = [self getSubDirs:path]; for (NSString* p in subs) { [self readDir:p]; // now refresh outline with newly acquired info and current data dispatch_sync(dispatch_get_main_queue(), ^{ \ [outlineView reloadData]; }); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7585956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to fix this to write a program that uses while loops to calculate the first n Fibonacci numbers I am new to C++ programming and I am a bit lost. Here is what I am suppose to do and my code. Any ideas on what to do? Write a program that uses while loops to calculate the first n Fibonacci numbers. Recall from math the following definition of the Fibonacci sequence: The Fibonacci numbers Fn are defined as follows. F0 is 1, F1 is 1 and Fi+2 = Fi + Fi+1 for i = 0, 1, 2, ... . In other words, each number is the sum of the previous two numbers. The first few Fibonacci numbers are 1, 1, 2, 3, 5, 8, and 13. The program should prompt the user for n (the number of Fibonacci numbers) and print the result to the screen. If the user enters an invalid value for n (n <= 0), print an error message and ask the user to re-enter n (an input validation loop for n). This MUST be a loop, not an if statement like Lab 2. The output should be similar to the following: Enter the number of Fibonacci numbers to compute: 3 The first 3 Fibonacci numbers are: 1 1 2 #include <iostream> using namespace std; int main() { int f0 = 0, f1 = 1,f2= 2, i = 0, n; cout << "Enter the number of Fibonacci numbers to compute: "; cin >> n; if ( n <= 0) { cout <<"Error: Enter a positive number: "; return 1; } while ( i < n){ f2 = f0 + f1; i++; } cout << "The first " << n << " Fibonacci numbers are: " << endl; cin >> n; return 0; } A: while ( i < n){ f2 = f0 + f1; i++; } See this loop, this is where the problem is, since this is homework, i'll not tell exactly what the problem is, take a pen and paper, and start executing your statements, specially this loop, you'll find your error. Just a hint, Fibonacci number is the sum of previous two fibonacci numbers. A: You got the f2=f0+f1 right. However, you should note that when you increment i, then f2 becomes f1 and f1 becomes f0. If you name them like this, it would make more sense: int f_i_minus_2 = 0, f_i_minus_1 = 1, f_i; and you would have f_i = f_i_minus_1+f_i_minus_2; Now, imagine i is 3. You have written: f[3] = f[2]+f[1] When you increment i, you must have: f[4] = f[3]+f[2] That is f_i is put in the place of f_i_minus_1 and f_i_minus_1 is put in the place of f_i_minus_2. (Look at this: f[3] = f[2] + f[1] | | \_____ \____ \ \ f[4] = f[3] + f[2] ) So you need two assignments after computing f_i: f_i_minus_2 = f_i_minus_1; f_i_minus_1 = f_i; Note that I first changed f_i_minus_2 to f_i_minus_1 because the second assignment destroys the value of f_i_minus_1. A: According to wikipedia, your definition is off. F0=0, F1=1, F2=1, F3=2, ... http://en.wikipedia.org/wiki/Fibonacci_number Assuming wikipedia is right your loop is basically int i = 0, f, fprev; while( i < n ) { if( i == 0 ) { f = 0; fprev = 0; } else if( i == 1 ) { f = 1; } else { int fnew = f + fprev; fprev = f; f = fnew; } i++; } A: If you are interested, there are better ways to calculate it. A: As others have pointed out, since you never modify f0 and f1 in the loop, f2 isn't going to depend on the number of times through the loop. Since you have to output all of the numbers at the end anyway, why not try keeping them in an array. I'd initialize the first two values manually, then loop until I had enough values. (This can be done quite nicely using the STL: // After having read n... std::vector<int> results( 2, 1 ); while ( results.size() < n ) results.push_back( *(results.end() - 1) + *(results.end() - 2)); I'm not sure that this is what your instructor is looking for, however. I rather suspect that he wants you to to some indexing yourself. Just remember that if you initialize the first two values manually, your index must start at 2, not at 0.) Another thing: the specification you post says that you should loop if the user enters an illegal value. This is actually a little tricky: if the user enters something that isn't an int (say "abc"), then 1) std::cin will remain in error state (and all further input will fail) until cleared (by calling std::cin.clear()), and the illegal characters will not be extracted from the stream, so your next attempt will fail until you remove them. (I'd suggest >>ing into an std::string for this; that will remove everything until the next white space.) And don't ever access the variable you >>ed into until you've checked the stream for failure—if the input fails. If the input fails, the variable being input is not modified. If, as here, you haven't initialized it, then anything can happen. Finally (and I'm sure this goes beyond your assignment), you really do need to do something to check for overflow. Beyond a certain point, your output will become more or less random; it's better to stop and output that you're giving up in this case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JGroups: send(null, null, Message)vs send(Address, null, Message) I've written simple test for using JGroups. There are two simple applications like this import org.jgroups.*; import org.jgroups.conf.ConfiguratorFactory; import org.jgroups.conf.ProtocolConfiguration; import org.jgroups.conf.ProtocolStackConfigurator; import java.util.List; /** * @author Sergii.Zagriichuk */ public class Test { public static void main(String[] args) throws Exception { JChannel ch = new JChannel(); ch.setReceiver(new ReceiverAdapter() { public void receive(Message msg) { System.out.println("received message " + msg.getObject()); } }); ch.connect("one"); } } and this package com.datacradle.example; import org.jgroups.Global; import org.jgroups.JChannel; import org.jgroups.Message; import org.jgroups.conf.ConfiguratorFactory; import org.jgroups.conf.ProtocolConfiguration; import org.jgroups.conf.ProtocolStackConfigurator; import org.jgroups.stack.IpAddress; import org.jgroups.util.SingletonAddress; import org.jgroups.util.Util; import java.util.List; /** * @author Sergii.Zagriichuk */ public class Test { void start(String props) throws Exception { JChannel chanel = new JChannel(); String line = "Test message"; chanel.connect("one"); // Message msg = new Message(null, null, new TestData(line, 1111, line + " Test suffix")); Message msg = new Message(new IpAddress("fe33:0:0:0:1986:ba23:d939:f226%12",55435) , null, new TestData(line,1111,line+" sdfasdfasdfasdfasdfa")); chanel.send(msg); } public static void main(final String[] args) throws Exception { new Test().start(null); } } So, If I use this style for creating message Message msg = new Message(null, null, new TestData(line, 1111, line + " Test suffix")); I will receive just a one message(this is for all subscribers in current group), but if I use this style Message msg = new Message(new IpAddress("fe33:0:0:0:1986:ba23:d939:f226%12",55435) , null, new TestData(line,1111,line+" sdfasdfasdfasdfasdfa")); I will receive a lot of messages like in a loop (this is for one dist address) What is the problem or I should added some additional parameters? P.S, JGroups 3.0.0 RC1 Thanks. A: You should not create a member address using the IpAddress class, as this is something that's opaque. I suggest fetch the target address from a view, e.g. List<Address> members=channel.getView().getMembers(); Address target=members.get(0); Message msg=new Message(target, null, "hello"); channel.send(msg);
{ "language": "en", "url": "https://stackoverflow.com/questions/7585958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Scala Interpreter: anyway to get the line of a compile error? I am using the scala interpreter to run some user defined script. for this I use the "IMain" class. Works like a charm except when it comes to report the line where a compile error happen. To get the error line number, I just parse the interpreter output message, it is in the form < console>:lineNumber: error: ... The problem is that the line number seems to change depending on the nature of the error and the enclosing scope (within a def or not). This happens also with the REPL, for example: Welcome to Scala version 2.9.1.final (Java HotSpot(TM) Server VM, Java 1.6.0_24). Type in expressions to have them evaluated. Type :help for more information. scala> val a=7 a: Int = 7 scala> a.toString2 <console>:9: error: value toString2 is not a member of Int a.toString2 ^ scala> a2.toString <console>:8: error: not found: value a2 a2.toString ^ scala> a.toString.length3 <console>:9: error: value length3 is not a member of java.lang.String a.toString.length3 ^ I would expect all error messages to start with "< console>:1" since the error is in the first line of the code to interpret... Using the IMain class, is there another way to get the error line number ? (in addition to incorrect results, parsing the output feels kind of a hack...) A: Part of the answer is that what you type isn't what the scala interpreter is really running. You can see this with scala -Xprint:parser : (I'm using scala 2.8.1, so that accounts for some of the difference) scala> a.toString2 [[syntax trees at end of parser]]// Scala source: <console> package <empty> { object line2$object extends scala.ScalaObject { def <init>() = { super.<init>(); () }; object $iw extends scala.ScalaObject { def <init>() = { super.<init>(); () }; import line0$object.$iw.$iw.a; object $iw extends scala.ScalaObject { def <init>() = { super.<init>(); () }; val res0 = a.toString2 } } } } <console>:7: error: value toString2 is not a member of Int a.toString2 ^ versus: scala> a2.toString [[syntax trees at end of parser]]// Scala source: <console> package <empty> { object line3$object extends scala.ScalaObject { def <init>() = { super.<init>(); () }; object $iw extends scala.ScalaObject { def <init>() = { super.<init>(); () }; object $iw extends scala.ScalaObject { def <init>() = { super.<init>(); () }; val res1 = a2.toString } } } } <console>:6: error: not found: value a2 a2.toString ^ Compare the output after both lines. See the extra line in the first bit of output that says: import line0$object.$iw.$iw.a; ? That extra import line accounts for the difference you're seeing in line numbers. So now what you need is some way for the IMain class to tell you how much stuff it's added to the top of the code before the error. (That still won't completely fix things - see the error line you get for g})
{ "language": "en", "url": "https://stackoverflow.com/questions/7585959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Dynamically Display Grid Content I have 3 different layouts (similar to I guess what you would call Skins but the layouts are hugely different, not just changes to colors and fonts) which I have developed for my application. The layouts are used for displaying the same data, but in a completely different format. Each of these layouts have been constructed within their own Grid. I want my application to decide which layout to display dynamically based on a string value available at runtime. What's the best way to get a parent Grid to display a Child Grid dynamically? I'm trying to find some sort of magical DataTemplate / DataBinding / Templating method but just can't seem to find the best way. Alternatively, should I be looking at a different method of displaying these different layouts? Like an ItemsControl or similar? Ben A: I usually use a ContentControl and DataTrigger to determine what ContentTemplate to use. For example, <ContentControl Content="{Binding MyViewModel}"> <ContentControl.Resources> <DataTemplate x:Key="DefaultTemplate"> <TextBlock Text="DefaultTemplate" /> </DataTemplate> <DataTemplate x:Key="TemplateA"> <TextBlock Text="Template A" /> </DataTemplate> <DataTemplate x:Key="TemplateB"> <TextBlock Text="Template B" /> </DataTemplate> </ContentControl.Resources> <ContentControl.Style> <Style TargetType="{x:Type ContentControl}"> <Setter Property="ContentTemplate" Value="{StaticResource DefaultTemplate}" /> <Style.Triggers> <DataTrigger Binding="{Binding SelectedView}" Value="ViewA"> <Setter Property="ContentTemplate" Value="{StaticResource TemplateA}" /> </DataTrigger> <DataTrigger Binding="{Binding SelectedView}" Value="ViewB"> <Setter Property="ContentTemplate" Value="{StaticResource TemplateB}" /> </DataTrigger> </Style.Triggers> </Style> </ContentControl.Style> </ContentControl>
{ "language": "en", "url": "https://stackoverflow.com/questions/7585962", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why can't Tomcat find SMTPTransport(Session, URLName)? We've got a web application that sends mail. For some reason, an installation of it has decided that it can't find the constructor for SMTPTransport that takes (Session,URLName) arguments. Relevant bits of the stack trace: javax.mail.NoSuchProviderException: Provider class does not have a constructor(Session, URLName): protocol=smtp; type=javax.mail.Provider$Type@1dedf78; class=com.sun.mail.smtp.SMTPTransport; vendor=Sun Microsystems, Inc at javax.mail.Session.getService(Session.java:499) at javax.mail.Session.getTransport(Session.java:387) at javax.mail.Session.getTransport(Session.java:347) at javax.mail.Session.getTransport(Session.java:376) at javax.mail.Transport.send(Transport.java:67) at javax.mail.Transport.send(Transport.java:48) ... Caused by: java.lang.NoSuchMethodException: com.sun.mail.smtp.SMTPTransport.<init>(javax.mail.Session, javax.mail.URLName) at java.lang.Class.getConstructor0(Class.java:2706) at java.lang.Class.getConstructor(Class.java:1657) at javax.mail.Session.getService(Session.java:496) ... 8 more We've already checked that SMTPTransport does exist in the classpath (which is not surprising, since we're not getting a ClassNotFoundException), and that it is the only copy of that class in the classpath. It's in tomcat/lib. Our webapp does not include a duplicate. There is not a duplicate in $JAVA_HOME/jre/lib. I've even gone so far as to decompile the class to verify that it does in fact have the Constructor in question. I've done a bit of googling and have found other people who have seen the same error, but no fixes for the problem. A: My coworker and I figured out why we were seeing this. I posted about it here: https://plus.google.com/105513684958738872125/posts/LBnjehZoss6 In summary: While I was looking for a duplicate SMTPTransport class, there was none to be found. The real culprit was a duplicate javax.mail.Session class that had gotten added to my webapp. This caused problems with Tomcat's hierarchical classloaders. When the in-webapp Session class tried to pass itself off to the Tomcat-level SMTPTransport, that one didn't recognize that Session type (which had been loaded by a different classloader) as the type that it needed for its constructor. Removing the duplicate javax.mail classes from the webapp fixes the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585967", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Provide/Export executable file to client I just completed working on a client's tool, which uses Jfreechart jar, and dll and a lib file for JNI interface. Now I would like to export/ provide a executable file to client, I tried to click on java project folder and export Java>Runnable Jar file (extract required libraries into generated JAR) , a Jar file is exported with some Warnings. However, we are not able to run the file on client's machine. How can I fix this, obviously I don't want to provide complete Java project and ask client to run from and IDE. Please provide me inputs. A: Since Java is a cross-platform environment, it doesn't really have "executable files" like EXEs or anything. Instead, you run your .jar file with the Java runtime. For example: C:\>java.exe MyProgram.jar Of course some operating systems will just do this for you once the Java runtime is installed. There are some programs to convert .JAR to .EXE, but I believe they just compile a thin wrapper that calls into the Java runtime.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable to read TLD "META-INF/stripes.tld" from JAR file error I'm encountering a bit of an unusual error after a major upgrade of our web application to ivy for build management which also included updating all of the major libraries involved as well. While we are managing to pass our unit tests, when we deploy the web application to Tomcat and try to navigate to it in the brower we get the following error: org.apache.jasper.JasperException: /index.jsp(1,1) /layout/taglibs.jsp(2,77) Unable to read TLD "META-INF/stripes.tld" from JAR file "file:/Library/Tomcat/apache-tomcat-6.0.32/webapps/cga/WEB-INF/lib/stripes-1.5.6.jar": org.apache.jasper.JasperException: Failed to load or instantiate TagExtraInfo class: net.sourceforge.stripes.tag.ErrorsTagExtraInfo I've checked the usual suspects and verified that the jar file is in the correct location, that the tld file is present in the jar, and so forth. Likewise, searching for the error shows only a limited number of returns, primarily related to a mailing list question with the same error. I've gone through that post and also tried those solutions with not much luck. Any ideas as to what might be causing this error? The full error trace that I'm receiving is as follows: org.apache.jasper.JasperException: /index.jsp(1,1) /layout/taglibs.jsp(2,77) Unable to read TLD "META-INF/stripes.tld" from JAR file "file:/Library/Tomcat/apache-tomcat-6.0.32/webapps/cga/WEB-INF/lib/stripes-1.5.6.jar": org.apache.jasper.JasperException: Failed to load or instantiate TagExtraInfo class: net.sourceforge.stripes.tag.ErrorsTagExtraInfo org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:40) org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:407) org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:88) org.apache.jasper.compiler.Parser.processIncludeDirective(Parser.java:300) org.apache.jasper.compiler.Parser.parseIncludeDirective(Parser.java:333) org.apache.jasper.compiler.Parser.parseDirective(Parser.java:442) org.apache.jasper.compiler.Parser.parseElements(Parser.java:1397) org.apache.jasper.compiler.Parser.parse(Parser.java:130) org.apache.jasper.compiler.ParserController.doParse(ParserController.java:255) org.apache.jasper.compiler.ParserController.parse(ParserController.java:103) org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:185) org.apache.jasper.compiler.Compiler.compile(Compiler.java:347) org.apache.jasper.compiler.Compiler.compile(Compiler.java:327) org.apache.jasper.compiler.Compiler.compile(Compiler.java:314) org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:592) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:326) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260) javax.servlet.http.HttpServlet.service(HttpServlet.java:717) A: This actually took awhile to chase down as the error message is not entirely reflective of what the actual problem is, but in a nut shell this an similar sounding errors (i.e. "Unable to read TLD “META-INF/*.tld” from JAR file") seem to occur when there is a class conflict between one the JAR files that you have deployed and what is deployed with Tomcat itself. This turned out to be the case for my error as there were two files in place (javax.servlet.jsp-api-2.2.1.jar and el-api-1.0.jar) that were conflicting. As this issue seems to popup quite a bit, here are a couple troubleshooting tips: * *Double check what you are deploying to make sure there is nothing unexpected, if you are using a dependency manager make sure the dependency of a dependency isn't causing you problems. *Double check to make sure you have cleared everything out of previous version and deploy again, surprisingly this caught me more than once causing some frustration. *Don't include servlet-api.jar directly in your own lib but rather use an external JAR with a variable path - guide. *Don't expect JAR files to be named as you expect or for them to not contain something you don't think they would have, if you have to, open them up to double check the contents.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Query related to fancybox in facebook page tab I want to use fancybox in a facebook tab based page. In that page there are seperate pages loading in fancybox, but what is happening is I can not give width of that page more than 520px as my fancybox opens inside the facebook page so there is a scrollbars in my facebook page. Is there a way where I can load my fancybox as overlay on full page so there my new pages that are opening in fancybox can have more than 520px width. Thanks in advance A: No, you only have control over the space that Facebook gives to you in your iFrame. There are certain dialogs you can ask Facebook to display, see if one of them fits your needs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585972", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: replace styles.less with styles.css via git post-receive I have a local development web with an index.html which is using: <!-- LESS --> <link rel="stylesheet/less" type="text/css" href="css/styles.less" /> <script src="js/lib/less-1.1.3.min.js" type="text/javascript"></script> When I am ready editing I commit/push to my development server and the git post-receive hook runs my build.sh and builds my css / requireJS / smartsprites app. How can I replace the above code in my static HTML file with: <link rel="stylesheet" type="text/css" href="css/styles.css" /> without switching to server-side scripting (PHP/etc) or on the fly node.js css rendering. In my build.sh script? With regexp? How? An example would be nice. A: You can just use sed: sed -i -e 's/styles\.less/styles\.css/g' index.html I haven't used git-post-receive (I didn't even know it existed! thanks :P), but you could just shove it into your build.sh file or whatever file runs when you push your files to the server.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to show a Wait cursor using C# without having an active (or any) Windows Form? I have tried using this code sample: private void DoShortRunningTask() { using (new StWaitCursor()) { Thread.Sleep(5000); // 5 sec delay. .. do some work .. } } From: http://www.codeproject.com/KB/cpp/WaitCursor.aspx But it did not do anything for me, since I did not have a main form. I do not need a main form. My C# project type is Windows Application, but the only GUI it shows if any is error or success messages dialogs. Is there a way for me to fake the existence of a WinForm (so that it exists but is not visible)? Would the mouse cursor have to be over it in order to show up? A: I don't think it would be good practice just to change the cursor when it's not in your UI. You wouldn't want another program messing with the cursor in your UI. If you just want to show that your application is running, have you thought of using a tray app. These are relatively simple to create. Here's an example I just googled: http://alanbondo.wordpress.com/2008/06/22/creating-a-system-tray-app-with-c/ You can also show speech bubble messages as your run progresses etc, if you want to let the user know things are happening. A: I do not need a main form Yes, you do. Any UI interaction needs a form, sorry. way for me to fake the existence of a WinForm (so that it exists but is not visible)? How is that faking? Make a form, make it invisible (transaprent - check all the properties on the form class and you will find it) and finished ;) Standard approach. Also tell it not to show up in the forms collection in the bottom of the screen and minimize it and you are finished. nothing fake here. A: TomTom++ Are you just wanting to change the current cursor? Try this http://www.csharp-examples.net/hourglass-wait-cursor/
{ "language": "en", "url": "https://stackoverflow.com/questions/7585980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Tomcat as Clients communicating with multiple separated Servers via SSL Here is the scenario: * *I have multiple application servers running locally for now (should be running in different host) --> each is listening on different port (at localhost). *I have a single client application running on Tomcat. *When startup Tomcat, login with different user's details with connect to different (above) servers remotely. My problem is: * *First, I startup Tomcat and logged in as userA, it then connected successfully to serverA(localhost:1000). *Then I logged out. *Logged in again as userB, it did NOT connect to serverB(localhost:1001) as expected; instead, it gave exception "javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown" *However, if I restart Tomcat, and login as userB first, it then connects successfully to serverB. Does anyone know what the problem is? I really appreciate any suggestion :) Code for client Tomcat: SetupClientKeystore(); SetupServerKeystore(); SSLContext context = SetupSSLContext(); SSLSocketFactory socketFactory = sslContext.getSocketFactory(); SSLSocket socket = (SSLSocket) socketFactory.createSocket(hostname, portNo); GZIPOutputStream gZipOut = new GZIPOutputStream(socket.getOutputStream()); // no trust certificate found throws here Code for serverA and B: setupClientKeyStore(); setupServerKeystore(); setupSSLContext(); server = new ServerSocket(portNo); SSLServerSocketFactory socketFactory = sslContext.getServerSocketFactory(); serverSocket = (SSLServerSocket) socketFactory.createServerSocket(portNo); serverSocket.setNeedClientAuth(true); while ( true ) { Socket client = serverSocket.accept(); inStream = client.getInputStream(); BufferedInputStream bufferedIn = new BufferedInputStream(inStream); //unknown_certificate throws here //do something here..... } A: "javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown" This usually indicates that the server's certificate is not trusted. Could it be that when you log-in as userA you load the trusted certificate of serverA and connect, and then when you try to connect to serverB you try to authenticate serverB using the certificate of ServerA (loaded when you logged in as userA)? As a result the SSL handshake fails. So when you restart and login as userB the appropriate certificate (i.e. of ServerB) is loaded and the connection is succesfull? You have no code in your post but if you do it as I say, this explains the exception.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Overriding Environment Variables in an Ant Script I have an issue where my automated build environment necessitates a different version of ant than the actual delegated scripts being run to produce the build. I do not have an environmental variable for ANT_HOME. I throw my CI environment the ANT_HOME to a directory of ant-1.7.0 But i need to override or unset ANT_HOME to a directory of ant-1.6.5 so the targets I call don't inherit the ANT_HOME, and run out of the 1.7.0 folder. Can anyone think of a good way to do this? I can't modify the delegated targets of the build script but I can modify anything in the front end. I'm using Cruisecontrol2.8.4 and the aforementioned ant versions. Edit: The build targets I call set their own ANT_HOME to the 1.6.5 folder but it is being ignored as the previously set ANT_HOME to invoke cruisecontrol is immutable A: You can unset properties with AntContrib. In your ant script... Import AntContrib: <taskdef resource="net/sf/antcontrib/antlib.xml"> <classpath> <pathelement location="folderwithantcontribjar/ant-contrib-1.0b3.jar"/> </classpath> </taskdef> Do the unset: <var name="ANT_HOME" unset="true"/> This removes ANT_HOME from the current set of properties allowing it to be set again. A: Try setting the anthome attribute of the ant builder in your cruisecontrol configuration file : http://cruisecontrol.sourceforge.net/main/configxml.html#ant This should call your version of ant and presumably all called ant scripts will also use this version.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585984", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Restricting records to one side of the join in a self join query Consider a table (name Term) as follows: [Id] [int] IDENTITY(1,1) NOT NULL, [CategoryId] [int] NOT NULL, [Label] [nvarchar](256) NOT NULL, [Uri] [nvarchar](1024) NOT NULL Now, consider that there are two categories defined: CategoryId 1 and CategoryId 2 and there are multiple terms that belong either to category1 or category2. I'm trying to find those Terms that have the same URI but different labels in these two categories, or within a single category of those two. To do so, I tried to write a self join SQL: SELECT t1.Id AS TermId1, t2.Id AS TermId2 FROM Term t1 INNER JOIN Term t2 ON t1.Uri = t2.Uri WHERE t1.CategoryId IN (@CategoryId1, @CategoryId2) AND t2.CategoryId IN (@CategoryId1, @CategoryId2) AND t1.Label <> t2.Label This works fine, but each row is returned twice... For example, TermId1, TermId2 TermId2, TermId1 If the termId1 is different from termId2, then there's no need to have the reverse order result. So, how am I supposed to get results once? Thank you for your help, A: Give this a try. You may not need the group by SELECT t1.Id AS TermId1, t2.Id AS TermId2 FROM Term t1 INNER JOIN Term t2 ON t1.Uri = t2.Uri AND t1.Label <> t2.Label AND t1.Id < t2.Id WHERE t1.CategoryId IN (@CategoryId1, @CategoryId2) and t2.CategoryId IN (@CategoryId1, @CategoryId2) group by t1.Id, t2.Id order by t1.Id, t2.Id
{ "language": "en", "url": "https://stackoverflow.com/questions/7585987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Failure 1 (unrecognized token: "1295980589.jpg") on 0x2a6530 this is the error: 09-28 17:48:03.830: ERROR/Database(1485): Failure 1 (unrecognized token: "1295980589.jpg") on 0x2a6530 when preparing 'INSERT INTO bookmarks (id, title, image1File) VALUES (2014, 'Hilton Craigendarroch, '1295980589.jpg')'. this is the code: this.db.execSQL("INSERT INTO " + CMSConstants.BOOKMARKS + " (" + CMSConstants.ID + ", " + CMSConstants.TITLE + ", " + CMSConstants.IMAGE1_FILE + ") VALUES (" + id + ", '" + title + ", '" + image + "')"); where is the problem? Hope someone can help me.... Thanx newone A: You're missing the closing single quote on the title. What you thought was the opening quote for the image name is the closing quote for the title. Try this: this.db.execSQL("INSERT INTO " + CMSConstants.BOOKMARKS + " (" + CMSConstants.ID + ", " + CMSConstants.TITLE + ", " + CMSConstants.IMAGE1_FILE + ") VALUES (" + id + ", '" + title + "', '" // <-- Note ' before , + image + "')"); A: this.db.execSQL("INSERT INTO " + CMSConstants.BOOKMARKS + " (" + CMSConstants.ID + ", " + CMSConstants.TITLE + ", " + CMSConstants.IMAGE1_FILE + ") VALUES (" + id + ", '" + title + "', '" + image + "')"); try this, you forgot one "'" A: You're missing the closing single quote on the title Try this this.db.execSQL("INSERT INTO " + CMSConstants.BOOKMARKS + " (" + CMSConstants.ID + ", " + CMSConstants.TITLE + ", " + CMSConstants.IMAGE1_FILE + ") VALUES (" + id + ", '" + title + "', '" + image + "')");
{ "language": "en", "url": "https://stackoverflow.com/questions/7585991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Contacting a dynamically created control I have created a textBox control on run-time for my winform application. The control appears just find once the form loads up, and works great too. However, I have just run into a problem as I realize I do not know how to write the code to write to a dynamically created control. Let's assume I have created a button (named "Button1") on design time. In Button1's click event, (Button1_Click), I would like to write the word "Hello" to a textBox control that won't be created until the application is executed. Some code below: C# Code: // Create the textBox control TextBox new_textBox = null; int x = 10; int y = 10; int xWidth = 300; int yHeight = 200; new_textBox = new TextBox(); new_textBox.Text = controlText; new_textBox.Name = "textBox" + controlName; new_textBox.Size = new System.Drawing.Size(xWidth - 10, yHeight - 10); new_textBox.Location = new Point(x, y); new_textBox.BringToFront(); new_textBox.Multiline = true; new_textBox.BorderStyle = BorderStyle.None; // Add the textBox control to the form this.Controls.Add(new_textBox); The Problem: From Button1_Click event, I cannot get in contact with a control that has not even been created yet. Thus, Visual Studio will throw an obvious error that the control does not exist (because it doesn't). So, is there some way to dynamically call a control, and more specifically, a textBox control? Thank you for any help on the matter, Evan A: Declare the new_textBox at class scope. Then the compiler can access it. For example: class MyForm { TextBox new_textBox; void InitializeTextBox() { new_textBox = new TextBox(); // initialization code here // Add it to the form this.Controls.Add(new_textBox); } void Button1_Click(...) { new_textBox.Text = "clicked"; } A: You can make the new_textBox a class member (member of the form). You can again assign it a value and add to the forms controls later dynamically. It would be a good practice to check if is null in the buttonClick event, though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585994", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is IIS appending localhost/default.aspx to the URL? This is a very strange problem. We have a Windows 7 machine. We have one web site set up and it works fine. We added a second web site. It is a very simple web site. There is only one file - test.html. Then we set up both sites to use host headers. Then we added entries in our HOSTS file that matches both of those and points back to 127.0.0.1. The first web site still works fine. However when we open up a browser and enter the following: http://site-2/test.html Immediately the browser changes to http://site-2/localhost/default.aspx/localhost/default.aspx/localhost/default.aspx/localhost/default.aspx... And it keeps repeating and repeating and I get an error about the length of the URL being too long. Does anyone have any idea why this would be happening? It is very strange and I have no idea what I am doing wrong. Thanks, Corey A: We figured it out. For some unknown reason the brand new second site that we created had an HTTP redirect set up to go to localhost/default.aspx. I don't know why it was set up that way by default when we created a brand new site but it was.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WebKit Scale Transformation issue I need help on webkit scale functionality. I have a .css file with properties as shown : @-webkit-keyframes expand { from {-webkit-transform:scale(1)} to {-webkit-transform:scale(1.2)} } .image-highlight { -webkit-animation-name: expand; -webkit-animation-duration:0.2s; -webkit-animation-iteration-count:1; -webkit-animation-timing-function:ease; } I have a html with elements : <div id="slider"> <img src="images/blueMarble_0.PNG" /> <img src="images/blueMarble_1.PNG" /> <img src="images/blueMarble_2.PNG" /> <img src="images/blueMarble_3.PNG" /> <img src="images/blueMarble_4.PNG" /> </div> I have a js file with a function which will animate(scale) the middle image of the array. and I am using this jQuery statement to do the animation: `$(pic[2]).addClass('image-highlight');` This jquery actually scales the image (pic[2]). But scaling happens for 0.2 secs and it scales down to original size. How can I retain the scaling even after completion of 0.2 secs? I don't want to resize it to original size. Can it be done without changing the animation duration? Please can you help me on this? A: I believe you want to add to your class: -webkit-animation-fill-mode: both This will cause the animation's initial keyframe to be shown immediately when your image-highlight class is applied and the final keyframe will continue to be shown after the animation finishes. Other values you can use: * *none - the effects of the animation are apparent only during the defined duration of the animation. (default) *backwards – the animation’s initial keyframe is applied as soon as the animation style is applied to an element. This only affects animations that have a nonzero value for -webkit-animation-delay. *forwards – the animation’s final keyframe continues to apply after the final iteration of the animation completes. -webkit-animation-fill-mode: forwards will probably also meet your needs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586003", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySQL Query help and outputting to PHP Below is an attached image of what I have so far. 1 = a feature and 2 = a benefit. What I need to do is match the feature with the benefit. The first #1 goes with the first #2 What I have so far is: <?php if ($result = $mysqli->query('SELECT FB_TEXT FROM `FB_DATA` WHERE `FB_MODELID` = "'.$sku_modelid.'" AND FB_TYPEID IN (1,2)')) { while( $row = $result->fetch_assoc()){ echo "<tr><td>".$row['FB_TEXT']."</td></tr>"; } } ?> Now this shows all results. What needs to happen is this: <tr> <td>Feature</td> <td>Benefit</td> </tr> Does anyone have any idea on how I could make that happen? A: There is no way the ensure this will happen correctly. Instead, you should link the 2 together, using a separate table and using indexes and unique identifiers for it. If the Feature and benefit are always used together, you could also add another column to it. This would make a table having 4 columns: * *ID (unique) *Feature *Benefit *Text A: I don't know what the others are on about, but if you know that when FB_TYPEID is 1 it is considered a feature and when FB_TYPEID is 2, it is considered a benefit, then ordering is easy. Use this query: SELECT `FB_TYPEID`, `FB_TEXT` FROM `FB_DATA` WHERE `FB_MODELID` = theModelIdYouAreLookingFor AND `FB_TYPEID` IN (1,2) ORDER BY CASE `FB_TYPEID` WHEN 1 THEN 0 WHEN 2 THEN 1 # switch this to: # WHEN 2 THEN 0 # WHEN 1 THEN 1 # if you want benefit to show first END Make sure you protect yourself against SQL injection. The way you query with mysqli now, is vulnerable to SQL injection (presuming $sku_modelid was not sanitized before). You should really be using prepared statements with bound parameters. Something like: $sql = ' SELECT `FB_TYPEID`, `FB_TEXT` FROM `FB_DATA` WHERE `FB_MODELID` = ? AND `FB_TYPEID` IN (1,2) ORDER BY CASE `FB_TYPEID` WHEN 1 THEN 0 WHEN 2 THEN 1 END '; if( $statement = $mysqli->prepare( $sql ) ) { // bind $sku_modelid to the first (and only) questionmark (placeholder) as an integer $statement->bind_param( 'i', $sku_modelid ); // execute the prepared statement if( $statement->execute() ) { // bind FB_TYPEID to $typeId and FB_TEXT to $text $statement->bind_result( $typeId, $text ); while( $row = $result->fetch_assoc() ) { // echo the table row if( $typeId == 1 ) echo '<tr>'; echo '<td>' . $text . '</td>'; if( $typeId == 2 ) echo '</tr>'; } } } (Could be missing something here, as I never use the mysqli library. But I believe it should work.) A: This is a very dangerous way to do this. Technically, SQL doesn't have any concept of "Order". Yes, in all actuality it orders things by the time you put them in there, but there is no guarantee that they will come out in that expected order. You'd be best off creating two separate tables, one for "features" and one for "benefits. Then join them with a foreign key. SELECT * FROM features JOIN benefits ON features.link_id = benefits.link_id WHERE features.model_id = 1
{ "language": "en", "url": "https://stackoverflow.com/questions/7586007", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: jQuery IE6 stripping HTML from XML. I have a problem with IE6 that is stripping HTML from XML even after I wrap this inside CDATA e.g <name>Product <![CDATA[<br />]]> Name</name> var phoneCarousel = $("#phone-carousel"), phoneXmlPath = "deals/phones.xml"; // Generate to allow image to be vertial aligned bottom. function generateTable(name, image){ var table = '<table cellspacing="0" cellpadding="0">'; table += '<tr><td class="img"><img alt="'+name+'" src="'+image+'"></td></tr>'; table += '<tr><td>'+name+'</td></tr>'; table += '</table>'; return table; } phoneCarousel.addClass("loading"); // Get Phones XML $.ajax({ type: "GET", url: phoneXmlPath, dataType: "xml", contentType: "application/xml; charset=utf-8", success: function(xml){ phoneCarousel.html(""); //This function will loop for each match on phones/phone $(xml).find("phone").each(function(index, value){ var tis = $(this), first = ''; if(index == 0){ first = ' class="selected"'; } phoneCarousel.append('<li'+first+'>' + generateTable(tis.find("name").text(), tis.find("thumbnail").text()) + '</li>'); }); phoneCarousel.removeClass("loading"); }, error:function(xhr,type){ if(type == null){ var errorMsg = "There was an error loading the phone.xml file!<br/>Please make sure the path to the xml file <strong>'"+phoneXmlPath+"'</strong> is correct."; }else if(type == "parsererror"){ var errorMsg = "There is an error in the file <strong>'"+phoneXmlPath+"'</strong>."; }else{ var errorMsg = "An error has been detected."; } phoneCarousel.removeClass("loading").html("<p><strong>Error:</strong> "+errorMsg+"</p><p><strong>Type of error:</strong> "+type+".</p>"); } }); A: Try using text/xml instead of application/xml as the content type, IE is very strict with content types.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Add html input boxes to a div on click using jquery I need to add input boxes to a page onclick of a button, I have written the following jquery script. It adds one input box when clicked the first time but does not repeat adding. <script type="text/javascript"> function addInput(){ $('#fileinput').html('<label>Filename:</label> <input type="file" name="file" id="file" />'); } </script> can some one please help me to modify the code so that it will add an input box each time the button is clicked. A: $('#buttonID').click(function(){ $('#fileinput').html($('#fileinput').html()+'<label>Filename:</label> <input type="file" name="file" id="file" />'); }); or use append as others suggested $('#buttonID').click(function(){ $('#fileinput').append('<label>Filename:</label> <input type="file" name="file" id="file" />'); }); A: Your code currently replaces the existing HTML in your #fileInput element with the same HTML. What you probably want to use is the append() method. function addInput(){ $('#fileinput').append('<label>Filename:</label> <input type="file" name="file" id="file" />'); } A: try using append instead of html: http://api.jquery.com/append/ <script type="text/javascript"> function addInput(){ $('#fileinput').append('<label>Filename:</label> <input type="file" name="file" id="file" />'); } </script> A: That's because you're not adding to the HTML each time, you're simply setting it to show the single input.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586014", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Url Routing (ASP.NET 4 Web Forms) returning 404 under IIS7 (Win2008) but OK under IIS7.5 (Win7)? I have an asp.net 4 website that is working fine locally under IIS7.5 (windows 7), and under the Classic Application Pool (albeit .NET 4). Some of the site uses routing and some of the older sections of the site don't. Anyway, it all works fine locally. I have just deployed this to our live webserver for the first time since introducing the routing parts of the site, and all I get is 404's for the sections of the site that are using Routing. The live webserver is IIS7 on Windows 2008, and again is set to use a .NET4 Classic App Pool. I have tried adding <modules runAllManagedModulesForAllRequests="true"> under the system.webserver section of my web.config, but this doesn't appear to have made any difference. Can anyone shed some light on what the problem might be/how to get around this please? A: I think I fixed this problem a while ago by running aspnet_regiis again (in the .Net Framework v4 folder). A: The only way I've been able to get around this unfortunately is by adding a wildcard script mapping in IIS7 as per this article: http://learn.iis.net/page.aspx/508/wildcard-script-mapping-and-iis-7-integrated-pipeline/ This has at least got the pages routing successfully, even if it does feel a little dirty.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: java insertion sort recursive i have an array and have to sort them using insertion sort. i tried to use the compareTo method to run through the array and see whats bigger. I ran into a problem because i was trying to reference an array index with a string which obviously didntwork (thats at compareTo(a[key])). any suggestions or hints as to how to do this would be appreciated. this is what i have so far. is it a good start? or a start in the right direction? public void insertionSort() { insertionSort(a.length-1); } private void insertionSort(int n) { String temp; if(n <= 1) { //Do nothing, easiest case } else { for(int i = 1; i < a.length; i++) { int j; String key = a[i]; while((j >= 0) && (a[i].compareTo(a[key]) > 0)) { a[i+1] = a[i]; j--; } a[i+1] = key; } insertionSort(n-1); } } A: My first suggestion would be that it's usually easier to understand a method if you pass in the required arguments. It's not clear at all what a is; I'd expect the public insertionSort method to take as an argument the objects to sort. (I suppose if you're defining this on your own list-like class it's not as bad, but it doesn't sound like that's the usage). Likewise I'm not entirely sure what n is supposed to be (presumably the index beyond which you know is sorted) but you don't use it at all in the body of the private method, so you're just doing the same thing n times. You also appear to be swapping elements of a, which you shouldn't need to do in an insertion sort. This looks more like a bubble sort. Try writing the method as pseudocode (e.g. comments) first to lay out your approach, then flesh out each comment with a small bit of code. Doing this can avoid getting too bogged down in the detail, and usually conceptual mistakes will appear more obvious, and be easier to avoid. This might look something like: public static int[] insertionSort(int[] input) { // Create the array to hold the results // Iterate through the contents of input and insert each one into // the result array in order (method call here) // return the result array } private void insertOneElement(int toInsert, int[] resultArray) { // Compare toInsert with first element of resultArray // etc. } A: Just change it to a[j].compareTo(key) (note that you want to compare a[j], not a[i]). You also need to initialize j, as smas commented. A: Replace the inner loop as follows: j = i - 1; //initialize j!!! String key = a[i]; //take value while((j >= 0) && (a[j].compareTo(key) > 0)){//Compare with key!!! a[j+1] = a[j]; j--; } a[j + 1] = key; //index is j here!!!!
{ "language": "en", "url": "https://stackoverflow.com/questions/7586033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get the ip range out of a CIDR Notation or an address netmask pair using Java For example: How to get the lower-higher ip address of the CIDR Notation 10.66.114.0/24 In this case the answer is: 10.66.114.1 - 10.66.114.254 A: Here's the gist of it (I'm a C guy): unsigned int network = 0x0a427200; /* 10.66.114.0 */ unsigned int subnet_length = 24; unsigned int mask = 0xfffffff << (32 - subnet_length); unsigned int bcast = 0xffffffff >> (32 - subnet_length); unsigned int start_ip = (network & mask) + 1; unsigned int end_ip = (network & mask) + (bcast - 1); A: #include <ncurses.h> // ncurses.h includes stdio.h #include <math.h> #include <stdlib.h> // determine network range of masked ip. eg: 192.168.113.0/25 // unsigned int network = 0x0a427200; /* 10.66.114.0 */ // unsigned int subnet_length = 24; // // unsigned int mask = 0xfffffff << (32 - subnet_length); // unsigned int bcast = 0xffffffff >> (32 - subnet_length); // // unsigned int start_ip = (network & mask) + 1; // unsigned int end_ip = (network & mask) + (bcast - 1); int main(int argc, char *argv[]) { // char arg[50] = " "; char ipmask[50] = "192.168.113.0/25"; // determine network range of masked ip. eg: 192.168.113.0/25 unsigned int network = 0xc0a87100; /* 192.168.113.0 */ unsigned int subnet_length = 25; unsigned int mask = 0xfffffff << (32 - subnet_length); unsigned int bcast = 0xffffffff >> (subnet_length); // unsigned int bcast = 0xffffffff >> (32 - subnet_length); unsigned int start_ip = (network & mask) + 1; unsigned int end_ip = (network & mask) + (bcast); initscr(); cbreak(); printw("\nipmask %s\nstart %x end %x range %x\n" "press any key\n", ipmask, start_ip, end_ip, end_ip - start_ip + 1); getch(); endwin(); // close ncurses library and restores previous console return(0); } /*****************************************************************************/ // end netmask gcc -Wall netmask.c -o netmask -lm -lncurses
{ "language": "en", "url": "https://stackoverflow.com/questions/7586041", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: 'Title' is not getting inserted I recently changed my site to allow a user to choose from a dropdown list or a textbox to be able to insert a title. The table is called Picklist, the columns are PicklistID, Title, Data. Can someone help me with the insert of the title? Protected Sub SubmitLink_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SubmitLink.Click LinkModal.Hide() Dim strSQL As String = "INSERT INTO Picklist (Title, Data) VALUES (@Title, @Data);INSERT INTO Marketing (ProductID, MarketingTypeID, MarketingTitle, MarketingData) VALUES (@ProductID, 1, 'Link', scope_identity())" Using cn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings ("LocalSqlServer").ConnectionString) Using cmd As New SqlCommand(strSQL, cn) If ddlDescription.SelectedValue <> "Select below or enter new" Then cmd.Parameters.Add(New SqlParameter("@Title", ddlLink.SelectedValue)) Else cmd.Parameters.Add(New SqlParameter("@Title", NewLinkTitle.Text)) End If cmd.Parameters.Add(New SqlParameter("@Data", LinkURL.Text)) cmd.Parameters.Add(New SqlParameter("@ProductID", ProductID.Value)) cn.Open() cmd.ExecuteNonQuery() End Using End Using Response.Redirect(Request.RawUrl) End Sub Here are the dropdown and textbox: Title:<asp:DropDownList ID="ddlLink" runat="server" DataSourceID="dsNewLink" DataTextField="Title" DataValueField="Title" enableViewstate="False" AppendDataBoundItems="True"> <asp:ListItem Text="Select below or enter new" Selected="True"> </asp:ListItem> </asp:DropDownList><br /> New Title:<asp:TextBox ID="NewLinkTitle" runat="server"> </asp:TextBox><br /> In the image below: See how in the background the line at the very top has nothing in it, but the delete button is there? That is a link that I just tried to add......the @Data column is inserted into the database, but not the @Title. But there are no errors! :/ A: Things to do: * *Check the column definition of your picklist table. Is the Title column either a char or varchar and does it contain enough space to hold your inserted data? *Set a break point in your code on the IF statement and run the program. When it gets there, inspect the ddlLink.SelectedValue property to see what, exactly, is contained there in. Step through the app to see which branch of code it goes through. And, finally, inspect the cmd.parameters property to see what values the parameters were set to. *If the above doesn't point out whats going on, use SQL Profiler and watch the query come across the wire. Look at the query to see if it's passing everything you think it should. If so, then copy that query and run it directly in management studio to find out what's going on.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Plugin for Maven that Exports non-project files of choosing to a RAR/compressed filetype Here's what I need to accomplish: Take some files, and create a Zip/Rar/Tar file while running the maven package command. With the maven-rar-plugin I can only create a compressed file containing all of the contents needed to run the program. Are there any sort of third part, or maven plugins that I may have missed? I know this can be done by adding/calling a python script from my pom.xml, but would like to do it all with maven. A: Perhaps maven assembly plugin will help here?
{ "language": "en", "url": "https://stackoverflow.com/questions/7586043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IIS output caching causing wrong pages to display I turned on output caching in IIS7.5 for .aspx pages but sometimes when I browse to PageB.aspx I see the output for PageA.aspx. Looking on google this seems like it's a common issue but no one has said if they have fixed it or how. How can I enable output caching but avoid this issue? Is there a variation I can add in the settings (querystring or headers) or is there a hotfix for this issue? update: If I add "Accept" to the Vary By Headers setting, it works better, but not 100% because pages with the same Accept header will have the issue. update: if I add "Accept, Referer" to the headers, it looks like everything is working as expected. A: It's a known bug in the rewrite engine. The following command should fix it: reg add HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\InetStp\Rewrite /v RewriteCacheEnabled /t REG_DWORD /d 0 You'll need to run iisreset after this command.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to pass a dynamically generated ID to Jquery I'm using a nice Jquery context menu which returns the ID of my element in the form $(context).attr('id') and not in the form $(this).attr('id') due to the fact that I'm using one single context menu for a large number of elements where each element has its unique ID. The context menu works perfectly as it executes the commands relative to the clicked element identified by its unique ID. I use the context menu to write data to a MySQl db via $.get and this works too. But now I would like to use the data I get back from $.get and use it with the .replaceWith method to change some text without refreshing the page: $.get("jq_get_go.php", { parameter2: $(this).attr('menuCommand'), id: $(context).attr('id') }, function(data) { $(".ci_saremo").xxxxx.replaceWith('<li class="Like ci_saremo" id="' + $(context).attr('id') + '"><a href="">' + data + '</a></li>'); } ); I don't understand what should I replace the xxxxx with to get the ID of my element that I know I have here $(context).attr('id') Of course if I omit xxxxx and leave $(".ci_saremo").replaceWith('<li class="Like ci_saremo" id="' + $(context).attr('id') + '"><a href="">' + data + '</a></li>'); every ".ci_saremo" text will be replaced. So I need to identify it by its ID. Basically, I don't understand how to chain/insert $(context).attr('id') in the above string. A: This should do it: $('#'+$(context).attr('id')).replaceWith... A: I may be misunderstanding your intentions, but it looks as if you're trying to replace the link text inside of the li item. If so, you should be able to do this: $(context). .find(".ci_saremo") .replaceWith('<li class="Like ci_saremo" id="' + $(context).attr('id') + '"><a href="">' + data + '</a></li>'); The find method will grab the .ci_saremo elements within $(context).attr('id'). This should isolate the single element you want to change. EDITED A: If $(context).attr('id') returns the ID, doesn't that mean that context is your element? If so, couldn't you just do this? $(context).replaceWith('<li class="Like ci_saremo" id="' + $(context).attr('id') + '"><a href="">' + data + '</a></li>');
{ "language": "en", "url": "https://stackoverflow.com/questions/7586052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Better Management of Binary Target of Exec Plugin Our build uses the exec plugin to execute a external binary. The way we do this currently is that each developer must install the binary on their machine, and then configure the plugin with the path to the executable. It seems to me that their must be some way to manage that binary itself as a dependency of the build. I'm a bit new to maven so I don't immediately see how to best do this. I'm thinking that the build should grab the binary on it's own, and execute it. This would be a much more "portable" build than expecting developers to install the binary themselves. So, what is the best way to go about this? A: I think you could just put the binary somewhere into the source code. Regarding the documentation, the exec:exec looks for path "relative to the root of the project".
{ "language": "en", "url": "https://stackoverflow.com/questions/7586055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to define method for specific attribute of class in Ruby? I have some Ruby-question. Let I have class Cat. Cat has age attribute, which is Class::Integer. How can I add method .humanize, which will calculate human age equivalent form all cats in my project? i.e. ... @cat.age #=> 2 @cat.age.humanize #=> 20 @tree.age #=> 5 @tree.age.humanize #=> NO METHOD ERROR!!! OH, YEAH! A: This is called metaprogramming. You can accomplish what you want by doing the following: def @cat.humanize_age return @age * 10 end You could add the method onto the Integer class from within Cat itself: class Cat attr_accessor :age def initialize(a) @age = a add_meta end def add_meta def @age.humanize return self * 10 end end end
{ "language": "en", "url": "https://stackoverflow.com/questions/7586058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why in ASP.NET MVC 3 the default route is not working for a controller called "ContentController"? I have a brand new asp.net mvc 3 project. I did not modify the routes in any way. I have a controller called PageController and another controller call ContentController. When I browse to domain.com/Page then the Index action on the Page controller gets executed as expected and displays the Index view. When I browse to domain.com/Content I get a 404 error. If I browse to domain.com/Content/Index then it works fine. How do I troubleshoot this single route? public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } I tried adding an additional route: public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); routes.MapRoute( "Content", // Route name "Content/{action}/{id}", // URL with parameters new { controller = "Content", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } But the additional route did not change the application's behavior. What could be causing this? A: its because there is a physical folder called content. having a controller with the same name as a physical folder will probably have some adverse affects on your website. A: Try adding the following to your route definitions: routes.RouteExistingFiles = true;
{ "language": "en", "url": "https://stackoverflow.com/questions/7586060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to calculate the angle between a line and the horizontal axis? In a programming language (Python, C#, etc) I need to determine how to calculate the angle between a line and the horizontal axis? I think an image describes best what I want: Given (P1x,P1y) and (P2x,P2y) what is the best way to calculate this angle? The origin is in the topleft and only the positive quadrant is used. A: Sorry, but I'm pretty sure Peter's answer is wrong. Note that the y axis goes down the page (common in graphics). As such the deltaY calculation has to be reversed, or you get the wrong answer. Consider: System.out.println (Math.toDegrees(Math.atan2(1,1))); System.out.println (Math.toDegrees(Math.atan2(-1,1))); System.out.println (Math.toDegrees(Math.atan2(1,-1))); System.out.println (Math.toDegrees(Math.atan2(-1,-1))); gives 45.0 -45.0 135.0 -135.0 So if in the example above, P1 is (1,1) and P2 is (2,2) [because Y increases down the page], the code above will give 45.0 degrees for the example shown, which is wrong. Change the order of the deltaY calculation and it works properly. A: import math from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) def get_angle(p1: Point, p2: Point) -> float: """Get the angle of this line with the horizontal axis.""" dx = p2.x - p1.x dy = p2.y - p1.y theta = math.atan2(dy, dx) angle = math.degrees(theta) # angle is in (-180, 180] if angle < 0: angle = 360 + angle return angle Testing For testing I let hypothesis generate test cases. import hypothesis.strategies as s from hypothesis import given @given(s.floats(min_value=0.0, max_value=360.0)) def test_angle(angle: float): epsilon = 0.0001 x = math.cos(math.radians(angle)) y = math.sin(math.radians(angle)) p1 = Point(0, 0) p2 = Point(x, y) assert abs(get_angle(p1, p2) - angle) < epsilon A: First find the difference between the start point and the end point (here, this is more of a directed line segment, not a "line", since lines extend infinitely and don't start at a particular point). deltaY = P2_y - P1_y deltaX = P2_x - P1_x Then calculate the angle (which runs from the positive X axis at P1 to the positive Y axis at P1). angleInDegrees = arctan(deltaY / deltaX) * 180 / PI But arctan may not be ideal, because dividing the differences this way will erase the distinction needed to distinguish which quadrant the angle is in (see below). Use the following instead if your language includes an atan2 function: angleInDegrees = atan2(deltaY, deltaX) * 180 / PI EDIT (Feb. 22, 2017): In general, however, calling atan2(deltaY,deltaX) just to get the proper angle for cos and sin may be inelegant. In those cases, you can often do the following instead: * *Treat (deltaX, deltaY) as a vector. *Normalize that vector to a unit vector. To do so, divide deltaX and deltaY by the vector's length (sqrt(deltaX*deltaX+deltaY*deltaY)), unless the length is 0. *After that, deltaX will now be the cosine of the angle between the vector and the horizontal axis (in the direction from the positive X to the positive Y axis at P1). *And deltaY will now be the sine of that angle. *If the vector's length is 0, it won't have an angle between it and the horizontal axis (so it won't have a meaningful sine and cosine). EDIT (Feb. 28, 2017): Even without normalizing (deltaX, deltaY): * *The sign of deltaX will tell you whether the cosine described in step 3 is positive or negative. *The sign of deltaY will tell you whether the sine described in step 4 is positive or negative. *The signs of deltaX and deltaY will tell you which quadrant the angle is in, in relation to the positive X axis at P1: * *+deltaX, +deltaY: 0 to 90 degrees. *-deltaX, +deltaY: 90 to 180 degrees. *-deltaX, -deltaY: 180 to 270 degrees (-180 to -90 degrees). *+deltaX, -deltaY: 270 to 360 degrees (-90 to 0 degrees). An implementation in Python using radians (provided on July 19, 2015 by Eric Leschinski, who edited my answer): from math import * def angle_trunc(a): while a < 0.0: a += pi * 2 return a def getAngleBetweenPoints(x_orig, y_orig, x_landmark, y_landmark): deltaY = y_landmark - y_orig deltaX = x_landmark - x_orig return angle_trunc(atan2(deltaY, deltaX)) angle = getAngleBetweenPoints(5, 2, 1,4) assert angle >= 0, "angle must be >= 0" angle = getAngleBetweenPoints(1, 1, 2, 1) assert angle == 0, "expecting angle to be 0" angle = getAngleBetweenPoints(2, 1, 1, 1) assert abs(pi - angle) <= 0.01, "expecting angle to be pi, it is: " + str(angle) angle = getAngleBetweenPoints(2, 1, 2, 3) assert abs(angle - pi/2) <= 0.01, "expecting angle to be pi/2, it is: " + str(angle) angle = getAngleBetweenPoints(2, 1, 2, 0) assert abs(angle - (pi+pi/2)) <= 0.01, "expecting angle to be pi+pi/2, it is: " + str(angle) angle = getAngleBetweenPoints(1, 1, 2, 2) assert abs(angle - (pi/4)) <= 0.01, "expecting angle to be pi/4, it is: " + str(angle) angle = getAngleBetweenPoints(-1, -1, -2, -2) assert abs(angle - (pi+pi/4)) <= 0.01, "expecting angle to be pi+pi/4, it is: " + str(angle) angle = getAngleBetweenPoints(-1, -1, -1, 2) assert abs(angle - (pi/2)) <= 0.01, "expecting angle to be pi/2, it is: " + str(angle) All tests pass. See https://en.wikipedia.org/wiki/Unit_circle A: I have found a solution in Python that is working well ! from math import atan2,degrees def GetAngleOfLineBetweenTwoPoints(p1, p2): return degrees(atan2(p2 - p1, 1)) print GetAngleOfLineBetweenTwoPoints(1,3) A: Based on reference "Peter O".. Here is the java version private static final float angleBetweenPoints(PointF a, PointF b) { float deltaY = b.y - a.y; float deltaX = b.x - a.x; return (float) (Math.atan2(deltaY, deltaX)); } A: Considering the exact question, putting us in a "special" coordinates system where positive axis means moving DOWN (like a screen or an interface view), you need to adapt this function like this, and negative the Y coordinates: Example in Swift 2.0 func angle_between_two_points(pa:CGPoint,pb:CGPoint)->Double{ let deltaY:Double = (Double(-pb.y) - Double(-pa.y)) let deltaX:Double = (Double(pb.x) - Double(pa.x)) var a = atan2(deltaY,deltaX) while a < 0.0 { a = a + M_PI*2 } return a } This function gives a correct answer to the question. Answer is in radians, so the usage, to view angles in degrees, is: let p1 = CGPoint(x: 1.5, y: 2) //estimated coords of p1 in question let p2 = CGPoint(x: 2, y : 3) //estimated coords of p2 in question print(angle_between_two_points(p1, pb: p2) / (M_PI/180)) //returns 296.56 A: deltaY = Math.Abs(P2.y - P1.y); deltaX = Math.Abs(P2.x - P1.x); angleInDegrees = Math.atan2(deltaY, deltaX) * 180 / PI if(p2.y > p1.y) // Second point is lower than first, angle goes down (180-360) { if(p2.x < p1.x)//Second point is to the left of first (180-270) angleInDegrees += 180; else //(270-360) angleInDegrees += 270; } else if (p2.x < p1.x) //Second point is top left of first (90-180) angleInDegrees += 90; A: matlab function: function [lineAngle] = getLineAngle(x1, y1, x2, y2) deltaY = y2 - y1; deltaX = x2 - x1; lineAngle = rad2deg(atan2(deltaY, deltaX)); if deltaY < 0 lineAngle = lineAngle + 360; end end A: A formula for an angle from 0 to 2pi. There is x=x2-x1 and y=y2-y1.The formula is working for any value of x and y. For x=y=0 the result is undefined. f(x,y)=pi()-pi()/2*(1+sign(x))*(1-sign(y^2)) -pi()/4*(2+sign(x))*sign(y) -sign(x*y)*atan((abs(x)-abs(y))/(abs(x)+abs(y)))
{ "language": "en", "url": "https://stackoverflow.com/questions/7586063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "263" }
Q: Access database on network I made a small C# Winform application with a simple GUI and a database (MyDB). Now I want to run my application on the Server. I want other users to access my database through the network. I have a Wired\Wireless network. Suppose I have 2 systems (sys1, sys2) I have my application in sys1. I created a shortcut of my application in sys1 and tried to run that shortcut. It worked. But when I am trying to open the shortcut in sys2, it gave me error: "The drive or network connection that the shortcut 'application.lnk' refers to is unavailable. Make sure the disk is properly inserted or network resource is available, and then try again.". Then I copied my application.exe.config file near application.lnk. Do I change anything in ConnectionString? What causes this error? Note: Application made in C# 4.0, VS 2010. A: It sounds like on sys1, application.lnk is pointing to your local copy, such as C:\MyApp\App.exe. When you copy application.lnk over to sys2, it's trying to find a file called C:\MyApp.App.exe on that machine, which doesn't exist. You'll have to host your application on a network drive, such as \\MyServer\Apps\App.exe and create a shortcut to that instead. That link should then work on any computer with access to that share.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: COM addin for MS Office doesn't load in a limited user account I've created a toolbar for Word. It's a COM addin and is written in C++. It works when Word is started by an Administrator account in XP. But when Word is started from a limited account it's not even loaded. I placed this code in DllMain: ///////////////////////////////////////////////////////////////////////////// // DLL Entry Point HINSTANCE g_hInst = NULL; extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) { static int passed = 0; if (!passed) { MessageBox(0, "foo", 0, 0); passed = 1; } g_hInst = hInstance; ............................ } The message box is displayed when running Word from an admin account but not when running from a limited account. I'm testing this on an XP machine with Word 2003. A: It turned out that my addin was registering itself in HKCU instead of HKLM (this was in the .rgs file). So only the user doing the install would have it registered. That's why Word wouldn't load it for other user accounts.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Ninject with custom WebViewPage type I am using ASP.NET MVC 3 + Ninject in my application which works great with my controllers. I also have a custom base page class that inherits from WebViewPage and I have setup an interface that I'd like to be injected in that custom base page class. However, it's not working (my interfaces are null), and I assume that is because Ninject doesn't know about System.Web.Mvc.MvcWebRazorHostFactory which I suspect it would have to override or intercept somehow. Can anyone point me in the right direction on how to allow my custom WebViewPage to use DI? A: Well, the best solution I found so far is inject the dependency manually from the constructor of the class using the DependencyResolver: public class MyView : WebViewPage<MyModel> { IContract _contract; public MyView () { _contract= DependencyResolver.Current.GetService<IContract>(); } } Since Ninject integrates with the DependencyResolver, it works good so far. Regards. A: Here is a possible workaround...Use a KernelPersister to state the kernel, and reference it directly from within your base View. It's not as pretty and seamless as constructor injection, but it does the trick. KernelPersister might look like this... public static class KernelPersister { static IKernel persistedKernel; /// <summary> /// Persists the provided kernel /// </summary> public static void Set(IKernel kernel) { if(persistedKernel == null) { throw new ArgumentNullException("kernel"); } persistedKernel = kernel; } /// <summary> /// Gets the persisted kernel /// </summary> public static IKernel Get() { if(persistedKernel == null) { throw new Exception("The kernel must be actively set in the persister"); } return persistedKernel; } } Base view might look like this... public abstract class MyBaseView : System.Web.Mvc.WebViewPage { /// <summary> /// Gets access to the MyService /// </summary> protected IMyService MyService {get; private set;} /// <summary> /// ctor the Mighty /// </summary> public MyBaseView() { var kernel = KernelPersister.Get(); this.MyService = kernel.GetService(typeof(IMyService)) as IMyService; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7586075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to do something at the end of a Youtube video I'm currently launching a Youtube video using this piece of code: Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube://"+token)); activity.startActivityForResult(intent, SmartBrowserWebViewActivity.ACT_YOUTUBE); It works great. But I would like at the end of the video play to get the capability to do what I want. For example how to change activity when the video is over ? Currently the user has to click back and I can handle it through the onActivityResult, but is there a way to avoid the user click on "back"? Maybe I should play flash video to do it or HTML5 video ? Thank you! A: Implement and OnCompletionListener. Here is an example of my code. It should work the same as a RAW file video. final VideoView vs = (VideoView) findViewById(R.id.imlsplash); // Set video link (mp4 format ) Uri video = Uri.parse("android.resource://"+getPackageName() +"/" +R.raw.iphonesplashfinal); vs.setVideoURI(video); vs.requestFocus(); vs.start(); vs.setOnCompletionListener(new OnCompletionListener(){ @Override public void onCompletion(MediaPlayer mp) { startActivity(new Intent(CurrentActivity.this, NextActivity.class)); CurrentActivity.this.finish(); } }); } you may have to replace the videoView with whatever you are using. If you are using a URL change URI to URL and add URL in place of "android.resource://"+getPackageName() +"/" +R.raw.iphonesplashfinal
{ "language": "en", "url": "https://stackoverflow.com/questions/7586083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Dynamic Linq to Xml example I need a basic example on how to use System.Linq.Dynamic with Xml. Here’s a functioning statement I want to convert to dynamic Linq: XElement e = XElement.Load(new XmlNodeReader(XmlDoc)); var results = from r in e.Elements("TABLES").Descendants("AGREEMENT") where (string)r.Element("AGRMNT_TYPE_CODE") == "ISDA" select r.Element("DATE_SIGNED"); foreach (var x in results) { result = x.Value; break; } Here’s the approach I am using: string whereClause = "(\"AGRMNT_TYPE_CODE\") == \"ISDA\""; string selectClause = "(\"DATE_SIGNED\")"; var results = e.Elements("TABLES").Descendants<XElement>("AGREEMENT"). AsQueryable<XElement>(). Where<XElement>(whereClause). Select(selectClause); foreach (var x in results) { result = (string)x; break; } It executes without error but produces no results. I am trying to code this similar to the canonical example found at http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx where a constructed string is applied against a database: Dim Northwind as New NorthwindDataContext Dim query = Northwind.Products _ .Where("CategoryID=2 and UnitPrice>3") _ .OrderBy("SupplierId") GridView1.Datasource = query GridView1.Databind() What am I missing? I finally got it working. I abandoned my original approach because as of now I'm not convinced it was even intended for use with Xml. I've seen little posted anywhere to argue against that statement. Instead, I used Jon Skeet's response to this question as the basis for my answer: XElement e = XElement.Load(new XmlNodeReader(XmlDoc)); List<Func<XElement, bool>> exps = new List<Func<XElement, bool>> { }; exps.Add(GetXmlQueryExprEqual("AGRMNT_TYPE_CODE", "ISDA")); exps.Add(GetXmlQueryExprNotEqual("WHO_SENDS_CONTRACT_IND", "X")); List<ConditionalOperatorType> condOps = new List<ConditionalOperatorType> { }; condOps.Add(ConditionalOperatorType.And); condOps.Add(ConditionalOperatorType.And); //Hard-coded test value of the select field Id will be resolved programatically in the //final version, as will the preceding literal constants. var results = GetValueFromXml(171, e, exps, condOps); foreach (var x in results) { result = x.Value; break; } return result; ... public static Func<XElement, bool> GetXmlQueryExprEqual(string element, string compare) { try { Expression<Func<XElement, bool>> expressExp = a => (string)a.Element(element) == compare; Func<XElement, bool> express = expressExp.Compile(); return express; } catch (Exception e) { return null; } } public static Func<XElement, bool> GetXmlQueryExprNotEqual(string element, string compare) { try { Expression<Func<XElement, bool>> expressExp = a => (string)a.Element(element) != compare; Func<XElement, bool> express = expressExp.Compile(); return express; } catch (Exception e) { return null; } } private IEnumerable<XElement> GetValueFromXml(int selectFieldId, XElement elem, List<Func<XElement, bool>> predList, List<ConditionalOperatorType> condOpsList) { try { string fieldName = DocMast.GetFieldName(selectFieldId); string xmlPathRoot = DocMast.Fields[true, selectFieldId].XmlPathRoot; string xmlPathParent = DocMast.Fields[true, selectFieldId].XmlPathParent; IEnumerable<XElement> results = null; ConditionalOperatorType condOp = ConditionalOperatorType.None; switch (predList.Count) { case (1): results = from r in elem.Elements(xmlPathRoot).Descendants(xmlPathParent) where (predList[0](r)) select r.Element(fieldName); break; case (2): CondOp = (ConditionalOperatorType)condOpsList[0]; switch (condOp) { case (ConditionalOperatorType.And): results = from r in elem.Elements(xmlPathRoot).Descendants(xmlPathParent) where (predList[0](r) && predList[1](r)) select r.Element(fieldName); break; case (ConditionalOperatorType.Or): results = from r in elem.Elements(xmlPathRoot).Descendants(xmlPathParent) where (predList[0](r) || predList[1](r)) select r.Element(fieldName); break; default: break; } break; default: break; } return results; } catch (Exception e) { return null; } } This approach, however, is obviously far from perfect. * *I have separate functions for resolving and compiling the expressions-- just to incorporate different conditional operators. What's worse, I will be adding more to support additional logical operators and numeric values; *The GetValueFromXml routine is clunky and will have to grow additional cases as I add more parameters. Any ideas or suggestions would be greatly appreciated. A: There are two issues here really, your where clause: ("AGMNT_TYPE_CODE") == "ISDA" ... will of course evaluate to false, because they are both strings. The second issue is that the ExpressionParser is limited in scope, it can only do comparisons on a set of predefined types. You need to recompile the Dynamic library and either allow some additional types (you can do this by modifying the predefinedTypes static field of the ExpressionParser type) or, remove the check for predefined types (which is what I have done previously): Expression ParseMemberAccess(Type type, Expression instance) { // ... switch (FindMethod(type, id, instance == null, args, out mb)) { case 0: throw ParseError(errorPos, Res.NoApplicableMethod, id, GetTypeName(type)); case 1: MethodInfo method = (MethodInfo)mb; //if (!IsPredefinedType(method.DeclaringType)) // Comment out this line, and the next. //throw ParseError(errorPos, Res.MethodsAreInaccessible, GetTypeName(method.DeclaringType)); if (method.ReturnType == typeof(void)) throw ParseError(errorPos, Res.MethodIsVoid, id, GetTypeName(method.DeclaringType)); return Expression.Call(instance, (MethodInfo)method, args); default: throw ParseError(errorPos, Res.AmbiguousMethodInvocation, id, GetTypeName(type)); } // ... } Those lines I have commented out are where the check for predefined types are done. Once you have made that change, you need to update your query (remember, ExpressionParser builds expressions that are compiled, so simply using "(\"AGRMNT_TYPE_CODE\") == \"ISDA\"" wont work. You would need something like: string where = "Element(\"AGMNT_TYPE_CODE\").Value == \"ISDA\""; A: Following this form of a template may assist you: Nodes = (from N in xDoc.Elements(NodeName) where (string)N.Element("AGMNT_TYPE_CODE") == "ISDA" select N);
{ "language": "en", "url": "https://stackoverflow.com/questions/7586084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Boost condition_variable destruction assert My question is: is there something specific I need to do (like call notify_all?) in the destructor of a thread that encapsulates a boost::condition_variable. The following code generates this assert when the Test destructor is called: cond_var: /usr/include/boost/thread/pthread/condition_variable_fwd.hpp:38: boost::condition_variable::~condition_variable(): Assertion `!pthread_cond_destroy(&cond)' failed. Aborted #include <boost/thread/mutex.hpp> #include <boost/thread/condition_variable.hpp> #include <boost/thread.hpp> class Test { public: ~Test() { /* ??? */ } int getI() { boost::mutex::scoped_lock lock(mtx); cond_var.wait(lock); return i; } void putI() { i=10; cond_var.notify_one(); } int i; boost::mutex mtx; boost::condition_variable cond_var; } t; void runPut () { for(;;) { t.getI(); } } void runGet () { for(;;) { t.putI(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } } int main() { boost::thread t1(&runPut); boost::thread t2(&runGet); boost::this_thread::sleep(boost::posix_time::seconds(5)); return 0; } (gdb) bt 0 0x00007ffff70c4d05 in raise () from /lib/x86_64-linux-gnu/libc.so.6 1 0x00007ffff70c8ab6 in abort () from /lib/x86_64-linux-gnu/libc.so.6 2 0x00007ffff70bd7c5 in __assert_fail () from /lib/x86_64-linux-gnu/libc.so.6 3 0x0000000000406a35 in boost::condition_variable::~condition_variable (this=0x6104d0, __in_chrg=<value optimized out>) at /usr/include/boost/thread/pthread/condition _variable_fwd.hpp:38 4 0x0000000000406f42 in Test::~Test (this=0x6104a0, __in_chrg=<value optimized out>) at cond_var.cpp:19 5 0x00007ffff70ca961 in exit () from /lib/x86_64-linux-gnu/libc.so.6 6 0x00007ffff70aff06 in __libc_start_main () from /lib/x86_64-linux-gnu/libc.so.6 7 0x0000000000405899 in _start () A: You need to join the two threads you've created before you exit. Add a global boolean variable called say, 'stop', initialized to false, and have t1 and t2 check that it's false every iteration: bool stop = false; void runPut () { while( !stop ) { t.getI(); } } void runGet () { while( !stop ) { t.putI(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } } Then after your sleep in main set it to true, and call join on t1 and t2. boost::this_thread::sleep(boost::posix_time::seconds(5)); stop = true; t1.join(); t2.join(); Otherwise the condition variables are getting destroyed while still in use.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to place inline div and input I have a html form. There are many input's and label's. In the bottom of the form I have one div and one input (submit). How can I place them (div and input (submit button)) in one horizontal line? A: This is one approach: <div> <div style="float:left">my div</div><input type="submit" style="float:left"> </div> A: div.someclass { float: left; width: 200px /* or whatever you need to make it look good */ } or gross inline styles with <div style="float: left;"></div><input type="submit" /> A: Make both elements float: left and make their parent overflow: auto. Mind sharing your code? It's a bit hard to do this blindly, as your HTML structure might be different that what I think it is. A: It is possible to target input types specifically, like: input [type=submit] { css rules here } So you could just assign your div to float:left; and do the same with your input. Floating them will cause them to line up next to each other. Example Here
{ "language": "en", "url": "https://stackoverflow.com/questions/7586091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: receive byte[] from asp.net website with webrequest I need to get some information from a website. that website is not meant to be accessed from a browser. so let's say that the website contains a byte array: I want to get that byte array from a console application. // c# code for asp website protected byte[] data; protected void Page_Load(object sender, EventArgs e) { data = new byte[] { 1, 100, 200, 255 }; // the byte array that I want to send } // the asp content <body> <form id="form1" runat="server"> <div> <%=data%> </div> </form> </body> if 'data' would have been a string I would be able to retrieve that by parsing the responseFromServer variable defined in the following code. // Create a request using a URL that can receive a post. WebRequest request = WebRequest.Create("http://localhost:4444/WebSite2/HelloFromC.aspx"); // Set the Method property of the request to POST. request.Method = "POST"; // Create POST data and convert it to a byte array. string postData = "This is a test that posts this string to a Web server."; byte[] byteArray = Encoding.UTF8.GetBytes(postData); // Set the ContentType property of the WebRequest. request.ContentType = "application/x-www-form-urlencoded"; // Set the ContentLength property of the WebRequest. request.ContentLength = byteArray.Length; // Get the request stream. Stream dataStream = request.GetRequestStream(); // Write the data to the request stream. dataStream.Write(byteArray, 0, byteArray.Length); // Close the Stream object. dataStream.Close(); // Get the response. WebResponse response = request.GetResponse(); // Display the status. Console.WriteLine(((HttpWebResponse)response).StatusDescription); // Get the stream containing content returned by the server. dataStream = response.GetResponseStream(); // Open the stream using a StreamReader for easy access. StreamReader reader = new StreamReader(dataStream); // Read the content. string responseFromServer = reader.ReadToEnd(); // Display the content. Console.WriteLine(responseFromServer); // Clean up the streams. reader.Close(); dataStream.Close(); response.Close(); Things that I have tried: I have tried converting the byte array { 1, 100, 200, 255 } to ASCII. then with the encoding class converting it back to a byte array. the problem with ASCII is that it does not hold 256 characters. Maybe I should use a different type of encoding. But I have to make sure that whatever class of encoding I use is supported by my website... A: use something similar to byte[] myBinaryResponse = new byte[response.ContentLength]; response.GetResponseStream().Read (myBinaryResponse, 0, myBinaryResponse.Length); A: Following on from the comments above you might like to look at this tutorial on handlers (as chris lively suggested) http://www.dotnetperls.com/ashx It might also help to give a few more details of the end goal. Are you always trying to push out a byte array? If so perhaps a web service might help. A web service tutorial How will you consume this data? In a different webpage or a windows application?
{ "language": "en", "url": "https://stackoverflow.com/questions/7586092", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Git working over http but not ssh I have a remote repository that is working fine when I communicate over http, but if I use ssh it gives me errors when trying to push. Goal: get the repo to work over ssh I can ssh directly into the remote machine without problem, all folders and files in the git repo and git working directory have 771 permissions, the owner is apache and group is 'test' (which the user I'm ssh-ing with 'test' is a member of). I also tried changing the owner and group to 'test', but that didn't help. I've confirmed the user account is able to read/write/execute from the git directories via ssh. I have a non-standard directory setup due to using virtualmin: /home/test (user home) /home/test/public_html (web root) /home/test/public_html/git (gitweb directory) /home/test/public_html/git/git.git (repo directory) This causes the same error message as below (no such file or directory) when I do any git commands 'locally' (directly on the remote server) unless I specify --git-dir and --work-tree, however, since http is working and pushing to the remote server shouldn't need to know the remote working directory, I don't see how this would be the issue (and also don't see how to fix it if it was). Also, if it's relevant, I'm using password authentication rather than keys. Does anyone have thoughts on how I can solve / further diagnose this issue? The error git push origin: Counting objects: 5, done. Delta compression using up to 4 threads. Compressing objects: 100% (3/3), done. Writing objects: 100% (3/3), 309 bytes, done. Total 3 (delta 2), reused 0 (delta 0) error: unable to create temporary sha1 filename ./objects/1d: No such file or directory fatal: failed to write object error: unpack failed: unpack-objects abnormal exit To test@test.local:/home/test/public_html/git/git.git/ ! [remote rejected] master -> master (n/a (unpacker error)) error: failed to push some refs to 'test@test.local:/home/test/public_html/git/git.git/' More info git push origin (WHEN USING HTTP to http://test@test.local/git/git.git/): Password: Password: Fetching remote heads... refs/ refs/heads/ refs/tags/ updating 'refs/heads/master' from 425f5c3810b1c9e4ecc7ee7df3cd1bb8818b2115 to 65d2358df3035689116339a14f504f34a6212a27 sending 3 objects done Updating remote server info To http://test@test.local/git/git.git/ 425f5c3..65d2358 master -> master (I'm a bit confused why there's so much difference between http and ssh here; the http asks me my password twice and then starts fetching remote heads, whereas the ssh asks me my password once and then starts counting objects.) git pull origin: Already up-to-date git remote show origin: * remote origin Fetch URL: test@test.local:/home/test/public_html/git/git.git/ Push URL: test@test.local:/home/test/public_html/git/git.git/ HEAD branch: master Remote branches: master tracked release tracked Local branches configured for 'git pull': master merges with remote master release merges with remote release Local refs configured for 'git push': master pushes to master (fast-forwardable) release pushes to release (up to date) And if it's of any use, my local config file: [core] repositoryformatversion = 0 filemode = true bare = false logallrefupdates = true [remote "origin"] fetch = +refs/heads/*:refs/remotes/origin/* url = test@test.local:/home/test/public_html/git/git.git/ [branch "master"] remote = origin merge = refs/heads/master [branch "release"] remote = origin merge = refs/heads/release And remote config file: [core] repositoryformatversion = 0 filemode = true bare = false worktree = /home/test/public_html sharedRepository = true Further investigation After Jan's comments I investigated the problem a bit further. I was assuming only the 'test' account would be used during push over ssh (and apache used over http push), but I think it must be both. I've gone back through the non-working repo and set the ownership the same as in the working repo (some files/folders are apache.test, others are test.test, and the config file is root.test). I haven't checked absolutely everything, but the files in the repo dir, and all files and folders under objects, refs and info all have identical ownership and permissions in both the working and non-working, and the user accounts are set up in the same way (I did try 777 in my troubleshooting previously). The main difference I can think of is that in the the non-working repo, I started using http and then switched to ssh, whereas in the working repo I went directly to using ssh and the repo was empty before that. Perhaps there's an odd file somewhere with wrong permissions that's breaking everything, or there's something bizarre going on inside the actual files that I've upset by using different protocols, or maybe it's just got corrupt due to my hours of trying to get it to work yesterday. A: I set up a brand new remote repository under a different user account and it's now working fine. All settings are the more or less the same (permissions are less strict this time), so I'm not sure what the issue was. A: If you search the web for the exact text of the error message you are getting, it returns lots of hits. From quick look at them, it seems to be a permission problem. You say you have the repository owned by apache.test. However, is apache actually running as apache.test? If not, the new directories the git server run by apache create will be owned by different group (whatever is primary group of the server) and the test user can't write there despite the fact you told git to make the repo group-writable. You have several options: * *Use suExec to run the git cgi as test.test and drop the group-writable permission. *Use the primary group of the web server as the owning group *Make the repo everybody-writable (core.sharedRepository = everybody) *It should be possible to make the repo SGID to the right group by setting core.sharedRepository to 2664, but I am not too sure with that. Personally I'd prefer the suExec.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586093", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: In-App purchase server model I have got few questions about In-App Purchase server model. I have got my DB, and a table in which I store item description. For example, I've got a Sword priced $0.49 and a Mace priced $0.99. So table with fields - id, name, price, info(description). I want to display this items in my iOs application, and allow users to buy them. My server-side is written on php. It seems that there is no normal tutorial on server-model for in-app purchase. So I was reading http://developer.apple.com/library/ios/#documentation/NetworkingInternet/Conceptual/StoreKitGuide/APIOverview/OverviewoftheStoreKitAPI.html (figure 1.3), and it seems that I have to: * *Send request to my server and receive this items data. What is product identifier, and where can I get it? *Application sends request to app store to get information for the products. What kind of request? Any sample code? What this request will return? *Ok, now i'm displaying this info to user, he picks item he wants to buy, and app sends payment request to the appstore. Again, what request, any examples? *Then app receives receipt data. And it must send it to my server. And my server must send this data to app store server to verify the purchase, how can I do it? *Apple server returns answer to my server, and I add item to users inventory(f.e). Now, about testing in-app purchase. As far as I understand I need to go to itunes connect, and add new application there, and add in-app monetization for this application, and test user, is it correct? A: There are a couple of good frameworks written by developers to help you on inAppPurchases. These frameworks are designed for all types of products (consumables, non consumables and subscriptions) along with a server model to validate the receipt. https://github.com/MugunthKumar/MKStoreKit - Good One https://github.com/anystone/AnystoneStoreKit - Another good wrapper. uses better delegates. There is a third very easy tutorial (only for non consumables) http://www.raywenderlich.com/2797/introduction-to-in-app-purchases This one explains every question you have and gets you started with an example.. A: This tutorial provides clear step by step means to implement in-app purchases from scratch... After going through countless others, the examples here should cover your questions. http://troybrant.net/blog/2010/01/in-app-purchases-a-full-walkthrough/
{ "language": "en", "url": "https://stackoverflow.com/questions/7586094", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Django: How to concatenate translation and constant string in template I'd like to pass a translation with variable to template tag. I'm trying to do it this way: {% my_tag _("Entries for tag")|add:" '"|add:tag|add:"'" %} But this does not work. Is there any solution? A: What's wrong with <span>{% my_tag _("Entries for tag") %} '{{tag}}'</span> A: One solution would probably be: {% blocktrans with tag=tag %} <span>Entries for tag</span> '{{ tag }}' {% endblocktrans %} But putting HTML inside translated strings is not the best idea. What is much worse though is assuming that you can just concatenate a translation of an English string with another string and get a valid sentence. You can never assume that position of {{ tag }} withing the sentence will be the same in other languages. Some language will probably need the translation to be Lorem ipsum „%(tag)s” dolor sit. But it seems you're trying to apply some HTML dynamically. Maybe what you really want is to ugettext('Entries for tag %(tag)s') inside my_tag and parse it accordingly (say find %(tag)s and add some HTML around it).
{ "language": "en", "url": "https://stackoverflow.com/questions/7586096", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Curious Spring AOP Exception I'm trying to get my first-ever Spring AOP-based MethodInterceptors working, and am getting some bizarre exceptions with my ultra-simple XML configuration. I have a class named Food which has a method called eat(ConsumptionRate rate) that takes an object of type ConsumptionRate as its sole parameter; every time that specific method (Food::eat(ConsumptionRate)) gets invoked, I want a MethodInterceptor to execute "around it": public class FoodInterceptor implements MethodInterceptor { public Object invoke(MethodInvocation method) { try { // Do some stuff before target method executes Object result = method.proceed(); return result; } finally { // Do some stuff after target method executes. } } } Here is my xml config (aop-config.xml) in its entirety: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <bean name="foodInterceptor" class="com.me.foodproject.core.FoodInterceptor"/> <aop:config> <aop:advisor advice-ref="foodInterceptor" pointcut="execution(public * Food.eat(..))"/> </aop:config> Project builds fine (compiles, etc.), but when I run it I get the following error: java.lang.IllegalArgumentException: warning no match for this type name: Food [Xlint:invalidAbsoluteTypeName] My only guess is that the pattern specified in the pointcut attribute is somehow wrong (maybe I need to include ConsumptionRate in it somehow). But the documentation for this XML Schema has been nearly impossible to find, and I'm stumbling around in the dark here. Anybody have any suggestions or see something that jumps out at them? Thanks in advance! As an aside, if someone knows of a site or any literature that documents all of these <aop> tags and their attributes, please let me know. Chapter 6 of the Spring AOP reference has been recommended to me, and although that is a very comprehensive tutorial, it is just full of examples, and does not document the entire xml schema. A: Make sure you're using the fully-qualified class name (or a wildcard version that also matches), otherwise the class scanner won't find it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MySQL COUNT(), SUM() and GROUP BY I have a particular question which is about MySQL. Please have a look at the query and the result set below: SELECT COUNT(c.Population) AS c, c.City AS cc FROM City c GROUP BY c.City ORDER BY c.City; 261 | Bristol ---------------- 910 | London ---------------- 241 | Manchester ---------------- I'd like to get the SUM of the COUNTs, so in this case I'd like to see '1412' in the next row, or in a new column, it doesn't really matter. Any advice? I have tried to apply sub-queries to this but I couldn't find a proper solution. Cheers A: Does WITH ROLLUP do what you need? SELECT COUNT(c.Population) AS c, c.City AS cc FROM City c GROUP BY c.City WITH ROLLUP; A: in the select statement, this should work (untested). SELECT COUNT(c.Population) AS c, c.City AS cc, (SELECT COUNT(c.Population) FROM City) as TotalPop FROM City c GROUP BY c.City ORDER BY c.City; A: On one row at the end: SELECT * FROM ( SELECT 0 as total , COUNT(c.Population) AS c , c.City AS cc FROM City c GROUP BY c.City union SELECT 1 as total , COUNT(c.Population) AS c , null AS cc FROM City ) myquery ORDER BY total , city ORDER BY c.City; A: With simple UNION; select count(d.Population) as c, 'TOTAL' as cc from City d union SELECT COUNT(c.Population) AS c, c.City AS cc FROM City c GROUP BY c.City ORDER BY c.City; John
{ "language": "en", "url": "https://stackoverflow.com/questions/7586105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: how do I pass all the files in a folder to shell script and get result in one file? I have a shell script #!/bin/bash a=`grep "var lon" $1 | tr -d 'var longitude=;'` b=`grep "var lat" $1 | tr -d 'var latitude=;'` echo "$1,$a,$b"; I have around 100 files with latitude and longtude. which i pass through this script to get it. like place,lat,lon . where place is file name. now i would like to pass all the file to the script at one shot and get all the lat lons in one file. how do I do this ? for eg: one output for sh script.sh aus aus,10.20,20.20 now i am looking to pass all the 100 files and get 100 such lines in one single file. Thank you. A: Change your script to accept multiple arguments like this: #!/bin/bash for arg in "$@" do a=`grep "var lon" "$arg" | tr -d 'var longitude=;'` b=`grep "var lat" "$arg" | tr -d 'var latitude=;'` echo "$arg,$a,$b" done Now you can pass in whichever files you like. You can even use wildcards. Here are a few examples: # only aus $ script.sh aus # two files $ script.sh aus usa # all files beginning with a $ script.sh a* # all files in the current directory # the output is written to output.txt $ script.sh * > output.txt A: I can't code bash off the top of my head very well, but you can loop through all the files and append the output to a file via >>: touch output.txt for file in * do a=`grep "var lon" $file | tr -d 'var longitude=;'` b=`grep "var lat" $file | tr -d 'var latitude=;'` echo "$file,$a,$b" >> output.txt done A: You don't need to call grep twice: awk -F '[=;]' ' $1 ~ /var longitude/ {lon = $2} $1 ~ /var latitude/ {lat = $2} END {print FILENAME, lon, lat} ' filename then get_coords() { awk -F '[=;]' ' $1 ~ /var longitude/ {lon = $2} $1 ~ /var latitude/ {lat = $2} END {print FILENAME, lon, lat} ' "$1" } for file; do get_coords "$file"; done If you have GNU awk on your system, you only need to call gawk once: gawk -F '[=;]' ' $1 ~ /var longitude/ {lon = $2} $1 ~ /var latitude/ {lat = $2} ENDFILE {print FILENAME, lon, lat} ' "$@"
{ "language": "en", "url": "https://stackoverflow.com/questions/7586110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Prototypes and object creation Lately I'm trying to get the technical aspects of the prototype chain. Now I have a few questions about object instantiation. Consider the following code: var Foo = function(s) { this._bar = s; }; var fooInst = new Foo('test'); Now when I examine the created object, then: Foo.prototype === Function.prototype; // true fooInst.prototype === ? fooInst.prototype.prototype === Object.prototype; // true I'm wondering, what fooInst.prototype exactly is. In Chromes inspector it seems to be some kind of Foo with an constructor property. But all sources I read about prototypes state that fooInst.prototype === Foo.prototype should be true. So my question: how exactly does JS handle the prototype chain. What exactly happens when I call new Foo. Thanks in advance! Edit So I found, that (in Chrome) Object.getPrototypeOf(fooInst) === Foo.prototype; is true, but Object.getPrototypeOf(fooInst) === Object.getPrototypeOf(Foo) is false. Why that? A: I'm wondering, what fooInst.prototype exactly is. It is undefined. fooInst.prototype === undefined; // true Only functions have an automatic .prototype property. Objects do not. If you create an object using a constructor, like: var fooInst = new Foo('test'); ...then fooInst will have an internal reference to Foo.prototype, but there's no standard property to get Foo.prototype from fooInst. That said, there is a non-standard property that is supported in some JavaScript environments for referencing the prototype object. fooInst.__proto__ === Foo.prototype; // true (if __proto__ supported) Also, there is a method provided by ECMAScript 5 that can be used. Object.getPrototypeOf( fooInst ) === Foo.prototype; // true That internal reference from an object to its prototype object can be just the first in a chain of such references. The prototype object likely has its own prototype object that is referenced. (In basic cases, this will be Object.prototype, or with longer chains, Object.prototype may be further down the chain.) Object.prototype itself references null as its prototype. This ends the chain. You should note that the internal reference from an object to its prototype object does not change if you change the .prototype object of the constructor function. It is a reference that exists for the life of the object. var Foo = function(s) { this._bar = s; }; var fooInst = new Foo('test'); Object.getPrototypeOf( fooInst ) === Foo.prototype; // true // Change the prototype object of Foo Foo.prototype = { some:'object' }; Object.getPrototypeOf( fooInst ) === Foo.prototype; // false A: Your first assumption: Foo.prototype === Function.prototype; Is not right, I think you are mixing up the concept of the [[Prototype]] internal property that all objects have, and makes the "link" of the prototype chain, and the prototype property that function objects have. The above comparison will produce false because the value of the Foo.prototype property is a new object, created at the time you created the Foo function. This object is initialized whenever you create a function object, it inherits from Object.prototype and it has a property, named constructor that points back to the function (Foo.prototype.constructor === Foo), and it's used when you call your function as a constructor. Now, if we talk about the [[Prototype]] internal property, you are right, the [[Prototype]] of your Foo function is Function.prototype in other words, Foo inherits from Function.prototype, e.g.: Object.getPrototypeOf(Foo) === Function.prototype; // true Foo instanceof Function; // true Foo.__proto__ === Function.prototype; // true About fooInst this object was created in a new expression, when you used your Foo function as a constructor, this new object is produced, and it inherits from Foo.prototype, (its internal [[Prototype]] property points to Foo.prototype). It doesn't have a prototype property, since this property is only meaningful for function objects. See also: * *JavaScript prototype limited to functions? *How does 'new' work internally A: You might find the explanations and diagrams in JavaScript. The Core useful here. All objects have a prototype chain. As such, fooInst has a prototype chain, at the head of which is Foo.prototype. When you called new Foo, an Object was created, Foo.prototype was set as its prototype chain and the constructor function was called in the context of the new Object. Some browsers expose this as a non-standard __proto__ property, such that: fooInst.__proto__ === Foo.prototype
{ "language": "en", "url": "https://stackoverflow.com/questions/7586113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: MVC Webgrid Column Pointing to Array Indices - is this possible? I'm playing with the MVC Webgrid in a project, pretty impressed so far, but I think I've found one restriction to it's capabilities, which I'm assuming is due to the nature of its reflection capabilities. It seems quite alright to point at data as such: var grid = new WebGrid(source: Model); //this has Model.Data - an IEnumerable list of "whatever". grid.Columns(grid.Column("Data.SomeProperty")); However you can't access a value in an array, such as: grid.Columns(grid.Column("Data.SomeArray[0]")); Which seems fair enough, as what I'm trying to do with this is a bit cheeky, but I just wondered if I'm missing something & this is technically possible... Many thanks A: Try like this: grid.Column("ColumnName", format: @<text>@item.Data.SomeArray[0]</text>)
{ "language": "en", "url": "https://stackoverflow.com/questions/7586114", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JOSM Map Editor component With the use of what is written editor component? Where can I find the source code for drawing editor ? I try to develop simple training map editor with fast interface and drawing, but I don't know how to do it with Java. A: JOSM is built with the standard Java API. Thus, all graphical components are based on Swing which is the standard GUI toolkit included in Java runtime. You can find the source code of JOSM at various locations. The primary and official location is the SVN repository: svn co https://josm.openstreetmap.de/svn/trunk JOSM editing and rendering system is powerful, so it is built thanks to many classes. You should have a look to the following ones to understand the basics required to render map objects and edit them: org.openstreetmap.josm.gui.NavigatableComponent org.openstreetmap.josm.gui.MapView org.openstreetmap.josm.data.osm.visitor.paint.AbstractMapRenderer org.openstreetmap.josm.data.osm.visitor.paint.WireframeMapRenderer A: I don't know what JOSM uses. But have a look at GEF http://www.eclipse.org/gef/. It's a graphical editing framework.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wordpress Custom Widget - Saving a list of checkboxes created from custom post types This is probably a pretty standard thing to do. I just can't work out for the life of me how to do it. I checked various other coded doing similar things but most of them seem to do things in a different way from me which I don't quite understand. Basically I am creating a simple custom widget. It pulls in all the post from a post type and displays them as checkboxes. I need to save which posts were selected and then pass this on as an array so that I can then display the selected posts. To display the checkboxes in a form I have: $postcount5 = 0; $featured_query5 = new WP_Query('showposts=5&post_type=adverts'); while ($featured_query5->have_posts()) : $featured_query5->the_post(); $do_not_duplicate[] = get_the_ID();$postcount5++; $currentid5 = get_the_ID(); echo '<p><label><input type="checkbox" name="adverts" value="'; the_id(); echo'" '; if ( $currentid5 == $adboxid ) echo 'checked="yes"'; echo '/> '; the_title(); echo' </label><br/></p>'; Once I have managed to save them I should be fine. I just cannot work out how to save a list of dynamically created checkboxes. Thanks in advance. A: The code as it is, wouldn't work even if it wasn't dynamically. What you need to do is rename the name of the checkboxes too, otherwise only the last value will be accessible. E.g. you could do it like so: $postcount5 = 0; $featured_query5 = new WP_Query('showposts=5&post_type=adverts'); while ($featured_query5->have_posts()) : $featured_query5->the_post(); $do_not_duplicate[] = get_the_ID(); $postcount5++; $currentid5 = get_the_ID(); echo '<p><label><input type="checkbox" name="adverts'.$postcount5.'" value="'.$the_id().'"; if ( $currentid5 == $adboxid ) echo 'checked="yes"'; echo '/> '; the_title(); echo' </label><br/></p>'; And to finally get the values, you need a submit button and wrap the whole thing into a with a set 'action' element like: <form name="postselector" action="whereever_you_want_the_user_to_go_next.php"> INSERT HERE ALL THE INPUT CHECKBOXES AND THE SUBMIT BUTTON </form> In whereever_you_want_the_user_to_go_next.php you can finally read the selected items by: if (isset($_POST['submit'])) { $selectedposts = array(); $i = 0; foreach($_POST as $name => $value) { if (preg_match('adverts',$name) { $selectedposts[$i] = $value; $i++; } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7586117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Common Table Expression in a SQL WHILE loop? How can I use a common table expression (CTE) in a while loop? The following is give errors on the "while" statement and the reference to the "cte": Errors: (1) Incorrect syntax near WHILE (2) Invalid object name 'cte' WITH cte AS ( SELECT t.employee FROM EmpTable as t WHERE (t.status = 3) ) WHILE ((SELECT COUNT(*) FROM cte) <> 0) --more stuff here A: You can't do that. The CTE's scope is only the for the next query. It is effectively actually just a part of the query it precedes. Just like an inline view (sub-query) is part of a larger query. In your case you'd need to go back to good old temp tables, table variables, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SQL Query Add an Alternate Blank Records I am using following Query to Display Records from SQL SERVER select * from orders Currently this query shows all 100 records in database, what i need is instead of 100 it should show 200 records ( so alternate blank records is fine ) It is possible can it be done ? A: -- sample table declare @Order table ( orderid int, qty int ) -- add some data insert into @Order select 1, 10 union all select 2, 20 union all select 3, 30 -- cross join the query against two rows select case D.N when 1 then O.orderid end as orderid, case D.N when 1 then O.qty end as qty from @Order as O cross join (select 1 union all select 2) as D(N) order by O.orderid, D.N Result: orderid qty ----------- ----------- 1 10 NULL NULL 2 20 NULL NULL 3 30 NULL NULL
{ "language": "en", "url": "https://stackoverflow.com/questions/7586122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Engine Yard deploy failed while executing migration script I am trying to deploy ruby on rails 2 based application using engine yard gem and get following error: ey deploy --migrate=rake db:migrate Beginning deploy for 'test' in 'test' on server... ~> Deploying revision 11111 Test commit. ~> Pushing code to all servers ~> Starting full deploy ~> Copying to /data/test/releases/20110928152454 ~> Ensuring proper ownership ~> Preparing shared resources for release ~> Set group write permissions ~> Remove revision-tracked shared directories from deployment ~> Create tmp directory ~> Symlink shared log directory ~> Create public directory if needed ~> Create config directory if needed ~> Create system directory if needed ~> Symlink shared pids directory ~> Symlink other shared config files ~> Symlink mongrel_cluster.yml ~> Symlink database.yml ~> Symlink newrelic.yml if needed ~> Setting ownership to deploy:deploy ~> Migrating: cd /data/test/releases/20110928152454 && PATH=/data/test/releases/20110928152454/ey_bundler_binstubs:$PATH RAILS_ENV=production RACK_ENV=production NODE_ENV=production MERB_ENV=production rake Run "rake db:migrate" to update your database then try again. ~> [Attention] Maintenance page still up, consider the following before removing: * any deploy hooks ran, be careful if they were destructive * any migrations ran, be careful if they were destructive * your old code is still symlinked as current Failed deployment recorded in AppCloud Deploy failed Has anyone face the same problem before?
{ "language": "en", "url": "https://stackoverflow.com/questions/7586127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Hashtable- Rehashing I have been told that Hashtable in .NET uses rehashing in order to reduce/avoid collision. Ie. “Rehasing works as follows: assume we have a set of hash different functions, H1 ... Hn, and when inserting or retrieving an item from the hash table, initially the H1 hash function is used. If this leads to a collision, H2 is tried instead and onwards up to Hn to avoid collision in Hashtable.” Assumption: We have a hashtable with n (where n < Infinity) element where asymptotic time complexity is o(1); we (CLR) have achieved this while applying some hashing function ( Hn-1 hash function where n>1). Question: Can someone explain me how CLR map Key to the hash code when we seek (retrieve) any element (if different hashing functions are used)? How CLR track (if it) the hashing function of any live object (hash table)? Thanks in advance A: Random selection of a hash function is know as Universal Hashing approach. AFAIK the hash function selected once per some initialization process so this is not a real case when in scope of a single hash table were used multiple hash functions. EDIT: More details Just back at home, opened "Introduction to algorithms" T. Cormen book and found following in the section 11.3.3 Universal Hashing: The main idea behind universal hashing is to select the hash function at random from a carefully designed class of functions at the beginning of execution You can read more by previewing the book at the Google Books site here
{ "language": "en", "url": "https://stackoverflow.com/questions/7586128", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: JQuery: Hide anchor if href is empty Been on this one for a while now. Basically, I need to check where a href on an anchor tag with the class .pdf-download is empty, and if it is, hide it. I have attempted a few options but with no luck. This is what i have so far: $("a.pdf-download").each(function (i) { if ($('[href]:empty',this).length == 1) { $(this).hide(); } else { $(this).show(); } }); A: You can also do this with a jQuery selector, as follows: // Hide any links with blank href or no href attribute $('a.pdf-download[href=], a.pdf-download:not([href])').hide(); A: Use this solution. it will also produce the desired results when the href attribute is not defined. If you use a CSS selector (JQuery), non-existent href attributes will not be detected. $("a.pdf-download").each(function (i) { if (!this.href) { $(this).hide(); } else { $(this).show(); } }) It's not necessary to use a JQuery method to get the href attribute, becausethis.href is just as readable, faster and also universally supported. A: Would something like this work? $("a.pdf-download").each(function (i) { if ($(this).attr('href').length == 0) { $(this).hide(); } else { $(this).show(); } }); A: if ($(this).attr('href') != '') { $(this).hide(); } else { $(this).show(); } Note that you can also do this in css with attribute selectors: a.pdf-download[href='']{ display:none; } This is not supported in ie6 though. A: I am a jquery beginner myself, but thats how I would do it: $("a.pdf-download").each(function (i) { var aHref = $(this).attr('href'); if (aHref == '' || !aHref) { $(this).hide(); }; }); Demo: http://jsfiddle.net/BZq9c/1/ A: $(function() { $('a').each(function() { (!$(this).attr('href')) ? $(this).hide() : $(this).show(); }); }); Almighty Demo: http://jsfiddle.net/each/j9DGw/ A: $("a.pdf-download").each(function() { var href = $(this).attr("href"); if(href == '') { $(this).remove(); } }); or $("a.pdf-download[href='']").remove()
{ "language": "en", "url": "https://stackoverflow.com/questions/7586136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Getting Type T from a StackFrame The goal is to create a generic instance based on the type that called my method. The problem is that when called from a generic, the StackFrame only appears to contain the open definition type parameters instead of the closed definition type arguments. How do I get type arguments from a StackFrame? Similar to this question. I'd like to think my situation is different since Log.Debug is being called from a closed method. If StackFrame isn't the right approach, any suggestions other than IoC? This code is meant to fill in the case where a reference to my Unity container isn't available. using System; using System.Reflection; namespace ReflectionTest { public class Logger { private readonly string loggerName; protected Logger(string loggerName) { this.loggerName = loggerName; } public void Debug(string message) { Console.WriteLine(string.Format("{0} - {1}", loggerName, message)); } } public class Logger<T> : Logger { public Logger() : base(typeof(T).FullName) { } } public static class Log { public static void Debug(string message) { // Determine the calling function, and create a Logger<T> for it. System.Diagnostics.StackFrame frame = new System.Diagnostics.StackFrame(1); MethodBase method = frame.GetMethod(); /// When method is from a generic class, /// the method.ReflectedType definintion is open: Type.ContainsGenericParameters is true /// How do I get the generic parameters of method.ReflectedType so /// Activator.CreateInstance() will not throw? Type logType = typeof(Logger<>); Type constructed = logType.MakeGenericType(new Type[] { method.ReflectedType }); Logger logger = (Logger)Activator.CreateInstance(constructed); logger.Debug(message); } } public class MyBase<T> { public void Run() { Log.Debug("Run Generic"); // throws on Activator.CreateInstance() } } class Program { static void Works() { Log.Debug("Run NonGeneric"); // works } static void DoesNotWork() { MyBase<int> b = new MyBase<int>(); b.Run(); } static void Main(string[] args) { Works(); DoesNotWork(); } } } A: The stack frame is not reliable and is for debugging purposes only. You cannot assume that anything useful is there. That's why it is in the "Diagnostics" namespace. More generally though, your question demonstrates a fundamental misunderstanding about what the stack frame tells you. You said The goal is to create a generic instance based on the type that called my method. The stack frame does not actually tell you who called your method. The stack frame tells you where control is going to return to. The stack frame is the reification of continuation. The fact that who called the method and where control will return to are almost always the same thing is the source of your confusion, but I assure you that they need not be the same. In particular, the coming "async/await" feature currently in preview release demonstrates the truth of this. Code that resumes from an await has no clue on the stack frame about who called it originally; that information is lost forever. Since the code that is going to run next is logically decoupled from the code that called the method originally, the stack frame does not contain that information. We need not get as exotic as that though. For example, suppose a method M contains a call to a method N, and N calls a method O. If the jitter chooses to inline N inside M then the stack frame observed from O will not contain N. The stack frame tells you where control resumes when the current method returns. Control will resume inside M when O returns, not N, so the stack frame does not include any information about N.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Logging in Joomla platform 11 JLog I'm playing with the new Joomla 1.7 system built on the Joomla platform 11-- and all my logging code from earlier versions of Joomla no longer work (they appear to be writing log entries but with improper syntax, so the messages are blank). Does anyone know the proper syntax for the new version of JLog? Here's my existing code-- $log = &JLog::getInstance('test.log.php'); $log->addEntry(array('COMMENT' => 'A test Logging message')); This creates the log file, but the actual log entry looks like this: #<?php die('Forbidden.'); ?> #Date: 2011-08-08 16:59:42 UTC #Software: Joomla Platform 11.1 Stable+Modified [ Ember ] 01-Jun-2011 06:00 GMT #Fields: date time priority clientip category message 2011-08-08 16:59:42 INFO 127.0.0.1 - I've searched the Joomla docs and the web and found no examples of how to use this class. Thanks! A: Yes, the logging changed a bit indeed in Joomla 1.7: // Include the JLog class. jimport('joomla.log.log'); // Add the logger. JLog::addLogger( // Pass an array of configuration options array( // Set the name of the log file 'text_file' => 'test.log.php', // (optional) you can change the directory 'text_file_path' => 'somewhere/logs' ) ); // start logging... JLog::add('Starting to log'); A: @hbit thx a lot..I fixed like this and it work.. but I created as function.. <?php function logWrite($level, $values, $file='%s.php',$path='',$showOnTop=0, $option='',$component=''){ /**** jlog Joomla 3.4 created by:gundambison (2015.04.26). THX: hbit@stackoverflow ****/ jimport('joomla.log.log'); $level=strtoupper($level); //You can change this com_name $component= $component==''? 'com_gundambison': $component; $date= date("Ymd"); $filename= sprintf($file, $date); $format= $option=='' ?"{TIME}\t{CLIENTIP}\t{CATEGORY}\t{MESSAGE}": $option; // create options and text $txt = is_array($values)? json_encode($values): $values; $options = array('text_file' => $filename,'text_entry_format'=>$format ); $options['text_file_path']=$path==''?'logs': $path; JLog::addLogger ($options); /* if you want the error to show in your page. */ if($showOnTop==1){ JLog::add("$level\t$txt"); }else{ JLog::add("$level\t$txt",$level,$component); } } /**** result: 14:28:39 ::1 com_whatever ALERT task:error ****/ ?> Hope this Help
{ "language": "en", "url": "https://stackoverflow.com/questions/7586142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Axis, wsdlsoap:address location and reverse proxy I've used AXIS 1.4 to generate some webservices. These webservices will be called by clients, but their calls will go through a reverse proxy (apach with mod_proxy). The process is working fine, however in the generated wsdl (when calling http://proxy/services/ServiceName?wsdl) axis generates the following block: <wsdl:service name="MyService"> <wsdl:port binding="impl:MyServicePortSoapBinding" name="MyServicePort"> <wsdlsoap:address location="http://internalserver:8080/myapp/services/ServiceName"/> </wsdl:port> </wsdl:service> The wsdlsoap:address still points to the internal, behind the firewall server - not the reverse proxy one. Although it does not seem to be a problem for my test clients at this stage, I'm wary of letting such information (servername, etc) public in the wsdl. I've tried adding a wsdlFile tag in the <service> configuration in the server-config.wsdd file, pointing to a manually updated WSDL, without success (it keeps displaying the previous information).
{ "language": "en", "url": "https://stackoverflow.com/questions/7586146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I add an object to an array in Objective-C? I am starting to program in Objective-C. I am using a book to learn the first basics. The given example is not working! I can not see the problem in my code. It was not so hard to understand it, but it just won't work. But everything I found elsewhere, they added Objects like I did. I don't know if the syntax changed? I am using the iOS 4.3 SDK and Xcode 3.2.6!? This part fails: [questions addObject: @”What is 7 + 7?”]; //FAILS [answers addObject: @”14”]; The error message says: /Applications/Quiz/Classes/QuizAppDelegate.m:32:0 Applications/Quiz/Classes/QuizAppDelegate.m:32: error: expected expression before '@' token I would be really happy, if someone can help me! Thank you! I attached the code as well! Jules Full code: .h: #import <UIKit/UIKit.h> @interface QuizAppDelegate : NSObject <UIApplicationDelegate> { int currentQuestionIndex; //The model objects NSMutableArray *questions; NSMutableArray *answers; //The view objects IBOutlet UILabel *questionField; IBOutlet UILabel *answerField; UIWindow *window; } @property (nonatomic, retain) IBOutlet UIWindow *window; -(IBAction)showQuestion:(id)sender; -(IBAction)showAnswer:(id)sender; @end Part code where it fails: .m: #import "QuizAppDelegate.h" @implementation QuizAppDelegate @synthesize window; -(id)init{ // Call the init method implemented by the superclass [super init]; // Create two arrays and make the pointers point to them questions = [[NSMutableArray alloc] init]; answers = [[NSMutableArray alloc] init]; // Add questions and answers to the arrays [questions addObject: @”What is 7 + 7?”]; //FAILS [answers addObject: @”14”]; [questions addObject: @”Was ist die Hauptstadt von Madagaskar?”]; //FAILS [answers addObject: @”Antananarivo”]; [questions addObject: @”Was ergibt 5-2*2+6?”]; //FAILS [answers addObject: @”7”]; // Return the address of the new object return self; } -(IBAction)showQuestion:(id)sender{ //Step to the next question currentQuestionIndex++; //Am I past the last question? if(currentQuestionIndex==[questions count]){ //Go back to the first question currentQuestionIndex=0; } // Get the string at that index in the questions array NSString *question = [questions objectAtIndex:currentQuestionIndex]; //Log the string to the console NSLog(@"displaying question:%@",question); //Display the string in the question field [questionField setText:question]; //Clear the answer field [answerField setText:@"???"]; } -(IBAction)showAnswer:(id)sender{ //What is the answer to the current question NSString *answer=[answers objectAtIndex:currentQuestionIndex]; //Display it in the answer field [answerField setText:answer]; } A: I think, you are using the false character for the double quote ", as yours is ”. Did you copy and paste the code from somewhere? A: Or even shorter: [myArray addObject:[NSString stringWithString:@"Wie hoch ist der Eiffelturm?"]];
{ "language": "en", "url": "https://stackoverflow.com/questions/7586152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Suppress the virtual touch screen Windows keyboard in a WPF full screen application We have a full screen application developed in WPF that will be used on a touch interface. As part of this project I developed a styled virtual keyboard that will be used to input when the application is run on a touch device. Everything works great except for the appearance of the Windows Virtual Keyboard input icon appearing when a user clicks on a textbox (for instance). What we would like to do is to suppress the Windows keyboard from activating when the user grabs focus on "specific" input controls. We may still want the keyboard on other input areas such as open or file save dialogs so disabling the keyboard for the application or globally is not an option. I have found documentation on MSDN that suggests a possible solution would be to use TextInputPanel from the Microsoft.Ink namespace. However, that last version of that code is 3.5 (this is a 4.0 app) and I cant seem to find the dll anywhere it should be. Any suggestions at this point would be greatly appreciated... A: You simply disable it in the corresponding menu: Start button > Control Panel > classic view > Ease of Access > click Use the computer without a mouse or keyboard > UN-check Use ON-screen Keyboard > Save http://answers.microsoft.com/en-us/windows/forum/windows_vista-desktop/is-there-a-way-to-turn-off-the-on-screen-keyboard/ce752b42-f8a5-4693-957c-c7acef0d80b3
{ "language": "en", "url": "https://stackoverflow.com/questions/7586153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Web service over SSL in Grails-cxf? I need to serve a specific CXF web service over HTTPS (I have several others that need to work over plain HTTP). In SecurityConfig.groovy, I set: httpsPort = 8443 and tried both of secureChannelDefinitionSource = ''' CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON PATTERN_TYPE_APACHE_ANT /services/doodah/**=REQUIRES_SECURE_CHANNEL /**=REQUIRES_INSECURE_CHANNEL ''' and channelConfig = [ secure: ['/services/productid/**'], insecure: '/' ] The service stops responding to http protocol at 8080, but doesn't appear to be on https:8443 - at least, telnet connection to 8443 fails. If I run the app with grails run-app -https, all the application works over https. To separate http from https services, I'll probably need to do this: "Automatic http/httpS switching with Grails", but for now I'd like at least to get different services running on two different ports. * *What steps should I follow to have one service working over HTTPS only? *Looks like there is something else SSL need to work in war, like in this quesion: SSL, Tomcat and Grails? My environment is: Grails 1.3.5, acegi-security 0.5.3 (I know it's outdated), Tomcat 6. A: Please correct me if I'm wrong. Both options in SecurityConfig.groovy do work. In a standalone Tomcat, there's no way to programmatically enable SSL Connector, one has to enable it in global server configuration (server.xml): SSL, Tomcat and Grails. For run-app, I added scripts/_Events.groovy with a eventConfigureTomcat hook and copied a piece of TomcatServer.groovy in Tomcat plugin: eventConfigureTomcat = { Tomcat tomcat -> keystore = "./some-keystore" keystoreFile = new File(keystore) keyPassword = "123456" System.setProperty('org.mortbay.xml.XmlParser.NotValidating', 'true') if (!(keystoreFile.exists())) { createSSLCertificate(keystore, keyPassword, keystoreFile) } def httpsPort = 8443 // TODO: Take from SecurityConfig.groovy Connector sslConnector = loadInstance( tomcat, 'org.apache.catalina.connector.Connector') sslConnector.scheme = "https" sslConnector.secure = true sslConnector.port = httpsPort sslConnector.setProperty("SSLEnabled", "true") sslConnector.setAttribute("keystore", keystore) sslConnector.setAttribute("keystorePass", keyPassword) sslConnector.URIEncoding = 'UTF-8' tomcat.service.addConnector sslConnector } I don't have to do protocol switch trick, Grails correctly redirects between http and https for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586154", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jqgrid width size problem in usercontrol I have a jqgrid in the third tab of a jquery ui tab, the grid is visible but the size is much smaller than its usual size. I dont have this problem when I move the grid to the first tab. I read and know that the hidden tabs are not reflecting the width and have seen some similar issues like this one: jqgrid and jquery tabs : loading text doesn't hide I would like to load my grid when the third tab is clicked in the select event of the tabs so the jqgrid is loaded with its original size. This is my code in the usercontrol page that includes the tabs. I should also add that each tab has its own .ascx page (I dont know if this makes a difference). $(document).ready(function () { $("#tabstest").tabs({ "select": function (event, ui) { switch (ui.index) { case 2: alert(" this is the test cases "); $("#list")[0].grid.hDiv.reloadGrid; $("#list")[0].grid.reloadGrid; break; } } }); }); <div id="tabstest"> <ul> <li><a href="#tabs-1">first</a></li> <li><a href="#tabs-2">second</a></li> <li><a href="#tabs-3">Third </a></li> </ul> <div id="tabs-1"> <% Html.RenderPartial("First", ViewData); %> </div> <div id="tabs-2"> <% Html.RenderPartial("second"); %> </div> <div id="tabs-3"> <% Html.RenderPartial("Third"); %> </div> </div> It is not loading my grid correctly, but the alert string shows so I am sure I enter this select event. Has anyone had this experience before? Any other tips will be appreciated. Thanks A: Not sure what those methods in your case are trying to do exactly (as Oleg asked) but you could always just adjust the styles after the grid has loaded: $(document).ready(function () { $("#tabstest").tabs({ "select": function (event, ui) { switch (ui.index) { case 2: $('#grid').css('width', '100%'); // Something like this break; } } }); }); A: This is the answer, I hope it helps $(document).ready(function () { $("#tabstest").tabs({ "select": function (event, ui) { switch (ui.index) { case 2: $("#tabstest").tabs( "load" , 2 ) break; } } }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7586159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Customize the Error Message for an invalid date in ASP.net MVC I have an ASP.net MVC model with a date: public class EditModel { [Display(Name="DOB")] public DateTime? DateOfBirth { get; set; } } @Html.TextBoxFor(m => m.DateOfBirth) @Html.ValidationMessageFor(m => m.DateOfBirth) When the user enters an invalid date such as 9/31/2011, the error message comes back as this: The value '9/31/2011' is not valid for DOB. This is happening when it is trying to do the model binding and is not one of my validations. Is there a way to customize this error message? I would like it to be something like: Please enter a valid date for the Date of Birth. I am not requiring the user to enter the Date, but when they do enter an INVALID value then I want to customize the error. A: You can use data annotations for errors, or, in this case you can do this: @Html.ValidationMessageFor(m => m.DateOfBirth , "Please enter a valid date for the Date of Birth.") A: Try this, [DataType(DataType.Date, ErrorMessage = "Please enter a valid date.")] public System.DateTime DateOfBirth { get; set; } Hope this will help you.. :) A: public class myClass() { [Display(Name="Date of Birth"), DataType(DataType.Date, ErrorMessage = "Please enter a valid date for the Date of Birth.")] public string dateOfBirth { get; set; } } A: With me error message in datatype not work Remove it using regular [Display(Name="Date of Birth")] [RegularExpression(@"^(3[01]|[12][0-9]|0[1-9])[-/](1[0-2]|0[1-9])[-/][0-9]{4}$", ErrorMessageResourceName = "DateNotValid", ErrorMessageResourceType = typeof(Resources))] public string dateOfBirth { get; set; } DateNotValid : is using in resource file. you can change to error message if you want the format above for: dd-MM-YYYYY
{ "language": "en", "url": "https://stackoverflow.com/questions/7586163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How to tell search engines which is the main menu? I wanted to implement the following structure on my website: <h1>Site Title</h1> <ul id="menu> <li>Section 1</li> <li>Section 2</li> <li>Section 3</li> </ul> I have several <ul> on the same page. So, I added <h1> to the <ul> which contains main menu and I was thinking that this will be easy for search engines to find the main menu. Many sources say that there should not be more than one <h1> tag on each page and <h1> must be different on each page. If it's true, how can I tell to search engines that the main menu is located inside of <ul id="menu> and not inside of some another <ul>? I just checked my website in Google and it shows 6 links below the title which look like section names but they are not. Thanks. A: it is right every page must have only one h1 and you may use h2 h3 and arrange your data for search engine all links will be followed and archived in search engine by default except if you tell other by your robot meta tag in every page and not only the main one you may submit sitemap xml in your website and search engine will submit all your pages. my advice is to think in search engines in every page with it's content not the whole website, search engines archive and rank website pages, so the good pages friendly to search engine will appear in first results in searching about a content in this pages. My Regards
{ "language": "en", "url": "https://stackoverflow.com/questions/7586165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Add A Gallery - Android How can I dynamically add a gallery to an android app, I have: Gallery gallery = new Gallery(this); But it doesnt work. A: set the Layout parameters of gallery, ie size then take a Layout and add into it LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30); gallery.setLayoutParams(layoutParams); LinearLayout mLinearLayout=(LinearLayout) findViewByID(R.id....); mLinearLayout.addView(gallery);
{ "language": "en", "url": "https://stackoverflow.com/questions/7586167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: c# Using setting dynamic expression dynamically? I'm new to the dynamic keyword and been researching it quite a bit, for I want to use it to parse xml. I came across this example I'm using as my test: http://blogs.captechconsulting.com/blog/kevin-hazzard/fluent-xml-parsing-using-cs-dynamic-type-part-1 In the example, they show: dx.book[2].authors.author[0].name.last.Value, I want to know if it's possible somehow to build a dynamic expression from a string or database value? psuedo example: dynamic dx = new DynamicXml(xml); Console.WriteLine("dx.book[2].authors.author[0].name.last.Value"); I looked into an EVAL to do something like this, or looking into reflection somehow, but curious if there is a better way. Any advice or help, or a simple no would be greatly appreciated. A: InvokeGetChain takes a string of properties and dynamically invokes them. It is more of a reflection style way of doing it (though easier and faster than reflection and works with dynamic objects. It's in the ImpromptuInterface open source project (via nuget). As of v6.0 it does parse indexers, in the exact format above, excluding the target object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Google Analytics - Tracking metrics for webpage content using the Data Export API I'm trying to write a program that will create a report of the page views within a date range for specific webpages within my site. I've been scouring the API help section, but i can't seem to find out how to get metrics for a specific page. I think it has something with defining a specific tableID, but I've been unable to find that number. Any help is appreciated. Thanks. A: new version: you can take the tableId from the query, is the number after the "p": for example the : 14725836 www.google.com/analytics/web/#dashboard/xxxxxxxxxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxxxxxp14725836/%3F_.date00%3D20111228%26_.date01%3D20111228/ old version is the param "id" www.google.com/analytics/reporting/?reset=1&id=14725836&pdr=20111127-20111227
{ "language": "en", "url": "https://stackoverflow.com/questions/7586170", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: getting NullPointerException in getApplicationContext() I am getting a Nullpointer exception when I open my app and this was on the background. My onResume calls an Asyntask which calls this method: public boolean reloadIni() throws NetworkConnetionException { if(mMyApp == null)//chek if the object has been deleted by the gc. { Log.d(TAG,"task mMyApp is null, initialize mMyApp"); mMyApp = (MyApp) getApplicationContext(); } User userLogin = mMyApp.getUserLogin(); //....more stuff } But as you can see I am cheking if my variable mMyApp is != null. Is it possible that getApplicationContext() returns null?
{ "language": "en", "url": "https://stackoverflow.com/questions/7586172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: IOUtilities.streamToBytes get Hanged in Blackberry When I try to get the data from IOUtilities.streamToBytes() it hangs. Has anyone else faced this sort of issue while trying to read data?
{ "language": "en", "url": "https://stackoverflow.com/questions/7586183", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Qt::Drawer type window signal on User-driven close Is there a signal being emitted when a user drags a Qt::Drawer type window (OSX specific) enough to close it? I need to capture that in my app so that I can trigger my "open" button again. A: Is your drawer widget getting a close event? If so, then you can key off that (by emitting a custom signal or otherwise). A: Probably it is emitting a QDragEnterEvent
{ "language": "en", "url": "https://stackoverflow.com/questions/7586184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: scala.tools.nsc.interpreter memory leak I need to implement a DSL (Domain Specific Language) using Scala, and this DSL will be interpreted in a Scala interpreter (scala.tools.nsc.interpreter). The problem is that the memory used by the interpreter keeps increasing until an outOfMemory exception is thrown. I cannot reinitialize the interpreter each time I have a line of DSL to execute, as the interpreter takes a while to load. I cannot just call reset(), as I need to keep track of some data in the execution environment of the interpreter. Memory leak will happen even I do the following: while (true) { interpreter.interpret("println(4 + 5)") } After a while, I'll get: Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at ch.epfl.lamp.util.ByteArray.<init>(ByteArray.java:24) at ch.epfl.lamp.fjbg.JCode.<init>(JCode.java:47) at ch.epfl.lamp.fjbg.JExtendedCode.<init>(JExtendedCode.java:113) at ch.epfl.lamp.fjbg.FJBGContext.JCode(FJBGContext.java:122) at ch.epfl.lamp.fjbg.JMethod.<init>(JMethod.java:52) at ch.epfl.lamp.fjbg.FJBGContext.JMethod(FJBGContext.java:87) at ch.epfl.lamp.fjbg.JClass.addNewMethod(JClass.java:246) at scala.tools.nsc.backend.jvm.GenJVM$BytecodeGenerator.genMethod(GenJVM.scala:755) at scala.tools.nsc.backend.jvm.GenJVM$BytecodeGenerator$$anonfun$genClass$7.apply(GenJVM.scala:307) at scala.tools.nsc.backend.jvm.GenJVM$BytecodeGenerator$$anonfun$genClass$7.apply(GenJVM.scala:307) at scala.collection.LinearSeqOptimized$class.foreach(LinearSeqOptimized.scala:59) at scala.collection.immutable.List.foreach(List.scala:45) at scala.tools.nsc.backend.jvm.GenJVM$BytecodeGenerator.genClass(GenJVM.scala:307) at scala.tools.nsc.backend.jvm.GenJVM$JvmPhase$$anonfun$run$4.apply(GenJVM.scala:86) at scala.tools.nsc.backend.jvm.GenJVM$JvmPhase$$anonfun$run$4.apply(GenJVM.scala:86) at scala.collection.mutable.HashMap$$anon$2$$anonfun$foreach$3.apply(HashMap.scala:102) at scala.collection.mutable.HashMap$$anon$2$$anonfun$foreach$3.apply(HashMap.scala:102) at scala.collection.Iterator$class.foreach(Iterator.scala:660) at scala.collection.mutable.HashTable$$anon$1.foreach(HashTable.scala:157) at scala.collection.mutable.HashTable$class.foreachEntry(HashTable.scala:190) at scala.collection.mutable.HashMap.foreachEntry(HashMap.scala:43) at scala.collection.mutable.HashMap$$anon$2.foreach(HashMap.scala:102) at scala.tools.nsc.backend.jvm.GenJVM$JvmPhase.run(GenJVM.scala:86) at scala.tools.nsc.Global$Run.compileSources(Global.scala:953) at scala.tools.nsc.interpreter.IMain$ReadEvalPrint.compileAndSaveRun(IMain.scala:756) at scala.tools.nsc.interpreter.IMain$ReadEvalPrint.compile(IMain.scala:731) at scala.tools.nsc.interpreter.IMain$Request.compile(IMain.scala:873) at scala.tools.nsc.interpreter.IMain.interpret(IMain.scala:576) at scala.tools.nsc.interpreter.IMain.interpret(IMain.scala:543) at com.ericsson.ims_dsl.IMS_Interpreter$$anonfun$e$1.apply(IMS_Interpreter.scala:50) at com.ericsson.ims_dsl.IMS_Interpreter$$anonfun$e$1.apply(IMS_Interpreter.scala:50) at scala.tools.nsc.interpreter.IMain.beQuietDuring(IMain.scala:200) Could someone please help me solve this issue? A: Every time you call the interpret method, the request is stored. Therefore if you try to call an infinite number of time this method, you should run into trouble. So it's not really a bug. You can increase the number of possible iterations before crash by increasing the JVM maximum heap size... You may want to count the number of possible calls to check if it meets your goal.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Stopping a Vimeo Video on close of jQuery Modal Thanks in advance for your help. Let me preface this by saying that I am mainly an HTML/CSS guy so please try and be as clear as possible in your responses to anything requiring javascript implementation. I have a Vimeo video loading in a modal box on my page at: http://sparkexperience.com/projects/nma/ However, in Safari and IE, on close of the window, the video continues to play. I had seen another thread similar to this on this site but still can't seem to figure it out: How to stop a Vimeo video with JQuery I basically copied all of the javascript code out exactly as is from the Vimeo Javascript API playground and still am having no luck (Playground link: http://player.vimeo.com/playground) A: copy this script in the footer of your page (default CSS selectors coming with Foundation) <script type="text/javascript"> jQuery(document).ready(function($) { $('body').live('click',function(){ if($('div.reveal-modal-bg').is(':visible')){ var resourceVideo = $('#myModal iframe').attr('src'); $('#myModal iframe').attr('src','').attr('src',resourceVideo); }; }) }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7586195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: EmbossMaskFilter strange effect on other drawings I've tried to use EmbossMaskFilter to create custom Drawable. However I've come across strange behaviour, that when I try to use Emboss it's causing black stripes on edges of other 2d-graphics objects that overlaps with "embossed" drawble bounds. Am I missing something? maybe some ~pixel blend setting or what? Example: black stripes on ScrollView "fadings". When I remove Emboss mask they are gone. Also when I've made ImageButton with background drawable using Emboss and front drawable as canvas drawing, this front drawable gets stripes too. Activity (+main.xml = LinearLayout in ScrollView = http://pastebin.com/031AV6Wp): public class TestEmbossActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Paint paint = new Paint(); paint.setColor(Color.RED); paint.setMaskFilter(new BlurMaskFilter(15, Blur.INNER)); paint.setMaskFilter(new EmbossMaskFilter(new float[] { 1, 1, 1 }, 0.4f, 5, 3f)); ViewGroup container = (ViewGroup) findViewById(R.id.container); for(int i = 0; i < 20; i++) { ImageView view = new ImageView(this); view.setScaleType(ScaleType.FIT_XY); Drawable drawable = new MyDrawable(paint); view.setImageDrawable(drawable); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(100, 100); params.bottomMargin = 10; container.addView(view, params); } } private static class MyDrawable extends Drawable { Paint paint; private MyDrawable(Paint paint) { this.paint = paint; } @Override public void draw(Canvas canvas) { Rect bounds = getBounds(); canvas.drawRect(bounds, paint); } @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } @Override public void setAlpha(int alpha) { // TODO Auto-generated method stub } @Override public void setColorFilter(ColorFilter cf) { // TODO Auto-generated method stub } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7586196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to determine minimum supported version of third party executables Putting together a collection of Bash scripts that will be released to a wider audience of users with expectation of various operating systems and software versions. The scripts themselves rely on software like mysqldump and getopt. Being a good citizen, I would like to figure out what is the minimum version required by my script of each of the third party programs I'm using, bash included. Short from installing distros of an old OS somewhere and testing this randomly, can anyone offer any advice on what would be the best approach for determining these version requirements? Software involved: bash, mysql, mysqldump, getopt, bzip2 (My guess would be that the true version requirement is 'any', but of course can't be sure...) A: You might look at the changelogs of the programs in question, but that would be quite tiresome. The pbuilder would make testing with old distributions much easier. It sets up a chroot-ed environment for a debian-compatible distribution. Set up a sh script testing your scripts, run it in a pbuilder environment for an old distribution, and see how old you can get. All in all, given an sh file, this test boils down to ~10 lines of additional sh code for the pbuilder test. If you can run on the current oldstable distribution of Debian, you're most probably sufficiently compatible. A: Although some projects use roughly systematic numbering schemes, there is no universal way to look at an arbitrary version number and determine compatibility. You have to investigate each case individually. Package managers (like apt) list dependencies in their package files. This lists the version requirements one program makes of another.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Input Integers in MIPS Assembly I am writing a program in MIPS that will read in signed integers from the keyboard. Is there a way to read input like that, the way we do in higher level languages from a console? If not, I already have an array as follows: .data intdata: .word 3, 23, -5, 57, -12, 41, 39, -43, 40, 30 # input of integers Can I operate on the array without knowing its length? So loop until at the end of the array. Or should I put another argument which holds the length of the array? A: This is assembly, you don't have such high level functions. Most simulators do, however, offer some functionality to read/write through I/O. This is done through syscalls. You should read the simulator's documentation, or tell us what simulator you're using (if using any). You can't operate with an array without knowing its length. You say "loop until the end of the array", but what's the end of the array? How would you know when programming? You have two basic solutions for this: either use another variable that holds array length or you use an end of array marker (a value that will let you know when the array has ended).
{ "language": "en", "url": "https://stackoverflow.com/questions/7586201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I simulate a very slow computing environment? Is there some emulator out there where I can program in some language (C, C++, Assembly etc.) and where I can slow down the Hz rate (down to 1MHz or something) I've been very curious how difficult it is to program with such a limitation and wondering if there is a software solution to this before I go out to buy a chip.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586208", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: XML drawable Bitmap tileMode bug? I'm having issues where my drawable resource uses the tileMode repeat. In some cases the image is just stretched and sometimes it is properly repeated. The following are the xml files I use to create the button states: Image drawable used for tile repeated ^^^^^^^^^^^^^ btn_menu_item.xml <selector xmlns:android="http://schemas.android.com/apk/res/android" android:constantSize="true" android:visible="true" android:variablePadding="true"> <!-- selected --> <item android:state_selected="true" android:drawable="@drawable/menu_item_selected"/> <!-- focused --> <item android:state_focused="true" android:drawable="@drawable/menu_item_pressed"/> <!-- pressed --> <item android:state_pressed="true" android:drawable="@drawable/menu_item_pressed"/> <!-- normal --> <item android:state_pressed="false" android:state_focused="false" android:drawable="@drawable/menu_item_normal"/> </selector> menu_item_normal.xml <layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <item android:state_selected="true"> <shape android:shape="rectangle"> <gradient android:startColor="#757575" android:endColor="#929292" android:angle="90"/> </shape> </item> <item> <bitmap android:src="@drawable/menu_lines_texture" android:tileMode="repeat" android:dither="true"/> </item> </layer-list> menu_item_pressed.xml <layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <item android:state_selected="true"> <shape android:shape="rectangle"> <gradient android:startColor="#dd4e00" android:endColor="#c64600" android:angle="90"/> </shape> </item> <item> <bitmap android:src="@drawable/menu_lines_texture" android:tileMode="repeat" android:dither="true"/> </item> </layer-list> Please see the images below of what exactly I'm talking about. A: This is a known bug, partially fixed in Android 3.0 and completely fixed in ICS. A: We were having a similar problem writing for 3.2 on Sony's Google TV device. We noticed some very similar background-striping stemming from using android:tileMode="repeat" on a bitmap as a background image. In this case, the fix was to turn off hardware acceleration on the view that contained the bitmap like so (from a function in our Activity): View tile_holder = this.findViewById(R.id.tile_holder); tile_holder.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
{ "language": "en", "url": "https://stackoverflow.com/questions/7586209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: What's the best way to filter/validate ID's in a '#show' action? So, this is really a Rails pattern question. I have a Rails 3.0.9 application that works, and well. We're using Airbrake to detect and report errors, and that's helped tune the last few leaks in the program design. Only, now it gets attacked by robots (Google, crawlers, etc) with bad input. ActiveRecord::StatementInvalid: PGError: ERROR: invalid input syntax for integer: "google_ads_dbg" LINE 1: ....message_thread_id WHERE "message_threads"."id" = 'google_ad... ^ : SELECT "message_threads".* FROM "message_threads" INNER JOIN "message_thread_users" ON "message_threads".id = "message_thread_users".message_thread_id WHERE "message_threads"."id" = 'google_ads_dbg' AND (("message_thread_users".user_id = 33899)) LIMIT 1 The restful routes: resource :inbox do resources :messages end The first line of the MessagesController#show @message_thread = current_user.message_threads.find(params[:id]) Do I prefix every .find params[:id] call to validate the integer-ness of the input? Do I tack-on :constraints => {:id => /[0-9]+/} to every resource line in my routes.rb ? A: You can supply the constraints for multiple resources at once. scope :constraints => { :id => /\d+/ } do resources :inbox do resources :messages end end This makes most sense to me. You could validate the integer in before-filters in your controllers, but I think that's a messy alternative given your situation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Ant - replace string I am looking for possible solution,how to replace specific String in my Android.manifest Currently I am using task: <replaceregexp flags="g" byline="false"> <regexp pattern="&quot;com.package.Something&quot;"/> <substitution expression="&quot;com.package.Extra.Something&quot;"/> <fileset dir="" includes="AndroidManifest.xml"/> </replaceregexp> All I need is to change every occurence of com.package to com.package.Extra, nevertheless what is before or after this statement. Up to now, this task replace occurence of com.package.Something by com.package.Extra.Something, but if I have in my manifest statement com.package (= without Sometning), is is not transfered. How to do that in code, that I want dynamically change only specified string and nothing more? It should by something like "If there is com.package, use com.package.Something instead and leave everything around exactly as it was before" Hope you understand Thanks A: Solution - use task < replace > as: <replace file="AndroidManifest.xml" token="com.package" value="com.package.Extra"/> com.package is replaced by com.package.Extra
{ "language": "en", "url": "https://stackoverflow.com/questions/7586216", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Program not entering if statement In my python program, an if statement is not being entered. I have simplified the code to the following: x = -5 while x < 5: if (x == 0): print 0 x += .01 This program does not output anything. However, changing the last line to x += .5 makes the program output 0. What's the problem? A: Floating point number representation might not be accurate enough. You should never test for zero equality but instead use something along if (abs(x) < 1E-10) ... A: Behold the power of the print statement... Let us insert a print statement... x = -5 while x < 5: if (x == 0): print 0 x += .01 print x Running this program, and inspecting the output around 0 reveals the problem: ... -0.13 -0.12 -0.11 -0.1 -0.0900000000001 -0.0800000000001 -0.0700000000001 -0.0600000000001 -0.0500000000001 -0.0400000000001 -0.0300000000001 -0.0200000000001 -0.0100000000001 -6.23077978101e-14 0.00999999999994 0.0199999999999 0.0299999999999 0.0399999999999 0.0499999999999 0.0599999999999 0.0699999999999 0.0799999999999 0.0899999999999 0.0999999999999 0.11 0.12 0.13 ... Oh boy, it is never actually equal to zero! Solutions: * *Use integers. Most reliable. x = -500 # times this by a 100 to make it an integer-based program while x < 500: if (x == 0): print 0 x += 1 *Never test equality with floating point arithmetic, but rather use a range: delta = 0.00001 #how close do you need to get point = 0 #point we are interested in if (point-delta) <= x <= (point+delta): # do stuff A: This is a rounding issue - decimal values cannot be represented exactly in binary, so x never exactly equals 0.0000000000.... try replacing if (x == 0): with if -0.001 < x < 0.001: BTW, the parentheses are unnecessary in a python if statement. edit: Printing out the values between -1 and 1 in steps of 0.01 shows this is the case - where zero should be it prints 7.52869988574e-16. A: Others have pointed out the issue with floating-point numbers being unable to represent values exactly. If you need exact decimal representation of a number, you can use the Decimal class: from decimal import Decimal x = Decimal(-5) while x < 5: if (x == 0): print 0 x += Decimal(".01") This will print 0 as you expect. Note the use of a string for the increment. If you used Decimal(.01) you'd have the same problem with accurate representation of 0.01, because you're converting from a floating-point number and have already lost the accuracy, so the class doesn't allow that. A: In binary, .01 has no exact representation but .5 does. It's the same problem you'd have in decimal if you represented 1/3 as .333333 and kept adding 1/3 until you reached 1. After three additions, you'd have .999999 which is not exactly equal to 1. Don't compare non-integers for equality unless you precisely understand the rules for doing so and are 100% sure your case is one of the ones that will work. A: -0.01 7.52869988574e-16 0.01 I suggest you say x > -.001 and x < .001 or something of the sort A: To be precise to your query, floating point numbers are stored in computer hardware in binary(base 2) fractions. So even if you store some floating point like 0.01 in a variable, the computer would ultimately convert that into it's equivalent binary value. For your convenience, conversion of 0.01 float to binary: 0.01 * 2 = 0.02 [0] 0.02 * 2 = 0.04 [0] 0.04 * 2 = 0.08 [0] 0.08 * 2 = 0.16 [0] 0.16 * 2 = 0.32 [0] 0.32 * 2 = 0.64 [0] 0.64 * 2 = 1.28 [0] 0.28 * 2 = 0.56 [0] 0.56 * 2 = 1.12 [1] ... This calculation would be too lengthy to show here in full and probably won't end at all. But the fact i want to state here is that, most fractional decimals cannot be exactly converted into binary fractions. As a result, the decimal point you store will be approximated by the binary floating fractions stored in the machine(which obviously can't store very very long binary value). So when the calculation is done with that value, you certainly shouldn't expect the accurate floating value. That's the case with putting x += 0.01 in your code. However conversion of 0.5 to it's binary equivalent would give: 0.5 * 2 = 1.0 [1] So binary equivalent of 0.5 float is 0.1. Since it is perfectly represented in binary in your machine. You would get the exact result. It has nothing to do with your code or python. It's just the way computer hardware works :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7586221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Attaching a .avi file to an email I'm trying to attach a video clip (.avi) to an email. Is there any way to do this within the .NET Framework 4.0? My logic is that I need to open up that avi in some sort of file stream then attach that stream to the email and send it off. The part that I am struggling with is the getting the stream from the file. A: Try this, standard way to add attachments in .NET MailMessage nMsg = new MailMessage(); nMsg.From = new MailAddress(fromAddress); nMsg.Subject = subject; Attachment attachFile = new Attachment("Your file path here"); nMsg.Attachments.Add(attachFile); SmtpClient mailer = new SmtpClient("yousmtpserver"); mailer.Send(nMsg);
{ "language": "en", "url": "https://stackoverflow.com/questions/7586225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I allow a ruby script (program ?) to access the internet through an http proxy? I was trying to install the blogger plugin for vim . According to the instructions , after installation and configuration, I should be able to write something like this : e blogger:list and I will see the list of the blog posts I have published. However I get the following error : /usr/lib/ruby/1.8/net/http.rb:560:in initialize': Connection refused - connect(2) (Errno::ECONNREFUSED) from /usr/lib/ruby/1.8/net/http.rb:560:inopen' from /usr/lib/ruby/1.8/net/http.rb:560:in connect' from /usr/lib/ruby/1.8/timeout.rb:53:intimeout' from /usr/lib/ruby/1.8/timeout.rb:101:in timeout' from /usr/lib/ruby/1.8/net/http.rb:560:inconnect' from /usr/lib/ruby/1.8/net/http.rb:553:in do_start' from /usr/lib/ruby/1.8/net/http.rb:542:instart' from /usr/lib/ruby/1.8/net/http.rb:379:in get_response' from /usr/lib/ruby/1.8/net/http.rb:356:inget' from /home/messi/.vim/autoload/metarw/blogger.rb:217:in __pagen from /home/messi/.vim/autoload/metarw/blogger.rb:130:inlist' from /home/messi/.vim/autoload/metarw/blogger.rb:329 I am behind an HTTP proxy. So I am guessing that is why I am getting these errors. I don't want to have to change the ruby scripts to make them work with the proxy settings. I tried setting environment variable HTTP_PROXY to the correct value to get it to work, but to no avail. A: That SW does not seem to contain code for dealing with proxies. I fear you have to change blogger.rb. See ruby-doc.org, you have to replace Net::HTTP.get by Net::HTTP::Proxy(proxy_addr, proxy_port).get and so on. Maybe it is possible to achieve this centrally by some monkey-patching.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WCF File Streaming 400 Bad Request So I have reviewed a large number of the same issue being reported, and for some reason I cannot get a working version on my end, even using the existing solutions to these questions. Could someone shed some light on what I am overlooking? It almost has to be related to the file upload size problem above 64k as I see the error almost instantly as soon as I attempt to pass a file above that size. Here is the web.config of my WCF Service <?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <customErrors mode="Off" /> <compilation debug="true" targetFramework="4.0"> <assemblies> <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> </assemblies> </compilation> <webServices> <protocols> <add name="HttpGet" /> <add name="HttpPost" /> </protocols> </webServices> <sessionState timeout="60" /> <httpRuntime maxRequestLength="2097151" useFullyQualifiedRedirectUrl="true" executionTimeout="14400"/> </system.web> <system.webServer> <modules runAllManagedModulesForAllRequests="true" /> </system.webServer> <system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/> <bindings> <basicHttpBinding> <binding name="FileManager" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" transferMode="Streamed"> <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/> <security mode="None"/> </binding> </basicHttpBinding> </bindings> <services> <service behaviorConfiguration="FileManagerBehavior" name="PrimeWebServices.FileManager"> <endpoint address="" binding="basicHttpBinding" bindingConfiguration="FileManager" contract="PrimeWebServices.IFileManager"/> <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" /> </service> </services> <behaviors> <serviceBehaviors> <behavior name="FileManagerBehavior"> <serviceMetadata httpGetEnabled="true"/> <dataContractSerializer maxItemsInObjectGraph="2147483647"/> <serviceDebug includeExceptionDetailInFaults="true"/> <serviceThrottling maxConcurrentCalls="500" maxConcurrentSessions="500" maxConcurrentInstances="500"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration> and here is my WCF Service code behind namespace PrimeWebServices { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "FileManager" in code, svc and config file together. [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class FileManager : IFileManager { public FileManager() { HttpContext httpContext = HttpContext.Current; if (httpContext != null) { httpContext.Response.BufferOutput = false; } } public string UploadStream(Stream stream) { ... } } } Finally here is the client configuration settings (its a winforms client, using a service reference) <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <bindings> <basicHttpBinding> <binding name="BasicHttpBinding_IFileManager" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Streamed" useDefaultWebProxy="true"> <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> <security mode="None"> <transport clientCredentialType="None" proxyCredentialType="None" realm="" /> <message clientCredentialType="UserName" algorithmSuite="Default" /> </security> </binding> </basicHttpBinding> </bindings> <client> <endpoint address="http://localhost:1116/FileManager.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IFileManager" contract="PrimeWebServices.IFileManager" name="BasicHttpBinding_IFileManager" /> </client> </system.serviceModel> </configuration> application functions fine as long as the file is under the 64kB limit I see others reporting, which makes me believe that I am just not wiring something up correctly and its failing back to a default configuration setting. A: If you're using IIS, and if you have the Request Filtering module installed, there is a maxAllowedContentLength limit for requests which defaults to 28.6MB. That's what you also need to adjust. Sample config (setting the limit to 150MB): <configuration> <system.webServer> <security> <requestFiltering> <requestLimits maxAllowedContentLength="157286400" /> </requestFiltering> </security> </system.webServer> </configuration> See here for more information: http://www.iis.net/ConfigReference/system.webServer/security/requestFiltering/requestLimits A: If you use ASP.NET development server, then Streaming mode is not supported. You need to deploy the service to IIS or WCF Service application to use Streaming transfer mode. A: In the client settings, make sure the BasicHttpBinding_IFileManager matches the FileManager bindings in the service.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to handle large doctrine Collections and Associations I'm working on a project where I have to collect a lot of data from the database. I'm using Symfony2 (symfony bf1281aebdc842a39ec0eb7438e1ea3fca9b9705) and Doctrine2 (doctrine 3b3186ee98392802a44118cd421a3530119aa7eaand ) as working base. The Problem I encounter is, that I have to fetch about 15.000 articles. After that, I need to iterate through all of them an fetch more data on base of the article id (there are direct and indirect associations with i.e. (inherited) media or prices, etc...). It's ok for about 50-100 records, but if I want to use more records it takes a lot of ram an time to fetch everything from the database. Is there a way to iterate through the data without using up all of the remaining ram? Is there a way to tell doctrine to stop using references? Thank you in advance for any help! A: save another line by using: $iterableResult = $doctrine->getManager()->createQuery("SELECT c FROM ENTITY c")->iterate(); while ((list($obj) = $iterableResult->next()) !== false) { // do something with $obj $em->detach($obj); } A: You can look into using iterative (step-by-step) hydration in Doctrine: $em = $this->getDoctrine()->getEntityManager(); $q = $em->createQuery("<DQL to select the objects I want>"); $iterableResult = $q->iterate(); while (($row = $iterableResult->next()) !== false) { // do stuff with the data in the row, $row[0] is always the object $em->detach($row[0]); // detach from Doctrine, so that it can be GC'd immediately } Details from this article, under Mass object processing A: Hard to answer without more specifics about what you're trying to do, exactly. Doctrine generally isn't a good fit for major data-crunching like you might be describing. I have several projects that fall-back on just using DBAL to run raw SQL for things like complicated reports. That said, if you don't actually need all 15k records loaded at once, then don't load them at once! Grab 50, process them, free memory, and repeat. This approach can keep totals as you go, so it's possible to get some aggregate statistics for the whole set. That said, if you're needing aggregate stuff, you're probably building some kind of "report", and you might well be better off using pure SQL, or even some stored procedures, and don't let the ORM get involved. A: There is actually another way, but you will not like it. You can use pure mysql :) When I tried to get 450k objects from database using getRepository("..")->findAll() - it taked hours until I closed script :). So I used code like $c = $doctrine->getConnection(); mysql_connect($c->getParams()['host'],$c->getParams()['user'],$c->getParams()['password']);//$link = mysql_select_db($c->getParams()['dbname']); $qid = mysql_query("SELECT id FROM TABLENAME"); while($i = mysql_fetch_row($qid)) { $object = $doctrine->getRepository("...")->find($i[0]); I got first object after 1.7 seconds, which is absolutely acceptable for me. Except messy code :( After googling a bit I located you question and doctrine manuall. After rewriting I got code $iterableResult = $doctrine->getManager()->createQuery("SELECT c FROM ENTITY c")->iterate(); while (($row = $iterableResult->next()) !== false) { $object = $row[0]; } Code above provided first item in 2.4 seconds, which is extremely fast, as for the doctrine2 and 450k items in table. My point is - doctrine2 already have almost anything you need for "real-life" usage, but you still can simplify your life with old school ugly code :) UPDATE: Dont forget to cascade detach all loaded entities. And in symfony2 you also need to disable SQL logging by running code $doctrine->getConnection()->getConfiguration()->setSQLLogger(null); A: From doctrine documentation: $batchSize = 20; $i = 0; $q = $em->createQuery('select u from MyProject\Model\User u'); $iterableResult = $q->iterate(); foreach ($iterableResult as $row) { $user = $row[0]; $user->increaseCredit(); $user->calculateNewBonuses(); if (($i % $batchSize) === 0) { $em->flush(); // Executes all updates. $em->clear(); // Detaches all objects from Doctrine! } ++$i; } $em->flush();
{ "language": "en", "url": "https://stackoverflow.com/questions/7586246", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: JAVA; When The string from the file is printed on screen null is also printed along with it at the end Soo my program is working...but there is just one problem...null is also being printed along with the content or string from the file... is there anyway i can stop null from being printed. The code read asks a user to give a filename .txt then the user is asked a the character he/she wold like to be searched and the program searches for the that specified character in the string , prints out the content of the text file and tells how many times it was found. The problem is after it prints out the contents of the text file (string) it also prints oout the word null but null is not in the txt file. import java.util.Scanner; import java.io.*; public class filefinder { public static void main(String[] args) throws IOException { //needed for scanner class Scanner kb = new Scanner(System.in); int charCount = 0; String filename = ""; String str = ""; String line = ""; boolean isString = false; boolean fileFound = false; FileReader freader; // get users string while (!fileFound) { while (!isString) { try { Thread.currentThread().sleep(500); } catch ( Exception e ) { } System.out.println("Please enter a filename: "); System.out.println(""); filename = kb.nextLine(); if (filename != null) isString = true; }//end inner while loop // open file try { freader = new FileReader(filename); fileFound = true; Thread.currentThread().sleep(1500); } catch (Exception e) { System.out.println(""); System.out.println("The system cannot find the file specified."); System.out.println(""); isString = false; }//end try-catch }//end outer while loop try { Thread.currentThread().sleep(1000); } catch ( Exception e ) { } freader = new FileReader(filename); BufferedReader inputFile = new BufferedReader(freader); // Read first line from file while (line !=null) { line = inputFile.readLine(); if (line != null) try { Thread.currentThread().sleep(1000); } catch ( Exception e ) { } str = str+ "\n" + line; }//end while System.out.println(str); inputFile.close(); // get users character System.out.println(""); System.out.println("Please enter a character you want to find: "); System.out.println(""); char userChar = kb.nextLine().charAt(0); while(str.length()>0){ for(int i= 0;i<str.length();i++){ if(str.charAt(i)==userChar) charCount++; } System.out.println("\n The entered character " +"\"" + userChar + "\" inside " + filename + "was found " + charCount + " times.\n"); break; } } } A: This is the problem: while (line !=null) { line = inputFile.readLine(); if (line != null) try { Thread.currentThread().sleep(1000); } catch ( Exception e ) { } str = str+ "\n" + line; } It's hard to tell exactly what you think that means because the indentation is so poor, but it's equivalent to this: while (line !=null) { line = inputFile.readLine(); if (line != null) { try { Thread.currentThread().sleep(1000); } catch ( Exception e ) { } } str = str+ "\n" + line; } In other words, you're still concatenating line in the loop whether or not it's null; you're just not sleeping if it's null. I suspect you wanted it to be this: while (line !=null) { line = inputFile.readLine(); if (line != null) { try { Thread.currentThread().sleep(1000); } catch ( Exception e ) { } str = str+ "\n" + line; } } I strongly recommend that: * *You get your IDE to perform indentation for you so you can clearly see what's covered by an if block etc *You always use braces for while/if/etc, again to make things clearer *You don't catch bare Exception (catch a more specific one) *You don't swallow exceptions without logging them *You don't sleep for a second at a time for no particular reason *You don't use string concatenation in a loop (use StringBuffer/StringBuilder instead) *You break up your code into smaller methods *You declare local variables at the point of first use, rather than all at the top of the method *You close streams and other similar resources in finally blocks to avoid leaking resources in the case of an exception being thrown A: The essential loop is String str = ""; while (line != null) { line = inputFile.readLine(); str = str + "\n" + line; }// end while System.out.println(str); This will read all lines until the last one. But since the check for end-of-file (i.e. line==null) is made inside the while-criterion, also the null line will be appended to your str variable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Quartz : Memory Leak? I am using Quartz to run a job every hour. The servlet is running on Tomcat and I am using the ServletConextListener to listen for when the context is destroyed. When I shut down tomcat, I get the message: "appears to have started a thread named [MyScheduler_Worker-1] but has failed to stop it". But later I see this message: "[DEBUG] 28 Sep 11:45:26.671 AM MyScheduler_Worker-1 [org.quartz.simpl.SimpleThreadPool] WorkerThread is shut down." So is it safe to assume that there is no memory leak because of this thread? Here is how my log looks: {SEVERE: The web application [/*************] appears to have started a thread named [MyScheduler_Worker-1] but has failed to stop it. This is very likely to c reate a memory leak. Sep 28, 2011 11:45:26 AM org.apache.catalina.loader.WebappClassLoader clearRefer encesThreads SEVERE: The web application [/*************] appears to have started a thread named [MyScheduler_Worker-2] but has failed to stop it. This is very likely to c reate a memory leak. Sep 28, 2011 11:45:26 AM org.apache.catalina.loader.WebappClassLoader clearRefer encesThreads SEVERE: The web application [/*************] appears to have started a thread named [MyScheduler_Worker-3] but has failed to stop it. This is very likely to c reate a memory leak. [DEBUG] 28 Sep 11:45:26.671 AM MyScheduler_Worker-2 [org.quartz.simpl.SimpleThre adPool] WorkerThread is shut down. [DEBUG] 28 Sep 11:45:26.671 AM MyScheduler_Worker-1 [org.quartz.simpl.SimpleThre adPool] WorkerThread is shut down. [DEBUG] 28 Sep 11:45:26.671 AM MyScheduler_Worker-3 [org.quartz.simpl.SimpleThre adPool] WorkerThread is shut down. A: I know this is an old thread but in case others are looking for it. We use to get the warnings of threads all the time until we added code to shutdown the Quartz Scheduler in our ServletContextListener.shutDown() method. To shutdown the Scheduler: quartzScheduler.shutdown(); int ct = 0; // Try waiting for the scheduler to shutdown. Only wait 30 seconds. while(ct < 30) { ct++; // Sleep for a second so the quartz worker threads die. This // suppresses a warning from Tomcat during shutdown. Thread.sleep(1000); if (quartzScheduler.isShutdown()) { break; } } A: You can assume there is no memory leak because you see thread shutdown message. However, its possible to over come warning by clearing up threads before shut-down. The shutdown-hook plugin catches the event of the JVM terminating, and calls shutdown on the scheduler. Details:- http://quartz-scheduler.org/documentation/quartz-2.x/configuration/ConfigPlugins
{ "language": "en", "url": "https://stackoverflow.com/questions/7586255", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Actionscript Compiler directive I have an established pattern for lazy loading data from a server via AMF. private var _XeventDispatched:Boolean; private var _X:ArrayCollection; public function get X():ArrayCollection{ if(!_XeventDispatched && (_X==null || _X.length==0)){ var evt:Event = new Event();//whatever event is need for this data member dispatcher.dispatchEvent(evt); _XeventDispatched = true; } return _X; } public function set X(ac:ArrayCollection):void{ return _X; } This way the data is not loaded from the server until it is needed. (I'm using the Mate framework by the way, so when a UI is instanciated, and the injectors fire, they call this get method in the data manager class.) What I'd like to do is create some kind of Metadata tag, similar to [Bindable] that will add the above methods in place of a public property. [LazyLoaded(eventName="com.myCompany.LoadX")] public var X:ArrayCollection; Does the compiler have any hooks for this type of extension? It would save a lot of boiler plate code that is hard to read. A: As Flextra's has mentioned, one option is to use runtime reflection of the Metadata, and build your framework around this. That's similar to how Lazy Loading is implented in dpHibernate (a Flex Lazy Loading framework which I'm a developer on). Specifically to get access to the getters and setters and intercept them with hooks for lazy loading, we make use of the [Managed] metatag, and tweak it's behaviour, which gets the compiler to build the hooks in for you. It's a bit of a hack, but it may help you. (And we've built a pretty successful framework on top of that hack). Alternatively, you can write your own compiler extensions which use your Metadata, and performs AST modifications to generate that code for you. However, it's not for the faint-of-heart. Although the hooks for these extensions have been around for many years now, there's very little out there about how to do it, and you'd need to work it out by looking through the existing source. Luckily, the boffin's at Adobe have been eating their own dogfood with regards to the compiler extensions, and a few of the Flex 4 features (such as Skinning) has been implemented as compiler extenions, giving you a few more examples to work from. The source for the compiler is available here.. It may pay to take a look at the code for the Managed extension as a good starting point. Alternatively, take a look at the SkinPart extension, HostComponent extension or [Embed] (which Clement Wong - the original developer of the compiler - once mentioned as the best starting point in understanding compiler extensions). A: I think you want to use the keep--as3-metadata compiler argument. Something like this: keep-as3-metadata+=LazyLoaded A: +1 Marty you lead me to this, but its different from your solution. I've created a base class (BaseDataManager) that all other Mate data managers can extend from, and in that class I've added the below code: private var eventsDispatched:Array = new Array(); protected function lazyLoad(value:*, eventType:String):*{ if(!eventsDispatched[event] && (value==null || (value is IList && IList(value).length==0))){ var clazzName:String = eventType.substr(0, eventType.indexOf(":")); var eventClazz:Class = Class(getDefinitionByName(clazzName)); var event:Event = new eventClazz(eventType); dispatcher.dispatchEvent(event); eventsDispatched[event] = true; } return value; } Then within each data manager, if the property is to be lazy loaded, this is their accessors: private var _X:ArrayCollection; public function get X():ArrayCollection{ return lazyLoad(_X, XLoadEvent.LOAD_EVENT_TYPE); } public function set X(value:ArrayCollection):void{ _X = value; } This way most of the ugly, hard to read code is hidden away from the dev, yet still accessible for debugging if any problems were to arise.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }