text
stringlengths
8
267k
meta
dict
Q: Is it possible to pull in all styles from external style sheets and put them on the same page? Is it possible with javascript or jQuery to pull in all CSS rules that are listed in external files, then do $('link').remove(), then put all the CSS rules in style blocks on the same page? To clarify: I want to move all external CSS rules into inline style blocks in the page with JavaScript, yes. If so, how might I go about accomplishing this? A: Well you could do something like: var $stylesheets = $("head link[rel=stylesheet]"), $style = $('<style>').appendTo('head'); $stylesheets.each(function() { var href = $(this).attr("href"); $.get(href, function(data) { $style.append(data); }); }); $stylesheets.remove(); Keep in mind that this will screw up relative paths to images/fonts in loaded stylesheets. A: I've left out the details about appending the rules as "inline" rules. That should be fairly trivial. Also, you'll see below I have DISABLED the style sheets rather than actually removing them. the important thing I want to hilight is that this solution allows for stylesheets that import other stylesheets. TEST.HTML <html> <body> <link rel="stylesheet" type="text/css" media="screen,projection" href="screen.css"> <link rel="stylesheet" type="text/css" media="screen,projection" href="screen2.css"> </body> <script> function processSheet(sheet){ if (sheet.cssRules){ for (var i=0; i< sheet.cssRules.length; i++){ if (sheet.cssRules[i].type == 3){ processSheet(sheet.cssRules[i].styleSheet); } else{ alert(sheet.cssRules[i].cssText); } } } } for (var i=0; i< document.styleSheets.length; i++){ processSheet(document.styleSheets[i]); } for (var i=0; i< document.styleSheets.length; i++){ processSheet(document.styleSheets[i].disabled=true); } </script> <div>Hi</div> </html> screen.css @import url("reset.css"); table { background-color:green; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7531269", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jqgrid Export to Excel roadmap? Does anyone know when an export to Excel/CSV function is going to be built into JQGrid? There are a handful of workarounds but we're looking for some simple functionality. A: see Does jqgrid support exporting to excel " out of the box" or do i need to write some server side code? I'm not affiliated with the jqGrid team, but I don't think there are any plans in the works to build the Excel export into the native jqGrid JavaScript library. You probably have to buy the php or ASP.NET libraries for that since the Excel generation requires server-side processing. It wouldn't be too hard to write a JSON-to-CSV converter in JavaScript, but do you really want to ? Also, I can't really think of a way to serve a file to a user purely via JavaScript. This question appears to address that problem using js & Flash Generate some xml in javascript, prompt user to save it Assuming you want to generate the Excel server-side, your best bet is to either buy the paid product, or write your own code to do it using the same datasource as the grid. A: This is an old thread, but just in case anyone else hits this issue. A few years ago, I wrote a C# class which let you export any DataSet, DataTable or List<> to a "real" Excel file, using the OpenXML libraries, with one line of code. C# ExportToExcel library I then documented a JavaScript library which would let you call this C# code from an Export button in your jqGrid: Full details here: Export to Excel from jqGrid The only gotcha is that your jqGrid must have the loadonce value set to true. If it isn't, my JavaScript code doesn't have access to the entire set of data which needs to be export to Excel. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531281", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript function not being called when submitting a form I am trying out this tutorial: http://www.9lessons.info/2009/04/submit-form-jquery-and-ajax.html and I am testing it on this sandbox here: http://www.problemio.com When I press the submit button of the form to add a problem, it doesn't do anything, and even there is no output to my javascript console in Chrome. I also added an alert statement in the JavaScript to see if it is being called, but that also isn't working. Any idea what I am doing wrong? Here is my code: <script type="text/javascript" > $(function() { $(".submit").click(function() { alert ("1"); var name = $("#name").val(); var username = $("#username").val(); var password = $("#password").val(); var gender = $("#gender").val(); var dataString = 'name='+ name + '&username=' + username + '&password=' + password + '&gender=' + gender; if(name=='' || username=='' || password=='' || gender=='') { $('.success').fadeOut(200).hide(); $('.error').fadeOut(200).show(); } else { $.ajax({ type: "POST", url: "join.php", data: dataString, success: function(){ $('.success').fadeIn(200).show(); $('.error').fadeOut(200).hide(); } }); } return false; }); }); </script> and the form setup: <form name="form" method="post"> A: You need an action attribute on your form tag to tell the form where to submit to. EDIT Also, the jQuery is not firing because this selector doesn't match your submit button: $(".submit").click. Try $("input[type=submit]").click A: Basing on the source code sample you indicated, first you must add an action attribute (even a fake one containing "#") to the form to enable form submission. Second, remember the ajax method url must be complete (e.g.: http://localhost/join.php). Edit: I also prepared a new example based on the one you posted; it is working for me. Please take care of changing the ajax method destination url. <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script> <script type="text/javascript" > $(function() { $(".submit").click(function() { var name = $("#name").val(); var username = $("#username").val(); var password = $("#password").val(); var gender = $("#gender").val(); var dataString = 'name='+ name + '&username=' + username + '&password=' + password + '&gender=' + gender; if(name=='' || username=='' || password=='' || gender=='') { $('.success').fadeOut(200).hide(); $('.error').fadeOut(200).show(); } else { $.ajax({ type: "POST", url: "http://localhost/test/join.php", data: dataString, success: function(){ $('.success').fadeIn(200).show(); $('.error').fadeOut(200).hide(); } }); } return false; }); }); </script> </head> <body> <form method="post" name="form" action="#"> <ul><li> <input id="name" name="name" type="text" /> </li><li> <input id="username" name="username" type="text" /> </li><li> <input id="password" name="password" type="password" /> </li><li> <select id="gender" name="gender"> <option value="">Gender</option> <option value="1">Male</option> <option value="2">Female</option> </select> </li></ul> <div > <input type="submit" value="Submit" class="submit"/> <span class="error" style="display:none"> Please Enter Valid Data</span> <span class="success" style="display:none"> Registration Successfully</span> </div></form> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7531282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ajax not executed with Jasmine I have troubles executing ajax with the Jasmine BDD framework. I want to test the actual ajax calls, not make fake responses. I have read the documentation and tried everything but it seems that the ajax code is simply ignored. i have also tried using spies but it doesn't seem to help. A very basic example that is not working: describe("A jQuery ajax test", function() { it("should make AJAX request", function () { expect(testAjax()).toBe(1); }); }); function testAjax() { var ret=0 $.ajax({ type: "GET", url: "obj.json", contentType: "application/json; charset=utf-8", dataType: "json", success: function(data){ret=1;} }); return ret; } The return is always 0, it never enters the success function. What am I doing wrong? A: Anwering my own question. Ajax calls in Jasmine needs to be async. If you do not want to change your code to be able to test it you can use the ajaxSetup to set the dafault value for async to be false it("getsetting", function () { $.ajaxSetup({ async:false }); expect(getUserSetting(101,0)).toBe('30'); }); A: While setting async to false solves the problem it's usually not an option in most of web applications because whole page will be locked during the ajax call. I would pass in callback function to testAjax() method that would be executed when you get response from the web service. You can then make an assertion(expect) inside your callback. It should look something like this: function testAjax(callback) { var ret=0 $.ajax({ type: "GET", url: "obj.json", contentType: "application/json; charset=utf-8", dataType: "json", success: function(data){ callback(ret); }, error:function(){ callback(ret); } }); } describe("A jQuery ajax test", function() { it("should make AJAX request", function () { testAjax(function(ret){ expect(ret).toBe(1); }); }); }); A: I understand that you would like to write an Integration test using jasmine, which is quite possible thanks to Async Support that jasmine has, I hope following example would help you understand how you can useAsync features of jasmine to write the an actual integration test: describe("A jQuery ajax test", function() { it("should make AJAX request", function () { var return = null; runs(function(){ // hosts actual ajax call return = testAjax(); }); waitsFor(function(){ //this method polls until the condition is true or timeout occurs,whichever occurs first return return.readyState==4; },"failure message",700//timeout in ms ); runs(function(){ // 2nd runs block can be used to verify the actual change in state // Add other relevant expectation according to your application context. expect(return).toBeTruthy(); }); }); }); function testAjax() { // result here is a deffered object whose state can be verified in the test var result = null; result = $.ajax({ type: "GET", url: "obj.json", contentType: "application/json; charset=utf-8", dataType: "json", success: function() { //do something on success} }); return ret; }​ Please note: While running the AJAX call you will be restricted by Cross-origin_resource_sharing and your server must return as per part of the response a header "Access-Control-Allow-Origin:your requesting domain "
{ "language": "en", "url": "https://stackoverflow.com/questions/7531283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: jQuery Accordion + Magento problems - Possible conflict? I'm using the jQuerytools accordion/tab within a Magento environment and for some reason the script doesn't seem to be working. If you look at the working page below you will see the content and script in a standalone environment working ok. But as soon as it is dropped in to Magento (Non-working page) the accordion panes don't open and I can't see any obvious errors. Working Page - http://www.justkitchens.co/sandbox/JustDoors/acrylic-kitchen-doors-chooser.html Non-Working Page - http://www.justkitchens.co/chooser-test/ Can anyone help me out here? EDIT: I've commented out the jquery-ui.min.js script being called up and things seem to be working... so looks like a conflict there... A: Are you running jquery in noConflict mode? Magento uses prototype so you need to do this. From http://www.fontis.com.au/blog/magento/using-jquery-magento: Normally, this would be all you need to do, however because Magento also includes Prototype, there is a subtlety we need to deal with. jQuery uses $ as shorthand for accessing the jQuery library. But Prototype also uses $ to access itself. This causes a conflict in the global JavaScript namespace of the web browser. Fortunately jQuery provides a solution, the jQuery.noConflict(); function defines a new shorthand for jQuery, such as: var $j = jQuery.noConflict(); The above code needs to come after the jQuery library code, but before any other JavaScript libraries. You can include the noConflict call at the bottom of the jQuery file you have copied to the js directory. Therefore you need make sure that "action method" line we included in layout/page.xml comes before the code that includes Prototype or any other JavaScript libraries. An alternative article on it: http://css-tricks.com/2011-using-jquery-in-magneto/
{ "language": "en", "url": "https://stackoverflow.com/questions/7531287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to implement a webkit animation: backgroundmove I've seen a certain webkit animation type: backgroundmove. It basically just scrolls your background across the page, etc. I've written a little css blurb for a basic -webkit-backgroundmove animation, but it doesn't work! I've tried everything on IE9/FF4/Chrome (latest). Question: is there something that interferes with the animation, keeping it from starting? The background shows up, but doesn't scroll linearly, so I'm guessing that there's interference or a problem with -webkit-animation My css is really basic: div#wrapper.cloud-animation { background-image: url(../images/clouds.png); background-size: 120%; background-repeat: repeat-x; background-position: -10px 150px; -webkit-animation: backgroundmove infinite 50s linear; } I can't even find documentation online for "webkit backgroundmove" so if anyone knows where to find it, that would be a big help! Thanks - A: backgroundmove is a custom animation, it doesn't exist, you need to define it yourself. @-webkit-keyframes backgroundmove { from { background-position: left top; } to { background-position: right top; } } Have a look at https://developer.mozilla.org/en/css/css_animations
{ "language": "en", "url": "https://stackoverflow.com/questions/7531289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: nodejs mustache/handlebars example project I've been looking to use mustache or handlebars and nodejs but I have't been successful to finding a sample project online that is working. I just need a sample skeleton structure which uses mustache as a templating engine. My goal is to use nodejs, mustache/handlebars, less (css framework) and some good routing but haven't been able to find a good example to work off. UPDATE I created a project which uses less, mustache and express using some tutorial online but I'm getting an error at startup. app.js at https://gist.github.com/1237758 I'm getting TypeError: Object # has no method 'compile' I have express, less and mustache in my node_modules. A: Try this: http://bitdrift.com/post/2376383378/using-mustache-templates-in-express A: You can use the stache module. It makes it much easier to use mustache in express. Check out the examples. A: The source of your error seems to reside in connect module, connect/lib/middleware/compiler.js but I can't reproduce the error. It is possible that you have an old connect module inside your $NODE_PATH A: As you have already received some answers with regard to templating I thought I would answer the routing one. Try out http://sammyjs.org/ a small web framework written in js. Also there are some examples https://github.com/quirkey/sammy/tree/master/examples/ A: I looked for a Express/Handlebars/Less framework, but couldn't find any templates that I was satisfied with. I ended up making my own Express/Handlebars/Less project template on GitHub: Express-Handlebars-Less-Jasmine-NodeUnit_Project-Template
{ "language": "en", "url": "https://stackoverflow.com/questions/7531290", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to do background-repeat in an HTML email that works in Outlook 2007? I am constructing a HTML email for clients and would like to have a content area that expands to fit the text. I would like the border of the container to have a shadow effect- which means repeating a 1px image vertically down each side. I have been very careful to use well-supported (and often legacy) tags and stylings so that it displays correctly in as many email clients as possible. However, I cannot get background-repeat working in Outlook 2007. I have also tried setting its height to 100% with mixed results. I'm actually using the background attribute in a td at the moment as the background styling did not work at all for popular clients (gmail, thunderbird). Can anyone think of a workaround I could use? If not, is there a way to detect if an email is being displayed in Outlook 2007 so that I could look into removing shadow images for the entire email? Many thanks A: This should work: background-image: url('/bg.jpg'); background-repeat: repeat-y no-repeat; background-position: top center; background-color: white; Notice the repeat-y and no-repeat. You need both or Outlook 2007 will assume repeat-x too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What method is called to evaluate Fixnum equality? I know that in Ruby, all numbers, including zero, evaluate to true when used in a conditional statement. However, what method is being called to perform this evaluation (see Ex. 2 below)? I thought it might be the == operator, but not so as they return opposite results. * *Example 1: The equality method evaluates zero to false >> puts "0 is " << (0 == true ? "true" : "false") 0 is false *Example 2: Yet zero alone evaluates to true, because it is not nil >> puts "0 is " << (0 ? "true" : "false") 0 is true A: They don't "evaluate to true" in the sense of being equal the object true. All objects except nil and false are considered to be logically true when they're the value of a condition. This idea is sometimes expressed by saying they are truthy. So, yes, testing equality uses the == operator. A bare 0 is truthy for the same reason 29 and "Hi, I'm a string" are truthy — it's not nil or false. A: 0 == true # evaluates to false => ergo "false" vs 0 # bare zero before the ? is evaluated using ruby truthiness and since it is not false or nil, "true" is returned
{ "language": "en", "url": "https://stackoverflow.com/questions/7531295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the fastest way in .Net 3.5 to call a method by string name? So the obvious way to do this is.. var handler = GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance); handler.Invoke(this, new object[] {e}); And I can add caching to keep the methods around but I'm wondering if there is a completely different and faster way? A: The fastest way would be to cache a typed delegate; if you know the signature is always: void PersonInstance.MethodName(string s); Then you could create an Action<Person,string> via Delegate.CreateDelegate: var action = (Action<Person,string>)Delegate.CreateDelegate( typeof(Action<Person,string>), method); This can then be cached against the name, and invoked as: action(personInstance, value); Note that the cache here is critical; the reflection to locate the method and prepare a typed-delegate is non-trivial. It gets harder if the signature is unpredictable, as DynamicInvoke is relatively slow. The fastest way would be to use DynamicMethod and ILGenerator to write a shim method (on the fly) that takes an object[] for the parameters and unpacks and casts it to match the signature - then you can store an Action<object, object[]> or Func<object,object[],object>. That is, however, an advanced topic. I could provide an example if really needed. Essentially writing (at runtime): void DummyMethod(object target, object[] args) { ((Person)target).MethodName((int)args[0],(string)args[1]); } Here's an example of doing that (note: it doesn't handle ref/out args at the moment, and possibly a few other scenarios - and I've left the "cache" side of things as an exercise for the reader): using System; using System.Reflection; using System.Reflection.Emit; class Program { static void Main() { var method = typeof(Foo).GetMethod("Bar"); var func = Wrap(method); object[] args = { 123, "abc"}; var foo = new Foo(); object result = func(foo, args); } static Func<object, object[], object> Wrap(MethodInfo method) { var dm = new DynamicMethod(method.Name, typeof(object), new Type[] { typeof(object), typeof(object[]) }, method.DeclaringType, true); var il = dm.GetILGenerator(); if (!method.IsStatic) { il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Unbox_Any, method.DeclaringType); } var parameters = method.GetParameters(); for (int i = 0; i < parameters.Length; i++) { il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Ldc_I4, i); il.Emit(OpCodes.Ldelem_Ref); il.Emit(OpCodes.Unbox_Any, parameters[i].ParameterType); } il.EmitCall(method.IsStatic || method.DeclaringType.IsValueType ? OpCodes.Call : OpCodes.Callvirt, method, null); if (method.ReturnType == null || method.ReturnType == typeof(void)) { il.Emit(OpCodes.Ldnull); } else if (method.ReturnType.IsValueType) { il.Emit(OpCodes.Box, method.ReturnType); } il.Emit(OpCodes.Ret); return (Func<object, object[], object>)dm.CreateDelegate(typeof(Func<object, object[], object>)); } } public class Foo { public string Bar(int x, string y) { return x + y; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7531297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: CKEditor Cache problem, edit skin css I'm trying to edit the dialog.css for a skin on CKEditor, the problem is it seems to be caching the css and no matter what, it doesn't seem to clear. I've switched browsers, cleared all cache, I also have the CKEDITOR.timesampe line uncommented from ckeditor_source.js, but still the CSS doesn't update. Any ideas how to clear cache on this? Thank you! A: There's a timestamp parameter in the file ckeditor.js. You can change its value to reset cache
{ "language": "en", "url": "https://stackoverflow.com/questions/7531304", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How does x86 eflags bit 18 (alignment check) work? (Related to check for 386 vs. 486 and later.) I've read that if eflags bit 18 (AC - alignment check) can be modified, you know the CPU is a 486 or newer. On the 386, the bit resists modification. I've lifted the following assembly code from this site and added exhaustive comments (leaving the odd syntax intact): asm mov bx,sx ; Save the stack pointer to bx (is sx a typo or a real register?). and sp,$fffc ; Truncate the stack pointer to a 4-byte boundary. pushfl ; Push the eflags register to the stack. pop eax ; Pop it into eax. mov ecx,eax ; Save the original eflags value into ecx. xor eax,$40000 ; Flip bit 18 in eax. push eax ; Push eax to the stack. popfl ; Pop modified value into eflags. pushfl ; Push eflags back onto the stack. pop eax ; Pop it into eax. xor eax,ecx ; Get changed bits from the original value. setz al ; Set al register to 1 if no bits changed (0 otherwise). and sp,$fffc ; Truncate the stack pointer to a 4-byte boundary. push ecx ; Push ecx (original eflags) to stack. popfl ; Pop it into eflags to restore the original value. mov sp,bx ; Restore the original stack pointer. end ['eax','ebx','ecx']; The CPU is a 386 if the al register is set to 1 at the end (assuming from the start that it's not older), and it's a 486 or newer otherwise. I understand this part. What I don't understand is, why does the stack pointer have to be truncated to a 4-byte boundary before doing the flag modification test? I assume that it's meant to set bit 18, since it's the alignment bit after all...but the xor with 0x40000 will flip the bit regardless of its value. In other words, the modification test should have the same result regardless of the initial value, right? If the answer is no, my best [uneducated] guess as to "why" is, "Maybe the following push/pop instructions could force alignment? This would align a previously unaligned stack pointer and cause the alignment bit to flip from 0 to 1 by itself. In that case, a successful modification would appear unsuccessful, and vice versa." (EDIT: This is definitely incorrect, because the alignment bit is about enforcing rather than tracking alignment. Plus, I doubt that pop/push would force alignment on a previously unaligned stack anyway.) Even if that's the case though, what is the purpose of aligning the stack pointer again after the test (right before restoring the original eflags and stack pointer)? Shouldn't it already be on a 4-byte boundary from before? If not, how could that have changed from pushing/popping 4-byte values? In short, some of the instructions seem redundant to me, and I feel that I must be missing something important. Can anyone here explain it? (Side question: The very first line copies the value from "sx" into bx. I've never seen a reference to an sx register anywhere. Does it actually exist, or is it a typo? The 'x' key is pretty far from the 'p' key, at least on US keyboards.) EDIT: Now that this question has been answered, I decided to remove an incorrect comment from the two alignment lines in the code. I originally made an assumption that aligning the stack would set the alignment bit, and I wrote that into my comment (the rest of the question continues with this incorrect logic). Instead, the alignment check bit really is about enforcing alignment (rather than tracking it), as flolo's answer regarding sigbus indicates. I decided to fix the comments to avoid confusing people with similar questions. A: My guess is very easy: The code dont want to sigbus. In case the check alignment is not set, and you set it, you actually enabling alignment checks (when setting it works). And when the stack pointer isnt aligned to a 4-byte boundary guess what happens? You got an unaligned memory access, which results in a sigbus. And if you dont want to let that invalid memory access happen (as you just want to change the bit for testing purpose), you have to take care that all accesses while you test are assuming the worst case (which is: you have enabled it, and your stack was before it not aligned, because it dont need to, as up to now the checks were disabled). A: There's no SX register. Either a typo or refers to a memory location.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Parsing Django Queryset JSON I want to parse a query set to output json data. However I need to make it so that the new jquery ui autocomplete can use it too, and the autocomplete needs the keys label, id and value to be able to read it. Currently I use: emp_list = Employees.objects.filter(eng_name__icontains=q_term) json_serializer = serializers.get_serializer('json')() json_data = json_serializer.serialize (emp_list, ensure_ascii=False, fields=('eng_name', 'chi_name')) and the output is something like [{"pk": 1, "model": "system.employees", "fields": {"rank": "manager", "eng_name": "Eli"}}, ........] I want to be able to parse it into something like this instead: [{"id": 1, "label": "Eli (manager)", "value": "Eli (manager)"}, ....] what is the best way to do this? A: build it in your view then json dump it employees_output_list = [] for emp in emp_list: name_rank_str = "%s (%s)" % (emp.first_name, emp.rank) emp_dict = { "id": emp.pk, "label": name_rank_str, "value": name_rank_str, } employees_output_list.append(emp_dict) return HttpResponse(json.dumps(employees_output_list)) something like this, don't know your actual field names
{ "language": "en", "url": "https://stackoverflow.com/questions/7531310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How does Eclipse stay up to date with Java updates? Our team uses Eclipse Helios SR1. We develop for Tomcat 6 and Java 6 on Windows 7/2008. We stay fairly up to date with the latest release of both Java 6 and Tomcat 6. We update the JDK/JVM on the Tomcat host and all developer workstations about twice per year. But I've never understood how Eclipse keeps up with the latest JDK update. I see that the referenced JRE System Libraries are all coming from the c:\program files\java\jre6\lib, which is updated with each JDK update. So the libraries that are called are up to date. But Eclipse's compiler is internal to Eclipse I think? I would guess that with each JDK update there is a new javac.exe. But we never do anything to update Eclipse's internal compiler. Is there something we need to be doing along with our JDK updates to update Eclipse? Thanks A: Eclipse is using the JDK you have configured to run and debug code. You can configure/change it in Window -> Preferences -> Java -> Installed JREs. Update from Kevin K's comment below - Eclipse does not use the installed JRE/JDK to compile, it uses the built in JDT incremental compiler for that. It uses the installed JRE/JDK for running and debugging. And, with a JDK, source attachment for Java libraries A: The referenced JRE System library that you are seeing is the JRE from where (1) the libraries are loaded for classpath resolution while compiling & (2) to run the application. For compiling java sources, Eclipse doesn't need a javac.exe or JDK as such, it uses its own compiler JDT. So when you update your JRE to its latest version, eclipse will automatically pickup the latest libraries to compile your sources. To include a new JRE, as you would already know.. goto Window -> Preferences -> Java -> Installed JREs A: It depends on how you install Java. There are two modes, "family" and "static" (See this article). If you install Java in "family" mode, the new version will replace the existing one in the "jre6" directory and since it is the same path Eclipse does not need to be reconfigured. If you install Java in "static" mode, the update is installed in a different path (e.g. "jre1.6.0_27") and Eclipse should be reconfigured to use that JRE. And to nitpick, the configured JRE is not used for compiling classes (Eclipse has a built-in incremental compiler), but it is used for running and debugging programs. A: I find your way to work with the latest pretty unusual. We normally work like that: * *Define in your operating system (JAVA_HOME) the java you want to take as a default. Use that variable in all your scripts, so it is easy to change it centrally. *If you start eclipse, you may include a parameter -vm that denotes the VM with which Eclipse will be started. If it is part of a JDK, eclipse will find it out and use that JDK as the standard VM to start and compile programs. *However, you may define additional JDKs and JREs and define which one should be the default for your workspace. When we develop for a customer (we always develop for a customer), it is appropriate to take the latest JDK (speed of development, ...), but the JDK for compiling and running the application is defined by the customer, and some of them even use JDK 1.4 at the moment. So if you want to steer which JDK should be used by eclipse, you should make that explicit (and yes, you have to do that on each installation for each developer).
{ "language": "en", "url": "https://stackoverflow.com/questions/7531315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: T-SQL Count question I have the following table that I need to summarize ID A B C D E F G ---------------------------------- 1-100 1 2 1 1 1 1 1 1-201 1 2 1 2 2 2 2 1-322 1 1 1 1 2 2 1 2-155 1 1 2 1 1 2 2 2-167 2 1 2 1 2 1 2 2-389 2 2 1 2 1 1 2 2-423 1 2 2 2 1 1 1 3-10 2 1 1 1 2 2 2 3-222 1 1 1 1 2 2 1 3-397 2 1 1 2 2 1 1 In the table above, the values 1 is coded as S while 2 is coded as R. Also, the ID is a code as XX, YY or XX where the digit before the - represents XX, YY, or XX. The summary I would like to have is this XX YY ZZ ------------------------------------------ A S 3 100% 2 50% 1 33% R 0 0% 2 50% 2 66% B S 2 66% 2 50% 3 100% R 1 33% 2 50% 0 0% C S 3 100% 3 75% 3 100% R 0 0% 1 25% 0 0% D S 2 66% 2 50% 2 66% R 1 33% 2 50% 1 33% E S 1 33% 3 75% 0 0% R 2 66% 1 25% 3 100% F S 1 33% 3 75% 2 66% R 2 66% 1 25% 1 33% G S 2 66% 1 25% 1 33% R 1 33% 3 75% 2 66% So I need to rotate the table, count the 1/2 and create percentages. This has got me quite puzzled and I have gone down a few dead ends on how to do this (let alone how to do it elegantly) Thanks in advance! With Martin's help I am ever so close. My data is of course a bit goofier than the example I gave so I am still having difficulties. I have censured the data as well as put the proper codings in that I want - yeah the codings are real goofy, I have no control over them :) I have extended Martins SQL to link to my data but there are two remaining issues. The order of the rows in the Thing Column is not quite what I want. When I try the following code, I get a "Must declare the scalar variable @order" - it does not like joining to my temp table called myOrder. DECLARE @myOrder TABLE (rug varchar(3), rugOrder int) INSERT @myOrder SELECT 'INH', 1 UNION ALL SELECT 'RIF', 2 UNION ALL SELECT 'KM', 3 UNION ALL SELECT 'AK', 4 UNION ALL SELECT 'CM', 5 UNION ALL SELECT 'MOX', 6 UNION ALL SELECT 'OFX', 7; WITH YourData(ID, INH, RIF, KM, AK, CM, MOX, OFX) As (SELECT Sample_ID, INH, RIF, KM, AK, CM, MOX, OFX FROM dbo.[GCT_Rug] WHERE Sample_ID NOT LIKE '99%') , Unpivoted AS ( SELECT S_R_Flag, Thing, Site = CASE WHEN LEFT(ID,1) = 1 THEN 1 WHEN LEFT(ID,1) = 6 THEN 1 WHEN LEFT(ID,1) = 8 THEN 2 WHEN LEFT(ID,1) = 9 THEN 3 END FROM YourData UNPIVOT (S_R_Flag FOR Thing IN (INH, RIF, KM, AK, CM, MOX, OFX) )AS unpvt) SELECT Thing ,SRFLAG = CASE WHEN S_R_Flag = 1 THEN 'S' WHEN S_R_Flag = 2 THEN 'R' END ,[1] AS IND ,round(CAST([1] AS FLOAT) / NULLIF(SUM([1]) OVER (PARTITION BY Thing),0)*100,1) AS 'Ind Percent' ,[2] AS MD ,round(CAST([2] AS FLOAT) / NULLIF(SUM([2]) OVER (PARTITION BY Thing),0)*100,1) AS 'MD Percent' ,[3] AS 'SA' ,round(CAST([3] AS FLOAT) / NULLIF(SUM([3]) OVER (PARTITION BY Thing),0)*100,1) AS 'SA Percent' FROM Unpivoted INNER JOIN @myOrder ON Unpivoted.Thing= @myOrder.rug PIVOT (COUNT (Site) FOR Site IN ( [1], [2], [3])) AS pvt ORDER BY rugOrder, SRFLAG; What does the error "Must declare the scalar variable @myOrder" mean and why can't I join to it ? Thanks again you guys (especially Martin) are awesome ! A: This essentially gives you the results you need though I haven't bothered mapping the numeric values to the codes ;WITH YourData(ID,A,B,C,D,E,F,G) As ( SELECT '1-100',1,2,1,1,1,1,1 UNION ALL SELECT '1-201',1,2,1,2,2,2,2 UNION ALL SELECT '1-322',1,1,1,1,2,2,1 UNION ALL SELECT '2-155',1,1,2,1,1,2,2 UNION ALL SELECT '2-167',2,1,2,1,2,1,2 UNION ALL SELECT '2-389',2,2,1,2,1,1,2 UNION ALL SELECT '2-423',1,2,2,2,1,1,1 UNION ALL SELECT '3-10 ',2,1,1,1,2,2,2 UNION ALL SELECT '3-222',1,1,1,1,2,2,1 UNION ALL SELECT '3-397',2,1,1,2,2,1,1 ), Unpivoted AS ( SELECT S_R_Flag, Thing, SUBSTRING(ID,1,CHARINDEX('-',ID )-1) AS Code,ID FROM YourData UNPIVOT (S_R_Flag FOR Thing IN (A,B,C,D,E,F,G) )AS unpvt) SELECT Thing ,S_R_Flag ,[1] ,CAST([1] AS FLOAT) / SUM([1]) OVER (PARTITION BY Thing) ,[2] ,CAST([2] AS FLOAT) / SUM([2]) OVER (PARTITION BY Thing) ,[3] ,CAST([3] AS FLOAT) / SUM([3]) OVER (PARTITION BY Thing) FROM Unpivoted PIVOT (COUNT (ID) FOR Code IN ( [1], [2], [3] )) AS pvt ORDER BY Thing, S_R_Flag;
{ "language": "en", "url": "https://stackoverflow.com/questions/7531317", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why does UploadedFile.content_type fail in FF only for me? I do a little validation in my form and everything works in Chrome and Safari, but in FF, for whatever reason I can't submit my form because of the following lines: if not song.content_type in ["audio/mp3", "audio/mp4"]: raise forms.ValidationError("Content type is not mp3/mp4") When I try and submit a form (with an mp3), I receive the error: "content type is not mp3/mp4". If I comment out the above two lines, everything works as planned. This ONLY happens in FF. Chrome and Safari allow me to upload the file with the above lines in place. What gives? What does this even have to do with the browser? Thanks in advance, this is a real mystery to me! A: i think in fire fox you getting different types for them. most probably spelling issue like capitalization. just to print song.content_type and hope fully you will getting the solution by yourself
{ "language": "en", "url": "https://stackoverflow.com/questions/7531319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Spring nullable String Bean I have a filtered configuration like so (using Maven for filtering): <bean class="com.whatever.SomeClass"> <property name="someString" value="${filter.prop.value}"/> </bean> Sometimes that string property needs to be null (for reasons I wont go into here), so I need a way to specify the property as null. Clearly if I filter with the property file value "null", the bean property will be the String "null" instead of actually null. I am aware that I can create something like a NullableStringFactoryBean which can look for the string "null" and handle it appropriately. My question is: Does Spring provide a mechanism to do this already or is there some better way I can go about achieving this? A: Have a look at the setNullValue method from the PropertyPlaceholderConfigurer class and see if it helps given your situation. Set a value that should be treated as null when resolved as a placeholder value: e.g. "" (empty String) or "null". EDIT: Since you are using Maven filtering and don't want to have two mechanisms (one done by Maven on the process-resources phase and later, at runtime, one done by Spring) I see only three options: 1) Use a "smart" setter as @Tomasz Nurkiewicz specified in his answer. This might have side effects though as you also mentioned and might become "to smart for one's own good". 2) Inject the value of the property by using a FactoryBean<String> as you demonstrated in the answer you added to the question (with Spring's "p-namespace" being a nice way of limiting the amount of XML you have to write to accomplish this). 3) (crazy idea) replace the entire property injection in the XML. That is, instead of having this: <bean class="com.whatever.SomeClass"> <property name="someString" value="${filter.prop.value}"/> </bean> Have this: <bean class="com.whatever.SomeClass"> ${filter.prop.value} </bean> Now, filter.prop.value instead of null or someValidValue can become some white space and <property name="someString" value="someValidValue"/>, respectively. This has the disadvantage that your IDE will complain about an invalid XML (since <bean> tag does not allow character children, only elements). But if you can live with that.... I would personally go for number 2. A: What about: public void setSomeString(String value) { if(value == null || value.equals("") || value.equals("null")) { this.value = null; } else { this.value = value; } } A: Well, in case anyone was wondering how this is done with a FactoryBean... public class NullLiteralResolvingStringFactoryBean implements FactoryBean<String> { private String value; @Override public String getObject() throws Exception { if (value == null || value.equals("null")) { return null; } return value; } @Override public Class<?> getObjectType() { return String.class; } @Override public boolean isSingleton() { return true; } public void setValue(String value) { this.value = value; } } Config: <bean id="someString" class="com.whatever.NullLiteralResolvingStringFactoryBean" p:value="${filter.someString}" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7531320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change the definition of a 'Week'? I'm generating an overtime report, and while Crystal Reports can group an employee's shifts into weeks, it uses a standard Sunday-Saturday week; I need a Monday-Sunday week(ie, Sept 12-18th inclusive). Is there any way to change this setting, or am I stuck with writing a complex formula? A: I don't know of a setting that will allow you to do this, but the group formula is not too bad. The following will give you the week number/index in the year using Mondays as the start of the week. datepart("ww",{table.date},crMonday) You will probably want to incorporate the year, too. You can ensure proper sorting by year and week with this totext(datepart("yyyy",{Orders.Order Date}),"####") + " " + totext(datepart("ww",{Orders.Order Date},crMonday),"##") A: You could group by {table.date} - 1.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to Handle the response from server after a form submission? I'm attempting to create ajax functionality to a form that uploads files. I created the isolated iframe and target the form submission to it. The server validates the files and sends back an XML doc in the response body. How would I handle and retrieve the XML doc on the client side, preferably using JavaScript? This is my handler, @Controller @RequestMapping("/upload") public class UploadController { @RequestMapping(method = RequestMethod.POST) public String handleFileUpload(HttpServletResponse response, @RequestParam("file") MultipartFile file) throws IOException{ response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write("<test>hello</test>"); return null; } } A: We do something similar but return JSON instead of XML. That JSON is then used as-is by the JavaScript function that triggers the upload ---- If i use the response type as json in the iframe form submit for file upload..i am seeing a download popup asking me to save or open... the application/json response is handled by the browser as a download ... issue occurs in IE and older versions of FF A: There were several suggestions on using a hidden iframe on the net. That's what my final attempt was, I sent an xml doc to the iframe's body and manage the data from there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Understanding the implementation of traditional and enhanced iterations on C# and Java I'm feeling quite confused about the way either C#'s foreach and Java's enhanced for works and even more frustrating is to realize why I haven't came across this detail before. But anyway the fact of the matter is, I'd really like to understand why this apparently similar flow control statements work so differently. For illustration purposes let's assume we need to iterate through an array of integers, with both implementations being something like: C# 4.0 (code) class Program { public static void Main(string[] args) { int[] foobar = new int[] {0, 1, 1, 2, 3, 5, 8, 13, 21}; Console.WriteLine(String.Format("[DEBUG] type: {0}", foobar.GetType())); Console.WriteLine(String.Format("[DEBUG] length: {0}", foobar.Length)); try { for (int i = 0; i < foobar.Length; i++) { Console.Write(String.Format("{0} ", foobar[i])); } Console.Write(Environment.NewLine); foreach (var i in foobar) { Console.Write(String.Format("{0} ", foobar[i])); } } catch (Exception exception) { Console.Write(Environment.NewLine); Console.WriteLine(exception.ToString()); } finally { Console.Write(Environment.NewLine); Console.Write("Press any key to continue . . . "); Console.ReadKey(true); } } } C# 4.0 (output) [DEBUG] type: System.Int32[] [DEBUG] length: 9 0 1 1 2 3 5 8 13 21 0 1 1 1 2 5 21 System.IndexOutOfRangeException: Index was outside the bounds of the array. at Dotnet.Samples.Sandbox.Program.Main(String[] args) in e:\My Dropbox\Work\P rojects\scm\git\sandbox\Dotnet.Samples.Sandbox\Dotnet.Samples.Sandbox\Program.cs :line 51 Press any key to continue . . . JAVA SE6 (code) class Program { public static void main(String[] args) { int[] foobar = new int[] {0, 1, 1, 2, 3, 5, 8, 13, 21}; System.out.println("[DEBUG] type: " + (foobar.getClass().isArray() ? "Array " : "") + foobar.getClass().getComponentType()); System.out.println("[DEBUG] length: " + foobar.length); try { for (int i = 0; i < foobar.length; i++) { System.out.print(String.format("%d ", foobar[i])); } System.out.print(System.getProperty("line.separator")); for (int i : foobar) { System.out.print(String.format("%d ", foobar[i])); } } catch (Exception e) { System.out.print(System.getProperty("line.separator")); System.out.println(e.toString()); } } } JAVA SE6 (output) [DEBUG] type: Array int [DEBUG] length: 9 0 1 1 2 3 5 8 13 21 0 1 1 1 2 5 21 java.lang.ArrayIndexOutOfBoundsException: 13 A: In the C# version.. foreach (var i in foobar) { Console.Write(String.Format("{0} ", foobar[i])); } ..should be.. foreach (var i in foobar) { Console.Write(String.Format("{0} ", i)); } Doing a foreach over an array of integers, as you are, does not iterate over array indices: it iterates over the integers. Given the array.. int[] foobar = new int[] {0, 1, 1, 2, 3, 5, 8, 13, 21}; ..your code was: Printing element 0: 0 Printing element 1: 1 Printing element 1: 1 Printing element 2: 1 Printing element 3: 2 Printing element 5: 5 Printing element 8: 21 Printing element 13: IndexOutOfRangeException !! A: You're using the value as an indexer, foreach gives you each value in the array, not each index if you write foreach (var i in foobar) { Console.Write(String.Format("{0} ", i)); } it should be correct A: Not sure if I should add this as a comment to Carson63000 or add as an answer, but the Java has the same issue. for(int i : foobar) {      System.out.print(i); } As a side note, I find Java's "enhanced for" to be less intuitive than C#'s foreach. I think after you deal with Java, you start to understand what "for(int i: foobar)" means, but I don't think anybody would argue that foreach is more straightforward. There are times when foreach and "enhanced for" are not the best choice when using a for loop though. If you need access to more than one value in the array, you are best to use the traditional for loop because the foreach/enhanced for will only allow you to access one value at a time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 3 Auto-Refreshing Divs on a page using JQuery but one of them doesn't work? I have three divs on my page and each one is auto-refreshed using JQuery, here's the HTML: <div id="photo"> <?php require("image.php"); ?> </div> <div id="right-bar"> <div id="facebook"> <?php require("graph.php"); ?></div> </div> <div id="bottom-bar"> <?php require("twitter.php"); ?> </div> Here is the JQuery: var imagecacheData; var imagedata = $('#photo').html(); var imageauto_refresh = setInterval( function () { $.ajax({ url: 'image.php', type: 'POST', data: imagedata, cache: false, dataType: 'html', success: function(imagedata) { if (imagedata !== imagecacheData){ //data has changed (or it's the first call), save new cache data and update div imagecacheData = imagedata; $('#photo').fadeOut("slow").html(imagedata).fadeIn("slow"); } } }) }, 60000); // check every minute var cacheData; var data = $('#facebook').html(); var auto_refresh = setInterval( function () { $.ajax({ url: 'graph.php', type: 'POST', data: data, dataType: 'html', success: function(data) { if (data !== cacheData){ //data has changed (or it's the first call), save new cache data and update div cacheData = data; $('#facebook').fadeOut("slow").html(data).fadeIn("slow"); } } }) }, 30000); // check every 30 seconds var twittercacheData; var twitterdata = $('#bottom-bar').html(); var twitterauto_refresh = setInterval( function () { $.ajax({ url: 'twitter.php', type: 'POST', data: twitterdata, dataType: 'html', success: function(twitterdata) { if (twitterdata !== twittercacheData){ //data has changed (or it's the first call), save new cache data and update div twittercacheData = twitterdata; $('#bottom-bar').fadeOut("slow").html(twitterdata).fadeIn("slow"); } } }) }, 60000); // check every minute - reasonable considering time it takes 5 tweets to scroll across As you can see, all of them are pretty much the same thing but the twitter section doesn't auto-refresh at all. Also, as you can see I am trying to only get the page to do the fade out/ fade in if the response is actually different but it seems to be doing it anyway - any ideas as to why this is? Thank you for your help in advance A: turns out it the problem was facebook wasn't signed in. Soon as that was done it was fixed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's the purpose of a private key passphrase? Sometimes, I see users use a private key and passphrase to log in. So, does it mean the public key is stored on the log in server? What's the purpose of the pass phrase? A: Yes, the server stores the public key, and the client stores the private key. A security feature to prevent stolen private keys from being useful to the thief is to encrypt them. The passphrase allows you to decrypt the private key to use it. Without the passphrase, the key is useless. You know whether a key is encrypted generally by looking at the PEM header surrounding it. For example, a DSA private key encrypted with 3DES in PEM format might look like this: -----BEGIN DSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: DES-EDE3-CBC,BF6892D860EC969F <encrypted key data here> -----END DSA PRIVATE KEY----- Whereas an unencrypted DSA private key in PEM format would not have a header saying it's encrypted: -----BEGIN DSA PRIVATE KEY----- <unencrypted key data here> -----END DSA PRIVATE KEY-----
{ "language": "en", "url": "https://stackoverflow.com/questions/7531333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android:CheckedTextView isChecked returns incorrect value Android version: 3.1 API version: Android 2.2 Device: Motorola MX604 I dynamically create a multi-select ListView of CheckedTextView items, and attach a OnItemClickListener to the ListView. In the onItemClick method of the listener, I invoke the isChecked method of CheckedTextView to determine if the associated checkbox is checked or unchecked. Simple enough. The problem: When I select a previously unselected item, the isChecked method returns false. When I select a previously selected item, the method returns true. The checkbox icon itself checks and unchecks correctly. Here is the layout for the CheckedTextView: <CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/text1" android:layout_width="match_parent" android:layout_height="?android:attr/listPreferredItemHeight" android:textAppearance="?android:attr/textAppearanceLarge" android:gravity="center_vertical" android:drawableLeft="?android:attr/listChoiceIndicatorMultiple" android:paddingLeft="6dip" android:paddingRight="6dip" /> This is how I create the ListView: private void createSortedChannelList() { emptyViewContainer(); ListView sortedListView = new ListView(this); sortedListView.setId(CHANNEL_LISTVIEW_ID); sortedListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); sortedListView.setItemsCanFocus(false); sortedListView.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int position,long id) { CheckedTextView selectedItem = (CheckedTextView) view; boolean isChecked = selectedItem.isChecked(); Log.e(mLogTag,"item clicked position = " + position + " isChecked = " + isChecked); } }); ArrayAdapter<Channel> listAdapter = new ArrayAdapter<Channel>(this,R.layout.favorite_channel_list_select_channel_row,mAllChannels); sortedListView.setAdapter(listAdapter); for(int channelIndex = 0;channelIndex < mChannelIds.length;channelIndex++){ if(mSelectedChannelIds.contains(mChannelIds[channelIndex])) sortedListView.setItemChecked(channelIndex, true); } addViewToViewContainer(sortedListView); } This is the log output that is produced when I select a previously unselected item: 09-23 09:08:59.650: item clicked position = 19 isChecked = false and when I select a previously selected item 09-23 09:10:20.800: item clicked position = 18 isChecked = true I have done an extensive search and I can only find one other report of similar behavior. This leads me to believe that the problem probably lies in my code, rather than the android class :p I have also looked at numerous examples that are set up in a similar fashion. Can anyone spot a problem? thanks PS This is my first post on any forum, so if I'm missing something that would be helpful to the readers of this post, please let me know. A: I believe the code is behaving the way it should. Selecting a previously unselected method will invoke the click listener before changing the checked state of the item in the list. In other words, isChecked() won't return true for the previously unselected item until after the onClick() method is finished. A: I've noticed that for me, at least, the behavior of when the state changes isn't consistent; on an emulator, isChecked() returned the pre-click state, but on a device it returned the post-click state. I got around this by bypassing the "isChecked" altogether, and just looking at the state of the underlying object I am toggling, since that won't change unless I explicitly do so. However, this solution may depend on how your code is set up, and there may be other gotcha's that I am overlooking. A: You should be using MultiChoiceModeListener for listening to checks. Here is the documentation
{ "language": "en", "url": "https://stackoverflow.com/questions/7531334", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: List in PropertyGrid C# I have an Employee class. There are many departments maintained in the database and an employee may only belong to a particular department. public class Employee { private string name; private int depID; public string Name { get { return name; } set { name = value; } } public int DepartmentID { get { return depID; } set { depID = value; } } } public class Department { private int depID; private string depName; public int DepartmentID { get { return depID; } } public int DepartmentName { get { return depName; } set { depName = value; } } } How can I display the object Employee in the PropertyGrid with the department as a one of the properties that will be displayed as combobox? Is it possible? Or is there any better implementation? Thanks in advance for your inputs. A: I went ahead and drafted you up an experiment (for myself as well since I have never done this). It uses Linq for this particular solution to populate the combo box at hand, but I'm sure you could populate it other ways as well. My documentation came from here under the subsection Adding Domain List and Simple Drop-down Property Support using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; public class Employee : StringConverter { DataClasses1DataContext mydb = new DataClasses1DataContext(); public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { var a = (from u in mydb.Customers select u.CustomerID).ToArray(); return new StandardValuesCollection(a); } public string Name { get; set; } [TypeConverter(typeof(Employee)), CategoryAttribute("Document Settings")] public string DepartmentID { get; set; } } On the form load I selected: private void Form1_Load(object sender, EventArgs e) { Employee temp = new Employee(); propertyGrid1.SelectedObject = temp; } I hope this is what you are looking for. It's worth noting that you may change StringConverter to TypeConverter if you'd like, but I used String becasue the field I'm dealing with is a string. A: You can achieve that by implementing the TypeConverter
{ "language": "en", "url": "https://stackoverflow.com/questions/7531335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What is the difference between text field types I am new to android. I was stuck on a problem but I finally solved it. I was using a TextField instead of CompleteTextViewField so whats the difference between these two and when should I use each one of them? Thanks A: Neither of those classes you mention (TextField, CompleteTextViewField) exist. Do you mean EditText and AutoCompleteTextView? I think the documentation explains it pretty well: [AutoCompleteTextView is] An editable text view that shows completion suggestions automatically while the user is typing. The list of suggestions is displayed in a drop down menu from which the user can choose an item to replace the content of the edit box with. That is, use it rather than a normal EditText if you have a set of common autocompletions for what gets entered in the box. The docs also link to a full sample that shows how to populate that list of suggestions with an Adapter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using lookup values in linq to entity queries I'm a total LINQ noob so I guess you'll probably have a good laugh reading this question. I'm learning LINQ to create queries in LightSwitch and what I don't seem to understand is to select an entity based on a value in a lookup table. Say I want to select all employees in a table that have a job title that is picked from a related lookup table. I want the descriptive value in the lookup table for the user to pick from a list to use as a parameter in a query, not the non-descriptive id's. Can someone point me to an article or tutorial that quickly explains this, or give me a quick answer? I AM reading books and have a Pluralsight account but since this is probably the most extensive knowledge I will need for now a simple tutorial would help me more that watching hours of videos and read thousands of pages of books. Thanks in advance! Edit: this is the code. As far as I know this should but won't work (red squigly line under EmployeeTitle, error says that EmployeeContract does not contain a definition for EmployeeTitle even though there is a relationship between the two). partial void ActiveEngineers_PreprocessQuery(ref IQueryable<Employee> query) { query = from Employee e in query where e.EmployeeContract.EmployeeTitle.Description == "Engineer" select e; } Edit 2: This works! But why this one and not the other? partial void ActiveContracts_PreprocessQuery(ref IQueryable<EmployeeContract> query) { query = from EmployeeContract e in query where e.EmployeeTitle.Description == "Engineer" select e; } A: Try something like this: partial void RetrieveCustomer_Execute() { Order order = this.DataWorkspace.NorthwindData.Orders_Single (Orders.SelectedItem.OrderID); Customer cust = order.Customer; //Perform some task on the customer entity. } (http://msdn.microsoft.com/en-us/library/ff851990.aspx#ReadingData) A: Assuming you have navigation properties in place for the foreign key over to the lookup table, it should be something like: var allMonkies = from employee in context.Employees where employee.EmployeeTitle.FullTitle == "Code Monkey" select employee; If you don't have a navigation property, you can still get the same via 'manual' join: var allMonkies = from employee in context.Employees join title in context.EmployeeTitles on employee.EmployeeTitleID equals title.ID where title.FullTitle == "Code Monkey" select employee; A: The red squiggly line you've described is likely because each Employee can have 1-to-many EmployeeContracts. Therefore, Employee.EmployeeContracts is actually an IEnumerable<EmployeeContract>, which in turn does not have a "EmployeeTitle" property. I think what you're looking for might be: partial void ActiveEngineers_PreprocessQuery(ref IQueryable<Employee> query) { query = from Employee e in query where e.EmployeeContract.Any(x => x.EmployeeTitle.Description == "Engineer") select e; } What this is saying is that at least one of the Employee's EmployeeContracts must have an EmployeeTitle.Description == "Engineer"
{ "language": "en", "url": "https://stackoverflow.com/questions/7531337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Div 100% width cross browser firefox issue If you look at http://www2.currensee.com in safari the page width is fine, but in firefox (3.6 at least) there is a horizontal scroll. Any ideas how I can fix this? A: It's fine in FF6. You could try the CSS3 style html { overflow-x:hidden; } but I'm not sure if it was implemented in FF3.6. A: if width is 100% and margin is > 0 you will get a scroll bar because the margin is extending outside the visible area. A: A box shadow was causing the error.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to put a line over a div at a specific place? I am using a javascript based calendar. I am supposed to introduce a line in it marking today's date. I was able to achieve it for cells that are expanded. But I cannot introduce a line when the cells are collapsed. The reason is that, during the collapsed case, the row is one full div as opposed to seven individual cells. You can see in the above image there is an ash Line running indicating today's date. But not for the collapsed times. What is the best way to achieve a line in between them? A: Is it required that those collapsed ones be only one div or can you make them into seven divs and get rid of the borders? The idea being that making them separate divs then allows you to put in thicker borders (assuming that is how you are generating the line). Alternatively you may be able to use a relatively positioned DIV for the marker line and do some calculations on where it needs to be and then have it floating over the rest of your content. This way it would not matter what layout the stuff underneath was. This does rely on there being a relatively easy way to calculate the desired position (I'm assuming its not always just before the last day).
{ "language": "en", "url": "https://stackoverflow.com/questions/7531343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jquery: bind load + change simultaneously In many cases, I need to bind a behaviour to an element after loading, and then after an event triggering (like "change"). I think the best way would be to make it in the same line: $('#element_id').bind('load, change', function () { ... }); But this works only for "change" and not for "load". There is a better way? A: I stumbled across the same problem. Removing comma is not enough, at least not in this case: $(document).ready(function(){ $('#element_id').bind('load change', function () { ... // (this DOESN'T get called on page load) }); }); I guess load events get triggered before $(document).ready(). This is a simple solution: $(document).ready(function(){ $('#element_id').bind('change', function () { ... }); $('#element_id').trigger('change'); }); A: For already loaded content, when you want to run a function on an event and also straight away, you can use a custom event of your own naming to avoid triggering any existing bindings from libraries etc. on the built in events, e.g. $(".my-selector").on("change rightnow", function() { // do stuff... }).triggerHandler("rightnow"); A: Don't you just need to remove the comma? A: try it without the comma: $('#element_id').bind('load change', function () { ... }); http://api.jquery.com/bind/#multiple-events
{ "language": "en", "url": "https://stackoverflow.com/questions/7531347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: Add JInternalFrame to JDesktopPane in execution time I have a problem with a JDesktopPane, I add JInternalFrame on it and then show it on a JFrame. The problem is when I try to add another JInternalFrame in execution time. I use the same method to add the same JInternalFrame but its dosnt shows up. public class Desktop extends JDesktopPane { (...) public void addJInternalFrameBox(JInternalFrameBox jifb) { this.add(jifb, desktop.CENTER_ALIGNMENT); this.repaint(); this.validate(); } } JInternalFrameBox class: public class JInternalFrameBox extends JInternalFrame { (...) public JInternalFrameBox(Integer id) { this.id = id; setUpFrame(); } public void setUpFrame() { JLabel lbl = new JLabel("test"); lbl.setVisible(true); this.add(lbl); this.setPreferredSize(INTERNAL_FRAME_SIZE); this.setLocation(100, 100); this.setIconifiable(true); this.setClosable(true); this.pack(); this.setVisible(true); } } jButtonBox the button that open the JInternalFrameBox: public class jButtonBox extends JButton implements MouseListener { public void mouseReleased(MouseEvent e) { JInternalFrameBox jifb = new JInternalFrameBox(id); jifb.setVisible(true); Desktop df = Desktop.getInstance(); df.addJInternalFrameBox(jifb); } (...) } A: Read the section from the Swing tutorial on How to Use Internal Frames for a working example. A: Don't use a JPanel for your desktop, but rather use a JDesktopPane. That's specifically what its for. A: you have to set both location and size of the internal frame, as in setSize(INTERNAL_FRAME_SIZE); // instead of setPref setLocation(100, 100); hm ... maybe not (just saw the pack in your code) - no more guessing without an sscce, as others already stated
{ "language": "en", "url": "https://stackoverflow.com/questions/7531348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: rails model validation in the database I have a table and have the validation for uniqueness setup in the table. eg. create table posts ( id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY UNIQUE, title varchar(255) unique, content text ); Here title is unique. Do also need to inform the model class about this uniqueness? If not when i insert a duplicate title, it gives me error. How do I catch that. Currently rails shows me the backtrace and i could not put my own error messages def create @f = Post.new(params[:post]) if @f.save redirect_to posts_path else @flash['message'] = "Duplicated title" render :action=>'new' end end I am not being redirected to the new and instead show a big backtrace. A: Use the validates_uniqueness_of validation. "When the record is created, a check is performed to make sure that no record exists in the database with the given value for the specified attribute (that maps to a column)" A: You will have to add all of the validations to your models. There is a gem called schema_validations, which will inspect your db for validations and create them in your models for you. https://github.com/lomba/schema_validations A: Yes you do as noted in other answers, the answer is validate_uniqueness_of - http://ar.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#M000086. Note, even though you have a validation in your model a race condition does exist where Rails may try and do two inserts unaware of there being a unique record already in the table When the record is created, a check is performed to make sure that no record exists in the database with the given value for the specified attribute (that maps to a column). When the record is updated, the same check is made but disregarding the record itself. Because this check is performed outside the database there is still a chance that duplicate values will be inserted in two parallel transactions. To guarantee against this you should create a unique index on the field. See add_index for more information. So what you have done, by creating a unique index on the database is right, though you may get database driver exceptions in your exception log. There are workarounds for this, such as detecting when inserts happen (through a double click). A: The Michael Hartl Rails Tutorial covers uniqueness validation (re. the "email" field) here. It appears the full uniqueness solution is: * *Add the :uniqueness validation to the model. *Use a migration to add the unique index to the DB. *Trap the DB error in the controller. Michael's example is the Insoshi people_controller--search for the rescue ActiveRecord::StatementInvalid statement. Re. #3, it looks like Michael just redirects to the home page on any DB statement exception, so it's not as complex (nor as accurate) as the parsing suggested by @Ransom Briggs, but maybe it's good enough if, as @Omar Qureshi says, the uniqueness constraint covers 99% of the cases.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531352", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: In Rails Marshal dumped data is not saving in its full length in mysql Marshal dump data is not saving in the database with its full length....why? I am using the Marshal to dump the objects and its length after dumping is around 145873 but after saving that data in the mysql its length is changed, means data is missed.... Its length in database is 2851 I have LongText field in the database. What is the solution to this problem ? create_table "report_instances", :force => true do |t| t.integer "report_id" t.integer "user_id" t.integer "role_type_id" t.integer "delayed_job_id" t.datetime "generated_at" t.text "result" t.text "report_data", :limit => 2147483647 t.datetime "created_at" t.datetime "updated_at" t.boolean "current", :default => true end x=Marshal.dump([users, total]) report_instance = report.report_instances.find(:last,:conditions=>["user_id=? and role_type_id=?",usr.id,usr.current_role_type_id]) report_instance.update_attribute(:report_data,x) A: i would strongly recommend using a BLOB (with t.binary) to store marshaled objects.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Detect if a selector has been specified I am developing my first jQuery plugin but want it to work in a slightly different manner to usual. I'll start by explaining it's purpose: Very simple, <input> fields with a title attribute specified will fill the input box with the value in the attribute, focusing on the input field will remove the value and allow the user to type in the box. I know this isn't new stuff and probably done 100 times before but it's more the learning curve than the final outcome. So, I've got it so far working in two ways, first method is the code is called onto a particular element: $('input').fillForm(); The other method involves using a selector within the plugin (specified as an option) which will find all elements on the page with a particular class and run the function: $().fillForm(); // Called from the document load $('.fillForm').each(function () {... // Within the plugin My question is, is there a way to detect whether or not the user as specified a selector: $('input').fillForm(); The bit highlighted in bold. That way, if they haven't then I can tell it to use the default css selector. Here is a fiddle of my code: http://jsfiddle.net/chricholson/HwkRw/ There are two versions there, swap the comments around to try out the other method. A: I'm not sure exactly what it is you're after, but you can access the selector property of the constructed jQuery object like this: console.log($("input").selector); // "input" From within your plugin, you can do: $.fn.myPlugin = function() { console.log(this.selector); } $("p").myPlugin(); // "p" A: A perhaps better approach to what you are trying to do: Have a default setting and overwrite it when needed: (function ($) { $.fillForm = function (args) { var options = { selector : '.fillForm' } $.extend(options, args); alert(options.selector); $(options.selector).each(function () { var input = $(this); input.val(input.attr('title')); input.focus(function () { if (input.val() == input.attr('title')) { input.val(''); } else { setTimeout(function () { input.select(); }, 10); } }); input.blur(function () { if (input.val() == "") { input.val(input.attr('title')); } }); }); }; })(jQuery); $(document).ready(function () { $.fillForm({'selector' : '.foo'}); }); Working example here: http://jsfiddle.net/82t3K/ A: Create a method on the root jQuery object (instead of in the fn namespace) which can be called without a selector. (function($) { var defaultSelector = '.fillForm'; // Use fillForm with your own selector. $.fn.fillForm = function() { // Blah blah blah. }; // Use fillForm with the default selector. $.fillForm = function() { $(defaultSelector).fillForm(); }; })(jQuery); Now you can call your plugin with $.fillForm() which is a more common pattern. A: Why not use the standard "placeholder" attribute and write a fallback that utilizes it? Or better yet, use one of the many fallbacks already written? Every answer posted so far has given varying degrees of really bad advice. For your task, I recommend using the html placeholder fallback written by Mike Taylor (from Opera): jQuery-html5-placeholder . Or at very least, use his work to inspire your own. A: The jQuery object has a .selector property that you can use. Here is an example, http://jsfiddle.net/Akkuma/CGFpC/ If you create an empty jQuery object $().selector; will equal an empty string. If you decided to turn this into a jQuery UI Widget you can't access it simply from this.element.selector.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Can I access web.config with an XBAP? I'm porting a Silverlight 4 app to WPF/XBAP. The app uses initParams initialized using asp from web.config app setting parameters. Unlike Silverlight, WPF lacks an InitParams property on StartupEventArgs. It sure seems like this would be something BrowserInteropHelper would help me do, but I don't see anything. Is there some way to access config params from the web.config to the app at startup? A: My workaround has been to add a web service to the web site that hosts the xbap, and call it when the app starts up using the BrowserInteropHelper.Source to determine the uri for the endpointaddress. public class ConfigService : IConfigService { public WebConfiguration GetWebConfig() { var outDict = new Dictionary<string, string>(); foreach (string key in WebConfigurationManager.AppSettings.AllKeys) { outDict.Add(key, WebConfigurationManager.AppSettings[key]); } var webconfig = new WebConfiguration(); webconfig.AppSettings = outDict; return webconfig; } } [DataContract] public class WebConfiguration { [DataMember] public Dictionary<string, string> AppSettings { get; set; } } Here's how the client calls it: private void Application_Startup(object sender, StartupEventArgs e) { try { var b = new System.ServiceModel.BasicHttpBinding(); string url; // when running xbap directly in browser the port is -1 if(BrowserInteropHelper.Source.Port != -1) { url = String.Format("http://{0}:{1}/ConfigService.svc", BrowserInteropHelper.Source.Host, BrowserInteropHelper.Source.Port); } else { url = @"http://localhost.:51007/ConfigService.svc"; } var address = new System.ServiceModel.EndpointAddress(url); SDDM3.ConfigServiceReference.ConfigServiceClient c = new ConfigServiceClient(b, address); c.GetWebConfigCompleted +=new EventHandler<GetWebConfigCompletedEventArgs>(c_GetWebConfigCompleted); c.GetWebConfigAsync(url); this.MainWindow.Content = new UserControl1(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } void c_GetWebConfigCompleted(object sender, GetWebConfigCompletedEventArgs e) { if (e.Error == null) { // MessageBox.Show(e2.Result. m_AppSettings = e.Result.AppSettings; MessageBox.Show("got appsettings: " + e.Result.AppSettings.Count.ToString()); this.MainWindow.Content = new Page1(); } else { string msg; if (e.UserState != null) msg = String.Format("Unable to get config from: \n{0} \n{1}", e.UserState, e.Error.Message); else msg = String.Format("Unable to get config: \n{0}", e.Error.Message); MessageBox.Show(msg); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7531365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Phonegap + Android - Error when linking to local HTML I have been trying to link to a local HTML file from my Phonegap app but it is not working. This is what I have in my index.html (which works perfectly) <!DOCTYPE HTML> <html> <head> <title>PhoneGap</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> function onLoad(){ document.addEventListener("deviceready", onDeviceReady, true); } function onDeviceReady(){ navigator.notification.alert("PhoneGap is working"); } </script> </head> <body onload="onLoad();"> <h1><a href="page2.html">Page 2</a></h1> </body> </html> page2.html is stored in the same assets/www folder as the index.html, it works on my desktop browser but nothing happens when I click the link on my device, except for an error which appears in the Log. 09-23 16:12:33.314: INFO/System.out(6244): startActivityForResult(intent,-1) 09-23 16:12:33.314: INFO/System.out(6244): Error loading url into DroidGap - file:///android_asset/www/page2.html:android.content.ActivityNotFoundException: Unable to find explicit activity class {ir.markdunne.hellophonegap/com.phonegap.DroidGap}; have you declared this activity in your AndroidManifest.xml? If this was a standard android App the solution would be to create an activity tag for page2 in the manifest but I cannot do that here. What is going wrong? Any help would be apprechiated A: This is due to a change in Phonegap 1.0.0. I solved it by adding the following to AndroidManifest.xml. Enter it as an additional activity block. Note that you need "intent-filter" as well. I tried the suggestion without "intent-filter" and it would not work. <activity android:name="com.phonegap.DroidGap" android:label="@string/app_name" android:configChanges="orientation|keyboardHidden"> <intent-filter> </intent-filter> </activity> A: Add this activity into your AndroidManifest.xml <activity android:name="com.phonegap.DroidGap" android:label="@string/app_name" android:configChanges="orientation|keyboardHidden"> </activity>
{ "language": "en", "url": "https://stackoverflow.com/questions/7531371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why does PuTTY use its own private key format when log into SSH server? Just a little bit curious, why PuTTY use its own version of private key format to do SSH? A: The author of PuTTY gives two main reasons for having the custom key format on this page. In short: * *PuTTY's format stores the public half of the key in plaintext, which allows PuTTY to send the public key to the server automatically. *The key is fully tamperproofed with the help of a Message Authentication Code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Algorithm Efficiency Improvement First I would like to apologize if this question has been asked. It is difficult to search for the answer w/o finding how to create arrays of hashes and hashes of arrays.... I am creating a log analyzer. Each error entry is in the form timestamp # # human_timestamp errno # i have created a hash of hashes using a mapping function to do the following: $logRef->{++$errCnt} = { line => $lineNum, timestamp => $timestamp, humanStamp => $humanStamp, errno => $errno, text => '' }; Later on i do some analysis where I would like to isolate the entries between line numbers. The analysis entries are stored in hashes as well... $analysis{++$iteration} = { result => $result, startLine => $startLine, endLine => $endLine, errors => undef }; $analysis{errors} is going to be an array reference. It is filled by doing the following. foreach my $iteration ( keys %analysis ) { my @errKeys = grep { $logRef->{$_}{line} >= $analysis{$iteration}{startLine} && $logRef->{$_}{line} <= $analysis{$iteration}{endLine} } keys %$logRef; my @errs = (); push @errs, $logRef->{$_}{errno} foreach ( @errKeys ); $analysis{$iteration}{errors} = \@errs; } It is not uncommon for my log files to contain 30000+ entries. The analysis run fairly quickly, with the exception of creating the errs array. Is there a more efficient way of generating this array? Thanks A: Whenever you find yourself saying something like $hash{++$counter} = ..., ask yourself whether it would be more appropriate to use an array ($array[++$counter] = ...). Retrieving a hash element $hash{$key} requires Perl to pass the key through a hash function and traverse a linked list, performing one or more string comparisons to find the value. It might also take some effort to stringify the key. Looking up an array element is much faster. Perl may need to convert the index to a number, but it is straightforward to find the memory location holding the array value from there. A: You're asking about micro-optimisations. Sometimes it's hard to predict, so Benchmarking is key. Hashes are arrays of linked lists. They're inherently going to be slower than using an array, so $logRef->{++$errCnt} = ...; is a tiny bit slower than push @$logRef, ...; Converting to arrays and doing some other micro-optimisations leaves you with: foreach my $analysis ( @analysis ) { $analysis->{errors} = [ map $_->{errno}, grep $_->{line} >= $analysis->{startLine} && $_->{line} <= $analysis->{endLine}, @$logRef ]; } or maybe even foreach my $analysis ( @analysis ) { $analysis->{errors} = [ map $_->{line} >= $analysis->{startLine} && $_->{line} <= $analysis->{endLine}, ? $_->{errno} : (), @$logRef ]; } Because * *grep EXPR, and map EXPR, are faster than grep BLOCK and map BLOCK. *When all other things are equal, fewer ops is faster, so this cuts off unnecessary ops.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to set the default selection on the currently added item using jquery I have this code using this code I am inserting an item from one list box to other list box. I need to set the default selection for tagrget list box item when it is added. please can any body help me out how to set the deafult selection to the list box. How to set the default selection to the currently added item to the list box function DoInsert(ind) { var sourceIndex = $("#lstAvailableCode").val(); /// Selected Item to add var targetIndex = $("#lstCodelist").val(); /// added item to the list box(target list box) var success = 0; var rightSelectedIndex = $("#lstCodelist").get(0).selectedIndex; var functionName = "/Ajax/SaveCodeforInsert"; if (ind == "plan") { functionName = "/Ajax/SaveCodeforInsertForPlan"; } $.ajax({ type: "POST", traditional: true, url: functionName, async: false, data: "ControlPlanNum=" + $("#ddControlPlan").val() + "&LevelNum=" + $("#ddlLevel").val() + "&ColumnNum=" + $("#ddlColumn").val() + "&SourcbaObjectID=" + sourceIndex + "&TargetbaObjectID=" + targetIndex + "&userID=<%=Model.userID%>", dataType: "json", error: function (data) { alert("Error Adding Code"); FinishAjaxLoading(); }, success: function (data) { if (data == 0) { success = 1; } else { success = data; } FinishAjaxLoading(); } }); A: could you use .focus() Example: $("#lstCodelist").focus(); A: you can use .focus in the success callback to set the focus $("element").focus()
{ "language": "en", "url": "https://stackoverflow.com/questions/7531379", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .net unit test project with CSV datasource not reading in values correctly I have a Unit Test project in .net 4.0. One of the test methods reads in a CSV file. Unfortunately, some of the values in the csv file are not being read. I think what is happening is that .net is choosing what type a column is and ignoring any values that do not fit within that type. For example, I may have a column where 90% of the values are numbers, but the other 10% are numbers with letters. The numbers with letters are not coming through. Any ideas on how to fix this? Here is the attribute on top of my test method [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\test.csv", "test#csv", DataAccessMethod.Sequential), DeploymentItem("MyProject.Tests\\TestData\\Test.csv"), TestMethod()] Thanks! AFrieze A: You need to enclose the values in the mixed-type column in quotation marks. E.g. AllNumeric,Mixed,AllString 1,"1",a 2,"2b",b Alternatively, you can create a file named Schema.ini in the same directory as the csv file to specify the type, as mentioned below. http://geekswithblogs.net/dotNETvinz/archive/2011/01/03/uploading-and-importing-csv-file-to-sql-server-in-asp.net.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7531383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Flush a pipe associated to an NSFileHandle I am reading piped output from a console application via an NSFileHandle in Cocoa. How can I flush the stream associated to that file handle. If I could get a FILE* object from the NSFileHandle I could call fflush(). Is there a way around this? A: I believe the equivalent in NSFileHandle is -synchronizeFile.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Which configuration do I need to use an external DLL in a WinForms application? I'm working with an external DLL to consume an OCR device using a wrapper written by me. I have made tests on the wrapper and it works perfectly. But, when I use a WinForms project to consume the client class of the wrapper (located an another project), an error arises when calling C# methods imported from the DLL (using [DLLImport(...)]) saying that the DLL is not registered. The error says: "DLL Library function no found. Check registry install path." All executions have been made in debug mode. I've compared both projects configuration. The most relevant difference is that Test project is oriented to Any CPU and WinForms app only points to x86. What could it be? Updates * *I've tried to register the dll using Regsvr32.exe but it didn't work. I thought about using Gacutil.exe but it required to uninstall all frameworks beyond .net framework 1.1... *I was wondering... at testing environment probably everything works well because testing framework has its dll's or executable files (or something like that) totally registered in windows, so those are trusted dlls. It is possible that debug generated dlls are not trusted by windows and therefore this problem arises? *I've created a form in the same troubling project and then I call the OCRWrapper from a button I've added to it. The OCR's worked!!. Unfortunately, it is difficult to rewrite the first form because we have invested a lot of hours in it; so, I'm still wondering what do I need to change in the troubling form... *I started again the form's development from scratch and added all the components related to it; everything worked well, the OCR read succesfully all data. When I loaded a combo box using a call to an ObjectContext and the error appeared again... I'm using an entity framework connected to Oracle. A: I have a theory. Let's imagine the following situation: * *The ocr.dll depends on some other native DLL, lets call it other.dll [A]. * *In case this is a static dependency, you'll see it through Dependency Walker. *If its dynamic, you can use Sysinternals Process Explorer to monitor DLL loading in your working test project at run-time. *Your ADO.NET provider uses native DLLs under the hood (this is certainly true for ODP.NET) which depend on other.dll [B], which happens to have the same name but is actually a different DLL (or at least a different version) compared to other.dll [A]. Then, in run-time, this might happen: * *When you connect to the database, ADO.NET provider dynamically loads its native DLLs, including the other.dll [B]. *Then you try to call a function from OCR DLL. The P/Invoke tries to load the OCR DLL dynamically and succeeds, but the other.dll [B] is already loaded and ocr.dll tries to use some function from it, instead from other.dll [A] where it actually exists. Welcome to DLL hell. So what can you do? * *Try varying the order of calls to ocr.dll and ADO.NET provider to see anything changes. If you are (very) lucky, other.dll [A] might actually be a newer version that is still backward-compatible with other.dll [B] and things migh magically start to work. *Try another version of ADO.NET provider. *Try another ADO.NET provider. *Try getting a statically-linked ocr.dll from your vendor (i.e. no run-time dependency on other.dll [A]). A: So, the call to the DLL works from a single button, but it does not work from a complex form. I'd say that there is an undefined behavior going on. The question remains whether it is you, that wrote the marshalling incorrectly, or it the DLL that is badly written. Since we do not have access to the source code of the DLL, maybe you can post the prototype of the function, and all relevant struct definitions, and the DllImport line that you wrote for it? A: Google can't find that error message which means(not definitely though :)) it is not a system message but a custom one coming from the code in the dll. So the dll does something dodgy. I guess it tries to double dispatch your call to another function internally. Few things I suggest you try: * *Run a x86 configuration. In the project properties -> Build tab set the platform to x86. this is assuming the dll is an x86 dll. dumpbin /headers orc.dll File Type: DLL FILE HEADER VALUES 14C machine (**x86**) 4 number of sections 4CE7B6FC time date stamp Sat Nov 20 11:54:36 2010 0 file pointer to symbol table 0 number of symbols E0 size of optional header 2102 characteristics Executable 32 bit word machine DLL This command line should tell you the bitness. In case it is a 64 bit run a 64 bit config instead but I bet it is 32 bit. * *Do not include the dll in the project. I guess you do that already. Make sure the dll is in a folder that is in the %PATH% environment variable. When you run this at command prompt: where ocr.dll should tell you where the dll is. If it doesn't add the folder where the dll is installed to the %PATH%.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531387", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: javascript error in IE 8? IE 8, 7, and 6 are all complaining about the same character in the below snippet: else if (page == "/about") { $.address.title("About"); $('#main').load("about.php", function () { }); <= This character (the semi colon) } You'll see three javascript errros with IE 8 all pointing to the same character. Am I missing something or is this an invalid character in older version of IE? A: For anyone else who has a similar issue, here was the problem. As mentioned below the error returned from IE was not even close to the correct location. That aside here is what happened. I had a php variable mixed with javascript like so: <textarea class="question_text" id="1" name="1" onFocus="if (this.value == <?php echo($question[0]['question_text']); ?>) { this.value = ''; }"><?php echo($question[0]['question_text']); ?></textarea> I needed to add quotes around the php value retured like so: <textarea class="question_text" id="1" name="1" onFocus="if (this.value == <?php echo("$question[0]['question_text']"); ?>) { this.value = ''; }"><?php echo("$question[0]['question_text']"); ?></textarea> A: According to my debugger, your 1st of 3 syntax errors is here: $.address.title("Edit Profile");
{ "language": "en", "url": "https://stackoverflow.com/questions/7531389", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why do I have to add execjs and therubyracer to my gemfile for rails3.1 to work? I don't like being in situations where I don't understand why something is working. I feel like I am using a trash bag and a rubber-band to fix a leaky pipe. Since upgrading to rails3.1 I have not been able to get it to work unless I add 'execjs' and 'therubyracer' to the gemfile. I do not understand what these gems even do. I just read somewhere on stackoverflow that you had to add them for the app to work. Anyone know what these gems are for? A: ExecJS supports these runtimes: therubyracer - Google V8 embedded within Ruby therubyrhino - Mozilla Rhino embedded within JRuby Node.js Apple JavaScriptCore - Included with Mac OS X Microsoft Windows Script Host (JScript) therubyracer is not necessary, you can use any of the js runtimes instead, for example I use Node.js. A: ExecJs - gives you the ability to, well - execute Javascript RubyRacer - gives you the interface from Ruby to V8 engine. Both are dependencies of the coffee-script gem, which is used by Rails 3.1 and the asset pipeline.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: GridView Cell Color I have to fill the cells of a gridview with just color. No text is required in this case. I have a List of Object X 's that I will bind to gridview. Object X has properties that correspond to the grid view. Suppose there is a property called Y in Object X that is a boolean , if Y is false I need to fill the cell with Red and if Y is true I need to fill it with Yellow. How do I go about doing this ?? I tried something like this: <asp:TemplateField> <HeaderTemplate>Default</HeaderTemplate> <ItemTemplate> <asp:Label ID="Default" runat="server" BackColor= '<%# Eval("Default") %>==true:Green:Blue' </asp:Label> </ItemTemplate> </asp:TemplateField> It gives me an error saying the server tag is not well formed. NOTE: I don't need to fill any text in the cell. Just color based on properties of Object X that are boolean. Hope I have made myself clear.. Any ideas and suggestions are greatly appreciated ! A: Use the style property: If( ObjectX.Y){ DataGridView1.Item(ColumnIndex, RowIndex).Style.BackColor = Red } else { Data GridView1.Item(ColumnIndex, RowIndex).Style.BackColor = Yellow } Not sure if there is a property for forecolor also.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iOS - GCC failing to see a function that seems to be plainly visible This problem may be as a direct result of either me misunderstanding the limitations of Objective-C(++) and how it interacts with C++. Or it may be a case of me missing something thats right in front of me. I have a C++ class that does some Objective-C++ work behind the scenes. As such I have a templated C++ class that makes a call to a templated function. I have then specialised the templated function to create me a UIImage. However when I build I get the following error. ../ImageProcessing/ImageProcessing/MacOS/MacOSImage.h:43: error: no matching function for call to 'MacOSImage<R5G5B5A1>::MakeUIImage(std::vector<R5G5B5A1, std::allocator<R5G5B5A1> >&, unsigned int, unsigned int)' ../ImageProcessing/ImageProcessing/MacOS/MacOSImage.h:41: note: candidates are: UIImage* MacOSImage<ColourSpace>::MakeUIImage() [with ColourSpace = R5G5B5A1] My header file looks like this: #ifndef ImageProcessing_MacOSImage_h #define ImageProcessing_MacOSImage_h #include "Image.h" #ifdef __OBJC__ #import <UIKit/UIImage.h> #else typedef void UIImage; #endif template< typename ColourSpace > UIImage* MakeUIImage( const std::vector< ColourSpace >& colours, unsigned int width, unsigned int height ) { return NULL; } template< typename ColourSpace > class MacOSImage : public BaseImage< ColourSpace > { protected: public: MacOSImage( unsigned int width, unsigned int height ); virtual ~MacOSImage() {}; UIImage* MakeUIImage(); }; template< typename ColourSpace > inline MacOSImage< ColourSpace >::MacOSImage( unsigned int width, unsigned int height ) : BaseImage< ColourSpace >( width, height ) { } template< typename ColourSpace > inline UIImage* MacOSImage< ColourSpace >::MakeUIImage() { return MakeUIImage( BaseImage< ColourSpace >::Pixels(), BaseImage< ColourSpace >::GetWidth(), BaseImage< ColourSpace >::GetHeight() ); } #endif I find this error rather confusing. Not least of all because if you ignore my specialisations there is a template function that ought to exactly match the prototype it is after at the top of the file. Its only disadvantage is that it will return NULL. However this would still give me an idea as to what is going on if I could get it to compile. So has anyone got any ideas why this won't compile? Cheers! Edit: As requested here is Image.h: #ifndef ImageProcessing_Image_h #define ImageProcessing_Image_h #include <vector> template< typename ColourSpace > class BaseImage { protected: unsigned int mWidth; unsigned int mHeight; std::vector< ColourSpace > mPixels; public: BaseImage( unsigned int width, unsigned int height ); virtual ~BaseImage() {}; std::vector< ColourSpace >& Pixels(); const std::vector< ColourSpace >& Pixels() const; unsigned int GetWidth() const { return mWidth; } unsigned int GetHeight() const { return mHeight; } unsigned int GetBytesPerPixel() const { return sizeof( ColourSpace ); } unsigned int GetBitsPerPixel() const { return GetBytesPerPixel() * 8; } }; template< typename ColourSpace > inline BaseImage< ColourSpace >::BaseImage( unsigned int width, unsigned int height ) : mWidth( width ), mHeight( height ), mPixels( width * height ) { } template< typename ColourSpace > inline std::vector< ColourSpace >& BaseImage< ColourSpace >::Pixels() { return mPixels; } template< typename ColourSpace > inline const std::vector< ColourSpace >& BaseImage< ColourSpace >::Pixels() const { return mPixels; } #if defined( _OSX ) #include "MacOS/MacOSImage.h" #define Image MacOSImage #elif defined( _WIN32 ) #include "Win32/Win32Image.h" typedef Win32Image Image; #else #error We need a platform specific implementation of the image class #endif #endif A: This is classical name lookup problem. The compiler stops looking for names when it finds a function with the same name, ignoring the signature. Only then it checks the signature and finds it does not match. You want to call the free version, so you need to say: return ::MakeUIImage( BaseImage< ColourSpace >::Pixels(), BaseImage< ColourSpace >::GetWidth(), BaseImage< ColourSpace >::GetHeight() ); Unrelated hint: Better put all your stuff into your own namespace, otherwise you might sooner or later run into related difficulties when everythign is in the global namespace
{ "language": "en", "url": "https://stackoverflow.com/questions/7531396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Waiting for applications to finish loading Possible Duplicate: Start external app with ShellExecuteEx and wait until it become initialized Is there some way of getting a Delphi app to wait for an external application to finish loading before it proceeds processing? I have an app that launches other apps by using ShellExecute (I have to use ShellExecute as I only have a filename and verb to work with, it launches the associated application as required), but I need my app to wait until the launched app has finished loading before it proceeds. For example, MS Word can take several seconds to load depending on installed plugins etc. I've seen code to get the app to wait until the launched app has been closed down, but I only need to wait till it has finished loading completely. Ideas appreciated.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Magento - Product details don't update When I try and update a product via admin, the update fails and there is no error message: Catalogue -> Manage Products -> Edit I change the name of a product for example I click save. A pop up states 'Please wait" after a couple of seconds it disappears and then the browser waits for the domain for about 60 seconds (I assume an ajax call?) and then does nothing. Thats it. There's nothing in the server error log. Version: Magento ver. 1.5.0.1 Running on cPanel server. A: Open the Net tab in Firebug and look what response do you recive from the server. Looks like you forgot something like echo 123; die; somwhere in yor code. Anyway, the response you'll see will help you to find where the problem is located. A: The solution was simple once I had correctly diagnosed the problem -PHP post_max_size was too low and needed increasing. And error that would have been spotted sooner if error reporting was enabled in admin area of Magneto and if the post wasn't done by AJAX.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: drag and drop in phonegap-android I am trying to drag and drop images using phonegap-android. When i run the code in the mozilla firefox browser then the code runs great and i am able to drag any image but when i run that code in phonegap android 2.1update then i am not able to drag it and even not able to click on it. Anyone can tell me whats going wrong. http://www.devarticles.com/c/a/JavaScript/Building-DragandDrop-DIVs-Developing-a-Basic-Script/ that i used for drag and drop plzz help me out.. Thnks A: Dear all use this in your html. It is not running because the functions working in browser are according to mouse motion mode. Thing you have to do is change to on touch mode of mobile then it works fine... $( init ); function init() { document.addEventListener("touchstart", touchHandler, true); document.addEventListener("touchmove", touchHandler, true); document.addEventListener("touchend", touchHandler, true); document.addEventListener("touchcancel", touchHandler, true); } function touchHandler(event) { var touches = event.changedTouches, first = touches[0], type = ""; switch(event.type) { case "touchstart": type = "mousedown"; break; case "touchmove": type="mousemove"; break; case "touchend": type="mouseup"; break; default: return; } var simulatedEvent = document.createEvent("MouseEvent"); simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY, false, false, false, false, 0/*left*/, null); first.target.dispatchEvent(simulatedEvent); event.preventDefault(); } A: Jquery Mobile Drag And Drop * *http://www.stevefenton.co.uk/Content/Jquery-Mobile-Drag-And-Drop/ Similar discussion: * *HTML Drag And Drop On Mobile Devices
{ "language": "en", "url": "https://stackoverflow.com/questions/7531412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Should messaging classes be immutable? When I say messaging classes I mean classes that are used strictly to get sent and be consumed by a consumer (or handler). Often I see tutorials on service buses (e.g. NServiceBus) that simply make heavy use of automatic properties when creating new messages. In my eyes once a message is sent there is no reason to change. If any changes should occur to the information the message contains then it seems fair to have to create a new message and sent it again. Should they be immutable? A: Yes, they should. There is no reason a message can be changed after their creation, just as you explained. Also messages are normally used for abstraction and/or multithreading. By not making them immutable you take away the benefits immutability provides (e.g. thread safety). A: There are many advantages to making these classes immutable. Messaging systems tend to be something that can easily be made parallel or asynchronous in their delivery. Any time you're introducing threading, immutability can provide a huge level of safety and prevent a lot of common mistakes. In my eyes once a message is sent there is no reason to change If this is your usage scenario, then I would definitely tend to work with immutable data types. I, personally, try to only make mutable types when there is a valid reason to have mutabililty. Otherwise, I always prefer immutability due to the flexibility it brings and the safety it provides when improving the systems that use the type later (ie: introducing concurrency).
{ "language": "en", "url": "https://stackoverflow.com/questions/7531413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Lucene-like searching through JSON objects in JavaScript I have a pretty big array of JSON objects (its a music library with properties like artist, album etc, feeding a jqgrid with loadonce=true) and I want to implement lucene-like (google-like) query through whole set - but locally, i.e. in the browser, without communication with web server. Are there any javascript frameworks that will help me? A: * *Go through your records, to create a one time index by combining all search able fields in a single string field called index. *Store these indexed records in an Array. *Partition the Array on index .. like all a's in one array and so on. *Use the javascript function indexOf() against the index to match the query entered by the user and find records from the partitioned Array. That was the easy part but, it will support all simple queries in a very efficient manner because the index does not have to be re-created for every query and indexOf operation is very efficient. I have used it for searching up to 2000 records. I used a pre-sorted Array. Actually, that's how Gmail and yahoo mail work. They store your contacts on browser in a pre-sorted array with an index that allows you to see the contact names as you type. This also gives you a base to build on. Now you can write an advanced query parsing logic on top of it. For example, to support a few simple conditional keywords like - AND OR NOT, will take about 20-30 lines of custom JavaScript code. Or you can find a JS library that will do the parsing for you the way Lucene does. For a reference implementation of above logic, take a look at how ZmContactList.js sorts and searches the contacts for autocomplete. A: You might want to check FullProof, it does exactly that: https://github.com/reyesr/fullproof A: Have you tried CouchDB? Edit: How about something along these lines (also see http://jsfiddle.net/7tV3A/1/): var filtered_collection = []; var query = 'foo'; $.each(collection, function(i,e){ $.each(e, function(ii, el){ if (el == query) { filtered_collection.push(e); } }); }); The (el == query) part of course could/should be modified to allow more flexible search patterns than exact match.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Can Eclipse CDT generate by-reference getter methods? Consider: struct A {}; struct B { A a; } If I let Eclipse automatically generate the getter method for `a' it has the following signature: A B::getA() const; Is it possible to automatically generate getters with other signatures, e.g. A& B::getA(); from within Eclipse CDT? Regards
{ "language": "en", "url": "https://stackoverflow.com/questions/7531416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails 3 - Update_attribues won't get changed parameters i have somes relations in my table like this Model : Floors has_many :photo Model : Photo belongs_to :floors belongs_to :file_type Model : file_type has_many :photo Photo are nested attributes with render inside floors form. The problem is if i change the file type inside the form without any other change in the form, the new selected alements are not updated, and the update_attributes (in the WEBrick) console, the new selected are not updated. Photo are a paperclip element with versioning. I don't want to update each time the file if i just want to change his file type related. Thanks for your help. EDIT : Has asked, my views. # _form.html.erb <% f.fields_for :floor_photo do |floor_photo| -%> <%= render 'floor_photo_fields', :f => floor_photo %> <% end -%> <div> <%= link_to_add_fields "Add Photo", f, :floor_photo %> </div> # _floor_photo_fields.html.erb <div class="fields"> <%= f.label 'Photo' %><br/> <%= f.file_field :photo %> <%= f.collection_select :file_type_id, FileType.all(:order => 'name'), :id, :name, {:prompt => 'Select'}%> <%= link_to_remove_fields "remove", f %><br/> <div style="margin-bottom:10px;"><%= f.object.photo_file_name %></div> </div> For now, if i click Add Photo, and set a file type to the photo, it's work, but when i edit a floors and want to change the file type, he don't want to take the new file_type_id and don't do any update sql statement. Like if i have nothing changed in my form. And yes, sorry for my relations, it was a typo mistake, all are good in my models form. # floor_photo.rb class FloorPhoto < ActiveRecord::Base versioned belongs_to :floor belongs_to :file_type has_attached_file :photo, :keep_old_files => true, :url => "/system/buildings/photos/:id/:version/:basename.:extension", :path => ":rails_root/public/system/buildings/photos/:id/:version/:basename.:extension" Paperclip.interpolates :version do |attachment, style| attachment.instance.version.to_s end end # file_type.rb class FileType < ActiveRecord::Base has_many :floor_photos end I hope this help someone to help me. Sorry, here is my controller floors_controllers.rb def edit @floor = Floor.find(params[:id]) end def update @floor = Floor.find(params[:id]) if @floor.update_attributes(params[:floor]) redirect_to space_path(@floor) else render :action => 'edit' end end A: The code doesn't look right: Model : Floors has_many :photo #should be :photos Model : Photo belongs_to :floors #should be :floor belongs_to :file_type Model : file_type has_many :photo #should be :photos
{ "language": "en", "url": "https://stackoverflow.com/questions/7531417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: problem formatting php output I have a php website that I want to use to gather information from a unix server. A good example would be a script that would ssh into a server and run an ls command. I am having problems formatting the output so it is readable. Any help would be appreciated. The code would look something like this: $output = system("ssh user@testServer ls -al"); print ($output); A: you probably want to use echo "<pre>"; echo system("ssh user@testServer ls -al"); echo "</pre>"; which shows code in $output as-is (3 spaces shows as 3 spaces, a new line shows as a new line) A: The problem is this The system() call also tries to automatically flush the web server's output buffer after each line of output if PHP is running as a server module. So you need to do this like this: echo '<pre>'; $output = system("ssh user@testServer ls -al"); echo '</pre>'; Alternative As suggested by Deebster, if you have exec function enabled on your server you can do this like this also $output = null; exec("ssh user@testServer ls -al", $output); echo '<pre>'; foreach($output as $line) echo $line . "\n"; echo '</pre>'; A: Try using htmlspecialchars() to escape anything that will cause rendering problems in HTML: print '<pre>' . htmlspecialchars($output) . '</pre>'; The pre tag will respect whitespace and defaults to a monospaced font so your lines will look like they would in a console. A: Not tested but I guess it will work since php doc says The system() call also tries to automatically flush the web server's output buffer after each line of output if PHP is running as a server module. ob_start(); system("ssh user@testServer ls -al"); $output = ob_get_clean(); echo '<pre>'; echo $output; echo '</pre>';
{ "language": "en", "url": "https://stackoverflow.com/questions/7531420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to set src in iframe using Javascript I'm working on a MVC project right now and the current feature being developed is a DropDownList with each option tied to a URL. When the user selects an item and presses Submit, the expected behaviour is for the page to load an iframe on the same page with the particular URL tied to their selection displayed in said frame. Controller: Function Configuration() As ActionResult Dim configList As List(Of String) = New List(Of String) configList.Add("10GBaseLX4") configList.Add("10GFC") configList.Add("10GigE") configList.Add("100BaseFX") ViewData("cprotocols") = New SelectList(configList) Return View() End Function Public Function Handle(ByVal cprotocols As String) As String Return "http://www.configlist.com/" + cprotocols + "_Config.xml" End Function View: <% Using (Ajax.BeginForm("Handle", New AjaxOptions With {.OnComplete = "showConfig"}))%> Select a configuration file to view: <%= Html.DropDownList("cprotocols") %> <br /> <input type="submit" value="Submit" /> <br /> <%End using %> <br /> <script type="text/javascript"> function showConfig(cprotocols) { var param1 = cprotocols; document.write('<iframe src="' + param1 + '"></iframe>'); } </script> </p> That's what i have in the view right now, but what ends up happening is that: * *The frame appears AFTER I press submit; ideally, I'd like the frame to already exist on the page, then have the url requested load inside it after submit is clicked. Is this possible? *A new page pops up, the frame is there, but I get a 404 "resource does not exist" error (obviously from the javascript syntax being wrong). My goal is to have the file requested load on the same screen as the DDL. *The URL is dealt with entirely by the Handle() action. A: You're better off just putting it in your page as path of the existing HTML (perhaps in your master page), then use JavaScript to set the SRC when the selection takes place. <iframe id="frm1" src="about:blank"></iframe> js: document.getElemenyById('frm1').src="...."
{ "language": "en", "url": "https://stackoverflow.com/questions/7531422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: strange syntax in javascript to access a specific id in the dom I am currently working on an old project with ton of legacy code. A syntax I have never met is used to access a specific id in the dom in javascript. Instead of using document.getElementById("btnsubmit"), $('btnsubmit') is used. I have never met this syntax. Moreover it seems that firebug doesn't like it either as it seems to break the debugger. I have issues where the code doesn't seem to be executed in a debugging environment although this code is used on a production site and seems to work. Does any one have a reference on this syntax? Where does it comes from, is it deprecated? A: It's from a javascript library, and in general it's more modern than getElementById. You need the script include though. Your example looks like Prototype A: $ is just a regular character in javascript and it is often used by javascript libraries and defined to be a function name so that $() is just a function call. In some cases, $ might be defined to be a synonym for document.getElementById() as shorthand to save typing and in other cases, it's a more robust CSS3 style selector engine (as in the jQuery library). In either case, if its undefined in your code, then you are probably missing a library reference that your code relies on. You will need to find out what library your code was written to use and make sure that library is included in the code before this spot so that the $() function is defined properly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531428", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to increase height of cell for the UIImagePickerViewController Hi i have ImagePickerViewController i Need to increase the height of the cell its look's like the tableview and i need to increase that cell height of the imagePickerviewController. I hope every one can understand my question. i am attaching the picture - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. // Add the navigation controller's view to the window and display. UIImagePickerController *albumPicker = [[UIImagePickerController alloc]init]; [albumPicker setDelegate:self]; [albumPicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary]; [albumPicker setContentSizeForViewInPopover:CGSizeMake(300, 700)]; [self.window addSubview:albumPicker.view]; [self.window makeKeyAndVisible]; return YES; } - (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated { UINavigationItem *ipcNavBarTopItem; // add done button to right side of nav bar UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Photos" style:UIBarButtonItemStylePlain target:self action:@selector(saveImages:)]; UINavigationBar *bar = navigationController.navigationBar; [bar setHidden:NO]; ipcNavBarTopItem = bar.topItem; ipcNavBarTopItem.title = @"Photos"; ipcNavBarTopItem.rightBarButtonItem = doneButton; } For the given picture which is an UIImagePicker And i need to increase its cell height. I try my luck. can any one help me out. A: It's obviously UITableView. Height of all cells could be set over rowHeight property of UITableView or individually for each cell in heightForRowAtIndexPath method of UITableViewDelegate. Have a look in your sources to understand where UITableView is set. A: To increase the height of the TableView cell implement the below method: - (CGFloat)tableView:(UITableView *)tv heightForRowAtIndexPath:(NSIndexPath *)indexPath { CGFloat height; height = 44; return height; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7531429", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to interrupt an XSLT for-each loop for not contiguos elements? I have a structured XML with this structure: <root> <item/> <item/> <something/> <item/> </root> If I use something like this: <xsl:for-each select="/root/item"> it will pick all the item elements inside the list. I want to interrupt the loop after the second item, because between the 2nd and the 3rd there is a something element. How can I get this? A: You can't actually break out of a xsl:for-each loop. You need to construct your loop so as to select only the elements you want in the first place. In this case, you want to select all item elements which don't have a preceding sibling that isn't also an item element. <xsl:for-each select="/root/item[not(preceding-sibling::*[not(self::item)])]"> <xsl:value-of select="position()" /> </xsl:for-each> When this is used, it should only select the first two item elements. A: In XSLT there isn't any possibility for a "break" out of an <xsl:for-each> or out of <xsl:apply-templates>, except using <xsl:message terminate="yes"/> which you probably don't want. This is due to the fact that XSLT is a functional language and as in any functional language there isn't any concept of "order of execution" -- for example the code can be executing in parallel on all the nodes that are selected. The solution is to specify in the select attribute an expression selecting exactly the wanted nodes. Use: <xsl:for-each select="/*/*[not(self::item)][1]/preceding-sibling::*"> <!-- Processing here --> </xsl:for-each> This selects for processing all preceding elements siblings of the first child element of the top element that isn't item -- that means the starting group of adjacent item elements that are the first children of the top element.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531431", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How does strace interpret syscall arguments? I know it uses ptrace for implementation, and it can get arguments in registers, but they're numbers only, how does strace convert them into literal information? Is it just hard code for every syscall? A: Basically, yes, its hardcoded. If you look at the sourcecode (detail), you can see big tables of system calls and big switch statements that know how to decode all their various arguments and return values for multiple different OSes and CPUs
{ "language": "en", "url": "https://stackoverflow.com/questions/7531436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I make different buttons show different data on a single screen on iPad I am making an app for iPad with different views. Till now I have added 2 views. First view is the home screen which has a single button and some images. Pressing button on first view navigates to the second view. Second view has 6 buttons. Now what I want to do is when I press any button on second view, it navigates to the third view. Each button on second view has to show different data. I don't want 6 different views, instead I want a single third view but it should show only that particular data respective to the button pressed on second view. How can it be done?? Please help me with the code.. Any help will be highly appreciated.. A: You just need a variable in the third view that you set before showing it. I would set a different tag value for each of my buttons and have them all call a single method. In that method, check the tag value of the sender and setup the third view accordingly. Then show it. In the third view's viewDidLoad method you can handle displaying or setting up the new data you assigned to it. For example, if you were setting some custom text in the third view you would have this for your button method in the second view: - (IBAction)buttonTap:(id)sender { UIButton *tappedButton = (UIButton *)sender; MyThirdViewController *thirdVC = [[MyThirdViewController alloc] initWithNib:@"MyThirdViewController" bundle:nil]; switch (tappedButton.tag) { case 1: thirdVC.customText = @"Something for button 1"; break; case 2: thirdVC.customText = @"Something for button 2"; break; case 3: thirdVC.customText = @"Something for button 3"; break; } [self.navigationController pushViewController: thirdVC]; [thirdVC release]; } In the third ViewController: - (void)viewDidLoad { self.myTextView.text = self.customText; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7531439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I use the Settings Bundle editor in XCode to specify UIs other than those for Settings? The Settings Bundle editor in XCode (New->File->iOS->Resource->Settings Bundle) seems like a convenient tool for rapidly specifying a large range of user interfaces other than just user preferences. Is there any way to use this tool and the .plist mechanism for declaratively specifying user interfaces in general, rather than just for user defaults? In other words, can I create a settings bundle (but not for settings) and programmatically load it from my application bundle and have iOS generate a view (and controller?) from it within my application? A: It sounds like you want something like In App Settings Kit. This will let you make a settings page identical to the iphone one but inside your app.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to fill an external web form with c# application? There is some url (say url1) which is blocked till some unknown time. Currently, when you request for url1 you're redirected to url2 (Though in fiddler I get a 200 status - why ?) When url1 will be available - the few first people who will fill the a web-fom and submit it can buy a really nice product in a disccounted price. i want to write a c# application which will try to access url1 in a loop. After it will enter url1 I want it to fill a known in advance form and select some drop-down list and submit my request. I have started with: static void Main(string[] args) { string url = "https://url1"; WebRequest request = HttpWebRequest.Create(url); WebResponse response = request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); string urlText = reader.ReadToEnd(); } But I'm not sure how to: 1. check the response's url (I thought to check for 302, but filddler show 200. can I see status code in this StreamReader reader ?) * *Given this form example, how can I fill it automatically ? <td style="width: 100px;"> *First name: </td> <td> <input name="ctl00$ctl00$Content$Main$OrderNameFirst" type="text" id="Content_Main_OrderNameFirst" style="width:150px;" /> <span id="Content_Main_RequiredFieldValidator9" class="textValidator" style="display:none;">שדה חובה</span> </td> <td style="vertical-align: top; padding-right: 100px;"> <input type="image" name="ctl00$ctl00$Content$Main$ImageButton1" id="Content_Main_ImageButton1" class="image" src="Images/buttonSubmitPaypal.png" onclick="javascript: return SubmitPaypal(this);" style="cursor:pointer;" /> </td> </tr> </td> </tr> <tr> <td> *Type: </td> <td colspan="2"> <select name="ctl00$ctl00$Content$Main$OrderCreditType" id="Content_Main_OrderCreditType"> <option value="Visa">A</option> <option value="IsraCard">B</option> <option value="MasterCard">C</option> A: The only way you can do this (Without invoking javascript which is insanely confusing) is to use a Web Browser control to do the auto fill. You can use Web Response and Web Request to get the response and when it receives the correct one you can use WebBrowser1.Navigate("http://url.com"); From there you can use a old trick to put data in to a form. This will not change the address of the current page but execute this javascript on page. It will find the first element with the class name of 'textbox' and give it a value of 'email@domain.com' WebBrowser1.Navigate("javascript: void(document.getElementsByClassName('textbox')[0].value = 'email@domain.com')"); TIP: You can make the WebBrowser invisible.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Omit object property during json serialization I'm using MVC Controller. Json method in order to send json result object to my javascript function. From time to time I want to omit one of my object's property from the json result object. How can I achive it? This is my .NET object: public class jsTreeModel { public string Data { get; set; } public JsTreeAttribute Att { get; set; } public string State { get; set; } public List<jsTreeModel> Children { get; set; } } I this case I want to omit the 'Children' property from the json result. Any idea? A: If you are using Json.NET as your serializer, you can omit a property fairly simply: public class jsTreeModel { public string Data { get; set; } public JsTreeAttribute Att { get; set; } public string State { get; set; } [JsonIgnore] public List<jsTreeModel> Children { get; set; } } I hope this helps you!
{ "language": "en", "url": "https://stackoverflow.com/questions/7531445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: CDI Injection into a FacesConverter From just a few searches, this seems like a problem that has been around for a while. I have written a FacesConverter that looks like the following. The object Category is a JPA entity and CategoryControl is the DAO that fetches it. @FacesConverter(value = "categoryConverter") public class CategoryConverter implements Converter { @Inject private CategoryControl cc; public CategoryConverter() { } @Override public Object getAsObject(FacesContext context, UIComponent component, String value) { if (cc != null) return cc.getByName(value); System.out.println("CategoryConverter().getAsObject(): no injection!"); return null; } @Override public String getAsString(FacesContext context, UIComponent component, Object value) { if (!(value instanceof Category)) return null; return ((Category) value).getName(); } } As you probably guessed by now, I never get the injection. I got this workaround from this page, which looks like this.: Workaround for this problem: create this method in your localeController: public Converter getConverter() { return FacesContext.getCurrentInstance().getApplication().createConverter("localeConverter"); } and use converter="#{localeController.converter}" in your h:selectOneMenu. However I can't make this work either. My backing bean creates and returns a converter all right, but it doesn't get the object injected into it. I am using MyFaces CODI 1.0.1. With the current GlassFish/Weld container. Can anyone suggest a solution before I re-code to not use a Converter? A: The @Inject Annotation only works in CDI managed instances. If you want to use CDI features inside a non-CDI managed instance (Like a JSF Validator or a JSF Converter) you can just programm against the CDI API. This works only in at least Java EE 7 + CDI 1.1 server. @FacesValidator("userNameValidator") public class UserNameValidator implements Validator { private UserService userService; public UserNameValidator(){ this.userService = CDI.current().select(UserService.class).get(); } @Override public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException { .... } } https://docs.oracle.com/javaee/7/api/javax/enterprise/inject/spi/CDI.html With all the AnnotationHell in Java EE people forget how to code. A: Replace @FacesConverter(value = "categoryConverter") by @Named and use <h:inputSomething converter="#{categoryConverter}" /> or <f:converter binding="#{categoryConverter}" /> instead of <h:inputSomething converter="categoryConverter" /> or <f:converter converterId="categoryConverter" /> By the way, similar problem exist for @EJB inside a @FacesConverter. It however offers a way to be grabbed by JNDI manually. See also Communication in JSF 2.0 - Getting an EJB in @FacesConverter and @FacesValidator. This way you can use a @FacesConverter(forClass=Category.class) without manually defining it everytime. Unfortunately I can't tell from top of head how to realize that for CDI beans. Update: if you happen to use JSF utility library OmniFaces, since version 1.6 is adds transparent support for using @Inject and @EJB in a @FacesConverter class without any additional configuration or annotations. See also the CDI @FacesConverter showcase example. A: Just use @Advanced of CODI for your @FacesConverter see the Wiki. As soon as a converter or a validator is annotated with @Advanced it's possible to use @Inject. A: Per BalusC's answer here, I decided to add JSF (requestscoped) managed beans that only contained @FacesConverter and Converter to resolve this issue in my app, since I'm migrating from JSF managed beans to CDI managed beans. I tried CODI @Advanced against @FacesConverter, but it does not inject the bean at all.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "32" }
Q: Is there any way to get around name collisions in nested structures in my Mustache.js templates? I'm really having problems with name collisions in my Mustache templates (using Mustache.js). This example illustrates those two problems: I'm passing this data: {'recs': {'code': 'foo', 'id': 1 'childRecs': [{'id': 2}, {'code': 'bar', 'id': 3}] } } Into this template: {{#recs}} Record ID: {{id}} {{#childRecs}} This child code is: [{{code}}] and its parent ID is: {{id}} {{/childRecs}} {{/recs}} Expected: Record ID: 1 This child code is: [] and its parent ID is 1 This child code is: [bar] and its parent ID is 1 Actual: Record ID: 1 This child code is [foo] and its parent ID is 2 This child code is [bar] and its parent ID is 3 * *There is no way in the nested {{#childRecs}} block to access the parent {{#recs}}{id}}{{/recs}} field -- it is overwritten by the {{#childRecs}}{{id}}{{/childRecs}} *If a variable in {{#childRecs}} is missing, and a parent variable of the same name exists, there is no way to prevent it from printing the parent variable. My nested structures are very deep and there are many name collisions, so renaming them in such a way that they do not collide is not a viable option. Is there any other way to solve my problems? A: I see two options: * *Enrich the data on the client-side before sending it for rendering. For instance, you can loop over all the childRecs and add a new parentId property - and then update your template accordingly, or *Use http://www.handlebarsjs.com/ - it keeps the mustache syntax but adds a few goodies like accessing the parent context (through ../). For instance: {{#recs}} Record ID: {{id}} {{#childRecs}} This child code is: [{{code}}] and its parent ID is: {{../id}} {{/childRecs}} {{/recs}}
{ "language": "en", "url": "https://stackoverflow.com/questions/7531450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: XML to excel error I've been importing various XML files to excel, which it does fine, but once i save and close the spread sheet and re-open it again to import other XML files an error occurs. The error is below. 'The operation cannot be completed because the XML map is corrupt. To fix this problem, remove the associated XML map from the workbook and then add the XML map back to the workbook.' When i try to remove it by clicking on the 'Source' button in the XML category on the ribbon the error appears again. Anyone have any suggestions?? A: One way to delete the map is in "Immediate" window of VB Page (Developer Macros Edit), enter the following command: thisworkbook.XmlMaps(1).Delete Then, what I've found is one needs to import a schema with no "includes", which means flattening out the XSD files into one big XSD file. Hope microsoft fixes this, because it's a pain!
{ "language": "en", "url": "https://stackoverflow.com/questions/7531451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Looking for CSS parser written in AS3 I need to load and apply CSS at runtime in my Flex app. I know that the adobe docs say that you need to compile the CSS before loading it but I would like to find a work around. I know that you can set individual styles like this: cssStyle = new CSSStyleDeclaration(); cssStyle.setStyle("color", "<valid color>); FlexGlobals.topLevelApplication.styleManager.setStyleDeclaration("Button", cssStyle, true); I was planning on parsing a CSS file and appling each attribute as above. I was wondering if: * *Adobe had a CSS parser library that I could use *Someone else had a CSS parser that I could use *If I write my own CSS parser what I should watch out for I know that the adobe flex.text.StyleSheet class has a CSS parser but I could not find a way to harness that. (Is there a way to get that source code?) A: Edit: This solution does not work. All selectors that are taken out of the parser are converted to lowercase. This may work for your application but it will probably not... I am leaving this answer here because it may help some people looking for a solution and warn others of the limitations of this method. Although it was not intended for this it is possible to use the StyleSheet class to parse the CSS. I am currently investigating how robust this is currently but for the most part it appears to be working. public function extractFromStyleSheet(css:String):void { // Create a StyleSheet Object var styleSheet:StyleSheet = new StyleSheet(); styleSheet.parseCSS(css); // Iterate through the selector objects var selectorNames:Array = styleSheet.styleNames; for(var i:int=0; i<selectorNames.length; i++){ // Do something with each selector trace("Selector: "+selelectorNames[i]; var properties:Object = styleSheet.getStyle(selectorNames[i]); for (var property:String in properties){ // Do something with each property in the selector trace("\t"+property+" -> "+properties[property]+"\n"); } } } A: I had similar problem but more precisely i want the completely avoid the compilation because my application is wrapper by ActiveX used by a custom exe file and i let the software distributor to customize their skin. In practice we put the <fx:Style> outside the application. To avoid low level parsing on the string we had transformed the Style Sheet in an XML: <styles> <namespace name="myNs" value="com.myComponent"> <declaration selector="myNS|Button#myselector:over #mysubselector"> color:#ffffff; font-size:bold </declaration> ... other styles </styles> Beside the security considerations about let the user know your components you can load the XML and create a CSSStydeclaration. Splitting and parsing only the selector let you create a series of CSSCondition and CSSSelector to add to your CSSStyleDeclaration. To parse the selector we use a little loop which search "#",":" and "." and split the string mantaining the sequence of the found CSS conditions. var selectors:Array = []; // first selector var conditions:Array = [ new CSSCondition(CSSConditionKind.ID, 'myselector'); new CSSCondition(CSSConditionKind.PSEUDO, 'over'); ]; // here you have to find and expand the namespace ancestor:CSSSelector = new CSSSelector('com.myComponent.Button', conditions); selectors.push(selector); // second selector var conditions:Array = [ new CSSCondition(CSSConditionKind.ID, 'mysubselector'); ]; selector:CSSSelector = new CSSSelector('', conditions, ancestor); selectors.push(selector); // Empty style declaration new CSSStyleDeclaration(selectors, styleManager, false); Then you can parse CSS properties by parseCSS() with the function created by @sixtyfootersdude, but using a fake selector: var myCSS:String = "#fake " + "{" + cssTextReadedFromXML + "}"; var style:StyleSheet = new StyleSheet(); sheet.parseCSS(myCSS); // here you have your parsed properties var list:Object = sheet.getStyle('#fake'); Then you can add the properties to the CSSStyleDeclaration and apply them by the setStyle method and apply the declaration as in your example. Less or more is how I've tryed to resolve this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Is there a difference between initializing a variable using new, followed by assignment and just assignment on initialization? I am trying to learn Java. I have a custom class, which has attributes: public class Person{ private String name; } I have another class, where I do: public class foo{ private Person guy; public void setGuy(Person guy){ this.guy = guy; } public Person getGuy(){ return guy; } void someMethod(){ Person anotherGuy = new Person(); anotherGuy = getGuy(); } } I am confused when I use the getGuy() method. I thought that when I do this: Person anotherGuy = new Person(); anotherGuy = getGuy(); I create a new object, which has the same value as guy. But it seems that anotherGuy is actually a pointer to guy. So Person anotherGuy = getGuy(); and the above 2 lines, do the exact same thing? I am confused. Also then how do I create a entirely new object in memory? A: So Person anotherGuy = getGuy(); and the above 2 lines, do the exact same thing? No, the other version creates a new Person() object first and then discards it (which is just a waste of memory and processor cycles). A: Person anotherGuy; this is a reference to a Person object anotherGuy = new Person(); this sets the reference to a new Person object anotherGuy = getGuy(); this sets the reference to the same reference as the guy member of foo. I you want to "copy" object you might want to have a look for Object.clone() A: While folks have already talked/explained about the behavior of your existing code, in order to do what you want to, use the clone feature in Java, wherein your Person class would implement the Cloneable interface, which would ask you to implement the clone() method. Your clone() method should like this : public Object clone() { Person p = new Person(); p.setName(this.name); // similarly copy any other properties you want return p; } and then invoke clone to copy your object: Person another = (Person) person.clone(); A: Java variables can only contain primitives and references. Person is a reference to an object. (You don't have to use & like you might in C++ because its the only option) When you do Person anotherGuy = new Person(); // create a new object and assign the reference. anotherGuy = getGuy(); // change the reference in `anotherGuy` to be the one returned by getGuy(); A: Yes, both do the same thing, in that after both method calls, anotherGuy == null.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IE8: Object doesn't support this property or method I know that my issue is known, I just can't figure out a way to fix the problem. However the code works in chrome,ff and safari, but not in ie6-8. I tried to debug the code and following popped up: Line: 272 Error: Object doesn't support this property or method This is line 272 from my js-file $('#page1')[0].addEventListener('webkitAnimationEnd', self.webkitAnimationEnd, true); Hav you got an idea what is wrong with it? I'm using jquery <script type="text/javascript" src="js/jquery-1.4.3.min.js">;</script> which is called in my .html file. I appreciate any help or useful hint. Thank you in advance. A: See mozilla docs for problem description and solution var el = $('#page1')[0]; if (el.addEventListener){ el.addEventListener('webkitAnimationEnd', self.webkitAnimationEnd, true); } else if (el.attachEvent){ el.attachEvent('webkitAnimationEnd', self.webkitAnimationEnd); } A: use attachEvent for IE here is a SO link MSIE and addEventListener Problem in Javascript? your code may look like if ( $.browser.msie ) { $('#page1')[0].attachEvent('webkitAnimationEnd', self.webkitAnimationEnd); } hope that will help
{ "language": "en", "url": "https://stackoverflow.com/questions/7531462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Symfony 2 - Doctrine : OnetoOne relationship unclear i've been losing my nerves over it and spent a couple of hours searching here and there, unfortunately to no avail. I've got 2 entities, we'll call them A and B for the sake of simplicity <?php namespace System\Main\SystemBundle\Entity; use Doctrine\ORM\Mapping as ORM; class A { /** * @ORM\OneToOne(targetEntity="B") * @ORM\JoinColumn(name="operator_I_id", referencedColumnName="_I_id") */ private $operator = null; class B { private $_I_id = null; I'd like to know how I could possibly get the related entity of A (i.e, B). Here I am with my instance of class A, not knowing how to fetch the related entity (of class B)...I'm stuck here and, to say the least, a bit confused. Thanks a lot for helping, S.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Most efficient way to add missing alt tags for images in a large html document In order to comply with accessibility standards, I need to ensure that all images in some dynamically-generated html (which I don't control) have an empty alt tag if none is specified. Example input: <html> <body> <img src="foo.gif" /> <p>Some other content</p> <img src="bar.gif" alt="" /> <img src="blah.gif" alt="Blah!" /> </body> </html> Desired output: <html> <body> <img src="foo.gif" alt="" /> <p>Some other content</p> <img src="bar.gif" alt="" /> <img src="blah.gif" alt="Blah!" /> </body> </html> The html could be quite large and the DOM heavily-nested, so using something like the Html Agility Pack is out. Can anyone suggest an efficient way to accomplish this? Update: It is a safe assumption that the html I'm dealing with is well-formed, so a potential solution need not account for that at all. A: Your problem seems very specific, you need to alter some output, but you don't want to parse the whole thing with (something general-purpose like) HTMLAgilityPack for performance reasons. The best solution would seem to be to do it the hard way. I would just brute force it. It would be hard to do it more efficiently than something like this (completely untested and almost guaranteed not to work exactly as-is, but logic should be fine, if missing a "+1" or "-1" somewhere): string addAltTag(string html) { StringBuilder sb = new StringBuilder(); int pos=0; int lastPos=0; while(pos>=0) { int nextpos; pos=html.IndexOf("<img",pos); if (pos>=0) { // images can't have children, and there should not be any angle braces // anyhere in the attributes, so should work fine nextPos =html.IndexOf(">",pos); } if (nextPos>0) { // back up if XML formed if (html.indexOf(nextPos-1,1)=="/") { nextPos--; } // output everything from last position up to but // before the closing caret sb.Append(html.Substring(lastPos,nextPos-lastPos-1); // can't just look for "alt" could be in the image url or class name if (html.Substring(pos,nextPos-pos).IndexOf(" alt=\"")<0) { sb.Append(" alt="\"\""); } lastPos=nextPos; } else { // unclosed image -- just quit pos=-1; } } sb.Append(html.Substring(lastPos); return sb.ToString(); } You may need to do things like convert to lowercase before testing, parse or test for variants e.g alt = " (that is, with spaces), etc. depending on the consistency you can expect from your HTML. By the way, there is no way this would be faster, but if you want to use something a little more general for some reason, you can also give a shot to CsQuery. This is my own C# implementation of jQuery which would do something like this very easily, e.g. obj.Select("img").Not("[alt]").Attr("alt",String.Empty); Since you say that HTML agility pack performs badly on deeply-nested HTML, this may work better for you, because the HTML parser I use is not recursive and should perform linearly regardless of nesting. But it would be far slower than just coding to your exact need since it does, of course, parse the entire document into an object model. Whether that is fast enough for your situation, who knows. A: I just tested this on a 8mb HTML file with about 250,000 lines. It did take a few seconds for the document to load, but the select method was very fast. Not sure how big your file is or what you are expecting. I even edited the HTML file to include some missing tags, such as </body> and some random </div>. It still was able to parse correctly. HtmlDocument doc = new HtmlDocument(); doc.Load(@"c:\\test.html"); HtmlNodeCollection col = doc.DocumentNode.SelectNodes("//img[not(@alt)]"); I had a total of 54,322 nodes. The select took milliseconds. If the above will not work, and you can reliably predict the output, it is possible for you to stream the file in and break it in to manageable chunks. pseduo-code * *stream file in *parse in HtmlAgilityPack *loop until end of stream I imagine you could incorporate Parallel.ForEach() in there as well, although I can't find documentation on whether this is safe with HtmlAgilityPack. A: Well, if I review your content for Section 508 compliance, I will fail your web site or content - unless the blank alt text is for decorative (not needed for comprehension of content) only. Blank alt text is only for decoration. Inserting it might fool some automated reporting tools, but you certainly are not meeting Section 508 compliance. From a project management standpoint, you are better off leaving it failing so the end-users creating the content become responsible and the automated tool accurately reports it as non-compliant. A: Hoping Chaps are clever enough to generate the Html markup wherever they need. Then here is the quick trick to convert the find out the SEO result for Images missing ALT attribute without too much struggle. private static bool HasImagesWithoutAltTags(string htmlContent) { var doc = new HtmlDocument(); doc.LoadHtml(htmlContent); return doc.DocumentNode.Descendants("img").Any() && doc.DocumentNode.SelectNodes("//img[not(@alt)]").Any(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7531465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Company Intranet, PHP/MySQL hosted locally on serve I created an intranet for my company, but I’m having a problem. The files and MySQL tables are hosted on our local server, and is written in PHP. Basically it has a login system for employees and a bulletin board, calendar, etc. Anyways, I created accounts for the employees, but nobody can login from their own computers, only my computer and the server computer. Is it because I only have PHP installed on these two computers? Do I need to install it on all computers? Any help is appreciated! A: You need to make your intranet ip address of server static . Type ipconfig /all in your command promt of server there will be ip address like 192.168.1.* (not 192.168.1.1) copy that and then use it from other computers to access your local website.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531470", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby mod_passenger process timeout A few Ruby apps I've worked with hang for a long time on slow calls causing processes to backup on the machine eventually requiring a reboot. Is there a quick and easy way in Passenger to limit a execution time for a single Apache call. In PHP if a process exceeds the max execution time setting in php.ini the process returns an error to Apache and the server keeps merrily plugging away. A: I would take a look at fixing the application. Cutting off requests at the web server level is really more of a band aid and not addressing the core problem - which is request failures, one way or another. If the Ruby app is dependent on another service that is timing out, you can patch the code like this, using the timeout.rb library: require 'timeout' status = Timeout::timeout(5) { # Something that should be interrupted if it takes too much time... } This will let the code "give up" and close out the request gracefully when needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do I animate elements stored in an array? except for the one I'm hovering over? This is what I have: jQuery.each(shapes, function(i) { this.hover(function(event) { this.animate({ fill: "#fff" }, 500); }, function(event) { this.animate({ fill: "#555" }, 500); }); }); I'm using raphael.js, but I figure this issue is general to jQuery syntax. So, when I hover over an element (stored in shapes) I want that element to remain as-is, but then change che opacity of all the other elements. I don't know where to start.=\ EDIT: so, I feel like, as far as semantics goes, this should work: jQuery.each(shapes, function(i) { current_shape = this; this.hover(function(event) { jQuery.each(shapes, function(j){ if (shapes[users_with_direct_employees[j][0]] != current_shape){ shapes[users_with_direct_employees[j][0]].animate({ fill: "#fff" }, 500); } }); }, function(event) { jQuery.each(shapes, function(j){ if (shapes[users_with_direct_employees[j][0]] != current_shape){ shapes[users_with_direct_employees[j][0]].animate({ fill: "#555" }, 500); } }); }); }); but only the last touched shape does the animation. I'll make a js fiddel here in a bit fiddle: http://jsfiddle.net/G5mTx/1/ A: Assuming, the shapes array is an array of DOM elements, I think you can use something like this where you set up a hover event handler for each shape and then within each function passed to the hover event handler, you iterate over the shapes array and if it's not the one that you are hovering over, you do the animation. jQuery.each(shapes, function(i) { this.hover(function(event) { var self = this; jQuery.each(shapes, function(index, value) { if (value != self) { $(value).animate({fill: "#fff"}, 500); } }); }, function(event) { var self = this; jQuery.each(shapes, function(index, value) { if (value != self) { $(value).animate({fill: "#555"}, 500); } }); }); }); or it might be cleaner with a local function: jQuery.each(shapes, function(i) { function animateIfNotMe(me, fillValue) { jQuery.each(shapes, function(index, value) { if (value != me) { $(value).animate({fill: fillValue}, 500); } }); } this.hover(function(event) { animateIfNotMe(this, "#fff"); }, function(event) { animateIfNotMe(this, "#555"); }); }); EDIT: I see you've added actual code now to your question (since I wrote my answer) and shapes isn't an array of DOM objects (it would be nice if you had disclosed that originally) so obviously this code won't work exactly as it is, but hopefully you can get the idea from this code for how you can iterate over all the other shapes and just exclude the current one you are hovering on and you can then adapt it to your particular shapes data structure. A: You can use the method .not(): jQuery.each(shapes, function(i) { $(this).hover(function(event) { shapes.not($(this)).animate({
{ "language": "en", "url": "https://stackoverflow.com/questions/7531478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Issue with obtaining the value of the checked radio button in a group? Please take a look at my test page, my issue is to do with finding the value of the selected radio button in the "Select picture" group. On loading I have used the following code: var currentImageFile = $("input:radio[name=selectedImage]:checked").val(); which picks up the default image for the "Selected picture" div on the left. So far so good. Now the problem is when a "Select picture" radio button is subsequently clicked my event code: $("input:radio[name=selectedImage]").click(function() { currentImageFile = $(this).val(); alert($(this).val()); }); (the alert is for testing only) returns no value at all! The HTML is pretty straight forward: <li><div class="xmasImage rounded" rel="http://www.completeinsight.co/resources/xmasHR/56269.jpg"> <img class="rounded" src="http://www.completeinsight.co/resources/xmasLR/56269_p.jpg" width="65" height="65" border="0" alt="56269" /> <div class="imageSelect"><input type="radio" name="selectedImage" value="56269"> &nbsp;<label for="selectedImage">56269</label> </div> </div></li> I am missing the obvious?? A: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { var currentImageFile = ''; $('#ImageSelection').find("input:radio[name=selectedImage]").click(function () { currentImageFile = $(this).val(); alert($(this).val()); }); }); </script> </head> <body> <ul id="ImageSelection"> <li> <div class="xmasImage rounded" rel="http://www.completeinsight.co/resources/xmasHR/56269.jpg"> <img class="rounded" src="http://www.completeinsight.co/resources/xmasLR/56269_p.jpg" width="65" height="65" border="0" alt="56269" /> <div class="imageSelect"> <input type="radio" name="selectedImage" value="56269"> &nbsp;<label for="selectedImage">56269</label> </div> </div> </li> <li> <div class="xmasImage rounded" rel="http://www.completeinsight.co/resources/xmasHR/56270.jpg"> <img class="rounded" src="http://www.completeinsight.co/resources/xmasLR/56270_p.jpg" width="65" height="65" border="0" alt="56270" /> <div class="imageSelect"> <input type="radio" name="selectedImage" value="56270"> &nbsp;<label for="selectedImage">56270</label> </div> </div> </li> </ul> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7531483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Controlling the ShareThis javascript window opens I have just started using ShareThis Widget to help handle social media integration with one of our sites. While the functionality is great, I feel I lose a lot of the capabilities I have if I were to code each item by hand, such as the ability to control the size of the windows opened by clicking a 'share' functionality. While their site shows basic functions you can add to the buttons (url, etc) I am looking to customize the feel such that when a button is clicked, I can control the size of that window or even possibly open in an existing colorbox snippet. Has anybody had luck with this before? When I try to control via javascript function it just seems to get overwritten or ignored. A: You'd need to unbind their events and handle them all yourself. It probably isn't a good idea, as your code will be at the mercy of their implementation. A: I am not sure if your question is resolved, but you will need to add as following inside JS. popup: 'true' The same is on their Support Page
{ "language": "en", "url": "https://stackoverflow.com/questions/7531490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Isolating monkey patches in a ruby gem? I've noticed that a few ruby gems that I use ship with a folder named ext or core_ext which contains a set of monkey patches to the core library that is used in their code. However, when I require those gems I get those monkey patches as well. Is it possible for gem authors or for gem users to isolate those monkey patches such that they are only visible in the Modules that the gem defines/exports? A: It won't be possible until refinements are implemented, see Shugo Maeda's proposal.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Aligning divs center next to eachother with valign: top Take a look here http://www.basenharald.nl/3d. For the home part i put on some black borders so you can see what i mean. The problem: I need to position the 2 blocks (the "hey"block and the right part) next to each other in the center and position them individual from there on out. The logical thing to do is to use display: inline block. Now the problem is that it does not valign top, so i cannot position them with margins. Basically what i want to do is position the "hey"part slightly to the left and the "right"part slightly to the right and a tat downwards. What is the best way to do so? It needs to be centered all time cause of the perspective effect and resolutions. Hope i am clear enough, otherwise just ask. this is the css part i am talking about: #home-welkom { text-align:left; width: 465px; margin: 360px 400px 100px; 230px; margin: 0 auto; display: inline-block; color:#787778; font-size:11px; border:1px solid black; } #home-right { text-align:left; width: 330px; margin: 50px 0px 0 0; position: relative; margin: 0 auto; display: inline-block; border:1px solid black; } Also not that the margin property does not influence the divs at all A: You're going to have to rethink your design strategy. Here's a few pointers: * *Use divs instead of lists to layout your page (lists are good for menus, etc) *margins can only be used once per class *use div floats to position your divs side by side *store your javascripts externally this way your code will be cleaner Now for your question this is what you're looking for to position your elements: <div id="wrapper" style="position: relative; margin: 0 auto; width: 800px; text-align: left"> <div id="leftcol" style="float: left; width: 400px;">left column</div> <div id="rightcol" style="float: left; width: 400px;">right column</div> </div> Finally I would make sure and validate my code and you can do so here: http://validator.w3.org/ Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Show specific part of ListView Android I need a little help with getting the specific part of list view based on current time.I have a list view with times as string like : "09:30" - "10:00" - "10:45".I'm using digital clock to show the current time in one activity and I want to show specific part of that listview based on current time. Example : It's 10:30 and I want to show the list view items which are bigger than 10:30 like : 10:45, 10:55 and etc. Any suggestions how to do that? A: I'm not sure how you're maintaining your data. Suppose each item is in a Time object that implements the Comparable interface, and you have List<Time> with all your data. Also, assume that the ListView is populated with an ArrayAdapter backed by a Time[] which you build from your List<Time>. (In MVC terminology, the List<Time> would be your model, the ListView would be the view, and your Activity class would be the controller.) The following code could be used to populate the ListView with data: private void updateTimes(List<Time> list) { Time[] times = new Time[list.size()]; list.toArray(times); mListView = (ListView) findViewById(R.id.listview); mListView.setAdapter(new ArrayAdapter<Time>(this, R.layout.listitem, times)); } When you wanted to filter the list to only show times after 10:30 (or any other time), you could do this (suppose List<Time> mAllTimes is the master list of times, and the Time class has a constructor that takes a String): private void filterTime(String onOrAfter) { Time time = new Time(onOrAfter); List<Time> filtered = new ArrayList<Time>(); for (Time t : mAllTimes) { if (t.compareTo(time) >= 0) { filtered.add(t); } } updateTimes(filtered); } Calling filterTime("10:30") would limit the list to only times on or after 10:30. Calling updateTimes(mAllTimes) would show the complete, unfiltered list.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android Issue with Resource after upgrade. I have an app, and stupid me decided to change a resource in the file from being filename.bmp to being a png, and released an upgrade with this, I removed the .bmp from the APK and added the PNG, and placed it on the marketplace. Now, I have some users who are not able to run the app, it is failing with a file not found on the line referencing the resource name in the VIEW XML description. Now, it is only some users, not all.. but its still infuriating, when a suer upgrades, are the old APK files removed? IE is the old .BMP file gone? I have been unable to fully replicated the problem on my equipment, but I am working off the theory that the .BMP and the .PNG file are now both in the resource/drawable directory and the XML inflate is just getting confused. A: You will need to rename the files BMP and PNG to completely different names. This could cause confusion though. I would recommend using one file type for all applications. And it may be that some user's are not experiencing the issue is because of screen density. Make sure all of the resources use the same naming convention and are availible for each screen size. A: Rename the file to something completely different. A: Have you tried cleaning your project?
{ "language": "en", "url": "https://stackoverflow.com/questions/7531499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sorting Gridview breaks ModalPopUp in GridView I have a gridview that has linkbuttons that call modalpopups and textboxes with values. I am trying to implement sorting for the gridview, but the if(!ispostback) statement I need for sorting prevents the modalpopup from appearing. It also does not sort the textboxes in the gridview. Is there a way to implement sorting without using ispostback in the page_load? Here is the code for the modalpopup, gridview binding and sorting. protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { ViewState["sortOrder"] = ""; Bind_Gridview("", ""); loadModals(); } } protected void viewModal(object sender, EventArgs e) { ... mainPanel.Controls.Add(exstModal); mainPanel.Controls.Add(exstModalBox); exstModalBox.Show(); } protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) { Bind_Gridview(e.SortExpression, sortOrder); } public string sortOrder { get { if (ViewState["sortOrder"].ToString() == "desc") { ViewState["sortOrder"] = "asc"; } else { ViewState["sortOrder"] = "desc"; } return ViewState["sortOrder"].ToString(); } set { ViewState["sortOrder"] = value; } } protected void gv1_RowCommand(object sender, GridViewRowEventArgs e) { ... CheckBox cb = new CheckBox(); TextBox ca = new TextBox(); ca.Width = 20; TextBox cga = new TextBox(); cga.Width = 20; if (e.Row.RowType == DataControlRowType.DataRow) //Foreach row in gridview { while (dr1.Read()) { ca.Text = dr1["cyla"].ToString(); cga.Text = dr1["cga"].ToString(); checkText = dr1["completed"].ToString(); if (checkText == "True") { cb.Checked = true; } else { cb.Checked = false; } } ... dr1.Close(); conn1.Close(); e.Row.Cells[6].Controls.Add(ca); e.Row.Cells[8].Controls.Add(cga); e.Row.Cells[9].Controls.Add(cb); ... } A: A GridView has built-in sorting capabilities. Depending on the dataset you are using to populate the data, you likely don't need to manually handle anything manually, let alone with the ViewState. Check out the second example on this MSDN page and note that it never does anything manually with the ViewState... the OnSorting and OnSorted events are there just to display extra information or to impose requirements: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sorting.aspx If you post a bit more of your code (including your .aspx pages, the markup for the modal popups, and the code for the loadModals() function, we might be able to better help you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Selenium WebDriver Multi-Threading & Browser Hiding using Java I'm using the Java API of the Selenium WebDriver: * *Is it possible to create multiple instances of the Selenium WebDriver from different threads simultaneously without conflict? *How do I change the path of the firefox installation directory that WebDriver uses if I installed firefox in a different directory? *How can I hide all the instances of the browsers(e.g firefox) that those threads started? Thank you. A: I can give you an answer to your first question. Yes, you can run multiple driver instances simultaneously. However it is not recommended to run more than 5 or so instances at once in a single selenium server. Selenium Grid was designed specifically for this (it is bundled with the Selenium Server).
{ "language": "en", "url": "https://stackoverflow.com/questions/7531507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to mark JTable cell input as invalid? If I take a JTable and specify a column's classtype on it's model as follows: DefaultTableModel model = new DefaultTableModel(columnNames, 100) { @Override public Class<?> getColumnClass(int columnIndex) { return Integer.class; }}; Then whenever a user tries to enter a double value into the table, Swing automatically rejects the input and sets the cell's outline to red. I want the same effect to occur when someone enters a 'negative or 0' input to the cell. I've got this: @Override public void setValueAt(Object val, int rowIndex, int columnIndex) { if (val instanceof Number && ((Number) val).doubleValue() > 0) { super.setValueAt(val, rowIndex, columnIndex); } } } This prevents the cell from accepting any non-positive values, but it doesn't set the color to red and leave the cell as editable. I tried looking into how JTable's doing the rejection by default, but I can't seem to find it. How can I make it reject the non-positive input the same way it rejects the non-Integer input? A: I figured it out. Override the DefaultCellEditor and return false / set the border to red if the number given is not positive. Unfortunately, since JTable.GenericEditor is static w/ default scope, I'm unable to override the GenericEditor to provide this functionality and have to re-implement it w/ a few tweaks, unless someone has a better way of doing this, which I'd like to hear. @SuppressWarnings("serial") class PositiveNumericCellEditor extends DefaultCellEditor { Class[] argTypes = new Class[]{String.class}; java.lang.reflect.Constructor constructor; Object value; public PositiveNumericCellEditor() { super(new JTextField()); getComponent().setName("Table.editor"); ((JTextField)getComponent()).setHorizontalAlignment(JTextField.RIGHT); } public boolean stopCellEditing() { String s = (String)super.getCellEditorValue(); if ("".equals(s)) { if (constructor.getDeclaringClass() == String.class) { value = s; } super.stopCellEditing(); } try { value = constructor.newInstance(new Object[]{s}); if (value instanceof Number && ((Number) value).doubleValue() > 0) { return super.stopCellEditing(); } else { throw new RuntimeException("Input must be a positive number."); } } catch (Exception e) { ((JComponent)getComponent()).setBorder(new LineBorder(Color.red)); return false; } } public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { this.value = null; ((JComponent)getComponent()).setBorder(new LineBorder(Color.black)); try { Class type = table.getColumnClass(column); if (type == Object.class) { type = String.class; } constructor = type.getConstructor(argTypes); } catch (Exception e) { return null; } return super.getTableCellEditorComponent(table, value, isSelected, row, column); } public Object getCellEditorValue() { return value; } } A: This code is a small improvement of the accepted answer. If the user does not enter any value, clicking on another cell should allow him to select another cell. The accepted solution does not allow this. @Override public boolean stopCellEditing() { String text = field.getText(); if ("".equals(text)) { return super.stopCellEditing(); } try { int v = Integer.valueOf(text); if (v < 0) { throw new NumberFormatException(); } } catch (NumberFormatException e) { field.setBorder(redBorder); return false; } return super.stopCellEditing(); } This solution checks for empty text. In case of an empty text, we call the stopCellEditing() method. A: The private static class JTable.GenericEditor uses introspection to catch exceptions raised by constructing specific Number subclasses with invalid String values. If you don't need such generic behavior, consider creating PositiveIntegerCellEditor as a subclass of DefaultCellEditor. Your stopCellEditing() method would be correspondingly simpler. Addendum: Updated to use RIGHT alignment and common error code. Addendum: See also Using an Editor to Validate User-Entered Text. private static class PositiveIntegerCellEditor extends DefaultCellEditor { private static final Border red = new LineBorder(Color.red); private static final Border black = new LineBorder(Color.black); private JTextField textField; public PositiveIntegerCellEditor(JTextField textField) { super(textField); this.textField = textField; this.textField.setHorizontalAlignment(JTextField.RIGHT); } @Override public boolean stopCellEditing() { try { int v = Integer.valueOf(textField.getText()); if (v < 0) { throw new NumberFormatException(); } } catch (NumberFormatException e) { textField.setBorder(red); return false; } return super.stopCellEditing(); } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { textField.setBorder(black); return super.getTableCellEditorComponent( table, value, isSelected, row, column); } } A: So first I created an analogy to make this topic easier to be understood. We have a pen(editor). This pen will need some ink(The component that the editor use, an example of a component is JTextField,JComboBox and so on) to write. Then this is a special pen when we want to write something using the pen, we speak(typing behavior in the GUI) to tell it to write something(write in the model). Before writing it out, the program in this pen will evaluate whether the word is valid(which being set in stopCellEditing() method), then it writes the words out on paper(model). Would like to explain @trashgod's answer since I have spent 4 hours on the DefaultCellEditor Section. //first, we create a new class which inherit DefaultCellEditor private static class PositiveIntegerCellEditor extends DefaultCellEditor { //create 2 constant to be used when input is invalid and valid private static final Border red = new LineBorder(Color.red); private static final Border black = new LineBorder(Color.black); private JTextField textField; //construct a `PositiveIntegerCellEditor` object //which use JTextField when this constructor is called public PositiveIntegerCellEditor(JTextField textField) { super(textField); this.textField = textField; this.textField.setHorizontalAlignment(JTextField.RIGHT); } //basically stopCellEditing() being called to stop the editing mode //but here we override it so it will evaluate the input before //stop the editing mode @Override public boolean stopCellEditing() { try { int v = Integer.valueOf(textField.getText()); if (v < 0) { throw new NumberFormatException(); } } catch (NumberFormatException e) { textField.setBorder(red); return false; } //if no exception thrown,call the normal stopCellEditing() return super.stopCellEditing(); } //we override the getTableCellEditorComponent method so that //at the back end when getTableCellEditorComponent method is //called to render the input, //set the color of the border of the JTextField back to black @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { textField.setBorder(black); return super.getTableCellEditorComponent( table, value, isSelected, row, column); } } Lastly, use this line of code in your class that initialise JTable to set your DefaultCellEditor table.setDefaultEditor(Object.class,new PositiveIntegerCellEditor(new JTextField())); The Object.class means which type of column class you wish to apply the editor (Which part of paper you want to use that pen. It can be Integer.class,Double.class and other class). Then we pass new JTextField() in PositiveIntegerCellEditor() constructor(Decide which type of ink you wish to use). If anything that I misunderstood please tell me. Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7531513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Need help using python 2.7.1 to select and run various batch files based on user input all. I am trying to use python 2.7.1 to run batch files based on what a user enters at the input prompt. The problem I'm having is the batch files do not run. I have been able to get a specific batch file to run from python if it is called from main() but cannot get python to select the file based on the input value. My code is: from subprocess import Popen def results(): Popen("results.txt") selection() def buildinga(): Popen("5463.bat") results() def base(): Popen("base.bat") results() def selection(): print "This tool will check the device status for the specified building." print "Type 'exit' to quit the program." selection.c = input("Please enter the device number: ") if selection.c == "001": base() if selection.c == "5463": buildinga() if selection.c == "exit": exit() def main(): selection() main() The way I can run a single batch file is: from subprocess import Popen def batchwriter(): Popen("make.bat") def main(): batchwriter() main() This way does not allow me to select which batch file to run, only the one specified. Any help would be much appreciated. I tried to post this in comments but could not. raw_input is working. The batch file is being run and then the results file displays, however, errors are displayed, as well. The errors don't seem to affect functionality because the results are correct. I am getting the following output: This tool will check the device status for the specified building. Type 'exit' to quit the program. Please enter the device number: 5463 Traceback (most recent call last): File "M:\cstat\ct.py", line 37, in <module> main() File "M:\cstat\ct.py", line 34, in main selection() File "M:\cstat\ct.py", line 26, in selection buildinga() File "M:\cstat\ct.py", line 10, in buildinga results() File "M:\cstat\ct.py", line 5, in results Popen("results.txt") File "C:\Utilities\Python\lib\subprocess.py", line 672, in __init__ errread, errwrite) File "C:\Utilities\Python\lib\subprocess.py", line 882, in _execute_child startupinfo) WindowsError: [Error 2] The system cannot find the file specified M:\cstat>[ 12:11:36.63] 5463 is ONLINE A: Use raw_input istead of input. input converts numeric input to from string to integer. >>> input() 001 1 >>> raw_input() 001 '001'
{ "language": "en", "url": "https://stackoverflow.com/questions/7531514", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to have more than one string resource file in Android? I have my primary string resource file for android, and it is quite full (with no end in sight). So, I was hoping to do some house cleaning and move some string into their own resource file. Is this possible? I know that one can have something like string-en or string-de, but is it possible to maybe have a resource file such as string-errors? A: Apparently so. I just took a small app of mine, created a new XML file, values/labels.xml, and moved some of my string resources from values/strings.xml into it. I made no other changes to the app; it still worked fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: Localized website, 1 bug: postback event doesn't work I've almost finished localizing a major website in ASP.NET. I'm using the CurrentUICulture to influence my localization. All goes well, except for the situation where I have a postback event. If I trigger this postback event, from the page that had it's culture changed, the Postback event uses the OLD CurrentUICulture value. It DOES work correctly if I've visited some other pages in the website first. I use the correctly localized page to trigger this event, that's why I am sure the localization worked. Is the postback event on a different thread? Did I miss something? I can't post any code from the project. The only setting I use is Thread.CurrentUICulture within a static wrapper class to set and get my localization. The class only contains static properties. EDIT: We set the currentUIculture in the OnInit of the loading page. We maintain the ui culture by setting it each time from the Session. A: Instead of setting the culture in the page OnInit event, override the InitializeCulture event. Here's an example, in vb, but you get the idea. Protected Overrides Sub InitializeCulture() Dim locale As String = Request.QueryString("lc") If locale IsNot Nothing AndAlso locale = "fr-ca" Then Me._LocaleID = 3084 End If Dim culture As New System.Globalization.CultureInfo(Me._LocaleID) System.Threading.Thread.CurrentThread.CurrentCulture = culture System.Threading.Thread.CurrentThread.CurrentUICulture = culture End Sub A: I just realized I did not answer this question. It turns out that a postback (which finally redirects) to another domain, makes the session disappear (obviously, surely good to know anyway). We've used the httpCookie domain setting to always set all cookies to the main domain, so sessions are shared between the different subdomains (en.website.com and nl.website.com) .
{ "language": "en", "url": "https://stackoverflow.com/questions/7531524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Need to pull data from all files in a directory Possible Duplicate: Excel - VBA Question. Need to access data from all excel files in a directory without opening the files So I need to pull data from multiple files in a directory and paste it into one excel file without having to open the files. Someone was nice enough to provide me with code on how to do that for a single file, now I just need to figure out how to do this for all the files in the directory. This code is for a single cell and I need it for a range. That's not an issue but I just thought I'd mention it as well. Dim rngDestinationCell As Range Dim rngSourceCell As Range Dim xlsPath As String Dim xlsFilename As String Dim sourceSheetName As String Set rngDestinationCell = Cells(3,1) ' or Range("A3") Set rngSourceCell = Cells(3,1) xlsPath = "C:\MyPath" xlsFilename = "MyBook.xls" sourceSheetName = "Sheet1" rngDestinationCell.Formula = "=" _ & "'" & xlsPath & "\[" & xlsFilename & "]" & sourceSheetName & "'!" _ & rngSourceCell.Address So I'm assuming I have to do some sort of loop to run through all the files but I'm not sure how to do it. If someone can help me with this I'd really really appreciate it. A: * *You CAN do this in VBA. And, in this case, you arguably SHOULD. *750 (or even 1000) is NOT excessive. Stop worrying about false economies, per your previous post. *Your basic alogorithm is: 1) Identify the .xls(x) file(s) you need to read 2) Extract the information you need in a loop *There are many different ways to accomplish both 1) and 2). For example: Dim wbList() As String, wbCount As Integer, i As Integer FolderName = "C:\Foldername" ' create list of workbooks in foldername wbName = Dir(FolderName & "\" & "*.xls") While wbName "" -- get info, per any of the links you've already been given -- Wend A: While I think this post should have been finished in your first thread, you can use the code below which is derived from the earlier link I provided to consolidate row 2 of each sheet called "loging form" from a folder you can specify (change C:\temp to your path) The code looks at .xls so it will work on Excel 2003 files, or Excel 2007/10 files. Dir works on all versions. The code skips any workbooks that don't contain a sheet called "loging form" Lastly the returned rows are consolidated on a new sheet (as values) of the workbook that hosts the code, a new sheet is created each time the code runs Sub ConFiles() Dim Wbname As String Dim Wb As Workbook Dim ws As Worksheet Dim ws1 As Worksheet Dim lngCalc As Long Dim lngrow As Long With Application .ScreenUpdating = False .EnableEvents = False lngCalc = .CalculationState .Calculation = xlCalculationManual End With Set ws1 = ThisWorkbook.Sheets.Add 'change folder path here FolderName = "C:\temp" Wbname = Dir(FolderName & "\" & "*.xls*") 'ThisWorkbook.Sheets(1).UsedRange.ClearContents Do While Len(Wbname) > 0 Set Wb = Workbooks.Open(FolderName & "\" & Wbname) Set ws = Nothing On Error Resume Next 'change sheet name here Set ws = Wb.Sheets("loging form") On Error GoTo 0 If Not ws Is Nothing Then lngrow = lngrow + 1 ws.Rows(2).Copy ws1.Cells(lngrow, "A") End If Wb.Close False Wbname = Dir Loop With Application .ScreenUpdating = True .EnableEvents = True .Calculation = lngCalc End With End Sub A: You can do a file search like this: ' Find all .xls files in a directory Dim ff As FoundFiles With Application.FileSearch .LookIn = "C:\MyPath\" .FileType = msoFileTypeExcelWorkbooks .Execute Set ff = .FoundFiles End With ' ff is now a collection of full paths to all excel files in dir ' But you need the filename separate from the folder path... ' FileSystemObject is a convenient tool to manipulate filenames (and more...) ' Before using it, you need to set a reference to it: ' Tools > References > set tickmark next to Microsoft Scripting Runtime Dim FSO As Scripting.FileSystemObject Set FSO = New FileSystemObject Dim i As Integer For i = 1 To ff.Count xlsFilename = FSO.GetFileName(ff.Item(i)) ' Do your stuff here... Next i As an alternative to Application.FileSearch, you can try using the Dir function. Have a look at VBA help for Dir.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is older version of flex SDK really required? I am configuring one already done project on my system which uses old flex sdk. following is my POM <FLEX_HOME>${build.flex3sdk.path}</FLEX_HOME> <flash.player.version>10</flash.player.version> <flex.sdk.version>4.1.0.16248</flex.sdk.version> I have latest flex SDK the version for this flex is "Version 4.5.1 build 21328". I am getting compile time error. Does a flex Mojo is dependent on the version of flex SDK ? why even changing the above POM to following is not helping me resolve the error? <FLEX_HOME>${build.flex3sdk.path}</FLEX_HOME> <flash.player.version>10</flash.player.version> <flex.sdk.version>4.5.1.21328</flex.sdk.version> Where can I find old sdk Version 4.1.0.16248? Kind of stuck .. PLz help A: For downloading legacy versions, you can use the links provided in the below website: http://joshblog.net/2014/download-legacy-adobe-flex-sdk-versions/ HTH A: Adobe Open Source includes Flex down to version 3. http://opensource.adobe.com/wiki/display/flexsdk/Flex+SDK They do have Flex SDK version 4.1.0.X. If you unable to find the version you need, perhaps you could get someone to share it with you from the Adobe Flex SDK Forum: http://forums.adobe.com/community/opensource/flexsdk A: Adobe still maintains a list of downloadable archived Adobe AIR runtimes and SDKs for versions 1.5 through 3.5. When the SDK was made open source and Flex was moved from Adobe to the Apache foundation, the later version SDKs are now available on SourceForge at: * *http://sourceforge.net/adobe/flexsdk/wiki/Versions/ If you want to download Flex 4.1A (Build 4.1.0.16076A), that can be done at: * *http://sourceforge.net/adobe/flexsdk/wiki/Download%20Flex%204/ The version you are looking for (4.1.0.16248) doesn't seem to be there (nor elsewhere). You may just have to use what is available from them in that case. However, depending on what compiler error you are seeing, this may or may not be an issue with the Flex SDK.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531527", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Writing draggable elements with jQuery? How can you write on this draggable element? Means if I double click the dragging widget it then text starts to get edit and write text in it. http://jqueryui.com/demos/draggable/ A: Maybe you are looking for the plugin jEditable which does what you need i think. You could also try to combine both things
{ "language": "en", "url": "https://stackoverflow.com/questions/7531530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to add page number option in footer with DynamicJasper API? I am creating report with help of code: FastReportBuilder fr = new FastReportBuilder(); I want to add page number in footer of each page like. page 1/3 page 2/3 A: As documented in the HOW-TO something like this: FastReportBuilder fr = new FastReportBuilder(); fr.addAutoText( AutoText.AUTOTEXT_PAGE_X_SLASH_Y, AutoText.POSITION_FOOTER, AutoText.ALIGNMENT_LEFT )
{ "language": "en", "url": "https://stackoverflow.com/questions/7531535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Conditional where clause T-SQL I have a stored procedure that returns data. I need to change the where clause based on parameters passed in. For example, the parameters are: @Region NVARHCAR(15) @CountryCode NVARCHAR(2) @ProductA BIT @ProductB BIT @ProductC BIT If @Region is passed in, then the where should select by region, if @CountryCode is passed in then the where should select by country code. For the products, if any of them are set to true, the where should select the data for that project. So the statement could look like this if @Region is passed in and @ProductA and @ProductC are set to true: SELECT * FROM table WHERE Region = @Region AND (Product = 'ProductA' OR Product = 'ProductC') Alternatively, the product conditional could be an IN statement. If @CountryCode was passed in it would look as follows: SELECT * FROM table WHERE CountryCode = @CountryCode AND (Product = 'ProductA' OR Product = 'ProductC') It's even possible that @CountryCode and @Region could be passed in. Is there any way to do this with T-SQL and not dynamic SQL generated from the app? Thanks A: You don't need to build a dynamic SQL statement, you just need to check the values of your parameters. Here is how I commonly build SQL clauses to achieve this: WHERE ((@Region IS NULL) OR (Region = @Region)) AND ((@CountryCode IS NULL) OR (CountryCode = @CountryCode)) AND ((@ProductA = 0) OR (Product = 'ProductA')) AND ((@ProductB = 0) OR (Product = 'ProductB')) AND ((@ProductC = 0) OR (Product = 'ProductC')) If your SQL is built like this, then you are only filtering on the Region column when you pass in a value for the @Region parameter. The same is true for CountryCode. A: This isn't necessarily the cleanest approach, but would avoid anything dynamic: SELECT * FROM table WHERE CountryCode = isnull(@CountryCode, CountryCode) AND Region = isnull(@Region, Region) AND (Product = 'ProductA' OR Product = 'ProductC') A: I'd simplify and write a stored procedure for each case. Or at least add procedural logic: IF NOT @Region IS NULL .... and have separate queries that can optimize on their own merits. EDIT: A couple principles that I think apply: http://en.wikipedia.org/wiki/Coupling_%28computer_programming http://en.wikipedia.org/wiki/Single_responsibility_principle A: You can always build the SQL statement as a string using your conditions.. then simply execute the resulting statement string using sp_executesql (a command which basically executes a Transact-SQL statement or batch that can be reused many times, or one that has been built dynamically)... I understand you may not want build sql strings but it a solution. A: If anything, the most direct approach (not necessarily the most elegant) is to set a default value for each parameter that is not a valid parameter value and perform a conditional check on each of them to see if the value contained in each parameter is different from the default value. Here I am assuming that the null value will never passed in as a valid value. CREATE PROC sp_ProdInfo ( @Region NVARHCAR(15) = NULL, @CountryCode NVARCHAR(2) = NULL, @ProductA BIT, @ProductB BIT, @ProductC BIT ) AS BEGIN -- other statements IF NOT @Region IS NULL BEGIN SELECT * FROM table WHERE Region = @Region AND (Product = 'ProductA' OR Product = 'ProductC') END ELSE BEGIN IF NOT @Country IS NULL BEGIN SELECT * FROM table WHERE CountryCode = @CountryCode AND (Product = 'ProductA' OR Product = 'ProductC') END ELSE BEGIN PRINT 'Neither Country nor Region was passed in.' END -- end inner if END -- end outer if -- other statements END A: I would use a Common table Expression
{ "language": "en", "url": "https://stackoverflow.com/questions/7531539", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: php wiki parser for trac-style formatting I am creating a very simple cms for my site and rather than using html, I'd like to insert content in the same kind of wiki-format that's used by the Trac project. Do you know of any open-source php scripts/classes that I can grab and use for this? Note: I am not trying to create a wiki site. Just that formatting aspect - like how this stack exchange site accepts wiki mark-up and renders it nicely. A: After doing some more research, I think I've found it. The Forever For Now wiki-syntax-to-html parser is pretty much the same as the formatting on the Trac project. ~I have not looked at the code yet, but its pretty likely to be cool. (like Fonzie)~ Edit - I've, now, looked at the code and its beautiful and elegant and does the job. A: PHP Markdown might work for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using custom datatypes in Entity POCOs? I have a business object, say a User. A User has a PhoneNumber field, which is represented by a string. I, for reasons best left to me, have created a PhoneNumber class that has implicit to/from string operators. Do I have to do anything special to get the PhoneNumber written as a string to the database? Right now, Entity has decided to break my PhoneNumber class up into its constituent parts (AreaCode, Prefix, etc) and save those to the database individually. PhoneNumber is stored in a separate assembly. public class PhoneNumber : IEquatable<PhoneNumber>, IComparable<PhoneNumber> { public static implicit operator string (PhoneNumber ph) { return ph.ToString (); } public static implicit operator PhoneNumber (string number) { return Parse(number); } public static PhoneNumber Parse(string number) { // ... } public override string ToString () { // produce a Parse-compatible output } } public class User { public virtual int Id { get; set; } public virtual string FirstName { get; set; } public virtual PhoneNumber Phone { get; set; } } public class MyContext : DbContext { public DbSet<User> Users { get; set; } } A: The only way is a workaround like this: // You want to store in same table and not a navigation property, right? // Then you need [ComplexType] [ComplexType] public class PhoneNumber : IEquatable<PhoneNumber>, IComparable<PhoneNumber> { // ... public string FullNumber { get { return Prefix + "-" + AreaCode + " " + Number; // or whatever } set { AreaCode = ParseToAreaCode(value); // or so... Prefix = ParseToPrefix(value); // or so... Number = ParseToNumber(value); // or so... } } [NotMapped] public string AreaCode { get; set; } [NotMapped] public string Prefix { get; set; } [NotMapped] public string Number { get; set; } } This way you would get only a FullNumber column in the database. A: If the rest of your design allows it, you could leave the PhoneNumber class out of the mapping and let User handle a string representation of it, like: public class User { public virtual int Id { get; set; } public virtual string FirstName { get; set; } public virtual string PhoneNumber { get { return this.PhoneNumber.ToString(); } // TODO: check for null set { this.PhoneNumber = PhoneNumber.Parse(value); } } [NotMapped] public virtual PhoneNumber Phone { get; set; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7531545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Best practice for bringing together GWT source into a WAR using Maven I'm currently in the process of splitting our rather over grown project down into its consecutive parts. The intention is that each separation becomes its own Maven project. There will be a parent Maven project that's responsible for ensuring all the correct parts are compiled and global properties are shared. With this in mind, our GWT code will be self-contained within its own project, and will be compiled using the GWT Maven plugin. Another project will be responsible for creating the WAR file, probably using the Cargo plugin as it's likely we'll need to merge web.xml files. Here lies the question, how do I get the compiled GWT source from the one project, into the WAR file that'll be created by the another project? What further complicates matters, is that there'll be feature extensions provided by further projects which will also be in their own projects, and these to will have compiled GWT source that'll need to be included into the WAR. Has anyone had experience of this? Any pointers to online resources or best practices? Should I be looking to structure it differently? Thanks. A: We have a similar layout (with slightly over 20 Maven modules). The webapp itself is composed of 3 projects: shared, client and server. * *The shared module is a simple JAR with our RequestFactory interfaces and other code that's shared between the client and server. *The client module has packaging=jar so it's seen as a Java project in Eclipse, it runs the gwt-maven-plugin in the prepare-package phase, and we use the assembly plugin to package the JS code into a ZIP. The module depends on shared both without classifier and with classifier=sources. *The server module is the webapp, and it uses the ZIP of the client module as a war overlay. Ideally, the gwt-maven-plugin would provide a new packaging specific to GWT, and a specific goal to output it in the war, similar to the flexmojos; but the above is almost what I would personally call the "perfect project layout". EDIT: I'm working on Maven archetypes using a similar layout: https://github.com/tbroyer/gwt-maven-archetypes
{ "language": "en", "url": "https://stackoverflow.com/questions/7531547", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: jQuery - is there a way to re-use parameters to cut down on code duplication? Let's say I have some code like this: jQuery('#retouching-image-1').beforeAfter({ animateIntro: true, introDelay: 500 }); jQuery('#retouching-image-2').beforeAfter({ animateIntro: true, introDelay: 500 }); Rather than duplicating animateIntro: true, introDelay: 500 each time I need it, is it possible to put these values into some kind of re-useable variable? Thanks. A: Try the following var x = { animateIntro: true, introDelay: 500 }; jQuery('#retouching-image-1').beforeAfter(x); jQuery('#retouching-image-2').beforeAfter(x); Another, probably more re-usable option is to use a class instead of an id to tag these elements. Say you added the `retouchImage' class to every one of these items. Then you could simplify your code to the following jQuery('.retouchImage').beforeAfter({ animateIntro: true, introDelay: 500 }); A: function dostuff(element) { element.beforeAfter({ animateIntro: true, introDelay: 500 }); } jQuery(function() { dostuff(jQuery('#retouching-image-1,#retouching-image-2')); }); Create a function, or simply do this instead: jQuery('#retouching-image-1,#retouching-image-2').beforeAfter({ animateIntro: true, introDelay: 500 }); Although personally, I would create a class and do it this way: jQuery('.retouching-images').beforeAfter({ animateIntro: true, introDelay: 500 }); A: Look closer at the code -- the answer is in there. Those parameters are actually just an object (note the curly braces surrounding them)! That means you could do the following: var animationObj = {animateIntro: true, introDelay: 500}; jQuery('#retouching-image-1').beforeAfter(animationObj); jQuery('#retouching-image-2').beforeAfter(animationObj); A: Try this: options = { animateIntro: true, introDelay: 500 } jQuery('#retouching-image-1').beforeAfter(options); jQuery('#retouching-image-2').beforeAfter(options); Even better: jQuery('#retouching-image-1, #retouching-image-2').beforeAfter({ animateIntro: true, introDelay: 500 }); should probably work as well. A: You can do it in a loop like so, $.each(["#id1", "#id2"], function(_ id){ $(id).beh(); }); A: You could do: jQuery('#retouching-image-1, #retouching-image-2').beforeAfter({ animateIntro: true, introDelay: 500 }); or if you have more ids you could use the attribute starts with selector jQuery('img[id^=retouching-image-]').beforeAfter({ animateIntro: true, introDelay: 500 }); A: jQuery('#retouching-image-1,#retouching-image-2').beforeAfter({ animateIntro: true, introDelay: 500 }); That's the correct syntax. Alternative way :P
{ "language": "en", "url": "https://stackoverflow.com/questions/7531549", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to cast a LONG to a CString? I want to cast a long to a cstring. I've been struggling with this for a while and I've seen so many variants of solving this problem, more or less riddled with hassle and angst. I know the question seems subjective, but it really shouldn't be in my opinion. There must be a way considered to be the best when the circumstances involve MFC and the standard libs that come with those circumstances. I'm looking for a one-line solution that just works. Sort of like long.ToString() in C#. A: There are many ways to do this: CString str(""); long l(42); str.Format("%ld", l); // 1 char buff[3]; _ltoa_s(l, buff, 3, 10); // 2 str = buff; str = boost::lexical_cast<std::string>(l).c_str(); // 3 std::ostringstream oss; oss << l; // 4 str = oss.str().c_str(); // etc A: It's as simple as: long myLong=0; CString s; // Your one line solution is below s.Format("%ld",myLong);
{ "language": "en", "url": "https://stackoverflow.com/questions/7531556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Why does EventRecord.FormatDescription() return null? When using System.Diagnostics.Eventing.Reader.EventLogQuery to read events from the Windows Event Log, the EventRecord.FormatDescription() method sometimes returns null. Why is this? In the Event Viewer there are messages on the events which return null. A: This is due to a bug in the .NET framework. Basically what you need to do to work around this bug is to set the CurrentCulture to "en-US". Example: var beforeCulture = Thread.CurrentThread.CurrentCulture; try { Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); using (var session = new EventLogSession(ipOrAddress, userDomain, username, password, SessionAuthentication.Default)) { var query = new EventLogQuery("System", PathType.LogName, queryString) { ReverseDirection = true, Session = session }; using (var reader = new EventLogReader(query)) { for (var record = reader.ReadEvent(); record != null; record = reader.ReadEvent()) { // Read event records string message = record.FormatDescription(); } } } } finally { Thread.CurrentThread.CurrentCulture = beforeCulture; } This workaround is was very hard to find, so I thought I would document it a place where it will be indexed by Google. I found it in an old MS Connect case, but it has been closed with a status of "wont fix". UPDATE: The bug has been reported for .NET 4 as well and the status is "Sent to Engineering Team for consideration" and comment alluding that the bug might be fixed in the next major .NET framework release (v5). A: so i've been struggling with this for a few days too. I couldn't get it to work by changing the culture. In the end, i just used the raw data in the Properties property of the event record. The message data is in there, it's just not pretty. (just about good enough for my audit needs though :-))
{ "language": "en", "url": "https://stackoverflow.com/questions/7531557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Get Gem vendor files in asset pipeline path I have created a gem with a vendor directory containing stylesheets and javascripts from bootstrap-sass and bootstrap itself. The directory structure is bootstrap-sass-gem/vendor/assets/javascripts and bootstrap-sass-gem/vendor/assets/stylesheets I've required the gem in a test project but whenever I try to require something from that gem I receive a Sprockets::FileNotFound error. For instance, in application.css I added *= require bootstrap. bootstrap is located at bootstrap-sass-gem/vendor/assets/stylesheets/bootstrap.scss and so by my reckoning should be included in the asset pipeline. I'm running RVM Ruby 1.9.2 and Rails 3.1. Here's my config file: $:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "bootstrap-sass-gem/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "bootstrap-sass-gem" s.version = BootstrapSassGem::VERSION s.authors = ["James Smith"] s.email = ["James@smithware.co.uk"] s.homepage = "http://www.smithware.co.uk" s.summary = "The Bootstrap-sass project Gemified" s.description = "Description of BootstrapSassGem." s.files = Dir["{lib,vendor,rdoc}/**/*"] + Dir["*"] #s.test_files = Dir["test/**/*"] s.require_paths = ["lib/**/*"] # We are dependent on the asset pipeline in 3.1.0 s.add_dependency "rails", "~> 3.1.0" # s.add_development_dependency "" end A: The problem was with my require_paths variable. The correct setting should have been: s.require_paths = ["lib"] A: I had the same problem, I solved it adding a dummy engine. This way in rails 3.1 the assets path was added automatically to Rails.application.config.assets.paths. Since Rails 3.0, if you want a gem to automatically behave as an engine, you have to specify an Engine for it somewhere inside your plugin’s lib folder. A: i think the asset pipeline expects your files to be named like bootstrap.css.scss. and I'm not sure, but maybe you need to define a railtie for your gem for rails to find the vendored stylesheets
{ "language": "en", "url": "https://stackoverflow.com/questions/7531563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Ajax update for jQuery I've got some very large data tables and I'm trying to make an automatic updater with jQuery but it seems to make a lot of unnecessary databbase calls before it does the update. What I would like is to check just one variable "lastModified" and compare it to the column in the database that will change when the table changes. What I have works, but I'd like to reduce the traffic. Any ideas? function update(){ var turl = "tracking?objId="; $.ajax({ type: "GET", url: turl + source, success: function(data){ $("#summary").html(data) } }); } var holdTheInterval = setInterval(update, 60000); (this is the basic code that does a nice job updating) EDIT I've solved this problem by using a separate jsp page with only an input containing the lastModified date, and on the page with the data tables, I've put another lastModifed input. I run the update() on the new jsp page, then compare the inputs. If they're different, I run the full update. This process works much better A: Currently you're polling only once per 10 hours, so I doubt someone will notice this. I'd say you can remove this ajax polling to reduce chance of getting more traffic, in case customer keeps browser open A: How about writing a dedicated server side script that will only return the last Rev. No in the DB? You can then * *poll that script via AJAX every so often without causing an insane amount of traffic. *do if (local_rev !== remote_rev) { update(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7531565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java With SQL Mapper Ok this is what I'm trying to do. Let's say I have several views each view can have aliases and such like that and each view goes back to either another or view or a table. What I want to do is trace a specific field from it's view all the way down to the source. For example if I have this sql statement: replace view blah Select t.acct_nmbr as I_account, sum (t.num1+p.location) as location, from blahTable as t left outer join blahTable2 p on t.acct_nmbr=p.acct_nmbr; This is a very simple case but what I want it is if I say trace(i_account) I will get the following hierarchy: I_account --> blahTable ---> acct_nmbr Or if I want location I would get the following: location --> sum (t.num1+p.location)-->blahTable --> num1 ------------------------------------------------>blahTable2 --> location You can see that adding more and more it can get complicated to trace this especially if there is multiple joins and select and derived tables as well. I'm currently trying to code this from scratch but I wasn't sure if there was something out there already that does this. A: I think this is an interesting concept. Ordinarily, I'd probably try to walk this recursively through a tree structure (which is what this is). However, you're going to run into a couple of problems really quick; * *A view generally has the effect of hiding the implementation details from somebody who wants data from it. When your application code queries a view for data, it has no way to tell that no such table exists - from it's standpoint, the view is a base level table. For a number of reasons, this is usually the desired outcome (it's the database version of encapsulation). So unless your java code has access to the view creation scripts (or can somehow get the definition of the views), you will not be able to 'walk' the structure. *Aggregate functions are a potential source of trouble. You're going to have issues with any CASE statements that switch fields for evaluation. You haven't listed your RDBMS, but some of them support multiple columns in some aggregates (like DB2 does for MAX()). This is going to cause problems because your destination column is dependent on the data retrieved. *Any stored procedures have the potential to completely invalidate your results. It's perfectly valid for me to create a stored procedure that changes the tables it access based on the time of day (depending on use case, this might actually be necessary). Additionally, unless you have the source code, you may not be able to complete the walk. *There is a command set called Alias, which basically repoints where a table (or view reference) actually points. This will have the effect of changing what 'base' table you're looking at (from an SQL standpoint). Depending on how you're getting your data, your Java code may resolve the alias or not. In either case, an alias is usually temporary, which has the potential to 'expire' your results. So, in short, for anything like a real-world scenario, it's pretty much impossible... 5.How are you planning on handling recursive CTEs (I'm assuming teradata allows them)? This is something of a wierd subset of point 2; any fields in them either resolves to a 'base table' (what the optimizer sees as a table anyways), or a recursion towards the base table. You would need to design your program to detect recursion of this type, and deal with it appropriately. Unfortunately, you won't be able to rely on the terminating condition (evaluated per-line at runtime); thankfully, however, you won't have to deal with cyclical relationships.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Simple way to combine #define with key in [NSBundle mainBundle] In my iOS application I have two targets with their own .plist file: Production and Test. My app uses a bunch of different URLs which are either on the production or the test server. Hence, I have added a new key to my two plists like so: <!-- MyAppTest-Info.plist --> ... <key>MAServerURL</key> <string>http://test.myap.com</string> ... <!-- MyApp-Info.plist --> ... <key>MAServerURL</key> <string>http://myapp.com</string> ... So now in my Const.h instead of defining the specific urls #define IMAGEURL @"http://myapp.com/images/" and changing them when I want to switch the environment I now can do this: // Const.h #define SERVER_URL [[[NSBundle mainBundle] infoDictionary] objectForKey:@"MAServerURL"]; #define IMAGE_URL [NSString stringWithFormat:@"%@/images", SERVER_URL]; #define AUDIO_URL [NSString stringWithFormat:@"%@/audio", SERVER_URL]; #define FEEDBACK_URL [NSString stringWithFormat:@"%@/mail/feedback", SERVER_URL]; .... Theoretically this would work but for every access of the constant the bundle is accessed and syntactically it is also not really a beauty (due to the verbose concatenation in OBJ-C). Any ideas and suggestions are very welcome. A: extern is your friend... Try to learn about it. Basically, you declare a global variable in your header file, using the extern modifier, basically meaning it's value will be defined later, in another source file. So you can have: const.h extern NSString * kAudioURL; This just declares the variable, as a NSString object. All files including your const.h file will be able to see this variable, even if it's not actually defined. Then, you'll defined the variable in another (implementation) file. const.m NSString * kAudioURL = @"foo"; This way, the definition will be hidden, as it happens in an implementation file, but other files will have access to your variable, by including the header file. So you'll be able to assign the correct value once. Of course, in your example, you are using computed values. As the kAudioURL is global, you won't be able to write: NSString * kAudioURL = [ NSString stringWithFormat: @"%@/images", SERVER_URL ]; But you may set the initial value to nil, and use an initialization function, maybe called from your application's delegate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }