text
stringlengths
8
267k
meta
dict
Q: Game Center Multiplayer Sandbox doesn't connect to players when invited I've got a GKMatchmakerViewController which works fine when auto-matching. But when inviting players, it doesn't work. Specifically, what happens is that the inviter is immediately connected to the invited player, but the invited player never connects to the inviter player. For the following code: [match expectedPlayerCount] [match playerIDs] The values on the inviter side are 0 and an array with the connected player's ID. The values on the other side are 0 and an empty array. What's the deal? A: Here is a great tutorial regarding GKMatchMakerViewController, which goes over how to invite other players. (This part is towards the bottom of the page.) Hope that Helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504793", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to call one function from within another function in python this may seem like a very basic question, but i have difficulty grasping it, and would appreciate any help. I want to be able to call CheckForJiraIssueRecord from verify_commit_text. here is the code: when i run it i get error: jira ticket regex matched! printing m.group(1) QA-65 my_args ... QA-65 transaction abort! rollback completed abort: pretxncommit.jira hook exited with status 1 meaning, that CheckForJiraIssueRecord(my_args) is just not getting called #!/usr/bin/env python import re, os, sys, jira, subprocess def verify_commit_text(tags): for line in tags: if re.match('^NO-TIK',line): return True elif re.match('^NO-REVIEW', line): return True elif re.match(r'[a-zA-Z]+-\d+', line): # Validate the JIRA ID print 'jira ticket regex matched!' m = re.search("([a-zA-Z]+-\d+)",line) print 'printing m.group(1)' print m.group(1) my_args = m.group(1) print 'my_args ...' print my_args result = CheckForJiraIssueRecord(my_args) print 'printing result....' print result if result == False: #util.warn("%s does not exist"%my_args) print 'result = False.......' else: print 'if result == False return True' return True return True else: return False def CheckForJiraIssueRecord(object): sys.stdout = os.devnull sys.stderr = os.devnull try: com = jira.Commands() logger = jira.setupLogging() jira_env = {'home':os.environ['HOME']} command_cat= "cat" command_logout= "logout" #my_args = ["QA-656"] server = "http://jira.myserver.com:8080/rpc/soap/jirasoapservice-v2?wsdl" except Exception, e: sys.exit('config error') if __name__ == '__main__': commit_text_verified = verify_commit_text(os.popen('hg tip --template "{desc}"')) #commit_text_verified = verify_commit_text(os.popen('hg log -r $1 --template "{desc}"')) if (commit_text_verified): sys.exit(0) else: print >> sys.stderr, ('[obey the rules!]') sys.exit(1); class Options: pass options = Options() options.user = 'username' options.password = 'password' try: jira.soap = jira.Client(server) jira.start_login(options, jira_env, command_cat, com, logger) issue = com.run(command_cat, logger, jira_env, my_args) except Exception, e: print sys.exit('data error') A: The function is being called but it's throwing an exception due to the following lines: 32 sys.stdout = os.devnull 33 sys.stderr = os.devnull You are assigning a string (os.devnull) to a what should be a file handle, so when anyone writes to stdout or stder it will throw an exception due to a type error. You should try: 32 sys.stdout = open(os.devnull) 33 sys.stderr = open(os.devnull) and see how that works for you. A: Offending lines: sys.stdout = os.devnull sys.stderr = os.devnull You must assign sys.stdout to a variable and after the function has done what its supposed to do, change it back. i.e out = sys.stdout err = sys.stderr .... Your code #Just befor function exits sys.stdout = out sys.stderr = err
{ "language": "en", "url": "https://stackoverflow.com/questions/7504797", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: asp net inline label text vs label control to paint labels on an asp .net webpage, is it better to use inline code like: <div><%$ Resources:TextResource, Name %></div> or set it as a label property like: <div><asp:Label ID="GuardarButton" runat="server" Text="<%$ Resources:TextResource, Name %>" /></div> I'm asking because label will use viewstate and won't have to read .resx file on every postback A: 6 of one half dozen of the other. One requires viewstate, which requires processing/deserialization. the other involves reading a cached resource. If you are looking to eliminate viewstate/trim it down, use the resource file otherwise viewstate (assuming many controls on the page). Otherwise, it doesn't much matter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: $_FILES limit in oscommerce (categories.php) I tried to extend oscommerce from 6 additional images to 12 images per product on the categories.php But when I submit it shows only 9 files in the $_FILES array no matter what I change I cannot get more than 9. I tried different variations just for testing it and the array always stops at 9 elements and the 10th gets cut off. Anybody have an idea what could be going on? this is the sizeof $_FILES and array output. You can see it stops at test2 and the rest is missing sizeof files:20 Array ( [products_image] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_med] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_lrg] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_sm_1] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_xl_1] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_sm_2] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_xl_2] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_sm_3] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_xl_3] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_sm_4] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_xl_4] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_sm_5] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_xl_5] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_sm_6] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_xl_6] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_sm_7] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_xl_7] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_sm_8] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_xl_8] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [test2] => Array ( [name] => letters_613.gif [type] => image/gif [tmp_name] => /var/www/html/web978/phptmp/php49lS7C [error] => 0 [size] => 3852 ) ) Array ( [products_image] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_med] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_lrg] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_sm_1] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_xl_1] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_sm_2] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_xl_2] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_sm_3] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_xl_3] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_sm_4] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_xl_4] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_sm_5] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_xl_5] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_sm_6] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_xl_6] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_sm_7] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_xl_7] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_sm_8] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [products_image_xl_8] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) [test2] => Array ( [name] => letters_613.gif [type] => image/gif [tmp_name] => /var/www/html/web978/phptmp/php49lS7C [error] => 0 [size] => 3852 ) ) A: Look for max_file_uploads in http://php.net/manual/en/ini.core.php#ini.sect.file-uploads Also the collective size is constrained by those settings. It's not OSC which restricts the amount.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Multiple Inheritance in Ruby, Java etc It may sound silly, but if every class implicitly extends Object class and it is allowed to extend one more class, how is it not multiple inheritance? From user's point of view it may be argued that they don't support multiple inheritance, because user is not allowed to extend more than one class. However, the languages seem to have internal support for multiple inheritance, which is just not exposed to user probably to keep it simple. Am I making sense? Note: I'm not arguing for or against support of multiple inheritance. Just trying to clarify some thoughts. A: Typical OO systems support a chain (with arbitrary length) of derived classes. From the point of view of any one subclass, the parents form a chain back to Object. Looking at all of the classes at once, we see that the class hierarchy is really a tree, with a very wide fanout immediately below Object. What is not typical is allowing two branches on the tree to merge again at a class which has direct multiple superclasses, and that specifically is what "multiple inheritance" means. You are correct that it's potentially "multiple" in the english sense either way, but not "multiple" in the OO sense of ultimately being able to pass a single object to multiple interfaces that each require an object of otherwise-unrelated parent classes. A way to work around this restriction is also typical, which is why you have interfaces in Java and included ("mixin") modules in Ruby. A: Situation which you described is just pure inheritance, it has nothing in common with multiple inheritance. For example in Java we have Integer which inherits from Number, and Number inherits from Object. Standard example of language with multiple inheritance is C++ class A { }; class B { }; class C { }; class X : public A, private B, public C { }; Whereas in Java we have class A { } class B extends A { } class C extends B { } class X extends C { } In terms of multiple inheritance Ruby is similar to Java (classes in ruby can have only one ancestor). However Ruby provides different mechanisms that "acts as" multiple inheritance i.e. modules # class XX inherits from CC class AA end class BB < AA end class CC < BB end class XX < CC end # class X mixin A,B,C modules module A end module B end module C end class X include A include B include C end In Ruby (similarly to Java) class AA has default ancestor (inheritance chain depends on Ruby version) X.ancestors [X, C, B, A, Object, Kernel, BasicObject] XX.ancestors [XX, CC, BB, AA, Object, Kernel, BasicObject] A: The difference is that "true" multiple inheritance allows you to inherate from difference classes in different class trees. The problem with that becomes if both classes your child class inherites from have similar properties or methods then you have to deal with that conflict in the child. In languages like Java, where multiple inheritance is not allowed, identical members are simply overridden by the member in the child class. In conclusion, even though you can have many classes in your type hierarchy you will only have one version of each member, as each child will override parent members with its own. A: Everything reference type in Java is a java.lang.Object, as you've noted. Developers who define custom types can be extended using one implementation. You can choose to implement multiple interfaces, but these don't come with any implementation. The developer has to add their own. So you may be strictly correct when you say that custom types in Java receive implementation from both java.lang.Object and extended super classes, but it's considered single inheritance of implementation because the developer can only extend one implementation class. You are arguing semantics. You can't extend multiple implementations in Java. But you can implement multiple interfaces.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504805", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Mock this concept class Test : ITest { public string MyValue { get; } public string Detail {get; set;} } I want to Mock the method MyValue in this way Test myTest = new Test() { Detail = "My Test" }; MockRepository repositoryTest = new MockRepository(MockBehavior.Default); Mock<Test> mockTest = repositoryTest.Create(myTest); mockTest.Setup(t => t.MyValue).Returns("Some text"); return myTest; N.B. this code does not work, is only for understanding what I want. Other way how can I mock an instance of an existing object? I use Google Moq. A: You should probably be mocking on the interface, not the implementing class. Use Mock<T>.Get(T) to get the Mock<T> from your T: ITest test = new Mock<ITest>().Object; Mock<ITest> mockTest = Mock<ITest>.Get(test); EDIT: You can stub out properties using the Moq.Stub namespace. Take a look at this page: http://blog.theagileworkshop.com/2009/03/24/stubs-in-moq/
{ "language": "en", "url": "https://stackoverflow.com/questions/7504807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Editor does not contain a main type Well I've done everything according to what our teacher has provided and what the book has to offer about this specific error. I've done everything correctly I believe but maybe someone on here can find the mistake. public abstract class school { public static void main(String[] args) { Scanner scan = new Scanner (System.in); final int name = Nick; final int age = 19; final int school = Northeast Lakeview final int dogsname = Lord Hawooru final int steps = 4000 final double miles = 1.757 system.out.print ("Hello my name is" + name "and I am" + age "years old"); system.out.print ( "I am enjoying the time I have spent so far at" + school); System.out.print ("Though I dearly miss my bundle of fun" + dogsname); System.out.print ("I am walking an average of" + steps "every day and that is equivalent to" + miles); } } A: * *You're using int types to enter string values. *You're using system instead of System. Classes and packages are case sensitive. *You're missing semicolons. *You've created an abstract class which can't be used standalone. *Eclipse probably tells you what's wrong anyway. A: First, this is not compilable code, you will not get to the point where it tells you that a main method is missing. Please look through and fix your syntax errors. When you get to the point at which it compiles then start thinking about virtual classes and I think you will realize the important problem in your code. If you still need help after that then edit your question and we will try to assist you further.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-5" }
Q: Use a function in another function in shell Type() { if [ -d $1 ] then return 1 elif [ -e $1 ] then return 2 else return 0 fi } Types() { local arg1 arg2 for arg1 in $@ do arg2=$(Type $arg1) if [ arg2 -eq 1 ] then echo "$arg1 est un répertoire." elif [ arg2 -eq 2 ] then echo "$arg1 n est pas un répertoire." else echo "$arg1 ne correspond à aucune entrée du répertoire." fi done } I don't know how can I use the function 'Type' in 'Types'. I tried "arg2=$(Type $arg1)" bur it doesn't seem to work. What's the correct syntax please ? A: return 1 Bash functions often return values through their standard output. For example, you could use something like this instead: exec echo 1 # sends 1 to the standard output and then ends the function Alternatively, you could return an integer between 0 and 255 as an exit code (as you are trying to do). If you choose to do so, you need to do: Type $arg1 arg2=$? # obtains exit code of last command/function executed However, if you need to return an array, you must use a global variable. You may want to refer to the Complex Functions and Function Complexities section of the Advanced Bash-Scripting Guide for examples of this method. A: If you want to use the function with $(Type ...), then you can change the return ... statements to echo ... (not exec echo ..., which does something else). If you want to keep the return ... statements in Type(), then you need to do something like Type ...; arg2=$? to test the return code from Type().
{ "language": "en", "url": "https://stackoverflow.com/questions/7504810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How To Highlight Selected Dates In Date Picker First is there a way to not highlight the current day. Second is there a way to highlight specific days like the way the current day was highlighted? Here is the code i have: <!DOCTYPE html> <html> <head> <link type="text/css" href="css/calendar-theme/jquery-ui-1.8.16.custom.css" rel="stylesheet" /> <script type="text/javascript" src="js/jquery-1.6.2.min.js"></script> <script type="text/javascript" src="js/jquery-ui-1.8.16.custom.min.js"></script> <script type="text/javascript"> var dates = [new Date(2011, 9 - 1, 19), new Date(2011, 9 - 1, 20), new Date(2011, 9 - 1, 20), new Date(2011, 9 - 1, 21), new Date(2011, 10 - 1, 31)]; $(function() { $('#datepicker').datepicker({ numberOfMonths: [1, 1], beforeShowDay: highlightDays, }); $('#datepicker').click(function() { // put your selected date into the data object var data = $('#datepicker').val(); $.get('getdata.php?date=' + data, function(data) { $('#events').html(data).show('slow'); }); }); function highlightDays(date) { for (var i = 0; i < dates.length; i++) { if (dates[i].getTime() == date.getTime()) { return [true, 'highlight']; } } return [true, '']; } }); </script> <style> #highlight, .highlight { background-color: #000000; } </style> </head> <body> <div id="datepicker" style="float:left;margin: 0 10px 0 0;font-size: 72.5%;"></div> <div id="events" style="float:left;font-size: 10pt;"> <p>Select a date on the calendar to see events.</p> </div> <div style="clear:both"></div> </body> </html> A: First is there a way to not highlight the current day. Yes, you can take away the highlighting by removing .ui-state-highlight and .ui-state-hover classes from the anchor element. Second is there a way to highlight specific days like the way the current day was highlighted? Yes, either add the classes for highlighting the current day to those days you want to have highlighted, or override the CSS with .ui-state-highlight's style. For the first approach, here's an example code snippet: $('#datepicker').datepicker({ numberOfMonths: [1, 1], beforeShowDay: highlightDays }).click(function() { // question 1 $('.ui-datepicker-today a', $(this).next()).removeClass('ui-state-highlight ui-state-hover'); // question 2 $('.highlight a', $(this).next()).addClass('ui-state-highlight'); }); See the first approach in action: http://jsfiddle.net/william/Aut9b. See the second approach in action: http://jsfiddle.net/william/Aut9b/1/. A: Use beforeShowDay option of jQuery UI date-picker to highlight selected dates in date-picker. Here the simple code: $( function() { // An array of dates var eventDates = {}; eventDates[ new Date( '08/07/2016' )] = new Date( '08/07/2016' ); eventDates[ new Date( '08/12/2016' )] = new Date( '08/12/2016' ); eventDates[ new Date( '08/18/2016' )] = new Date( '08/18/2016' ); // datepicker $('#datepicker').datepicker({ beforeShowDay: function( date ) { var highlight = eventDates[date]; if( highlight ) { return [true, "event", 'Tooltip text']; } else { return [true, '', '']; } } }); }); The above JavaScript will add event class on selected dates. Now you will need to define the style for selected dates. For the complete guide, you can check the source link mentioned above.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504819", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: gwt logging patternlayout Does the gwt logger have a PatternLayout similar to log4j's pattern layout?
{ "language": "en", "url": "https://stackoverflow.com/questions/7504820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I retain the text of any textbox in jQuery I have multiple textboxes with the same class ".input". Each textbox has different default text: First Name, Last Name, etc... On the focus of a particular textbox, I'd like the default text to go away, and a ".focus" class to be added to the textbox. On the blur of that textbox, I'd like the default text to return if no text has been entered by the user. I'd also like the ".focus" class to be removed unless the user has entered text. I know how to do this for one textbox, but not multiple (without writing a function for each textbox). I'm guessing there is a way. I'm also working with asp.NET textboxes so I had to modify the selector. var myText var myBox $('input:text.input').focus(function () { myText = $(this).val(); myBox = $(this); //alert('focus'); }).blur(function () { alert($(myText).val()); }); I'm pretty sure the global vars don't retain their values by the time the blur function is called. I've seen this done many times on multiple sites, I just can't figure it out. Any help is appreciated. Thanks! I've searched and come up with something close... However, when blur is called, the default text goes away even though I've entered in text. $('input:text.input').focus(function () { if (this.value == this.defaultValue) { this.value = ''; } if (this.value != this.defaultValue) { this.select(); } }); $('input:text.input').blur(function () { $(this).removeClass("focus"); if ($.trim(this.value == '')) { this.value = (this.defaultValue ? this.defaultValue : ''); } }); Thanks for your help! Here is the code with some tweaks. $('input:text.input').focus(function () { if($(this).hasClass('focus')) { } else { $(this) .data('stashed-value', $(this).val()) // stash it .addClass('focus') .val(''); // clear the box } }).blur(function () { if ($(this).val() != '') { } else { $(this) .val($(this).data('stashed-value')) // retrieve it .removeClass('focus'); } }); A: One way is to stash the value you want to save within the element itself, using data(): $('input:text.input').focus(function () { $(this) .data('stashed-value', $(this).val() ) // stash it .val(''); // clear the box }).blur(function () { // presumably you'll check some conditions here (e.g. input empty) then: $(this).val( $(this).data('stashed-value') ); // retrieve it }); A: If you are using HTML5, placeholder text will do this for you: <input name="q" placeholder="Search Bookmarks and History"> http://diveintohtml5.ep.io/forms.html#placeholder You can check it out in Chrome or FF. You can also do this with jQuery $('input').focus(function(){ if($(this).val() == 'Search'){ $(this).val(''); } }); $('input').blur(function(){ if($(this).val() == ''){ $(this).val('Search') } }); Example: http://jsfiddle.net/jasongennaro/YaXSg/ A: You could implement a combination of the answers to create a solution that works in HTML5 compliant browsers and gracefully degrades on others. Html5: <input type='text' placeholder="First Name" class="input" /> <input type='text' placeholder="Last Name" class="input" /> <input type='text' placeholder="Email" class="input" /> jQuery code for backwards compatibility: $('input:text.input').each(function (i) { $(this).val($(this).attr('placeholder')); $(this).focus(function() { if ($(this).val() == $(this).attr('placeholder')) { $(this).val(''); } }); $(this).blur(function() { if (!$(this).val()) { $(this).val($(this).attr('placeholder')); } }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7504822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: set errormessage for customvalidator? I would like to use a customvalidator control to handle all my validation, but I can't figure out how to set the error message in the code-behind for different checks. Is this possible? A: You can set the error message in the OnServerValidate method as you wish based on your validation logic: protected void customValidator1_Validate(object sender, ServerValidateEventArgs e) { if (e.Value.Length < 5) { e.IsValid = true; } else { customValidator1.ErrorMessage = "Length must be less than 5."; e.IsValid = false; } } A: For One Control you can do like this.. <!-- In Designer Page --> <asp:CustomValidator runat="server" id="cusCustom" controltovalidate="txtCustom" onservervalidate="cusCustom_ServerValidate" errormessage="The text must be exactly 8 characters long!" /> <br /><br /> /* In Code Behind*/ protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e) { if(e.Value.Length == 8) e.IsValid = true; else e.IsValid = false; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7504824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Ruby - DateTime, cookbook solution to show the difference between two times is not working, can you see what's wrong? I have two variables containing dates: curr_time = Wed Sep 21 11:13:50 -0700 2011 prev_time = Wed, 21 Sep 2011 09:44:56 UTC +00:00 to find out how many minutes have passed between these two I am using the following: elapsed = ((curr_time - prev_time) / (60)).to_i However the result is 522, it should be 89 minutes. I've tried this a few different ways, but I'm clearly missing something here. Any help would be appreciated! A: curr_time = "Wed Sep 21 11:13:50 -0700 2011".to_time prev_time = "Wed, 21 Sep 2011 09:44:56 UTC +00:00".to_time ((curr_time - prev_time)/60).to_i => 88
{ "language": "en", "url": "https://stackoverflow.com/questions/7504829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: super-keyword in Java giving compile-error class That { protected String nm() { return "That"; } } class More extends That { protected String nm() { return "More"; } protected void printNM() { That sref = super; System.out.println("this.nm() = " + this.nm()); System.out.println("sref.nm() = " + sref.nm()); System.out.println("super.nm() = " + super.nm()); } public static void main(String[] args) { new More().printNM(); } } When trying to compile More.java I'm getting 4 errors: More.java:7: error: '.' expected That sref = super; ^ More.java:7: error: ';' expected That sref = super; ^ More.java:9: error: illegal start of expression System.out.println("this.nm() = " + this.nm()); ^ More.java:9: error: ';' expected System.out.println("this.nm() = " + this.nm()); ^ 4 errors Is something wrong with the code? (It's from the book "The Java Programming Language" p.62) EDIT: From the book: "And here is the output of printNM: this.nm() = More sref.nm() = More super.nm() = That So either they're using some deprecated super-feature(I think this is the first edition of the book) or it is a typo and maybe they meant: "That sref = new More()" A: You can't use super that way. Either use it in a constructor, with brackets - super() or super.method() (or in generics) In your case this keyword shouldn't be there. If you want an instance of the super class, just have That sref = new That(); A: Change : That sref = super; to That sref = super(); This statement is basically trying to get hold of the object reference of the super class type, so you need to call the constructor for it - which is done using super(). A: Simply stated, you can't. You probably could do some hacks through reflection, but side from that you can't do it. You need to know what class you're making your new Object. In this case, you have to make it new That().
{ "language": "en", "url": "https://stackoverflow.com/questions/7504830", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Simple FTP program in C or Java I need to write a program in C or Java to transfer the files from windows to Linux machine. requirement is to connect Linux machine, authenticate, option for select mode , transfer the file and disconnect. But I am not getting a simple C or Java program for it,at least connect it and transfer a simple file. can you tell me please from where I can start? or any simple example programs are available, any clue any link. Thanks in Advance A: search for sample client/server applications in Java or C as you prefer.Than you can start adding your communication protocol. You may be interested in asynchronous connections using select or other methods so the server will not hang waiting for client connections... A: First thing I would do is decide Java or C. Deciding that, google for " FTP Libraries". Read through their documentation and proceed to build your client. Keep in mind that you must be connecting to a machine that is accepting FTP connections (or perhaps you have to write the FTP server side as well? Get verification of this from whoever is giving you the assignment.) A: You might want to have a look at the libcurl library. There is, in the examples section, an ftp client program that might suit you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to make SCONS update the contents of a file used in a build What's the proper SCONS method for updating the contents of a file that is part of build? I use SCONS to build a fairly large project. But for the sake of a simple question, assume it looks like this: env.Program("foo", ["foo.c", "version.c"]) Under certain build conditions, it's necessary to update the contents of one of the CPP files in the build with new information - version information actually. In the above example, I would need to modify the contents of "version.c". I thought I could do this rather nicely with the following example: env.Command(target="version.c", source=[], action=PythonFunctionToUpdateContents) env.Program("foo", ["foo.c", "version.c"]) The PythonFunctionToUpdateContents would use target[0] as the name of the file, open it, look for some specific text, change it, write the changes back to the same file. Unfortunately, the above sample doesn't work. SCONS automatically deletes a target file before building it, so my "version.c" file got deleted before it could be updated. I tried setting the target and source to the same file in the env.Command() call, but that just creates a dependency cycle. I know that I could solve this by having SCONS generate the ENTIRE version.c file, but that's not suitable since version.c contains a lot of other code that can change as part of normal development. A: The usual way to do this is to have a "version.c.in" or "version-in.c" or whatever you like to call it. Modify that and output it to version.c. You would add the "in" file to your version control system, while the version.c file would not be in there. So the result of all this would look as follows: env.Command(target="version.c", source="version-in.c", action=PythonFunctionToUpdateContents) env.Program("foo", ["foo.c", "version.c"]) This applies to other build systems too - it is generally a bad idea to have an input file also be an output file. Far better to use an intermediate file to get the job done. A: This answer is kinda late to the party, but here it is anyway: You should use env.Precious("version.c"). This prevents the file from being deleted before being built. You probably also want to use env.NoClean("version.c") so that it doesn't get deleted during a clean. You COULD use env.SideEffect maybe, but that one seems to have a couple weird things about it. I was told on the mailing list to generally not use that one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Why is my addition of 2 shorts causing a casting compile error due to ints? In my code i have the following code: Order = config.DeploymentSteps.Select(x => x.Order).DefaultIfEmpty().Max() + 1; This gives me the error Cannot implicitly convert type 'int' to 'short'. As a Reference Order and x.Order are both shorts, and Max() is correctly returning a short (I have verified this). So I get it, it thinks the 1 is an integer and erroring. So I changed it to: Order = config.DeploymentSteps.Select(x => x.Order).DefaultIfEmpty().Max() + (short)1; I'm now still getting the same compile. So maybe it's not casting it right, so I tried changing it to Order = config.DeploymentSteps.Select(x => x.Order).DefaultIfEmpty().Max() + Convert.ToInt16(1); Yet I still get the same error. Finally I got it to work by converting the whole expression: Order = Convert.ToInt16(config.DeploymentSteps.Select(x => x.Order).DefaultIfEmpty().Max() + 1); Why can't I cast the 1 to a short and add it to another short, without casting the whole thing? A: It is because short + short = int. Eric Lippert explains it here. He says: Why is short plus short result in int? Well, suppose short plus short was short and see what happens: short[] prices = { 10000, 15000, 11000 }; short average = (prices[0] + prices[1] + prices[2]) / 3; And the average is, of course, -9845 if this calculation is done in shorts. The sum is larger than the largest possible short, so it wraps around to negative, and then you divide the negative number. In a world where integer arithmetic wraps around it is much more sensible to do all the calculations in int, a type which is likely to have enough range for typical calculations to not overflow. A: As much as it sounds redundant, would you mind declaring a short variable (or perhaps a const) and initilize it to 1 and use that while assigning your Order variable. Unlike an int or long, there is no literal way of specifying a short. A: The C# language specification (download link) lists the predefined addition operators. For integral types, these are: int operator +(int x, int y); uint operator +(uint x, uint y); long operator +(long x, long y); ulong operator +(ulong x, ulong y); The reason you have to cast is because there's no specific operator to add shorts. I know that "because C# is made to work like this" isn't a particularly useful answer but there you go. I'd just go with: Order = (short) config.DeploymentSteps.Select(x => x.Order).DefaultIfEmpty().Max() + 1; or: Order = config.DeploymentSteps.Select(x => x.Order).DefaultIfEmpty().Max(); Order++;
{ "language": "en", "url": "https://stackoverflow.com/questions/7504837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Php/mysql xml and Google maps I am following step by step this tutorial http://code.google.com/apis/maps/articles/phpsqlajax.html . I have tried all the 3 ways to output data to an xml file . But i get error "error on line 9 at column 1: internal error" which is the line that php script begins. Connection to database is ok. tables and fields are ok. I tried and copy pasted the exact code from google's tutorial (same values everywhere) to check if there was a problem with my database engine or something and I got an error again this time error on line 10 at column 8: Extra content at the end of the document that is $xmlStr=str_replace('"','"',$xmlStr); I am running XAMPP 1.7.4 [PHP: 5.3.5] A: Did you forget this line? header("Content-type: text/xml"); How do you call your file? From an url? Thank you
{ "language": "en", "url": "https://stackoverflow.com/questions/7504840", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I have to use the Field type when writing a mysql storage engine? I am working on a storage engine for MySQL. But I am already struggling with simply parsing data. For example there is a method with the following signature: int ha_engine::update_row(const uchar *old_data, uchar *new_data); So the data is stored in the old_data and new_data arrays. However to get the data out of this array, one should use the Field class to access the data in these rows. Now the problem is, that I have no idea how to do that. For example this code: longlong val = table_share->field[0]->val_int(); will not work, or I don't know from which row I will get the first column. So how should one do that?? Thanks in adcance for any help! A: You can use the field type information to determine the kind of variable to hold the data and also which function to use to fetch the data. In my database applications, the type of the field is always known, as the program creates the tables and populates them. I have a hierarchy of classes derived from a Field class: class Field { public: virtual std::string get_field_name(void) const = 0; virtual std::string get_value_as_string(void) const = 0; virtual void load_from_mysql_record(const MySQLRecord& r) = 0; }; class Field_Integer : public Field { public: int m_value; std::string get_value_as_string(void) const { std::ostringstream oss; oss << m_value; return oss.str(); } }; class Field_String : public Field { public: std::string m_value; std::string get_value_as_string(void) const { return m_value; } }; Each field leaf class would use the get_field_name function to fetch the data from the MySQL record. Alternatively, a method could be created in the Field class to fetch data in a record by field index.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504860", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Making PHP cookies stay on after browser in closed A user is automatically logged out of my site upon closing the browser. Is there a way to make cookies stay active after the browser is closed? A: <?php setcookie("test", "test", time()+3600); ?> Just set the time on it to expire in the future. A: You need to manualy set the cookies to keep the session. You need a manualy computed session to identify the user when he opens the browser again.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C#: How to perform 'as' operation with a Type I want to test whether a given object can be cast to a given Type. In this scenario, I have an object, and the Type representing what type I want to cast it to: public function FooBar(..., object data, Type expected) { ... var unboxedData = ? if (unboxedData == null) { .... } ... } How can I cast data to the type type represents? Basically, I want to do this: var unboxedData = data as Type; ...but of course you can't use Type with an as statement, so what do I do? A: Edit 2: I'm going to say it's not possible without reflection or generics. With reflection, you have no compile-time checking and must use reflection (or dynamic) to further call methods/properties of the object. With generics, you can't use a Type object to get there alone. Take your pick. Is it possible to refactor your calling code to allow generics? If allowed, this may be more easily handled with a generic method: public resultType FooBar<T>(..., object data) { ... T unboxedData = (T)data; ... } Edit: Also, you can use data as T if you include a generic type constraint of where T : class: public something FooBar<T>(..., object data) where T : class { ... T unboxedData = data as T; if (unboxedData == null) { ... } ... } A: ...but of course you can't use Type with an as statement, so what do I do? Morre importantly, you can't use var this way. So there is nothing to be gained here. You can test if it's the right type with if (expected.IsInstanceOfType(data)) But then you still can't write any decent code to access properties or methods on data. A: C# provides the as keyword to quickly determine at runtime whether a given type is compatible with another. When you use the as keyword, you are able to determine compatibility by checking against a null return value. Consider the following: Hexagon hex2 = frank as Hexagon; if (hex2 == null) Console.WriteLine("Sorry, frank is not a Hexagon..."); In addition to the as keyword, the C# language provides the is keyword to determine whether two items are compatible. Unlike the as keyword, however, the is keyword returns false, rather than a null reference, if the types are incompatible. if (emp is SalesPerson) { Console.WriteLine("{0} made {1} sale(s)!", emp.Name, ((SalesPerson)emp).SalesNumber); } A: if (data.GetType() == t || data.GetType().IsSubclassOf(t)) { //do your thing } Should tell you if it's exactly or a subclass of (so it can be cast in to it). A: This is pretty tricky. The problem is that var does not mean "variant". It is acts more like a temporary placeholder that C# fills in with an actual type once the type information can be inferred from the expression. unboxedData is still very much a strongly typed variable. Its just the compiler is trying to figure out the type instead of you explicitly specifying it. It is is of vital importance to note that the typing is still occurring at compile time and not runtime. If you want to dynamically cast an object at runtime then you will not be able to use var or any other concrete type specifier. Your options are limited to one of the two possible declarations: * *object *dynamic Based on what I think you want to do with unboxedData I suspect dynamic is the route you want to go because it would allow you to call any method on the target Type. So here is what I came up with. public void FooBar(object value, Type expected) { dynamic unboxedData = expected.FromObject(value); unboxedData.CallSomeMethodDefinedInTheTargetType(); // This will work. } This requires the following extension method. public static class TypeExtension { public static object FromObject(this Type target, object value) { var convertable = value as IConvertible; if (convertable != null) { return convertable.ToType(target, null); } Type type = value.GetType(); if (target.IsAssignableFrom(type)) { return value; } MethodInfo[] methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public); foreach (MethodInfo mi in methods) { if (mi.ReturnType == target) { try { return mi.Invoke(null, new object[] { value }); } catch (TargetInvocationException caught) { if (caught.InnerException != null) { throw caught.InnerException; } throw; } } } throw new InvalidCastException(); } } The cast will work if one of the following are true. * *The value to be converted implements IConvertible and has a conversion path to the target type. *The value to be converted subclasses the target type. *The value to be converted defines an explicit conversion operator in its class declaration. A: Well, looking around I found somthing... How to check if implicit or explicit cast exists? Be wary, I haven't given it much testing, but at a glance it seems to be promising. A big negative is that it throws the exception if it can't convert it: static bool isConvertableTo(object o, Type t) { try { var expr = Expression.Constant(o); var res = Expression.Convert(expr, t); return true; } catch { } return false; } Another useful link with same approach: Checking if a type supports an implicit or explicit type conversion to another type with .NET
{ "language": "en", "url": "https://stackoverflow.com/questions/7504863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to add an EditText to a ListView I'm looking to read some product details in from a database and then add them to a ListView. I then want on each line a qty EditText box where customer can add a qty in. How can I do this? I did a simple page but when I enter a qty and the scroll down and then back up again I loose the data or it even appears in another qty box on another row. A: Okay so the first thing you will need to do is create a Row.xml file for the layout that you want each row in the list to have.. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <ImageView android:id="@+id/icon" android:padding="2dip" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ok" /> <TextView android:id="@+id/label" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="40sp" /> //Add a edittext here.. /LinearLayout> Next you will need to extends listview and override get view to load in your custom row. public class Demo extends ListActivity { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); setListAdapter(new Adapter());} //Here extends a ArrayAdapter to create your custom view class Adapter extends ArrayAdapter<String> { Adapter() { super(DynamicDemo.this, R.layout.row, R.id.label, items); } public View getView(int position, View convertView, ViewGroup parent) { //Here load in your views such as the edittext } Thats what you will need to get started you can then call onItemListClick() to get each click when the user clicks the item. You can get a full tutorial here... Tutorial EDIT: Also if you want to save the number in the quantity box you will need to have a Bundle. Such as saveState() method This will save your users quantity number while the app is still alive, and when brought back into view pull the number or int from the bundle. This should be of help http://www.edumobile.org/android/android-beginner-tutorials/state-persistence/ A: You should save state(content entered by user in EditText) in some sort of array, supplied to your list adapter. Probably you create new EditText in getView() method of your list adapter. A: Hi below is the code i have been playing around with package sanderson.swords.mobilesales; import java.text.DecimalFormat; import java.text.NumberFormat; import android.app.AlertDialog; import android.app.ListActivity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteException; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.AdapterView.OnItemClickListener; public class OrderProductSearch extends ListActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try{ setContentView(R.layout.orderproducts); } catch (Exception e) { // String shaw=""; shaw = e.getMessage(); } //Create view of the list where content will be stored final ListView listContent = (ListView)findViewById(R.id.orderproductlistview); //Set for fast scrolling listContent.setFastScrollEnabled(true); //Create instance of the database final DbAdapter db = new DbAdapter(this); //Open the Database and read from it db.openToRead(); //Routine to call all product sub groups from the database final Cursor cursor = db.getAllSubGroupProduct(); //Manages the cursor startManagingCursor(cursor); //The columns we want to bound String[] from = new String[]{DbAdapter.KEY_PRNAME, DbAdapter.KEY_PRSIZE, DbAdapter.KEY_PKQTY}; //This is the id of the view that the list will be map to int[] to = new int[]{R.id.productlinerow, R.id.productlinerow2, R.id.productlinerow3}; //Create simple cursor adapter SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.productlinerow, cursor, from, to); //Set the cursor to the list content view listContent.setAdapter(cursorAdapter); //Close the database db.close(); //check if any orders are on the system int check = cursor.getCount(); AlertDialog.Builder ps = new AlertDialog.Builder(OrderProductSearch.this); final Button border = (Button) findViewById(R.id.orderqty); //notify the user if there are no orders on the system if (check == 0) { ps.setTitle("No Products Found"); ps.setMessage("There are no products in this group"); ps.setPositiveButton("Ok", new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int which) { OrderProductSearch.this.finish(); startActivity(new Intent("sanderson.swords.mobilesales.PRODUCTENQUIRY")); } }); ps.show(); } border.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { try { String clicked = ""; clicked = "neil shaw"; } catch (Exception e) { String error = e.getMessage(); error = error + ""; } } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7504868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Where is VMware vSphere SDK C# samples required references for VimApi namespaced classes? I cannot compile the C# samples from the VMware vSphere SDK 5.0 using Visual Studio 2010. The error is missing references for namespaces AppUtil and VimApi. The references in the VS2010 solution file point to these files. ..\AppUtil\bin\Debug\AppUtil.dll ..\..\Vim25Service2010.dll ..\..\Vim25Service2010.XmlSerializers.dll ..\..\VimService2010.dll ..\..\VimService2010.XmlSerializers.dll ..\VMware.Security.CredentialStore\bin\Debug\VMware.Security.CredentialStore.dll Where are these files in the SDK, or how do I get them if not in the SDK? Two of the references are from other projects in the solution; including the AppUtil namespace. I can update each project to reference the project instead of the debug output. Is there a build step I am missing to generate the other dlls? Is VimApi part of a different download? The release notes don't mention additional downloads to get the projects to compile. A: Chapter 3 of the developers setup guide explains how to build the VimService dlls. Jason's script above works, but leaves out one critically important (and irritating) step. After generating the XMLSerializer dll, you need to EDIT the VimService.cs file to force the reference to the XMLSerializer assembly and remove the inline XMLIncludeAttribute calls. After the edit (which is explained in the setup guide) you need to recompile VimService. It works without doing the edit, but it can cause a HUGE delay when instantiating VimService. I found it to be a 3 minute wait, which was unacceptable. If you're encountering the delay, recompile VimService according to the instructions and update your reference to the new assembly (and make sure your build isn't hanging on to the old version). A: I hate to answer my own question, but I came up with a solution. Based on the KB article pointed to from the readme I was able to create instructions for VS2010. Run the following commands from the directory that has the solution file inside a Visual Studio command prompt. rem Script to generate required references for VMware vSphere SDK 5.0 cd .. if not exist VimService2010.dll ( wsdl /n:VimApi /o:VimService.cs ..\..\wsdl\vim\vim.wsdl ..\..\wsdl\vim\vimService.wsdl csc /t:library /out:VimService2010.dll VimService.cs sgen /p VimService2010.dll ) if not exist Vim25Service2010.dll ( wsdl /n:Vim25Api /o:Vim25Service.cs ..\..\wsdl\vim25\vim.wsdl ..\..\wsdl\vim25\vimService.wsdl csc /t:library /out:Vim25Service2010.dll Vim25Service.cs sgen /p Vim25Service2010.dll ) This script creates the needed dll files from the wsdl files in the SDK. A: Example instructions on how to modify the VimService.cs file can be found here. http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=87402 A: It's a real shame VMware didn't pre-build the assemblies like before. There are 100s of lines to manually edit if you follow their instructions to do it properly and avoid hangs. So I wrote some scripts to do this properly. You can find them here... A: I also experienced that the dlls are missing. I've chosen to build on the VMware.Vim.dll too but am sort of boated out now too. I was using the one that was found in the PowerCLI, but suddenly it's gone. I've already requested an answer from the community but nobody answered that... have a look: http://communities.vmware.com/message/1815356#1815356 I've also written a small "how to start" but became no feedback at all. It's outdated too since the dll is gone now. But maybe it helps when you've found the right dlls: http://communities.vmware.com/message/1806388#1806388 Hope this helps, at least by showing what not to do. Greetings, Kjellski
{ "language": "en", "url": "https://stackoverflow.com/questions/7504870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Prevent AJAX flooding in Javascript My site has a Javascript method that makes an AJAX request to add an item to cart without reloading the page and making a simple notification. AddToCart() However, using any Javascript console, I found you can flood this request with a simple statement: while (true) {AddToCart()} And eventually lock the server until the browser crashes. A more stable browsing environment could probably even lock the server indefinitely. So what would be the best way to protect against such an attempt? A: Perhaps you should just define the function in a private namespace? (function() { function AddtoCart(){}; })(); That way you can't reference it through the console. This of course is not bulletproof as anyone could just replicate the code or make HTTP requests to the URI. You can't stop the HTTP requests but you can stop the page processing data possibly by implementing CSRF tokens so that it won't do the heavy processing unless the CSRF token matches, which is generated from your page which creates the CSRF based on variables like timestamp and such, so it can't be (easily?) reproduced. A: There are lots of ways that servers protect themselves from rogue clients. In this particular case, "rate limiting" is probably appropriate where the server selects a maximum number of operations per minute from the client that it thinks it reasonable for a human to operate and when the rate of operations from one client exceeds that it protects itself. How it chooses to protect itself depends. It might immediately fail each new request for awhile to keep from using many server resources, it might log the client out, it might fail silently or return an error. Servers should know that real protection against this type of thing has to be done at the server because ajax calls can be done by anyone, not just your own client code. On the client, you could protect from rogue javascript being injected a number of ways. Down lower in your code, you could also implement rate limiting (like right before you make the actual ajax call) and refuse to carry out more than X ajax calls per minute. This doesn't fully protect your server, but protects you from your own AddToCart() function being used in this way. Or, you could make it so there is no top level global namespace function that requires no parameters that can be called this way. You could do this either by removing the relevant functionality from the global namespace (make it a method on one of your objects that requires a proper "this" pointer) or you could make the function require some relevant internal state that wouldn't always be known. Personally, I don't really fell like a client needs to be protected from abuse that its owner might inflict on it when there's no legitimate purpose for what's being done other than to cause mayhem. If the user wants to do bad things that crash their own client, that's fine. They can bring down the client with task manager if they want. You do want to protect it from spraying your server with bad stuff and protect it from anything bad that might happen with legitimate normal user operations, but if the user wants to take down their own client, I'm not going to lose any sleep over that. A: They could do much more damage using ab (Apache benchmark) with a high concurrency value, or they could just sit there hitting F5. You need a lower-level solution - rate limiting, by IP perhaps, or a one-use hash, or any number of other solutions. A: A request is a request, AJAX or not. The same rules apply for a regular DOS attack. There's nothing to stop people from calling your URL directly, even without AJAX. A: Someone clever enough to figure out your code, open their browser's console, and type while (true) {AddToCart()} doesn't even need a browser (or your code) – they could just execute wget in an infinite loop, or if the goal is really a DoS, use a script for that purpose. On the server side, you're dealing with how to mitigate a denial of service attack. There are many strategies; using the Nginx reverse proxy is the first that popped into my mind. A: One thing you could do is make the AddToCart function only do the request if one is not already in progress. Another think you can do is obfuscate the code (there are tools to do this, do a search for javascript obfuscation) so its not obvious what method does what. Those two methods will help, but won't solve the problem entirely. The server really needs to detect if its getting spammed with requests from one client and limit them, via a rate limiter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Ruby Mechanize does not pass cookie with request I have a problem with Ruby mechanize where it loses the cookie during a 302 redirect after a manual post request. 1) Load page agent.get(url) Log: I, [2011-09-21T19:50:46.077628 #5040] INFO -- : Net::HTTP::Get: /some_site D, [2011-09-21T19:50:46.077628 #5040] DEBUG -- : request-header: accept => */* D, [2011-09-21T19:50:46.077628 #5040] DEBUG -- : request-header: user-agent => Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4b) Gecko/20030516 Mozilla Firebird/0.6 D, [2011-09-21T19:50:46.077628 #5040] DEBUG -- : request-header: accept-encoding => gzip,deflate,identity D, [2011-09-21T19:50:46.077628 #5040] DEBUG -- : request-header: accept-charset => ISO-8859-1,utf-8;q=0.7,*;q=0.7 D, [2011-09-21T19:50:46.077628 #5040] DEBUG -- : request-header: accept-language => en-us,en;q=0.5 D, [2011-09-21T19:50:46.077628 #5040] DEBUG -- : request-header: host => site.com I, [2011-09-21T19:50:47.965232 #5040] INFO -- : status: Net::HTTPOK 1.1 200 OK D, [2011-09-21T19:50:47.965232 #5040] DEBUG -- : response-header: date => Wed, 21 Sep 2011 17:50:46 GMT D, [2011-09-21T19:50:47.965232 #5040] DEBUG -- : response-header: server => Apache/2.2.9 (Debian) mod_ssl/2.2.9 OpenSSL/0.9.8g PHP/5.2.17 mod_perl/2.0.4 Perl/v5.10.0 D, [2011-09-21T19:50:47.965232 #5040] DEBUG -- : response-header: x-powered-by => PHP/5.2.17 D, [2011-09-21T19:50:47.965232 #5040] DEBUG -- : response-header: set-cookie => frontend=9d47f1e106d4f2efcc2830988eb66610; expires=Wed, 21-Sep-2011 18:50:46 GMT; path=/; domain=site.com D, [2011-09-21T19:50:47.965232 #5040] DEBUG -- : response-header: expires => Thu, 19 Nov 1981 08:52:00 GMT D, [2011-09-21T19:50:47.965232 #5040] DEBUG -- : response-header: cache-control => no-store, no-cache, must-revalidate, post-check=0, pre-check=0 D, [2011-09-21T19:50:47.965232 #5040] DEBUG -- : response-header: pragma => no-cache D, [2011-09-21T19:50:47.965232 #5040] DEBUG -- : response-header: content-encoding => gzip D, [2011-09-21T19:50:47.965232 #5040] DEBUG -- : response-header: vary => Accept-Encoding,User-Agent D, [2011-09-21T19:50:47.965232 #5040] DEBUG -- : response-header: keep-alive => timeout=15, max=100 D, [2011-09-21T19:50:47.965232 #5040] DEBUG -- : response-header: connection => Keep-Alive D, [2011-09-21T19:50:47.965232 #5040] DEBUG -- : response-header: transfer-encoding => chunked D, [2011-09-21T19:50:47.965232 #5040] DEBUG -- : response-header: content-type => text/html; charset=UTF-8 D, [2011-09-21T19:50:48.370832 #5040] DEBUG -- : saved cookie: frontend=9d47f1e106d4f2efcc2830988eb66610 This all works fine and looks good to me. Session cookie gets set, added to Mechanize cookie jar. pp agent.cookies[0] displays the cookie frontend= no problem. 2) Send POST request to server agent.post(url,{"product" => "10000","qty" => "1"}) This does not send the cookie to the server. I receive an error message ("cookies not enabled, please enable to continue"). Does Mechanize only pass cookies on POST request when specified? The cookie is not sent to server unless I specifically add it to POST request. agent.post(url,{"product" => "10000","qty" => "1"},'cookie' => agent.cookies[0]) In this case, logger shows this: D, [2011-09-21T19:50:48.480032 #5040] DEBUG -- : request-header: cookie => frontend=9d47f1e106d4f2efcc2830988eb66610 3) Server does a 302 redirect. For the GET request of the redirect page, Mechanize does not pass the session cookie. Thus, the session gets lost and a new session cookie set by server. I, [2011-09-21T19:50:49.182034 #5040] INFO -- : follow redirect to: http://site.com/redirect/ I, [2011-09-21T19:50:49.182034 #5040] INFO -- : Net::HTTP::Get: /redirect/ D, [2011-09-21T19:50:49.182034 #5040] DEBUG -- : request-header: accept => */* D, [2011-09-21T19:50:49.182034 #5040] DEBUG -- : request-header: user-agent => Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4b) Gecko/20030516 Mozilla Firebird/0.6 D, [2011-09-21T19:50:49.182034 #5040] DEBUG -- : request-header: accept-encoding => gzip,deflate,identity D, [2011-09-21T19:50:49.182034 #5040] DEBUG -- : request-header: accept-charset => ISO-8859-1,utf-8;q=0.7,*;q=0.7 D, [2011-09-21T19:50:49.182034 #5040] DEBUG -- : request-header: accept-language => en-us,en;q=0.5 D, [2011-09-21T19:50:49.182034 #5040] DEBUG -- : request-header: host => site.com D, [2011-09-21T19:50:49.182034 #5040] DEBUG -- : request-header: referer => http:/site.com/referrerlink/ I, [2011-09-21T19:50:49.728035 #5040] INFO -- : status: Net::HTTPOK 1.1 200 OK D, [2011-09-21T19:50:49.728035 #5040] DEBUG -- : response-header: date => Wed, 21 Sep 2011 17:50:49 GMT D, [2011-09-21T19:50:49.728035 #5040] DEBUG -- : response-header: server => Apache/2.2.9 (Debian) mod_ssl/2.2.9 OpenSSL/0.9.8g PHP/5.2.17 mod_perl/2.0.4 Perl/v5.10.0 D, [2011-09-21T19:50:49.728035 #5040] DEBUG -- : response-header: x-powered-by => PHP/5.2.17 D, [2011-09-21T19:50:49.728035 #5040] DEBUG -- : response-header: set-cookie => frontend=c08477bb03473d68acd83ed81ed56101; expires=Wed, 21-Sep-2011 18:50:49 GMT; path=/; domain=site.com D, [2011-09-21T19:50:49.728035 #5040] DEBUG -- : response-header: expires => Thu, 19 Nov 1981 08:52:00 GMT D, [2011-09-21T19:50:49.728035 #5040] DEBUG -- : response-header: cache-control => no-store, no-cache, must-revalidate, post-check=0, pre-check=0 D, [2011-09-21T19:50:49.728035 #5040] DEBUG -- : response-header: pragma => no-cache D, [2011-09-21T19:50:49.728035 #5040] DEBUG -- : response-header: content-encoding => gzip D, [2011-09-21T19:50:49.728035 #5040] DEBUG -- : response-header: vary => Accept-Encoding,User-Agent D, [2011-09-21T19:50:49.728035 #5040] DEBUG -- : response-header: content-length => 6441 D, [2011-09-21T19:50:49.728035 #5040] DEBUG -- : response-header: keep-alive => timeout=15, max=98 D, [2011-09-21T19:50:49.728035 #5040] DEBUG -- : response-header: connection => Keep-Alive D, [2011-09-21T19:50:49.728035 #5040] DEBUG -- : response-header: content-type => text/html; charset=UTF-8 Any suggestions on how I can prevent Mechanize from losing the cookie during the 302 redirect? I am not able to anything but the manual POST request due to javascript used on the site. And is this common behaviour of Mechanize to only send cookies with a manual POST request when explicitly specified (from my experience of using POST requests, I have not have problems with losing session cookies until now). I appreciate your help. Thanks, Chris A: I ran into the same problem with redirects, where the cookies weren't being saved in the jar after a redirect. I downloaded the latest version of Mechanize from the github repository (version 2.0.2) and the issue seems to be fixed. Not exactly sure what change in the code base fixed this problem, but the cookies now seem to be saving after redirects. When you are trying this fix, make sure that you're using version 2.0.2 of the gem, and not another locally installed version of the gem. That got me for a while. :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7504893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Adding overflow-y to block element causes width to decrease. This is what I have, I have left div, and a right div. The left div is a fixed width, and floated left. The right Div is a "display: block" to make it full width, and has a margin on the left to compensate for the left div. Both of the boxes have a fixed height, and need to be scrollable (the contents inside). I add an overflow-y to the Left div successfully. However when I add overflow-y: auto to the right div, the div no longer spans the whole div. Before adding Overflow: http://jsbin.com/asecuy/ After adding Overflow: http://jsbin.com/asecuy/2 A: You need to unset .eventdetails { margin-left: 252px; } This margin is causing the bug. I'm guessing it just doesn't play nice together with overflow-y and the float next to it (should work though I think). Here it is working: http://jsbin.com/asecuy/3/#html
{ "language": "en", "url": "https://stackoverflow.com/questions/7504896", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to decode "\u002522\u00253A etc" In C# I'm not familiar with this encoding, what is it and how do I decode it in C#? \u00257B\u002522target_id\u002522\u00253A\u002522p\u00257C29681347\u002522\u00252C+\u002522prop_id\u002522\u00253A\u0025222\u002522\u00252C+\u002522tid\u002522\u00253A\u0025221316132877\u002522\u00252C+\u002522 A: Assuming that it's a C# string literal like this string text = "\u00257B\u002522target_id\u002522\u00253A\u002522p..."; then you don't need to decode it at all. It's just a string literal that happens to contain an escape code. The escape code \udddd (where dddd is a four-digit number) represents the Unicode character U+dddd. Eight-digit Unicode escape codes are also recognized: \Udddddddd. So \u0025 represents the character %. If you display the string, e.g. Console.WriteLine(text); you get the following output: %7B%22target_id%22%3A%22p... The output looks like an URL encoded string. You can decode it using the Uri.UnescapeDataString Method: string decoded = Uri.UnescapeDataString(text); // decoded == "{\"target_id\":\"p..." If you display the decoded string Console.WriteLine(decoded); you get the following output: {"target_id":"p... A: Use System.Web.HttpUtility.UrlDecode() on that string to get {"target_id":"p|29681347", "prop_id":"2", "tid":"1316132877", " Clearly it is a fragment of the entire string. A: That's a unicode representation for a keyvalue pair list: {"target_id":"p|29681347",+"prop_id":"2",+"tid":"1316132877",+" You can decode it with the common System.Text.Encoding.Unicode classes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Json response does not output in view, but prompts me to download the file instead I am using WebRequest to read JSON data from the FCC so I can output it to a view. Here is my custom class to hold an FCC license: public class License { public string Name{ get; set; } public string Frn { get; set; } public string Callsign { get; set;} public string CategoryDesc { get; set; } public string ServiceDesc { get; set; } public string StatusDesc { get; set; } public DateTime ExpiredDate { get; set; } public string Id { get; set; } public string DetailUrl { get; set; } } Here is the Controller action that I am using to read the json results. I have Verizon Wireless hard-coded as the search value for now: public ActionResult GetLicenses() { var result = string.Empty; var url = "http://data.fcc.gov/api/license-view/basicSearch/getLicenses?searchValue=Verizon+Wireless&format=jsonp&jsonCallback=?"; var webRequest = WebRequest.Create(url); webRequest.Timeout = 2000; using (var response = webRequest.GetResponse() as HttpWebResponse) { if (response.StatusCode == HttpStatusCode.OK) { var receiveStream = response.GetResponseStream(); if (receiveStream != null) { var stream = new StreamReader(receiveStream); result = stream.ReadToEnd(); } } } return new ContentResult { Content = result, ContentType = "application/json" }; } Here is the view. I am trying to enumerate through all the licenses and output them to a table, but when I go to /Home/GetLicenses, it prompts me to download the file: @model IEnumerable<MvcApplication1.Models.License> @{ ViewBag.Title = "Licenses"; } <h2>Licenses</h2> <table> <tr> <th> Name </th> <th> Frn </th> <th> Callsign </th> <th> CategoryDesc </th> <th> ServiceDesc </th> <th> StatusDesc </th> <th> ExpiredDate </th> <th> DetailUrl </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Name) </td> <td> @Html.DisplayFor(modelItem => item.Frn) </td> <td> @Html.DisplayFor(modelItem => item.Callsign) </td> <td> @Html.DisplayFor(modelItem => item.CategoryDesc) </td> <td> @Html.DisplayFor(modelItem => item.ServiceDesc) </td> <td> @Html.DisplayFor(modelItem => item.StatusDesc) </td> <td> @Html.DisplayFor(modelItem => item.ExpiredDate) </td> <td> @Html.DisplayFor(modelItem => item.DetailUrl) </td> </tr> } </table> I got the above working if I do it directly through jquery's getJSON method, but I wanted to see if I could get the results from a contoller to a view and then have it rendered in the view. This is a sample of what is returned in the results variable: ?({ "status": "OK", "Licenses": { "page": "1", "rowPerPage": "100", "totalRows": "1995", "lastUpdate": "Sep 21, 2011", "License": [ { "licName": "CELLCO PARTNERSHIP (\"VERIZON WIRELESS\")", "frn": "", "callsign": "", "categoryDesc": "Satellite Earth Station", "serviceDesc": "", "statusDesc": "Active", "expiredDate": "", "licenseID": "2300007967", "licDetailURL": "http://licensing.fcc.gov/cgi-bin/ws.exe/prod/ib/forms/reports/swr031b.hts?prepare=&column=V_SITE_ANTENNA_FREQ.file_numberC/File+Number&q_set=V_SITE_ANTENNA_FREQ.file_numberC/File+Number/=/FCNNEW2000060800036" }, { "licName": "CELLO PARTNERSHIP (\"VERIZON WIRELESS\")", "frn": "", "callsign": "", "categoryDesc": "Satellite Earth Station", "serviceDesc": "", "statusDesc": "Active", "expiredDate": "", "licenseID": "2300010661", "licDetailURL": "http://licensing.fcc.gov/cgi-bin/ws.exe/prod/ib/forms/reports/swr031b.hts?prepare=&column=V_SITE_ANTENNA_FREQ.file_numberC/File+Number&q_set=V_SITE_ANTENNA_FREQ.file_numberC/File+Number/=/FCNNEW2000083100048" }, { "licName": "Cellco Partnership d/b/a Verizon Wireless", "frn": "0003290673", "callsign": "KE2XMC", "categoryDesc": "Experimental", "serviceDesc": "Experimental Developmental", "statusDesc": "Unknown", "expiredDate": "12/14/2000", "licenseID": "3000020853", "licDetailURL": "https://fjallfoss.fcc.gov/oetcf/els/reports/ELSSearchResult.cfm?callsign=KE2XMC" }, { "licName": "Cellco Partnership d/b/a Verizon Wireless", "frn": "0003290673", "callsign": "WA2XPS", "categoryDesc": "Experimental", "serviceDesc": "Experimental Developmental", "statusDesc": "Unknown", "expiredDate": "12/14/2000", "licenseID": "3000020851", "licDetailURL": "https://fjallfoss.fcc.gov/oetcf/els/reports/ELSSearchResult.cfm?callsign=WA2XPS" }, { "licName": "Cellco Partnership dba Verizon Wireless", "frn": "0003290673", "callsign": "KNKP866", "categoryDesc": "Mobile/Fixed Broadband", "serviceDesc": "Cellular", "statusDesc": "Cancelled", "expiredDate": "10/01/2005", "licenseID": "13328", "licDetailURL": "http://wireless2.fcc.gov/UlsApp/UlsSearch/license.jsp?__newWindow=false&licKey=13328" } ] } }) I added this class: public class FCC { public string status { get; set; } public Licenses Licenses { get; set; } } But I still get the Invalid JSON primitive. public ActionResult GetLicenses() { var result = string.Empty; var url = "http://data.fcc.gov/api/license-view/basicSearch/getLicenses?searchValue=Verizon+Wireless&format=jsonp&jsonCallback=?"; var webRequest = WebRequest.Create(url); webRequest.Timeout = 2000; webRequest.ContentType = "application/json"; using (var response = webRequest.GetResponse() as HttpWebResponse) { if (response.StatusCode == HttpStatusCode.OK) { var receiveStream = response.GetResponseStream(); if (receiveStream != null) { var stream = new StreamReader(receiveStream); result = stream.ReadToEnd(); } } } FCC fcc = new FCC(); if (result.StartsWith(@"?(")) { result = result.Substring(2); } if (result.EndsWith(@")")) { result = result.Remove(result.Length - 1); } if (result != null) { JavaScriptSerializer serializer = new JavaScriptSerializer(); fcc = serializer.Deserialize<FCC>(result); } return View(fcc.Licenses.License); } A: By returning a ContentResult from your ActionMethod, your browser is going to respond with the appropriate action based upon the content. In this case a JSON string will be downloaded similar to a file since it is not a HTML doc. If you want to render the results in a View and not through AJAX, then you will need to create a C# Model class representing your WebRequest response data, and then return a ViewResult and pass the model (or collection of models) to the View. I would suggest changing your ActionMethod to do something like below, and also create a View called "Licenses" Also, your example response is a bit of a trick. It is more complex than an array of your original License Object, AND it is wrapped with a ?(). The JavaScriptSerializer will only deserialize properties that it can match based on property name (it is case sensitive as well). And because of the ?() wrapping, we need to remove that so the deserialization won't break. So you would need to modify your License object accordingly: public class FCC { public string status {get;set;} public Licenses Licenses {get; set;} } public class License { public string licName{ get; set; } public string frn { get; set; } public string callsign { get; set;} public string categoryDesc { get; set; } public string serviceDesc { get; set; } public string statusDesc { get; set; } public string expiredDate { get; set; } //JSON dates and C# Dates are very finicky public string licenseID { get; set; } public string licDetailURL { get; set; } } public class Licenses { public int page {get; set;} public int rowPerPage {get; set;} public int totalRows {get; set;} public string lastUpdate {get; set;} public List<License> License {get; set;} } public ActionResult Licenses() { var result = string.Empty; var url = "http://data.fcc.gov/api/license-view/basicSearch/getLicenses?searchValue=Verizon+Wireless&format=jsonp&jsonCallback=?"; var webRequest = WebRequest.Create(url); webRequest.Timeout = 2000; using (var response = webRequest.GetResponse() as HttpWebResponse) { if (response.StatusCode == HttpStatusCode.OK) { var receiveStream = response.GetResponseStream(); if (receiveStream != null) { var stream = new StreamReader(receiveStream); result = stream.ReadToEnd(); } } } FCC fcc = new FCC(); if (result.StartsWith(@"?(")) { result = result.Substring(2); } if (result.EndsWith(@")")) { result = result.Remove(result.Length - 1); } if(result != null) { JavaScriptSerializer serializer = new JavaScriptSerializer(); fcc = serializer.Deserialize<FCC>(result); } return View(fcc.Licenses.License); //pass the data that your view needs } Lastly, you will need to change the property names in your CSHTML file, since the new License object doesn't have the same property names anymore. AJAX is probably another question, but I'll post back here if I run across a good example A: There are a couple of issues with your code which I will try to address: * *You have a controller action which returns a JSON string and you have defined some Razor view but this razor view is never invoked from the action. *You are querying a remote service which returns JSONP instead of using the JSON possibility of the API which seems more adapted. *You are jeopardizing a worker thread during the fetching of the remote resource. So let's start by our view models: public class License { public string Name { get; set; } public string Frn { get; set; } public string Callsign { get; set; } public string CategoryDesc { get; set; } public string ServiceDesc { get; set; } public string StatusDesc { get; set; } public DateTime ExpiredDate { get; set; } public string Id { get; set; } public string DetailUrl { get; set; } } public class Licenses { public License[] License { get; set; } } public class FCC { public string status { get; set; } public Licenses Licenses { get; set; } } then we would have the following controller: public class HomeController : Controller { public ActionResult Index() { using (var client = new WebClient()) { var json = client.DownloadString("http://data.fcc.gov/api/license-view/basicSearch/getLicenses?searchValue=Verizon+Wireless&format=json"); var serializer = new JavaScriptSerializer(); var model = serializer.Deserialize<FCC>(json); return View(model.Licenses.License); } } } Notice how in the url I am no longer specifying the jsonCallback querystring parameter which is intended to be used with JSONP and I don't want JSONP, I want JSON. For that matter I have also set the format=json parameter. And finally we could have the following ~/Views/Home/Index.cshtml view: @model IEnumerable<License> <table> <thead> <tr> <th> Name </th> <th> Frn </th> <th> Callsign </th> <th> CategoryDesc </th> <th> ServiceDesc </th> <th> StatusDesc </th> <th> ExpiredDate </th> <th> DetailUrl </th> <th></th> </tr> </thead> <tbody> @Html.DisplayForModel() </tbody> </table> and the corresponding display template which will be rendered for each element of the Licenses collection (~/Views/Home/DisplayTemplates/License.cshtml): @model License <tr> <td> @Html.DisplayFor(x => x.Name) </td> <td> @Html.DisplayFor(x => x.Frn) </td> <td> @Html.DisplayFor(x => x.Callsign) </td> <td> @Html.DisplayFor(x => x.CategoryDesc) </td> <td> @Html.DisplayFor(x => x.ServiceDesc) </td> <td> @Html.DisplayFor(x => x.StatusDesc) </td> <td> @Html.DisplayFor(x => x.ExpiredDate) </td> <td> @Html.DisplayFor(x => x.DetailUrl) </td> </tr> OK, so far we have addresses point 1. and 2. Now the third one. The problem with this synchronous call is the following line: client.DownloadString. This is a blocking call. Blocking calls on remote resources are very bad in ASP.NET applications. Here you are fetching some remote resource which could take time => you will be traversing network boundaries, internet firewalls, ... until you hit the remote web server which itself, in order to serve the request will query a database, ... You get the point: it is slow. And during all this time your web application is sitting and waiting and a thread was monopolized. Remember that you have a limited number of worker threads at your disposal so don't waste them. The way to solve this very serious issue is to use asynchronous controllers and I/O Completion Ports. Those are built directly into windows kernel and allow you to perform IO intensive operations without blocking and monopolizing threads on your server. Here's how your HomeController will become: public class HomeController : AsyncController { public void IndexAsync() { var client = new WebClient(); AsyncManager.OutstandingOperations.Increment(); client.DownloadStringCompleted += (s, e) => { AsyncManager.OutstandingOperations.Decrement(); if (e.Error != null) { AsyncManager.Parameters["error"] = e.Error.Message; } else { var serializer = new JavaScriptSerializer(); var model = serializer.Deserialize<FCC>(e.Result); AsyncManager.Parameters["licenses"] = model.Licenses.License; } }; client.DownloadStringAsync(new Uri("http://data.fcc.gov/api/license-view/basicSearch/getLicenses?searchValue=Verizon+Wireless&format=json")); } public ActionResult IndexCompleted(License[] licenses, string error) { if (!string.IsNullOrEmpty(error)) { ModelState.AddModelError("licenses", error); } return View(licenses ?? Enumerable.Empty<License>()); } } A: Here is what i did and its showing me Json data in DIV... Your Controller... public JsonResult GetLicenses() { var result = string.Empty; const string url = "http://data.fcc.gov/api/license-view/basicSearch/getLicenses?searchValue=Verizon+Wireless&format=jsonp&jsonCallback=?"; var webRequest = WebRequest.Create(url); webRequest.Timeout = 2000; using (var response = webRequest.GetResponse() as HttpWebResponse) { if (response != null && response.StatusCode == HttpStatusCode.OK) { var receiveStream = response.GetResponseStream(); if (receiveStream != null) { var stream = new StreamReader(receiveStream); result = stream.ReadToEnd(); } } } return Json(result,JsonRequestBehavior.AllowGet); make the return type Json and type JsonResult in Action and if you want to call this through AJAX then here is the $.ajax <script type="text/javascript"> $(document).ready(function () { $.ajax({ type: 'GET', url: '@Url.Action("GetLicenses","Home")', success: function (data) { $('#content').html(data); }, error: function (data) { $('#content').append(data); } }); }); and make sure that you reference the Jquery files in _Layout.cshtml..
{ "language": "en", "url": "https://stackoverflow.com/questions/7504910", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: windows phone 7.1/7.0 - Reading from IsolatedStorage in Application_Launching event The best practices for Windows Phone 7 says not to include any time consuming code in the Application_Launching event handler. This includes reading from IsolatedStorage. They mention to do it asynchronously. The question I have is, after launching the application, I want to take the user to his preferred screen. There are different views in my app that user can choose to keep as their preferred setting. How can I implement this scenario without reading from IsolatedStorage? Where else can I store user settings to read quickly and navigate to that screen? Any help with this is greatly appreciated because if I add code to access IsolatedStorage, it is taking longer for the app to load. Thanks. A: I'd recommend looking at using IsolatedStorageSettings to hold this but having an animated loading page displayed while you query this and which then triggers navigation to the actual page the users wants when known. The page(s) you navigate to should then remove the loading page from the backstack.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Page can't render when running from Home Screen on iPad I have a web app that runs on an iPad with no problem. However, in Safari, when I'm on the page and choose "Add to Home Screen" then click the icon to open the page, I get the following error: This page contains the following errors: error on line 1 at column 2: StartTag: invalid element name Below is a rendering of the page up to the first error. It's blank after the error since it is occurring on line 1. Why would it work when running it within the browser but not when running it from the home screen? I was under the assumption that it still used the Safari engine either way. A: I think this might actually be a generic IIS / .NET error rather than a Safari rendering error. Maybe you can capture the User-agent string from fullscreen iPad Safari and see if it differs from regular Safari. From there you could spoof it into Firefox / Chrome and see what happens next.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504915", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting mouse down event on superview I have an NSScrollView and its document view is an NSView subview titled MasterPage. On MasterPage I have a bunch (depending on user input) of subviews (from a class called Page).They are laid out in a grid format. I'm trying to capture the NSPoint of the mouse click on MasterPage. It works where there are no subviews but if the point clicked is within the area of a subview then the superview does not register it. Is there a way to do this? I hope that makes sense. The red area registers a mouse click in the superview's .m file. The four subviews do not. A: In your MasterPage class, you could override NSView's -hitTest: method and have it return self rather than one of the Page subviews. See Event Handling Guide: The Path of Mouse and Tablet Events. In this example project, http://www.markdouma.com/developer/SubviewSuperview.zip, you can watch the logging calls to see what NSView receives the events. If you hold down the Alt/Option key and click, the white view will override -hitTest: and return itself, preventing the gray views from receiving the event.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create a DIV with vertical scrollable contents and fixed footer which is always visible? The HTML should be sth like the following (sorry for the format and formatting but I do not know how to post HTML sample) <div id="dialog-window"> <div id="scrollable-content"> what ever content here...div's, ul's and li's </div> <div id="footer"> </div> </div> The result i'm looking for is to always have a vertical scrollbar only for the content and the footer should be always visible at the bottom of the dialog-window. The dialog-window is a fixed size dialog. I have tried with some ideas from other posts here but do not fit all requirements. Any ideas to do this using CSS (js and jquery also welcome) A: How about something like the below? Just create a container which holds two divs one for the scrollable content and one for the footer. Fix all the heights and make the content div scrollable. CSS (I won't charge for my expert color choices): #dialog-window { height: 200px; border: 1px black solid; } #scrollable-content { height: 180px; overflow: auto; background-color: blue; } #footer { height: 20px; background-color: green; } Example of HTML <div id="dialog-window"> <div id="scrollable-content"> <ul> <li>Sample</li> <li>Sample</li> <li>Sample</li> <li>Sample</li> <li>Sample</li> <li>Sample</li> <li>Sample</li> <li>Sample</li> <li>Sample</li> <li>Sample</li> <li>Sample</li> <li>Sample</li> <li>Sample</li> </ul> </div> <div id="footer"> </div> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7504918", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Mysql Group by column names I've written a query where I select the likes and the dislikes out of a column. I get the results but now I want to add a name to each of the grouped result, is this possible ? Table structure: id , snippet_id , user_id , kind the query: SELECT COUNT(v) as likes FROM Vote v GROUP BY v.kind The result I get: array(0 => 10, 1 => 3); I want a result like this: array('likes' => 10, 'dislikes' => 3); A: Add v.kind to your field list: SELECT v.kind, COUNT(v) as likes FROM Vote v GROUP BY v.kind A: I think you use mysql_fetch_array to get your results, you have to use mysql_fetch_assoc I hope to help you. A: You can return an associative array using mysql_fetch_assoc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it defined to provide an inverted range to C++ standard algorithms? Consider standard algorithms like, say, std::for_each. template<class InputIterator, class Function> Function for_each(InputIterator first, InputIterator last, Function f); As far as I can tell, there is actually no requirement placed on the relative states of the two InputIterator arguments. Does that mean that the following is technically valid? Or is it undefined? What can I realistically expect it to do? std::vector<int> v{0,1,2,3,4}; std::for_each( v.begin()+3, // range [3,0) v.begin(), [](int){} ); geordi tells me: error: function requires a valid iterator range [__first, __last). [+ 13 discarded lines] but I can't tell how compliant this debug diagnostic is. I came up with this question when trying to pedantically determine how explicit is defined the behaviour of the following: std::vector<int> v; // <-- empty std::for_each( // <-- total no-op? stated or just left to implication? v.begin(), v.end(), [](int){} ); A: The result is Undefined. C++03 Standard: 25.1.1 For each and C++11 Standard: 25.2.4 For each states: template<class InputIterator, class Function> Function for_each(InputIterator first, InputIterator last, Function f); 1 Effects: Applies f to the result of dereferencing every iterator in the range [first, last), starting from first and proceeding to last - 1 While another section defines the valid range [first,last) as: C++03 Standard: 24.1 Iterator requirements and C++11 Standard: 24.2.1 Iterator requirements Para 7 for both: Most of the library’s algorithmic templates that operate on data structures have interfaces that use ranges.A range is a pair of iterators that designate the beginning and end of the computation. A range [i, i) is an empty range; in general, a range [i, j) refers to the elements in the data structure starting with the one pointed to by i and up to but not including the one pointed to by j. Range [i, j) is valid if and only if j is reachable from i. The result of the application of functions in the library to invalid ranges is undefined. Having remembered of reading this somewhere, just browsed through: C++ Standard Library - A Tutorial and Reference - By Nicolai Josutils This finds a mention in: 5.4.1 Ranges The caller must ensure that the first and second arguments define a valid range. This is the case if the end of the range is reachable from the beginning by iterating through the elements. This means, it is up to the programmer to ensure that both iterators belong to the same container and that the beginning is not behind the end. If this is not the case, the behavior is undefined and endless loops or forbidden memory access may result. A: The standard explicitly requires the last iterator to be reachable from the first iterator. That means that by incrementing first one should be able to eventually hit last. 24.1 Iterator requirements ... 6 An iterator j is called reachable from an iterator i if and only if there is a finite sequence of applications of the expression ++i that makes i == j. If j is reachable from i, they refer to the same container. 7 Most of the library’s algorithmic templates that operate on data structures have interfaces that use ranges. A range is a pair of iterators that designate the beginning and end of the computation. A range [i, i) is an empty range; in general, a range [i, j) refers to the elements in the data structure starting with the one pointed to by i and up to but not including the one pointed to by j. Range [i, j) is valid if and only if j is reachable from i. The result of the application of functions in the library to invalid ranges is undefined. A: Does that mean that the following is technically valid? Or is it undefined? What can I realistically expect it to do? No it is not. Your code would exhibit undefined behavior when for_each increments the iterator and that iterator would be pointing to end and there is nothing to dereference(Well, it is enough to get undefined behavior at this point, so there is no point talking about past end)! A: This is explained by section 24.1 of the standard, "Iterator Requirements": An iterator j is called reachable from an iterator i if and only if there is a finite sequence of applications of the expression ++i that makes i == j. If j is reachable from i, they refer to the same container. … Range [i, j) is valid if and only if j is reachable from i. The result of the application of functions in the library to invalid ranges is undefined. So v.begin() + 3 is reachable from v.begin(), but not the reverse. So [v.begin()+3, v.begin()) is not a valid range, and your call to for_each is undefined. A: The standard defines complexity constraints for the functions taking ranges. In the specific case of for_each (25.2.4 in the C++ standard): Complexity: Applies f exactly last - first times So it's effectively a no-op in your example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Where is the default authentication route configured in ASP.NET MVC? I've got an old WebForms-based ASP.NET app that I have upgraded to ASP.NET 4.0 and I want to add some portions of the site that use MVC. I've successfully done this but the problem is I want to share the old login page. I used the instructions here to integrate MVC. Both parts of the site use the SqlMemberbershipProvider, but even though my web.config is configured to route unauthenticated requests to my "~/Login.aspx" page, they are now getting kicked to "Accounts/Login". Here's my web config auth entry: <authentication mode="Forms"> <forms loginUrl="login.aspx" name=".ASPXFORMSAUTH" /> </authentication> Where in the MVC plumbing does it now override that to force it to "Accounts/Login". is this just a "convention" used by MVC? The upshot is I still want to redirect unauthenticated requests to Login.aspx no matter what the target page/route is. Mike A: That's a known bug. You may try adding the loginUrl app key following to your web.config: <appSettings> <add key="loginUrl" value="~/login.aspx" /> <appSettings>
{ "language": "en", "url": "https://stackoverflow.com/questions/7504926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a Case invariant way to compare string with a Enum in Enum.IsDefined / Enum.Parse So if you don't have access to an Enum or control over a string that is to be compared with enum values, is there a better or cleaner way than the below code to get the value of the Enum that matches and use it in a call to: Enum.IsDefined() or Enum.Parse() Example: var enumValues = Enum.GetValues(typeof(someType)); foreach (var value in enumValues) { if (value.ToString().ToLowerInvariant() == stringToCompare.ToLowerInvariant()) { stringToCompare = value.ToString(); } } Which at this point if there was a match you would have the correct enum value that you could then use in either (Enum.IsDefinied() or Enum.Parse()) Is there a better way than what I defined? A: someType varName = Enum.Parse(typeof(someType), stringToCompare, true); Using this overload of enum.Parse()
{ "language": "en", "url": "https://stackoverflow.com/questions/7504928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sending messages from multiple servers to one Service Broker Queue I have a couple of SQL servers with databases supporting two different applications. I need to capture changes to similar data from each database, but process it sequentially. Service Broker fits the bill, I just have a couple of implementation questions. I've created a "third" database for extending the two applications. On this database, I've enabled service broker, created a message schema, contracts, service and queue. If I want to send messages of this type //mysite.com/extensions/message to an ExtensionsQueue on EXTENSIONSERVER.Database from LEGACYSERVER.Database, do I need to run the SQL statements to create those pieces (schema, contract, message, etc) in each database I want to talk to this queue from? It seems that, minimum, I would need the message schema in each database to force integrity. Assuming I need to (which only seems to make sense) should I name the services, queues, etc on each server the same, or will that cause issues? For example, should I name the service on the EXTENSIONSERVER something like //extensionserver/extensions/message and //legacyserver/extensions/message? Do I even need to create a service and queue on LEGACYSERVER or would a route like this take care of it? CREATE ROUTE WITH SERVICE_NAME = '//extensionserver/extensions/message', ADDRESS = 'extensionserver:1433' A: This actually turned out to be quite a setup. I ended up mostly following this tutorial. One key point that it didn't mention though was routes for external database instances need to be in the MSDB database.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problem With Using Elements Of An String i have this code for example: string i = "100"; if(i[1]==0) { MessageBox.Show("ok"); } and I thought I should get "ok" but it doesnt work. What is i[1] here? A: Your comparison is using the wrong type. When you use an indexer with a string, the result is a char. Your if statement is using an int. You need to change your code to: if(i[1] == '0') { MessageBox.Show("Ok"); } A: You're comparing a string to an integer. Try if (i[1] == '0'). A: i[1] is a char of '0' (Unicode U+0030), which is different than (int) 0. A: char i[0] is compared against an integer A: i[1] is the second character in the string, as arrays in c# are zero-based.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to determine if the combobox selectionchangecommitted was raised by keyboard or mouse input I want the ignore the up and down arrow keys on the SelectionChangeCommitted event of a combo box and only have the mouse allow selection. Does anyone know how to do this? I need a way to determine whether key or click caused the SelectionChangeCommitted event. I guess I could have a flag that turns on in a mouseclick event and off in a key down, but I wondered if there was a cleaner way? A: You should be able to handle the KeyPress event for your combobox, and cancel (e.Canceled = true;) it. This will also prevent the combobox item from changing when you hit a key that matches the first letter of an item. A: You can suppress the key by using the KeyDown event like this; private void comboBox1_KeyDown(object sender, KeyEventArgs e) { e.SuppressKeyPress = true; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7504934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Interactively manipulating a rectangle on a matlab figure I would like to draw and manipulate a rectangle on a matlab figure. By manipulating, I mean I want to drag, rotate, resize (change side lengths) the rectange with "intuitive" mouse clicks. I have not found any built in mechanism for doing this. (Property editor? Or matlab function? Or matlab file exchange?) Maybe I can't google well. So, in order to write my own, it looks to me like the buttonDownFcn on the rectangle function is a start for this. That is, I can use this to listen to mouse clicks on the rectangle itself, but what about mouseclicks on the inside of the rectangle? I can't figure out how to receive them. What about a "buttonUpFcn" don't see one of those. What about when I move the cursor around, I see no way to capture those (unless I start querying the figure instead of the rectangle, but that gets to be a huge hassle, and very complicated I would think.) Thanks for your consideration. John A: If you don't absolutely need rotation, IMRECT will do what you want. Also, if you need to be able to draw oblique lines, IMPOLY, could be helpful, though you may need to write a POSITIONCONSTRAINFCN to guarantee that you're drawing right angles. A: One way to do it is to store the location of the top-left and bottom-right rectangle corners and use those to determine whether clicks are inside or outside the rectangle. Those corners will give you the [xmin ymin] and [xmax ymax] values of the rectangle, and you can simply compare the location of the click to those values to determine whether the click is inside or outside the borders.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504940", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Javascript programming model to organize Web Applications I have been programming in PHP and C# for a long time, but I have done very little Javascript. For server side programming I use MVC, which is very nice and my code is neatly organized. Now, for Javascript, when I write code, I usually screw things up. It becomes something like spaghetti code. I don't know how to organize my code. Can anyone please help me with any resource, book, or anything which might help with writing neat and organized Javascript code? Thanks in advance. A: You mention that you have been programming in PHP and C# for a long time. Take your code organization experience and apply it to your javascript. Couple of frameworks Google's Closure tools - http://code.google.com/closure/ If Google uses it to organize Gmail and Google Docs, then it should work for most large applications. Also, Yahoo! YUI is good too - http://developer.yahoo.com/yui/ http://yuilibrary.com/ And backbone.js (not as "big" as Google or Yahoo) - http://documentcloud.github.com/backbone/ https://github.com/documentcloud/backbone Decent Book For me, writing javascript unit test helps me stay organized - Test-Driven JavaScript Development http://www.amazon.com/Test-Driven-JavaScript-Development-Developers-Library/dp/0321683919/ A: Write modular code. It's not very hard. Personally I recommend you write very many modules and user a building process and package manager to append them into one. I use browserify for that. // DOM-utils.js module.exports = { // util methods } // some-UI-Widget.js var utils = require("DOM-utils"), jQuery = require("jQuery"); // do ui logic module.exports = someWidget I would go further and recommend you use a mediator pattern (see mediator) to keep all your code loosely coupled. See this example application A: JavaScript: The Good Parts http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742 Plus any Crockford videos from YUI Theater. http://yuilibrary.com/theater/ A: Not sure if a library suggestion is what you're after, but we started using Mootools as our base js library. Mootools' Class system is amazing for creating a class hierarchy. It's helped our team out immensely in keeping all our code organized. If you're looking for simpler object-oriented solutions and need inheritance there are many, many libraries offering this. Two of my favorite are klass and selfish.js. A: Here is an excellent reference. It is difficult to avoid spaghetti in Javascript at times. Also be aware that Javascript does NOT support Polymorphism. http://dev.opera.com/articles/view/javascript-best-practices/ A: Alex MacCaw wrote a book just out, JavaScript Web Applications that covers some of the JavaScript frameworks available. MacCaw is the creator of Spine, another MVC JavaScript framework (like backbone.js is). There are tutorials on the Spine site covering how to use it. Additionally, if you're interested in backbone.js, Peepcode currently has two screencasts (not free) that cover using it. A: Check these articles out and you will get good ideas on how to use OOP in JavaScript: http://www.cyberminds.co.uk/blog/articles/polymorphism-in-javascript.aspx http://www.cyberminds.co.uk/blog/articles/how-to-implement-javascript-inheritance.aspx Regards, Joe
{ "language": "en", "url": "https://stackoverflow.com/questions/7504947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: PHP date of birth checker I am currently using the following PHP code to check date of birth, the code uses the american mm/dd/yyyy although I'm trying to change it to the british dd/mm/yyyy. I was hoping someone could tell me what to change: function dateDiff($dformat, $endDate, $beginDate) { $date_parts1=explode($dformat, $beginDate); $date_parts2=explode($dformat, $endDate); $start_date=gregoriantojd($date_parts1[0], $date_parts1[1], $date_parts1[2]); $end_date=gregoriantojd($date_parts2[0], $date_parts2[1], $date_parts2[2]); return $end_date - $start_date; } //Enter date of birth below in MM/DD/YYYY $dob="04/15/1993"; echo round(dateDiff("/", date("m/d/Y", time()), $dob)/365, 0) . " years."; A: the explode is breaking up the string into an array, it is using the / as the separator. So for us dates you would get $date_parts1[0] = 04 $date_parts1[1] = 15 $date_parts1[2] = 1993 what you want is to swap the values at index 0 and 1. try this: $start_date=gregoriantojd($date_parts1[1], $date_parts1[0], $date_parts1[2]); $end_date=gregoriantojd($date_parts2[1], $date_parts2[0], $date_parts2[2]); Edit, added correction from comment: also change the last line to echo round(dateDiff("/", date("d/m/Y", time()), $dob)/365, 0) . " years."; A: It will be better to use timestamp when saving dates. echo time(); \\ 1316631603 (Mumber of seconds since the Unix Epoch - January 1 1970 00:00:00 GMT) It will give you a better control as the format is always in seconds. It is also easy to format to any date format, sort and perform calculations. echo date("m/d/Y", 1316631603); // as US format (09/21/2011) echo date("d/m/Y", 1316631603); // as British and Danish format (21/09/2011) If you choose to use timestamp the answer to your question is: $user_bdate = date_create_from_format("m/d/Y", "11/30/1978")->format('U'); // Convert a US date to timestamp $time_diff = time() - $user_bdate; // Take current date and subtract the birth date echo (int) ($time_diff / (365 * 24 * 60 * 60)) . " years."; // 43 years. Referrer: * *php - What is a Unix timestamp and why use it? - Stack Overflow *PHP: time - Manual *PHP: date - Manual *PHP: date_create_from_format - Manual A: If you only need a function to return the years given the birthday on that specific format you could use something like this to avoid passing much data on the function call: <?php function get_age($birthdate){ list($d, $m, $y) = explode('/', $birthdate); $time_birth = mktime(0, 0, 0, $m, $d, $y); return round( (time() - $time_birth) / (60*60*24*365) ) ; } //example, use dd/mm/yyyy $dob="04/15/1993"; echo get_age($dob). " years."; ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7504955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SSIS: Intergrating two servers So I have two servers. SER1, SER2. SER1 is the one from where I am supposed to copy the data and put it in SER2. Also I have few stored procs on SER2 that I need to execute and then put back the desired results in a different table on SER1. Now, I need 2 more stored procs. 1. to copy basic data from SER1 to SER2 and other for copying all DATA from SER2 to SER1. Question: * *On which server should I make these stored procs ? *I am supposed to make a SSIS package which can run ALL SP's so SSIS package is taking care of copying data from SER1 to SER2 ? (i dont have linked servers) A: Yes you can execute stored procs as data sources without having a linked server in SSIS. However, you cannot use temp tables in the stored proc. I have gotten aorund this by using derived tables or CTEs. The proc should only be a select not an action proc. You want the proc to be inthe location where you can run it from SSMS. SO if it referces tables in server a, database b, that is where it needs to be. In SSIS you create a connection to each database you want o beable to use as either a source or destination. Then create a data flow and use the database containing the proc you want to run as the source connection in an OLE DB source connection. Set the data Accessmode to SQL Command and put the exec statemenet to run the proc inteh SQL Command text. If you need need input parameters, click on the parameter button to do that. Now check the columns tab. If no columns appear, your stored proc needs adjustment to make it work as a connection. Then select the connection for the database you want to put the data in as the destination connection. and tell it what table and do the mappings. A: First, you need linked servers, I dont understand what you mean by "I dont have linked servers" - with that you need to create a linked server. For 1) You write the stored procedure based on the logic, if you have two servers 1 and 2 and you want to copy data from server 1 to server 2 then server 1 should logically contain the stored procedure. Does it have to be this way, no absolutely not, it can be on server 2, but think logically about this. For 2) You need a linked server, how else can you execute ServerName.DbName.Owner.Table ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7504956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Usage of subqueries in RFC_READ_TABLE OPTIONS Is it possible to use subqueries in the OPTIONS parameter table for the RFC_READ_TABLE in SAP? Something like this field in (select otherfield from othertable where ...) A: No. Specifying an OPTIONS parameter which contains parentheses will cause an error (ABEND dump). From the SAP doco (4.6C): WHERE (itab) The internal table itab may only have one field. This must have type C, and may not be longer than 72 characters. You must specify itab in parentheses, without a space between the parentheses and the table name. The condition contained in the internal table must have the same form as a corresponding condition in the ABAP source code. The following restrictions apply: - You can only use literals as values, not variables. - You cannot use the IN operator in the form f1 IN itab1. The internal table itab may be empty.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504963", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Where is the exe file from MonoDevelop? I just made a project and it runs in MonoDevelop, but I would like to run it myself from commandline so I know I can just give the exe file onwards and I can't find the exe file for it. So is there some special place I should look for it? A: I couldn't find a better link that than these two - http://mono.1490590.n4.nabble.com/Copying-files-to-output-directory-in-MonoDevelop-td1514760.html http://lists.ximian.com/pipermail/monodevelop-list/2009-January/008833.html But it seems to suggest the output can be configured by you. You can see it in the .csproj file. The default appears to be ../ProjectFolder/Bin/Release/ or ../ProjectFolder/Bin/Debug/
{ "language": "en", "url": "https://stackoverflow.com/questions/7504964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can someone explain the attr? I am looking at the Honeycomb Gallery sample code (here) and I ran across the following code while trying to add action items in my own app: <item android:id="@+id/camera" android:title="Camera" android:icon="?attr/menuIconCamera" android:showAsAction="ifRoom" /> The ?attr is throwing me for a loop. Can someone please explain what this is doing? How is this related to a drawable? I can't seem to find any good information on Google. Also is there a listing or gallery of attributes we can use for icons instead of just menuIconCamera? Thanks Edit: I did some more looking around and found that attrs.xml looks like this: <resources> <declare-styleable name="AppTheme"> <attr name="listDragShadowBackground" format="reference" /> <attr name="menuIconCamera" format="reference" /> <attr name="menuIconToggle" format="reference" /> <attr name="menuIconShare" format="reference" /> </declare-styleable> Unfortunately that just makes it even more confusing for me. What is this doing? A: The ?attr/menuIconCamera value means that an icon from menuIconCamera attribute of the current theme will be used. There must be a drawable assigned to the menuIconCamera attribute somewhere in the themes.xml file. If there're two themes with different values of this attribute then actual icon will depend on a theme which is currently used. The attrs.xml file is used to define custom attributes. Without this definition compiler will treat unknown attributes as erroneous. A: The ?attr: syntax is used for accessing attributes of current theme. See referencing style attributes. A: This is for refering style Attributes. see R.attr ?[<package_name>:][<resource_type>/]<resource_name> Referencing style attributes A: This blog post does an amazing job going over how to reference values for style-attributes that are defined in the current theme: https://trickyandroid.com/android-resources-and-style-attributes-cheatsheet/ * *When you see ? notation - it means that we are trying to reference a style attribute - a value which may vary depending on current theme. In each specific theme we can override this attribute, so the XML layout doesn't need to be changed, and the correct theme needs to be applied. *When you see the @ notation - we reference actual resource value (color, string, dimension, etc). This resource should have an actual value. In this case we know exactly what value we are dealing with. Here's an example: <style name="AppTheme" parent="Theme.AppCompat.NoActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> <style name="LauncherButton" parent="TextAppearance.AppCompat.Medium"> <item name="android:textColor">?colorAccent</item> <item name="android:layout_width">match_parent</item> <item name="android:layout_height">wrap_content</item> <item name="android:layout_centerHorizontal">true</item> <item name="android:textAllCaps">false</item> </style> A: I know this post is very old, but I feel the following explanation will help beginners understand it easily. So in layman's terms, someAttribute="?attr/attributeName" means - set the value of someAttribute to whatever is the value of attributeName in current theme A common example occurs in styling a Toolbar <style name="AppTheme" parent="@style/Theme.AppCompat.Light.NoActionBar"> <item name="colorPrimary">@color/primary_color</item> //some more stuff here </style> <!-- custom toolbar style --> <style name="myToolbar" parent="Widget.AppCompat.Toolbar"> <item name="android:background">?attr/colorPrimary</item> //some code here </style> Here value of android:background will be set to @color/primary_color because ?attr/colorPrimary refers to @color/primary_color in the current theme (AppTheme) A: My English is not good, sorry. But I know this question android:icon="?attr/menuIconCamera" want use attrs.xml <resources> <declare-styleable name="AppTheme"> <attr name="listDragShadowBackground" format="reference" /> <attr name="menuIconCamera" format="reference" /> <attr name="menuIconToggle" format="reference" /> <attr name="menuIconShare" format="reference" /> </declare-styleable> </resources> styles.xml <style name="AppTheme.Light" parent="@android:style/Theme.Holo.Light"> <item name="android:actionBarStyle">@style/ActionBar.Light</item> <item name="android:windowActionBarOverlay">true</item> <item name="listDragShadowBackground">@android:color/background_light</item> <item name="menuIconCamera">@drawable/ic_menu_camera_holo_light</item> //this.... <item name="menuIconToggle">@drawable/ic_menu_toggle_holo_light</item> <item name="menuIconShare">@drawable/ic_menu_share_holo_light</item> </style> use @drawable/ic_menu_camera_holo_light
{ "language": "en", "url": "https://stackoverflow.com/questions/7504967", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "91" }
Q: Solr Searching Multivalued Fields I have a multivalued field that appears like this : <arr name="some_name"> <str>a-value-1 a-value-2 ....a-value-n</str> <str>b-value-1 b-value-2 ....b-value-m</str> </arr> where n and m could be arbitrarily large(assume values in each <str> come from a paragraph in a page or something). How would I search so that the result contains only the documents where all search parameters are contained in the same <str> entity(That is without generating any false positive)? For instance if the document A has this : <arr name="some_name"> <str>london foo-1 foo-2 ...foo-k 2012 foo-k+1 foo-k+2 ...foo-k+n</str> <str>beijing bar-1 bar-2 ....bar-j 2008 bar-j+1 bar-j+2 ....bar-j+m</str> </arr> what will be the query that would not include document A in the result when searching for the words london AND 2008? If I were to try something like this some_name:("london AND 2008"~n), I don't know what the value of n would be. A: Consider using a high positionIncrementGap, which will help to separate the multivalued tokens and cross matching across different multivalued entries. However, even this wont be a foolproof solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ext JS - Cell with multiple values, with "list" of combo boxes I'm using the Ext JS Grid component, and I've got the following fields (along with their datatypes): ID (int) Name (string) Foods (List<string>) As defined, there can be multiple Foods per user, and each food is selected from an existing Food DataStore. Displaying the Food list in the cell is easy; I just use a custom renderer. The potentially complicated part is editing those foods. Whenever a user edits the Foods cell, I'd like a combo box to appear for each food item, populated from the Foods DataStore. I'll also need the user to be able to add/delete Food items, which means I'll need a small form of some sort. Could anyone tell me the best way to accomplish this? I've perused the documentation on Ext JS (though perhaps not well-enough), but I was unable to find a good solution. I'm still fairly new to it. Any help/suggestions are much appreciated. Thanks, B.J. A: my suggestion would be to take editing functionality out of your grid and use it only to show data. you can edit them easily with a Ext.msg popup shown after rowclick or rowdblclick event had been fired. inside Ext.msg you can use some html tags. you can also follow this link to learn about capturing cellclick event. A: I did something similar to this, but without being able to add/delete items. In your grid, you'll want to set the editor for the column in question to a combobox. I don't think you'll need to bother with changing the renderer at all, the combobox should take care of it for you. xtype: 'grid', store: Ext.create('MySite.store.UserStore'), columns: [ { header: 'ID', dataIndex: 'id' }, { header: 'Name', dataIndex: 'name' }, { header: 'Foods', dataIndex: 'foods', minWidth: 200, editor: { xtype: 'combobox', store: Ext.create('MySite.store.FoodStore'), valueField: "food", displayField: "food", editable: true, maxHeight: 150, width: 310, multiSelect: true } } ], selType: 'cellmodel', plugins: [ Ext.create('Ext.grid.plugin.CellEditing', { clicksToEdit: 1 }) ] The store that populates the grid (I called mine UserStore here) will need to use a type of 'auto' for the List field. Ext.define('MySite.store.UserStore', { extend: 'Ext.data.Store', storeId: 'UserStore', autoLoad: true, fields: ['id', 'name', { name: 'foods', type: 'auto' }], proxy: { type: 'ajax', url: // your data provider reader: { type: 'json', root: 'items', successProperty: 'success', messageProperty: 'message' } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7504970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Pydev-pylint fix all errors at once I am using the pylint plugin in pydev (eclipse) to check for static errors in my code. Often there will be same type of errors in many places, for example, unused variable i. Is there a way to execute one corrective step for all such cases instead of going to each error location. In this case I would like to rename any such unused variable as dummy, all at once. There are other similar errors like unnecessary semi-colons (I also code a lot of c++ :( ) and unused imports, which I want to delete all at once. Thank you! A: Unfortunately, there are currently no such quick-fixes in PyDev. Please report that as a feature request.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: WP7 - Bind an ItemsControl item to a VM property containing HTML string I'm displaying a list of data in an ItemsControl. I'm binding my ItemsControl to an ObservableCollection of a ViewModel representing each item. In the item's ViewModel, there is a property containing HTML as a string, which I'd like to display as rich text as in a WebBrowser control. I'm relatively new to WP7, so I'm looking up how to handle this. What I've found so far is that I need a WebBrowser control and call NavigateToString on it. My problem is that this needs to be displaying as a list item which I have defined in a DataTemplate. Is there a way to handle this with bindings? Is there another way besides WebBrowser to display strings with HTML formatting? A: Another way to display strings with HTML formatting is to parse the strings with your own code transforming it to a Xaml string that has the approximate formatting. How close you can get the generated Xaml to the HTMLs intended rendering will vary on the effort put in. For example it should be fairly easy to replace <b>..</b> with <run FontWeight="Bold">..</run>. Much depends on how sophisticated the input HTML strings are.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Deserializing JSON as a Generic List I have a filter string as shown in the below format: {"groupOp":"AND","rules":[{"field":"FName","op":"bw","data":"te"}]} I need to deserialize this as a Generic list of items. Can anyone guide me on how to do this? A: Have a look at JSON.NET. It allows you to do things like: JObject o = new JObject( new JProperty("Name", "John Smith"), new JProperty("BirthDate", new DateTime(1983, 3, 20)) ); JsonSerializer serializer = new JsonSerializer(); Person p = (Person)serializer.Deserialize(new JTokenReader(o), typeof(Person)); Console.WriteLine(p.Name); // John Smith Source: the documentation. A: Try using the JavaScriptSerializer class like so: Deserialization code using System.Web.Script.Serialization; ... string json = "{\"groupOp\":\"AND\",\"rules\":[{\"field\":\"FName\",\"op\":\"bw\",\"data\":\"te\"}]}"; JavaScriptSerializer serializer = new JavaScriptSerializer(); Filter filter = (Filter)serializer.Deserialize<Filter>(json); Classes public class Filter { public string GroupOp { get; set; } public List<Rule> Rules { get; set; } public Filter() { Rules = new List<Rule>(); } } public class Rule { public string Field { get; set; } public string Op { get; set; } public string Data { get; set; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7504999", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NHibernate 1.2 Id Generated by Database Trigger In NHibernate 1.2 is it possible to have the ID generated by a database trigger? Basically we need to change one of our tables to stop using a sequence and instead use a trigger to generate the primary key. So obviously I need to update the nhibernate mapping to use a different generator class but I'm not sure what class I should use, or even if this is supported in 1.2. Any help would be greatly appreciated. Thanks! A: NHibernate allows you to do this but only starting from 2.1.0: trigger-identity The “trigger-identity” is a NHibernate specific feature where the POID is generated by the RDBMS at the INSERT query trough a BEFORE INSERT trigger. In this case you can use any supported type, including custom type, with the limitation of “single-column” (so far)... select The “select” generator is a deviation of the “trigger-identity”. This generator work together with natural-id feature. The difference “trigger-identity” is that the POID value is retrieved by a SELECT using the natural-id fields as filter... If you don't want to upgrade to later versions of NHibernate (because of .NET 1.1?) then you can try Ayende's custom dialect solution or extend NHibernate as suggested here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505001", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Customize Django admin index page to display model objects In the Django admin index page, the app and its models will normally be listed. How can the model objects also be listed in this index page? Instead of displaying just the app, I want to also display its model objects. How should it be customized? A: UPDATE Setomidor answer for django 10 Always great to come back to this clean solution! step 2 - it is around line 125 (was 52) step 3 - in sites.py - update the new method - _build_app_dict inside the for loop : for model, model_admin in models.items(): add step 3 as said around lines 430 and 460 instances = [] if (model._meta.list_instances == True): instances = model_admin.get_queryset(None) A: I wanted the same functionality for my site and added it by doing slight modifications to the core django system. Step 1: First we need a way to indicate which models should have their properties listed. Add the following code to the models for which you want the instances listed (in models.py): class Meta: list_instances = True Step 2: We need to modify Django to recognize and read this new attribute. In core-django file: db/models/options.py, roughly at line 22 append 'list_instances' to DEFAULT_NAMES: DEFAULT_NAMES = ('verbose_name', 'verbose_name_plural', 'db_table', 'ordering', 'unique_together', 'permissions', 'get_latest_by', 'order_with_respect_to', 'app_label', 'db_tablespace', 'abstract', 'managed', 'proxy', 'auto_created', 'list_instances') and in the same file, roughly at line 52, create a default field for this attribute right after the other attributes : self.list_instances = False Step 3: We need to pass this information along to the template that generates the index page. In core-django file: contrib/admin/sites.py, inside index() method and inside the "if has_module_perms:" part, add the following code: instances = [] if (model._meta.list_instances == True): instances = model_admin.queryset(None) This will create the list of instances to show, but only if the list_instance attribute is set. In the same file, a few lines further down, append these values to the "model_dict" construct. model_dict = { 'name': capfirst(model._meta.verbose_name_plural), 'admin_url': mark_safe('%s/%s/' % (app_label, model. __name__.lower())), 'perms': perms, 'list_instances':model._meta.list_instances, 'instances': instances, } Step 4: The final step is to modify the template to support this. Either edit the core-django file /contrib/admin/templates/admin/index.html or copy this file to the templates/admin/ directory of your specific app. Add a few lines after the standard code for generating rows to generate the "sub-rows" if applicable. Roughly at line 40, right between "/tr>" and "{% endfor %}": {% if model.list_instances %} {% for instance in model.instances %} <tr> <td colspan="2" style="padding-left: 2em;">{{ instance }}</td> {% if model.perms.change %} <td><a href="{{ model.admin_url }}{{ instance.id }}/" class="changelink">{% trans 'Change' %}</a></td> {% else %} <td>&nbsp;</td> {% endif %} </tr> {% endfor %} {% endif %} This will cause the item to be listed with the name generated by the unicode() method in the model. Step 5: Lo and behold! It should look something like this: Edit: Optional Step 6: If you want the instance names to be clickable too, just change the template (index.html) and replace: <td colspan="2" style="padding-left: 2em;">{{ instance }}</td> with: <td colspan="2" style="padding-left: 2em;"> {% if model.perms.change %} <a href="{{ model.admin_url }}{{ instance.id}}">{{ instance }}</a> {% else %} {{ instance }} {% endif %} </td> A: You can do this by changing the various admin templates - the root one is called app_index.html and controls what gets displayed there. The best way to investigate what's happening where is to install django-debug-toolbar and then look at the templates being used for each view to figure out how to customise.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Can I use a hashmark in .htaccess URL? I'm using jquery address and everything is working great except for one small issue inside my .htaccess file. I'd like to redirect one of my urls that includes a hashmark to another URL. Here is my current setup using redirect (that works): Options +FollowSymLinks RewriteEngine on RewriteRule view_profile=(.*)$ view_profile.php?id=$1 If a user logs in at any point this URL doesn't work because my jquery address looks like this: http://localhost/#view_profile=5 If I add the leading hash as part of my rewriterule it breaks. Does anyone know if it's possible to use a leading hashmark as part of the URL? A: No you can't do this, as anything after the # is a fragment identifier and therefore not sent to the server. See the RFC on URIs here: https://www.rfc-editor.org/rfc/rfc3986#section-3.5
{ "language": "en", "url": "https://stackoverflow.com/questions/7505008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Resteasy/JAX-RS URL Encoding @PATH I am trying to build a client for a restful webservice with Resteasy. The issue is with my client code(below) @Path("solr") public interface TestClient{ @GET @Path(value="select?indent...") @Produces("application/xml") ClientResponse<String> getStuff(); } The problem is that the ? in the @Path annotation is automatically URL encoded to a %3F. This is in keeping with the javadocs here, but it's causing me to get 404 errors. I tried overriding this with the encode=false here but that just creates compiler errors. Is there a way to override or escape this? A: Why do you think you need a ? in the Path? It seems like @QueryParam is what you'd want instead. See http://docs.jboss.org/resteasy/docs/1.0.1.GA/userguide/html/RESTEasy_Client_Framework.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7505009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bulk ingest into Redis I'm trying to load a large piece of data into Redis as fast as possible. My data looks like: 771240491921 SOME;STRING;ABOUT;THIS;LENGTH 345928354912 SOME;STRING;ABOUT;THIS;LENGTH There is a ~12 digit number on the left and a variable length string on the right. The key is going to be the number on the left and the data is going to be the string on the right. In my Redis instance that I just installed out of the box and with an uncompressed plain text file with this data, I can get about a million records into it a minute. I need to do about 45 million, which would take about 45 minutes. 45 minutes is too long. Are there some standard performance tweaks that exist for me to do this type of optimization? Would I get better performance by sharding across separate instances? A: The fastest way to do this is the following: generate Redis protocol out of this data. The documentation to generate the Redis protocol is on the Redis.io site, it is a trivial protocol. Once you have that, just call it appendonly.log and start redis in append only mode. You can even do a FLUSHALL command and finally push the data into your server with netcat, redirecting the output to /dev/null. This will be super fast, there is no RTT to wait, it's just a bulk loading of data. Less hackish way, just insert things 1000 per time using pipelining. It's almost as fast as generating the protocol, but much more clean :) A: I like what Salvadore proposed, but here you are one more very clear way - generate feed for cli, e.g. SET xxx yyy SET xxx yyy SET xxx yyy pipe it into cli on server close to you. Then do save, shutdown and move data file to the destination server.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Testing Rails 3.1 engine routes with RSpec 2 I'm trying to test a Rails 3.1 engine with RSpec 2. After a lot of trial and error (and documentation and Stack Overflow searching) the app is working and I've gotten most of the specs to pass. The problem is that my route specs are still failing. For an engine "foo" with an isolated namespace and a controller Foo::BarsController, I have this: require "spec_helper" describe Foo::BarsController do describe "routing" do it "routes to #index" do get("/foo/bars").should route_to("bars#index") end it "routes to #new" do get("/foo/bars/new").should route_to("bars#new") end end end This results in: 1) Foo::BarsController routing routes to #index Failure/Error: get("/foo/bars").should route_to("bars#index") ActionController::RoutingError: No route matches "/foo/bars" # ./spec/routing/foo/bars_routing_spec.rb:6:in `block (3 levels) in <top (required)>' 2) Foo::BarsController routing routes to #new Failure/Error: get("/foo/bars/new").should route_to("bars#new") ActionController::RoutingError: No route matches "/foo/bars/new" # ./spec/routing/foo/bars_routing_spec.rb:10:in `block (3 levels) in <top (required)>' My spec dummy application seems to be set up correctly: Rails.application.routes.draw do mount Foo::Engine => "/foo" end If it helps to answer this question, my view specs are also not working. Here is a typical error: 9) foo/bars/index.html.erb renders a list of bars Failure/Error: render ActionView::Template::Error: undefined local variable or method `new_bar_path' for #<#<Class:0x00000100c14958>:0x0000010464ceb8> # ./app/views/foo/bars/index.html.erb:3:in `___sers_matt__ites_foo_app_views_foo_bars_index_html_erb___1743631507081160226_2184232780' # ./spec/views/foo/bars/index.html.erb_spec.rb:12:in `block (2 levels) in <top (required)>' Any ideas? A: Try changing your get method to use the specific route get("/foo/bars", :use_route => :foo) A: OK, I got this working! And wrote a blog post about it. http://www.matthewratzloff.com/blog/2011/09/21/testing-routes-with-rails-3-1-engines/ It requires a new method to import engine routes into the application route set for tests. Edit: Caught a bug with named route handling and fixed it. A: It's actually not so hard to get this to work. It's a bit hacky since you are adding code to the engine's routes.rb file that changes depending on which env it's running in. If you are using the spec/dummy site approach for testing the engine then use the following code snippet in /config/routes.rb file: # <your_engine>/config/routes.rb if Rails.env.test? && Rails.application.class.name.to_s == 'Dummy::Application' application = Rails.application else application = YourEngine::Engine end application.routes.draw do ... end What this is basically doing is switching out your engine for the dummy app and writing the routes to it when in test mode. A: Here is the official rspec documentation solution: https://www.relishapp.com/rspec/rspec-rails/docs/routing-specs/engine-routes
{ "language": "en", "url": "https://stackoverflow.com/questions/7505015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Repeated State changes in Opengl Its a fact that state changes in Opengl leads to performance degradation. //Say If i'm calling glEnable(GL_DEPTH_TEST) / glBlendFunc repeatedly in every frame. EDIT: >Here I just mean to say 'some state changes like this which state changes cause performance problems' Can any one please explain the reason for this in detailed? To my knowledge, The states can be maintained with in a register and can be used in traditional rendering GPU(Immediate mode kind) or can maintain a state vector for each draw call in Tile based deferred Rendering. Is this really costly to maintain? (wonder why GPU's are having still this problem :( ) A: Indeed state changes may be a performance killer. However the important question to ask is: "Which state". Some state changes are so cheap, that is simply doesn't make sense to keep track of them to minimize their use. On today's OpenGL implementations glEnable/glDisable have virtually no performance penality (of course some states en-/disabled have large influence on the rendering performance in general). So what are expensive state changes? About everything that kills the caches' contents, and the data in the cache is to be accessed at high bandwidth or requires high throughput. Textures are about the most expensive source of data to switch. So as a basic rule you sort your scene by use of textures, to switch textures as few as possible. Another expensive state change is switching shaders. Switching a shader affects the GPU in a negatively in two ways: First it forces the processing units into a full stop, flushing their execution pipeline. Refilling the pipeline until the thing works "like clockwork" takes a few hundred cycles. The other problem is, that different shaders have different execution and data access patterns. Execution patterns are determined by codepath prediction units to estimate which operations are about to be executed most likely. This also means knowing, which data to prefetch. Switching the shader trashes this vital information. States that are very cheap, but not for free is anything that can be described by a small set of numbers: Uniforms. Switching uniforms is extremely cheap, since it requires only very little overhead in the communication with the GPU and since Uniforms live in registers, changing them will effect neither cachelines nor execution prediction. And if you're wondering about traditional, fixed function OpenGL: Transformation matrices, lighting parameters, clip planes are uniforms (just look into the OpenGL-2.1 GLSL spec, which built-in uniforms there are). A: I believe that glEnable(GL_DEPTH_TEST) would not incur significant performance degradation. The expensive state changes I believe are shader program binds, buffer binds, texture binds and buffer offset/stride changes. Because these require validation to ensure that the buffer is large enough etc. If you think this could be affecting performance you can order elements to be rendered by material (textures, shaders, depth testing) before rendering, and perform the state changes only once. A: You should enable some opengl state only if you disabled it first. So there is no reason to call glEnable(GL_DEPTH_TEST) or glBlendFunc every frame if you don't need such changes
{ "language": "en", "url": "https://stackoverflow.com/questions/7505018", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Oracle - How to create a materialized view with FAST REFRESH and JOINS So I'm pretty sure Oracle supports this, so I have no idea what I'm doing wrong. This code works: CREATE MATERIALIZED VIEW MV_Test NOLOGGING CACHE BUILD IMMEDIATE REFRESH FAST ON COMMIT AS SELECT V.* FROM TPM_PROJECTVERSION V; If I add in a JOIN, it breaks: CREATE MATERIALIZED VIEW MV_Test NOLOGGING CACHE BUILD IMMEDIATE REFRESH FAST ON COMMIT AS SELECT V.*, P.* FROM TPM_PROJECTVERSION V INNER JOIN TPM_PROJECT P ON P.PROJECTID = V.PROJECTID Now I get the error: ORA-12054: cannot set the ON COMMIT refresh attribute for the materialized view I've created materialized view logs on both TPM_PROJECT and TPM_PROJECTVERSION. TPM_PROJECT has a primary key of PROJECTID and TPM_PROJECTVERSION has a compound primary key of (PROJECTID,VERSIONID). What's the trick to this? I've been digging through Oracle manuals to no avail. Thanks! A: Have you tried it without the ANSI join ? CREATE MATERIALIZED VIEW MV_Test NOLOGGING CACHE BUILD IMMEDIATE REFRESH FAST ON COMMIT AS SELECT V.*, P.* FROM TPM_PROJECTVERSION V,TPM_PROJECT P WHERE P.PROJECTID = V.PROJECTID A: To start with, from the Oracle Database Data Warehousing Guide: Restrictions on Fast Refresh on Materialized Views with Joins Only ... * *Rowids of all the tables in the FROM list must appear in the SELECT list of the query. This means that your statement will need to look something like this: CREATE MATERIALIZED VIEW MV_Test NOLOGGING CACHE BUILD IMMEDIATE REFRESH FAST ON COMMIT AS SELECT V.*, P.*, V.ROWID as V_ROWID, P.ROWID as P_ROWID FROM TPM_PROJECTVERSION V, TPM_PROJECT P WHERE P.PROJECTID = V.PROJECTID Another key aspect to note is that your materialized view logs must be created as with rowid. Below is a functional test scenario: CREATE TABLE foo(foo NUMBER, CONSTRAINT foo_pk PRIMARY KEY(foo)); CREATE MATERIALIZED VIEW LOG ON foo WITH ROWID; CREATE TABLE bar(foo NUMBER, bar NUMBER, CONSTRAINT bar_pk PRIMARY KEY(foo, bar)); CREATE MATERIALIZED VIEW LOG ON bar WITH ROWID; CREATE MATERIALIZED VIEW foo_bar NOLOGGING CACHE BUILD IMMEDIATE REFRESH FAST ON COMMIT AS SELECT foo.foo, bar.bar, foo.ROWID AS foo_rowid, bar.ROWID AS bar_rowid FROM foo, bar WHERE foo.foo = bar.foo; A: You will get the error on REFRESH_FAST, if you do not create materialized view logs for the master table(s) the query is referring to. If anyone is not familiar with materialized views or using it for the first time, the better way is to use oracle sqldeveloper and graphically put in the options, and the errors also provide much better sense. A: The key checks for FAST REFRESH includes the following: 1) An Oracle materialized view log must be present for each base table. 2) The RowIDs of all the base tables must appear in the SELECT list of the MVIEW query definition. 3) If there are outer joins, unique constraints must be placed on the join columns of the inner table. No 3 is easy to miss and worth highlighting here A: USE THIS CODE CREATE MATERIALIZED VIEW MV_ptbl_Category2 BUILD IMMEDIATE REFRESH FORCE ON COMMIT AS SELECT * FROM ptbl_Category2; Note- MV_ptbl_Category2 is the Materialized view name Ptbl is the table name.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }
Q: emacs process in background without `&` Hi I use emacs as my default editor. I would like emacs to run a process in the background from the shell without typing the& at the end How do I customize that? gaurish108 ~: emacs hello.cpp & [1] 3889 gaurish108 ~: A: As Burton Samograd said, this is part of the shell syntax. If you want to hide it, try saving this in something like emacs.sh emacs "$@" & Then, chmod +x emacs.sh, and as long as emacs.sh is in a directory on your PATH, you should be able to run emacs as emacs.sh filename A: I always do emacs --daemon which actually using a very cool emacs feature where emacs runs as a server. You then connect via emacsclient -nw ## text mode, say via ssh on text connect or emacsclient -c & ## new x11 windows, return to prompt and the best part is that the actual buffers remain active in the background emacs server while the front-end clients can go up or down --- stateful editing, and particular for modes with sessions (shell, SQL, R, ...) it makes a huge difference. A: That irritating & is how you run a process in the background from the shell. This is so you get your command prompt back after you run a program. There is no way around it, it's just shell syntax.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: My application's text and size becomes smaller and smaller until it finally crashes. Why? I am using Samsung Galaxy S 4G (the new one). Previously, I tested this on the Dell Streak Tablet phone, as well as the HTC Desire, and it performed perfectly. But now, when I start the application things are misaligned, and as I use the application the text becomes smaller and smaller, the graphics become skewed, until finally the app crashes. Why is this? And how can I fix it? I am NOT changing the size of anything ... like I said, I've used the same application on two other devices and nothing has made a difference. I am currently thinking it maybe has to do with the Manifest file, an SDK version issue? I read about a similar issue when someone changed language, the text got smaller, which was fixed with <uses-sdk android:minSdkVersion="integer"> so I am looking into that. Edit: The logcat output: 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): FATAL EXCEPTION: main 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): java.lang.RuntimeException: Unable to start activity ComponentInfo{a.company.organization/a.company.organization.travel.TravelTab}: java.lang.RuntimeException: Unable to start activity ComponentInfo{a.company.organization/a.company.organization.travel.TravelMap}: android.view.InflateException: Binary XML file line #130: Error inflating class <unknown> 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at android.app.ActivityThread.access$2300(ActivityThread.java:125) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at android.os.Handler.dispatchMessage(Handler.java:99) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at android.os.Looper.loop(Looper.java:123) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at android.app.ActivityThread.main(ActivityThread.java:4627) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at java.lang.reflect.Method.invokeNative(Native Method) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at java.lang.reflect.Method.invoke(Method.java:521) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at dalvik.system.NativeStart.main(Native Method) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): Caused by: java.lang.RuntimeException: Unable to start activity ComponentInfo{a.company.organization/a.company.organization.travel.TravelMap}: android.view.InflateException: Binary XML file line #130: Error inflating class <unknown>09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at android.app.ActivityThread.startActivityNow(ActivityThread.java:2503) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:127) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:339) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at a.company.organization.tabcontrol.TabBarActivity.displayCurrentScreen(TabBarActivity.java:159) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at a.company.organization.tabcontrol.TabBarActivity.displayCurrentScreen(TabBarActivity.java:137) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at a.company.organization.tabcontrol.TabBarActivity.setCurrentTab(TabBarActivity.java:422) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at a.company.organization.tabcontrol.TabBarActivity.onCreate(TabBarActivity.java:369) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): ... 11 more 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): Caused by: android.view.InflateException: Binary XML file line #130: Error inflating class <unknown> 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at android.view.LayoutInflater.createView(LayoutInflater.java:513) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:563) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at android.view.LayoutInflater.rInflate(LayoutInflater.java:618) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at android.view.LayoutInflater.rInflate(LayoutInflater.java:621) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at android.view.LayoutInflater.rInflate(LayoutInflater.java:621) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at android.view.LayoutInflater.rInflate(LayoutInflater.java:621) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at android.view.LayoutInflater.inflate(LayoutInflater.java:320) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at android.view.LayoutInflater.inflate(LayoutInflater.java:276) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at a.company.organization.travel.TravelMap.onCreate(TravelMap.java:66) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): ... 20 more 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): Caused by: java.lang.reflect.InvocationTargetException 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at android.widget.ImageView.<init>(ImageView.java:108) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at java.lang.reflect.Constructor.constructNative(Native Method) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at java.lang.reflect.Constructor.newInstance(Constructor.java:446) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at android.view.LayoutInflater.createView(LayoutInflater.java:500) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): ... 32 more 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): Caused by: android.content.res.Resources$NotFoundException: File res/drawable-mdpi/carousel_top_bar.png from drawable resource ID #0x7f020087 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at android.content.res.Resources.loadDrawable(Resources.java:1714) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at android.content.res.TypedArray.getDrawable(TypedArray.java:601) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at android.widget.ImageView.<init>(ImageView.java:118) 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): ... 36 more 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): Caused by: java.lang.IllegalArgumentException: width and height must be > 0 09-21 15:18:34.301: ERROR/AndroidRuntime(7377): at android.graphics.Bitmap.nativeCreate(Nati 09-21 15:18:34.313: WARN/ActivityManager(6572): Force finishing activity a.company.organization/.travel.TravelTab 09-21 15:18:34.316: ERROR/(6572): Dumpstate > /data/log/dumpstate_app_error A: To fix this issue, you should restrict the sdk version. To do that for 2.0 and above add: <uses-sdk android:minSdkVersion="5" android:maxSdkVersion="5" /> You should also modify the Manifest file to include: <supports-screens android:smallScreens="true" android:largeScreens="true" android:resizeable="false" android:normalScreens="true" android:anyDensity="true"></supports-screens> The resources I used for finding out about is here, and for API Level to Platform level check I used this
{ "language": "en", "url": "https://stackoverflow.com/questions/7505026", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to tell Pex not to stub an abstract class that has concrete implementations I'm trying to use Pex to test some code. I have an abstract class with four concrete implementations. I have created factory methods for each of the four concrete types. I had also created one for the abstract type, except as this nice thread explains, Pex will not use the abstract factory method, nor should it. The problem is that some of my code depends on the four concrete types being all there are (since it is very, very unlikely that any more subclasses will be created), but Pex is breaking the code by using Moles to create a stub. How can I force Pex to use one of the factory methods (any one, I don't care) to create instances of the abstract class without ever creating Moles stubs for that abstract class? Is there a PexAssume directive that will accomplish this? Note that some of the concrete types form a type of tree structure, so say ConcreteImplementation derives from AbstractClass, and ConcreteImplementation has two properties of type AbstractClass. I need to ensure that no stubs are used anywhere in the tree at all. (Not all the concrete implementations have AbstractClass properties.) Edit: It appears that I need to add some more information on how the class structure itself works, though remember that the goal is still how to get Pex not to stub classes. Here are simplified versions of the abstract base class and the four concrete implementations thereof. public abstract class AbstractClass { public abstract AbstractClass Distill(); public static bool operator ==(AbstractClass left, AbstractClass right) { // some logic that returns a bool } public static bool operator !=(AbstractClass left, AbstractClass right) { // some logic that basically returns !(operator ==) } public static Implementation1 Implementation1 { get { return Implementation1.GetInstance; } } } public class Implementation1 : AbstractClass, IEquatable<Implementation1> { private static Implementation1 _implementation1 = new Implementation1(); private Implementation1() { } public override AbstractClass Distill() { return this; } internal static Implementation1 GetInstance { get { return _implementation1; } } public bool Equals(Implementation1 other) { return true; } } public class Implementation2 : AbstractClass, IEquatable<Implementation2> { public string Name { get; private set; } public string NamePlural { get; private set; } public Implementation2(string name) { // initializes, including Name = name; // and sets NamePlural to a default } public Implementation2(string name, string plural) { // initializes, including Name = name; NamePlural = plural; } public override AbstractClass Distill() { if (String.IsNullOrEmpty(Name)) { return AbstractClass.Implementation1; } return this; } public bool Equals(Implementation2 other) { if (other == null) { return false; } return other.Name == this.Name; } } public class Implementation3 : AbstractClass, IEquatable<Implementation3> { public IEnumerable<AbstractClass> Instances { get; private set; } public Implementation3() : base() { Instances = new List<AbstractClass>(); } public Implementation3(IEnumerable<AbstractClass> instances) : base() { if (instances == null) { throw new ArgumentNullException("instances", "error msg"); } if (instances.Any<AbstractClass>(c => c == null)) { thrown new ArgumentNullException("instances", "some other error msg"); } Instances = instances; } public override AbstractClass Distill() { IEnumerable<AbstractClass> newInstances = new List<AbstractClass>(Instances); // "Flatten" the collection by removing nested Implementation3 instances while (newInstances.OfType<Implementation3>().Any<Implementation3>()) { newInstances = newInstances.Where<AbstractClass>(c => c.GetType() != typeof(Implementation3)) .Concat<AbstractClass>(newInstances.OfType<Implementation3>().SelectMany<Implementation3, AbstractUnit>(i => i.Instances)); } if (newInstances.OfType<Implementation4>().Any<Implementation4>()) { List<AbstractClass> denominator = new List<AbstractClass>(); while (newInstances.OfType<Implementation4>().Any<Implementation4>()) { denominator.AddRange(newInstances.OfType<Implementation4>().Select<Implementation4, AbstractClass>(c => c.Denominator)); newInstances = newInstances.Where<AbstractClass>(c => c.GetType() != typeof(Implementation4)) .Concat<AbstractClass>(newInstances.OfType<Implementation4>().Select<Implementation4, AbstractClass>(c => c.Numerator)); } return (new Implementation4(new Implementation3(newInstances), new Implementation3(denominator))).Distill(); } // There should only be Implementation1 and/or Implementation2 instances // left. Return only the Implementation2 instances, if there are any. IEnumerable<Implementation2> i2s = newInstances.Select<AbstractClass, AbstractClass>(c => c.Distill()).OfType<Implementation2>(); switch (i2s.Count<Implementation2>()) { case 0: return AbstractClass.Implementation1; case 1: return i2s.First<Implementation2>(); default: return new Implementation3(i2s.OrderBy<Implementation2, string>(c => c.Name).Select<Implementation2, AbstractClass>(c => c)); } } public bool Equals(Implementation3 other) { // omitted for brevity return false; } } public class Implementation4 : AbstractClass, IEquatable<Implementation4> { private AbstractClass _numerator; private AbstractClass _denominator; public AbstractClass Numerator { get { return _numerator; } set { if (value == null) { throw new ArgumentNullException("value", "error msg"); } _numerator = value; } } public AbstractClass Denominator { get { return _denominator; } set { if (value == null) { throw new ArgumentNullException("value", "error msg"); } _denominator = value; } } public Implementation4(AbstractClass numerator, AbstractClass denominator) : base() { if (numerator == null || denominator == null) { throw new ArgumentNullException("whichever", "error msg"); } Numerator = numerator; Denominator = denominator; } public override AbstractClass Distill() { AbstractClass numDistilled = Numerator.Distill(); AbstractClass denDistilled = Denominator.Distill(); if (denDistilled.GetType() == typeof(Implementation1)) { return numDistilled; } if (denDistilled.GetType() == typeof(Implementation4)) { Implementation3 newInstance = new Implementation3(new List<AbstractClass>(2) { numDistilled, new Implementation4(((Implementation4)denDistilled).Denominator, ((Implementation4)denDistilled).Numerator) }); return newInstance.Distill(); } if (numDistilled.GetType() == typeof(Implementation4)) { Implementation4 newImp4 = new Implementation4(((Implementation4)numReduced).Numerator, new Implementation3(new List<AbstractClass>(2) { ((Implementation4)numDistilled).Denominator, denDistilled })); return newImp4.Distill(); } if (numDistilled.GetType() == typeof(Implementation1)) { return new Implementation4(numDistilled, denDistilled); } if (numDistilled.GetType() == typeof(Implementation2) && denDistilled.GetType() == typeof(Implementation2)) { if (((Implementation2)numDistilled).Name == (((Implementation2)denDistilled).Name) { return AbstractClass.Implementation1; } return new Implementation4(numDistilled, denDistilled); } // At this point, one or both of numerator and denominator are Implementation3 // instances, and the other (if any) is Implementation2. Because both // numerator and denominator are distilled, all the instances within either // Implementation3 are going to be Implementation2. So, the following should // work. List<Implementation2> numList = numDistilled.GetType() == typeof(Implementation2) ? new List<Implementation2>(1) { ((Implementation2)numDistilled) } : new List<Implementation2>(((Implementation3)numDistilled).Instances.OfType<Implementation2>()); List<Implementation2> denList = denDistilled.GetType() == typeof(Implementation2) ? new List<Implementation2>(1) { ((Implementation2)denDistilled) } : new List<Implementation2>(((Implementation3)denDistilled).Instances.OfType<Implementation2>()); Stack<int> numIndexesToRemove = new Stack<int>(); for (int i = 0; i < numList.Count; i++) { if (denList.Remove(numList[i])) { numIndexesToRemove.Push(i); } } while (numIndexesToRemove.Count > 0) { numList.RemoveAt(numIndexesToRemove.Pop()); } switch (denList.Count) { case 0: switch (numList.Count) { case 0: return AbstractClass.Implementation1; case 1: return numList.First<Implementation2>(); default: return new Implementation3(numList.OfType<AbstractClass>()); } case 1: switch (numList.Count) { case 0: return new Implementation4(AbstractClass.Implementation1, denList.First<Implementation2>()); case 1: return new Implementation4(numList.First<Implementation2>(), denList.First<Implementation2>()); default: return new Implementation4(new Implementation3(numList.OfType<AbstractClass>()), denList.First<Implementation2>()); } default: switch (numList.Count) { case 0: return new Implementation4(AbstractClass.Implementation1, new Implementation3(denList.OfType<AbstractClass>())); case 1: return new Implementation4(numList.First<Implementation2>(), new Implementation3(denList.OfType<AbstractClass>())); default: return new Implementation4(new Implementation3(numList.OfType<AbstractClass>()), new Implementation3(denList.OfType<AbstractClass>())); } } } public bool Equals(Implementation4 other) { return Numerator.Equals(other.Numerator) && Denominator.Equals(other.Denominator); } } The heart of what I am trying to test is the Distill method, which as you can see has the potential to run recursively. Because a stubbed AbstractClass is meaningless in this paradigm, it breaks the algorithm logic. Even trying to test for a stubbed class is somewhat useless, since there is little I can do about it other than throw an exception or pretend that it is an instance of Implementation1. I would prefer not to have to rewrite the code under test to accommodate a specific testing framework in that way, but writing the test itself in such a way as never to stub AbstractClass is what I am trying to do here. I hope it is apparent how what I am doing differs from a type-safe enum construct, for instance. Also, I anonymized objects for posting here (as you can tell), and I did not include all methods, so if you're going to comment to tell me that Implementation4.Equals(Implementation4) is broken, don't worry, I'm aware that it is broken here, but my actual code takes care of the issue. Another edit: Here is an example of one of the factory classes. It is in the Factories directory of the Pex-generated test project. public static partial class Implementation3Factory { [PexFactoryMethod(typeof(Implementation3))] public static Implementation3 Create(IEnumerable<AbstractClass> instances, bool useEmptyConstructor) { Implementation3 i3 = null; if (useEmptyConstructor) { i3 = new Implementation3(); } else { i3 = new Implementation3(instances); } return i3; } } In my factory methods for these concrete implementations, it is possible to use any constructor to create the concrete implementation. In the example, the useEmptyConstructor parameter controls which constructor to use. The other factory methods have similar features. I recall reading, though I cannot immediately find the link, that these factory methods should allow the object to be created in every possible configuration. A: Have you tried telling Pex using the [PexUseType] attribute, that non-abstract subtypes for your abstract class exist? If Pex is not aware of any non-abstract subtypes, then Pex's constraint solver would determine that a code path that depends on the existence of a non-abstract subtype is infeasible.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "61" }
Q: Authentication failed while calling WCF service from ASP.NET Platform: VS 2008, .NET 3.5, C#, Oracle 11g I've created a WCF service which takes some data elements and then inserts them into a database table and returns an integer. I've also created a small ASP.NET web app to test that service. The test web app only has a page with the fields and a button, clicking that button actually calls the web service to insert the data and return a integer value. The steps I took: * *Build the WCF service *Publish the WCF Service *Generate the proxy class (.cs) and app.config using svcutil *Build the test asp.net app and add the proxy class and config settings as generated on the above step. *Ruin the test app It works fine when I deploy both the WCF and the test web app on my computer - Windows XP, IIS 5.1. But, whenever I'm trying to deploy them on a remote server it doesn't work. When I'm trying to consume the service (deployed on remote server - Windows 2003 server, IIS 6) I'm getting the following error: The request for security token could not be satisfied because authentication failed. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.ServiceModel.FaultException: The request for security token could not be satisfied because authentication failed. Following are the .config files content: wcf section of the Web.Config of calling ASP.NET web app (Consumer): <system.serviceModel> <bindings> <wsHttpBinding> <binding name="WSHttpBinding_IMyWCFService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false"> <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" /> <security mode="Message"> <transport clientCredentialType="Windows" proxyCredentialType="None" realm="" /> <message clientCredentialType="Windows" negotiateServiceCredential="true" algorithmSuite="Default" establishSecurityContext="true" /> </security> </binding> </wsHttpBinding> </bindings> <client> <endpoint address="http://57.23.85.28:8001/MyWCFService/MyWCFService.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IMyWCFService" contract="IMyWCFService" name="WSHttpBinding_IMyWCFService"> <identity> <dns value="localhost" /> </identity> </endpoint> </client> </system.serviceModel> Web.Config of the WCF: <configuration> <connectionStrings> <add name="DSMyWCF" connectionString="Data Source=XXX;User id=XXX;Password=XXX;"/> </connectionStrings> <system.web> <compilation debug="true" /> </system.web> <!-- When deploying the service library project, the content of the config file must be added to the host's app.config file. System.Configuration does not support config files for libraries. --> <system.serviceModel> <services> <service behaviorConfiguration="MyWCFService.MyWCFServiceBehavior" name="MyWCFService.MyWCFService"> <endpoint address="" binding="wsHttpBinding" contract="MyWCFService.IMyWCFService"> <identity> <dns value="localhost" /> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> <host> <baseAddresses> <add baseAddress="http://localhost:8731/Design_Time_Addresses/MyWCFService/MyWCFService/" /> </baseAddresses> </host> </service> </services> <behaviors> <serviceBehaviors> <behavior name="MyWCFService.MyWCFServiceBehavior"> <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --> <serviceMetadata httpGetEnabled="True"/> <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> <serviceDebug includeExceptionDetailInFaults="False" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration> A: Could be related with security configuration of wcf service, to be specific, Windows credential type requires valid domain username and password information. Try providing the following attributes on clientside; proxy.ClientCredentials.Windows.ClientCredential.UserName = "UserName "; proxy.ClientCredentials.Windows.ClientCredential.Password = "Password "; proxy.ClientCredentials.Windows.ClientCredential.Domain = "Domain ";
{ "language": "en", "url": "https://stackoverflow.com/questions/7505031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: XPath and XNodes vs Xelements, whats better for mapping two large xml documents? I want to map two fairly large xml documents, one of them using the NIEM schema. I am most familiar with the System.Xml.Linq (XElement) class but have heard good things about using XPath and XNodes, contained in the System.Xml namespace. Anyone have any pros and cons on the two in terms of mapping? A: I think the main issue (as you have large XML documents) is whether you need write access or not. If you're mapping from one file to a new file you can use an XmlReader which gives only forward read only access to the xml document but it is really fast. I would say however that using XPath is less intuitive than XElement as most programmers are familiar with Linq syntax but not everyone might be familiar with XPath queries.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iOS Programming Best Practices - Help for Puzzle I am creating a simple drag and drop puzzle for the iPad/iOS. Basically you can drag a sprite to a location and if it matches up then bingo, it matches. Like the kids animal puzzle games. Drag a chicken to the chicken but not a chicken to a cow. Now, I set up the level and I have collision detection working on the puzzle pieces. I also have boundaries set up and accelerometer working to clear the game pieces. My question is what route do I go for the empty slots? I was thinking of just adding them as sprites in set locations and then check if chicken piece collides with the chicken slot then bingo. But that seems inefficient since I will have to create a bunch of them. Then I started thinking looping and using an 'empty piece' object. But then I still have to 'hard code' the locations of the empty slots. I am using cocos2d and box2d right now and really just need to be pointed in the right direction. Is there a vertices editor that I should be using instead? Do I set up the sprites as sensors? Thanks A: If you create three empty slots, give an incremented z value to each. int index = 0; [self addChild:emptyPiece1 z:++index] [self addChild:emptyPiece2 z:++index] [self addChild:emptyPiece3 z:++index] And then for your actual pieces, give an incremented z value to each. [self addChild:puzzlePiece1 z:++index] [self addChild:puzzlePiece2 z:++index] [self addChild:puzzlePiece3 z:++index] You can compare the z values at collision to see if the difference between the two is the correct difference (in this case 3). Something like: if (abs(obj1.z - obj2.z) == (index/2)) {}
{ "language": "en", "url": "https://stackoverflow.com/questions/7505038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: InvalidCastException HttpWebRequest c# I have a problem: app throws InvalidCastException when I creating HttpWebRequest in BackgroundAgent. This code works in App foreground tasks, but doesn't works in BackgroundAgent: HttpWebRequest request = (HttpWebRequest)WebRequest.Create(//InvalidCastException new Uri(url)); request.BeginGetResponse(r => { HttpWebRequest httprequest = (HttpWebRequest)r.AsyncState; try { Full code: http://pastebin.com/zyCHBQuP A: The type returned is dependent on the Uri passed into the Create method. You will get some descendant of WebRequest. You must be sure the Uri you pass is of the type that will return an HttpWebRequest if you are going to make that cast, or you will need to test the type returned from Create prior to casting or use the as HttpWebRequest. http://msdn.microsoft.com/en-us/library/0aa3d588.aspx (for .net) http://msdn.microsoft.com/en-us/library/0aa3d588%28v=VS.95%29.aspx (for silverlight)
{ "language": "en", "url": "https://stackoverflow.com/questions/7505039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MySQL in-operator must match all values? I've made my own forum. When doing a search I want to find any threads where two (or more) specific users have participated. I came up with this: SELECT * FROM table1 INNER JOIN table2 ON table1.threadid=table2.threadid WHERE table2.threadcontributor IN ('1','52512') Before realizing that it actually means '1' OR '52512'. Is there any way to make it work so that all id's has to match? A: SELECT * FROM table1 INNER JOIN table2 ON table1.threadid=table2.threadid WHERE table2.threadcontributor IN ('1','52512') GROUP BY table1.PrimaryKey HAVING COUNT(DISTINCT table2.threadcontributor) = 2
{ "language": "en", "url": "https://stackoverflow.com/questions/7505045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Rails 3 Devise redirect within custom strategy My setup: Rails 3.0.9, Ruby 1.9.2, Devise 1.3.4 I implemented a custom Devise / Warden strategy to authenticate against a 3rd party API and if successful, a new user is created the first time. I should clarify that the user creation is done within the custom strategy code in devise.rb devise.rb config.warden do |manager| manager.strategies.add(:mls_strategy) do def authenticate! ... authenticate against 3rd party API... if res.body =~ /success/ u = User.find_or_initialize_by_email(params[:user][:email]) if u.new_record? u.save end success!(u) end end end That all works except that that upon creation, the user sees the login page still with an alert saying Signed in successfully. The desired behavior is that the user gets redirected to the application's root which I tried to do by adding redirect_to "/" after creating user but it couldn't find redirect_to method and I'm not even sure that's the best way to do it. I have also tried adding this to routes.rb without success namespace :user do root :to => "blah#index" end Suggestions? A: Argh, as it turns out, all I need to do is to use save! instead of just save. Apparently save! persists it to the database whereas save delays it causing Devise to not recognize the user as authenticated. A: You need to make a new controller "Registrations" and customize the appropriate method: class RegistrationsController < Devise::RegistrationsController protected def after_sign_up_path_for(resource) '/an/example/path' end end you can find more information here: https://github.com/plataformatec/devise/wiki/How-To:-Redirect-to-a-specific-page-on-successful-sign-up-%28registration%29
{ "language": "en", "url": "https://stackoverflow.com/questions/7505046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Adding EditText box to android app based on x,y coordinates? I am looking to be able to first detect touch events to draw a box whatever size the user wants on the canvas - this part I have completed. I then need to take the coordinates of that box and create a edittext box in its place. Any Suggestions ? I would then like to make the text entered become part of the canvas itself, no longer editable any ideas there either ? thanks! A: Use AbsoluteLayout and add touch listener via setOnTouchListener(..) Then when touch happens, detect the location and add EditText via AbsoluteLayout.LayoutParams layoutParams = new AbsoluteLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT, x, y); absoluteLayout.addView(editText, layoutParams);
{ "language": "en", "url": "https://stackoverflow.com/questions/7505054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: If I don't explicitly map a column in code-first EF to an existing DB, will that column still work? I have the following mapping defined: protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<InsuranceProvider>() .Map(ins => ins.Properties(p => new { PKID_Insuance = p.Id, InsuranceProvider = p.Name, Address1 = p.Address.Address1, Address2 = p.Address.Address2, City = p.Address.City, State = p.Address.State, Zipcode = p.Address.Zipcode, })).ToTable("Insurance"); } The table and object both share properties such as Phone and Fax with the same name. Do I need to explicitly map those or will the fall into place magically? Thanks. Solution: Sure enough the mapping I proposed did not work. Once I had it working with the .HasColumnName() method, I swapped that out for the code here and got a "the property expression.... is not valid" error. Bummer. The scaffold "Create" in MVC 3 did, however, pull both the values I defined in the mapping as well as the ones from the Database with the shared names. Funny how that works. It would be nice if they brought that syntax back. It seems so much cleaner for remapping large quantities of columns. A: Did this work at all what you have so far? The usual way to map properties to column names in the DB is: modelBuilder.Entity<InsuranceProvider>() .Property(i => i.Name) .HasColumnName("InsuranceProvider"); modelBuilder.Entity<InsuranceProvider>() .Property(i => i.Address.Address1) .HasColumnName("Address1"); // assuming here that Address is a complex property, not a navigation property // etc. And then yes, you don't need to define a mapping for properties which have the same name as the columns in the database. This mapping will happen by convention. Alternatively you can use the [Column("...")] attribute on the properties in your model classes (doesn't work though for complex properties, only for scalars, I think). A: It will not work. The mapping is not correct. It will create two tables because Map is used to work with inheritance mapping and entity splitting (as pointed by @Slauma in comment) so your mentioned properties will be in Insurance table and other properties + PK will be in another table. Also your usage of Map is not correct. You must use anonymous type without specifying names of properties. You must use approach mentioned by @Slauma.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505056", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: TeamCity AssemblyInfo patcher Patches file, but DLL version isn't "right" Here's what my assemblyinfo.cs version strings look like pre build: [assembly: AssemblyVersion("2.0.0920.10")] [assembly: AssemblyFileVersion("2.0.0920.10")] During the build, the patcher does what I want, modifies the files: [assembly: AssemblyVersion("2.0.0.1146")] [assembly: AssemblyFileVersion("2.0.0.1146")] But at some point during the build it also does this: [assembly: AssemblyVersion("2.0.0921.00")] [assembly: AssemblyFileVersion("2.0.0921.00")] Then when the build is finished, it looks like this again: [assembly: AssemblyVersion("2.0.0920.10")] [assembly: AssemblyFileVersion("2.0.0920.10")] When I right click on the resulting DLL in Windows Explorer, hit Properties then go to the Details tab, File Version is "2.0.921.0" and Product version is "2.0.921.00". I also get "2.0.921.0" with Assembly.GetExecutingAssembly().GetName().Version.ToString() My Build has 2 Build steps, one that is a VS Solution Build and another that is a command line step that just copies the DLLs to the dev server. I don't want to paste the whole build log because it's large, but here are what I think are the highlights: [14:24:54]: Step 1/2: Visual Studio 2010 Build (Visual Studio (sln)) (27s) [14:24:54]: [Step 1/2] Update assembly versions: scanning checkout directory for AssemlyInfo files to update version [14:24:54]: [Update assembly versions] ... for all of our assemblies [14:24:55]: [Step 1/2] Starting: C:\TeamCity\buildAgent\plugins\dotnetPlugin\bin\JetBrains.BuildServer.MsBuildBootstrap.exe /workdir:C:\TeamCity\buildAgent\work\677e8e784c19cc26 /msbuildPath:C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe [14:24:55]: [Step 1/2] in directory: C:\TeamCity\buildAgent\work\677e8e784c19cc26 [14:25:01]: [Step 1/2] main\solution.sln: Build target: Rebuild (20s) [14:25:01]: [main\solution.sln] ValidateSolutionConfiguration [14:25:01]: [ValidateSolutionConfiguration] Building solution configuration "Release|Mixed Platforms". [14:25:02]: [Step 1/2] main\SolutionDir\solution.csproj: Build target: Rebuild (7s) ... [14:25:21]: [Step 1/2] Process exited with code 0 [14:25:21]: Step 2/2: Copy Dlls and Templates to Sohodev (Command Line) (3s) [14:25:21]: [Step 2/2] "BuildAndCopyDllsAndTemplatesv2.cmd" is not present in directory C:\TeamCity\buildAgent\work\677e8e784c19cc26 [14:25:21]: [Step 2/2] Starting: C:\Windows\system32\cmd.exe /c BuildAndCopyDllsAndTemplatesv2.cmd [14:25:21]: [Step 2/2] in directory: C:\Scripts\Build [14:25:21]: [Step 2/2] 1 file(s) copied. [14:25:21]: [Step 2/2] 1 file(s) copied. [14:25:24]: [Step 2/2] Process exited with code 0 [14:25:24]: Reverting patched assembly versions [14:25:24]: [Reverting patched assembly versions] Restoring ... for all of our assemblies [14:25:24]: Publishing internal artifacts (2s) [14:25:27]: [Publishing internal artifacts] Sending build.finish.properties file [14:25:27]: Build finished Edit Our TeamCity version number: 6.5.1 (build 17834) Edit I just upgraded to 6.5.4 (build 18046). No change in behavior. A: As expected, everything is working as configured. We had a VersionNumber.targets file that was fiddling with the assemblyinfo.cs files <Import Project="$(MSBuildExtensionsPath)\Microsoft\AssemblyInfoTask\Microsoft.VersionNumber.targets"/> Commenting this out made everything work as desired.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: AJAX sending json data as text/xml I have two sites using the same javascript code to interact with several web services. The code works perfectly in one site, but in the other, it is sending the data as text/xml. I have looked at the web config files in both sites and cannot spot anything that could cause the difference. The AjaxControlToolkit DLL files are the same. The AJAX call fails with an error 500 because the data is not in the proper form. Code that makes the AJAX call: function displaySessionNotifications() { $.ajax({ type: "POST", async: false, url: "NotificationService.asmx/ListSessionNotifications", contentType: "application/json; charset=utf-8", dataType: "json", data: JSON.stringify({}), success: function (data) { $list = JSON.parse(data.d); if (window.console.log) { window.console.log('Notification Service Msg Cnt: ' + $list.length) }; for (var i = 0; i < $list.length; i++) { displayMessage($list[i].MessageText, $list[i].MessageType, $list[i].IsSticky, $list[i].jGrowlClass, $list[i].ContainerId); }; if ($list.length > 0) { clearSessionNotifications($list[0].SessionId); } }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert("NotificationService/ListSessionNotifications failed: " + XMLHttpRequest.responseText); } }); } Watch Data from Firebug: this Object { url="NotificationService.asmx/ListSessionNotifications", global=true, type="POST", more...} XMLHttpRequest Object { readyState=4, status=0, statusText="error"} errorThrown [Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE)" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js :: <TOP_LEVEL> :: line 16" data: no] { name="NS_ERROR_FAILURE", message="Component returned fail...4005 (NS_ERROR_FAILURE)", result=2147500037, more...} textStatus "error" Firebug console display of the code that works: Server ASP.NET Development Server/10.0.0.0 Date Wed, 21 Sep 2011 17:44:39 GMT X-AspNet-Version 4.0.30319 Cache-Control private, max-age=0 Content-Type application/json; charset=utf-8 Content-Length 10 Connection Close Request Headers Host 127.0.0.1:54837 User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0.2) Gecko/20100101 Firefox/6.0.2 Accept application/json, text/javascript, */*; q=0.01 Accept-Language en-us,en;q=0.5 Accept-Encoding gzip, deflate Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7 Connection keep-alive Content-Type application/json; charset=utf-8 x-requested-with XMLHttpRequest Referer http://127.0.0.1:54837/WebSite/TestNotifications.aspx Content-Length 2 Cookie JXID=80VR2F3uNRgK8YteuGgnAbsR; JXHID=false; Identifier=Id=20c8b636-7ec4-464f-b6dc-867d0924f475; enhanced=pass; Skin=Default; ASP.NET_SessionId=3nientky4k1hdy3gkfemne04; linkedin_oauth_BW-FUQKDybTn3R7TmZ-gHFmiFpzKY9ztqInF8jLVbHwNNkm_iSnIii26jEJts4wI_crc=null Same data for code that fails: Response Headersview source Server ASP.NET Development Server/10.0.0.0 Date Wed, 21 Sep 2011 18:34:01 GMT X-AspNet-Version 4.0.30319 Cache-Control private Content-Type text/html; charset=utf-8 Content-Length 4516 Connection Close Request Headersview source Host 127.0.0.1:60391 User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0.2) Gecko/20100101 Firefox/6.0.2 Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language en-us,en;q=0.5 Accept-Encoding gzip, deflate Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7 Connection keep-alive Origin http://localhost:60391 Access-Control-Request-Me... POST Access-Control-Request-He... content-type,x-requested-with Pragma no-cache Cache-Control no-cache
{ "language": "en", "url": "https://stackoverflow.com/questions/7505061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: rails 3 query string params I try to make a simple message controller with new/create actions, when I call new action I give through query string the to_id param, /messages/new?to_id=1 that contains id of recipient, now my code is: def new @message = Message.new @message.to = User.find(params[:to_id]) end def create @message = Message.new(params[:message]) @message.from = current_user respond_to do |format| if @message.save format.html { redirect_to messages_path } else format.html { redirect_to common_error_path, :notice => "failed to send message" } end end end It's pretty default, my problem is that the changes in @message object that have been made in new action are not available in create action and I lose my to_id value, the first thing come to my mind is to store to_id value using session object, but I think it's not the best idea, maybe someone have better solution for this A: You'll need to pass that parameter back with the POST on create. For example, if you have a belongs_to :to, :class_name => 'User' association on your Message model, you could do app/views/messages/new.html.erb <%= form_for @message do |f| %> <%= f.hidden_field :to_id %> ... <% end %> The above assumes you've kept your new action the same. Now, on your create action, your params[:message] would be equal to {:to_id => 1} and would assign it properly. Does that make sense?
{ "language": "en", "url": "https://stackoverflow.com/questions/7505063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to get the location on a Control that is inside another control Possible Duplicate: C# Get a control's position on a form C# Winforms: I have a big table layout that it has some panels inside it and they have some listboxes inside those panels with Dock->Fill, so if I say listbox.Top it will be Zero... but I want to know the location based on the X,Y of the Form or at least that tableLayout, How can I do that? thanks A: For this, you need to consider the location from Parent Control. Control(X, Y) = ( UserControl.Location.X (@ Parent Control) + Control.Location.X (@ UserControl) , UserControl.Location.Y (@ Parent Control) + Control.Location.Y (@ UserControl) ) X = UserControl.Location.X (@ Parent Control) + Control.Location.X (@ UserControl) Y = UserControl.Location.Y (@ Parent Control) + Control.Location.Y (@ UserControl)
{ "language": "en", "url": "https://stackoverflow.com/questions/7505065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Hibernate HQL query does not update the Lucene Index I am using Hibernate 3.6.3 Final and Hibernate Search 3.4.1. I wrote an HQL delete query. The objects are deleted from the database but they are not removed from the Lucene Index after the transaction completes. Here is the query: Session session = factory.getCurrentSession(); Query q = session.createQuery("delete from Charges cg where cg.id in (:charges)"); q.setParameterList("charges", chargeIds); int result = q.executeUpdate();` What am I missing? What do I need to do to solve issue? I created a PostDeleteEvent, hoever the FullTextEventListener doesn't appear to be receiving the event: SessionImpl sessImpl = (SessionImpl) factory.getCurrentSession(); SessionImplementor implementor = sessImpl.getPersistenceContext().getSession(); EntityPersister persister = implementor.getEntityPersister("Charges", cg); EntityEntry entry = sessImpl.getPersistenceContext().getEntry(cg); Object[] deletedState = new Object[] { cg}; entry.setDeletedState(deletedState); PostDeleteEvent pdEvent = new PostDeleteEvent(entry, entry.getId(), deletedState, entry.getPersister(), (EventSource) sessImpl);` Thank you. A: This is an expected limitation, documented in the Hibernate Search reference. HQL update statements are interpreted to * *Generate the batch SQL to perform the operation *Invalidate any relevant cache (if using any second level cache) *See if pending operations need to be flushed to the database before executing the query But it's not going to load all potential matches in memory from the database! That would kill performance. Still Lucene requires the elements in memory, so indeed this is a design limitation and is expected: you should not run mass-update statements on indexed types, but rather iterate on them in memory and apply changes on the entities in a loop. Loading all entities will be slow as it will need to materialize all data in memory, but that's required to feed Lucene anyway; a good second level cache configuration usually does the trick, or just start the MassIndexer to re-synch it all if changes are massive.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Streaming microphone audio from iPhone to outside server I've seen questions on here about this, but no can't find any solutions. Does anyone have a push in the right direction for streaming audio picked up from the mic to a server? Like a one-way walkie talkie. A: You'll need a combination of AVCaptureSession and AVCaptureDevice to read from the microphone - see the AV Foundation Programming Guide. Then once you've got the data you'll need to stream it up to a server. Use TCP/IP sockets (see the CFNetwork Programming Guide). Then just read the mic data, optionally transform it (compress, bit rate etc) and push it down the socket.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use jQuery objects as parameters for the delegate method Multiple selectors are used with delegate using the following: $(contextElement).delegate('selector1, selector2' , 'eventName', function(){ //blabla }); In larger projects where managing DOM elements becomes crucial, storing the elements in variables that are binded to the window object becomes an attractive way to work. However I can't join this way of working with using multiple selectors on the delegate method: window.someControl = { contextElement = $('selector0'), DOMasProperty1 = $('selector1'), DOMasProperty2 = $('selector2') } someControl.contextElement.delegate( 'you magic answer for using DOMasProperty1 and DOMasProperty2', 'click', function(){ //blabla }); Note: I am aware that the string value of the selector as oppose to its jQuery object can be stored in the someControl object. However I am storing the jQuery objects to improve the performance of the code and simply calling the string values over and over again will make this way of working not different to simply using the selector name wit the method. I need an answer to somehow combine the use of delegate with reducing DOM lookups A: jQuery objects have a .selector property that will refer to your original selector. someControl.contextElement.delegate( window.someControl.DOMasProperty1.selector + ',' + window.someControl.DOMasProperty2.selector, 'click', function(){ //blabla }); Note that it will work for: DOMasProperty1 = $('selector1'), ...but probably not if you include DOM traversal methods like: DOMasProperty1 = $('selector1').parent(), A: I'm not entirely clear on your question, but I might do something like this: window.someControl = { contextElement: $('selector0'), selectors: ['selector1', 'selector2'] } someControl.contextElement.delegate(someControl.selectors.join(','), 'click', function(){ // … }); Note that the syntax for creating objects JavaScript looks like this: { key: value } Not like this: { key = value }
{ "language": "en", "url": "https://stackoverflow.com/questions/7505075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I get my email to center in Hotmail? I am testing my HTML email using http://www.emailonacid.com and Hotmail is causing problems. This table is appearing as left aligned and I can't figure out why: <div align="center"> <table align="center" width="200" style="background:red"> <tr> <td>Please Help</td> </tr> </table> </div> It looks fine in IE but not in FF. A: Hotmail places your email inside a div with a class named “ExternalClass” - here are the properties they have set on that class: .ExternalClass{display:inline-block; line-height: 131%}; This has no effect on your email when using IE but every other browser the email will not be centered. To overwrite this simply include this in your embedded CSS: .ExternalClass {width: 100%;} I found this to be a great resource for other similar Hotmail issues: Emailology.org
{ "language": "en", "url": "https://stackoverflow.com/questions/7505076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-5" }
Q: JACKSON Mapping XML config Without Annotations I have a library of objects, whose source code is not editable so cant annotate them, is there another way to config Jackson Mapper like via XML. A: What do you want to configure? Often there isn't need to configure anything. One way to use annotations without modifying value classes is to use "mix-in annotations" (see, for example this)
{ "language": "en", "url": "https://stackoverflow.com/questions/7505082", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Why does the C++ standard algorithm "count" return a difference_type instead of size_t? Why is the return type of std::count the difference_type of the iterators (often a ptrdiff_t). Since count can never be negative, isn't size_t technically the right choice? And what if the count exceeds the range of ptrdiff_t since the theoretical possible size of an array can be size_t? EDIT: So far there is no suitable answer as to why the function returns ptrdiff_t. Some explanation gathered from the answers below is that the return type is iterator_traits<InputIterator>::difference_type which is generic and can be anything. Up until that point it makes sense. There are cases where the count may exceed size_t. However, it still does not make sense why the return type is typedef ptrdiff_t iterator_traits<InputIterator>::difference_type for the standard iterators instead of typedef size_t iterator_traits<InputIterator>::difference_type. A: The return type is typename iterator_traits<InputIterator>::difference_type which in this particular case happens to be ptrdiff_t. Presumably difference_type was selected because the maximum number of matching elements in the range would be the iterator difference last - first. A: The std::count() algorithm relies on the iterator type to define an integral type large enough to represent any size of a range. Possible implementation of containers include files and network streams, etc. There is no guarantee that the entire range fits into the process' address space at once, so std::size_t might be too small. The only integral type offered by the standard std::iterator_traits<> is std::iterator_traits<>::difference_type, which is suitable for representing "distances" between two iterators. For iterators implemented as (wrappers of) pointers, this type is std::ptrdiff_t. There is no size_type or the like from iterator traits, so there is no other choice. A: size_t is not technically the correct choice, since it might not be big enough. Iterators are permitted to iterate over "something" that is larger than any object in memory -- for example a file on disk. When they do so, the iterator can define a type larger than size_t as its difference_type, if one is available. difference_type needs to be signed because in contexts other than std::count it represents offsets between iterators in both directions. For random access iterators, it + difference is a perfectly sensible operation even when difference is negative. iterator_traits doesn't offer an unsigned type. Maybe it should, but given that it doesn't iterator_traits<InputIterator>::difference_type is the best type available. The issue of whether iterators should offer an unsigned type probably relates to a massive conflict of coding styles, whether unsigned types should be used for counts at all. I don't propose to reproduce that argument here, you can look it up. ptrdiff_t does have a weakness that on some systems it cannot represent all valid pointer differences, and hence also cannot represent all expected results of std::count. As far as I can tell, even in C++03 the standard actually forbade this, maybe by accident. 5.7/6 talks about subtraction possibly overflowing ptrdiff_t, just like C does. But table 32 (allocator requirements) says that X::difference_type can represent the difference between any two pointers, and std::allocator is guaranteed to use ptrdiff_t as its difference_type (20.1.5/4). C++11 is similar. So one part of the standard thinks that pointer subtraction can overflow ptrdiff_t, and another part of the standard says it can't. std::count presumably was designed under the same (possibly defective) assumption as the allocator requirements, that ptrdiff_t is big enough to express the size of any object and (in general) an iterator's difference_type can express the count of iterands between any two iterators. A: Originally std::count was: template <class InputIterator, class EqualityComparable, class Size> void count(InputIterator first, InputIterator last, const EqualityComparable& value, Size& n); In that function Size is a template parameter. It can be whatever you like, and it's your responsibility to make sure it's correct. It could be the longest type on your platform. My suspicion is that when the newer form: template <class InputIterator, class EqualityComparable> iterator_traits<InputIterator>::difference_type count(InputIterator first, InputIterator last, const EqualityComparable& value); was added iterator_traits was already in existence, so re-using the existing type had the advantage that it kept the changes to the standard small and localised, compared to adding another typedef in iterator_traits. Doing it this way, using iterator_traits as opposed to simply using std::size_type means that every possible iterator gets the option to specify exactly what type should be returned by std::count. This includes custom iterators which read from a network, or disk, which can use something much larger than either ptrdiff_t or size_type and friends. (It could be some kind of "BigInt" if needed). It also means that the user isn't responsible for deducing the appropriate type to use though, which can be tricky, precisely because of the custom iterator possibility. A: Even though a count can't be negative, the return type is specified as iterator_traits<InputIterator>::difference_type and the difference between two iterators can be negative. A: If the iterator was an array, it would imply the result is within the range of the array. For this specific algorithm I can't think of a reason that is interesting. For someone using this as a component it may be interesting, though. The page does say that it would do something equivalent. So for the case of an array it may do something like a direct pointer difference. This would be a pretty fast specialization if it were applicable. A: difference_type usually denotes the type suitable to denote a distance in an array or similar. The following wording is from the allocator requirements, but whenever the standard talks about difference_type it means the same concept: a type that can represent the difference between any two pointers in the allocation model The natural type for this is ptrdiff_t. For the size_type it says: a type that can represent the size of the largest object in the allocation model. The natural type here is size_t. Now for the count of any elements in a range (or an array) does need at least the type suitable to specify the difference last-first. It seems most natural to chose that one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "53" }
Q: Avoid exposing too many assemblies to client consuming WCF service I need a bit of guidance here. I have a WCF service that is part of a larger solution. Currently, too many assemblies must be referenced by an end-consumer due to inheritance issues. For example, here is my basic project setup: MyProject.Domain namespace MyProject.Domain { public interface IFooable{} public class Foo : IFooable{} } MyProject.Contracts namespace MyProject.Contracts { [DataContract] public class FooData : IFooable{} [ServiceContract] public class IFooService { IEnumerable<FooData> GetFoos(); } } MyProject.Proxies namespace MyProject.Proxies { public class WCFClient{} } The problem lies here: class ConsumerCode { private WCFClient = new WCFClient(); void consumeService() { // Compiler error. No reference to MyProject.Domain.IFooable var foos = WCFClient.GetFoos(); } That means an end-consumer who uses the FooData object will have to also include a reference to MyProject.Domain, which stinks because I shouldn't have to expose the Business Logic Layer to the end-client of a WCF service. Is there a way around this? A: Its pretty straightforward- define IFooable in Contracts, not in Domain. The logic here is that anything that is exposed to the client is (by definition) a contract or part of a contract, not a domain entity.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SqlConnection Problems in asp.net i have created a 3tier application.. where i want to call the update method which connect the database and update the records accordingly. below is my database access layer. public class DataLogic { public DataLogic() { } public SqlConnection ConnectDatabase { get { return new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString); } } public int UpdateArticle(BusinessLogic b, int ArticleId) { int updateExecuted = -1; StringBuilder formParamString = new StringBuilder(); formParamString.Append("IsArticlePaging=" + b.IsPagingEnable + " "); string updateString = "update crossarticle_article set " + formParamString.ToString() + "where id = " + ArticleId + ""; try { using (SqlCommand comUpdateArticle = new SqlCommand(updateString, ConnectDatabase)) { ConnectDatabase.Open(); updateExecuted = comUpdateArticle.ExecuteNonQuery(); } } catch (Exception ex) { HttpContext.Current.Response.Write(ex.Message); } finally { ConnectDatabase.Close(); } return updateExecuted; } } below is my business logic layer public class BusinessLogic { DataLogic dLogic = new DataLogic(); public BusinessLogic() { } private bool _IsPagingEnable; public bool IsPagingEnable { get { return _IsPagingEnable; } set { _IsPagingEnable = value; } } private int _articleID; public int ArticleID { get { return _articleID; } set { _articleID = value; } } public int UpdateExtraFieldArticle() { return dLogic.UpdateArticle(this, ArticleID); } } now when i create the BusinessLogic object and call the update method, it calls the DataLogic's update method as expected, but before updating the database it throws error saying, ExecuteNonQuery requires open and available connection. but i have already opened the connection. Please any one help me regarding the sqlconnection. A: The problem is you are opening two separate connections. Try the following: using (sqlConnection connection = ConnectDatabase) { using (SqlCommand comUpdateArticle = new SqlCommand(updateString, connection)) { connection.Open(); updateExecuted = comUpdateArticle.ExecuteNonQuery(); } } A: Your ConnectDatabase always returns a new Connection: public SqlConnection ConnectDatabase { get { return new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString); } } You should use a local variable and initialize it once from a factory-method: public SqlConnection CreateConnection { return new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString); } For example: using (SqlConnection con = CreateConnection()) { using (SqlCommand comUpdateArticle = new SqlCommand(updateString, con)) { con.Open(); updateExecuted = comUpdateArticle.ExecuteNonQuery(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7505101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I make Codeigniter function variables globally available? I am working on a simple game where the user will randomly be generated a bingo board. Once they initialize the game (i.e. round 1 after clicking "start" on index.php), the code starts using a new controller (bingo_play.php). This controller tracks the tiles that have been marked and the information in each tile. Here's the code: $card['products'] = array( 1 => 'hamburger', 2 => 'fries', 3 => 'soda', 4 => 'taco', 5 => 'bacon', 6 => 'onions', // etc. ); if ($card['card_number'] == 1) { $card['card_entries'] = array( 'a1' => '2', 'b1' => '8', 'c1' => '11', 'a2' => '9', 'b2' => '14', 'c2' => '1', 'a3' => '16', 'b3' => '15', 'c3' => '23' ); } I suppose I could assign them as session data, but didn't think that would be the best move. Not really sure as I'm brand new to Codeigniter. In just a normal PHP project, I probably would just run an include() to the function. My question is, what is the best way to make the tiles' id and text available through multiple function calls without having to check and assign the array in each function? A: global variables and $GLOBALS can lead to a lot of problems, and on top of that can be extremely difficult to debug. They have their use, but once you start approaching every problem this way, things can get out of hand and difficult to maintain. My question is, what is the best way to make the tiles' id and text available through multiple function calls without having to check and assign the array in each function? While I'm not 100% clear on what you're working with, and if the card data is static or not, or if users can have several cards or update cards, these tips might help: If the data never changes, use the Config class to your advantage. Store it in a config file, load it, and read the items with config_item() or $this->config->item(). If there's more to it than just some static data, consider creating a class/library to handle everything "bingo board" related. A very simple example: class Bingo_Board { private $card; function get_card($id) { // Assign the values to the $card property if not set yet, // getting the values from the database, a file, or wherever they are // Randomize them, do whatever you want if (empty($this->card)) { $this->card = array(/* your data here*/); } // Return the card return $this->card; } } Then you can access the card like so: $this->bingo_board->get_card(); The values will be set for the duration of the request, and you can expand on this by adding functions like reset_card(), validate_card(), update_card() and so on. If you need to store many cards, just use an array for the $card property and set/get the items by array index. However, if you need the data to persist accross different requests, and the data is not static (for instance, it is updated after each request), you will have to use session data or store it in the database in order to retrieve it in the next request/page. Just store as little data as possible, like the card id perhaps. Codeigniter (and PHP for that matter) provide several ways for you to approach a problem. In the end - use whatever method works best for you. Global variables can be a nice convenient lazy way to get/set arbitrary data, but if you can avoid using them - you should.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I write a Resque condition that says "if a process is running for longer than n seconds, kill it"? I have a god/resque setup that spans a few worker servers. Every so often, the workers get jammed up by long polling connections and won't time out correctly. We have tried coding around it (but regardless of why it doesn't work), the keep-alive packets being sent down the wire won't let us time it out easily. I would like certain workers (which I already have segmented out in their own watch blocks) to not be allowed to run for longer than a certain amount of time. In pesudocode, I am looking for a watch condition like the following (i.e. restart that worker if it takes longer than 60 sec to complete the task): w.transition(:up, :restart) do |on| on.condition(:process_timer) do {|c| c.greater_than = 60.seconds} end Any thoughts or pointers on how to accomplish this would be greatly appreciated. A: require 'timeout' Timeout::timeout(60) do ... end A: Although you have an answer I'll drop this here since I already made it: class TimedThread def initialize(limit, &block) @thread = Thread.new{ block.call } @start = Time.now Thread.new do while @thread.alive? if Time.now - @start > limit @thread.kill puts "Thread killed" end end end.join end end [1, 2, 3].each_with_index do |secs, i| TimedThread.new(2.5){ sleep secs ; puts "Finished with #{i+1}" } end A: As it turns out, there is an example of how to do this in some sample resque files. It's not exactly what I was looking for since it doesn't add an on.condition(:foo), but it is a viable solution: # This will ride alongside god and kill any rogue stale worker # processes. Their sacrifice is for the greater good. WORKER_TIMEOUT = 60 * 10 # 10 minutes Thread.new do loop do begin `ps -e -o pid,command | grep [r]esque`.split("\n").each do |line| parts = line.split(' ') next if parts[-2] != "at" started = parts[-1].to_i elapsed = Time.now - Time.at(started) if elapsed >= WORKER_TIMEOUT ::Process.kill('USR1', parts[0].to_i) end end rescue # don't die because of stupid exceptions nil end # Sleep so we don't run too frequently sleep 30 end end A: Maybe take a look at resque-restriction? It doesn't appear to be under active maintenance but might do what you need.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505107", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: $facebook->getUser() fails, but fb:login-button indicates that user is logged in At some point, Facebook changed the behavior of the fbml login button so that it does not appear when the user is already logged into your website via FB. That's all well and good, but I am running into a situation where the PHP SDK thinks that the user is not logged in, but the FBML button DOES think that the user is logged in, and as a result, it's not displaying itself. Any ideas for how I might debug this further? This might be an edge case, but I need to fix it because users won't be able to log in when the FB button is missing. A: Here is an update on what we have learned for anyone running into the same problem. The problem appears to occur because we upgraded our Facebook PHP SDK to 3.1.1 from a previous version. After tracing through the code, we learned that in the previous version of the FB PHP SDK, session state was stored in a cookie called fbs_. The new version of the SDK isn't able to restore the session from this cookie. Instead, it relies on a cookie called fbsr_ in order to store a signed request. So if fbs_ is set a certain way, the fb:login-button thinks that you are logged in, but the 3.1.1 SDK does not think you are logged in. We tried manually clearing the fbs_XXX cookie via code, but that cookie would be restored every time the fb:login-button did its thing. In the end, we ended up creating our own login button using $facebook->getLoginUrl(), which seems like the new way that Facebook wants you to do things anyway.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java GAE DeferredTask example? I'm a bit confused by the documentation for Java DeferredTask. I've read the Python documentation here: http://code.google.com/appengine/articles/deferred.html but I'm unclear on exactly how I'd use the Java version. Can you provide working sample code that launches a DeferredTask to do a simple write using a DatastoreService? A: To use deferred, you first have to define a class that contains the code you want to run: class MyDeferred implements DeferredTask { @Override public void run() { // Do something interesting } }; Just like any other serializable class, you can have locals that store relevant information about the task. Then, to run the task, instantiate an instance of your class and pass it to the task queue API: MyDeferred task = new MyDeferred(); // Set instance variables etc as you wish Queue queue = QueueFactory.getDefaultQueue(); queue.add(withPayload(task)); You can even use anonymous inner classes for your tasks, but beware of the caveats described in the note here. A: The Java deferred library is still not in the GAE SDK and that's why you can't find any Official documentation. This feature request is fixed since March 2011 and you can now use the deferred library straight from the Sdk You could use the Vince Bonfanti deferred library that is available here. The library usage is fairly simple and it is well explained in the doc: 1) The deferred task handler (servlet) needs to be configured within web.xml. Note that the init-param must match the actual url-pattern: <servlet> <servlet-name>Deferred</servlet-name> <servlet-class>com.newatlanta.appengine.taskqueue.Deferred</servlet-class> <init-param> <param-name>url-pattern</param-name> <param-value>/worker/deferred</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Deferred</servlet-name> <url-pattern>/worker/deferred</url-pattern> </servlet-mapping> 2) The "deferred" queue needs to be configured within queue.xml (use whatever rate you want). If you use the optional queue name in the defer() method, create queues with the appropriate names. <queue> <name>deferred</name> <rate>10/s</rate> </queue> 3) Create a class that implements the com.newatlanta.appengine.taskqueue.Deferred.Deferrable interface; the doTask method of this class is where you implement your task logic. 4) Invoke the Deferred.defer method to queue up your task: DeferredTask task = new DeferredTask(); // implements Deferrable Deferred.defer( task ); If the task size exceeds 10KB, the task options are stored within a datastore entity, which is deleted when the task is executed. Your doTask method can throw a PermanentTaskFailure exception to halt retries; any other exceptions cause the task to be retried. Couple of bonus links: * *Feature request here. *Google groups thread here. *Github Fork
{ "language": "en", "url": "https://stackoverflow.com/questions/7505116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Can I pass T to a class constructor I have a class such as: public MyClass { public myEnumType Status {get;set;} public DataTable Result{get;set;} } Because DataTables suck I want to implement an object orientated approach. However I have existing code such as: public interface IData { MyClass AddData(int i); MyClass GetData(string Tablename); } I would like to use this interface but instead of returning a DataTable I want to return an object of some sort eg/Person class. I did think of creating a new class that inherited MyClass like so: public MyInheritedClass<T> : MyClass { public new T Result{get;set;} } However whenever you get data from a class that implements the interface you will have to cast the result of the methods from MyClass to MyInheritedClass. So I was wondering if there was a way of using the existing MyClass to put a constructor in that passes a generic type so I end up with something like public MyClass { public MyClass(T MyObjectOrientatedClass) { MyOOClass = MyObjectOrientatedClass; } public myEnumType Status {get;set;} public DataTable Result{get;set;} public T MyOOClass {get;set;} } A: You can't refer to a generic type parameter without declaring it in the pointy brackets, so you'll either have to have a IData<T> and/or MyClass<T> type, in which case you won't need to specify it as a parameter to the constructor. If you can't change those types you can still avoid explicit casting by using dynamic dispatch. Overload a method with the different subtypes and use a dynamic expression to defer the method resolution to runtime, and it'll be automatically cast to the subtype for you: void DoSomethingWith(Person p) { ... } void DoSomethingWith(AnotherClass x) { ... } void DomSomtheingWithMyInheritedClass(MyClass x) { DoSomethingWith((dynamic) x.Result); } A: In C#, the types of expressions are determined by the types of their constituent pieces at compile time. This means something like your last example (where the type of the property is unknowable just by knowing the type of the class) can't work. Imagine if that class definition compiled. Then you have this problem: // What would you use as the type of this variable? ??? val = GetMyClassFromSomewhere().MyOOClass; Sure you could use object, but then you wouldn't know anything about the property value, so you'd have to cast before you could do anything with it anyway. Addressing your original issue, it is possible (with a few rough edges) to extend your existing types in a compatible fashion by deriving a new generic interface from your existing IData interface: public interface IData<T> : IData { new MyInheritedClass<T> AddData(int i); new MyInheritedClass<T> GetData(string Tablename); } A: Why not create a generic interface like public interface IData<T> { T AddData(int i); T GetData(string Tablename); } we can then even have a generic implementation: public class MyGenericClass<T> : IData<T> { } A: While it is a somewhat horrible idea, as long as what you wanted to put into T can be boxed into MyClass, you could write a method like... public T GetResult<T>() where T : MyClass { return (T)Result; } Pretty gross, but it would allow you to "encapsulate" the cast. In reality, though, we're talking about the difference between... var result = (DerivedMyClass)obj.Result; ...and... var result = obj.GetResult<DerivedMyClass>(); I'm not sure I think one of those is necessarily better than the other and would probably just stick with casts.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery - Syntax Error in a Conditional $(".editAd").change({ if ($(this).val() == 1) { $("#submitBtn").val("Next Step"); } else { $("#submitBtn").val("Submit Changes"); } }); There is a syntax error on the second line of this code. Missing : after property ID. I swore this was the proper use of val() in a conditional, but I suppose I could be wrong... I know this is a pretty simple fix, but I can't find any resources off of a few minutes of research, and I was hoping the users of SO could help me out. :) Thank you! EDIT: There's always a silly error that developers make that stumps them for a period of time... Always review the ENTIRETY of your code for errors because the developer tools may not actually pick up the proper line of the error, as in this case. A: You forgot to include function(){} $(".editAd").change(function(){ if ($(this).val() == 1) { $("#submitBtn").val() = "Next Step"; console.log($("#submitBtn").val()); } else { (element.attr("name") == "submitBtn").val() = "Submit Changes"; // no idea what this is but it doesn't look like it will work } }); A: val() is a function execution. to set a value do something like $('selector').val('set me'); not $('selector').val() = 'set me'; start there. Other things might clear up. A: Missing : after property ID This is caused by the lack of a function () identifier before the conditional. Because it was bracketed {} the javascript parser thought you were passing an object literal with if as a property identifier. It was looking for a colon after it to identify the value of the property. Not sure what you are trying to do on this line: (element.attr("name") == "submitBtn").val() = "Submit Changes"; But it looks like you are trying to call val on a boolean value, which is not valid. You are also assigning a string to the output of val() which won't work. To assign a value to an element, jQuery's val takes one parameter: element.val("Submit Changes"); A: There are numerous problems with your code. Firstly, the cause of the error you are talking about, is the missing function keyword. That's required as the change method takes a function as an argument. Next, you're assigning a value to the val method, which is incorrect ($("#submitBtn").val() = "Next Step";). You need to pass the string in as an argument. Third, your else block is very confusing. I'm not sure what you were trying to do there, but it will evaluate to something like true.val() = "Submit Changes"; which is completely wrong. It's another assignment to a function, and you're trying to call that function on a boolean value, not a jQuery object. So, based on all that, this is what I think you were trying to do: $(".editAd").change(function(){ if ($(this).val() == 1) { $("#submitBtn").val("Next Step"); console.log($("#submitBtn").val()); } else { if($(element).attr("name") == "submitBtn") { $(element).val("Submit Changes"); } } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7505124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to set up my WCF service to be able to be accessed by remote clients I have a WCF service that is being hosted in a windows service and I can connect to it and consume its services just fine when using the same machine, but when I try to run my client on a remote machine it times out and won't connect. I thought I could just update the app.config file for the client with the IP of the service machine instead of localhost, but that didn't work. Here is the app.config of the client: <system.serviceModel> <bindings> <wsDualHttpBinding> <binding name="WSDualHttpBinding_IWCFService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"> <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> <reliableSession ordered="true" inactivityTimeout="00:10:00" /> <security mode="Message"> <message clientCredentialType="Windows" negotiateServiceCredential="true" algorithmSuite="Default" /> </security> </binding> </wsDualHttpBinding> </bindings> <client> <endpoint address="http://192.168.1.141:8731/Design_Time_Addresses/WCF/WCFService/" binding="wsDualHttpBinding" bindingConfiguration="WSDualHttpBinding_IWCFService" contract="WCFService.IWCFService" name="WSDualHttpBinding_IWCFService"> <identity> <dns value="192.168.1.141" /> </identity> </endpoint> </client> And here is the app.config of the serivice: <system.serviceModel> <services> <service name="WCF.WCFService" behaviorConfiguration="WCFBehavior"> <endpoint address="" binding="wsDualHttpBinding" contract="WCF.IWCFService"> <identity> <dns value="localhost" /> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" bindingConfiguration="" contract="IMetadataExchange"/> <host> <baseAddresses> <add baseAddress="http://localhost:8731/Design_Time_Addresses/WCF/WCFService/" /> </baseAddresses> </host> </service> </services> <behaviors> <serviceBehaviors> <behavior name="WCFBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> Is there something I need to do on the service side to allow remote connections or am I just no configuring the client correctly? A: This may seem like a simplistic suggestion, but have you checked the firewall on your server to make sure that it's not blocking communications? I spent three days banging my head on a wall until I noticed that. A: This seems like you are doing this from home based on your 192 address. You will need to punch a whole in your router and windows firewall to start. After that if you want to access this out side of your house you should try using DynDNS to fake having a static IP for hosting the service. A: Are you able to telnet to your service? If it is not a firewall issue, I suspect from the service security. Since it configured to authenticate via windows credential, which requires your service and client to be in the same domain, correct me if I'm wrong. A: It might be a better option than simply disabling the windows firewall to add a rule for the specific port using: Firewall -> Advanced Settings -> Inbound Rules -> New Rule.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: LDAP | How to programmatically tell whether a search for specific attribute is case sensitive? Many LDAP attributes are defined case-insensitive for search. For example: userId ATTRIBUTE ::= { WITH SYNTAX DirectoryString { 256 } EQUALITY MATCHING RULE caseIgnoreMatch SUBSTRINGS MATCHING RULE caseIgnoreSubstringsMatch ID id-userid } However, this may be changed by the administrator. How can I determine whether a specific attribute search is case-sensitive? Is there a way to check this programmatically? Thanks! A: Use :caseExactMatch:. See RFC 4515.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to cancel ASIHTTPRequest with wrong response HTTP code? I'm uisng ASIHTTPRequest for HTTP requests and to save result into separate file. As the file is expected to be large, it should also be able to resume. request.allowResumeForFileDownloads = YES; request.downloadDestinationPath = destFile; request.temporaryFileDownloadPath = tmpFile; I use the following selectors: request.didFinishSelector = @selector(didFinishRequest:); request.didFailSelector = @selector(didFailRequest:); request.didReceiveResponseHeadersSelector = @selector(didReceiveResponse:); Now I'm testing different cases with loosing connection, different proxies, etc and found a problem, that if a response is received with code other like 503 or something, then ASIHTTPRequest still saves result into temp file, which is wrong, because the data is some random HTML page with error (if there was partial downloaded file, then this HTML is appended to it which makes my data corrupted). So what I'm trying to do is to check response code and if it is not 2XX, then cancel request without saving anything. This doesn't help: - (void)didReceiveResponse:(ASIHTTPRequest*)request { if (request.responseStatusCode < 200 || request.responseStatusCode >= 300) { [request clearDelegatesAndCancel]; Any ideas? A: So far haven't found a clean solution, so there is a little hack: In ASIHTTPRequest.m in the very last line of method readResponseHeaders we need to change to waitUntilDone:YES (line 2281), so the code doesn't continue running and processing data. [self performSelectorOnMainThread:@selector(requestReceivedResponseHeaders:) withObject:[[[self responseHeaders] copy] autorelease] waitUntilDone:YES]; Unfortunately, in the didReceiveResponse: selector we can't simply call clearDelegatesAndCancel method, as it will just hang the thread, because of the locks in ASIHTTPRequest. So what I did is just used some of the methods that I took from ASIHTTPRequest: [request setComplete:YES]; [request setDownloadComplete:YES]; [request requestFinished]; [request markAsFinished]; Although, the first two methods are not public and Xcode shows warning, but it still works. By the way, just 2 days ago I saw a post saying that ASIHTTPRequest is not being supported any more :(
{ "language": "en", "url": "https://stackoverflow.com/questions/7505132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does my very simple Chrome extension work on Mac but not PC? I have written a very simple Chrome extension. It consists of this background page: <script type="text/javascript"> chrome.tabs.onDetached.addListener(function(tabId, info){ var id = tabId; chrome.tabs.get(id, function(tab) { chrome.tabs.create({ windowId : info.oldWindowId, index : info.oldPosition, url : tab.url }); }); }); </script> All it does is allows you to pull a tab from a window without losing that tab and web address from the window. It basically duplicates the tab when you detach it. The problem is that this works perfectly on a Mac but when I have tried it on two different Windows machines I get this error background.html:7Uncaught TypeError: Cannot read property 'url' of undefined It appears the tab object isn't being passed into the get callback. Does anyone know why this might be? It obviously is when I run the code on a Mac. A: So this is the only workaround that I can think of: * *OnDetached - store id of tab and also its window id *OnAttached - check whether tab id matches stored tab id AND that window id is now different. If so then create new tab in the old window. Behavior does seem wonky. Perhaps file a bug report? A: The problem is tab id changes after it is detached (old one doesn't exist anymore). Not sure whether it is an error or feature, but if it is inconsistent between Mac and PC then it is definitely an error (could be just performance difference - api method executes faster than tab detaches on a different computer). mrtsherman was on right track with workaround, only instead of saving id you should save info as that id doesn't mean anything anymore. Then you would have all information to recreate a tab (use attached info to get tab id, and saved detached info to get old position and window).
{ "language": "en", "url": "https://stackoverflow.com/questions/7505135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to break apart an integer? Let's say I have an integer, such as 2,734,465, and it is called intOne. How do I "break apart" that integer so that I can put the number in 7 UILabels? So, in the first label I will have 2, then in the second label I will have 7, and so on. How would I do this? Thanks for your help! A: Convert it to a string using something like NSString *intString = [NSString stringWithFormat:@"%d", myInt]; Then you can get the individual characters out: myChar = [intString characterAtIndex: i]; A: After you have the string you may also use: NSString *keyStr = [intString substringWithRange:NSMakeRange (i, j)]; to get a substring directly As an alternative to string manipulation this is how you break the number n apart mathematically: int n = 1357246; int digit; int divisor; for (int i = log10(n); i> 0; i--) { divisor = pow(10,i); digit = n / divisor; n = n - digit*divisor; NSLog(@"%i ",digit); } NSLog(@"%i ",n); A: Here's a different approach. This creates an array whose elements are the individual digits (and a preceding "-" if negative): #import <Foundation/Foundation.h> NSArray* brokenArrayWithInt(NSInteger intOne) { NSMutableArray *result = [[[NSMutableArray alloc] init] autorelease]; BOOL isNegative = NO; if (intOne < 0) { isNegative = YES; intOne = -intOne; } do { [result insertObject:[NSNumber numberWithInteger:intOne % 10] atIndex:0]; intOne /= 10; } while (intOne > 0); if (isNegative) { [result insertObject:@"-" atIndex:0]; } return result; } int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSArray *brokenArray = brokenArrayWithInt(2734465); NSLog(@"Array: %@", brokenArray); brokenArray = brokenArrayWithInt(-2734465); NSLog(@"Array: %@", brokenArray); brokenArray = brokenArrayWithInt(0); NSLog(@"Array: %@", brokenArray); [pool drain]; return 0; } Here's the result: Running… 2011-09-21 12:28:52.531 so7505138[6739:a0f] Array: ( 2, 7, 3, 4, 4, 6, 5 ) 2011-09-21 12:28:52.533 so7505138[6739:a0f] Array: ( "-", 2, 7, 3, 4, 4, 6, 5 ) 2011-09-21 12:28:52.533 so7505138[6739:a0f] Array: ( 0 ) A: It depends if you want the number to pick up the relevant locale specific formatting for e.g. thousand separators and decimal point. If you do, then turn it to a string and then extract characters as others have suggested. If you want to get the value of each decimal digit, then you divide modulo 10, 100, 1000 etc, starting from the power of 10 that is less than the total value (e.g. for 213, start with 100, then 10, then 1) A: Cast the integer into a string - then use a method to split/substring the string into 7 strings. Or the amount which you require. Put a string in each label. Start off with [NSString stringWithFormat:@"%d", myNum];
{ "language": "en", "url": "https://stackoverflow.com/questions/7505138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Dynamic expression in linq I am trying to make a library where I can specify query parameters and operators in an xml file and at runtime i can generate linq expressions based on an xml file. I have it working only on building the "where" expressions so simple queries such as select * from table where table.id = 1. Here is an example of a simple query in the xml file: <query name="latest"> <PropertyValue PropertyName="TimeStamp" OperatorName="GreaterThanOrEqual" ParamName="lastUpdated" /> </query> The TimeStamp property name is the name of the Property in the C# class to use. The ParamName is a url parameter coming in from a http request in my asp.net application. In the code i can build the linq expression out of this and make the following where clause: (IQueryable<DataObject>)dataObjects.Where(expression); where expression is: TimeStamp >= "2011-09-21T11:54:24" But i have a new type of query that i need to be able to handle: select * from theTable t where Id=(select top 1 Id from theTable where Source=t.Source order by Id desc) This query runs on a table that has an Id field and a Source field. The query returns the newest entry per each Source. So it groups by source and orders it in descending order and returns the first entry for each source. Then the outer select returns all the columns for each of the results in the inner select. Example: Table: id source field3 field4 1 Device1 test test 2 Device2 test2 test2 3 Device1 test3 test3 4 Device2 test4 test4 Results of the query: id source field3 field4 3 Device1 test3 test3 4 Device2 test4 test4 So now i need to dynamically generate a nested query in the where clause. I guess my first question is can that string query be converted to a linq query? Then i need to be able to dynamically build that nested query somehow.. Sorry if it doesn't make a lot of sense... A: Maybe the PredicateBuilder is what you're looking for?
{ "language": "en", "url": "https://stackoverflow.com/questions/7505142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to output a Euro symbol in a PDF I am trying to output a Euro symbol to a PDF using Core Graphics. I have the following code, which uses NSMacOSRomanStringEncoding (I had to use this to get £ and $ symbols to appear correctly), but the Euro symbol comes out as ¤ CGRect pageRect = CGRectMake(0, 0, 800, 1150); CFMutableDataRef pdfData = (CFMutableDataRef) [NSMutableData dataWithCapacity:0]; CGDataConsumerRef dataConsumer = CGDataConsumerCreateWithCFData(pdfData); CGContextRef pdfContext = CGPDFContextCreate(dataConsumer, &pageRect, nil); CGContextSelectFont(pdfContext, "Helvetica", 15, kCGEncodingMacRoman); CGContextSetTextDrawingMode (pdfContext, kCGTextFill); CGContextSetRGBFillColor (pdfContext, 0, 0, 0, 1); const char *ctext = [@"€" cStringUsingEncoding:NSMacOSRomanStringEncoding]; CGContextShowTextAtPoint(pdfContext, 10, 10, ctext, strlen(ctext)); A: Thats because MacRomanEncoding doesn't contain euro symbol by default, see this quote from "PDF reference 1.7" (Section D.1 Latin Character Set and Encodings): * *In PDF 1.3, the euro character was added to the Adobe standard Latin character set. It is encoded as 200 in WinAnsiEncoding and 240 in PDFDocEncoding, assigning codes that were previously unused. Apple changed the Mac OS Latin-text encoding for code 333 from the currency character to the euro character. However, this incompatible change has not been reflected in PDF’s MacRomanEncoding, which continues to map code 333 to currency. If the euro character is desired, an encoding dictionary can be used to specify this single difference from MacRomanEncoding. A: You should be able to use CGContextShowGlyphsAtPoint to draw the Euro symbol. The catch is that you need to pass that function a CGGlyph as input, rather than a Unicode character. Furthermore, the mapping from Unicode characters to CGGlyphs is font-dependent and often nontrivial. (Sometimes it's a simple offset that you can guess based on trial and error.) It looks like Core Text has a function CTFontGetGlyphsForCharacters which might perform the transformation; I've never used it in practice, though: http://developer.apple.com/library/mac/#documentation/Carbon/Reference/CTFontRef/Reference/reference.html Also: if you use CGContextShowGlyphsAtPoint you will need to replace the call to CGContextSelectFont with CGContextSetFont and CGContextSetFontSize instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505143", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: module array output I'm writing a module to add functionality to the FlagShihTzu gem. Basically it goes through the flags and outputs the keys for the ones assigned to the object. It's working, but I also want to be able to use a block in the view to do things with the output. The problem is that it's outputting both the array from the module and the output from the block in the view. module AwesomeFlags def my_flags(column = nil) a = self.flag_mapping if column.nil? c = a.values.map {|var| var.keys}.flatten else b = a[column] c = Array.[](b.keys).flatten end c.map {|var| self.send(var) ? "#{var.to_s} " : nil}.compact! end end In the view: = book_offer.my_flags.each do |flag| = flag.titleize What I get is: Regular Complimentary regular complimentary A: You should switch that to be: - book_offer.my_flags.each do |flag| = flag.titleize The = means to include the output of the method call, where - means to simply execute it. The each loop is returning the items in the list.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: phonegap + codeigniter ajax question I have phonegap and jquery mobile working properly and am trying to add codeigniter into the picture. I'm thinking there might be a few ways of doing this to send/receive data. I've searched for such a question and read the codeigniter nettuts tutorial but am still confused to make it work with phonegap. For an example, to help explain, lets assume I'm trying to receive an array of objects that stores 3 fields, id, articleheadline and article. Article System -Table fields id articleheadling- text article $.ajax({ url: 'http://www.server.com/controllername/method/id', success: function( data ) {alert('add to view'); }}); Can i use a .ajax post call to a controller like (http://www.server.com/controllername/method/id) and load it into a div using a json returned var from php to js where the array or objects is added to the view( i.e. screen) or should I have the ajax call return a partial html thats processed on serverside to the view. I'd really appreciate any examples , I've also saw an example I think I can use here <?php $jsonurl = "http://search.twitter.com/trends.json"; $json = file_get_contents($jsonurl,0,null,null); $json_output = json_decode($json); foreach ( $json_output->$articles as $article ) { echo "{$article->$articleheadline}\n"; } ?> the url in the above example is from the original. but if I tried something like that what would that trends.json file look like? I hope this wasnt too long but I tried my best to split up my questions. Thanks A: For use with phonegap, I've tried this approach: Use jQuery Mobile and save mustache templates in your phonegap application. Then use jquermobile to request json data from the controller, and load the response in the mustache template. This will require you to hack the jquery mobile library to support mustache templates and reading/populating template files. In the above, your codeigniter application is essentially acting as a REST API that returns a json response, which contains data to load in the mustache template, the template file to load, and any error messages or such to display. The phonegap+jquerymobile setup is dumbed down to handle navigation and page rendering only. Each link the application maps to an api url that jquerymobile calls via ajax automatically.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: running SKYPE4COM on iis 64bit I create a web application that communicate with Skype by using SKYPE4COM. Now, I have finished with my coding and the program can run properly. I use VS2008 and config a debug mode that run on x86 (Actually my machine is 64 bit) So,I put my code on iis7 and run this page but it's not working anymore. Does anyone have a idea to fix this problem? I search all information in the internet. Maybe the problem is SKYPE4COM must run as a 32 bit application. A: You are right. SKYPE4COM is a 32 bits COM server and so it registers itself in the 32 bits registry halve. You can write a COM "LOCAL SERVER" that's simple an executable that exposes COM components. Since you have control over this LOCAL SERVER you can set it up to run as x86 and then SKYPE4COM should work (assuming the user which IIS runs have the required rights) Hope this helps. A: Compile your web app for 32bits. Build -> Platform Target: x86. A: Set your application pool under IIS to classic that should do the trick
{ "language": "en", "url": "https://stackoverflow.com/questions/7505150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Sandboxed Plugin architecture I was googling and searching SO for plugin architecture and I'm satisfied by general knowledge on how to implement it. Now I went further to look for a sandboxed architecture. Basically what I mean is an application with plugin whereby crashing in plugin won't crash the whole app and the plugin can be reloaded. I cannot find good documentation. I know Firefox implements it (crashing flash plugin does not affect whole FF thing and can be reloaded) Thanks! A: The only way you can have a truly sandboxed architecture wherein a plug-in cannot directly crash the parent application's process or corrupt its memory is by placing it into a separate OS process, with a separate memory space. When doing this, you will need to rely on interprocess communication facilities of the OS (pipes, sockets, remote procedure calls, memory mapped files, shared memory, synchronization objects, etc.) to interact with the plug-in. A: Google's native client technology may be more thorough than what you were looking for, but it might be worth a read.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505151", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Updating jquery version in rails I'm running rails3 and was going to play around with jquery mobile, but it requires jQuery 1.5, and my install is currently using 1.4 When I run rails g jquery:install I get a jQuery UJS error, but it might not matter because it says 'downloading jQuery 1.4.4', which is the same version I already have. When I request jQuery v 1.6.1 from with the javascript_include_tag, rails says that the version of jQuery isn't compatible with rails. Should I just turn off the error?? If so, how? Or should I somehow update something else in rails? How can I update the version of jQuery?
{ "language": "en", "url": "https://stackoverflow.com/questions/7505152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }