text
stringlengths
8
267k
meta
dict
Q: Zend Dojo Element Id missing I am creating a Zend Form using Dojo elements and I would like to layout the form elements using CSS. Unfortunatly the element is not being given an ID like all other elements in my form. Output <dt id="purchase_required-label"></dt> <dd><table id="widget_purchase_required" class="dijit dijitReset dijitInlineTable disabled dijitTextBox dijitTextBoxDisabled" cellspacing="0" cellpadding="0" wairole="presentation" dojoattachevent="onmouseenter:_onMouse,onmouseleave:_onMouse" name="purchase_required" style="display: -moz-inline-stack;" role="presentation" widgetid="purchase_required"></table></dd> <dt id="purchase_supplier_id-label"></dt> <dd id="purchase_supplier_id-element"></dd> Example Code $purchase_required = new Zend_Dojo_Form_Element_DateTextBox('purchase_required'); $purchase_required->setLabel('Required Date'); $purchase_required->setAttribs(array("dojoType"=>"dijit.form.DateTextBox")); $purchase_required->setRequired(TRUE); $purchase_required->addErrorMessage('Please enter date as YYYY-MM-DD'); $this->addElement($purchase_required); Is this a bug or am I missing something? A: It appears that id is removed from that element in Zend_Dojo_Form_Element_Dijit when it overrides loadDefaultDecorators. You could probably restore it by using something like what happens in Dijit's superclass: Zend_Form_Element: $getId = create_function('$decorator', 'return $decorator->getElement()->getId() . "-element";'); $purchase_required->addDecorator( 'HtmlTag', array( 'tag' => 'dd', 'id' => array('callback' => $getId) ) );
{ "language": "en", "url": "https://stackoverflow.com/questions/7610814", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Open Source Scripting Languages that work well with Microsoft SQL Server I have been using PHP for a number of years now and have found it to be (relatively) well documented, easy to work with, to setup and to use. One of its main advantages is its capablility of working, without many modifications, similarly on a Windows or *nix platforms. It also has good support for connecting to Microsoft SQL Servers, in particular 2005 + 2008 through the mssql module + ntwdblib.dll or FreeTDS. That being said, the more time I spend developing PHP, the more I feel the need to pick up another scripting language to broaden my skill set and to develop better web-based applications. Because of this I've spent some time exploring alternative scripting languages in an effort to evaluate their suitability. At present the biggest hurdle I have come accross is support provided by recent versions of the Open Source scripting languages, specifically: Python 3.2.2, Ruby 1.9.2, Node 0.5.7 for the Windows OS (WinXP in my case) and Microsoft SQL Server (2005 + 2008). My existing working environ necessitates the requirement for connecting to a MSSQL database. I'm looking for answers from developers who have experience working with either Python, Ruby or Node.js and using them to interacting with a MS SQL Server. What would be your recommended Open Source scripting language which has good support for MS SQL Server. Ideas welcome. -P. A: Both Ruby and Python should be able to connect to MS SQL databases. Python libraries: * *PyTDS *pymssql Ruby libraries: * *TinyTDS - doesn't seem to be DBI compliant, but there is an ActiveRecord adapter. A: Ruby on Rails / ActiveRecord has support for mssql, using the activerecord-sqlserver-adapter gem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610815", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is sparrow framework compatible with iOS 3.0? I am new to iOS development. I want to build a simple game with sparrow or cocos2d (whichever of these i find more useful). I want to know that whether sparrow framework is compatible with iOS 3.0. I wanted it so that the game also works on iPhone 1. I also want my game to work in iPAD. Lastly which one of these would be more useful to develop simple 2D games on iPhone- Cocos2D or Sparrow? A: Sparrow Framework has a System Requirement for at least iOS 3.0 which must mean it supports iOS 3.0 which works on the iPhone. It also says it runs on all hardware generations which includes the iPhone 1. Source: http://www.sparrow-framework.org/info/features/
{ "language": "en", "url": "https://stackoverflow.com/questions/7610816", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UITableViewController change navigation button I have several UITableViewControllers where I am trying to change the background image of the "back" button or navigation button (see image below). How is this possible? button http://casperslynge.dk/button Thank you. A: Just set the tintColor of the UINavigationBar. For more information, please refer to this link: tintColor in UINavigationBar Hope this helps. A: we can use tintcolor but in that only some default will be there we can use use those colors only toolbar.tintColor=[UIColor blackColor];
{ "language": "en", "url": "https://stackoverflow.com/questions/7610817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to Read a csv or text file and put into list I am new to android programming, I am trying to read a simple list , like a grocery list, from a text file (.txt) to put it into a list for an app I am making I was wondering how I would do this I or if anyone knows any tutorials for a simple tutorial. I am also working this through with fragments. A: Follow this link: OpenCSV I used it to create a CSV file in code, but it also allows parsing a file. But if you create the file manually anyway, why don't you use a string array and put it in your source-folder. Then add it to your listAdapter when you create the content for your list.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610819", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jquery ui - autocomplete - several parameters for input I wanted to do search the streets with autocomplete. Select Province, city, street. Has a problem that based on the selected region and fetch parameter passed to the search of the city in a region. Later, the street on the basis of the parameter state and city. Can someone explain what to change these relationships were maintained. At this moment I find work but without the dependencies. file index.php <script type="text/javascript"> $().ready(function() { $("#w1").autocomplete("get_w_list.php", { width: 260, matchContains: true, minChars: 3, selectFirst: false }); $("#m1").autocomplete("get_m_list.php", { width: 260, matchContains: true, minChars: 3, selectFirst: false }); $("#u1").autocomplete("get_u_list.php?", { width: 260, matchContains: true, minChars: 3, selectFirst: false }); }); </script> </head> <body> <div id="content"> <form action="" autocomplete="off"> <p> Województwo <label>:</label> <input type="text" name="w1" id="w1" /> </p> <p> Miasto <label>:</label> <input type="text" name="m1" id="m1" /> </p> <p> Ulica <label>:</label> <input type="text" name="u1" id="u1" /> </p> <input type="submit" value="Submit" /> </form> </div> file get_w_list.php <?php require_once "config.php"; $q = strtolower($_GET["q"]); if (!$q) return; $sql = "select DISTINCT woj from lb_mu where woj LIKE '%$q%'"; mysql_query('SET CHARSET utf8'); $rsd = mysql_query($sql); while($rs = mysql_fetch_array($rsd)) { $cname = $rs['woj']; echo "$cname\n"; } ?> file get_m_list.php <?php require_once "config.php"; $q = strtolower($_GET["q"]); if (!$q) return; $sql = "select DISTINCT miasto from lb_mu where miasto LIKE '%$q%'"; mysql_query('SET CHARSET utf8'); $rsd = mysql_query($sql); while($rs = mysql_fetch_array($rsd)) { $mmname = $rs['miasto']; echo "$mmname\n"; } ?> Please help me solve this problem. thx A: Andrew is right I would use the newer version of the plugin. From what I can tell in your code you are calling different methods based on what they are searching for. I'm not sure if this is necessary you can pass all the parameters in one method. Syntax is a little rough but hopefully you get the idea. var url = "get_list.php?w=" + $('#w1').val() + '&m=" + $('#m1').val(); $("#w1").autocomplete(url, { width: 260, matchContains: true, minChars: 3, selectFirst: false }); <?php require_once "config.php"; $m = strtolower($_GET["m"]); $w = strtolower($_GET["w"]); if m != "" $sql = "select DISTINCT woj from lb_mu where woj LIKE '%$q%'" else if w != "" $sql = "select DISTINCT miasto from lb_mu where miasto LIKE '%$q%'" else return } ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7610831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Viewing available methods In XCode, when I am about to write method call, pressing Esc shows all the available methods from that class and all it's superclasses. Is there a shortcut to show ONLY the methods defined in that class? A: I don't think so. But you can see the .h file of the class. Press command and click with mouse in the class name, or double click it and with left button mouse, click in Jump to Definition. This is the same than read the docs files :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7610833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Widget integrated going out of its own zone I got a main window (Item) with a 640*480 size. I integrated a custom widget defined in another qml file, its size is 100*100. This item contains a Pathview that only shows 3 items from a list containing a lot of items. The thing is that when I add my CustomPathView to my main window at coords (0, 0), the PathView goes to the bottom of my main window, displaying 7/8 items... (?!?) My CustomPathView.qml file starts with : Item { width: 100 height: 100 That's why I really don't understand why it is displaying 8 items... Did I do something wrong ? Do I have to precise to my CustomPathView that he can't go out of its zone (how ?) ? Thanks in advance for any help about it ! A: Just set the clip property to true.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610835", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JavaScript Future Date Failing Checking Date these dates fail What do I need to change? 20 Jan 2013 20 jan 2013 20 JAN 2013 2 Jan 2013 30 Jan 2013 20 feb 2013 20 jun 2013 Code: function ValidateFutureDate(alertstring,pCheckDate) { // Default Return Variable to return success. var returnSuccess = 1; // setup a temporary array. var temp = new Array(); // split the date into the array. temp = pCheckDate.split(' '); // Setup the Test Date var testDate = new Date ( temp[1]+" "+temp[0]+", "+temp[2] ); var testMonth=testDate.getMonth()+1; if (testMonth<10) { testMonth = "0"+testDate.getMonth(); } // This is the Date to test if it is a valid date. var testIsDate = ( testMonth+"/"+temp[0]+"/"+temp[2] ); // Is this a valid Date if(!(isDate(testIsDate))) { returnSuccess = 0; } else if // Check to see if this date is greater then today. (!(testDate.getTime() > (new Date().getTime()))) { //return Failure zero is a failure. returnSuccess = 0; alertstring = alertstring + 'Expiration must be in the future. \n'; } // Return the Success or Failure of the Date Format Validation return returnSuccess; } A: The following section of your code isn't quite right: var testDate = new Date ( temp[1]+" "+temp[0]+", "+temp[2] ); var testMonth=testDate.getMonth()+1; if (testMonth<10) { testMonth = "0"+testDate.getMonth(); // change this line } When you initialise testMonth you remember to add 1 because .getMonth() returns a zero-based month, but then inside your if test you use .getMonth() again without adding 1. You should change that to testMonth = "0" + testMonth;. (Also, not the problem, but when you create temp there is no point initialising it to a new array when on the next line you assign it to something else.) Sorry, I have to go so I don't have time to look for any other issues in your code. A: How your isDate looks? I've checked the following (with testMonth = "0" + testMonth change): document.write( ""+ValidateFutureDate("---","20 Jan 2013")); document.write( ""+ValidateFutureDate("---","20 jan 2013")); document.write( ""+ValidateFutureDate("---","20 JAN 2013")); document.write( ""+ValidateFutureDate("---","2 Jan 2013")); document.write( ""+ValidateFutureDate("---","30 Jan 2013")); document.write( ""+ValidateFutureDate("---","20 feb 2013")); document.write( ""+ValidateFutureDate("---","20 jun 2013")); with function isDate(date){ return true; } and it prints 1 seven times (Firefox/Opera).
{ "language": "en", "url": "https://stackoverflow.com/questions/7610845", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Animated Images in ImageView? Example Images Would implementing these into an android app as an ImageView be the same as implementing a regular image, or would problem, low performance occur since they are .GIFs? I am aware that .PNGs are the go to image for android so is it possible to create animated .PNG images, if not what is the best practice for including animated images? A: First, PNG's can't be animated. From bitmap formats, only GIF supports animation. Unfortunately Android doesn't support animated gifs. Read also this: Display Animated GIF You may use AnimationDrawable to display animated set of images. However, such storing of animation frame by frame is taking much more memory than typical animated gif. There's no easy solution for displaying animated gif on Android at present.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: unit test to verify that a repository loads an entity from the database correctly I have a simple standard repository that loads a composite entity from the database. It injects all dependencies it need to read the complete entity tree from a database through IDbConnection (wich gives the repository access to IDbCommand, IDbTransaction, IDataReader) that I could mock. public class SomeCompositionRootEntityRepository : IRepository<SomeCompositionRoot> { public RecipeRepository(IDbConnection connection) { ... } public void Add(SomeCompositionRootEntity item) { ... } public bool Remove(SomeCompositionRootEntity item) { ... } public void Update(SomeCompositionRootEntity item) { ... } public SomeCompositionRootEntity GetById(object id) { ... } public bool Contains(object id) { ... } } The question is how would I write unit test for this in a good way? If I want to test that the reposity has read the whole tree of objects and it has read it correcty, I would need to write a hughe mock that records and verifies the read of each and every property of each and every object in the tree. Is this really the way to go? Update: I think I need to refactor my repository to break the repository functionality and unit test into smaller units. How could this be done? I am sure I do not want to write unit test that involve reading and writing from and to an actual database. A: The question is: What functionality do you want to test? * *Do you want to test that your repository actually loads something? In this case I would write a few (!) tests that go through the database. *Or do you want to test the functionality inside the repository methods? In this case your mock approach would be appropriate. *Or do you want to make sure that the (trivial) methods of your repository aren't broken? In this case mocks and one test per method might be sufficient. Just ask yourself what the tests shall ensure and design them along this target! A: I think I understand your question so correct me if I'm wrong... This is a where you cross the line from unit to integration. The test makes sense (I've written these myself), but you're not really testing your repository, rather you're testing that your entity (SomeCompositionRoot) maps correctly. It isn't inserting/updating, but does involve a read to the database. Depending on what ORM you use, you can do this a million different ways and typically its fairly easy. ::EDIT:: like this for linq for example ... [TestMethod] public void ShouldMapBlahBlahCorrectly() { CheckBasicMapping<BlahBlah>(); } private T CheckBasicMapping<T>() where T : class { var target = _testContext.GetTable<T>().FirstOrDefault(); target.ShouldNotBeNull(); return target; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7610848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I change acceptance with decimal separator to . instead of , with input in Netbeans IDE 7.0.1 on Windows 7 x 64 english? How do I change acceptance with decimal separator to . instead of , with input in Netbeans IDE 7.0.1? This is within Netbeans itself like trying this --> System.out.println("Cost?: "); cost = keyboard.nextDouble(); If this is input with 37.5 following happens --> Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextDouble(Scanner.java:2387) at Lab3_ChangeMoney.main(CostProgram.java:47) Java Result: 1 But with input 37,5 its ok I tried via Control Panel, but not A: An instance of this class is capable of scanning numbers in the standard formats as well as in the formats of the scanner's locale. A scanner's initial locale is the value returned by the Locale.getDefault() method; it may be changed via the useLocale(java.util.Locale) method. So this could be fixed by setting the locale to Locale.US: keyboard.useLocale(Locale.US); Read more about localized numbers on the manual
{ "language": "en", "url": "https://stackoverflow.com/questions/7610849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to call native code which draw in WPF Image from C# code? I have a native library (no sources available) wrapped into C# code. The following C# declaration exists: [DllImport(DRIVER_DLL_NAME, CallingConvention = CallingConvention.Cdecl, EntryPoint = "RenderBitmap")] private static extern int RenderBitmap(int hWnd); I need to call this function from my WPF C# project. I have a working sample code for Windows forms: System.Windows.Forms.PictureBox DisplayWindow; ... RenderBitmap(DisplayWindow.Handle.ToInt32()); And I have not found how to do so with WPF System.Windows.Controls.Image instead of System.Windows.Forms.PictureBox - there is no Handle property or something similar. Moreover I found in "WPF and Win32 Interoperation" the following statement: "When you create a WPF Window, WPF creates a top-level HWND, and uses an HwndSource to put the Window and its WPF content inside the HWND. The rest of your WPF content in the application shares that singular HWND.". It seems that HWND handle does not exist at all for Image. How to call native code which draw in WPF Image from C# code? A: WPF Controls does not have handles like in WinForms. Only main window handle is accessible: For instance, in main window class (or use Application.Current.MainWindow): var handle = (new WindowInteropHelper(this)).Handle; var hwnd = HwndSource.FromHwnd(handle); So looks like you've to consider another approach instead of native calls. BTW, why you need such a low level drawing functionality? I just can assume that you simply want to reuse already implemented one for WinForms. Perhaps you can achieve the same using built in WPF features.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Handling VB.NET DataRow Input string was not in a correct format for a null value I am looping through the rows of a DataRowCollection and assigning the fields of each row to a variable. I always get "Input string was not in a correct format" no matter how I cast this. I just need gapCd to contain 0 if the field is null or the value otherwise. It seems the IsDbNull is not returning true properly. I've also tried DbNull.Value comparisons with no luck. Any help is much appreciated. Dim gapCd As Integer = IIf(IsDBNull(row("GAP_CD")), 0, row("GAP_CD")) A: Remember that as a value type, Integer is already initialized to zero. So try this: Dim gapCd As Integer If Not IsDBNull(row("GAP_CD")) Then gapCd = CInt(row("GAP_CD")) and if that doesn't work, it's time to try some logging: Dim gapCd As Integer Try If Not IsDBNull(row("GAP_CD")) Then gapCd = CInt(row("GAP_CD")) Catch Ex As Exception SomeLoggingFunction(row("GAP_CD").ToString()) End Try Saw this again today for some reason, and on the fresh read was clear to me that all you have to do is remove one "I" from your code to change the IIf() function to the If() operator and force short-circuiting evalutation: Dim gapCd As Integer = If(IsDBNull(row("GAP_CD")), 0, row("GAP_CD"))
{ "language": "en", "url": "https://stackoverflow.com/questions/7610861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why its returning an error? #include <stdio.h> int call() { extern int b; b=10; printf("%d",b); } int main () { int b=8; call(); return 0; } Why is throwing an error like these do I get the following linker error: /tmp/ccAsFhWX.o:meka.c:(.text+0x7): undefined reference to `_b' collect2: ld returned 1 exit status I wanted to change the b value in the other function using extern keyword but it gives me an error.am i right in doing so ? A: Declaring the extern int b declares it as.... extern. It must be defined elsewhere. If it isn't, drop the extern keyword? I think you wanted a global variable: #include <stdio.h> static int b; int call() { b=10; printf("%d",b); } int main () { b=8; call(); return 0; } If you declare the global b as extern you gain the possibility (and the duty) to define it elsewhere (perhaps in another translation unit (helpers.c) or a library (helpers.a) etc.) A: In the C programming language, an external variable is a variable defined outside any function block. Please read about extern variables (here, for example). Also, variables have scopes. For example, it can be a local variable, a global variable etc. You can read more about that here. So what you have done here is declared a function scope variable in function call () without defining it using the power of extern keyword. In other words, simply tells the compiler that variable already exists somewhere. On top of that, you declared and defined another function scope variable in function main (), which has the same name. It is important to understand that those variables are totally different. So at the end of day, when you link your program, the definition of the variable b for function call () is not found. You declared it but never defined, remember? Here are possible solutions. Do not declare multiple b variables as that was clearly not your intent. Stick with a single declaration and definition: #include <stdio.h> extern int b; void call() { b = 10; printf("%d\n",b); } int b = 8; int main () { call(); return 0; } But global variables are usually very bad - global scope makes them extremely pipeline unfriendly, introduce threading issues etc. So you must look into something like this: #include <stdio.h> void call (int *b) { printf ("%d\n", *b = 10); } int main () { int b = 8; call (&b); return 0; } I'd also recommend you read the following question and answers here. It explains a lot about extern variables in C. And by the way, you function call () is declared with int return type but returns nothing. Hope it helps! A: To change the "b" in main(), you must pass a pointer to "call" like call (&b) and then do void call (int *b) { *b = 10; printf("%d",*b); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7610862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: modifying least significant bits in double (Java and C++) How to set to zero N least significant bits of a double in Java and C++? In my computations, the "...002" in 1699.3000000000002, is caused by numerical error, so I would like to eliminate it. A: I'd guess that you are actually doing currency calculations. In which case using a binary data type like double is probably the root cause of your problems. Switch to a decimal type and you should be able to side-step such issues. A: In Java, 1e-12*Math.rint(1e12*x) will round a double and return a double as the result. In C++, you can write 1e-12*floor(1e12*x + 0.5). Note, however, that these behave differently if 1012x is exactly between two integers. The Java version will round towards an even number, whereas the C++ version will always round upwards.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to trigger an event after using event.preventDefault() I want to hold an event until I am ready to fire it e.g $('.button').live('click', function(e){ e.preventDefault(); // do lots of stuff e.run() //this proceeds with the normal event } Is there an equivalent to the run() function described above? A: A more recent version of the accepted answer. Brief version: $('#form').on('submit', function(e, options) { options = options || {}; if ( !options.lots_of_stuff_done ) { e.preventDefault(); $.ajax({ /* do lots of stuff */ }).then(function() { // retrigger the submit event with lots_of_stuff_done set to true $(e.currentTarget).trigger('submit', { 'lots_of_stuff_done': true }); }); } else { /* allow default behavior to happen */ } }); A good use case for something like this is where you may have some legacy form code that works, but you've been asked to enhance the form by adding something like email address validation before submitting the form. Instead of digging through the back-end form post code, you could write an API and then update your front-end code to hit that API first before allowing the form to do it's traditional POST. To do that, you can implement code similar to what I've written here: $('#signup_form').on('submit', function(e, options) { options = options || {}; if ( !options.email_check_complete ) { e.preventDefault(); // Prevent form from submitting. $.ajax({ url: '/api/check_email' type: 'get', contentType: 'application/json', data: { 'email_address': $('email').val() } }) .then(function() { // e.type === 'submit', if you want this to be more dynamic $(e.currentTarget).trigger(e.type, { 'email_check_complete': true }); }) .fail(function() { alert('Email address is not valid. Please fix and try again.'); }) } else { /** Do traditional <form> post. This code will be hit on the second pass through this handler because the 'email_check_complete' option was passed in with the event. */ $('#notifications').html('Saving your personal settings...').fadeIn(); } }); A: Just don't perform e.preventDefault();, or perform it conditionally. You certainly can't alter when the original event action occurs. If you want to "recreate" the original UI event some time later (say, in the callback for an AJAX request) then you'll just have to fake it some other way (like in vzwick's answer)... though I'd question the usability of such an approach. A: The approach I use is this: $('a').on('click', function(event){ if (yourCondition === true) { //Put here the condition you want event.preventDefault(); // Here triggering stops // Here you can put code relevant when event stops; return; } // Here your event works as expected and continue triggering // Here you can put code you want before triggering }); A: as long as "lots of stuff" isn't doing something asynchronous this is absolutely unneccessary - the event will call every handler on his way in sequence, so if theres a onklick-event on a parent-element this will fire after the onclik-event of the child has processed completely. javascript doesn't do some kind of "multithreading" here that makes "stopping" the event processing neccessary. conclusion: "pausing" an event just to resume it in the same handler doesn't make any sense. if "lots of stuff" is something asynchronous this also doesn't make sense as it prevents the asynchonous things to do what they should do (asynchonous stuff) and make them bahave like everything is in sequence (where we come back to my first paragraph) A: Another solution is to use window.setTimeout in the event listener and execute the code after the event's process has finished. Something like... window.setTimeout(function() { // do your thing }, 0); I use 0 for the period since I do not care about waiting. A: The accepted solution wont work in case you are working with an anchor tag. In this case you wont be able to click the link again after calling e.preventDefault(). Thats because the click event generated by jQuery is just layer on top of native browser events. So triggering a 'click' event on an anchor tag wont follow the link. Instead you could use a library like jquery-simulate that will allow you to launch native browser events. More details about this can be found in this link A: you can use it with Timer or without Timer. const form = document.querySelector('#form'); form.addEventListener('submit', (x) => { x.preventDefault() // Ajax or nay Code setTimeout(() => { x.target.submit(); }, 1000) }) A: You can do something like $(this).unbind('click').click(); A: Nope. Once the event has been canceled, it is canceled. You can re-fire the event later on though, using a flag to determine whether your custom code has already run or not - such as this (please ignore the blatant namespace pollution): var lots_of_stuff_already_done = false; $('.button').on('click', function(e) { if (lots_of_stuff_already_done) { lots_of_stuff_already_done = false; // reset flag return; // let the event bubble away } e.preventDefault(); // do lots of stuff lots_of_stuff_already_done = true; // set flag $(this).trigger('click'); }); A more generalized variant (with the added benefit of avoiding the global namespace pollution) could be: function onWithPrecondition(callback) { var isDone = false; return function(e) { if (isDone === true) { isDone = false; return; } e.preventDefault(); callback.apply(this, arguments); isDone = true; $(this).trigger(e.type); } } Usage: var someThingsThatNeedToBeDoneFirst = function() { /* ... */ } // do whatever you need $('.button').on('click', onWithPrecondition(someThingsThatNeedToBeDoneFirst)); Bonus super-minimalistic jQuery plugin with Promise support: (function( $ ) { $.fn.onButFirst = function(eventName, /* the name of the event to bind to, e.g. 'click' */ workToBeDoneFirst, /* callback that must complete before the event is re-fired */ workDoneCallback /* optional callback to execute before the event is left to bubble away */) { var isDone = false; this.on(eventName, function(e) { if (isDone === true) { isDone = false; workDoneCallback && workDoneCallback.apply(this, arguments); return; } e.preventDefault(); // capture target to re-fire event at var $target = $(this); // set up callback for when workToBeDoneFirst has completed var successfullyCompleted = function() { isDone = true; $target.trigger(e.type); }; // execute workToBeDoneFirst callback var workResult = workToBeDoneFirst.apply(this, arguments); // check if workToBeDoneFirst returned a promise if (workResult && $.isFunction(workResult.then)) { workResult.then(successfullyCompleted); } else { successfullyCompleted(); } }); return this; }; }(jQuery)); Usage: $('.button').onButFirst('click', function(){ console.log('doing lots of work!'); }, function(){ console.log('done lots of work!'); }); A: Override the property isDefaultPrevented like this: $('a').click(function(evt){ evt.preventDefault(); // in async handler (ajax/timer) do these actions: setTimeout(function(){ // override prevented flag to prevent jquery from discarding event evt.isDefaultPrevented = function(){ return false; } // retrigger with the exactly same event data $(this).trigger(evt); }, 1000); } IMHO, this is most complete way of retriggering the event with the exactly same data. A: A more recent answer skillfully uses jQuery.one() $('form').one('submit', function(e) { e.preventDefault(); // do your things ... // and when you done: $(this).submit(); }); https://stackoverflow.com/a/41440902/510905 A: It is possible to use currentTarget of the event. Example shows how to proceed with form submit. Likewise you could get function from onclick attribute etc. $('form').on('submit', function(event) { event.preventDefault(); // code event.currentTarget.submit(); }); A: I know this topic is old but I think I can contribute. You can trigger the default behavior of an event on a specific element any time in your handler function if you already know that behavior. For example, when you trigger the click event on the reset button, you actually call the reset function on the closest form as the default behavior. In your handler function, after using the preventDefault function, you can recall the default behavior by calling the reset function on the closest form anywhere in your handler code. A: If this example can help, adds a "custom confirm popin" on some links (I keep the code of "$.ui.Modal.confirm", it's just an exemple for the callback that executes the original action) : //Register "custom confirm popin" on click on specific links $(document).on( "click", "A.confirm", function(event){ //prevent default click action event.preventDefault(); //show "custom confirm popin" $.ui.Modal.confirm( //popin text "Do you confirm ?", //action on click 'ok' function() { //Unregister handler (prevent loop) $(document).off("click", "A.confirm"); //Do default click action $(event.target)[0].click(); } ); } ); A: If you add an event listener to a form and await its submission then after checking what you need to check you can call the submission of the form with .submit ie const checkoutForm = document.getElementById('checkout-form'); const cart = {}; if (checkoutForm) { checkoutForm.addEventListener('submit', e => { e.preventDefault(); if(JSON.stringify(cart) === '{}'){ console.log('YOUR CART IS EMPTY') alert('YOUR CART IS EMPTY'); return; } else{ checkoutForm.submit(); } }) } <form id="checkout-form" action="action-page" method="post"> <input type="text" name="name" /> <button>Submit</button> </form> With this you can solve the form submission issues like checking for the strength of the password and checking whether all fields needed have the correct data A: Here is my old idea of using preventDefault and trigger "click" inside. I just pass argument "prevent" to the function: $(document).on('click', '.attachments_all', function(e, prevent = true){ if(prevent){ e.preventDefault(); var button = $(this); var id = button.data('id'); $.ajax({ type: 'POST', url: window.location.protocol + '//' + window.location.host + path + '/attachments/attachments-in-order/' + id, dataType: 'json', success: function(data){ if(data.success && data.attachments){ button.trigger('click', false); } else { swal({ title: "Brak załączników!", text: "To zamówienie nie posiada żadnych załączników!", type: "error" }); return; } } }); } }); I hope someone will find it useful
{ "language": "en", "url": "https://stackoverflow.com/questions/7610871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "191" }
Q: Javascript autogenerating getters for corresponding property name issue Hi I do not understand behavior... var myObject = {}; for (prop in obj){ var fnName = "get" + prop; myObject[fnName] = function(){ return obj[prop]; }; } I have object "obj" containing properties which have objects assigned. For each property I want to create "get" + name of property function and assign it to "myObject". Everything is fine except that, when I call myObject.getXXXA(); myObject.getXXXB(); myObject.getXXXC(); I receive the same object for each "getXXX()" method. Returned object is the one which was iterated as last one in "for (prop in obj)" loop. It is like "prop" variable in function body "return obj[prop];" was changed for every already assigned function. Could someone explain me that behaviour please ? A: Be careful of defining closures inside a loop. The inner closure closes over the variable prop , not over its value. (Therefore all the props are always the same value, since they use the same variable. In the end props is the last object). Have a function maker function so you can create a new custom prop variable for each method. function make_getter(p){ return function(){ return obj[p]; }; } for(prop in obj){ myObjec['get' + prop] = make_getter(prop); } This problem also often happens when someone tries to use an i from the for(;;) loop in a closure.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Parse string using RegEx and C# I have the following Regular Expression- string s = "{\"data\": {\"words\": [{\"wordsText\": \"Three Elephants /d in the jungle\"}]}}"; string[] words = s.Split('\\',':','[',']','{','}','"'); foreach (string word in words) { Console.WriteLine(word); } Which outputs- data words wordsText Three Elephants /d in the jungle What is the best way to get rid of the first 3 lines in the output so that I only get the last line- Three Elephants /d in the jungle. I believe if I were to write out all text after "wordsText\": this could be a possible method, any help is much appreciated. A: You could use RegEx sure, but since that looks like JSON you would be better off using JSON.NET to parse that. JObject o = JObject.Parse(@"{ ""Stores"": [ ""Lambton Quay"", ""Willis Street"" ], ""Manufacturers"": [ { ""Name"": ""Acme Co"", ""Products"": [ { ""Name"": ""Anvil"", ""Price"": 50 } ] }, { ""Name"": ""Contoso"", ""Products"": [ { ""Name"": ""Elbow Grease"", ""Price"": 99.95 }, { ""Name"": ""Headlight Fluid"", ""Price"": 4 } ] } ] }"); string name = (string)o.SelectToken("Manufacturers[0].Name"); // Acme Co decimal productPrice = (decimal)o.SelectToken("Manufacturers[0].Products[0].Price"); // 50 string productName = (string)o.SelectToken("Manufacturers[1].Products[0].Name"); // Elbow Grease See: Json.Net Select Token This uses the JSON.NET Library. A: I would use the Regex in C# your expressions for that would be like this MatchCollection matchCtrls = Regex.Matches(pageText, @"Th(.*)e", RegexOptions.Singleline); If you don't know what the text is going to be specifically then probably something like this MatchCollection matchCtrls = Regex.Matches(pageText, @"": \(.*)\", RegexOptions.Singleline);
{ "language": "en", "url": "https://stackoverflow.com/questions/7610875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's the meaning of "Min xfer" and "throughput" in the output of IOzone I'm a new user of IOzone, when I run the IOzone with the command: ./iozone -i 0 -i 1 -t 2 -T, it generates the following result(partially): Command line used: ./iozone -i 0 -i 1 -t 2 -T Output is in Kbytes/sec Time Resolution = 0.000001 seconds. Processor cache size set to 1024 Kbytes. Processor cache line size set to 32 bytes. File stride size set to 17 * record size. Throughput test with 2 threads Each thread writes a 512 Kbyte file in 4 Kbyte records Children see throughput for 2 initial writers = 650943.69 KB/sec Parent sees throughput for 2 initial writers = 13090.24 KB/sec Min throughput per thread = 275299.72 KB/sec Max throughput per thread = 375643.97 KB/sec Avg throughput per thread = 325471.84 KB/sec Min xfer = 356.00 KB Children see throughput for 2 rewriters = 1375881.50 KB/sec Parent sees throughput for 2 rewriters = 10523.74 KB/sec Min throughput per thread = 1375881.50 KB/sec Max throughput per thread = 1375881.50 KB/sec Avg throughput per thread = 687940.75 KB/sec Min xfer = 512.00 KB Children see throughput for 2 readers = 2169601.25 KB/sec Parent sees throughput for 2 readers = 27753.94 KB/sec Min throughput per thread = 2169601.25 KB/sec Max throughput per thread = 2169601.25 KB/sec Avg throughput per thread = 1084800.62 KB/sec Min xfer = 512.00 KB Children see throughput for 2 re-readers = 2572435.25 KB/sec Parent sees throughput for 2 re-readers = 26311.78 KB/sec Min throughput per thread = 2572435.25 KB/sec Max throughput per thread = 2572435.25 KB/sec Avg throughput per thread = 1286217.62 KB/sec Min xfer = 512.00 KB iozone test complete. I get confused about meaning of "throughput" and "Min xfer", is there someone can help me? By the way, why the throughput seen from children and parent is different? Thanks! A: Min xfer refers to the smallest amount of data written at one time. "Each thread writes a 512 Kbyte file in 4 Kbyte records" So if the Min xfer was 512.00 KB it wrote the entire actual file to disk at once (grouped all the 4 Kbyte records together). Children and parent throughput are different due to OS I/O buffering. iozone doesn't force direct (non-buffered) read or writes with the throughput test. What you're really testing is your system's buffer cache + disk cache + disk speed combo.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What is the purpose of Dynamic Bean in ATG I've read documentation, but there is no definition of the main purpose of Dynamic Bean. I understand how to implement this but dont know why this approach so good. So could someone tell the situation when it's good to use Dynamic Bean? Thanks A: Dynamic beans typically allow you to get and set fields which may not be explicit members. The most direct comparison is a map - maps allow you to get and set fields without defining them beforehand. However, a dyanamic bean conforms to standard java idioms (getters/setters). Unlike a hashmap, however, dyanbeans can enforce constraints more readily (and they hide the underlying data structure implementation, so they can be lazy, or make data connections when being set, etc... ) . For example, you can easily add a getter or setter to your dynabean that is explicit, and the code would read very idiomatically and cleanly interact with other bean apis. public int getCost() { if(this.get("cost")==null) return -1; return Integer.parseInt(super.get("cost")); } A: The most useful part about dynamic beans in ATG is providing additional DynamicPropertyMapper classes for classes that aren't already covered by it. First, note that you can use the DynamicBeans.setPropertyValue(object, property, value) and DynamicBeans.getPropertyValue(object, property) static methods to set or get properties on an object that don't necessarily correspond with Java bean properties. If the object you're using isn't registered with dynamic beans, it'll try to use Java bean properties by default. Support is provided out of the box to do that with repository items (properties correspond to repository item properties; also applies to the Profile object, naturally), DynamoHttpServletRequest objects (correspond to servlet parameters), maps/dictionaries (correspond to keys), and DOM Node objects (correspond to element attributes followed by the getters/setters of Node). To add more classes to this, you need to create classes that extend DynamicPropertyMapper. For instance, suppose you want to make HttpSession objects work similarly using attributes with a fallback to the getters and setters of HttpSession. Then you'd implement the three methods from DynamicPropertyMapper, and the getBeanInfo(object) class can be easily implemented using DynamicBeans.getBeanInfo(object) if you don't have any custom BeanInfo or DynamicBeanInfo classes for the object you're implementing this for. Once you have a DynamicPropertyMapper, you can register it with DynamicBeans.registerPropertyMapper(mapper). Normally this would be put into a static initialization block for the class you're writing the property mapper for. However, if you're making a property mapper for another class out of your control (like HttpSession), you'll want to make a globally-scoped generic service that simply calls the register method in its doStartService(). Then you can add that service to your initial services.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610877", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: jQuery change text in link I have a simple question for jQuery... I have a table with a link like this <table> <tr> <td class="views-field"> <a href="ciao">201105</a> </td> </tr> </table> Now I would change the link's text from 201105 to 2011-05 (simple add a "-" after the first 4 characters) I tried substring but don't work... Help me!! A: This will translate all td.views-field links: $('td.views-field a').each(function () { var oldText = $(this).text(); $(this).text(oldText.substr(0,4) + '-' + oldText.substr(4)); }); A: Try the code below, that should work fine. var replaceElement = $("td.views-field a").first(); var oldDate = replaceElement.text(); var newDate = oldDate.substring(0, 4) + "-" + oldDate.substring(4,6); replaceElement.text(newDate); A: $("a").text($("a").text().substring(0,4)+"-"+$("a").text().substring(4,6) );
{ "language": "en", "url": "https://stackoverflow.com/questions/7610879", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Combining SVN repositories I have multiple svn repositories, that i'm trying to combine to one. I did a couple of svnadmin dump {old-repo} | svnadmin load --parent-dir {new-subfolder} {new-repo} runs to combine them all. However is there a way to point the working copies to the new revision? If I do a svn switch --relocate {old-repo} {new-repo} I get get the error: svn: The repository at '{new-repo}' has uuid '70567957-ca9a-40a3-95c2-c7c7f5304040', but the WC has 'e7f76c56-4d0d-472c-a1f0-6eac23a5d238' I don't think it is easy to an new clean checkout. Because most of the WC have some local changes (like DB credentials / user images). And one even has a (required) cache dir with millions image thumbnails, which take +/- 2 days to regenerate. Can I force svn to ignore the uuid, and just accept the new location? A: There is an answer in a new stack exchange site (Unix & Linux) titled svn switch --relocate: wrong uuid? that explains how to set the UUID of the new repository. That has the following consequences: * *You may only set 1 UUID, but you have n old repositories. You have to decide which one to use, and for this one, the change of UUID may work. *All other will have to a new checkout. Sorry, no complete solution, it seems. A: You can create patch files of your current working copies, then re-checkout and finally apply the patches. Create patch file: $> svn diff > ~/old_repo.patch Checkout: $> svn co {new_repo} Apply patch: $> cd new_repo $> patch -p0 -i ~/old_repo.patch
{ "language": "en", "url": "https://stackoverflow.com/questions/7610880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Making a program with singletons multithreaded C# I have written a program in C#. Now I finished all the functionality and it works. But only running with one thread. I'm doing a lot of calculation and sometimes loading about 300 MB or more of measurement files into the application. I now want to make the program multithreaded because the user experiance is really bad in times of intense processing or i/o operations. What is the best way to refactor the program, so that it can be made multithreaded without too much affort? I know this is stuff I should have thougth before. But I havn't. I used the singleton pattern for about 3 big and important modules which are involved in nearly every other functionality of the program. I used a more or less clean MVC (Model View Control) architecture. So I wonder if it is maybe possible to let the User Interface run in one thread and the rest of the application in another. If not, loading and parsing 300MB, creating objects will take about 3 minutes to finish. In this time the user gets no response from the GUI. :/ UPDATE: My singletons are used as a kind of storage. One singleton saves the objects of the parsed measurement files, while the other singleton saves the result. I have different calculations, which use the same measurementfiles and creating results which they want to save using the other singleton. This is one problem. The second is to keep the guy responsive to user action or at least avoid this warning that the window is not responding. Thank you all for all advices. I will try them. Sorry for the late answere. A: Generally, I avoid the singleton pattern because it creates a lot of issues down the road, particularly in testing. However, there is a fairly simple solution to making this work for multiple threads, if what you want is a singleton per thread. Put your singleton reference in a field (not a property) and decorate it with the ThreadStaticAttribute: public class MySingleton { [ThreadStatic] private static MySingletonClass _instance = new MySingletonClass(); public static MySingletonClass Instance { get { return _instance; } } } Now each thread will have its own instance of MySingleton. A: The easiest way is to move all calculations to one separate thread and update the GUI using Invoke/InvokeRequired. public partial class MyForm : Form { Thread _workerThread; public MyForm() { _workerThread = new Thread(Calculate); } public void StartCalc() { _workerThread.Start(); } public void Calculate() { //call singleton here } // true if user are allowed to change calc settings public bool CanUpdateSettings { get { return !_workerThread.IsAlive; } } } } In this way you have get a response GUI while the calculations are running. The application will be thread safe as long as you don't allow the user to make changes during a running calculation. Using several threads for doing the calculations is a much more complex story which we need more information for to give you a proper answer. A: You can use TPL You can make the loops with TPL parallel, and further more it is built-in with .NET 4.0 so that you don't have to change your program so much
{ "language": "en", "url": "https://stackoverflow.com/questions/7610881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: artifactory classifier metadata snapshot maven 3.0 My problem is "simple" but I didn´t found the solution until now: I have 2 projects. * *Project A built with a classifier (called dev or pro) with help of a specific profile *Project B with a dependency to A (using classifier dev or pro) *I execute install goal on A with a classifier (dev) *I re-execute install goal with another classifier (pro) Then I compile the B project (and i put the dependency to A, with classifier DEV) It works well. But when I do the same with artifactory (goal deploy) , it doesn´t work (and the repository is configured "unique") It doesn´t work because artifactory? maven dependency? is trying to download A with classifier dev AND latest timestamp, buildnumber of whatever. But this "logic" is wrong because the latest timestamp is valid for A classifier pro!!! I read the metadata.xml between local repository and artifactory repository. There are similar (but not exactly the same) What i´m wrong? Thanks guys! * *Maven version : 3.03 *Artifactory version : 2.3.4.1 A: This might be due to the fact that at the time of writing this answer, Artifactory generates Maven 2 type of metadata, which as opposed to the newer type generated by Maven 3, does not specify a separate "latest version" per classifier\type of Artifact. That is, while Maven 2 metadata specifies the latest build and known history: <?xml version="1.0" encoding="UTF-8"?> <metadata> <groupId>org.jfrog.test</groupId> <artifactId>multi1</artifactId> <version>2.1-SNAPSHOT</version> <versioning> <snapshot> <timestamp>20110928.112713</timestamp> <buildNumber>14</buildNumber> </snapshot> <lastUpdated>20110928112718</lastUpdated> </versioning> </metadata> Maven 3 specifies the latest build per artifact type and classifier: <?xml version="1.0" encoding="UTF-8"?> <metadata> <groupId>org.jfrog.test</groupId> <artifactId>multi1</artifactId> <version>2.1-SNAPSHOT</version> <versioning> <snapshot> <timestamp>20110928.112713</timestamp> <buildNumber>14</buildNumber> </snapshot> <lastUpdated>20110928112718</lastUpdated> <snapshotVersions> <snapshotVersion> <classifier>tests</classifier> <extension>jar</extension> <value>2.1-20110928.112713-14</value> <updated>20110928112713</updated> </snapshotVersion> <snapshotVersion> <extension>pom</extension> <value>2.1-20110928.112713-14</value> <updated>20110928112713</updated> </snapshotVersion> ... </snapshotVersions> </versioning> </metadata> Support for Maven 3 metadata generation is currently planned for Artifactory's next version (2.3.5). Until then I can only suggest that you produce both artifacts with different artifact IDs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: JavaScript date() Object returns NaN with getYear (and other) I am currently having some issues converting a string dateTime object in JavaScript I am assuming it is because my string cannot me used properly in a new Date() but I'm not sure that is the problem. My Input: "2011-09-29 14:58:12" My code: var date = "2011-09-29 14:58:12"; var added = new Date(date); var year = added.getYear(); However, my year var contains NaN. Same with getDay() or getMonth(). What is the problem? ps: I'm getting the date in it's format from a SQLite database. And I'm using Titanium Mobile, so javascript and SQLite are the only things involved A: You're relying on the Date constructor parsing an unsupported format. Until recently, there was no standard string format supported by the Date constructor. As of ECMAScript5, there is one (YYYY-MM-DDTHH:MM:SS, note the T rather than space), but it's only been specified for just under two years and naturally doesn't work in older browsers. For the time being, your best bet is to parse it yourself (you can find code in this question and its answers), or use something like DateJS, MomentJS, date-fns, etc. to parse it for you. A: The Date constructor will not parse a string for you. You'll need to use Date.parse to do that. Interestingly enough, Date.parse doesn't actually return a Date. Instead it returns a unix timestamp. You can then pass the unix timestamp into the Date constructor to get what you're looking for. var d = new Date(Date.parse("2011-09-29 14:58:12"));
{ "language": "en", "url": "https://stackoverflow.com/questions/7610886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How do I create a dynamic mouse cursor .NET without using interop? I have an application which I'm interested in eventually porting to mono so I'm trying to avoid using p/invoke's to accomplish this task. I would like to load a cursor dynamically, as in I have a Bitmap that is generated on the fly in the application. From what I can tell the safest way to do it without using p/invoke's is to create a .cur file which I can then load to a memory stream and use the Cursor(Stream) constructor. However I have no idea how to create a .cur file. I found this article on the Microsoft Knowledge Base which sort of explains the format, but I'm not sure how it can be used without the interop calls. How To Create an Alpha Blended Cursor or Icon in Windows XP Does anyone else have a managed solution I can use to accomplish this task? A: I was reference the post: How can i replace cursor with bitmap in winform You can create a Array of static cursor and use Timer to change it to make dynamic mouse cursor effect! Create static cursor from bitmap is so simply and without using interop: public partial class Form1 : Form { public Form1() { InitializeComponent(); Icon icon = this.Icon; Bitmap bmp = icon.ToBitmap(); Cursor cur = new Cursor(bmp.GetHicon()); this.Cursor = cur; } } A: Here's an example in VB.NET of creating a bitmap on the fly and turning it into a cursor. Not sure who this will help 7+ years on, but here goes: Private Function GetCircleCursor(iDiameter As Integer) As Cursor Dim oBitmap As Bitmap = New Bitmap(Convert.ToInt32(iDiameter), Convert.ToInt32(iDiameter), System.Drawing.Imaging.PixelFormat.Format32bppArgb) Using g As System.Drawing.Graphics = Graphics.FromImage(oBitmap) g.Clear(Color.Transparent) g.DrawEllipse(New System.Drawing.Pen(Color.White, 3), New Rectangle(0, 0, iDiameter, iDiameter)) g.DrawEllipse(New System.Drawing.Pen(Color.Black, 1), New Rectangle(0, 0, iDiameter, iDiameter)) End Using Return New Cursor(oBitmap.GetHicon) End Function A: The code below creates a stream filled with data in .cur format, which I succesfully tested in Ubuntu with Mono. However .NET without using Win32 API only supports black and white colors in custom cursor: The Cursor class does not support animated cursors (.ani files) or cursors with colors other than black and white. Therefore in Unix with Mono one is rewarded with a cursor which * *displays black and white colors only *has no semi-transparent pixels, only fully opaque / fully transparent ones ¯\_(ツ)_/¯ using System; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Windows.Forms; namespace StackoverflowExample { public static class CursorHelper { public static Cursor CreateCursor(Bitmap bmp, Point hotSpot) { // https://en.wikipedia.org/wiki/ICO_(file_format) var bmpData = bmp.LockBits(new Rectangle(default, bmp.Size), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); try { int numBytes = bmpData.Stride * bmpData.Height; var bgraValues = new byte[numBytes]; Marshal.Copy(bmpData.Scan0, bgraValues, 0, numBytes); int max = Math.Max(bmp.Width, bmp.Height); if (max > 256) throw new NotSupportedException(); byte iconSizeByte = _sizes.FirstOrDefault(s => s >= max); // 0 means 256 int iconSizeI = iconSizeByte == 0 ? 256 : iconSizeByte; const int bytesPerPixel = 4; const int bytesPerPixelSource = 4; byte[] emptyPixel = new byte[bytesPerPixel]; using (var stream = new MemoryStream()) using (var writer = new BinaryWriter(stream)) { writer.Write((ushort)0); // idReserved writer.Write((ushort)2); // idType, 1 = .ico 2 = .cur writer.Write((ushort)1); // idCount writer.Write(iconSizeByte); writer.Write(iconSizeByte); writer.Write((byte)0); // colorCount writer.Write((byte)0); // reserved writer.Write((ushort)hotSpot.X); writer.Write((ushort)hotSpot.Y); var pixelsCount = iconSizeI * iconSizeI; var xorLength = pixelsCount * bytesPerPixel; var andLength = pixelsCount / 8 * 2; writer.Write((uint)(40 + xorLength + andLength)); // sizeInBytes writer.Write((uint)stream.Position + sizeof(uint)); // fileOffset = 22 = 0x16 writer.Write(40u); // cursorInfoHeader.biSize writer.Write((int)iconSizeI); // cursorInfoHeader.biWidth writer.Write((int)iconSizeI * 2); // cursorInfoHeader.biHeight writer.Write((ushort)1); // cursorInfoHeader.biPlanes writer.Write((ushort)(8 * bytesPerPixel)); // cursorInfoHeader.biBitCount writer.Write(0u); // cursorInfoHeader.biCompression writer.Write(0u); // cursorInfoHeader.biSizeImage writer.Write(0); // cursorInfoHeader.biXPelsPerMeter; writer.Write(0); // cursorInfoHeader.biYPelsPerMeter; writer.Write(0u); // cursorInfoHeader.biClrUsed = binaryReader2.ReadUInt32(); writer.Write(0u); // cursorInfoHeader.biClrImportant = binaryReader2.ReadUInt32(); using (var andMask = new MemoryStream(andLength)) { byte def = 255; for (int j = 0; j < iconSizeI; j++) { int y = iconSizeI - 1 - j; byte curByte = def; for (int i = 0; i < iconSizeI; i++) { var bitIndex = 7 - i % 8; if (i < bmp.Width && y < bmp.Height) { var p = y * bmpData.Stride + i * bytesPerPixelSource; stream.Write(bgraValues, p, bytesPerPixel); if (bgraValues[p + 3] > 0) curByte = (byte)(curByte & ~(1 << bitIndex)); } else stream.Write(emptyPixel, 0, emptyPixel.Length); if (bitIndex == 0) { andMask.WriteByte(curByte); curByte = def; } } } for (int j = 0; j < iconSizeI; j++) for (int b = 0; b < iconSizeI / 8; b++) andMask.WriteByte(def); andMask.Seek(0, SeekOrigin.Begin); andMask.CopyTo(stream); } stream.Seek(0, SeekOrigin.Begin); // debug // File.WriteAllBytes("/home/kolia/Documents/stream", stream.ToArray()); // stream.Seek(0, SeekOrigin.Begin); var cursor = new Cursor(stream); return cursor; } } finally { bmp.UnlockBits(bmpData); } } private static readonly byte[] _sizes = { 16, 32, 64, 128 }; } } A: Simple: YOU CAN NOT - the functionaltiy you ask for is not part of the .NET framework, so you need to go native. If you application needds porting to mono, isloate this code in one class so you can turn if off like with a compiler switch - not hard.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is it possible to unset a session variable with a specific and variable index? Let's say I have this specific session variable, $_SESSION['cart_'.$itemid]. Is it possible to sort all through session variable and find the once with index 'cart_'.$itemid and unset them? A: Sure. You could do something like foreach ($_SESSION as $key=>$val) { // Look for "cart_" at the front of the array key if (strpos($key, "cart_") === 0) { unset($_SESSION[$key]); } } Or the same thing using array_keys(): foreach (array_keys($_SESSION) as $key) { // Look for "cart_" at the front of the array key if (strpos($key, "cart_") === 0) { unset($_SESSION[$key]); } } Addendum If I may make a design suggestion though, if you have the ability to change this structure I would instead recommend storing these cart items as an array. The array then holds as values the item IDs contained inside. // Updated after comments.... $_SESSION['cart'] = array(); // Add to cart like this: $_SESSION['cart'][$itemId] = $new_quantity; This would make it easier to do things like: foreach ($_SESSION['cart'] as $item=>$quantity) { // process the cart } A: $matches = preg_grep('/^cart_/', array_keys($_SESSION)); foreach ($matches as $match) { unset($_SESSION[$match]); } A: There would only be one item stored in $SESSION['cart' . $itemId] unless you are varying the contents of $itemId. Anyway, sure you can unset that: if (isset($_SESSION['cart_' . $itemId])) { // don't need this if you are iterating through $_SESSION unset($_SESSION['cart_' . $itemId]); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7610890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery img.attr('width') returns zero.. IE7 Works in all browsers except <= IE7.. Check this example, http://jsfiddle.net/uVRbG/1 in iE7. When I remove the style display:none from the object however, it works correctly: http://jsfiddle.net/uVRbG/2/ I don't get it, I simply want the hardcoded value...it shouldn't matter whether or not the object is visible at the time.. Is there any other method to get the width and height? Note: I need the width and height at document.ready, I can't wait for all these images to load and then use img.width(); HTML: <div id="test" style="display:none"> <img src="http://neuro.amygdala.net/wp-content/uploads/2007/11/i-stress-test.gif" width="100" height="100" /> </div> <div id="result"></div> <div id="result2"></div> Javascript: $('#result').html($('#test img:first').attr('width')); $('#result2').html($('#test img:first')[0].getAttribute('width')); Thanks, Wesley A: You could just use jquery.hide() instead of display none, and store the width in a variable before it's hidden? A: Try to use .width() instead http://jsfiddle.net/uVRbG/3/ A: .width() might help you, but as to why IE7 has a problem with this, I think it might be to do with your selector. I've always had trouble with :first and :last pseudo-selectors in IE, it might just not be selecting the image. .attr() doesn't have any bugs with display:none afaik. Hope this helps EDIT: Try adding this to your fiddle: var imgWidth = $($('#test').html()).attr('width'); alert(imgWidth); Bit of a hacky workaround but might work. I've tried and can't test with IE7, it throws a script error when I load jsfiddle >:( EDIT: Last resort, a regex: var imgWidth = $('#test').html().search(/width=[\"\'][0-9]+/); alert(imgWidth); A: Try this workaround: use visibility:hidden;position:absolute instead of display:none. Then the image is loaded and positioned out of the way, so the width can be computed. When you want to show the image later, change it back to position:relative at the same time. http://jsfiddle.net/uVRbG/7/ A: You have to wait for the image to be loaded before you can get the width!
{ "language": "en", "url": "https://stackoverflow.com/questions/7610892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I return a class that inherits a generic list? I have this class: public class CampaignMaps : List<CampaignMap> { }; The CampaignMap object is my of my own and does not inherit anything. It has your standard properties and methods. I then have a CampaignMapAdapter object which acts as the data to my ObjectDatasource. It has one private property for the data: [DataObject(true)] public class CampaignMapAdapter { private Database db = new Database( ConfigurationManager.AppSettings["AppName"], ConfigurationManager.AppSettings["DBService"], ConfigurationManager.AppSettings["DBUser"]); private CampaignMaps _data { get { CampaignMaps maps = new CampaignMaps(); CampaignsAdapter adapter = new CampaignsAdapter(); db.Init(); db.AddParameter(null, null, ParameterDirection.ReturnValue, OracleType.Cursor); DataSet ds = db.ExecuteDataSet(PROC_GET_CAMPAIGN_MAPS); DataTable dt = ds.Tables[0]; foreach (DataRow row in dt.Rows) { CampaignMap campaignMap = new CampaignMap(); //populate the campaignMap object... maps.Add(campaignMap); } return maps; } set { _data = value; } } [DataObjectMethod(DataObjectMethodType.Select, true)] public CampaignMaps GetFiltered(bool hasErrors) { var selectQuery = from c in _data where c.HasError == hasErrors select c; _data = selectQuery; } } _data = selectQuery; is throwing the error: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'CampaignMaps'. An explicit conversion exists (are you missing a cast?) I suppose in plain English I want _data to always contain ALL my data elements, then calling a particular select should whittle them down as desired. How do I go about doing this? Thanks in advance. A: Well, you could do: CampaignMaps maps = new CampaignMaps(); maps.AddRange(selectQuery); _data = maps; That would get you the right data in the right types. However, I would strongly consider not deriving from List<T> to start with - it's almost never a good idea; prefer composition over inheritance unless you're really specializing the behaviour. I'd also say that mutating the current object in a method called GetFiltered violates the principle of least surprise. I would either change it to make it clearer that it's a mutation (e.g. "FilterByErrors") and give it a void return type, or just make it return the filtered list without mutating the current object. A: Why are you doing _data = selectQuery;? I would think your intention in the GetFiltered method would be something like: return new CampaignMaps(selectQuery); However, like Adam said, I would seriously consider why you are using a CampaignMaps class. If you want the public interface to only allow filtering by "HasErrors", make the GetFiltered method look like this: public IEnumerable<CampaignMap> GetFiltered(bool hasErrors) { return _data.Where(c => c.HasError == hasErrors); } I don't see any reason why you'd want to have this GetFiltered method in the first place. Why not expose the _data property as a get-only IEnumerable<CampaignMap> and then allow other objects to run Linq queries on it directly? Like this: public IEnumerable<CampaignMap> Data { get { return _data; } } Then somewhere else I can just write Data.Where(c => c.HasError == whatever).
{ "language": "en", "url": "https://stackoverflow.com/questions/7610893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to insert value into xml? I am really new to XML and JDOM so I have a noob question, sorry for that. I have a XML file and I want to insert value into it. My XML file is like that; <?xml version="1.0"?> <message> <header> <messageType> </messageType> <sendFrom> </sendFrom> <HostName> </HostName> <sendTo> </sendTo> <receiverName> </receiverName> <date> </date> </header> <body> </body> </message> So what I want is for example is to add value between <sendTo> </sendTo> and also I want to add <A> data </A> between <body> </body>. Can you please tell me how to do that ? Thanks a lot. A: If you use dom,you can do it as follows; DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(inputFile); Node messageType= doc.getElementsByTagName("messageType").item(0);//zero tells the order in the xml messageType.setTextContent("SMS"); A: http://www.cafeconleche.org/books/xmljava/chapters/ch14s04.html http://www.java2s.com/Code/Java/XML/MakeupandwriteanXMLdocumentusingDOM.htm A: I'd recommend using XStream for XML handling. Here, is the link to a 2 minute tutorial: http://x-stream.github.io/tutorial.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7610894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I use SQLite to read data from the Firefox cookies file? In my Firefox profile directory there is a cookies.sqlite file which holds the data for Firefox's cookies. I grabbed the Firefox SQLite Manager extension and loaded this file, which works, but how can I use plain query commands to read the cookies out of that file? This is what I've tried so far: $ sqlite3 cookies.sqlite sqlite> SELECT * FROM dbname.sqlite_master WHERE type='table'; SQL error: file is encrypted or is not a database I can't even list the tables, so I'm not able to start trying to list the cookies yet. If I can connect I'd like to be able to read and write data there, but I'm new to SQLite. A: I had the same problem trying to read the cookies.sqlite file on Mac OS 10.6.8 (Snow Leopard). I downloaded SQLite 3.7.10 from http://www.sqlite.org/download.html and then I could open the file. Here's a walkthrough of what I did... * *Download SQLite 3, go to your downloads folder and unzip the file so that you now have a new SQLite 3 sitting in your downloads folder. *Open up a new finder window, press CMD + Shift + G, in the 'go to' dialog that pops up enter ~/Library/Application Support/Firefox/Profiles and then press return. *Presuming you only have one Firefox profile, you should see a folder here called XXXXXXXX.default (where the XXX string will be some random characters). Open this folder, or if you have more than one profile, open the folder of the profile you are looking for. *Inside you will find the cookies.sqlite database file, you can use this here directly, but you might want to make a copy somewhere else to use without risk of messing up the one that Firefox uses. If you want to use the Firefox one directly then I think you have to quit Firefox first, otherwise it has a lock on the file. *Open a new terminal window, and drag the sqlite3 binary from the downloads folder to the terminal window, this should enter the path to sqlite3 onto the command line. *Now, drag the cookies.sqlite3 database (the original or your copy) to the terminal, press return in the terminal. If all goes well you should get the sqlite> command prompt. If you enter .tables you should see the table moz_cookies, which you can then query and investigate further. The following commands might help: .mode column .headers on select * from moz_cookies where domain = '.stackoverflow.com'; You should see all the values stored in your cookie for this site. If you want to update the existing sqlite3 on your Mac, I did sudo mv /usr/bin/sqlite3 /usr/bin/sqlite3.old (just in case of any future problems, I can move it back again) and then sudo mv ~/downloads/sqlite3 /usr/bin/sqlite3. A: I was able to open it with DBeaver, an open source universal database manager. A: Use sqlite3 sqlite3 file.sqlite Then use the below command to view the tables .tables
{ "language": "en", "url": "https://stackoverflow.com/questions/7610896", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Accent insensitive string comparison? Is there any way to do an accent insensitive string comparison? For example, é == e? I couldn't find any options to pass rangeOfString:options:. Any help is greatly appreciated. A: You want to pass the NSDiacriticInsensitiveSearch option to whichever method you use (e.g. compare:options: or rangeOfString:options:) A: If you also want a substring search and have an array of items you want to filter I recommend this: [self.objects filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id _Nullable evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) { MyClass *object = (MyClass *)evaluatedObject; if ([object.name localizedStandardContainsString:filterString]) return YES; return NO; }]];
{ "language": "en", "url": "https://stackoverflow.com/questions/7610898", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: How do I host a Django project's admin static files? I've heard I should use Apache for serving static files in a production environment. I'm having some problems understanding how I'm supposed to do that though. My project's static URL is /static/, and django.contrib.admin's static path is /static/admin/. Those are two completely separate directories on my server, and I can hardly do this: Alias /static /path/to/site.com/static Alias /static/admin /usr/local/.../django/contrib/admin/media Since they overlap. How am I supposed to do this? Do I really have to copy the contrib admin static folder into my own? A: Firstly, no-one says you have to serve your admin static files from the same base path as the others. You can set ADMIN_MEDIA_PREFIX to whatever you like. However, surely the easiest thing is just to add a symlink from your static folder to django/contrib/admin/media. A: Common solution is using /media/ for admin media static files, so it could be in settings.py ADMIN_MEDIA_PREFIX = '/media/' and in virtual host config: Alias /media /path/to/django/contrib/admin/media/ <Location /media> SetHandler None </Location> A: You can reverse the order of the Alias entries and Apache will parse it as intended: Alias /static/admin /usr/local/.../django/contrib/admin/media Alias /static /path/to/site.com/static This is because when Apache loads its configuration, it stores entries from a top down perspective. So it first tries to match /static/admin, then if the URI doesn't match, it then tries to match /static.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610910", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Increase shipping price and/or add line item for extra cost I'm implementing a custom FedEx integration solution for a Magento site. Part of this is to add a signature requirement checkbox in the onepage checkout, and add $3 if this is checked. Unfortunately it seems that the FedEx Rate Web Service doesn't take any parameter regarding signature requirements, so I must manually add this cost to the order. I was thinking about taking one of these two approaches, but I'm not sure will be best nor am I sure how to actually accomplish it: * *Add $3 to whatever price FedEx returns *Create a new line item for this Assuming that I have a handle on the $order, which solution would be best and how would I do it? The code should run inside an observer method which is called by the checkout_controller_onepage_save_shipping_method event, which is triggered immediately after $this->getOnepage()->saveShippingMethod($data);. This means I can't add $3 when the FedEx API returns a result, as I won't know if the checkbox is checked until afterwards. A: I came up with a solution; it's not the best but it works perfectly fine for me: * *Magento fires an event when saving the shipping info. I grab the POST data and save it in the db as well as the address object. *If the checkbox has changed, have it reload that same tab instead of moving onto the payment step. *In the shipping quote, check the address object for the checkbox value. If set, add a certain amount to the quote result.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AppEngine Python SDK for Windows fails to run apps with an EOFError I'm using Google AppEngine Python SDK for windows on a project, I get the following error when trying to launch an app. 2011-09-30 17:20:21 Running command: "['C:\\Python25\\pythonw.exe', 'C:\\Program Files\\Google\\google_appengine\\dev_appserver.py', '--admin_console_server=', '--port=8086', 'E:\\Programming\\Python\\notepyd']" WARNING 2011-09-30 11:51:10,549 urlfetch_stub.py:108] No ssl package found. urlfetch will not be able to validate SSL certificates. ERROR 2011-09-30 11:51:15,627 dev_appserver_main.py:644] <type 'exceptions.EOFError'>: 2011-09-30 17:21:15 (Process exited with code 1) This happened after a power failure. How do I fix it? A: Start Python and run this: >>> import tempfile >>> print tempfile.gettempdir() c:\users\..\appdata\local\temp Go to that directory and delete any files that start with dev_appserver. A: In your position, I'd be tempted to reinstall Python. You can install a more recent vintage Python (i.e., post-2.5) as long as you don't use any post-2.5 language features or packages. A: Open: c:\users\{your_pc_name}\appdata\local\temp Delete the directory named: appengine.{your_app_name}
{ "language": "en", "url": "https://stackoverflow.com/questions/7610917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Slider with ajax content I have a jquery slider, its like on default it is closed. So when the user try to open and ajax request is send and the data comes. My problem is each time the user closes and opens the ajax request is send. so how can i make the ajax call for the first time and if the user closes and opens the slider how to retain the data? A: A wild guess: (I am a Javascript beginner, so this probably is a dumb idea) You could add a class (lets call it '.clicked') to the "open link" in the ajax success function once the content has been loaded. And than you would of course need to wrap the whole ajax code in an "if" statement to check if the link has already been clicked once and only execute the code if it hasnt been clicked and if there is no ".clicked" class applied to it yet. I hope you get what I mean. A: You can set a variable, for example: var alreadySent = false; then in your ajax callback function you can change it to true (assuming you are using jQuery post): if (!alreadySent) { $.post("address", params, function(data) { // do something alreadySent = true; }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7610918", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What are the special things about tag Anchor tag is one of the very important element in HTML that is used for connectivity in web pages. There are many special things about this tag. One of the important things I came to know about today is the "rel" attribute in <a> tag, that is used to avoid search-engines to index a link. Can you guys please share any other interesting information about this tag? A: Here you go: http://www.w3schools.com/tags/tag_a.asp A: Lots of goodies here: http://dev.w3.org/html5/spec/Overview.html#the-a-element Interesting also is the type attribute. http://dev.w3.org/html5/spec/Overview.html#attr-hyperlink-type
{ "language": "en", "url": "https://stackoverflow.com/questions/7610919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: redirect nohup stdout and flush I want to use nohup and redirect stdout to a file but I do not need a archive I just want to be able to interactively view the current stdout. I am thinking I can redirect the stdout to a file to for it to be flushed after each output ??? nohup ruby myapp.rb > output.log & interactly view the output tail -F ./output.log A: You'll need to take a look at my answer to another question here: Linux non-blocking fifo (on demand logging). Assuming that by now you've got the ftee program ready, if you call your app like this: $ mkfifo /tmp/mylog $ nohup ruby myapp.rb 2>&1 | tee output.log | ftee /tmp/mylog & you'll get: * *full output log int the file output.log *current output of your app available on demand via the /tmp/mylog fifo Now if you want to just take a peek at your prog's latest output do: $ cat /tmp/mylog Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610922", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: FileOutputStream into FileInputStream What is the simplest way to convert a FileOutputStream into FileInputStream (a piece of code would be great)? A: I receive an FileOutputStream. What I want is read it. You certainly can't read from an OutputStream. I think you mean you want to read from the file being written to by the FileOutputStream. I don't think you can do that either. The FileOutputStream doesn't seem to keep a reference to the file being written to. What you need to do is discover what File or path (a String) was passed into the FileOutputStream and use that same File or String to create a new FileInputStream. A: If you mean that you want to be able to read the contents after writing (without flushing to disk), use a ByteArrayOutputStream and a ByteArrayInputStream. Once you're done writing to the ByteArrayOutputStream, you can get the underlying byte data and use a ByteArrayInputStream to read it back. ByteArrayOutputStream outStream = new ByteArrayOutputStream(); // do any output onto outStream you need ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray()); // you can read back the output with inStream now If you want a buffer (producer/consumer type problem), look into the Buffers provided with java's nio package. A: This might help you: http://ostermiller.org/convert_java_outputstream_inputstream.html This article mentions 3 possibilities: * *write the complete output into a byte array then read it again *use pipes *use a circular byte buffer (part of a library hosted on that page) Just for reference, doing it the other way round (input to output): A simple solution with Apache Commons IO would be: IOUtils.copyLarge(InputStream, OutputStream) or if you just want to copy a file: FileUtils.copyFile(inFile,outFile); If you don't want to use Apache Commons IO, here's what the copyLarge method does: public static long copyLarge(InputStream input, OutputStream output) throws IOException { byte[] buffer = new byte[4096]; long count = 0L; int n = 0; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); count += n; } return count; } A: If you can use @Thomas example given, otherwise you can do: import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; public class FileInputOutputExample { public static void main(String[] args) throws Exception { InputStream is = new FileInputStream("in.txt"); OutputStream os = new FileOutputStream("out.txt"); int c; while ((c = is.read()) != -1) { System.out.print((char) c); os.write(c); } is.close(); os.close(); } } example from java2s.com EDIT: As @Thomas deleted his answer, I will just add for reference Commons IO approach for handling this: IOUtils.copy(InputStream is, OutputStream os) A: What you want is a RandomAccessFile. This has the same basic methods of both the FileInputStream and a FileOutputStream. I know, you probably aren't given that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Photoshop psd file loses alpha channel in Maya Cg shader For one of our 3D artists I've ported and extended a shader from Unity3D to Maya. The shader in Unity3D uses PSD files as input for textures and makes use of the alpha channel of one of the textures as a heightmap. In Maya it seems as if the alpha channel is lost, because it's always 1. We tested this with PSD and PNG files. However, when using a TGA file, the heightmap could be used as intended and the shader functioned correctly. Below some Cg code to illustrate what I mean: float4 bottomColor = tex2D(RGBA_Texture2, IN.TexCoord.xy); float4 height = float4(1.0f) - bottomColor.aaaa; In the above code, bottomColor.aaaa is always (1.0, 1.0, 1.0, 1.0) when using a PSD texture, but not when using a TGA texture. Note: Converting all textures to TGA is (unfortunately) NOT an option. A: 1) Double click the psd file node in the hypershader 2) In the attribute editor below the path to the psd file you will see an option called "alpha to use". 3) Open the dropdown where it says "default" and choose "Alpha 1" or what ever you called it in photoshop.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Callable as the default argument to dict.get without it being called if the key exists I am trying to provide a function as the default argument for the dictionary's get function, like this def run(): print "RUNNING" test = {'store':1} test.get('store', run()) However, when this is run, it displays the following output: RUNNING 1 so my question is, as the title says, is there a way to provide a callable as the default value for the get method without it being called if the key exists? A: See the discussion in the answers and comments of dict.get() method returns a pointer. You have to break it into two steps. Your options are: * *Use a defaultdict with the callable if you always want that value as the default, and want to store it in the dict. *Use a conditional expression: item = test['store'] if 'store' in test else run() *Use try / except: try: item = test['store'] except KeyError: item = run() *Use get: item = test.get('store') if item is None: item = run() And variations on those themes. glglgl shows a way to subclass defaultdict, you can also just subclass dict for some situations: def run(): print "RUNNING" return 1 class dict_nokeyerror(dict): def __missing__(self, key): return run() test = dict_nokeyerror() print test['a'] # RUNNING # 1 Subclassing only really makes sense if you always want the dict to have some nonstandard behavior; if you generally want it to behave like a normal dict and just want a lazy get in one place, use one of my methods 2-4. A: I suppose you want to have the callable applied only if the key does not exist. There are several approaches to do so. One would be to use a defaultdict, which calls run() if key is missing. from collections import defaultdict def run(): print "RUNNING" test = {'store':1} test.get('store', run()) test = defaultdict(run, store=1) # provides a value for store test['store'] # gets 1 test['runthatstuff'] # gets None Another, rather ugly one, one would be to only save callables in the dict which return the apropriate value. test = {'store': lambda:1} test.get('store', run)() # -> 1 test.get('runrun', run)() # -> None, prints "RUNNING". If you want to have the return value depend on the missing key, you have to subclass defaultdict: class mydefaultdict(defaultdict): def __missing__(self, key): val = self[key] = self.default_factory(key) return val d = mydefaultdict(lambda k: k*k) d[10] # yields 100 @mydefaultdict # decorators are fine def d2(key): return -key d2[5] # yields -5 And if you want not to add this value to the dict for the next call, you have a def __missing__(self, key): return self.default_factory(key) instead which calls the default factory every time a key: value pair was not explicitly added. A: Another option, assuming you don't intend to store falsy values in your dictionary: test.get('store') or run() In python, the or operator does not evaluate arguments that are not needed (it short-circuits) If you do need to support falsy values, then you can use get_or_run(test, 'store', run) where: def get_or_run(d, k, f): sentinel = object() # guaranteed not to be in d v = d.get(k, sentinel) return f() if v is sentinel else v A: If you only know what the callable is likely to be at he get call site you could subclass dict something like this class MyDict(dict): def get_callable(self,key,func,*args,**kwargs): '''Like ordinary get but uses a callable to generate the default value''' if key not in self: val = func(*args,**kwargs) else: val = self[key] return val This can then be used like so:- >>> d = MyDict() >>> d.get_callable(1,complex,2,3) (2+3j) >>> d[1] = 2 >>> d.get_callable(1,complex,2,3) 2 >>> def run(): print "run" >>> repr(d.get_callable(1,run)) '2' >>> repr(d.get_callable(2,run)) run 'None' This is probably most useful when the callable is expensive to compute. A: I have a util directory in my project with qt.py, general.py, geom.py, etc. In general.py I have a bunch of python tools like the one you need: # Use whenever you need a lambda default def dictGet(dict_, key, default): if key not in dict_: return default() return dict_[key] Add *args, **kwargs if you want to support calling default more than once with differing args: def dictGet(dict_, key, default, *args, **kwargs): if key not in dict_: return default(*args, **kwargs) return dict_[key] A: Here's what I use: def lazy_get(d, k, f): return d[k] if k in d else f(k) The fallback function f takes the key as an argument, e.g. lazy_get({'a': 13}, 'a', lambda k: k) # --> 13 lazy_get({'a': 13}, 'b', lambda k: k) # --> 'b' You would obviously use a more meaningful fallback function, but this illustrates the flexibility of lazy_get. Here's what the function looks like with type annotation: from typing import Callable, Mapping, TypeVar K = TypeVar('K') V = TypeVar('V') def lazy_get(d: Mapping[K, V], k: K, f: Callable[[K], V]) -> V: return d[k] if k in d else f(k)
{ "language": "en", "url": "https://stackoverflow.com/questions/7610933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Activity and thread handling I want to make an http request (I use ksoap2) in the onCreate() during this time I want to have a ProgressDialog on screen to block the user. Once the request is done, I want to finish my onCreate using the elements that I retrieve from my http request. For now: I have a class which implements Runnable. I instantiate it in my onCreate. This class make the http request, during this time a ProgressDialog is on the screen. Once it's done the ProgressDialog is dismissed. But since it's not in the UI thread the following of the onCreate is executed before getting the result of the http request. I also tried, at first: in the onCreate I do a show() of my ProgressDialog then the http request then a dismiss() ProgressDialog and finally finish my onCreate with the result of my http request... it's ok except that the ProgressDialog is not showing this time. Sorry for the messy explanations, my english is really not helping either. Anyway, ideas ? Thanks. PS : BTW I know AsyncTask is better, it is what I usually use but having it with a ProgressDialog is not at all easy. My question is more : is there a way in an onCreate() to make an http request to get the value of an int. While this request is made: showing a ProgressDialog to block the user but also block the UI thread so that the end of the onCreate can use the value retrieved by the http request once it is complete. An ugly way would be a loop in the onCreate with a sleep waiting for the value to be retrieved... that's really ugly. A: Edit: I know you mentioned you didn't want to use AsyncTask due to the complexities of showing the ProgressDialog, but unless I'm missing something it should be as simple as the below. Alternatively, you could use a handler to fire the call back? I think you need some kind of handler to callback once the HTTP request is done, and then in the callback finish off your code. I also use ksoap2 for a web service call and show a ProgressDialog whilst it's called. Once the web server call is finished, it raises an event and I close the ProgressDialog. I'm not sure if this will help you, but I have the following (of course, there may be better ways, but this works for me), this way the ProgressDialog is called on the UI thread, an AsyncTask completes and calls the complete method (which returns the thread back to the UI) and I dismiss the dialog: // Notify user the web service is connecting final ProgressDialog dialog = ProgressDialog.show( Screen_GlobalLeaderboard.this, "Getting scores", "Please wait...", true); dialog.setCancelable(true); WebService ws = new WebService(this) { @Override public void webServiceCallComplete(boolean success, Object data, String errorMessage, WebMethods callingWebMethod) { dialog.dismiss(); // Your complete code here } }; ws.getTopLeaderboardResults(top, gameMode); Edit: I think what you're asking is onCreate (ran from the UI thread), you want to show a ProgressDialog and in the same method return a value from an HTTP request and once it completes, hide the dialog. You then say you've tried that and the ProgressDialog does not show. This is because you block the UI thread with the HTTP request. Providing you call the HTTP request from the onCreate method, you must run it in a separate thread (or as you done, implement Runnable) and a handler which will call the runnable with which you can then handle the return value. Put simply, you can't: Show ProgressDialog > Call HTTP request > Get value > Hide ProgressDialog without adding another thread for the HTTP request (or the ProgressDialog will not show) which in turn means your return HTTP request code must be outside of the calling onCreate method. A: In your oncreate show dialog first, then create a thread and do your http task there and once you are done with that call the handler from the thread and dismiss your dialog.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610945", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unresolved dependence org.jboss.arquillian:arquillian-bom in JBoss 7 Quickstarts I'm trying to get arquillian run with jboss 7. I have downloaded the Quickstart projects from JBoss site, at http://www.jboss.org/jbossas/downloads, but I'm having troubles in running the Arquillian tests in the kitchensink project. Maven is not able to find: org.jboss.arquillian:arquillian-bom:pom:1.0.0.CR1 When I run mvn clean test -Parq-jbossas-managed Maven allways fail to find the artifact: Downloading: http://repo1.maven.org/maven2/org/jboss/arquillian/arquillian-bom/1.0.0.CR1/arquillian-bom-1.0.0.CR1.pom [INFO] Unable to find resource 'org.jboss.arquillian:arquillian-bom:pom:1.0.0.CR1' in repository central (http://repo1.maven.org/maven2) [INFO] ------------------------------------------------------------------------ [ERROR] BUILD ERROR [INFO] ------------------------------------------------------------------------ [INFO] Error building POM (may not be this project's POM). Project ID: org.jboss.arquillian:arquillian-bom Reason: POM 'org.jboss.arquillian:arquillian-bom' not found in repository: Unable to download the artifact from any repository org.jboss.arquillian:arquillian-bom:pom:1.0.0.CR1 from the specified remote repositories: central (http://repo1.maven.org/maven2) for project org.jboss.arquillian:arquillian-bom I'm using Maven 3, though with maven 2 the result is the same. is Anyone running into this dependency problem? A: The dependency org.jboss.arquillian:arquillian-bom dependency is available in the JBoss Maven repository. It is preferable to add the "jboss-public" group of the JBoss Maven repository to your Maven settings.xml file so that you do not need to add this repository to every project POM. A: I have this dependency problem, too, although I've added the JBoss Maven repository like Vineet suggested. arquillian-parent-jetty-1.0.0.CR1.pom is correctly downloaded from the JBoss repository: Downloading: https://repository.jboss.org/nexus/content/groups/public-jboss/org/jboss/arquillian/container/arquillian-parent-jetty/1.0.0.CR1/arquillian-parent-jetty-1.0.0.CR1.pom But then Maven tries to download arquillian-bom from repository central, although it's available at https://repository.jboss.org/nexus/content/groups/public-jboss/org/jboss/arquillian/arquillian-bom/1.0.0.CR1/arquillian-bom-1.0.0.CR1.pom Downloading: http://repo1.maven.org/maven2/org/jboss/arquillian/arquillian-bom/1.0.0.CR1/arquillian-bom-1.0.0.CR1.pom [INFO] Unable to find resource 'org.jboss.arquillian:arquillian-bom:pom:1.0.0.CR1' in repository central (http://repo1.maven.org/maven2) As workaround I copied the arquillian-bom-1.0.0.CR1.pom to my local repository myself but then everyone else who wants to build my project has to do that too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: client PC information from web page asp.net I need to create an asp.net web page which shows the client system (PC) information when they access the page. I think i need to use some sort of plug in to get access to client system. But i dont know where to start the things here and how to integrate the plugin with my aspx page? So to summarize, from my computer if I go to this website and it tells me the memory on my computer, disk space, OS, etc. Any help will be much appreciated.. EDIT: Yes, i know its not going to happened with simple page. But what about the plugins? Cant i use any plugin which needs to get installed on browser and give me the info i want? Thank you. A: There is no way to obtain that information without prompting the user, and even then the information would be extremely limited. Allowing a web application to retrieve data from the client would be a serious breach of privacy. With all of the scrutiny surrounding privacy these days, that would be a very slippery slope. A: Not going to happen. At least in the honest way, or without the user consent. Browsers are not meant to give system and user info to any webpage, so even if you find a workaround that will be probably fixed in a next version of the browser (or OS). The top info you can get is probably the OS, the user-agent, and maybe the screen resolution. EDIT: One crazy idea, if you can't find an ActiveX/IE combination for that, and you really, really want to get that info and you know your users and the users trust you, you can build a web service that runs on the user side to give the info on your server request (this can help http://msdn.microsoft.com/en-us/library/Aa389273). Please note that this is not a basic task since you will have to provide security for the users in this web service.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610953", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: What is the effect of reverse proxy on a GWT application? I am deploying a GWT 2.4 app on Glassfish 3.0.1. I can easily access my application via http://host:PORT/appContext/ However, when I reverse proxy the application with Apache I get an exception with the following excerpt (from Glassfish logs): Exception while dispatching incoming RPC call com.google.gwt.user.client.rpc.SerializationException: Type 'com.ozdokmeci.basicgwtproject.shared.GroupData' was not assignable to 'com.google.gwt.user.client.rpc.IsSerializable' and did not have a custom field serializer. For security purposes, this type will not be serialized. Implementing IsSerializable solves the problem as advised by Chi in a related question. There are also other workarounds in the related question. My question is what is the underlying cause of this and how come two seemingly unrelated solutions (implementing a marker interface and extending a servlet class) solve this problem? Also are there any disadvantages to both of the methods mentioned in the related question? Note: The exception does not occur if the app is reached directly. Note2: Class related to the exception already implements the interface Serializable, which should be equivalent to the IsSerializable as far as GWT is concerned. A: I had the exact same issue and when I traced through the source code I found that the directory of GWT serialization files was not being found when reverse-proxying (I think because the directory was a relative path). This is why you are getting serialization exceptions even though you have implemented IsSerializable. My solution in the end was to move to restful JSON for my RPC. Using JSON will allow you to reverse proxy because it doesnt need to find these Serialization files. Edit If you want to still use GWT RPC though, I have an idea of how it's possible (though I havent implemented it myself). First, take a look at the GWT Help about these rpc files: https://developers.google.com/web-toolkit/doc/2.4/DevGuideCompilingAndDebugging#key_application_files You will notice it says: The serialization policy file must be accessible by your RPC RemoteServiceServlet via the ServletContext.getResource() call So you will need to override RemoteServiceServlet and re-point the location of the rpc (serialization policy) files. Here is one suggestion, taken from this site: http://code.google.com/p/google-web-toolkit/issues/detail?id=4817 public class MyRemoteServiceServlet extends RemoteServiceServlet { ... @Override protected SerializationPolicy doGetSerializationPolicy( HttpServletRequest request, String moduleBaseURL, String strongName) { //get the base url from the header instead of the body this way //apache reverse proxy with rewrite on the header can work String moduleBaseURLHdr = request.getHeader("X-GWT-Module-Base"); if(moduleBaseURLHdr != null){ moduleBaseURL = moduleBaseURLHdr; } return super.doGetSerializationPolicy(request, moduleBaseURL, strongName); } ... In apache config add: ProxyPass /app/ ajp://localhost:8009/App-0.0.1-SNAPSHOT/ <Location /app/> RequestHeader edit X-GWT-Module-Base ^(.*)/app/(.*)$ $1/App-0.0.1-SNAPSHOT/$2 </Location> Hopefully my suggestion above at least points someone in the right direction. Please let us know if someone implements this and it works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610969", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Should I use and add on to the existing denormalized DB structure, or create my own? We have a 3rd party software, and I have been asked to create an extension for it. The extension will deal with data that exists in the current software, and include some additional data. The existing data is extremely denormalized. Most of the data I will be working with, which is for about 4-5 different entities, exists in a single table. I will need to add additional fields to most of these entities. I see 2 ways of doing this: * *Create a new table for the new fields, that matches the existing table 1:1 and uses the same denormalized style they use Pros: It would fit in with the existing denormalized database structure, and be easy to create Cons: Very denormalized, and I'm a bit obsessed about normalizing my databases. The current table already has over 50 columns, and it should really be split up into 4-5 different tables. I also don't think I can use EF easily with the current database structure (my preferred way of working with the database) and would have to manually create data models in the code instead of using EF to generate them *Create a whole new set of tables and use triggers to synchronize the data between the tables Pros: Can create the tables the way I want, and can use EF to handle database operations, and to generate the data models for me Cons: Need to use Triggers to synchronize data with existing table Which do you think is the better idea? A: I think the answer is how to best utilize your time combined with how much control you have over the tables for now and in the future. Personally I would create an alternate table with some relationship. If you choose to modify the existing table you not only now have to regression test the app and test your new app but you stand the risk of future updates breaking both apps. So I say, work with what you can control. You're time will be more effectively used and you position yourself with less risk down the road. Smart for you and smart for business. Hope that helps. A: I think it depends on how much of an extension you're looking at. If you are adding a couple of bells and whistles to the existing interface, and especially if you aren't going to have to wrap the existing interface, then you might be better off to hold your nose and live with the ugly base data structure. It all comes down to which is a smaller pile of code to build and maintain: * *Extension code that is made ugly by the denormalized base + extended attributes - or - *Clean extension code + all of the ugly table synchronization trigger code. It seems to me that if the extension is really substantial, then 2 could turn out to be smaller than 1. However, if you're looking at just those few bells and whistles, then 1 is probably going to be a lot smaller than 2.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Automatic build with source control monitoring I am using SourceSafe 2005, and I have a project in VB.NET Framework 4. What I want is a way to automate the build process and hopefully integrate easy deployment. I'd like to be able to send an automated notification when a build is made that lists the comments of the SourceSafe check-in's in the body of the message. I've looked at a few options and some of them are confusing. I've seen it implemented with SVN, nAnt and CruiseControl, but it looks like it might take ages to set up being a novice of the aforementioned technologies. What would be the easiest way to set something like this up in your opinion? If I have to start using SVN for this, then that would also be a possibility. A: If you're looking for a simple build and maybe a deployment to the first environment, you should be able to use any number of tools including free ones like CC.Net and team level CI solutions like Sylvanaar mentioned. If the deployment gets trickier, my company's tools (urbancode.com) could be more appropriate as we focus pretty hard on the "what comes after the build" part of CI. As an aside, VSS is a pretty terrible place to store your source code (I've heard it called 'visual source shredder' by multiple clients). Microsoft's new TFS is better, as is Subversion (and many, many others). You do not need to switch source control to implement build and deploy. Many CI tools have VSS integrations (you can find a list here) but friends don't let friends use VSS. A: I recommend TeamCity It supports SourceSafe and building of SLN's or via MSBUILD.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Matplotlib inset polar plot I'm trying to inset a polar plot inside a normal x vs y plot in cartesian coordinate. I know that inset can be obtained through pylab.axes as illustrated in this example. But I do not know how to specify this is a polar plot, possibly without any grid. Any help is welcomed A: Here you have a working example. The main point is to specify a new, smaller axes for the second figure import numpy as np from matplotlib import pyplot as plt from scipy import randn, convolve #data t = np.arange(0.0, 20.0, 0.001) r = np.exp(-t[:1000]/0.05) x = randn(len(t)) s = convolve(x,r)[:len(x)]*0.001 theta = 2 * np.pi * t # fig = plt.figure(figsize=(7, 6)) #main plt.plot(t, s) plt.axis([0, 1, np.amin(s), 2.5*np.amax(s)]) plt.xlabel('xlabel') plt.ylabel('ylabel') #polar ax = fig.add_axes([0.2, 0.47, 0.30, 0.40], polar=True, axisbg='yellow') ax.plot(theta, t, color='blue', lw=3) ax.set_rmax(1.0) plt.grid(True) plt.show()
{ "language": "en", "url": "https://stackoverflow.com/questions/7610973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Detect distance of HTML element from to top and to left? I have a tag within a HTML5 document. How can I detect the distance with JavaScript from the top-left corner of the HTML page to the top left corner of the canvas tag? I need to be able to position dynamically generated html tags relative to the canvas. A: getBoundingClientRect() is your friend and is supported in recent-ish versions (Firefox 3, Safari 4, Chrome, Opera 9.5, IE 5) of all browsers. It will give you coordinates relative to the viewport rather than the page, however, so you need to add on the document's scroll amounts: function getPageTopLeft(el) { var rect = el.getBoundingClientRect(); var docEl = document.documentElement; return { left: rect.left + (window.pageXOffset || docEl.scrollLeft || 0), top: rect.top + (window.pageYOffset || docEl.scrollTop || 0) }; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7610974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: linked reports in sharepoint On sharepoint server we can publish out SSRS reports. And it is fine. We are moving our SSRS reports from reporting services to sharepoint. But I have some linked reports. After a little research, I've found that "linked reports are not supported". here Is there any way to implement "linked reports" on sharepoint. A: What do you want to hear... it is not supported by Microsoft. And when migrating reports to Reporting Services SharePoint integrated mode you will have several annoyances to deal with (this is one of them). Since the Reporting Services Instance is configured to run in SharePoint integrated mode you also won't have any luck running the report outside of SharePoint instead of nicely integrated, I reckon. Your only chance might be to set up another Reporting Service instance and have those reports with linked reports run off of that, it will be a hassle though - maybe you're better off re-designing your reports. A: Wrong. It's just called something different. Click on "View Properties", then in the ribbon "Manage Copies". You can do it in there. Below is a site that gives a visual. I hope this helps someone, because we'v struggled with it for 3 months and just now stumbled on how to do it. http://www.mssharepointtips.com/tip.asp?id=1127&page=2
{ "language": "en", "url": "https://stackoverflow.com/questions/7610975", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to use a generic delegate in an interface I'm trying to create an interface holding a generic delegate. I then want the classes implementing the interface to decide the actual type method, or preferably even return another delegate. Below are some code describing what I'm trying to acheive. public delegate void GenericMethod<T>(T arg); public delegate void StringMethod(string str); public delegate void ByteMethod(byte bt); public interface ITest { GenericMethod<T> someMethod; } public class TestA : ITest { public GenericMethod<string> someMethod { get { return stringMethod; //which is of type StringMethod(string str), defined above } } } public class TestB : ITest { public GenericMethod<byte> someMethod { get { return byteMethod; //which is of type ByteMethod(byte bt);, defined above } } } Is this possible? Or is it impossible to switch delegates in such a manner? A: I do not think that this is possible without making the interface generic. The common implementation would be: public interface ITest<T> { GenericMethod<T> someMethod; } Or, if you want to actually have a non-generic interface, use: public interface ITest { GenericMethod<object> someMethod; } You can also take a look at two interfaces IEnumerable and IEnumerable<T> to see how you can combine both generic and non-generic interfaces. Just implement the non-generic interface explicitly for use when you do not care about the concrete type. A: public delegate void GenericMethod<T>(T arg); public delegate void StringMethod(string str); public delegate void ByteMethod(byte bt); public interface ITest<T> { GenericMethod<T> someMethod { get; }; } public class TestA : ITest<string> { public GenericMethod<string> someMethod { get { return stringMethod; //which is of type StringMethod(string str), defined above } } } public class TestB : ITest<byte> { public GenericMethod<byte> someMethod { get { return byteMethod; //which is of type ByteMethod(byte bt);, defined above } } } A: You cannot do this because of inheritance principles. All, that works in ITest, should work in derived classes/interfaces. That means, if I'm able to use GenericMethod<int> someMethod (look at int) in ITest, I should be able to use it in TestA and TestB. You are trying to ignore this restriction
{ "language": "en", "url": "https://stackoverflow.com/questions/7610978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby on rails add javascript variable to link_to url params I have a javascript variable, I would to send along with my params when a person clicks a link. var js_variable = something; ... <%= link_to_remote "Link Name", {:url => {url_params}, ajax_options}, {html_options} %> how do I add js_variable to the url_params hash?? Using rails 2.3.8 A: possibly this older question will be useful to you Rails3 - How to send Javascript Variable to a controller's action with the link_to helper? But it seems to me you should be using link_to_function and change the href at runtime
{ "language": "en", "url": "https://stackoverflow.com/questions/7610981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Elements not wrapping inside fixed-width div I have this simple html, with styling: <!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> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <style> #buttons { width:300px; max-width:300px; border-width:1px; white-space:normal; border-style:solid; } #buttons span { cursor:default; padding:10px; white-space: nowrap; } </style> </head> <body> <nav id="buttons"> <span>Some Button</span><span>Button</span><span>A longer button</span><span>Another button</span><span>Click me first</span><span>Button</span></nav> </body> </html> The main block element (#buttons) should be fixed in width, but the containing span elements are dynamically generated, and have variable lengths. I want these 'span' elements to wrap and stay inside the block, no matter how many they are. So basically the main block element should expand vertically if needed. Right now, they expand horizontally, overflowing the main container. For some strange reason, if I put white spaces between the inline 'span' elements, it works. But I can't do that on production (they are attached to the DOM by a javascript library). A: I added the bits in bold to your css: #buttons { width:300px; max-width:300px; border-width:1px; white-space:normal; border-style:solid; **overflow: auto;** } #buttons span { **float: left;** cursor:default; padding:10px; white-space: nowrap; } Can see in action at http://jsfiddle.net/S9rz8/ Think this is what you want? A: This answer is if you want more than one item per line. If you add float: left; to the style of the spans, they wrap. Add position: absolute; to #buttons to make the container have height. http://jsfiddle.net/TNmrZ/1/ A: I think both of your element are considered inline. Make them display:block and it should work fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610984", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can we make a process restart faster? i have an app that runs a process and a service. When I use an auto killer application, it ends the process of that app and then it shows "restarting.." when I see the running applications. How can I make this "restart" faster or how can I prevent the auto killer apps from ending my process app? Thanks in advance! A: How can I make this "restart" faster? Follow good programming practices and design patterns that make your app more efficient and responsive How can I prevent the auto killer apps from ending my process app? I think that this is not possible.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610985", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: face book like button is not showing like on facebook account. I am using facebook like button. I have taken the code from http://developers.facebook.com/docs/reference/plugins/like/ I want user to be able to like products from the cart in magento. Below is my code. <iframe src="https://www.facebook.com/plugins/like.php?href=<?php echo $this->getProductUrl() ?>;send=false&amp;layout=button_count&amp;width=450&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:21px;" allowTransparency="true"></iframe> With the help of above code liking count is being generated in a proper manner but it is not showing it on facebook that i have liked this page when i click on like. so what parameter is missing that it is not showing on face book. If any one has the solution kindly tell. A: &amp was missing in href parameter. Due to that it was not sharing it on face book. but only liking. After placing &amp it works in a nice manner. <iframe src="https://www.facebook.com/plugins/like.php?href=<?php echo $this->getProductUrl() ? >&amp; send=false&amp;layout=button_count&amp;width=450&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:21px;" allowTransparency="true"></iframe>
{ "language": "en", "url": "https://stackoverflow.com/questions/7610988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: nhibernate QueryOver not throwing exception when mapping is missing Can anyone explain what's the idea behind nHibernate QueryOver not throwing exception when there is no mapping for used class? Let's say i have a FakeClass class and no mapping defined, code below executes without exception. var result = session.QueryOver<FakeClass>() .Where(x => x.Name == "SomeName").List(); A: well it's a reported bug: https://nhibernate.jira.com/browse/NH-2829 hope it won't end like this : https://nhibernate.jira.com/browse/NH-2183 A: Does FakeClass exist as a table in the database? If so, i would think that Fluent's automapping feature would map to it as designed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610998", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Notification flags have value -3 I'm writing a custom upload notification, very similar to that from the Picasa Photo Uploader http://code.google.com/p/picasaphotouploader/source/browse/trunk/src/com/android/picasaphotouploader/UploadNotification.java At creation, I set the FLAG_ONGOING_EVENT and it works. After the upload is done, i have these two lines: flags =~ Notification.FLAG_ONGOING_EVENT; flags += Notification.FLAG_AUTO_CANCEL; However, my notification is not cancelable, and flags has a value of -3. Do you have any idea why I can't change the flags anymore? A: A late answer but just in case someone else runs into this issue. I believe you should be using bitwise operations instead of arithmatic operations here. In this case use: flags = (~Notificatoin.FLAG_ONGOING_EVENT | Notification.FLAG_AUTO_CANCEL); This may look weird because, if you don't know bitwise operations, your instincts tell you "not ongoing or auto cancel" but it really means to disable the ongoing bit and to enable the auto cancel bit. I suggest reading up on bitwise operators and bit masks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611003", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Blender default UV Mapping Coming from 3d Studio, I am used to primitive and procedurally generated objects (ruled, lathed, extruded, NURB-based) having UV mapping coordinates by default, and in the case of more complex meshes, breaking out a more manual mapping process. I am currently having difficulty in Blender, because is seems as though no items have default mappings and that unwrapping need to occur for every mesh as it is created. Is this correct? I plan on pulling everything into unity 3d for simple tests it seems excessive to do these steps. Thanks Al A: I don't know 3ds and I am not sure if I understand you right. What you can do in Blender is applying a texture to a model without UV mapping. And you can of course assign multiple materials to one object each one with a different texture and all without doing UV mapping. I just opened an old sample and tried it out - you can download it here. But I found out that this not true if you want to import your Blender objects into Unity3D. From my experience there is no chance to get the objects's texture displayed in Unity3D if it has no explicit UV mapping. Furtheron I did not manage to get an object with two different textures straight into Unity3D. In that case I use parenting or a single texture, which I assume to be faster when rendering. I wrote a blog article about that, maybe it helps you: Working with Blender 2.59 And Unity3D 3.4 A: Blender does give objects a default UV mapping; it's just that it pretty much equals "slap each face on the texture from [0,0] to [1,1]". So yeah if you want a "nicer" UV map you'll have to do something manually.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: m2eclipse "Resolve in workspace" but in IntelliJ? Possible? I am trying to make IntelliJ choose a Maven module in my Intellij Project over the module in the repository, but I can't get it to work! I am trying to do what is called "Resolve in workspace" in Eclipse... anyone who knows how to do this in IntelliJ? A: Check the comments in this bug discussion.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I make my code run in a loop and ask the user "Try again Yes or no?" import java.io.*; public class Magic{ static final int maxsize = 50; public static void main (String [] args) throws IOException{ int i, j, k, l, n, key; boolean n_ok; String line; int [] [] square = new int [maxsize] [maxsize]; BufferedReader KeybIn = new BufferedReader(new InputStreamReader(System.in)); try{ System.out.print("Size of square? "); line = KeybIn.readLine(); n = Integer.parseInt(line); n_ok = (1<=n) & (n<=maxsize+1) & (n%2==1); if ( n_ok ){ for (i=0;i<n;i++) for (j=0;j<n;j++) square[i][j] = 0; square[0][(int)(n-1)/2] = 1; key = 2; i = 0; j = (int)(n-1)/2; while ( key <= n*n ){ k = i - 1; if ( k < 0 ) k = k + n; l = j - 1; if ( l < 0 ) l = l + n; if ( square[k][l] != 0 ) i = (i+1) % n; else { i = k; j = l; } square[i][j] = key; key = key + 1; } System.out.println("Magic square of size " + n); for (i=0;i<n;i++) { for (j=0;j<n;j++) System.out.print("\t"+square[i][j]); System.out.println(); } } }catch (NumberFormatException e){ System.out.println("Error in number, try again."); } } } So how do I put the "Try again yes or no"? just that.. then if I enter y .. it will ask the user the size of the square again .. if letter n it will exit .. this is for magic square A: String tryAgain = "y"; do { // you code System.out.println("Try again? enter \"y/n\"."); tryAgain = System.in.readLine(); } while(!tryAgain.equals("n")); A: Put your code that computes your magic square in a separate method, and have your input reading code in a while loop, that calls that method until the user presses N, for example. A: Wrap the try/catch statement with a while loop. while(not true) { do foo() } A: Check out the Scanner class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: How to Run C# Exe without .Net Framework I am using Visual Studio 2010. I made a C# project and it runs perfectly on my Computer. Problem is this that when Application is run on another Computer, that ask for .Net Framework. Everybody doesn't have administrator Access to install .Net Framework and also peoples don't want to install that. What alternative i should follow to sort out this problem? (Specifically for Windows 7). A: No way! CLR is absolutely needed for managed apps. A: The only alternative is to not use a programming language that is based on the .net framework. If you're writing a c# application, then the .net framework is required. Perhaps you want to create a c++ application instead? A: Windows contains a version of .NET by default. Here's a listing of them. XP * *.NET v1.0 -- Service pack 1 *.NET v2.0 -- Service packs 2 & 3 Vista * *.NET v3.0 -- All service packs Windows 7 * *.NET v3.5 -- All versions and service packs Windows 8 * *.NET v4.0 + Metro UI available. Windows 8.1 * *.Net v4.5 + Metro UI available. Windows 10 * *.Net v4.6 + Metro UI + Universal Apps available. Note: All contains .NET v4.6 if Windows Update is enabled. (Not for all versions of windows) Options of deployment: There are several options of deployment. * *Checking for .NET in installation. (Install systems like NSIS support this). See this for more info. *If you want to deploy portable app, notify users to install the required .NET version. (easier) *Target .NET 2.0 and all users are able to run your app since I think nobody is using XP SP1. (easiest. I use this to deploy mine.) EDIT There needs some clarity with some other answers, so I'm quoting this Wikipedia note. .NET Framework 1.0 is integral OS component of Windows XP Media Center edition or Tablet PC edition. Installation CDs for the Home editions and the Professional editions of Windows XP SP1, SP2 or SP3 comes with .NET Framework installation packages. A: If you are targeting Windows 7 or later version of the OS, then just compile your program using C# 3.5. The version 3.5 of the framework is part of Windows 7. I guess you were compiling C# 4.0 code. A: Correct me if I am wrong but windows 7 comes with .Net framework installed. Windows Vista comes with installed .net framework and I believe this is valid for windows 7 as well. And to answer your question - it is not possible to run the exe on a machine that does not have the framework as the program compiles to intermediate language that is only "understandable" by the Common language runtime(CLR) A: Yes, there is Spoon (earlier XenoCode) that can wrap everything that your app needs and runs it in as a standalone. From their site: Spoon Studio Easily virtualize all of your applications for instant, zero-install delivery on Spoon Server and Spoon.net. Spoon Studio lets you convert your existing software applications into virtual applications that run with no installs, conflicts, or dependencies.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Binding Style to DataGridTextColumns ElementStyle I have a datagrid with some objects. The objects have a name, a "type" property and a bunch of irrelevant properties. based on if the type is "MaterialType" or not i want to set a style for the cells textblock (bold & intend 10px) I started out with a converter. => it gets the type and converts to a font-weight. <DataGridTextColumn.ElementStyle> <Style TargetType="TextBlock"> <Setter Property="FontWeight" Value="{Binding type, Converter={StaticResource ResourceKey=TypeToFontWeightConverter}}"/> <Setter Property="Padding" Value="10,0,0,0"/> </Style> </DataGridTextColumn.ElementStyle> It works.. but I only got to set the font-weight. I want an individual style. so I edited my converter into a TypeToStyle Converter class TypeToStyleConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { Style style = new Style(typeof(TextBlock)); if (value is Type && value == typeof(MaterialType)) { style.Setters.Add(new Setter(TextBlock.FontWeightProperty, FontWeights.Bold)); style.Setters.Add(new Setter(TextBlock.PaddingProperty, new Thickness(0))); } else { style.Setters.Add(new Setter(TextBlock.FontWeightProperty, FontWeights.Bold)); style.Setters.Add(new Setter(TextBlock.PaddingProperty, new Thickness(10,0,0,0))); } return style; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } #endregion } Then I bind the converter. <DataGridTextColumn Binding="{Binding Name}" Header="Name" IsReadOnly="True" Width="1*" ElementStyle="{Binding type, Converter={StaticResource ResourceKey=TypeToStyleConverter}}"/> It all compiles fine. But no styles. The converter doesn't get triggered... A: I think you want to look into using a StyleSelector instead of a Converter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Updating Subversion from PHP on Windows - Permissions-related (Access Denied) I have written a PHP script which updates a SVN working copy. It works fine on my development machine (W2k3 Server)but I cannot get it to work on a production server (W2k8 Server). I'm using the latest Collabnet Subversion binaries (1.6.17). Here's the PHP code: $command = 'svn update C:\inetpub\wwwroot\mysite --config-dir C:\Windows\Temp'; $response = array(); $handle = popen("$command 2>&1", 'r'); $read = ''; while( $read = fread( $handle, 20096 ) ) { $response[] = $read; } pclose( $handle ); flush(); echo '<h2>Command</h2><p> ' . $command . '</p>'; echo '<h2>Response</h2><p>' . implode( '<br />', $response ) . '</p>'; When I run the same command from the command prompt it works fine. But when I run it through IIS, I get: svn: Can't open file 'C:\inetpub\wwwroot\mysite.svn\lock': Access is denied. Presumably I need elevated permissions but I have no idea how to implement it. I've tried giving the _IUSR account full control of the folder containing svn and the C:\inetpub\wwwroot\mysite.svn\ folders but it makes no difference. Thanks A: * *Account IUSR_COMPUTERNAME must have read/write access to the folder C:\inetpub\wwwroot\mysite.svn if it is a checkout. *Next (not sure), you may need to give write access to the folder in the IIS properties for the virtual folder C:\inetpub\wwwroot\mysite.svn. A: Had issues just like this with SVN and Windows Server 2008. The issue is caused by the UAC stuff that typically prevents someone from changing a file if they don't own the file. In the case of SVN, the issue was typically that one user performed the initial checkout, creating the .svn folders and associated bits. Then a different user went to svn up and got OS-level access issues about modifying the SVN database files. Unfortunately, the best fix we could get to was disabling UAC. Actually solved a few other problems and it really makes sense on servers. If it is running as a scheduled task then you could try "run with highest priviliges" but elevating that much makes little sense for a web app. A: I think you need to specifically grant read/write permissions to the user that PHP is running under. In my case php is running as an Apache module, so it runs under the same account. I am less familiar with your setup, however the basic idea is the same. Once you have determined what account you are running PHP under, grant it write permissions to the lock file and your problem should go away. I DO NOT recommend disabling UAC on a production server!! EVER!!! You want to grant the smallest amount of permissions for the smallest number of users to the smallest amount of resources necessary. DO NOT remove all of your user account security to write to a lock file!!! Instead, grant the single permission write. Not full control. Grant it to the single user who needs it (likely the local system account). Grant it for the specific file(C:\inetpub\wwwroot\mysite.svn\lock) which it needs to write to. This approach keeps you from opening a security hole that could be exploited by the malicious! A: Thanks everyone. In the end all these answers helped. I needed to do several things: * *Performed a svn cleanup *Turned of UAC if access is denied when setting permissions *The top level .svn folder needed write permissions for IIS_IUSR *All .svn folders need Read/Write permissions for the Users group. However, there's no apparent way to do this, so the permissions need to be set on the whole site directory. After which the PHP script was able to perform an svn update command. Phew!
{ "language": "en", "url": "https://stackoverflow.com/questions/7611025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to make NSUserDefaults data last for 3 sessions I have this piece of code NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; if (![defaults objectForKey:@"firstRuns"]){ [defaults setObject:[NSDate date] forKey:@"firstRuns"]; if ([cellValue isEqual: @"First"] || [cellValue isEqual: @"Primo"]){ cell.backgroundColor = [UIColor yellowColor]; } else { cell.backgroundColor = [UIColor whiteColor]; } } [[NSUserDefaults standardUserDefaults] synchronize]; in - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath in order that the background of the row called "Primo" or "First" is set to yellow for the first use of the user. I want the yellow background to last at least 3 sessions, how can i do that? Thanks A: Something like: NSNumber *runNumber = [[NSUserDefaults standardUserDefaults] objectForKey:@"runNum"]; if (runNumber) { if ([runNumber intValue] < 3) { if ([cellValue isEqual:@"First"] || [cellValue isEqual:@"Primo"]) { cell.backgroundColor = [UIColor yellowColor]; } else {             cell.backgroundColor = [UIColor whiteColor]; } [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:[runNumber intValue] + 1] forKey:@"runNum"];     } else { cell.backgroundColor = [UIColor whiteColor]; } } else { [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:1] forKey:@"runNum"]; cell.backgroundColor = [UIColor whiteColor]; } [[NSUserDefaults standardUserDefaults] synchronize]; A: Use the UserDefaults in applicationDidLaunch: NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSInteger sessionCount = [[defaults objectForKey:@"sessionCount"] intValue]; sessionCount++; [defaults setInteger:sessionCount forKey:@"sessionCount"]; Use that value in your tableview session to trigger yellow or white
{ "language": "en", "url": "https://stackoverflow.com/questions/7611029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CSS display: inline-block does not accept margin-top? I have an element with display: inline-block, but it doesn't seem to accept margin-top. Is this because the element is still treated as an inline element? If yes, does anyone have a workaround? EDIT #1: My CSS is quite simple: .label { background: #ffffff; display: inline-block; margin-top: -2px; padding: 7px 7px 5px; } I ended up wrapping the content in another div and giving that a margin-top. But that causes a lot of extra markup and makes my code less clear. EDIT #2: margin-top & margin-bottom on inline-block elements only seems to work with positive values. A: you can also try replacing the negative margin with .label{ position:relative; top:-2px; } in addition to the rest of your .label style A: That is indeed the case. Instead of a margin, you could use a padding. Another solution would be to use a container div for the element. You make that div inline-block, and make your current element a block inside that container. Then, you can give a margin to your element. It would help if you got a concrete example, preferably in jsfiddle.net or so. It would help answers to be more specific too, instead of containing just general descriptions like mine here. ;) A: I used display: table. It has the content-fitting properties of inline-block but also supports negative margins in a way that will shift the content following it up along with it. Probably not how you should be using it, but it works. .label { background: #ffffff; display: table; margin-top: -2px; padding: 7px 7px 5px; } A: You can try vertical-align like this: .label { background: #ffffff; display: inline-block; margin-top: -2px; vertical-align: 2px; padding: 7px 7px 5px; } I made an example on jsfiddle: http://jsfiddle.net/zmmbreeze/X6BjK/. But vertical-align not work well on IE6/7. And there is a opera(11.64) rendering bug. So I recommend to use position:relative instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "72" }
Q: F# Lambda Signature I'm reading Programming F# by Chris Smith right now trying to figure out F# when i come across Lambadas. Here is a lambda from one of the examples let generatePowerOfFunc base = (fun exponent -> base ** exponent);; I get that it takes in something and returns a function, but what i don't get is the Signature of this function which is val generatePowerOfFunc : float -> float -> float How does it have three floats instead of two? And when there's this method let powerOfTwo = generatePowerOfFunc 2.0;; It only has 2 floats val powerOfTwo : (float -> float) Maybe Im not getting the whole type signature deal. Any help would be much appreciated. Thanks A: In addition to kongo2002: The last item in the -> chain is the return type, not another argument. The first accepts two floats and returns a float, and the second accepts one float and returns one. The idea of doing it like that, and not something like (float, float) : float, is that you can use a concept called "currying". generatePowerOfFunc is of type float -> float -> float, which is equivalent to float -> (float -> float), so we can give it a single float and get back a function of type float -> float (and we can give it another float, and get back a float). This means that when you call generatePowerOfFunc 2. 4., you apply twice. Once you apply 2., and once you apply 4.. A: The function generatePowerOfFunc takes two arguments of type float and returns a float value: val generatePowerOfFunc : float -> float -> float // ^^^^^^^^^^^^^^ // arguments // ^^^^^ // return value The function powerOfTwo is like a partial function application that just takes one float argument (the exponent) and returns a float.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Django not evaluating base template in views I'm quite new to Django and I just set up my first registration page with django-registration and everything worked well (users can register, change passwords etc.). Now I want to expand my app a bit so I wanted to add a simple profile page so when a user logs in he/she can see their profile. So I created a profile_page.html template to extend the base template and in my views set up a very simple view: @login_required def profile_info_view(request, template_name='profile/profile_page.html'): user_profile = request.user.username return render_to_response(template_name,{ "user":user_profile }) My base template looks like this: <!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" xml:lang="en" lang="en"> <head> <link rel="stylesheet" href="{{ STATIC_URL }}css/style.css" /> <link rel="stylesheet" href="{{ STATIC_URL }}css/reset.css" /> {% block extra_head_base %} {% endblock %} <title>{% block title %}User test{% endblock %}</title> </head> <body> <div id="header"> {% block header %} {% if user.is_authenticated %} {{ user.username }} | <a href="{% url auth_password_change %}">{% trans "Profile" %}</a> | <a href="{% url index %}">{% trans "Home" %}</a> | <a href="{% url auth_logout %}">{% trans "Log out" %}</a> {% else %} <a href="{% url auth_login %}">{% trans "Log in" %}</a> | <a href="{% url registration_register %}">{% trans "Sign up" %}</a> {% endif %} {% endblock %} </div> <div id="content"> {% block content %}{% endblock %} </div> </body> </html> and the profile_pages.html template is: {% extends "base.html" %} {% load i18n %} {% block content %} Hi, {{ user }} {% endblock %} and url.py: urlpatterns = patterns('', (r'^accounts/', include('registration.urls')), (r'^profile/', profile_info_view), (r'^$', direct_to_template,{ 'template': 'index.html' }, 'index'), ) urlpatterns += staticfiles_urlpatterns() So I want it to be that when a logged in user goes to the profile page (example.com/profile/) it shows the profile page and the login page if a user has not logged in. But when a logged in user goes to /profile it evaluates the base template as if the user hasn't registered (is shows Log in in the header) but it does show the profile result. Moreover the static files do not work as well? Any clues to why this might be happening? p.s. I've included the template dirs in settings.py Thanks for any help! A: As dm03514 says in the comments, you're passing the username - a string - to the template as the user variable, instead of the actual user object. The username string doesn't have the method is_authenticated, so your check returns False. In fact, you shouldn't pass the user to the template context at all. Instead, use RequestContext, which uses context processors to add various items to the context - including the user. return render_to_response(template_name, {}, context_instance=RequestContext(request))
{ "language": "en", "url": "https://stackoverflow.com/questions/7611040", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Parse asp:boudfield in a gridview I have the following gridview: I need to parse the first 8 elements of the datetime and view these only in the gridview. How can i do that? <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" BackColor="White" BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="1" DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" GridLines="Horizontal" CellSpacing="4" Height="20px" Width="842px" ShowFooter="True"> <FooterStyle BackColor="White" ForeColor="#333333" /> <RowStyle ForeColor="#333333" BackColor="White" /> <Columns> <asp:ButtonField CommandName="Select" Visible="false" /> <asp:BoundField DataField="ID" HeaderText="ID" HeaderStyle-HorizontalAlign="Left" InsertVisible="False" ReadOnly="True" /> <asp:BoundField DataField="title" HeaderStyle-HorizontalAlign="Left" HeaderText="Title"/> <asp:BoundField DataField="location" HeaderStyle-HorizontalAlign="Left" HeaderText="Location"/> <asp:BoundField DataField="datetime" HeaderStyle-HorizontalAlign="Left" HeaderText="Datetime"/> </Columns> <PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" /> <SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" /> </asp:GridView> A: Try this: <asp:BoundField DataFormatString="{0:MM/dd/yy}" DataField="datetime" HeaderStyle-HorizontalAlign="Left" HeaderText="Datetime" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7611041", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MVC 3: How do I dynamically enable/disable client side validation I have a check out view that serves as a wizard. Steps (5 of them) are contained in their own div's and are shown/hidden via jQuery as a user goes through the checkout process wizard. On one of the steps, I have payment information. Payment options are "Pay With My Account" or "Pay with my credit card". Choosing one or the other shows input controls for the chosen payment option. All this works beautifully. Lets say I choose "Pay with my account" which then hides the credit card inputs and shows the account info inputs. This is again done through jQuery by hiding the containing div. When I go to hit the next button, client side validation fires on the hidden credit card inputs (the containing div is hidden). My question is, how can I use javascript/jQuery to dynamically enable/disable the validation on the hidden input controls? Thanks in advance for any replies... A: I ended up stumbling upon MVC Foolproof Validation over at CodePlex (http://foolproof.codeplex.com). It does everything I need to and more and I didn't have to reinvent the wheel. :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7611042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: VB.NET Sort files in directory by alphanumeric How do I sort the files in this directory below by alphanumeric? An example of a file: 12325_2011.jpg Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then Dim di As New IO.DirectoryInfo(ImagePath) Dim imageArray As IO.FileInfo() = di.GetFiles() Dim image As IO.FileInfo 'list the names of all images in the specified directory For Each image In imageArray CheckBoxList1.Items.Add(image.Name) Next End If End Sub A: Just modify your existing For Each loop like this: For Each image In imageArray.OrderBy(Function(i) i.Name) CheckBoxList1.Items.Add(image.Name) Next A: You could use the sorted list class instead of your image array: http://msdn.microsoft.com/en-us/library/system.collections.sortedlist.aspx e.g. For each Item in di.GetFiles 'Add image url to sorted list Next For Each Item in SortedList 'Add to checkbox list Next
{ "language": "en", "url": "https://stackoverflow.com/questions/7611058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: QT push button and a python lambda function I'm just trying to create a UI for my script in maya/py using QT Designer. The problem is that I want to use a lambda expression as a command for my buttons by adding a dynamic property with the type set to string, property name set to "+command" and lambda x: print('fobar!') as the value. But running the code back in Maya using the loadUI Python command gives me a syntax error. It actually loads the UI but the button's function doesn't work! A: How about: button_name.clicked.connect(lambda : print('foobar'))
{ "language": "en", "url": "https://stackoverflow.com/questions/7611060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: OCaml expression type issue I am trying to make an OCaml function that addsthe number of 'a's in a string to a given argument. let rec count_l_in_word (initial : int) (word : string) : int= if String.length word = 0 then initial else if word.[0] = 'a' then count_l_in_word initial+1 (Str.string_after word 1) else count_l_in_word initial (Str.string_after word 1) I get an error on line 4 saying 'This expression has type string -> int but is here used with type int'. I am not sure why it expects the expression 'count_l_in_word initial+1' to be an int. It should really expect the whole line 'count_l_in_word initial+1 (Str.string_after word 1)' to be an int. Can anyone help with this A: count_l_in_word initial+1 (Str.string_after word 1) is parsed as (count_l_in_word initial) + (1 ((Str.string_after word) 1)) so you need to add some parens: count_l_in_word (initial + 1) (Str.string_after word 1)
{ "language": "en", "url": "https://stackoverflow.com/questions/7611064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Adding Exception to the operations in Sparx Enterprise Architect I have a Class Diagram in Enterprise Architect . One of the my classes has some methods and I want my methods to thrown Exception. Does any have any idea how can I do that? As in Attached image I've interface (HsaInterface) which has two methods and I want both to throw Exception. Image Showing class A: EA's representation of exceptions thrown by an operation is a bit messy, and rather poorly documented as well. Essentially, an exception is represented by a single tagged value on the operation, carrying the (non-qualified) names of the exception classes in a comma-separated list. For example, the method parseLine in the Java class com.sun.activation.registries.MailcapFile would have a tag throws with the value MailcapParseException,IOException. If you create an operation in a class, that operation does not automatically get a tag for exceptions. This is because the tag name depends on the implementation language; it is "throw" for SystemC and "throws" for C# and Java (according to the manual anyway, I haven't verified this). You can create the tag yourself, however. If you reverse-engineer a set of Java classes, the exception tags will be populated in the model. This might be the easiest way to see how it's used. This name-only link is obviously very weak. It is used in code generation, but if you change the name of the exception class, you will need to change the tag value manually. EA does not check whether the listed class names exist or are in scope during code generation, it just writes the names into the method signature. Furthermore, tagged values on operations cannot be displayed in diagrams. So while you can add exceptions to your operations, you can only see them by looking at the operations' properties. Interestingly, EA's data model does include a Throws column in the t_operation table (and consequently, a Throws attribute in the Method class in EA's API). This appears to be unused. So it boils down to the purpose of your model. If you will be generating code in one of the languages where EA supports exceptions, you'll need to add the throws tag manually. If you want to show the exceptions in diagrams, that approach doesn't work. For such a purpose, you're better off drawing a Dependency from the operation to the exception class and stereotyping it "throws". In order to anchor a connector to an operation, draw it from the class as usual, then right-click the connector near the end you want to anchor and select Link to Element Feature.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611069", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Force ipv4 connections in .NET? I am running a console app on my server and trying to connect to my site also on the server. Its causing problems by connecting via ipv6. The software i am running in php doesnt support ipv6 thus i get errors. How do i force the console app (which is using webclient) to use ipv4 connection/ip address rather then ipv6? A: This depends entirely on how the underlying operating system and network resolves the name. If your dns returns an IPv6 address, that's what it will use. There's nothing in .Net that can change that, unless you want to write your own dns lookup code to ignore ip6 responses.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Segmented controls with 2 buttons I'm trying to create a segmented control with 2 Round rect buttons but don't know how to set the 'forState' for Highlighted button. Others said to set the background image in IB and modify the Image programmatically Tried: [buttonName setImage:[UIImage imageNamed:@"UnselectedImage.png"] forState:UIControlStateNormal]; [buttonName setImage:[UIImage imageNamed:@"SelectedImage.png"] forState:UIControlStateHighlighted]; The problem is the background image doesn't remanins after I've clicked on it, any clue? A: The "highlighted" state is used only while the user touches the button. As soon as the user release his/her finger from the button, the states goes back to normal. You may try using the "Selected" state instead (not tested but worth trying as it seems quite logical). If it doesn't work, you may need to change the "selected" state of your buttons yourself by code (in the button action or the segmentedControl delegate methods) A: You need to set the selected image for UIControlStateSelected, rather than UIControlStateHighlighted A: A UIButton is kind of like a momentary switch. It doesn't have a "hot now" state. "Highlighted" is literally just while it's being tapped, and then it's out of that state. It seems like you maybe need some external variable to track the state of your buttons, and maybe to manage the twiddling of the images, too. I like that image. That's going to be a nice effect, once you get it running. A: You could try the following code: 1 Image: int iButtonState = 1; if (iButtonState == 1) { [buttonName setImage:[UIImage imageNamed:@"Normal.png"] forState:UIControlStateNormal]; iButtonState = 2; } else if (iButtonState == 2) { [buttonName setImage:[UIImage imageNamed:@"Other.png"] forState:UIControlStateNormal]; iButtonState = 1; } 2 Images: int iButtonState = 1; int iTabImageA = 1; int iTabImageB = 1; if (iButtonState == 1) { if (iTabImageA == 1) { [buttonName setImage:[UIImage imageNamed:@"ImageA1.png"] forState:UIControlStateNormal]; iTabImageA = 2; } else if (iTabImageA == 2) { [buttonName setImage:[UIImage imageNamed:@"ImageA2.png"] forState:UIControlStateNormal]; iTabImageA = 1; } iButtonState = 2; } else if (iButtonState == 2) { if (iTabImageB == 1) { [buttonName setImage:[UIImage imageNamed:@"ImageB1.png"] forState:UIControlStateNormal]; iTabImageB = 2; } else if (iTabImageB == 2) { [buttonName setImage:[UIImage imageNamed:@"ImageB2.png"] forState:UIControlStateNormal]; iTabImageB = 1; } iButtonState = 1; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7611078", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Filtering a list with linq Being new to linq, I am having trouble trying to apply a filter to a List object. This is what I have so far var filter = productList.GroupBy(a => a.Product.FamilySku).Select(grp => grp.OrderByDescending(a => a.Product.FamilySku).First()); This works except I want to not apply the filter if the a.Product.IsFamily != true I want to add an except clause: Except(a.Product.IsFamily != true) So in pseudo code, I want to group by all the Product.FamilySku's but not group them if Product.IsFamily != true. Thx for the help A: Just put in a Where() filter before the grouping: var filter = productList.Where(p => p.Product.IsFamily) .GroupBy(a => a.Product.FamilySku) .Select(grp => grp.OrderByDescending(a => a.Product.FamilySku).First()); A: Looks like you just need to use a the Where() method: var filter = productList .Where(a => a.Product.IsFamily) .GroupBy(a => a.Product.FamilySku) .Select(grp => grp.OrderByDescending(a => a.Product.FamilySku).First()); A: The other answers work if you want to completely leave out the products where IsFamily is false. But if what you want is for them to be in the filtered list, but not grouped, then you could Concat() them on at the end like this: var filter = productList.Where(p => p.Product.IsFamily) .GroupBy(p => p.Product.FamilySku) .Select(grp => grp.OrderByDescending(p => p.Product.FamilySku).First()) .Concat(productList.Where(p => !p.Product.IsFamily)); There may be a better way to do it if you don't want to change their order. A: productList.Where(!a.Product.IsFamily).GroupBy(a => a.Product.FamilySku) .Select(grp => grp.OrderByDescending(a => a.Product.FamilySku).First());
{ "language": "en", "url": "https://stackoverflow.com/questions/7611080", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I access the skipped "parent" of SelectMany when using dotted syntax in Linq? In query syntax I can write var greendoorsWithRooms = from room in house.roooms from door in room.doors where door.Color = green select new {d=door,r=room} Is there a way I could achieve the same with dotted syntax? var greendoorsWithRooms = house.rooms.SelectMany(room=>room.Doors) .Where(door=>door.Color==green) .Select(door=>new{ <room is not in scope> } I am teaching some non-programmers to use LINQPad against a proprietary object model so that we don't have to create GUI around every odd case. It would be beneficial if they didn't have to learn query syntax. Presently, I've supplied snippets solving this using foreach, but the question still comes up once in a while. A: This is also possible: house.rooms.SelectMany(room => room.Doors.Where(door => door.Color == green), (room, door) => new { r = room, d = door }) It's this overload of SelectMany. A: Not ideal, but you could always use anonymous types in SelectMany: var greendoorsWithRooms = house.rooms.SelectMany(room=> new { Room = room, Doors = room.Doors}) .Where(roomAndDoors=>roomAndDoors.Door.Color==green) .Select(roomAndDoors => ... A: All LINQ queries are converted by the compiler into method (dotted) syntax. Query notation is just syntactic sugar. In the C# language specification, the translation of "from x1 in e1 from x2 in e2" is explicitly called out on page 211. from x1 in e1 from x2 in e2 becomes from * in (e1).SelectMany(x1 => e2, (x1, x2) => new { x1, x2 }) Following the cookbook then, your example would be from * in house.rooms.SelectMany(room => room.doors, (room, doors) => new { room, doors }) and then you would complete the conversion to dotted notation by adding Where and Select clauses. In fact the documentation for SelectMany gives your query as an example! var query = petOwners .SelectMany(petOwner => petOwner.Pets, (petOwner, petName) => new { petOwner, petName }) .Where(ownerAndPet => ownerAndPet.petName.StartsWith("S")) .Select(ownerAndPet => new { Owner = ownerAndPet.petOwner.Name, Pet = ownerAndPet.petName } ); You just have to change "owner" to "room" and "pets" to "doors" and change your filter condition.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "33" }
Q: Linux(MIPS): Temporarily "change" register contents when viewing core dump Some of the threads in my app are sat in optimized functions and when I debug the app, gdb can't backtrace from those functions. But I've looked at the assembler and can partially unwind the stack by hand up to the previous function's frame by doing something like: set $old_ra = $ra set $old_sp = $sp set $ra = *(unsigned long*)($sp+28) set $sp = $sp + 48 bt set $ra = $old_ra set $sp = $old_sp This works perfectly if I'm doing live debugging, and it successfully shows a complete backtrace. I want to be able to do the same offline when looking at a core dump. Obviously the concept of poking a register is meaningless in a core dump, but is there a way to tell gdb "just use this value for the register" so I can do a similar backtrace? A: Not out of the box. The only way I found is to physically modify the core file. ELF core file would usually have one or more 'reg' sections that contain process' registers. All you need is to figure out where exactly in that section is the register you want to change and then edit the file, put the new value there and re-run GDB.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611082", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Sharepoint 2010 impersonation of user for whole Log-in session Situation: We have employees that are requesting for a feature that allows them to give their privileges to another person. This is useful if they need to be on leave, and need to give their permissions/privileges to another user. Thus this another user can take actions on his/her behalf. Example: John is going to be on scheduled leave for the next 2 days. Seeing this may hinder the approval of documents, he then decides to designate Mary as his "impersonator." In essence, when Mary logs in to Sharepoint, she has the permissions that John originally has. It's like impersonating another user for your whole log-in session. Current research: I've found sites mentioning about impersonating another user to execute a block of code. However it's only for a certain piece of code. Question: How can I accomplish a user to impersonate another user for the whole log-in session? A: I think this is not advisable as, even if you manage to do it right, it'll mess with all the security features of your site: auditing and accountability. If Mary is allowed to impersonate John, it'll virtually impossible to tell who did what. A better solution is adopt a policy of not having a single person be the approver of time sensitive documents. Instead use groups (even if the groups will initially have 1 person). This way when John goes on vacation, he (or an admin) can add Mary to the group and she can do his tasks without having to impersonate him. If you do want to implement impersonation, you might have to use Forms authentication. Perhaps create a new zone that uses forms. So when John requests that Mary be allowed to impersonate him, you put that in some database table. When Mary logs on using the forms URL, you lookup the value of the person she's supposed to impersonate and associate her session with that person's account.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Attaching to Process Issue In VS 2010, I attached my source code to a process for debugging purposes. I set a breakpoint to a line that my log4net log said was failing. When I set the breakpoint, started and attached to the process, the breakpoint showed up as clear. When I hovered over the breakpoint, a warning said that my breakpoint wouldn't get hit because that particular symbol wasn't loaded. I don't understand how I could've chosen the wrong source file to set a breakpoint. I got it directly from the log, which gave an absolute path of the file and line where my code failed. Please advise me. Thx A: clear bp means that the source code you're looking at is not being executed. we know this for a fact. so a) you attached the wrong source code b) your source code is out of date or otherwise doesn't precisely match the binary c) if you have a prebuilt binary that you're linking against (a dll or a .lib) probably you need to download official "debug symbols" -- because a "release" binary does not include enough information to correlate it with source code. if these aren't provided you may need to rebuild the 3rd party library from source code yourself so you can make a debug build. haven't done visual studio in a while, so this might be a bit off. A: I don't understand how I could've chosen the wrong source file to set a breakpoint. I got it directly from the log, which gave an absolute path of the file and line where my code failed You haven't chosen the wrong source file (most likely). The problem is Visual Studio needs more than that to hit the breakpoint you've set - it needs the pdb files that were hopefully created when you compiled the application you are debugging - Do you have these files? Did you compile in Debug or Release mode? Bring up the modules windows (Debug -> Windows -> Modules) and look for your dll/exe. Right click on that and choose 'Symbol Load Information'. Whats that say?
{ "language": "en", "url": "https://stackoverflow.com/questions/7611084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Disable scrolling in listview I have a list view and depending on some logic I want to temporary disable the scrolling. view.setOnScrollListener(null); doesn't helps me I guess I need to write some code, can someone give me a hist or some snippet ? Thanks A: make your CustomListView @Override public boolean onInterceptTouchEvent(MotionEvent ev) { if(needToStop){ return false;} return super.onInterceptTouchEvent(ev); } on false the childs will handle the touch event, make sure you put your if condition to check you need to scroll or not. A: If you have an event bound to the list items, then dragging the list with any of these solutions will still trigger the event. You want to use the following method to account for users expectation to cancel the event by dragging away from the selected item (adapted from Pointer Null's answer): @Override public boolean dispatchTouchEvent(MotionEvent ev) { final int actionMasked = ev.getActionMasked() & MotionEvent.ACTION_MASK; if (actionMasked == MotionEvent.ACTION_DOWN) { // Record the position the list the touch landed on mPosition = pointToPosition((int) ev.getX(), (int) ev.getY()); return super.dispatchTouchEvent(ev); } if (actionMasked == MotionEvent.ACTION_MOVE) { // Ignore move events return true; } if (actionMasked == MotionEvent.ACTION_UP) { // Check if we are still within the same view if (pointToPosition((int) ev.getX(), (int) ev.getY()) == mPosition) { super.dispatchTouchEvent(ev); } else { // Clear pressed state, cancel the action setPressed(false); invalidate(); return true; } } return super.dispatchTouchEvent(ev); } Full custom view class is available: https://gist.github.com/danosipov/6498490 A: The best answer for me is the One from Dan Osipov. I'd improve it like this. (firing a CANCEL action event instead of manually erasing the pressed state). @Override public boolean dispatchTouchEvent(MotionEvent ev) { final int actionMasked = ev.getActionMasked() & MotionEvent.ACTION_MASK; if (actionMasked == MotionEvent.ACTION_DOWN) { // Record the position the list the touch landed on mPosition = pointToPosition((int) ev.getX(), (int) ev.getY()); return super.dispatchTouchEvent(ev); } if (actionMasked == MotionEvent.ACTION_MOVE) { // Ignore move events return true; } if (actionMasked == MotionEvent.ACTION_UP) { // Check if we are still within the same view if (pointToPosition((int) ev.getX(), (int) ev.getY()) != mPosition) { // Clear pressed state, cancel the action ev.setAction(MotionEvent.ACTION_CANCEL); } } return super.dispatchTouchEvent(ev); } A: In your CustomListView: @Override public boolean dispatchTouchEvent(MotionEvent ev){ if(ev.getAction()==MotionEvent.ACTION_MOVE) return true; return super.dispatchTouchEvent(ev); } Then ListView will react to clicks, but will not change scroll position. A: Another option without creating a new custom ListView would be to attach an onTouchListener to your ListView and return true in the onTouch() callback if the motion event action is ACTION_MOVE. listView.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { return (event.getAction() == MotionEvent.ACTION_MOVE); } }); A: use listview.setEnabled(false) to disable listview scrolling Note: This also disables row selections A: When writing code for swipe to delete on a list view, I wanted to prevent the vertical scrolling once the swipe had been detected. I set a boolean flag in the ACTION_MOVE section once the swipe to delete conditions had been met. The dispatchTouchEvent method checks that condition and prevents the scroll from working. In the ACTION_UP I set the flag back to false to re-enable the scroll. private float mY = Float.NaN; private boolean mStopScroll = false; @Override public boolean onTouch(View view, MotionEvent event) { if(!mStopScroll) { mY = event.getY(); } switch (event.getAction()) { case MotionEvent.ACTION_MOVE: if(<condition that stops the vertical scroll>) { mStopScroll = true; } break; case MotionEvent.ACTION_UP: mStopScroll = false; // your code here return true; default: } return false; } @Override public boolean dispatchTouchEvent(MotionEvent motionEvent) { if(mStopScroll) { motionEvent.setLocation(motionEvent.getX(), mY); } return super.dispatchTouchEvent(motionEvent); } A: My answer will be interesting for Xamarin and MvvmCross users. Main concept is the same like in previous posts, so main steps are: * *Mute scroll events *Change dynamically list height Here you are helper class, that allows to disable scroll in list view: using System; using Cirrious.MvvmCross.Binding.Droid.Views; using Android.Content; using Android.Util; using Android.Views; using Android.Database; namespace MyProject.Android.Helpers { public class UnscrollableMvxListView : MvxListView { private MyObserver _myObserver; public UnscrollableMvxListView (Context context, IAttributeSet attrs, MvxAdapter adapter) : base(context, attrs, adapter) { } protected override void OnAttachedToWindow () { base.OnAttachedToWindow (); var dtso = new MyObserver(this); _myObserver = dtso; Adapter.RegisterDataSetObserver (dtso); } protected override void OnDetachedFromWindow () { Log.Debug ("UnscrollableMvxListView", "OnDetachedFromWindow"); if (_myObserver != null) { Adapter.UnregisterDataSetObserver (_myObserver); _myObserver = null; } base.OnDetachedFromWindow (); } //Make List Unscrollable private int _position; public override bool DispatchTouchEvent (MotionEvent ev) { MotionEventActions actionMasked = ev.ActionMasked & MotionEventActions.Mask; if (actionMasked == MotionEventActions.Down) { // Record the position the list the touch landed on _position = PointToPosition((int) ev.GetX (), (int) ev.GetY()); return base.DispatchTouchEvent(ev); } if (actionMasked == MotionEventActions.Move) { // Ignore move events return true; } if (actionMasked == MotionEventActions.Up) { // Check if we are still within the same view if (PointToPosition((int) ev.GetX(), (int) ev.GetY()) == _position) { base.DispatchTouchEvent(ev); } else { // Clear pressed state, cancel the action Pressed = false; Invalidate(); return true; } } return base.DispatchTouchEvent(ev); } //Make List Flat public void JustifyListViewHeightBasedOnChildren () { if (Adapter == null) { return; } var vg = this as ViewGroup; int totalHeight = 0; for (int i = 0; i < Adapter.Count; i++) { View listItem = Adapter.GetView(i, null, vg); listItem.Measure(0, 0); totalHeight += listItem.MeasuredHeight; } ViewGroup.LayoutParams par = LayoutParameters; par.Height = totalHeight + (DividerHeight * (Adapter.Count - 1)); LayoutParameters = par; RequestLayout(); } } internal class MyObserver : DataSetObserver { private readonly UnscrollableMvxListView _unscrollableMvxListView; public MyObserver (UnscrollableMvxListView lst) { _unscrollableMvxListView = lst; } public override void OnChanged() { Log.Debug("UnscrollableMvxListView", "OnChanged"); base.OnChanged (); _unscrollableMvxListView.JustifyListViewHeightBasedOnChildren (); } } } A: This is the code Joe Blow (comment on OP post) pointed at on http://danosipov.com/?p=604 but I'm posting it here to preserve it in case the link is orphaned: public class ScrollDisabledListView extends ListView { private int mPosition; public ScrollDisabledListView(Context context) { super(context); } public ScrollDisabledListView(Context context, AttributeSet attrs) { super(context, attrs); } public ScrollDisabledListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { final int actionMasked = ev.getActionMasked() & MotionEvent.ACTION_MASK; if (actionMasked == MotionEvent.ACTION_DOWN) { // Record the position the list the touch landed on mPosition = pointToPosition((int) ev.getX(), (int) ev.getY()); return super.dispatchTouchEvent(ev); } if (actionMasked == MotionEvent.ACTION_MOVE) { // Ignore move events return true; } if (actionMasked == MotionEvent.ACTION_UP) { // Check if we are still within the same view if (pointToPosition((int) ev.getX(), (int) ev.getY()) == mPosition) { super.dispatchTouchEvent(ev); } else { // Clear pressed state, cancel the action setPressed(false); invalidate(); return true; } } return super.dispatchTouchEvent(ev); } } When you add this ListView to your layout remember to precede it with its package name, otherwise an exception will be thrown when you try to inflate it. A: Try this: listViewObject.setTranscriptMode(0); Works for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611085", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "44" }
Q: How to access class constants in Twig? I have a few class constants in my entity class, e.g.: class Entity { const TYPE_PERSON = 0; const TYPE_COMPANY = 1; } In normal PHP I often do if($var == Entity::TYPE_PERSON) and I would like to do this kind of stuff in Twig. Is it possible? A: After some years I realized that my previous answer is not really so good. I have created extension that solves problem better. It's published as open source. https://github.com/dpolac/twig-const It defines new Twig operator # which let you access the class constant through any object of that class. Use it like that: {% if entity.type == entity#TYPE_PERSON %} A: As of 1.12.1 you can read constants from object instances as well: {% if var == constant('TYPE_PERSON', entity) A: Just to save your time. If you need to access class constants under namespace, use {{ constant('Acme\\DemoBundle\\Entity\\Demo::MY_CONSTANT') }} A: {% if var == constant('Namespace\\Entity::TYPE_PERSON') %} {# or #} {% if var is constant('Namespace\\Entity::TYPE_PERSON') %} See documentation for the constant function and the constant test. A: If you are using namespaces {{ constant('Namespace\\Entity::TYPE_COMPANY') }} Important! Use double slashes, instead of single A: Edit: I've found better solution, read about it here. * *Read more about how to create and register extension in Twig documentation. *Read about Twig extensions in Symfony2 documentation. Let's say you have class: namespace MyNamespace; class MyClass { const MY_CONSTANT = 'my_constant'; const MY_CONSTANT2 = 'const2'; } Create and register Twig extension: class MyClassExtension extends \Twig_Extension { public function getName() { return 'my_class_extension'; } public function getGlobals() { $class = new \ReflectionClass('MyNamespace\MyClass'); $constants = $class->getConstants(); return array( 'MyClass' => $constants ); } } Now you can use constants in Twig like: {{ MyClass.MY_CONSTANT }} A: In book best practices of Symfony there is a section with this issue: Constants can be used for example in your Twig templates thanks to the constant() function: // src/AppBundle/Entity/Post.php namespace AppBundle\Entity; class Post { const NUM_ITEMS = 10; // ... } And use this constant in template twig: <p> Displaying the {{ constant('NUM_ITEMS', post) }} most recent results. </p> Here the link: http://symfony.com/doc/current/best_practices/configuration.html#constants-vs-configuration-options
{ "language": "en", "url": "https://stackoverflow.com/questions/7611086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "152" }
Q: xsl concat function I am having a hard time in printing an attribute in a tag using xsl. This is my input xml <input> <subscriptons> <services> <service-info> First </service-info> <service-info> Second </service-info> </services> </subscriptons> </input> Now using XSL I am trying to convert the above xml to <Main_Subscriptions elem="0"> <Main_Services elem="0"> First Service </Main_Services> </Main_Subscriptions> <Main_Subscriptions elem="1"> <Main_Services elem="1"> Second Service </Main_Services> </Main_Subscriptions> Using XSL I am able to get everything except the arguments elem="x", basically whenever I am trying to use " or < my xsl fails, e.g. this is what I am doing to get the Main_Subscriptions tag: <xsl:value-of select="concat('&lt;Main_Subscriptions elem=&quot;', position(), '&quot;&gt;')" disable-output-escaping="yes" /> Any ideas why it is not working ? Thanks ! A: you can simply use below code: <xsl:element name="Main_Subscriptions"> <xsl:attribute name="elem"> <xsl:value-of select="position()"/> </xsl:attribute> </xsl:element>
{ "language": "en", "url": "https://stackoverflow.com/questions/7611090", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Which database storage-engine is best for implementing a blog? Possible Duplicate: MySql: MyISAM vs. Inno DB! I am implementing a blog in php using MySql. Not all engines support special field types, as BLOB (binary large object) or TEXT types, which I need to use a lot. Furthermore I will heavily need to manage comments to posts, and different possible archives of posts, using foreign key mechanism. Which database storage engine (MyISAM, InnoDB,..) is it best to use in terms of efficiency and functionalities? A: I'd recommend InnoDB over MyISAM, because of better transactional properties. Inno would be a little slower when it comes to writing, but your data is safer, and it's not that you're gonna write 5000 records a minute. Some software (like MediaWiki and I think WordPress too) mix up the types. They use Inno for all relations and meta data, and keep a separate table for content fields, which are stored in a MyISAM table, because it allows using FULLTEXT indexes. But this is a workaround as well. Better use Inno all the time. If you need advanced searching, use a separate seach engine like Sphinx.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to Run cmd as admin and pass command to it? Possible Duplicate: To run cmd as administrator along with command? I want to run a cmd using administrator privileges and then pass the command to the process that is running cmd as administrator. I don't want to use proc.standardinput to pass the command is there any other method? A: You need to use the next api function from advapi32.dll CreateProcessAsUser
{ "language": "en", "url": "https://stackoverflow.com/questions/7611102", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Embedding window into another process I have read some posts here on StackOverflow, but none has worked for me. Here is the code I am using to display the window of the standard Calculator on my form: procedure TForm1.Button1Click(Sender: TObject); var Tmp: Cardinal; R: TRect; begin CalcWindow := FindWindow(nil, 'Calculator'); if (CalcWindow <> 0) then begin GetWindowThreadProcessID(CalcWindow, CalcProcessID); Tmp := GetWindowLong(CalcWindow, GWL_STYLE); Tmp := (Tmp and not WS_POPUP) or WS_CHILD; SetWindowLong(CalcWindow, GWL_STYLE, Tmp); GetWindowRect(CalcWindow, R); SetForegroundWindow(CalcWindow); Windows.SetParent(CalcWindow, Panel1.Handle); SetWindowPos(CalcWindow, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE or SWP_FRAMECHANGED); AttachThreadInput(GetCurrentThreadID(), CalcWindow, True); end; end; It does display the window on my form, but the glass border is lost and sometimes (especially when I move my form), it is hard to restore the focus to the embedded window (I need to click several times). What may be causing this? Also, do you see any potential issues I may get into with using this method? Thank you for your time. A: For the sake of your sanity, and the sanity of your program's users, I think you'd better abandon this idea: I tried to do exactly this thing with my own software (a window from 32-bit app embedded into 64-bit wrapper), and it never worked 100%, even using the tricks from the other answers you've got here. * *It is very hard to make it work reliably, there are zillion little subtle issues that you'll never get right. If you're messing with windows of other applications, which are not aware of your manipulation, generally you're asking for trouble. *You're changing the way users expect Windows to behave. This will be confusing and unexpected for them. A: Try this code. I took it from one of my older source codes. You will lose glass frame, but main menu is visible, and I didn't notice any problem in setting focus back to the embedded app. You should be able to do so using SetForegroundWindow() API function. Whenever you move your container form, your embedded app loses focus, so you need to call SetForegroundWindow again to restore focus : procedure ShowAppEmbedded(WindowHandle: THandle; Container: TWinControl); var WindowStyle : Integer; FAppThreadID: Cardinal; begin /// Set running app window styles. WindowStyle := GetWindowLong(WindowHandle, GWL_STYLE); WindowStyle := WindowStyle - WS_CAPTION - WS_BORDER - WS_OVERLAPPED - WS_THICKFRAME; SetWindowLong(WindowHandle,GWL_STYLE,WindowStyle); /// Attach container app input thread to the running app input thread, so that /// the running app receives user input. FAppThreadID := GetWindowThreadProcessId(WindowHandle, nil); AttachThreadInput(GetCurrentThreadId, FAppThreadID, True); /// Changing parent of the running app to our provided container control Windows.SetParent(WindowHandle,Container.Handle); SendMessage(Container.Handle, WM_UPDATEUISTATE, UIS_INITIALIZE, 0); UpdateWindow(WindowHandle); /// This prevents the parent control to redraw on the area of its child windows (the running app) SetWindowLong(Container.Handle, GWL_STYLE, GetWindowLong(Container.Handle,GWL_STYLE) or WS_CLIPCHILDREN); /// Make the running app to fill all the client area of the container SetWindowPos(WindowHandle,0,0,0,Container.ClientWidth,Container.ClientHeight,SWP_NOZORDER); SetForegroundWindow(WindowHandle); end; You can call it this way: ShowAppEmbedded(FindWindow(nil, 'Calculator'), Panel1);
{ "language": "en", "url": "https://stackoverflow.com/questions/7611103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Sorry but Another WCF service The maximum array length quota (16384) has been exceeded I know this question has been asked many times on here but I have gone through each of these and can't seem to get it to work for me. From my client, I am trying to pass in 2 byte parameters and return byte[] but while it works fine when the parameters are small, it throws the "WCF service The maximum array length quota (16384) has been exceeded". Here is my Client web.config: <system.serviceModel> <bindings> <basicHttpBinding> <binding name="BasicHttpBinding_GenerateDocument" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true"> <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" /> <security mode="Transport"> <transport clientCredentialType="None" proxyCredentialType="None" realm="" /> <message clientCredentialType="UserName" algorithmSuite="Default" /> </security> </binding> <binding name="BasicHttpBinding_IGenerateDocument" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true"> <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> <security mode="None"> <transport clientCredentialType="None" proxyCredentialType="None" realm="" /> <message clientCredentialType="UserName" algorithmSuite="Default" /> </security> </binding> </basicHttpBinding> </bindings> <client> <endpoint address="http://localhost:6543/GenerateDocument.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_GenerateDocument" contract="NWIS.DocumentGeneratorService.IGenerateDocument" name="NWIS.DocumentGeneratorService.GenerateDocument.svc" /> <endpoint address="http://localhost:6543/GenerateDocument.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IGenerateDocument" contract="DocGenService.IGenerateDocument" name="BasicHttpBinding_IGenerateDocument" /> </client> </system.serviceModel> and here is the Server equivalent: <system.serviceModel> <bindings> <basicHttpBinding> <binding name="BasicHttpBinding_GenerateDocument" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true"> <readerQuotas maxDepth="32" maxStringContentLength="5242880" maxArrayLength="2147483646" maxBytesPerRead="4096" maxNameTableCharCount="5242880"/> <security mode="Transport"> <transport clientCredentialType="None" proxyCredentialType="None" realm="" /> <message clientCredentialType="UserName" algorithmSuite="Default" /> </security> </binding> </basicHttpBinding> </bindings> <behaviors> <serviceBehaviors> <behavior name="ServiceBehaviour"> <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --> <serviceMetadata httpGetEnabled="true" /> <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> <serviceDebug includeExceptionDetailInFaults="false" /> </behavior> </serviceBehaviors> </behaviors> <serviceHostingEnvironment multipleSiteBindingsEnabled="false" /> <services> <service name="NWIS.DocumentGeneratorService.GenerateDocument" behaviorConfiguration="ServiceBehaviour"> <host> <baseAddresses> <add baseAddress="http://localhost:6543/"/> </baseAddresses> </host> <endpoint address="http://localhost:6543/GenerateDocument.svc" binding="basicHttpBinding" contract="NWIS.DocumentGeneratorService.IGenerateDocument" /> </service> </services> </system.serviceModel> If anyone could see the reason that this works for say 400 bytes but does not for say 20000 bytes, I would be grateful for any guidance. Thanking you all in advance A: You have defined your binding configuration on the server side with the extra large values - but you're not using it! You need to specify in your service endpoint what binding configuration to use! So change your current config to: <service name="NWIS.DocumentGeneratorService.GenerateDocument" behaviorConfiguration="ServiceBehaviour"> .... <endpoint address="http://localhost:6543/GenerateDocument.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_GenerateDocument" <== add this line here!! contract="NWIS.DocumentGeneratorService.IGenerateDocument" /> </service> and then, hopefully, your service will actually use those values you've configured!
{ "language": "en", "url": "https://stackoverflow.com/questions/7611104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Trouble parsing string date in us with the Datetime.TryParse I'm trying to put a variable, stored in a string format in a dateTime variable. System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US"); System.Globalization.DateTimeFormatInfo usaDateFormatInfo = culture.DateTimeFormat; string sDataStored = "10/15/2011"; if (DateTime.TryParse(sDataStored , usaDateFormatInfo, System.Globalization.DateTimeStyles.None, out TestedDateTime)) DateTime dMyUSDateTime = TestedDateTime; Unfortunately, the final result in my variable is not : "10/15/2011" but "15/10/2011" (the french culture, which is the current culture of the application for the moment). Same result with the TryParseExact. I could go thru a "Convert", inside a "try/catch", but Im sure there are other better way to solve this problem... Thanks for your help. A: When you say the result is 15/11/2011 where are you seeing that? In the debugger? The debugger will just format the variable according to your current culture (by just calling ToString). The DateTime object doesn't stored the culture it was parsed from. You need to pass the culture to it when you convert it back to a string so it formats according to the US culture. e.g. dMyUsDateTime.ToString(usaDateFormatInfo) A: A DateTime doesn't have a culture attached to it. When you want to display a DateTime value, you need to specify the date/time format to use. If you don't specify a format (or view the value in the Visual Studio debugger), the current thread's current culture is used. string result = someDateTime.ToString("d", new CultureInfo("en-US")); // result == "10/15/2011"
{ "language": "en", "url": "https://stackoverflow.com/questions/7611107", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: _trackEvent error in google analytics? I use this snippet to track some clic on a link without loading a new page but analytics didn't record the clic, do I made a mistake? <a onClick="document.getElementById('divCode').style.display = 'none';document.getElementById('lecode').style.display = 'block'; clic_code_bon();_gaq.push(['_trackEvent', 'Clic', 'Telephone']);"> <span class="">Obtenir le numéro</span> </a> Thanks for your inputs! A: The function "clic_code_bon()" is apparently not defined on the page (and looking at the source, I don't see it). That's causing an error (in Firefox at least). The error happens before the call to the Google API, so that call does not happen. You have to click on the link in order to see the error (obviously).
{ "language": "en", "url": "https://stackoverflow.com/questions/7611109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery .animate() to change facing position of game character I'm making a game using jQuery but using a simple example that I found made by someone else and building on top of it. Here is the sample that i'm using: http://motyar.blogspot.com/2010/04/angel-dreams-jquery-game.html I need to change the chase() function so that when the angel chases the dream, I want to be able to use different images of the angel facing in different directions. So basically if the angel has to go up to catch the dream, it would use the image of the angel facing up. Same thing if going down, left, right and even on a slant. I want it to look like the character (angel) is actually chasing after the dream as it will be facing the dream wherever it goes. Here is the function that fired when the angel chases the dream: function chase(x, y, dream) { //angel gets the dream angel.animate({ top: y, left: x }, 1000, function () { //explode the dream explode(x, y, dream); //you lose lose(); }); } There is nothing wrong with the example. I just need to add the feature for being able to rotate the character(angel) and face it toward the direction that it moves when it chases after the dream. (look at the sample link I provided. I need to modify that sample to do what I explained above) I have been trying to do this for a while now but have been unsuccessful. Hope someone can help. Thanks A: I would suggest have more than one image of the angel looking in various directions and display the one that is appropriate based on where she is headed on the screen (you'll have to determine this logic). function chase(x, y, dream) { // if angel is going left load the "looking left" image // angel.attr('src', 'angel_left.gif'); // if angel is going right load the "looking right" image // angel.attr('src', 'angel_right.gif'); //angel gets the dream angel.animate({ top: y, left: x }, 1000, function () { //explode the dream explode(x, y, dream); //you lose lose(); }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7611113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Soft keyboard enter key event handle I want to do some stuff on soft keyboard enter key press. See my code and output below. It executes twice, but I want it to be executed only once. How to fix it? public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); txt = (EditText)findViewById(R.id.txt); txt.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER) { Log.e("test","--------- on enter"); return false; } return false; } }); } A: The best way possible: if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) { Log.d(TAG, "enter_key_called"); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7611115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Getting year and week of year from PHP date() when week spans two years I have run into an interesting issue using PHP's date() function. Haven't had any luck locating a discussion of this on SO or using Google, but maybe someone else has run into the same issue before? I am trying to get the YEAR and the WEEK OF THE YEAR for a given timestamp. This is the code I am using: date("Y-\WW"); Which as of today correctly outputs: 2011-W39. The problem is when supplying a timestamp, if the timestamp in question is, for example, on January 3rd, 2011 (which was actually part of the "52nd week of 2010". PHP correctly returns W52, but it also returns 2011 as the year, instead of 2010. date("Y-\WW", 1294016400); Outputs: 2011-W52 Any idea on how to solve this problem? I should note that although in this case it would be easy to just compare that the strtotime() of the output is greater than the current time() and adjust, but I need a solution that will work for previous years as well (e.g. if the same thing happened for January 3rd 2010). A: Darn, apparently I didn't re-read the documentation closely enough, the letter o was added in PHP 5.1.0: From the documentation for date(): ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0) So my code should have been date("o-\WW");
{ "language": "en", "url": "https://stackoverflow.com/questions/7611120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Flex Incompatible Override, bug? I'm writing an extension to the Flex DataGridColumn class. I want to override the editable and sortable properties so that I can dispatch an event in the setter. So I looked up the method signature from the Adobe Docs (I'm using Flex 3.5 compiler): Language Version: ActionScript 3.0 Implementation public function get editable():Boolean public function set editable(value:Boolean):void public var sortable:Boolean I should be able to override both the setter for editable, and use a setter to override the functionality of sortable. in my code I have: public override function set editable(value:Boolean):void { super.editable = value; //code to dispatch event } and public override function set sortable(value:Boolean):void{ super.sortable = value; //code for event } However I get a #1023 error : Incompatible override. I've tried all sorts of combinations on the method signatures, but these are exactly the same as the ones in the docs above. What gives? Am I missing something obvious? EDIT: Apparently the documentation is not in line with the actual source code. Both editable and sortable are variables in DataGridColumn.as. Anyway I can override them with a setter/getter without modifying the base class? DataGridColumn.as Source: public var editable:Boolean = true; public var sortable:Booelan = true; A: You cannot override variable as property(get/set). BTW, editable and sortable became properties in SDK 4.0.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to format the results of a query using a Lambda Expression? Let's say I have this query I pass to a repository: var results = userRepository.Get(u => u.Username == "JDoe" && u.Password == "123456"); Now, let's say I create an expression to format the results a certain way: Expression<Func<User,string>> userDisplay = u => u.Firstname + " " + u.LastName + " - " + u.CompanyName So I may have to write my own extension, but something like this: var formatedResults = results.Format(userDisplay); Update: What about a more complicated solution to project the results into another object: public class SearchResult { object EntityId {get; set;} object Displaytext {get; set;} } So, using the same idea to use the specific display expression, what is a good way to project the results into the SearchResult object? A: you should be able to just call Update As noted in the comments Select doesn't accept an Expression argument. Unless userDisplay needs to be an expression it could just be updated as a delegate: Func<User,string>> userDisplay = u => u.Firstname + " " + u.LastName + " - " + u.CompanyName; var formatedResults = results.Select(userDisplay); Update Select allows you to transform whatever you are iterating over. Some examples of what you could do: var formattedResults = results.Select(x=> new SearchResult { EntityId = x.Id, DisplayText = userDisplay(x){); //anonymous type var formattedResults = results.Select(x=> new { EntityId = x.Id, DisplayText = x.ToString()});
{ "language": "en", "url": "https://stackoverflow.com/questions/7611125", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: RelativeLayout background image + color I have a RelativeLayout where I need to have a black background and a small image exactly in the middle of it. I used this code: <RelativeLayout android:id="@+id/bottomBox" android:layout_weight="4" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/bottom_box_back" android:layout_marginTop="4dp" /> where the @drawable/bottom_box_back is: <bitmap xmlns:android="http://schemas.android.com/apk/res/android" android:src="@drawable/logo_icon" android:tileMode="disabled" android:gravity="center" android:filter="true" /> In this way I have the image centered. But the background is still gray as the main window. I need a black back to the image spread all over the RelativeLayout space. Any suggestions? A: I would make the background of your RelativeLayout black and then put the Image into an ImageView and center that in the middle of the RelativeLayout, so: <RelativeLayout android:background="@color/yourBlackColor"> <ImageView android:layout_centerInParent="true"> </ImageView> </RelativeLayout> Hope this helps you A: Another option is to use a 9-patch image. You can actually have multiple stretchable areas on a 9-patch image so all you have to do is put the image you want centered in the middle area, and then surround it in the black you want as the background color. Then when declaring the stretchable areas, select the areas above, below, and to the left and right of your image as stretchable. When the app stretches the areas it stretches them evenly so the image will stay in the center as long as the stretchable areas are the same size. I know this already has an accepted answer but I thought this was another neat way of accomplishing the same thing without having to add another image view to the layout.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WPF Slider control (NullReferenceException) I'm trying to display the value of a slider control in a TextBlock. However I keep getting a NullRerferenceException when I try to load the dialog. public partial class GeneralSettingsDialog : Window { public GeneralSettingsDialog() { InitializeComponent(); } private void DistSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { DistTextBlock.Text = DistSlider.Value.ToString(); } } XAML: <TabItem Header="Miscellaneous" Name="tabItem1" Background="#FFF0F0F0"> <Grid Height="230" Background="#FFF0F0F0"> <TextBlock Height="23" HorizontalAlignment="Left" Margin="13,13,0,0" Name="textBlock1" Text="Spacing" VerticalAlignment="Top" /> <Slider Height="23" HorizontalAlignment="Left" IsSnapToTickEnabled="True" TickPlacement="BottomRight" Margin="13,35,0,0" Name="DistSlider" VerticalAlignment="Top" Width="100" Interval="1" Maximum="50" Minimum="1" ValueChanged="DistSlider_ValueChanged" /> <TextBlock Height="23" HorizontalAlignment="Left" Margin="111,35,0,0" Name="DistTextBlock" Text="TextBlock" VerticalAlignment="Top" /> </Grid> </TabItem> A: Not exactly sure why your way isn't working, I guess the controls are not fully initialized when the first value changed event is thrown. But you can do it that way directly in xaml without any code behind: in TextBlock bind directly to the slider's current value and remove the value changed event handler: Text="{Binding ElementName=DistSlider, Path=Value}" PS: When you attach to the slider's value changed event in codebehind after InitializeComponent() your approach should also work fine: public MainWindow() { InitializeComponent(); DistSlider.ValueChanged +=new RoutedPropertyChangedEventHandler<double>(DistSlider_ValueChanged); } private void DistSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { DistTextBlock.Text = DistSlider.Value.ToString(); } A: In your XAML you have the TextBlock DistTextBlock defined after DistSlider. When the XAML is loaded for the first time it will fire the ValueChanged handler and DistTextBlock will be null. You can protect against this in a few ways: // 1. Naive, but least changes to your code if (DistTextBlock != null) { DistTextBlock.Text = DistSlider.Value.ToString(); } There is @SvenG's excellent suggestion, which moves the logic to the XAML (no need for a ValueChanged handler): <TextBlock Text="{Binding Value, ElementName=DistSlider}" ... /> Lastly you could use a ViewModel (or any data context supporting INotifyPropertyChanged) to handle the passing to and from of the value. The important part of using the binding is it allows you to put any string formatting right alongside its usage in the XAML (say, if this slider was for a currency amount): <TextBlock Text="{Binding Value, ElementName=DistSlider, StringFormat={}{0:C}}" The last bonus of using a binding is coming out in .Net Framework 4.5, which allows you to specify a time delay prior to the binding updating its source. This would allow your GUI to seem more reactive if the binding is used in expensive operations. <Slider Value="{Binding DollarAmount, Delay=50}" ... /> <TextBlock Text="{Binding DollarAmount, StringFormat={}{0:C}}" ... />
{ "language": "en", "url": "https://stackoverflow.com/questions/7611130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: fopen() hangs. Sometimes I am running on Debian Etch: Linux nereus 2.6.18-6-686 #1 SMP Sat Dec 27 09:31:05 UTC 2008 i686 GNU/Linux I have a multi threaded c application, and one thread is hanging. Sometimes. Through core files, I have figured out that it is hanging on a fopen(): #0 0xb7f4b410 in ?? () #1 0xb660521c in ?? () #2 0x000001b6 in ?? () #3 0x00008241 in ?? () #4 0xb77c45bb in open () from /lib/tls/i686/cmov/libc.so.6 #5 0xb7768142 in _IO_file_open () from /lib/tls/i686/cmov/libc.so.6 #6 0xb77682e8 in _IO_file_fopen () from /lib/tls/i686/cmov/libc.so.6 #7 0xb775d8c9 in fgets () from /lib/tls/i686/cmov/libc.so.6 #8 0xb775fe0a in fopen64 () from /lib/tls/i686/cmov/libc.so.6 #9 0x0805600f in comric_write_external_track_file (control=0xbfc9c284) at ../COMRIC/comric_thread.c:784 #10 0x08055b0e in store_tracks (control=0xbfc9c284, hdr=0xb3d1b828) at ../COMRIC/comric_thread.c:695 #11 0x080568be in comric_thread (userdata=0xbfc9c284) at ../COMRIC/comric_thread.c:997 #12 0xb789530f in g_thread_create_full () from /usr/lib/libglib-2.0.so.0 #13 0xb783f240 in start_thread () from /lib/tls/i686/cmov/libpthread.so.0 #14 0xb77d349e in clone () from /lib/tls/i686/cmov/libc.so.6 This thread gets data from an external source, processes it, and writes it to a text file. The text file is being written over and over and over again, as we get new data. No one else is accessing this file. The file size is typically less than 1KB. I am checking the fclose() call to make sure it is returning success, and it is. When the main thread detects that we haven't heard from the problem thread in more than 30 seconds, it calls abort() so we can get the core dump you see above. 99% of the time, everything runs smoothly. But in the last four days, this is been happening more and more (6+ times a day). I worried that it might be a hard drive problem, but I cannot find any errors reported in any of the logs. (Unfortunately, SMART information is not available.) This application has been running smoothly for 2 years. Anyone have any thoughts? Source code: int comric_write_external_track_file( struct ComricControl *control ) { FILE *file; if( strlen( control->extern_track_file ) == 0 ) return 1; file = fopen( control->extern_track_file, "w" ); if( !file ) { ps_slog( "ERROR opening external track file: \"%s\"", control->extern_track_file ); return 0; } // Write the file G_MUTEX_LOCK( control->mutex ); g_hash_table_foreach( control->tracks, comric_write_track, file ); G_MUTEX_UNLOCK( control->mutex ); fsync( fileno( file )); if( fclose( file ) != 0 ) { ps_slog( "FATAL ERROR - fclose() FAILED with error \"%s\" (%d)", strerror( errno ), errno ); sleep( 1 ); abort(); // can we get any debug info out of this? } return 1; } I added the fsync() call after doing some hunting on the net. At first, I thought this might be related to the fclose() failing, but it doesn't seem to be the case. A: You're hanging in open() - so this is likely a problem at the kernel or driver level. First, check dmesg for obvious error messages. If this fails, you can try useing the SysRq w command to get a stacktrace of the offending process.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: NIO Performance Improvement compared to traditional IO in Java I have seen many articles/blogs saying that Java NIO is a better solution compared to traditional Java IO. But today one of my co-worker showed me this blog http://mailinator.blogspot.com/2008/02/kill-myth-please-nio-is-not-faster-than.html. I am wondering whether anyone from the Java community has done this kind of benchmarking related to Java NIO performance. A: The problem with the article is it compares blocking IO vs non-blocking NIO. In my own tests comparing blocking IO vs blocking NIO (more like for like) NIO is up to 30% faster. However unless your application is trivial, like a proxy server, its is unlikely to matter. What the application does is far more important. Both IO and NIO have been tested with up to 10,000 connections. If you want super fast IO you can use Asynch IO (Java 7+) with Infiniband (not cheap, but lower latency) A: NIO vs IO is a pretty fun topic to discuss. It's been my experience that the two are two different tools for two different jobs. I have heard of IO being referred to as the 'Thread per Client' approach and NIO as the 'One thread for all Clients' approach and I find the names, while not 100% accurate, to be fitting enough. The real issue with NIO and IO, as I see it, is with scalability. An NIO network layer will (should?) use a single thread to handle the selector and dispatch read/write/accept jobs to other thread(s). This allows the thread handling the selector (the 'Selector Thread') to do nothing but just that. This allows for much faster response when dealing with a lot (note the lack of actual numbers) of clients. Now, where NIO starts to fall apart is when the server is getting so many read/write/accept that the Selector Thread is constantly working. Any additional jobs past this and the server starts to lag. Additionally, since all read/write/accept jobs are processed by the Selector Thread, adding additional CPUs to the mix will not improve performance. An IO network layer will likely take the approach of 1 thread per socket, including the listening socket. So the number of threads is directly proportional to the number of clients. Under a moderate amount of clients, this approach works really well. The cost that one pays by using this approach comes in the form of the cost of a thread. if you have 2000 clients attached to a server... you have at least 2001 threads. Even in a quad chip, 6 core per chip machine, you only have 24 processing nodes (48 if you count HyperThreading) to handle those 2001 threads. Instantiating all those Threads costs cpu time and ram, but even if you use Thread Pooling, you still have to pay the cost of the CPUs context switching as they move from thread to thread. This can get very ugly at high server loads, and, if not coded properly, can grind the entire machine to a halt. On the plus side, adding CPUs to the machine WILL improve performance in this case. Now all that is well and good, but is in the abstract because there's no numbers in my description to aid in making a decision to go with IO or NIO. This is because there's even more variables to consider: * *Life time of a client? Short or long? *Amount of data expected per client? Lots of small chunks or few huge chunks? *Just how many clients are expected to be connected simultaneously? *What OS are you on and what JVM are you using? Both factor into Thread and polling costs. Just some food for thought. To answer the question of which is faster, NIO or IO: Both and neither :) A: The article you cite is three years old. It used Java 1.4.2 (4). Since then Java 5, 6, and now 7 are out. Huge changes inside of the JVM as well as the class library have rendered anything having to do with benchmarking of 1.4.2 irrelevant. If you begin to dig, you'll also note that the distinction between java.io and java.nio isn't quite so clear. Many of the java.io calls now resolve into java.nio classes. But whenever you want increased performance, the solution is not to just do any one thing. The only way to know for sure is to try different techniques and measure them, because what's fast for my application isn't necessarily so for your application, and vice-versa. NIO might well be slower for some applications. Or it might be the solution to performance problems. Most likely, it's a little of both. A: Also, AFAIK, Java IO was rewritten to use NIO under-the-covers (and NIO has more functionality). Microbenchmarks are just a bad idea, particularly when they're old, as lavinio states. A: A is faster than B is often a very simplistic view and sometimes plain wrong. NIO is not automatically faster than plain IO. Some operations are potentially faster using NIO and you can scale to many network connections much easier with NIO (because you don't need one thread per connection). But NIO is not a magic "make stuff faster"-switch that needs to be applied to everything. A: NIO is used not because it's faster but because it has better scalability especially there are amounts of clients. IO (Blocking IO/Stream IO) is usually one thread per connection to get better response to the clients. Suppose you use single thread to (blocking)listen/(blocking)read/process/(blocking)write for all the clients, just like Starbucks serves all the customers in a single window, Starbucks customers (your clients) would get impatient (timeout). Note you may think about thread pool to avoid huge number of threads drag down your server. While it just like Starbucks lines all the customers into several windows, the customers are still delay because of other's blocking. So that's why one thread per connection is a good choice in tradition java IO programming. NIO (None Blocking IO/Block IO which one to use) uses Reactor Pattern to handle IO events. In this case, you could use single thread to blocking/listen|read|process|write. Then the clients blocking (waiting period) would not affect each other. Note both IO and NIO can use multiply-threads to utilize more cpu-resources, more details in Doug lee's introduction. A: Java NIO is considered to be faster than regular IO because: * *Java NIO supports non-blocking mode. Non-blocking IO is faster than blocking IO because it does not require a dedicated thread per connection. This can significantly improve scalability when you need to handle lots of simultaneous connections, as threads are not very scalable. *Java NIO reduces data copying by supporting direct memory buffers. It is possible to read and write NIO sockets without any data copying at all. With traditional Java IO, the data is copied multiple times between the socket buffers and byte arrays. A: Java NIO and the reactor pattern are not much about networking performance itself, but about the advantages that the single-threaded model can deliver to a system in terms of performance and simplicity. And that, the single-threaded approach, can lead to dramatic improvements. Take a look here: Inter-socket communication with less than 2 microseconds latency A: There is no inherent reason why one is faster than the other. The one-connection-per-thread model is currently suffering from the fact that Java thread has a big memory overhead - thread stack is preallocated to a fixed (and big) size. That can be and should be fixed; then we can cheaply create hundreds of thousands of threads. A: Java IO encomapsses several constructs and classes. You cannot compare on such general level. Specifically , NIO uses memory mapped files for reading - This is theoretically expected to be slightly faster than a simple BufferedInputStream file reading. However , if you compare something like a RandomAccess file read , then NIO memory mapped file will be a lot faster.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: glutBitmapString() was not declared in this scope when i try to plot some strings with the following code: // label min and max for current vector glRasterPos2f(nx+1,y1); glutBitmapString(GLUT_BITMAP_8_BY_13,"min"); glRasterPos2f(nx+1,y2); glutBitmapString(GLUT_BITMAP_8_BY_13,"max"); i get the error error: ‘glutBitmapString’ was not declared in this scope upon compilation. the crazy thing is that // label min and max for current vector glRasterPos2f(nx+1,y1); glutBitmapCharacter(GLUT_BITMAP_8_BY_13,'1'); glRasterPos2f(nx+1,y2); glutBitmapCharacter(GLUT_BITMAP_8_BY_13,'2'); compiles just fine, so it's not like i have not included the glut library or anything (i have glutSwapBuffers() and a bajillion other glut calls as well!) why on earth won't glutBitmapString() compile? i have checked the spelling and everything, and it just won't compile! A: just add one line: #include < GL/freeglut.h> This function is a new function added by freeglut which is not exited in glut A: What implementation of Glut are you using? According to the FreeGlut documentation, the original Glut does not include glutBitmapString http://freeglut.sourceforge.net/docs/api.php#FontRendering And indeed, there is no mention of glutBitmapString in the Glut documentation http://www.opengl.org/resources/libraries/glut/spec3/node75.html#SECTION000110000000000000000 If you really need to use this function it looks like you will need to use FreeGlut.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }