text
stringlengths
8
267k
meta
dict
Q: Building GSL (GNU Scientific Library) in Windows for use with VS2005 I'm trying to get GSL working in a windows environment for my team and I'm running into many problems. My team develops in C++ in VS2005, and we'd like to use GSL. I've downloaded the GSL-1.15 tar.gz, and unzipped it, but i'm not really sure what to do from here - I believe only two compilers will build it properly. On the GNU website, it says that a compiled version of GSL is available as part of Cygwin on windows, so I installed Cygwin, but again, I'm not really sure what to do from there. Ideally, what I'm trying to get is a folder on my C:\ with a bunch of dll / libs that I can link to in VS2005 to use the GSL functions. I'm aware of GSL ports to VS (http://gladman.plushost.co.uk/oldsite/computing/gnu_scientific_library.php), but we can't rely on them as I would be dependent on the publisher releasing a port every time a new version of GSL is released. Has anyone successfully gone through this process of building GSL and getting it to work with C++ in VS2005? I've done some google searches and haven't found anything that I understand. Thank you. A: With Cygwin Install one or more of the GSL packages gsl gsl-apps gsl-devel gsl-doc With MinGW I have personally built GSL with MinGW using this incantation wget ftp.gnu.org/gnu/gsl/gsl-1.15.tar.gz tar xf gsl* cd gsl* ./configure # Warning, make takes about 7 min. make make install ref
{ "language": "en", "url": "https://stackoverflow.com/questions/7603106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: MongoMapper examine query How I can check which query will be send to the MongoDB server when I call a certain association on my model from the Rails console ? A: turn on MongoMapper logging in your connection string (typically in an initializer file): MongoMapper.connection = Mongo::Connection.new('localhost', 27017, :logger => Rails.logger) #the logger param does the trick
{ "language": "en", "url": "https://stackoverflow.com/questions/7603108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Symfony2 + DataFixtures + Capifony - FATAL ERROR Doctrine Proxies - Cannot redeclare unserialize() For 2 weeks i'm struggling with fallowing problem. Im using DataFixturesBundle to load my fixtures to database. Everything works fine. I decided to use capifony (capistrano) to deploy my application on production. That went well too. I have implemented all things i wanted capifony to do for me with my app on production server. But I do get one error and I dont even know what bundle is causing that. IMPORTANT This error only shows on production server, it does NOT matter if i'm on DEV or PROD environment ( also DEBUG ), but the error never shows on my local hosts (tested on 2 computers, mac & win ). Fatal error: Cannot redeclare Proxies\TestBundleEntityPartnerProxy::unserialize() in /public_path/testapp.com/app/releases/20110929191120/app/cache/dev/doctrine/orm/Proxies/TestBundleEntityPartnerProxy.php on line 489 And that is right. Doctrine makes two the same methods both for unserialize() and both for serialize() in the same class (proxy). This only happens on my production server. I can't even make the problem shows on my local host. On my local host there are no two methods with the same name (unserialize() and serialize()). There is one unserialize() and one serialize() Any help would be appreciated. Cheers, Bart A: fixed here: https://github.com/doctrine/doctrine2/pull/177 A: This is not capifony, but some edge case bug or situation. I'm not sure what's causing it yet. Some details here: http://groups.google.com/group/symfony-devs/browse_thread/thread/435a19119e9d6bdb
{ "language": "en", "url": "https://stackoverflow.com/questions/7603111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a way to get the bounds of a TabPage in a Winforms TabControl? I have a Form with only a single TabControl, with many tabs, where each tab has only square buttons side by side. I am trying to make it so that when the user clicks on a tab, the form resizes itself to a size where you can see all the buttons in a particular tab or a size where you can see all the tabs, whichever is greater. I am just curious if there is a way to query where the last control in a tab page is? So I can just do something like: tabForm.Width = currentTabPage.UsedContentBorder + 10; Or do I have to do this by adding all the controls and the sizes between them, etc? A: You want to find out the maximum coordinates of all controls in a specific tab? Easy with LINQ: int right = tab.Controls.Cast<Control>().Max(c => c.Right); int bottom = tab.Controls.Cast<Control>().Max(c => c.Bottom); Now, to properly choose the size of the form, I imagine you just have to figure out how much larger the Form is than its TabPages... I would guess something like this: int extraWidth = form.Width - tabControl.SelectedTab.Width; int extraHeight = form.Height - tabControl.SelectedTab.Height; Then you just do form.Size = new Size(right + extraWidth, bottom + extraHeight); (the TabControl will resize automatically if its Anchor property is set to all four sides.) It occurs to me that this may malfunction if the user resizes the form very small... you may be able to compensate by calculating extraWidth and extraHeight in the Form.Load event and then saving those values for when you need them later.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: When should I use Satellite Assemblies when it comes to localization? And When should I use Resources Files(.resx)? I'm creating a windows appplication in which I wanna do some localization. That application will also use a DLL that might use a different language(CultureInfo) than the main application. Which one of those two localization concepts applies best to my case? A: I don't quite think you understand .Net's localization model. Actually, when you add resx file to your project in Visual Studio and set language (change from Default to something else), not only it will automatically create language copy of your Default (invariant) resource file, but will also create Resource Managers to load data from Satellite Assemblies behind the scenes. Go ahead and try it by yourself. You should observe some language-based subdirectories with satellite assemblies in your output directory. Therefore your question quite does not make sense.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Position div to make it visible while scroll If I have a div with an overflow property and a wide (many columns) table within that div how would I position another element inside the first container that will remain visible withing the div as I scroll to the right/left while I view table data? <div id="mainContainer" style="width:300px; overflow-x:auto"> <div id="floatingContainer" style="border: 1px solid #ccc">Stay in the middle</div> <table> <tr> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> </table> </div> Can it be done with CSS only or do I need to add some jQuery? I guess it's something like position: fixed except relative to the div that I place it in... A: Maybe like this? http://jsfiddle.net/eeRMV/7/ I didnt get it to work without the use of specific height attributes. But some1 with more experience probably knows a way to do this without adding a specific height attr. to the three elements (#mainContainer,#floatingContainer,table). A: Put your table in a div for whom who set width and height and with css property overflow: auto. That should give you the expected result <div id="mainContainer" style="width:300px; overflow-x:auto"> <div id="floatingContainer" style="border: 1px solid #ccc">Stay in the middle</div> <div style"height:100px;overflow: auto"> <table> <tr> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> </table> EDIT: If you want a scrollbar on your whole container you can go the jQuery way. var floatingContainer = $('#floatingContainer'); $('#mainContainer').scroll(function(event) { floatingContainer.css('margin-left', event.currentTarget.scrollLeft); }); Here is a demo on jsFiddle.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603125", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: scripting or programming language? Possible Duplicate: When is a language considered a scripting language? what is the difference between programming and scripting languages? I have worked on C/C++ for a while and now I started looking at Python, I was told it is a good scripting language this post. But as I'm learning, I'm finding that everything that can be done with C till now can be done with Python! so what is the actual true difference between scripting and programming languages? A: I actually believe the question is a bit misleading. Of course a scripting language is also a programming language. But there are differences: Between Compiled and Interpreted Languages. Traditionally a language like c is compiled into machine code that can be understood directly by a cpu. A "script language" on the other hand usually is not being compiled into machine code before execution but interpreted using an interpreter. The advantage of an interpreted language usually is that it has a faster development cycle because no compilation is necessary and it is easier to move from one platform to another. E.g. python scripts can be executed on windows, linux, mac without changes. The advantage of a compiled language on the other hand is that it executes usually much faster. I used "usually" and "traditionally" very often because there are now technologies that make it much harder to draw the line. E.g. it is possible to compile python code directly into native code and there are also interpreters for c code. Also "Just In Time" compiler and virtual machines make it harder to draw here black and white. More: http://en.wikipedia.org/wiki/Interpreted_language Duck-Typed and Strong-Typed Languages Usually script languages are duck-typed which means that a variable can be assigned any type and there is no or only optional checking of types. In compiled languages on the other side like C and C++ every variable is typed and it can and will only hold values of that type. The advantage of a duck-typed language is usually that it requires less physical typing and less code (e.g. type names can be left of function declarations etc...) and it is easier to write reusable functions. The advantage of a strong-typed language usually is that it "helps" the programmer finding bugs before running the application. E.g. the compiler would complain about type errors without the need to run the concrete line where the error is happening. Especially in big projects with many contributors this can become an amazing advantage. More: http://en.wikipedia.org/wiki/Duck_typing
{ "language": "en", "url": "https://stackoverflow.com/questions/7603131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Monodroid - passing data to ListView according to GREF limit C#, Mono for Android. I need to output a large portion of combined data into ListView. To achieve this, I use the following obvious approach with Adapter: class ItemInfo { public string Id; public string Name; public string Description; public int Distance; //Some more data } class ItemAdapter : ArrayAdapter<ItemInfo> { public WorldItemAdapter (Context context, int textViewResourceId, List<WorldItemInfo> items) : base(context, textViewResourceId, items) { } //... public override View GetView (int position, View convertView, ViewGroup parent) { //Some stuff to format ListViewItem } } public class OutputActivity : Activity { ListView _listView; //... void FillList (object SomeParameters) { var adaptedList = someDataSource.Where().Join().Union().//anything can be imagined .Select ((item, item2, item3) => new ItemInfo (){ Id = item.Id, Name = item.Name, Description = String.Format(..., item2, item3), Distance = ..., //so on } ).OrderBy ((arg) => arg.Name).ToList (); _listView.Adapter = new ItemAdapter (this, Resource.Layout.ListItemFormat, adaptedList ()); } } This works very fine... until I start to refresh my ListView frequently. If I generate many ItemInfo's (by refreshing my view, for example), I reach GREF limit soon (described here, "Unexpected NullReferenceExceptions" section), and my application crashes. Looking into Android log, I can see thousands of Android.Runtime.IJavaObject objects, which overflow GREF limit. According to concepts of Mono VM + Dalvik VM bridge I can understand, that my ItemInfo's need to be passed to Dalvik VM, wrapped to IJavaObject and to be formatted in ListView by native environment - this creates GREF's. As long as garbage collecting is a non-determined process, if I call FillList() many times, old, already used ItemInfo's stay into memory, leaking. How can I avoid leaking? Or, possible, is there another way to output large portions of formatted data into ListView? I tried: * *I can't reduce the number of ItemInfo's, as long as I need to place my data somehow. *I can't follow this advice, as long as my ItemInfo is not an IJavaObject. *As a temporarily solution, I call GC.Collect() every time I need to refresh list, but this looks not a clean way. Also, if I need to output more than 2к objects into list, this doesn't help. A: In my project i had the same problem. * *ItemInfo is managed object, so you don't need to do anything with it, GC collects when it will be necessary. *ListView does not load view for each list item at once, so you can control number of created views and dispose them. Here is my solution I have removed some unnecessary overrides from BaseAdapter so don't be afraid if it ask you to implement them. class CustomViewAdapter : BaseAdapter<ItemInfo> { private readonly Context _context; private IList<ItemInfo> _items; private readonly IList<View> _views = new List<View>(); public CustomViewAdapter(IntPtr handle) : base(handle) { } public CustomViewAdapter (Context context, IList<ItemInfo> objects) { _context = context; _items = objects; } private void ClearViews() { foreach (var view in _views) { view.Dispose(); } _views.Clear(); } public override View GetView(int position, View convertView, ViewGroup parent) { var inflater = LayoutInflater.From(_context); var row = convertView ?? inflater.Inflate(Resource.Layout.ListItemView, parent, false); /// set view data if(!_views.Contains(row)) _views.Add(row); return row; } public override int Count { get { return _items == null ? 0 : _items.Count; } } public override void Dispose() { ClearViews(); base.Dispose(); } } Usage example [Activity] public class MessagesActivity : Activity { private CustomViewAdapter _adapter; protected override void OnCreate(Android.OS.Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.ListView); _adapter=new CustomViewAdapter(this,Enumerable.Empty<ItemInfo>); FindViewById<ListView>(Resource.Id.list).Adapter=_adapter; } public override void Finish() { base.Finish(); if(_adapter!=null) _adapter.Dispose(); _adapter=null; } } A: Answer found. I've inherited my ItemInfo class from Java.Lang.Object explicitly and now can call Dispose() when object is no longer needed. This kills leaking GREFs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make a JTable Column changes it color According to Specific Values from the Database I'm Building a Client/server Desktop Application. I wanted to know if it is possible to make a JTable Column Changes its color according to specific values from the database (oracle). * *Red= "Refused". *Green="Accepted". *yellow="Quarantine". A: Use an appropriate renderer. A: Use a custom column renderer for this: public class ColorColumnRenderer extends DefaultTableCellRenderer { Color bkgndColor, fgndColor; public ColorColumnRenderer(Color bkgnd, Color foregnd) { super(); bkgndColor = bkgnd; fgndColor = foregnd; } public Component getTableCellRendererComponent (JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component cell = super.getTableCellRendererComponent (table, value, isSelected, hasFocus, row, column); cell.setBackground( bkgndColor ); cell.setForeground( fgndColor ); return cell; } } You can use that renderer like this (example for a single column): TableColumn tm = table.getColumnModel().getColumn(0); tm.setCellRenderer(new ColorColumnRenderer(Color.lightGray, Color.blue)); Once you have the color changing code you can create a listener which listens for the value changes to the table model and by checking the changes you can apply the colors you want to specific columns.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iPhone App Running Slower on Simulator I am currently working on an iPhone app where I use 2 main timers that make the game work as one piece. The only problem I've encountered so far is that when I run it on the iOS Simulator from Xcode the game seems to lag a bit, and all of the animations run slower. I'm not sure if this is a memory issue, but isn't the iOS Simulator supposed to run just as smooth as the iPhone? When I run it on my iPod Touch 4th Generation, I don't encounter this problem. Is there a way I can fix this, or does anyone know why this happens? A: The frameworks are designed to work with specific hardware on device for graphics acceleration. This is not present in the simulator, so you'll see diminished performance on graphics-intensive applications. You might however see increased performance in the simulator in non-graphics related areas. The bottom line is always test on real hardware - the simulator is just a convenience.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Disable arrow keys from scrolling only when user is interacting with I have added an event listener in JS to listen for keyup/keydown events, I am attempting to move a sprite across the HTML canvas. I have that mostly working, but the page is being scrolled when the user presses the arrow keys. I am returning false, and that does not seem to work. In addition, my understanding is that returning false in this manner would disable arrow button scrolling for the entire page. I would like to only disable this while the user is interacting with the canvas itself. Here is my event listener: addEventListener('keydown', function(e){ move = false; x = false; y = false; var keycode; if (window.event) keycode = window.event.keyCode; else if (e) keycode = e.which; switch(keycode){ case 37: move = true; x = 'negative'; break; case 38: move = true; y = 'negative' break; case 39: move = true; x = 'positive' break; case 40: move = true; y = 'positive' break; } if(move){ animation.move(x,y); } return false; }) Edit: The below answer has a good idea of how to make sure that the canvas is focused, but I am still puzzled why returning false in my EventListener function which returns false is not disabling scrolling. A: As long as you are giving your canvas focus somehow (ie canvas.tabIndex = 1;) then you can just add e.preventDefault() right before your return false and it will work. Example: http://jsfiddle.net/faAkN/ A: I had a similar problem, and came up with a fix. Here's what I came up with: function $(){ return document.querySelector.apply(document,arguments); } var canvas = $('canvas'), keysDown = []; // You can also define this as an object, {} canvas.tabIndex = 0; canvas.onclick = function(e){ document.body.scrollTop = canvas.offsetTop; // scrolls to canvas element canvas.focus(); // re-focuses canvas in case the scroll unfocused it } canvas.onkeydown = canvas.onkeyup = function(e){ keysDown[e.keyCode] = e.type == 'keydown'; e.preventDefault(); return false; } function isDown(key){ return keysDown[key]; } function resetMap(){ keysDown = []; return false; } To check if a key is down, use isDown(keycode) either in an interval loop or in a keydown function. For a regular key listener: canvas.onkeydown = canvas.onkeyup = function(e){ // [...] if(isDown(17) && isDown(32)){ // Ctrl + Space alert('Ctrl and Space were pressed'); resetMap(); } e.preventDefault(); return false; } For a rapid key listener similar to ActionScript 2.0's Key.isDown function KeyLoop(){ if(isDown(17) && isDown(32)){ // Ctrl + Space console.log('Lots of text'); resetMap(); } setTimeout(keyLoop,1000/24); // @ 24 fps } keyLoop(); I put a different action here for two reasons: 1) Mixing alert() with a repeating interval is never a good idea, and 2) to demonstrate the lack of delay, which is what makes this similar to the AS2 Key.isDown() function. To see the logged text, bring up firebug or a regular JavaScript console. In Chrome, that's CtrlShiftJ. In Firefox, CtrlShiftK. This should fix your scrolling problem by focusing on the element when you click the canvas. An added benefit is that you can check for multiple keys at once since you're using keysDown[] as an abstraction from the original event, making an 8-directional game easy to make. A: Have you tried something like this? <script type="text/javascript"> canvas_active = false; </script> <canvas onfocus="javascript: canvas_active = true;" onblur="javascript: canvas_active = false;" /> Then in your current method check to see if the canvas_active is true and if so, return false, else return true. This would only work if the canvas is focused the whole time they are moving it, of course.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Preserving part of a canvas When drawing on a HTML5 canvas element, is it possible to leave part of it untouched? Can you take part of the image, and then redraw that part if its not directly possible? The only solution I have thought of is to draw to a seprate, smaller canvas and then copy that over to the main canvas. Is this a feasible approach? I wish to draw a game scene while preserving the ui. Unfortunately, the draw order is not known in advance. A: I guess you're looking for .clip: http://jsfiddle.net/eGjak/122/. ctx.rect(100, 50, 200, 100); // make a region ctx.clip(); // constrain to that region ctx.drawImage($("img").get(0), 0, 0); // draw image A: Draw the UI on another canvas. You can layer canvas elements if need be. HTML <div id="gameframe"> <canvas id="game-ui"></canvas> <canvas id="game"></canvas> </div> CSS #gameFrame { position: relative; width: 800px; height: 800px;} #game-ui { position: absolute; z-index: 10; bottom: 0; left; 0; height: 50px; width: 100%;} #game { position: absolute; z-index: 5; height: 100%; width: 100%;} Yields ------------------------------------------------------- - - - - - - - <canvas id="game"> - - - - - - - - - ------------------------------------------------------- - <canvas id="game-ui"> - ------------------------------------------------------- A: When creating Canvas games i've always layered the GUI on top of the game canvas. #ui{position: fixed; margin-left: auto; margin-right: auto; z-index: 1000; width: 500; height: 500} #game{position: fixed; margin-left: auto; margin-right: auto; z-index: 999} <div id="ui"><!--UI elements--></div> <canvas id="game" width="500" height="500"></canvas> Obviously you can layer another canvas on top, or build the UI using html elements.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: User cannot see TFS2010 test results in VS2010 I have a few lists of tests that I setup for a project that builds to a website. I have a bunch of unit tests and integration tests that runs before deploying the site. I have one user that clicks on the failed build in Build explorer but the Test results(that I can see-all test) that appears below that is empty. If I click on it I can see a complete list of tests that passed as well as the test that failed. In the "Test Results" window at the bottom there is a drop down list to choose the(it looks like environment??) and when they choose "System@SERVERNAME SERVERTIME" it does not show the list that I can see if I am logged in. It seems to be a permission issue but where? Thank you Jack
{ "language": "en", "url": "https://stackoverflow.com/questions/7603144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android Compressed Texture Loading (GL Extensions Missing) When trying to load an ATITC, S3TC, or PVRTC compressed texture in Java on Android (glCompressedTexImage2D), which GL constants should be set for the third parameter? For example...if I wanted to load a PVRTC texture that supports alpha. Am I supposed to use a constant that describes the format (but does not necessarily have the format in the name)? ex. GL_RGBA A: If anyone has problems with this..I finally find out how to accomplish this. After finding the extension documentation (ex. AMD_compressed_ATC_texture), the values of the various formats are listed under the section "New Tokens". Only if I had scrolled down the first time I saw the page..
{ "language": "en", "url": "https://stackoverflow.com/questions/7603147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: javascript unicode property from c# Im using this code: $(document).ready(function () { var breadCrumps = $('.breadcrumb'); breadCrumps.find('span').text("<%= ArticleSectionData.title %>"); }); title is a property which has values encoded in unicode (I think). These are Greek letters. On the local IIS developer server (embedded in visual studio), the characters are displayed in correct way but, on the test server they appear as: &#931; Do You know any solution for this problem ? Thanks for help EDIT: I have changed the code a little bit: breadCrumps.find('span').text(<%= ArticleSectionData.title %>); And now it works correctly, encoding is frustrating ... A: If you are working off of a different database in test than in dev, then I suspect the issue is with the data. If you are storing HTML entities (eg, &#931;) in your database, then you need to use .html(). If you are storing actual unicode characters (eg, Σ) in the database, then you need to use .text(). The way to represent Σ in html is with &#931;. But if you set the text of an element to &#931;, it displays that literally - the innerHTML of that element would contain &amp;#931;. A: I don't know root of problem, but you can use this http://www.strictly-software.com/htmlencode for decode &#931; to Sigma
{ "language": "en", "url": "https://stackoverflow.com/questions/7603152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Check credentials against an LDAP server Assume an application that can be configured to use an LDAP server - be it ActiveDirectory, or OpenLDAP etc. - for authenticating its users and retrieving some additional information about them for authorization purposes. The way the application binds to the LDAP server is also configurable - it can use a simple or a SASL bind, depending on what the LDAP server supports and the overall security requirements. It's assumed that if a bind succeeds with whatever credentials the user provided, then it must mean that those credentials are valid. However, that's not always the case; it can happen that a simple bind succeeds even though an empty password was provided where a non-empty one was in fact expected. According to the RFC about LDAP authentication methods a simple bind with a non-empty username and an empty password is interpreted as an intention to establish an unauthenticated connection, with anonymous authorization. The server can be configured to fail such attempts with unwillingToPerform, but it can also allow them. The question is: in such a scenario, where an application can be configured to use a variety of LDAP servers, and bind in a configurable way - simple or over SASL - is there a way to unequivocally check the credentials the user entered against that particular LDAP server, other than trying to bind with those credentials, given that a simple bind can lead to false positives? Thank you and I look forward to your replies. A: Surely all you have to do is disallow, or maybe even just remember, cases where the password was empty? A: In PHP, at least, you just have to do this: <?php $ds = ldap_connect($ip_address); if(@ldap_bind($ds, $username, $password) { // Login successful! } else { // Login unsuccessful :( } ?> Your mileage may vary with other languages, but this has worked for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to cope with extension-less source files and tools that rely on extension information? C++ code I'm working with is happily using the "no extension needed for header files" rule. This gives me a headache when using tools such as cscope and sloccount on directories containing these files, because these tools ignore extension-less files. Does anyone know a way to avoid this (except renaming the files or putting symlinks etc.)? A: Just rename the files to use normal convention so that future maintainers don't have headaches trying to figure out what code is where. The no-extension standard include files should be treated as the exception rather than the rule to follow, since the standard doesn't even guarantee they correspond to a physical file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603162", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does this query require dynamic sql? SQL Server I want to select the parameters of a stored procedure and then check whether each parameter is null or not in a loop. The problem I'm having is that when I want to evaluate the variable in the IF statement, it is not being evaluated correctly. I want to evaluate each parameter I stored in the table variable. I don't know the syntax for this...or maybe it isn't even possible? Does this require Dynamic SQL? If so, when executing dynamic sql, the value of the variable will be out of scope so how do I deal with that? I verified everything up to the IF statement works. CREATE PROCEDURE dbo.UpdateBank ( @BankKey [smallint] = NULL, @Bank [varchar] (30) = NULL, @BankCode [char] (4) = NULL, @MasterBankCode [char] = NULL, @Bin [char] (6) = NULL, @WebSite [varchar] (50) = NULL, @isActive [bit] = NULL, @CreateDate [smalldatetime] = NULL ) AS SET NOCOUNT ON SET ANSI_NULLS OFF DECLARE @MaxRow TINYINT, @Count TINYINT DECLARE @SPName VARCHAR (128), @CurrentRow TINYINT SET @SPName = OBJECT_NAME(@@PROCID) -- SP self-reference to find its current name DECLARE @SPParametersList TABLE (ID INT Identity(1,1) Primary Key, ParameterName NVARCHAR (128), DataType NVARCHAR (128), ParameterMode NVARCHAR (10)) CREATE TABLE #TempExec(ID INT Identity(1,1) Primary Key, Num BIT) INSERT INTO @SPParametersList (ParameterName, Datatype, ParameterMode) SELECT PARAMETER_NAME,DATA_TYPE,PARAMETER_MODE FROM INFORMATION_SCHEMA.PARAMETERS WHERE SPECIFIC_NAME = @SPName SET @CurrentRow = 1 SELECT @MaxRow = ISNULL(MAX(ID),0) FROM @SPParametersList WHILE @CurrentRow <= @MaxRow BEGIN IF ((SELECT ParameterName FROM @SPParametersList WHERE ID = @CurrentRow) <> NULL) BEGIN SELECT 'Success' SET @Count = @Count + 1 END SELECT 'Fail' SET @CurrentRow = @CurrentRow + 1 END SELECT @Count I always get 'Fail' when I run this stored proc A: Change your line: IF ((SELECT ParameterName FROM @SPParametersList WHERE ID = @CurrentRow) <> NULL) to IF ((SELECT ParameterName FROM @SPParametersList WHERE ID = @CurrentRow) IS NOT NULL) You also need to initialize the @Count variable to 0: SET @Count = 0 SET @CurrentRow = 1 SELECT @MaxRow = ISNULL(MAX(ID),0) FROM @SPParametersList A: I suspect that this is an example of a query that can be rewritten without the use of loops/cursors (most sql is in my experience...) Does the query below give you your desired results? with temp as ( SELECT '@BankKey' as ParamName UNION SELECT '@Bank' ) SELECT COUNT(*) as myCount FROM INFORMATION_SCHEMA.PARAMETERS as isp LEFT JOIN temp as t ON t.ParamName = isp.PARAMETER_NAME WHERE SPECIFIC_NAME = @SPName AND t.ParamName is null You should try to avoid using Loops/Cursors as much as possible. SQL Server (and most DBMSs in general) are excellent at performing Set based operations and terrible at performing row based operations (loops/cursors). A: Probably the issue is in the <> NULL which should IF EXISTS(SELECT ParameterName FROM @SPParametersList WHERE ID = @CurrentRow) but I'm not sure what you want to achieve with that piece of code... A: (1) "I always get 'Fail' when I run this stored proc": you have forget the ELSE branch IF ((SELECT ParameterName FROM @SPParametersList WHERE ID = @CurrentRow) /*<>*/ IS NOT NULL) BEGIN SELECT 'Success' SET @Count = @Count + 1 END ELSE -- << here BEGIN SELECT 'Fail' END SET @CurrentRow = @CurrentRow + 1 (2) To count all not null parameters: SELECT @Count=COUNT(*) FROM @SPParametersList a WHERE a.ParameterName IS NOT NULL To count all null parameters: SELECT @Count=COUNT(*) FROM @SPParametersList a WHERE a.ParameterName IS NULL Note: if you want to test for NULL / NOT NULL you should use column/@variable IS [NOT] NULL operator and SET ANSI_NULLS must be ON: SET ANSI_NULLS ON.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MVC validation in model requires database repository I'm writing an MVC app using the repository pattern. It is a financial system which has invoices in them. I have validation in the Invoice model: #region IValidatableObject Members public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if ((TotalExcludingTax + (TotalExcludingTax * .15m)) != TotalIncludingTax) { yield return new ValidationResult("The total (exc. Tax) + Tax does not equal the total (inc. Tax)."); } } #endregion The problem is the tax rate .15 is variable. At the moment it is hard coded in here which isn't much good. The only way I can think of doing this is: #region IValidatableObject Members public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { var taxRepository = new Repository<tax>(); if ((TotalExcludingGst + (TotalExcludingGst * taxRepository.GetCurrentTaxRate())) != TotalIncludingGst) { yield return new ValidationResult("The total (exc. Gst) + Gst does not equal the total (inc. Gst)."); } } #endregion Using this method I now am instantiating a taxRepository instance within the invoice model. Is this bad practice? Is there a better way of doing this? A: Yeah, your current approach isn't great and this is exactly the scenario that FluentValidator was built for. As an example, in one of our objects we have some PostCode validation that requires complex rules to determine if a postcode is valid so we do something like this: public class AddressValidator : AbstractValidator<Address> { private readonly IPostCodeRepository _postcodeRepo; public AddressValidator(IPostCodeRepository postcodeRepo) { _postcodeRepo = postcodeRepo; RuleFor(a => a.Postcode) .NotEmpty() .WithMessage("Postcode is required") .Must(BeValidPostcodeSuburbStateCombo) .WithMessage("Postcode is not valid for this state"); } private bool BeValidPostcodeSuburbStateCombo(Address model, string property) { return _postcodeRepo.ValidatePostcode(model.Postcode, model.Suburb, model.State); } } The advantage of this approach is that it keeps your models nice and clean and still allows you to validate complex logic. If switching to FluentValidator isn't an option for you, I would suggest putting an additional property on your model called TaxRate and setting it before the Validate method is called. It's not ideal, but it means you're not taking a dependency in the repository within your model.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is it possible to use FB Connect in an iframe on a 3rd party site? I have an iframe on a 3rd party site. Inside the iframe is my application, which users authenticate to using FB Connect. I am using the omniauth gem with my Ruby on Rails site to handle the connection to Facebook. It works seamlessly if a) you are already logged in to FB, and b) you have already given my site permission to use your details. If either of these are missing - at that moment where FB connect calls out to Facebook - it all stops, and I get the FB logo and a link to click through to Facebook. When I click the link - it takes me out of my iframe and into Facebook. Obviously once I return - there is no iframe to go back to and I am no longer on the 3rd party site - but on mine. Should this technique be possible? And if so - where might I be going wrong? As I said - if a) and b) are met - it works seamlessly. A: You can't do the redirect to Facebook from within an iframe, it has to be loaded into the top-level page. That's why you see the FB logo and link, it's there to force a breakout of the iframe structure. If you want to avoid that intermediate step, make sure you do a top-level redirect yourself (usually by outputting some javascript code that sets top.location). On the return side, you can either set redirect_uri to point to the 3rd-party site instead of directly to your site (or accepting the default redirect_uri which is probably doing that invisibly), or if that is impossible because of your app config on Facebook, detect that your page is being loaded into the top level and do a redirect to the 3rd-party site to force it back into the iframe.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603170", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is different between a static class that has static method, and a a regular class that has a static method? Example: public class person { public String Name {get;set;} } public static class FactoryStatic { public static person Create(string name) { return new person() {Name =name}; } } public class FactoryNoneStatic { public static person Create(string name) { return new person() {Name =name}; } } My question is what is difference between those two factory class, and when to use them? A: A static class can only contain static members. So you cannot create an instance of a static class. A: For the direct use, the creation of a Person object, there is no difference. It is however possible to create an instance of FactoryNoneStatic, which is probably not desirable. By marking the class as static you are clear about your intent and you prevent mis-use of the class. So in this situation, use the static class FactoryStatic. A: A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded. Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods. The main features of a static class are: They only contain static members. They cannot be instantiated. They are sealed. They cannot contain Instance Constructors. A static method, field, property, or event is callable on a class even when no instance of the class has been created. If any instances of the class are created, they cannot be used to access the static member. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events. Static members are often used to represent data or calculations that do not change in response to object state; for instance, a math library might contain static methods for calculating sine and cosine. I might be stating this wrong, but if you have a static class, it's usually because everything in that class can be static, and there's never a reason to maintain an instance of it. If you have static members of a non-static class, you still want to maintain state of that object (or at least carry an instance of it), but some methods that relate to it can be called without instantiating the class. A: In general not much. Marking the class as static makes it immediately obvious that it can only have static members. If a class isn't marked as static then the assumption is that there are non-static members. There's one situation that I'm aware of where you must use a static class is that extension methods are only allowed in static classes As for when to use them, if the class only contains static members, then mark the class as static to make it obvious. There may be some extremely minor performance differences, but I'd consider them negligible. A: A static class can have only static members in it. Also, it is not possible to create instances of a static class using the new keyword. On the other hand a static methodis callable on a class even when no instance of the class has been created. If any instances of the class are created, they cannot be used to access the static member. A: Simply a static class can not be instansiated ex: public static class StaticClass { public static void Function() { /* */ } } You can't do like this: StaticClass sc = new StaticClass(); You will do it like this: StaticClass.Function();
{ "language": "en", "url": "https://stackoverflow.com/questions/7603171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Updating Varchar Field So That Number Within Field is to 3 Decimal Places This is a fairly odd question... I believe it would involve some sort of regex with MySQL. Say I have a query on a table as such below: >select description from foo; ---------------------------------- | description | ---------------------------------- Kitten, 3 in., Lightsaber Mouse, 5.5 in., Luke Skywalker Dog, 9.000 in., Death Star Is there a way to update foo such that the "inches" (in.) portions are to three decimal places. i.e. After the update: >select description from foo; ----------------------------------- | description | ----------------------------------- Kitten, 3.000 in., Lightsaber Mouse, 5.500 in., Luke Skywalker Dog, 9.000 in., Death Star Any advice/guidance is greatly appreciated! Thanks. A: According to the documentation, that's not possible in a SELECT command. REGEXP only tells you if it's a match or not; it does not provide match indexes or substitution. You should export the data to a flat text file, treat it with your favorite Regex enable text editor and re-apply the data to a brand new data structure. Seriously, you have to change your DB design. Update After further investigation, it seems like my answer should be: it's not possible out of the box. Check this topic: How to do a regular expression replace in MySQL? You can do that via SQL through UDF.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Microprocessor vs discrete FET clock speed How do microprocessors achieve such high clock speeds when discrete FETs can only achieve approx 20MHz? Do they have a large number of parallel sequential logic systems? Thanks in advance. A: Single transistors can switch much faster than the clock of a microprocessor. One example: 45 GHz transistors by Infineon. Usually there are somewhere around 15-25 transistors in series in the longest path of a modern CPU, so the clock speed is at least an order of magnitude less than the switching speed of the individual transistors.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to submit the form via post and open the target page in an iframe I have a form which redirects to a new page index.aspx after posting .However instead of opening the new page in a new window,I would like to open it as an iframe so that it remains in the current window How do I go about that. The current code is : <form id="Form2" action="index.aspx" method="post" name="Form2" > ..... <input type="image" style="border-width: 0px;" src="images/form_ordernow_btn.jpg" tabindex="129" id="Form1_ImageButton1" name="Form1$ImageButton1" > I am using asp.net by the way A: Put the form into the iframe already. So the postback will open in the same iframe... @Edit: if the form must be on the same page but cannot be in the iframe at the time of posting, the following solution may work: * *postback to the same(!) page *insert the iframe into the page on the server *give the iframe an url according to the postdata i.e. change POST -> GET data *construct the target page (index.aspx) that way to handle the GET parameters
{ "language": "en", "url": "https://stackoverflow.com/questions/7603182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Add a new trusted CA to Netbeans SVN manager So I have a private SVN server for my company that has its own self signed certificate, it was signed by the company CA, I have the CA certificate and I want to add it to the list of default trusted CAs in the Netbeans SVN client. I have tried adding it to the windows trusted CA list and it works fine for the windows stuff, and I have added it to the JRE/JDK keystore using keytool and it works in eclipse but I can't seem to find any information on what keystore netbeans uses so I can add a new CA to it. Also the Accept Permanently option doesn't work so I can't use that either for some reason so I'd really like to learn how to add this cert to netbeans if anyone knows. Thanks in advanced. A: I had similar problem with NB 6.8/6.9. I am not sure whether it's the case with 7.0. I solved it by checking out the repo manually using command line client and picked the option "trust permanently" (not sure about the precise name). It creates certificate file in following location: $HOME/.subversion/auth/svn.ssl.server/ Use this file in NB svn dialog as "Client certificate file".
{ "language": "en", "url": "https://stackoverflow.com/questions/7603185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can't install glib with cabal on Windows - during the configure step On windows 7 x64, I tried: 1. install gtk+ all in one bundle 2.16 2. add MinGW's bin address to PATH Environment variables 3. add GTK+'s bin address to PATH Environment variables On command line execute the: cabal update cabal install gtk2hs-buildtools So far so good. But when I execute the: cabal install gtk the error arise gtk-0.12.1 depends on glib-0.12.1 which failed to install. I execute next command: cabal install glib Then I tried: cabal install glib --ghc-option=-DCABAL_VERSION_MINOR=10 Relults: Resolving dependencies... [1 of 2] Compiling SetupWrapper ( C:\Users\User\AppData\Local\Temp\glib-0.12 .16572\glib-0.12.1\SetupWrapper.hs, C:\Users\User\AppData\Local\Temp\glib-0.12.1 6572\glib-0.12.1\dist\setup\SetupWrapper.o ) [2 of 2] Compiling Main ( C:\Users\User\AppData\Local\Temp\glib-0.12 .16572\glib-0.12.1\Setup.hs, C:\Users\User\AppData\Local\Temp\glib-0.12.16572\gl ib-0.12.1\dist\setup\Main.o ) Linking C:\Users\User\AppData\Local\Temp\glib-0.12.16572\glib-0.12.1\dist\setup\ setup.exe ... Warning: .drectve `-aligncomm:___gmp_junk,2' unrecognized cabal: Error: some packages failed to install: glib-0.12.1 failed during the configure step. The exception was: C:\Users\User\AppData\Local\Temp\glib-0.12.16572\glib-0.12.1\dist\setup\setup.exe: runProcess: invalid argument (Exec format error) Help, thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/7603186", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Getting Time intervals between operations during parsing in iOS I am parsing an xml and I would like to know how I can keep track of the time it takes to do the same. I tried to use alerts, but it kept crashing my app due to the large number of alert popping up. Is it the same if I try to run my project on my iPAD through XCODE (i.e. by selecting target as my iPAD) and if I try to run the project when the iPAD is not connected to the mac? I ask this because, when I try NSLogging the times, it comes out on the Xcode. But I feel that is it not right. A: NSLog is supposed to show in XCode. It prints a log message to the system log, which, on the iPad you have no way of seeing on the device itself. If it were me, I'd do something like this: Store an NSDate variable before decoding the XML (probably as a property, since you're most likely doing XML decoding asynchronously) self.timingDate = [NSDate date]; Then, when the XML has finished decoding: NSLog(@"Time taken: %f", [[NSDate date] timeIntervalSinceDate:self.timingDate]); That will print out the amount of time spent decoding in seconds. A: You can use NSLog and run it while not connected to your XCode machine. Afterwards, y0u can connect it to XCode and read the console entries made while it was disconnected. Just go to the organizer and select your device's console. edit: You can also see the NSlog entries on the device itself by installing the Console app from the App Store.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603190", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails 3.1 authenticity_token + uploadify I am trying to use Uploadify with my Rails 3.1 app, i've went through all the steps (middleware, initializers, config ...etc) and i think they are all working good but for one thing, my authenticity token is being "evaluated" somewhere in the process and the (+) plus signs are then turned into spaces! .. my original token is <meta content="GS19lVJNr+/6ghijiM/hNZbo9a89I64nn1Sg+1zbqC8=" name="csrf-token" /> while the one that i see on the console is "authenticity_token"=>"GS19lVJNr /6ghijiM/hNZbo9a89I64nn1Sg 1zbqC8=" and this of course results in "Cant' verify authenticity token" error and then the request is redirected to elsewhere. any ideas on that? thank you. A: do you encode it? If you're using something like encodeURIComponent try it like so: encodeURI(encodeURIComponent(token)) or just try to encode/decode the token right in the firebug/chrome tools to see what's happening EDIT that's weird. Can you please show the entire scriptData you're sending? A: ...had the same problem in Rails 3.2.9 but in my case the reason was that I was using this middleware which is ment for Rails 3.0 , once I removed it it was working
{ "language": "en", "url": "https://stackoverflow.com/questions/7603193", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Setting correct time settings on Liferay The time on my Liferay install is incorrect. Where do I go to change the time settings? I have Liferay 6 running on Glassfish 3. Thanks! A: If it is question on incorret time zone go to Control panel -> Portal settings - Display settings and change zime zone.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how can I prevent Excel 2003 from checking every hyperlink in a document when the document opens? I have a spreadsheet that has several worksheets, each containing a hundred or so hyperlinks to other documents on our network (file:////server/share/path/to/spreadsheet.xls). Opening these files within Excel 2003 takes a very long time, compared to how long it takes to open in 2007 or 2010. I took a look in Task Manager at the network tab to see what was going on when these files are opened and noticed a lot of steady network traffic while the file was opening, and as soon as the spreadsheet finally displayed on the screen, the network traffic dropped down to almost nothing. As I removed some of those links, the file would open faster, until I finally got rid of all the links and the file opened almost as fast as any other normal spreadsheet. Is there a way to prevent Excel from doing whatever it's doing with those links when the file first opens? A: This is a programming-related forum so: Workbooks.Open AFile, False See: http://msdn.microsoft.com/en-us/library/ff194819.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7603196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: After copying my asp.net website I get 500 and 404 errors? Possible Duplicate: Database Deployment issues I followed the steps in this video: http://www.asp.net/iis/videos/developing-and-deploying-in-a-shared-hosting I just open my website on VS2010. then use the copy tool and I create a new directory and copy my web application into this new dir. the copy is done successfully but when I try to access it I get 500 for the main page which contain only some static menus and when I try to access any of my other pages it gives me a 404 error! I tried to add some sections to my web.config to handle the errors and show me what's exactly wrong as advised before but It won't give me any details! .. also when I try to remotely access my IIS I can only see the folder of my application but I can't see any files! and the icon for my application is a normal folder, I've seen some screenshots of an IIS of a deployed website and the folder icon is converted to an application icon. I've also tried to click on my application in IIS a right click > Deploy > Convert To Application. but it generates "An Error occurred when the request was processed on the remote computer. the server experienced an issue processing the request"! I've been trying to deploy my website for 3 days and posted three questions with no results! :S Problem Solved I've tried to speak to my provider again today and an agent advised me that I need to have my application on a virtual path to deploy it as an application. and it worked. But I marked Chris's answer as the correct one not because it's the only answer but has really stated some good points and I really appreciate his help. Thank you so much guys :) A: Well.. 404 means file not found. 404's won't be caught by the .net runtime, unless it's for a file with a regular .net extension like .aspx. 500 is an internal server error. Things I would investigate * *Can you deploy just a regular HTML file and load it? if this works, move to #2. If not then either you aren't pointed to the right machine or you aren't deploying your files to the correct location. *Can you deploy a very simple (nearly blank and self contained) .aspx file and load it? If this works, then .Net is installed. If not, then you need to figure that out. *Can you look at the file system to see if anything is actually there? If you aren't seeing it, then it didn't get deployed. *Is the appropriate version of the .Net framework installed on the remote computer? Basically, if your app is a .Net 4.0 app, then you need the 4.0 framework installed on the machine. *Is the app pool correctly configured for the correct .net framework version? Regardless of whether the correct version of the .net framework is installed, you still have to configure the website to use the right version of the .net framework. Some helpful hints. Don't deploy to c:\inetpub\wwwroot. wwwroot is a directory for the default IIS website and is usually not configured correctly. Just create another directory like c:\inetpub\myapp and deploy there. Also, make sure you disable the default website in IIS and create a new site (not a virtual directory) and point it to the correct location. I suspect that either you aren't deploying to the correct location and/or your iis settings are bad. Somewhere along the way on the above you ought to figure it out.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trouble tracking down a Bus Error/Seg Fault in C++ and Linux I have a program that processes neural spike data that is broadcast in UDP packets on a local network. My current program has two threads a UI thread and a worker thread. The worker thread simply listens for data packets, parses them and makes them available to the UI thread for display and processing. My current implementation works just fine. However for a variety of reasons I'm trying to re-write the program in C++ using an Object Oriented approach. The current working program initialized the 2nd thread with: pthread_t netThread; net = NetCom::initUdpRx(host,port); pthread_create(&netThread, NULL, getNetSpike, (void *)NULL); Here is the getNetSpike function that is called by the new thread: void *getNetSpike(void *ptr){ while(true) { spike_net_t s; NetCom::rxSpike(net, &s); spikeBuff[writeIdx] = s; writeIdx = incrementIdx(writeIdx); nSpikes+=1; totalSpikesRead++; } } Now in my new OO version of the program I setup the 2nd thread in much the same way: void SpikePlot::initNetworkRxThread(){ pthread_t netThread; net = NetCom::initUdpRx(host,port); pthread_create(&netThread, NULL, networkThreadFunc, this); } However, because pthead_create takes a pointer to a void function and not a pointer to an object's member method I needed to create this simple function that wraps the SpikePlot.getNetworSpikePacket() method void *networkThreadFunc(void *ptr){ SpikePlot *sp = reinterpret_cast<SpikePlot *>(ptr); while(true) { sp->getNetworkSpikePacket(); } } Which then calls the getNetworkSpikePacket() method: void SpikePlot::getNetworkSpikePacket(){ spike_net_t s; NetCom::rxSpike(net, &s); spikeBuff[writeIdx] = s; // <--- SegFault/BusError occurs on this line writeIdx = incrementIdx(writeIdx); nSpikes+=1; totalSpikesRead++; } The code for the two implementations is nearly identical but the 2nd implementation (OO version) crashes with a SegFault or BusError after the first packet that is read. Using printf I've narrowed down which line is causing the error: spikeBuff[writeIdx] = s; and for the life of me I can't figure out why its causing my program to crash. What am I doing wrong here? Update: I define spikeBuff as a private member of the class: class SpikePlot{ private: static int const MAX_SPIKE_BUFF_SIZE = 50; spike_net_t spikeBuff[MAX_SPIKE_BUFF_SIZE]; .... } Then in the SpikePlot constructor I call: bzero(&spikeBuff, sizeof(spikeBuff)); and set: writeIdx =0; Update 2: Ok something really weird is going on with my index variables. To test their sanity I changed getNetworkSpikePacket to: void TetrodePlot::getNetworkSpikePacket(){ printf("Before:writeIdx:%d nspikes:%d totSpike:%d\n", writeIdx, nSpikes, totalSpikesRead); spike_net_t s; NetCom::rxSpike(net, &s); // spikeBuff[writeIdx] = s; writeIdx++;// = incrementIdx(writeIdx); // if (writeIdx>=MAX_SPIKE_BUFF_SIZE) // writeIdx = 0; nSpikes += 1; totalSpikesRead += 1; printf("After:writeIdx:%d nspikes:%d totSpike:%d\n\n", writeIdx, nSpikes, totalSpikesRead); } And I get the following output to the console: Before:writeIdx:0 nspikes:0 totSpike:0 After:writeIdx:1 nspikes:32763 totSpike:2053729378 Before:writeIdx:1 nspikes:32763 totSpike:2053729378 After:writeIdx:1 nspikes:0 totSpike:1 Before:writeIdx:1 nspikes:0 totSpike:1 After:writeIdx:32768 nspikes:32768 totSpike:260289889 Before:writeIdx:32768 nspikes:32768 totSpike:260289889 After:writeIdx:32768 nspikes:32768 totSpike:260289890 This method is the only method where I update their values (besides the constructor where I set them to 0). All other uses of these variables are read only. A: I'm going to go on a limb here and say all your problems are caused by the zeroing out of the spike_net_t array. In C++ you must not zero out objects with non-[insert word for 'struct-like' here] members. i.e. if you have an object that contains a complex object (a std string, a vector, etc. etc.) you cannot zero it out, as this destroys the initialization of the object done in the constructor. A: This may be wrong but.... You seemed to move the wait loop logic out of the method and into the static wrapper. With nothing holding the worker thread open, perhaps that thread terminates after the first time you wait for a UDP packet, so second time around, sp in the static method now points to an instance that has left scope and been destructed? Can you try to assert(sp) in the wrapper before trying to call its getNetworkSpikePacket()? A: If you are allocating the spikeBuff array anywhere then make sure you are allocating sufficient storage so writeIdx is not an out-of-bounds index. I'd also check that initNetworkRxThread is being called on an allocated instance of spikePlot object (and not on just a declared pointer). A: It looks like your reinterpret_cast might be causing some problems. When you call pthread_create, you are passing in "this" which is a SpikePlot*, but inside networkThreadFunc, you are casting it to a TetrodePlot*. Are SpikePlot and TetrodePlot related? This isn't called out in what you've posted.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: CSS gets all screwed up in IE(like half of the CSS didn't get loaded) I have a site that gets completely screwed up in IE, and I was wondering if anyone could help me track down what's wrong with it. The page in question is http://eksai.com/testing/ When I open it in IE it's like half the CSS code didn't get loaded. Font colors are the same, there are no columns, etc. I've cut the CSS file to a minimum trying to figure out what's causing this...but I still can't get it to work right. Can anyone help me figure out what's causing it? here is the CSS file: html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td{margin:0;padding:0;border:0;font-size:100%;font:inherit;vertical-align:baseline} a img{border:none} @font-face{font-family:"agb";src:url("../fonts/b.eot");src:url("../fonts/b.eot?#iefix") format("eot"),url("../fonts/b.ttf") format("truetype")} body, input,textarea,select,button{font:normal 16px "helvetica neue",helvetica,arial,sans-serif;line-height:24px} h1{font:48px/60px "helvetica neue",helvetica,arial,sans-serif;font-weight:normal;margin-bottom:20px} h2{font-size:26px;line-height:30px;margin-bottom:5px;font-weight:bold} h3{margin-bottom:5px;font-size:20px;line-height:25px;font-weight:normal;color:#3a3e42} h4{font-weight:bold} a{outline:0;text-decoration:none;color:#2d81c5} html{background:#d5d8db url(../images/public/body.png) fixed;background:url(../images/public/body-gradient.png) repeat-x fixed,#d5d8db url(../images/public/body.png) fixed;color:#52585d;text-rendering:optimizeLegibility;-webkit-font-smoothing:antialiased} .wrapper{position:relative;width:1020px;margin:30px auto 100px;padding:0 2px} .page{position:relative;background:#fff url(../images/public/page.png);-moz-box-shadow:0px 0px 3px rgba(0,0,0,0.5);-webkit-box-shadow:0px 0px 3px rgba(0,0,0,0.5);-o-box-shadow:0px 0px 3px rgba(0,0,0,0.5);box-shadow:0px 0px 3px rgba(0,0,0,0.5);margin-bottom:20px;min-height:400px} .page:after{content:" ";position:absolute;bottom:-8px;left:-1px;width:1022px;height:8px;text-indent:-119988px;overflow:hidden;text-align:left;background-image:url('../images/public/page-shadow.png');background-repeat:no-repeat;background-position:0 0} .platter-section{padding:20px 60px 0px 20px;} .main-nav{height:74px;background:#fff;-moz-box-shadow:rgba(0,0,0,0.1) 0 1px;-webkit-box-shadow:rgba(0,0,0,0.1) 0 1px;-o-box-shadow:rgba(0,0,0,0.1) 0 1px;box-shadow:rgba(0,0,0,0.1) 0 1px} .main-nav .logo{position:absolute;top:18px;left:24px;display:block;width:152px;height:40px} .main-nav .actions{position:absolute;top:20px;right:25px} .hang{ background-image: url("../images/hang.png"); background-position: 0 0; background-repeat: no-repeat; height: 284px; left: 180px; overflow: hidden; position: absolute; text-align: left; text-indent: -119988px; top: -46px; width: 300px; } .actions {z-index: 2;} h1{font-size:60px;line-height:64px;margin:20px 0} .alpha{float:left;width:474px; color:#ff0000;} .beta{color:#fff000; border-left: 1px solid rgba(0, 0, 0, 0.1); float: left; padding-bottom: 20px; padding-top: 159px; position: relative; width: 300px;} .signup-section-full-width{clear:both;} A: Many of the elements your applying styles to are HTML5 - IE8 and below don't recognize them as valid, block-level, or stylable. For old versions of Firefox, you just need to do stuff like: section, article {display:block;} For old versions of IE, use this in the head: <!--[if lt IE 9]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> A: FYI, you have a number of CSS errors. http://jigsaw.w3.org/css-validator/validator?uri=http%3A%2F%2Feksai.com%2Ftesting%2Ffiles%2Fpublic.css&profile=css21&usermedium=all&warning=1&vextwarning=&lang=en EDIT: You're also using HTML5 elements, so you might want to include something like Modernizr, which will adapt HTML5 to downlevel browsers. A: IE8 and below do not support CSS for unknown elements which you use in HTML5 by default (no fuzz in IE9 though). But if you create a element of the same tagname with JS document.createElement, IE will magically become aware if those previously unknown elements. See here: http://ejohn.org/blog/html5-shiv/ So use a script which creates dummy elements of HTML5 and you can go on. http://remysharp.com/2009/01/07/html5-enabling-script/
{ "language": "en", "url": "https://stackoverflow.com/questions/7603214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Changing Web.Config in Production Environment My client insists not to store prone-to-change configuration settings in the Web.Config file for our webservice (WCF). His reasoning is that he will have to deploy the application every time he wants to change this or that setting in the configuration file. He, then, told me to store this configuration information in the database because, he says, that way one can change it whenever one needs without re-deploying the whole application, and because it is a more central place if we ever need to have more than one instance of the service running. Of course I find this argument and reasoning plainly wrong. However, I would like to provide him with clear evidence in that he his mistaken. Can anyone please point me out a source or two I may site to show him that changes in Web.Config are automatically propagated to the runtime and that he doesn't need to do any kind of re-deployment? A: Straight from MSDN on ASP.NET Configuration. ASP.NET Configuration Overview ASP.NET detects any changes to the configuration files and then automatically applies those changes to the affected applications, restarting the applications in most cases. A: See How to: Transform Web.config When Deploying a Web Application Project
{ "language": "en", "url": "https://stackoverflow.com/questions/7603216", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bluetooth: program stuck at connect() method I'm programming a simple Bluetooth client to send and receive text messages throught RFCOMM as a serial port. I had a look at the Android SDK tutorials and did it in the same way: an Activity which calls a thread to make the connection, and once done, another thread to take care of msg reception. I'm trying to connect to a Parallax EasyBluetooth. Connection works all right between computer and EasyBT, and also between a Java based mobile and the EasyBT. So the problem must be at the code or, I hope not, at the Android mobile bluetooth chip. Anyway it gets on and off, and detects other devices when scanning, so I guess problem is just my coding. The problem is that the code gets stuck at the connect() method. So let's see if anyone knows why. The XML for the activity is simple: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/boton" android:id="@+id/boton_enviar" /> </LinearLayout> Of course I have added the bluetooth permissions to the Manifiest: <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> And the code is the following: package uniovi.PFC; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.UUID; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; public class PruebaBTActivity extends Activity { private String TAG = "pruebaBT"; private BluetoothAdapter mBluetoothAdapter; private Map<String, BluetoothDevice> mArrayAdapter; private ConnectedThread hiloEscuchas; private ConnectThread hiloConectando; private Handler mHandler; private Button botonEnviar; private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); private static final int REQUEST_ENABLE_BT = 1; private static final int MESSAGE_READ = 1; private byte bytes_enviar[]; private String cmd; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Log.d(TAG, "On create abriendo"); mArrayAdapter = new HashMap<String, BluetoothDevice>(); botonEnviar = (Button)findViewById(R.id.boton_enviar); botonEnviar.setEnabled(false); botonEnviar.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { cmd = "A"; bytes_enviar = cmd.getBytes(); hiloEscuchas.write(bytes_enviar); } }); Log.d(TAG, "On create cerrando"); } @Override public void onResume() { super.onResume(); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { Log.d(TAG, "Device does not support Bluetooth"); } if (!mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); // If there are paired devices if (pairedDevices.size() > 0) { // Loop through paired devices for (BluetoothDevice device : pairedDevices) { // Add the name and address to an array adapter to show in a ListView mArrayAdapter.put(device.getName(), device); } } BluetoothDevice device = mArrayAdapter.get("EasyBT"); hiloConectando = new ConnectThread(device); hiloConectando.run(); //while(hiloEscuchas.isConnected()==false); //botonEnviar.setEnabled(true); } private class ConnectThread extends Thread { private final BluetoothSocket mmSocket; private final BluetoothDevice mmDevice; public ConnectThread(BluetoothDevice device) { // Use a temporary object that is later assigned to mmSocket, // because mmSocket is final BluetoothSocket tmp = null; mmDevice = device; // Get a BluetoothSocket to connect with the given BluetoothDevice try { // MY_UUID is the app's UUID string, also used by the server code tmp = device.createRfcommSocketToServiceRecord(MY_UUID); } catch (IOException e) { } mmSocket = tmp; } public void run() { // Cancel discovery because it will slow down the connection mBluetoothAdapter.cancelDiscovery(); try { // Connect the device through the socket. This will block // until it succeeds or throws an exception mmSocket.connect(); } catch (IOException connectException) { // Unable to connect; close the socket and get out try { mmSocket.close(); } catch (IOException closeException) { } return; } // Do work to manage the connection (in a separate thread) hiloEscuchas = new ConnectedThread(mmSocket); hiloEscuchas.run(); } /** Will cancel an in-progress connection, and close the socket */ public void cancel() { try { mmSocket.close(); } catch (IOException e) { } } } private class ConnectedThread extends Thread { private final BluetoothSocket mmSocket; private final InputStream mmInStream; private final OutputStream mmOutStream; private boolean conectado; public ConnectedThread(BluetoothSocket socket) { mmSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; conectado = false; mHandler = new Handler(); // Get the input and output streams, using temp objects because // member streams are final try { tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); } catch (IOException e) { } mmInStream = tmpIn; mmOutStream = tmpOut; conectado = true; } public boolean isConnected(){ return conectado; } public void run() { byte[] buffer = new byte[1024]; // buffer store for the stream int bytes; // bytes returned from read() // Keep listening to the InputStream until an exception occurs while (true) { try { cmd = "A"; bytes_enviar = cmd.getBytes(); hiloEscuchas.write(bytes_enviar); // Read from the InputStream bytes = mmInStream.read(buffer); // Send the obtained bytes to the UI Activity mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer) .sendToTarget(); } catch (IOException e) { break; } } } /* Call this from the main Activity to send data to the remote device */ public void write(byte[] bytes) { try { mmOutStream.write(bytes); } catch (IOException e) { } } /* Call this from the main Activity to shutdown the connection */ public void cancel() { try { mmSocket.close(); } catch (IOException e) { } } } } There was some code to make a bluetooth scan for devices, but in order to get things simple until it works, I wrote the MAC address manually into a variable. Comments explain this, and also shows where it gets stuck. Thanks A: I think these are causing at least part of your problem: hiloConectando = new ConnectThread(device); hiloConectando.run(); and hiloEscuchas = new ConnectedThread(mmSocket); hiloEscuchas.run(); You should be calling start(), not run(), e.g.: hiloConectando = new ConnectThread(device); hiloConectando.start();
{ "language": "en", "url": "https://stackoverflow.com/questions/7603221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Node server, Socket.io 'io is not defined'? I've followed the exact same steps which have always previously worked for me, create application through express, place the module dependencies in the node_modules folder. It appears that the socket.io client-side javascript file isn't being found. (I've looked at other peoples fixes, which is to include the JavaScript file in a script tab. I have not had to do this for my previous node + socket.io projects). JavaScript on client: var socket = io.connect('http://localhost'); JavaScript on server: var io = require('socket.io').listen(app); node_modules folder: socket.io, which has an internal node_modules folder containing socket.io-client Error Message: Uncaught ReferenceError: io is not defined (anonymous function) When I include the socket.io client manually: http://cdn.socket.io/stable/socket.io.js I get a different error which is: Uncaught TypeError: Object #<Object> has no method 'connect' (anonymous function) A: Node.js newbie here! I am pretty sure this has been answered. Yet I kept finding problems with the src for the socket. Apparently this : <script src="/socket.io/socket.io.js"> was not working for me on the client side. I've replaced the above line with this and it seems to work fine. <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script> (Edit: although this is obvious, this link may not work depending on when you are reading this answer. Please pick the latest link from: https://cdnjs.com/libraries/socket.io) Here is a working client side code: <body> <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script> <script src="https://code.jquery.com/jquery-1.11.1.js"></script> <script> $(function(){ var socket = io('http://localhost:8080'); console.log("Socket connected"+socket.connected); socket.on('notification', function(value){ //insert your code here }); }); </script> On the server side (handles only 1 socket) var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); var port = process.env.PORT || 8080; app.get('/', function(req, res){ console.log("app works"); }); io.on('connection', function(socket){ socket.emit('notification', {message:"hi"}); }); http.listen(port, function(){ console.log('listening on :' + port); }); A: I managed to blunder through this, and squandered about an hour, on something that turned out to be a very basic error. When an function is not defined? Such as " Uncaught ReferenceError: io is not defined ". Does that not mean that the function is getting "used" before it is "created"? In the part of my HTML file, that "calls" the javaScript files, it look like this : <script src='./js/playerChatter.js'></script> <!-- this one calls io --> <script src="http://localhost:2019/socket.io/socket.io.js"></script><!--ThisCreatesio--> and i changed it to this <script src="http://localhost:2019/socket.io/socket.io.js"></script> <!--ThisCreates io--> <script src='./js/playerChatter.js'></script> <!-- this on calls io --> So now the item "io", whether it is an object or function... Is actually getting created before it is getting used :D Have FUN! A: On the client: <head> <script src="http://localhost/socket.io/socket.io.js"></script> </head> A: On the client, did you do: <script src="/socket.io/socket.io.js"></script> before you set the socket variable? A: I solved this by running the index page by the Node.js server. Most likely "index.html" and "/socket.io/socket.io.js" files should be served by your Node.js server. as mentioned in the url Uncaught ReferenceError: io is not defined So when I executed https://localhost:3000 (3000 the port where the nodejs has been started) the error got resolved. A: * *Use server.listen() can fixed it;
{ "language": "en", "url": "https://stackoverflow.com/questions/7603224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: SMJobBless - documentation on when it asks for admin password I cannot seem to locate any documentation on this, so hopefully someone can confirm the behavior I am seeing with Apple's sample SMJobBless code. I was under the impression that it would only ask for an admin password if it detected a that a new version of the helper tool needed to be installed. However, this impression is apparently incorrect. The behavior I am seeing under 10.6 is that if I launch the app for the first time, it will ask for the password. If I launch almost immediately, it won't. However, if I wait a long enough time, it will ask for the password again. During all of this, the helper tool does not change. Can anyone point to documentation that defines this as the correct behavior? A: If anyone is interested, this (probably) turned out to be a bug and one has been filed. rdar://10280469 The way the system currently works is that it will ask for an admin password every time regardless of whether or not the SMJobBless function needs to install the helper tool or not. The bug is (probably) that a admin password request should not be made if the helper tool does not need to be installed (for example, it is already installed and has the same version as the one in the app bundle). So, what this means is that the determination of whether or not the helper tool needs to be installed needs to be made before a call to SMJobBless and SMJobBless should only be called if it is already known the helper tool needs to be installed. In my case, I only need to check whether the tool is installed (SMJobCopyDictionary handles this) and, if the tool is installed, whether or not it's version is older then the version of the tool in my app bundle. Some (incomplete) code to check whether the tool is installed and what the versions are is below. There is another alternative to do a version check of the helper tool which is for the helper tool to receive a request for it's version and for it to send a version reply back. Personally, I like the method below, but wanted to mention this alternative as it may be the best path in some situations. NSDictionary* installedHelperJobData; installedHelperJobData = (NSDictionary*)SMJobCopyDictionary( kSMDomainSystemLaunchd, (CFStringRef)@"com.apple.bsd.SMJobBlessHelper" ); NSString* installedPath = [[installedHelperJobData objectForKey:@"ProgramArguments"] objectAtIndex:0]; NSURL* installedPathURL = [NSURL fileURLWithPath:installedPath]; NSDictionary* installedInfoPlist = (NSDictionary*)CFBundleCopyInfoDictionaryForURL( (CFURLRef)installedPathURL ); NSString* installedBundleVersion = [installedInfoPlist objectForKey:@"CFBundleVersion"]; NSInteger installedVersion = [installedBundleVersion integerValue]; NSLog( @"installedVersion: %ld", (long)installedVersion ); NSBundle* appBundle = [NSBundle mainBundle]; NSURL* appBundleURL = [appBundle bundleURL]; NSURL* currentHelperToolURL = [appBundleURL URLByAppendingPathComponent:@"Contents/Library/LaunchServices/com.apple.bsd.SMJobBlessHelper"]; NSDictionary* currentInfoPlist = (NSDictionary*)CFBundleCopyInfoDictionaryForURL( (CFURLRef)currentHelperToolURL ); NSString* currentBundleVersion = [currentInfoPlist objectForKey:@"CFBundleVersion"]; NSInteger currentVersion = [currentBundleVersion integerValue]; NSLog( @"currentVersion: %ld", (long)currentVersion );
{ "language": "en", "url": "https://stackoverflow.com/questions/7603226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: declaring a pointer in c# to point to unmanaged structure in c dll I am stuck with one issue that I have not been able to solve for two days. The error message looks as below: Cannot take the address of, get the size of, or declare a pointer to a managed type ('Control_Vertilon.Imports.PHOTONIQ_CONFIG_TABLE') Below is the code, UInt16[] Arguments = new UInt16[PHOTONIQ_ARG_BUFF_SZ]; PHOTONIQ_CONFIG_TABLE PhotoniqConfigTable = new PHOTONIQ_CONFIG_TABLE(); UInt16 *cfgPtr = (UInt16*)&PhotoniqConfigTable; for(int i = 0; i < Imports.CONFIG_TABLE_SZ; i++){ Arguments[i+1] = *cfgPtr++; } Imports.ControlInterface(Opcode, Arguments, 0x1, Imports.TimeoutMs, ref errInNoErrorStruct, ref NumRetArguments, ref PhotoniqConfigTable, Imports.CONFIG_TABLE_SZ, ref errOutStruct); where the PhotoniqConfigTable which I marshaled looks as below, [StructLayout(LayoutKind.Sequential)] unsafe public struct PHOTONIQ_CONFIG_TABLE { [MarshalAs(UnmanagedType.U2)] public UInt16 SystemMode; //Indicates current system mode, acquire or standby mode 0 = Standby Mode 1 = Acquire Mode [MarshalAs(UnmanagedType.U2)] public UInt16 HVLimit0; // Maximum allowed voltage on HV supply 1 Range = 500 ?9250 (50 ?925V) [MarshalAs(UnmanagedType.U2)] public UInt16 HVLimit1; [MarshalAs(UnmanagedType.U2)] public UInt16 NumChannelsB0; [MarshalAs(UnmanagedType.U2)] public UInt16 NumChannelsB1; [MarshalAs(UnmanagedType.U2)] public UInt16 NumChannelsB2; [MarshalAs(UnmanagedType.U2)] public UInt16 NumChannelsB3; [MarshalAs(UnmanagedType.U2)] public UInt16 HVEnabled; [MarshalAs(UnmanagedType.U2)] public UInt16 HVSetpoint0; [MarshalAs(UnmanagedType.U2)] public UInt16 HVSetpoint1; [MarshalAs(UnmanagedType.U2)] public UInt16 UserConfigID; [MarshalAs(UnmanagedType.U2)] public UInt16 DCRD_AOut_0; [MarshalAs(UnmanagedType.U2)] public UInt16 BandEnables; [MarshalAs(UnmanagedType.U2)] public UInt16 Band0StartIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 Band0StopIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 Band1StartIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 Band1StopIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 Band2StartIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 Band2StopIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 Band3StartIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 Band3StopIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 Band4StartIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 Band4StopIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 Band5StartIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 Band5StopIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 Band6StartIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 Band6StopIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 Band7StartIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 Band7StopIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 FlagEnables; // pterm flag enables [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public UInt16[] Flag0Operands; // flag 0 operands: 64 bits [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public UInt16[] Flag1Operands; // flag 0 operands: 64 bits [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public UInt16[] Flag2Operands; // flag 0 operands: 64 bits [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public UInt16[] Flag3Operands; // flag 0 operands: 64 bits [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public UInt16[] Flag4Operands; // flag 0 operands: 64 bits [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public UInt16[] Flag5Operands; // flag 0 operands: 64 bits [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public UInt16[] Flag6Operands; // flag 0 operands: 64 bits [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public UInt16[] Flag7Operands; // flag 0 operands: 64 bits [MarshalAs(UnmanagedType.U2)] public UInt16 PTerm0; // flag 0 - 7 product terms [MarshalAs(UnmanagedType.U2)] public UInt16 PTerm1; [MarshalAs(UnmanagedType.U2)] public UInt16 PTerm2; [MarshalAs(UnmanagedType.U2)] public UInt16 PTerm3; [MarshalAs(UnmanagedType.U2)] public UInt16 PTerm4; [MarshalAs(UnmanagedType.U2)] public UInt16 PTerm5; [MarshalAs(UnmanagedType.U2)] public UInt16 PTerm6; [MarshalAs(UnmanagedType.U2)] public UInt16 PTerm7; [MarshalAs(UnmanagedType.U2)] public UInt16 DataFilterEnable; // 1 = enable spectral filtering, 0 = disable [MarshalAs(UnmanagedType.U2)] public UInt16 ProcessingEnables; // bit 0 = spect filt, bit 1 = gain, 2 = bkgnd sub. [MarshalAs(UnmanagedType.U2)] public UInt16 TimestampEnable; // 1 = enable time stamp, 0 = disable [MarshalAs(UnmanagedType.U2)] public UInt16 DACspare; [MarshalAs(UnmanagedType.I4)] public Int32 TimestampInterval; // [MarshalAs(UnmanagedType.U2)] public UInt16 CustomWordsEnable; // 1/0 [MarshalAs(UnmanagedType.U2)] public UInt16 EventCustomCount; // [MarshalAs(UnmanagedType.U2)] public UInt16 RESERVED; [MarshalAs(UnmanagedType.U2)] public UInt16 ImageAcqMode; // 1 = image, 0 = particle [MarshalAs(UnmanagedType.U2)] public UInt16 InputTrigThresh; [MarshalAs(UnmanagedType.U2)] public UInt16 InputTrigChannel; // [MarshalAs(UnmanagedType.U2)] public UInt16 RangeErrorEnable; // 1 = enable range error, 0 = disable [MarshalAs(UnmanagedType.U2)] public UInt16 CrossBankConfig; // [MarshalAs(UnmanagedType.U2)] public UInt16 ReportPackingMode; // [MarshalAs(UnmanagedType.U2)] public UInt16 GPOutputEnable; // [MarshalAs(UnmanagedType.I4)] public Int32 GPOutputDelay; // [MarshalAs(UnmanagedType.I4)] public Int32 GPOutputPeriod; // [MarshalAs(UnmanagedType.U2)] public UInt16 IntBoxcarEnable; [MarshalAs(UnmanagedType.U2)] public UInt16 BoxcarWidthEnable; [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public Int32[] ResetDelay; [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public UInt16[] TrigSource; [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public Int32[] TrigPeriod; [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public Int32[] IntegPeriod; [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public Int32[] IntegDelay; [MarshalAs(UnmanagedType.U2)] public UInt16 SibSel0; [MarshalAs(UnmanagedType.U2)] public UInt16 SibSel1; [MarshalAs(UnmanagedType.U2)] public UInt16 SibSel2; [MarshalAs(UnmanagedType.U2)] public UInt16 SibSel3; [MarshalAs(UnmanagedType.U2)] public UInt16 SibSel4; [MarshalAs(UnmanagedType.U2)] public UInt16 SibSel5; [MarshalAs(UnmanagedType.U2)] public UInt16 SibSel6; [MarshalAs(UnmanagedType.U2)] public UInt16 SibSel7; [MarshalAs(UnmanagedType.I4)] public Int32 TriggerEndCount; [MarshalAs(UnmanagedType.U2)] public UInt16 TrigStampSelect; [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public UInt16[] DataFormat; // 4 banks: 0 = 17bit sign/mag, 1 = 16bit 2's, comp, 2 = 16b, 2's 1/2 scale [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 7)] public UInt16[] RESERVED1; [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 256)] public UInt16[] GainArray; [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 256)] public UInt16[] TrigThreshArray; [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 16)] public UInt16[] TrigEnableArray; // 256 bits, 1/0 for each channel (max of 256 channels) [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 322)] public UInt16[] RESERVED2; // 678-999 [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 250)] public UInt16[] CustomArray; // user custom space: 1000-1249 [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 567)] public UInt16[] FactoryArray; // start of factory table [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 32)] public SByte[] ModelNumber; // model number [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 151)] public UInt16[] FactoryArray1; // last piece of factory table } The problem is, I thought I made the structure unmanaged type yet compiler saying it is managed type. Or it could be that the UInt16 pointer pointing such way is wrong in managed code. The buffer Argument[] is in 16bit and that's the passing argument in the dll function so I have stick with 16bit whether using as pointer or buffer to move data. It would be a tremendous help if anybody can help how to solve this problem. I have searched web yet could not find precise answer. Thanks in advance. ================================================================================== Hi thanks for the reply, Here I receive different errors with code below: fixed (UInt16 *cfgPtr = (UInt16*)&PhotoniqConfigTable){ //modify config table, then send it back up to PhotoniQ PhotoniqConfigTable.NumChannelsB0 = 6; PhotoniqConfigTable.IntegPeriod[0] = per; PhotoniqConfigTable.TrigPeriod[0] = 100000; PhotoniqConfigTable.TrigStampSelect = 1; PhotoniqConfigTable.TimestampEnable = 0; PhotoniqConfigTable.RangeErrorEnable = 0; PhotoniqConfigTable.DataFormat[0] = 0; PhotoniqConfigTable.GPOutputEnable = 1; PhotoniqConfigTable.GPOutputDelay = 10; PhotoniqConfigTable.GPOutputPeriod = 1000; for (int i = 0; i < Imports.CONFIG_TABLE_SZ; i++) { Arguments[i + 1] = *cfgPtr++; } } The error messages are: Cannot assign to 'cfgPtr' because it is a 'fixed variable'. The right hand side of a fixed statement assignment may not be a cast expression. You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement. (Three same errors for different lines) anybody who can explain to me will be great help since I am in short of time. The structure now looks as below: [StructLayout(LayoutKind.Sequential)] unsafe public struct PHOTONIQ_CONFIG_TABLE { [MarshalAs(UnmanagedType.U2)] public UInt16 SystemMode; //Indicates current system mode, acquire or standby mode 0 = Standby Mode 1 = Acquire Mode [MarshalAs(UnmanagedType.U2)] public UInt16 HVLimit0; // Maximum allowed voltage on HV supply 1 Range = 500 ?9250 (50 ?925V) [MarshalAs(UnmanagedType.U2)] public UInt16 HVLimit1; [MarshalAs(UnmanagedType.U2)] public UInt16 NumChannelsB0; [MarshalAs(UnmanagedType.U2)] public UInt16 NumChannelsB1; [MarshalAs(UnmanagedType.U2)] public UInt16 NumChannelsB2; [MarshalAs(UnmanagedType.U2)] public UInt16 NumChannelsB3; [MarshalAs(UnmanagedType.U2)] public UInt16 HVEnabled; [MarshalAs(UnmanagedType.U2)] public UInt16 HVSetpoint0; [MarshalAs(UnmanagedType.U2)] public UInt16 HVSetpoint1; [MarshalAs(UnmanagedType.U2)] public UInt16 UserConfigID; [MarshalAs(UnmanagedType.U2)] public UInt16 DCRD_AOut_0; [MarshalAs(UnmanagedType.U2)] public UInt16 BandEnables; [MarshalAs(UnmanagedType.U2)] public UInt16 Band0StartIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 Band0StopIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 Band1StartIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 Band1StopIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 Band2StartIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 Band2StopIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 Band3StartIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 Band3StopIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 Band4StartIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 Band4StopIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 Band5StartIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 Band5StopIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 Band6StartIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 Band6StopIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 Band7StartIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 Band7StopIndex; [MarshalAs(UnmanagedType.U2)] public UInt16 FlagEnables; // pterm flag enables //[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public fixed UInt16 Flag0Operands[4]; // flag 0 operands: 64 bits //[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public fixed UInt16 Flag1Operands[4]; // flag 0 operands: 64 bits //[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public fixed UInt16 Flag2Operands[4]; // flag 0 operands: 64 bits //[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public fixed UInt16 Flag3Operands[4]; // flag 0 operands: 64 bits //[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public fixed UInt16 Flag4Operands[4]; // flag 0 operands: 64 bits //[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public fixed UInt16 Flag5Operands[4]; // flag 0 operands: 64 bits //[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public fixed UInt16 Flag6Operands[4]; // flag 0 operands: 64 bits //[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public fixed UInt16 Flag7Operands[4]; // flag 0 operands: 64 bits [MarshalAs(UnmanagedType.U2)] public UInt16 PTerm0; // flag 0 - 7 product terms [MarshalAs(UnmanagedType.U2)] public UInt16 PTerm1; [MarshalAs(UnmanagedType.U2)] public UInt16 PTerm2; [MarshalAs(UnmanagedType.U2)] public UInt16 PTerm3; [MarshalAs(UnmanagedType.U2)] public UInt16 PTerm4; [MarshalAs(UnmanagedType.U2)] public UInt16 PTerm5; [MarshalAs(UnmanagedType.U2)] public UInt16 PTerm6; [MarshalAs(UnmanagedType.U2)] public UInt16 PTerm7; [MarshalAs(UnmanagedType.U2)] public UInt16 DataFilterEnable; // 1 = enable spectral filtering, 0 = disable [MarshalAs(UnmanagedType.U2)] public UInt16 ProcessingEnables; // bit 0 = spect filt, bit 1 = gain, 2 = bkgnd sub. [MarshalAs(UnmanagedType.U2)] public UInt16 TimestampEnable; // 1 = enable time stamp, 0 = disable [MarshalAs(UnmanagedType.U2)] public UInt16 DACspare; [MarshalAs(UnmanagedType.I4)] public Int32 TimestampInterval; // [MarshalAs(UnmanagedType.U2)] public UInt16 CustomWordsEnable; // 1/0 [MarshalAs(UnmanagedType.U2)] public UInt16 EventCustomCount; // [MarshalAs(UnmanagedType.U2)] public UInt16 RESERVED; [MarshalAs(UnmanagedType.U2)] public UInt16 ImageAcqMode; // 1 = image, 0 = particle [MarshalAs(UnmanagedType.U2)] public UInt16 InputTrigThresh; [MarshalAs(UnmanagedType.U2)] public UInt16 InputTrigChannel; // [MarshalAs(UnmanagedType.U2)] public UInt16 RangeErrorEnable; // 1 = enable range error, 0 = disable [MarshalAs(UnmanagedType.U2)] public UInt16 CrossBankConfig; // [MarshalAs(UnmanagedType.U2)] public UInt16 ReportPackingMode; // [MarshalAs(UnmanagedType.U2)] public UInt16 GPOutputEnable; // [MarshalAs(UnmanagedType.I4)] public Int32 GPOutputDelay; // [MarshalAs(UnmanagedType.I4)] public Int32 GPOutputPeriod; // [MarshalAs(UnmanagedType.U2)] public UInt16 IntBoxcarEnable; [MarshalAs(UnmanagedType.U2)] public UInt16 BoxcarWidthEnable; //[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public fixed Int32 ResetDelay[4]; //[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public fixed UInt16 TrigSource[4]; //[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public fixed Int32 TrigPeriod[4]; //[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public fixed Int32 IntegPeriod[4]; //[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public fixed Int32 IntegDelay[4]; [MarshalAs(UnmanagedType.U2)] public UInt16 SibSel0; [MarshalAs(UnmanagedType.U2)] public UInt16 SibSel1; [MarshalAs(UnmanagedType.U2)] public UInt16 SibSel2; [MarshalAs(UnmanagedType.U2)] public UInt16 SibSel3; [MarshalAs(UnmanagedType.U2)] public UInt16 SibSel4; [MarshalAs(UnmanagedType.U2)] public UInt16 SibSel5; [MarshalAs(UnmanagedType.U2)] public UInt16 SibSel6; [MarshalAs(UnmanagedType.U2)] public UInt16 SibSel7; [MarshalAs(UnmanagedType.I4)] public Int32 TriggerEndCount; [MarshalAs(UnmanagedType.U2)] public UInt16 TrigStampSelect; //[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)] public fixed UInt16 DataFormat[4]; // 4 banks: 0 = 17bit sign/mag, 1 = 16bit 2's, comp, 2 = 16b, 2's 1/2 scale //[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 7)] public fixed UInt16 RESERVED1[7]; //[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 256)] public fixed UInt16 GainArray[256]; //[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 256)] public fixed UInt16 TrigThreshArray[256]; //[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 16)] public fixed UInt16 TrigEnableArray[16]; // 256 bits, 1/0 for each channel (max of 256 channels) //[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 322)] public fixed UInt16 RESERVED2[322]; // 678-999 //[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 250)] public fixed UInt16 CustomArray[250]; // user custom space: 1000-1249 //[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 567)] public fixed UInt16 FactoryArray[567]; // start of factory table //[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 32)] public fixed SByte ModelNumber[32]; // model number //[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 151)] public fixed UInt16 FactoryArray1[151]; //public fixed UInt16 FactoryArray1[151]; // last piece of factory table }; A: A second answer, to answer your second question: The error messages are: Cannot assign to 'cfgPtr' because it is a 'fixed variable'. The right hand side of a fixed statement assignment may not be a cast expression. You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement. The error messages are telling you what is wrong. Read them. Cannot assign to 'cfgPtr' because it is a 'fixed variable'. You are assigning to it here: Arguments[i + 1] = *cfgPtr++; Once you initialize a variable containing a pointer that points to a fixed-in-space block you cannot change that variable because you might be changing it to point to a not-fixed-in-space block. In order to prevent this common bug, C# stops you from modifying that variable. If you want to modify the variable, create a different variable instead. Set it equal to cfgPtr and then modify that variable. Make sure you do it correctly; you are now responsible for ensuring that you keep the pointer pointing to something that is fixed. The right hand side of a fixed statement assignment may not be a cast expression. In my last answer I told you to read section 18.7 of the specification, which states that the "fixed" statement takes: A simple-name or member-access that references a fixed size buffer member of a moveable variable A cast expression is not a "simple name or member access". A cast expression is a cast expression. And this cast doesn't even make sense! A pointer to a structure is not a pointer to ushort! Remove the cast. Change the expression in the initializer to be a member access to a fixed-size buffer member of a moveable variable. You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement. You're using a fixed-size buffer directly. You can't do that. You can only use a fixed-size buffer by obtaining a pointer to it. Again, this is part of the safety system that ensures that you don't accidentally access a fixed-in-size buffer that is not fixed-in-place. Stop trying to access the buffer directly. Obtain a pointer to the buffer and access it via the pointer. anybody who can explain to me will be great help since I am in short of time. Let me be very clear on this point: you have turned the managed safety system off and the correctness of your program and the stability of the process are now your problem, not the managed runtime's problem. If you do not understand everything about how to safely manage your own pointers, stop what you are doing and read up on it until you do understand it. By rushing now and writing a whole lot of code that you do not understand, you are risking having to deal with horrible bugs later. This is no time to be in a hurry. Begin by reading all of chapter 18. Only once you thoroughly understand all that stuff should you attempt to write complicated unsafe code. A: You've said how the arrays are to be laid out in unmanaged memory but have not said how they are to be laid out in managed memory. The compiler therefore believes that you have a bunch of references to garbage-collected managed memory in that struct -- all those arrays -- and will not let you take a pointer to it as a result. I suspect that you intended those arrays to be fixed-size buffers, not managed arrays, yes? You'll want to read the C# specification, section 18.7, to understand how fixed-size buffers work in structs. Note also that there is a big difference between a "fixed in size" array and a "fixed in place" object pointed to by a pointer; those are two completely different usages of the word "fixed". Many people get them confused, particularly since to correctly and safely use a "fixed in size" buffer, the memory of the buffer must be "fixed in place". A: Instead of [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 151)] public UInt16[] FactoryArray1; say public unsafe fixed ushort FactoryArray1[151]; because arrays "look" different in managed and unmanaged memory, but fixed-size buffers "look" the same (i.e. are blittable).
{ "language": "en", "url": "https://stackoverflow.com/questions/7603230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Dropdown menu appearing beneath content area I have two relatively positioned areas on my page, the content and the header. The content has a higher z-index than the header - this is a requirement for the structure of the page. I've simplified the HTML and CSS to illustrate what I'm trying to do here: http://cb3.securetree.com/example.html This presents an issue with dropdown menus that exist in the header because they display underneath the content region even though their z-index is higher. On the example page, notice how the dropdown menu goes beneath the content region. Appreciate any assistance in solving this issue. A: Relatively positioned elements will display on top of things that are not relatively positioned. You should avoid having to use relative positioning where it's not necessary. If you use floats and margins etc to move things around on the page, you shouldn't have any z-index issues.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS Image button styling I'm trying to accomplish something like this Where the buttons are centered in the middle of the page and separated by 50px Here is what I did. HTML <div class="btn btn_tours"><a href="maps.html">Maps</a><span></span></div> <div class="btn btn_maps"><a href="dbtest.html">DB Test</a><span></span></div> <div class="btn btn_locations"><a href="geolocation.html">Geolocation</a><span></span></div> <div class="btn btn_directions"><a href="accel.html">Accelerometer</a><span></span></div> CSS .btn { position: relative; padding: 10px 10px 10px 10px; cursor: pointer; overflow: visible; width:50px; height: 50px; } .btn_directions{ background: url(http://tinyurl.com/5r6a3jy); no-repeat;} .btn_maps{ background: url(http://tinyurl.com/5r6a3jy); no-repeat; } .btn_tours{ background: url(http://tinyurl.com/5r6a3jy); no-repeat;} .btn_locations{ background: url(http://tinyurl.com/5r6a3jy); no-repeat; } JSFIDDLE A: Simple example here: http://jsfiddle.net/rgmCc/ A: Your JSFiddle doesn't seem to be loading images. Wrap your .btn in a div. Give it a fixed width and overflow: hidden;. Set it to margin: 0 auto;. Get rid of the <center> tags. Set your .btn to float: left;. To horizontally center, an element must have a width and 'auto' on the left and right sides. To set up a grid of elements inside of a div, you'll usually float them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603238", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ColdFusion ORM cannot find CFCs when using virtual directory I have some entities with relationships: component name="Store" persistent="true" { property name="Products" fieldtype="one-to-many" cfc="Product"; } component name="Product" persistent="true" { property name="Store" fieldtype="many-to-one" cfc="Store"; } The above code is simplified. My project resided in C:\ColdFusion9\wwwroot\StoreTracker, and everything worked great. But then I had to move it to a virtual directory. I moved my project to C:\Projects\StoreTracker, but now the ORM does not work anymore with the following error: Cannot load the target CFC Store for the relation property Store in CFC Product. Could not find the ColdFusion component or interface Store. If I fully qualify the name though by using: property name="Store" fieldtype="many-to-one" cfc="entities.Store"; then the ORM works. Does anybody know why moving it to a virtual directory causes the ORM to search through the wrong folder for persistent entities, and if there's an easier way to change which folder it's searching through so I don't have to fully qualify every relationship? Edit: Here is the relevant part in Application.cfc: this.ormSettings = { cfclocation="entities" }; And the folder structure for the model folder: C:\Projects\StoreTracker\entities There are no sub-folders under the entities folder and all my persistent entities are in there. I was able to get it to work correctly if I add the following line to Application.cfc: this.mappings["/entities"] = "C:\Projects\StoreTracker\entities"; Though I'm not sure why this works. Without it, CF ORM seems to read the entities just fine if they only have simple properties, but when there's a relationship, it bombs out saying that it can't find the related CFC. Perhaps a bug? A: If by virtual directory you mean a virtual directory set up in Apache or IIS, then this makes sense. Those virtual directories exist in the web server, not in ColdFusion. CF has no knowledge of them. You probably need to create a ColdFusion mapping to your application. I am not sure exactly how your app is structured or where you are putting your ORM objects, but you may want to add something like this to your Application.cfc in the pseudo-constructor area. <cfset application.mappings["/StoreTracker"] = "C:\Projects\StoreTracker" /> Update: Oh and don't forget to ormReload()
{ "language": "en", "url": "https://stackoverflow.com/questions/7603240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: DLL not found in distributed application I've written a pretty simple Windows Form Application that calls an unmanaged DLL to perform most of the actual calculations done by the program. The program runs fine in Debug and Release modes. It also installs correctly and runs on the development computer. The problem arises when I attempt to install it on target computer (running the same operating system: 64bit Windows 7). Despite the DLL being in the same directory as the .exe file, I'm getting a "DLL Not Found Exception". I'm getting this exception when I attempt both OneClick publishing as well as when I use a .msi installation file. The error will even cite the location of the file while stating the file could not be found. Is one of my installer settings incorrect? Am I not including the DLL or a reference in the appropriate place? Any help or advice would be appreciated. Thanks. A: The DLL you deployed may have additional dependencies that you haven't deployed. If those dependencies aren't there then you'll generally get this type of error. UPDATE: The "D" in MSVCR100D means that it's the debug version of the library. That most likely isn't on the target system and licensing prevents you from deploying it. You need to do a full recompile under Release mode. Once that is done your DLL should target MSVCR100 (note the lack of "D") instead. If not, then you probably have a debug build of that assembly. Locate a release version and link to that. A: If you are invoking the unmanaged code by calling CreateObject then make sure that you have registered the unmanaged DLL on target computer as well. A: In a post about a similar 'dll not found' error at Microsoft: http://support.microsoft.com/kb/319114 you can learn how to fix this problem based on the fact that it might happen due to: 1) Missing or corrupt dll file (also here) 2) The registration path which is calling that that dll is probably wrong/missing/damaged somehow. Otherwise you might want to verify that new virus/malware is around...
{ "language": "en", "url": "https://stackoverflow.com/questions/7603243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Dynamic callback method for System.Threading.ThreadPool.QueueUserWorkItem C# What I am trying to do is be able to pass a function reference to another function and have it used as a callback method for a System.Threading.ThreadPool.QueueUserWorkItem. See in method D() the 'Any' parameter. I need to be able to pass the callback method pointer or reference for the 'Any' parameter. I can't use a delegate, because that would need to be static, is that correct? Any ideas? private void A() { /*code*/ } private void B() { /*code*/ } private void C(int i) { switch(i) { case 1: D(A()); break; case 2: D(B()); break; default: break; } } private void D(type? Any) { System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(Any)); } A: I can't use a delegate, because that would need to be static, is that correct. No that is not correct. delegate void MyMethods(); class Foo { void Minstance() {} static void Mstatic() {} MyMethods m1 = Minstance; // OK MyMethods m2 = Mstatic; // OK } And the following is incorrect syntax: case 1: D(A()); // here you call (execute) A break; just omit the parenthesis after the method: case 1: D(A); // this passes a reference to A break; And now you have to properly define D : void D(WaitCallback any) { ThreadPool.QueueUserWorkItem(any); } A: I think this will do what you want, but WaitCallback delegates take an object as a parameter. private void A(object state) { // does one thing } private void B(object state) { // does a different thing } private void C(int i) { switch (i) { case 1: D(new System.Threading.WaitCallback(A)); break; case 2: D(new System.Threading.WaitCallback(B)); break; default: break; } } private void D(System.Threading.WaitCallback worker) { System.Threading.ThreadPool.QueueUserWorkItem(worker); } A: Yes, you want to use a delegate: public void CallbackDelegate(); private void D(CallbackDelegate D) { } A: Maybe that could help: private void D(Delegate any) { System.Threading.ThreadPool.QueueUserWorkItem(ignored => any.DynamicInvoke()); } A: Try using an delegate like here. Please ask me if you have any questions. using System; using System.Threading; namespace Thread.Pool.Test { delegate void VoidDelegate (object obj); public class Delegate { /// <summary> /// ThreadPool Entry Point for A /// </summary> /// <param name='obj'> /// EventWaitHandle /// </param> /// <exception cref='ArgumentException'> /// Is thrown when an argument passed to a method is invalid. /// </exception> private void A (object obj) { if (!(obj is EventWaitHandle)) throw new ArgumentException ("Only EventWaitHandle supported!"); A ((EventWaitHandle)obj); } private void A (EventWaitHandle handle) { // does one thing //finsihed handle.Set (); } /// <summary> /// ThreadPool Entry Point for B /// </summary> /// <param name='obj'> /// EventWaitHandle /// </param> /// <exception cref='ArgumentException'> /// Is thrown when an argument passed to a method is invalid. /// </exception> private void B (object obj) { if (!(obj is EventWaitHandle)) throw new ArgumentException ("Only EventWaitHandle supported!"); B ((EventWaitHandle)obj); } private void B (EventWaitHandle handle) { // does a different thing //finsihed handle.Set (); } private void C (int i) { EventWaitHandle waitHandle = new ManualResetEvent (false); switch (i) { case 1: D (A ,waitHandle); break; case 2: D (B ,waitHandle); break; default: throw new Exception ("Case not supported"); } //Wait for the thread to finish waitHandle.WaitOne (); } private void D (VoidDelegate any, EventWaitHandle waitHandle) { ThreadPool.QueueUserWorkItem (new System.Threading.WaitCallback (any),waitHandle); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7603245", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C++ and QML integration, can't seem to access properties Ok. So I thought i had understood this completely, but obiously I have done something wrong and I can't for the life of me understand what. I've followed the tutorials to the letter (i checked) but can't get it to work, so here, let me ask a simple question. I've created a QObject based class which has a simple QString variable that stores the name of the class (this is just for testing), it looks like this: #include <QObject> class CategoryPane : public QObject { Q_OBJECT Q_PROPERTY(QString catName READ getCategoryName WRITE setCategoryName); public: explicit CategoryPane(QObject *parent = 0); QString getCategoryName(); void setCategoryName(QString); signals: void nameChange(); private: QString categoryName; }; This is registered with the following function: qmlRegisterType("ITI_UI", 1, 0, "CategoryPane"); And I'm trying to print out the name variable of my CategoryPane class in a QML-file that looks like this: import QtQuick 1.0 import ITI_UI 1.0 Rectangle { width: 300 height: 300 CategoryPane { id: whatever catName: "ey" Text { text: whatever.catName } } } But I get the following error: qrc:/main.qml:11:3: Cannot assign to non-existent default property Note: I get no error msg if I remove the Text {} field, but then again I can't print out my name string which is the whole point... Thanks in advance for your time and patience! A: CategoryPane is being used like a visual item, but it derives from QObject. Have you tried inheriting from QDeclarativeItem instead? If you just want to access the property and not use it as a visual item, you should be able to do like: C++: QDeclarativeView view; CategoryPane pane; view.rootContext()->setContextProperty("categoryPane", &pane); QML: import QtQuick 1.0 Rectangle { width: 300 height: 300 Text { text: categoryPane.catName } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7603260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: HTML5: manipulating browser windows Does HTML5 give the ability to directly manipulate browser windows (like switching a window to the foreground, closing it, getting its name and contents, etc) even if my window doesn't "own" them? I realize this is a security risk, but I would like to at least do this on my local system where I can provide privileged permission to a script if necessary. A: Your best bet is to make a Firefox add on or Chromium add on. It's the only way you are truly going to be able to gain access to the things you are wanting access to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bidirectional one-to-one mapped to multiple fields I have a domain class called Flight that represents a flight that has been flown. I have another class called Movement which can represents either a departure or an arrival and contains a date and time and the airport at which the movement occured. @Entity public class Flight implements Serializable { private Movement departure; private Movement arrival; } @Entity public class Movement implements Serializable { @Temporal(TemporalType.TIMESTAMP) private Date dateTime; @ManyToOne private Airport airport; private Flight flight; } I am however not sure how to properly annotate the flight field in the Movement class. I figured the Flight class has to be the owning side of the relationship because if it is not, there is no way to tell if the Movement of a specific Flight was the departure or the arrival: @OneToOne private Movement departure; @OneToOne private Movement arrival; This, however, poses a problem. I can't map the flight field in the Movement class on both fields: // This obviously does not work @OneToOne(mappedBy = "departure") @OneToOne(mappedBy = "arrival") private Flight flight; How would I go about properly annotating this, having both the departure and arrival field properly reference the Movement and still be able to have the flight field on the Movement class reference the Flight class? A: If you really need a bidirectional relationship, then you'll need to have to fields in movement, with one of them always being null: @OneToOne(mappedBy = "departure") private Flight departureFlight; @OneToOne(mappedBy = "arrival") private Flight arrivalFlight; But you could have a single getter: public Flight getFlight() { return departureFlight == null ? arrivalFlight : departureFlight; } A: If you need two way relationship, you could change relation type to @ManyToMany, so you could use a join table with additional status column. There you'd specify whether it's an arrival or departure. Wikibooks provide an example how to map it. This kind of relation, though, is quite cumbersome to handle in code. Or maybe you don't need a two way relationship at all, as glowcoder suggests? It would be much simpler to map, use, and faster to run.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Star schema modeling - many-to-many I'm building a data warehouse based on NFL statistics for educational purposes as I learn this paradigm - I have the following modelling problem Players can play for different teams different years and similarly coaches can coach different teams different years of their career; players could also potentially play different positions in different years too (rare but possible) What is the best way to model the assignment between players, coaches and teams for different years? Would I store the different years' roster information in a dimension? eg DimTeamRoster which would have a TimeKey, TeamKey and CoachKey (since a team can only have one Head Coach) with a FactTeamRoster with a TeamRosterKey, PlayerKey, Positionkey Or would I have a FactTeamRoster which would have a TimeKey, TeamKey, PlayerKey, PositionKey? But then would this approach make sense because this fact-table wouldn't really be storing any measures, it would be simply storing the assignment for that year What're some of the other possible solutions and pros / cons / correctness of each approach? A: For starters, this would do -- I think. dimRole may look something like RoleKey RoleName RoleGroup --------------------------------------- 1 quarterback player 2 tackle player 3 head coach coach 4 assistant coach coach
{ "language": "en", "url": "https://stackoverflow.com/questions/7603275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why does (1 >> 0x80000000) == 1? The number 1, right shifted by anything greater than 0, should be 0, correct? Yet I can type in this very simple program which prints 1. #include <stdio.h> int main() { int b = 0x80000000; int a = 1 >> b; printf("%d\n", a); } Tested with gcc on linux. A: 6.5.7 Bitwise shift operators: If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined. The compiler is at license to do anything, obviously, but the most common behaviors are to optimize the expression (and anything that depends on it) away entirely, or simply let the underlying hardware do whatever it does for out-of-range shifts. Many hardware platforms (including x86 and ARM) mask some number of low-order bits to use as a shift-amount. The actual hardware instruction will give the result you are observing on either of those platforms, because the shift amount is masked to zero. So in your case the compiler might have optimized away the shift, or it might be simply letting the hardware do whatever it does. Inspect the assembly if you want to know which. A: according to the standard, shifting for more than the bits actually existing can result in undefined behavior. So we cannot blame the compiler for that. The motivation probably resides in the "border meaning" of 0x80000000 that sits on the boundary of the maximum positive and negative together (and that is "negative" having the highmost bit set) and on certain check that should be done and that the compiled program doesn't to to avoid to waste time verifying "impossible" things (do you really want the processor to shift bits 3 billion times?). A: It's very probably not attempting to shift by some large number of bits. INT_MAX on your system is probably 2**31-1, or 0x7fffffff (I'm using ** to denote exponentiation). If that's the case, then In the declaration: int b = 0x80000000; (which was missing a semicolon in the question; please copy-and-paste your exact code) the constant 0x80000000 is of type unsigned int, not int. The value is implicitly converted to int. Since the result is outside the bounds of int, the result is implementation-defined (or, in C99, may raise an implementation-defined signal, but I don't know of any implementation that does that). The most common way this is done is to reinterpret the bits of the unsigned value as a 2's-complement signed value. The result in this case is -2**31, or -2147483648. So the behavior isn't undefined because you're shifting by value that equals or exceeds the width of type int, it's undefined because you're shifting by a (very large) negative value. Not that it matters, of course; undefined is undefined. NOTE: The above assumes that int is 32 bits on your system. If int is wider than 32 bits, then most of it doesn't apply (but the behavior is still undefined). If you really wanted to attempt to shift by 0x80000000 bits, you could do it like this: unsigned long b = 0x80000000; unsigned long a = 1 >> b; // *still* undefined unsigned long is guaranteed to be big enough to hold the value 0x80000000, so you avoid part of the problem. Of course, the behavior of the shift is just as undefined as it was in your original code, since 0x80000000 is greater than or equal to the width of unsigned long. (Unless your compiler has a really big unsigned long type, but no real-world compiler does that.) The only way to avoid undefined behavior is not to do what you're trying to do. It's possible, but vanishingly unlikely, that your original code's behavior is not undefined. That can only happen if the implementation-defined conversion of 0x80000000 from unsigned int to int yields a value in the range 0 .. 31. IF int is smaller than 32 bits, the conversion is likely to yield 0. A: well read that maybe can help you expression1 >> expression2 The >> operator masks expression2 to avoid shifting expression1 by too much. That because if the shift amount exceeded the number of bits in the data type of expression1, all the original bits would be shifted away to give a trivial result. Now for ensure that each shift leaves at least one of the original bits, the shift operators use the following formula to calculate the actual shift amount: mask expression2 (using the bitwise AND operator) with one less than the number of bits in expression1. Example var x : byte = 15; // A byte stores 8 bits. // The bits stored in x are 00001111 var y : byte = x >> 10; // Actual shift is 10 & (8-1) = 2 // The bits stored in y are 00000011 // The value of y is 3 print(y); // Prints 3 That "8-1" is because x is 8 bytes so the operacion will be with 7 bits. that void remove last bit of original chain bits
{ "language": "en", "url": "https://stackoverflow.com/questions/7603279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: How long will a session variable last if you don't unset it? When I store a variable in a session (in php), how long will that variable linger in that file? Will it be there until someone unsets the variable or deletes the file? update: so it is session.gc-maxlifetime setting that is set in php.ini file. You can check your setting by calling phpinfo(). Mine is set to 1440 seconds so 24 minutes. Might have found a duplicate here, although when googling I didn't find it at first because of the wording. A: By default it will be there 24 minutes. (Which is the default php.ini file setting). As you commented, this is the setting: http://www.php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime A: Look in your php.ini file. It will tell you exactly how long the default session will last.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Select statement taking a long time Hi I have a method like: public JsonResult GetActivities(int id) { var activities = ActivityRepository.GetAll().Where(x => x.AreaId == id); var jsonData = new { rows = activities.Select(q => new { Id = q.Id.ToString(), q.Descriptor }).ToList() }; return Json(jsonData, JsonRequestBehavior.AllowGet); } It works fine but I find the line: var jsonData = new { rows = activities.Select(q => new { Id = q.Id.ToString(), q.Descriptor }).ToList() }; takes a very long time to execute. Could someone please explain to me why this is and is there a more efficient way? A: The problem is most likely related to your database somehow... As @geofftnz already have mentioned, then you should use a SQL profiler (ex. AnjLab Sql Profiler), and figure out what's going on behind the scenes. The reason for that it's not taking a long time for: var activities = ActivityRepository.GetAll().Where(x => x.AreaId == id); is that it's not sending any queries to the database yet, because of the return type IEnumerable<Activity> (lazy). However when you do: var jsonData = new { rows = activities.Select(q => new { Id = q.Id.ToString(), q.Descriptor }).ToList() }; it will make up a query, and hit the database at .ToList() (eager).
{ "language": "en", "url": "https://stackoverflow.com/questions/7603285", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Displaying .ai files in Java I've been talking with an artist and she is planning to send me .ai files for a project I'm working on that is using Java for its front end. Unfortunately, I'm having a lot of trouble searching for this issue because search engines are replacing .ai with "a" (even when I specifically say not to) or are searching for artificial intelligence. Obviously neither of those are what I'm looking for. Is anyone aware of a Java library capable of rendering .ai files as static images? A: .ai file are vector graphics, they shouldn't be used in production. When the final copy of your image is ready your artist should be sending you a .png / .jpg or similar end working file. .ai stands for Adobe Illustrator and are intended for use only by Illustrator. It's like a developer creating .java files and sending them to a client, it's more likely they'd want a executable jar or a program installer. Worst case scenario you should install CS5.5 (there's a trial version) and exporting the .ai files to a static file type yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: VB.NET DOEVENTS I have a VB6 app, which does a lot of processing in the form_load. A call to DoEvents ensures that the form loads before the processing is complete. However,this does not appear to work in VB.NET i.e. in the following code, the loop finishes befoRe the form is loaded, even though I have called DOEVENTS: Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load For i = 0 To 100000 Application.DoEvents() Dim Test As String = "Test" Next End Sub What have I missed? A: Your statement: A call to DoEvents ensures that the form loads before the processing is complete To the best of my knowledge, this is NOT true. The form "paints" before processing your load event - the processing (that is loading) is still not complete. All that is ensured by a call to DoEvents is OTHER messages get a chance to be handled when you are in the middle of a long processing. MSDN's help of DoEvent() describes it as: Processes all Windows messages currently in the message queue. Also, it specifically states: Unlike Visual Basic 6.0, the DoEvents method does not call the Thread.Sleep method. I believe it might be risky for you to handle your requirement in the Load event. Just a search for "Application.DoEvents in load" in google talks about bad experiences for many. I suggest you can explore handling your requirement in Shown event. A: DoEvents in VB.NET should be actively avoided. Have a look at DoEvents in .NET and Stop DoEvents and DoEvents is Evil to see why. It is a common misconception that this does the same as the VB6 DoEvents. In almost all cases what you want to achieve can be done in some other way in .NET without the need to call DoEvents. Your best bet is probably a BackgroundWorker object have a look at this example to get you started. A point to note though is that you can't update controls on your form from a background worker without using a delegate - but that is another question... A: You should use a BackgroundWorker component in order to do lots of background work without freezing up the user interface in VB.Net. Look at this MSDN tutorial How to run an operation in the background
{ "language": "en", "url": "https://stackoverflow.com/questions/7603294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Connecting to SQL Server 2008 database using asp I tried a lot but I am not able to deal with this problem. I wasted last 2 days without any significant result. Hope I will get some help here. I wanted to connect to a SQL Server 2008 database using ASP. I installed SQL Server 2008, created a database, but I am not able to connect to that database using the asp code. I can see the database in Visual Web Developer, I can also connect it through asp.net using the add connection wizard of visual web developer but I don't want to use add connection wizard. I want to write my asp code to connect to SQL Server database in notepad. My IIS is working and I am able to run asp code to access other database like ms access database but I can't access SQL Server db. The object explorer of SQL Server Management Studio shows: localhost\SQLSERVER3(SQL Server 10.0.1600-RAJ-PC\raj) Databases examples tables System Tables dbo.cars columns id(PK,int,not null) name(varchar(50),null) You can see the SQL Server and its databases in the attached jpg image. I want to connect to example database and then want to access cars table. Please help me. UPDATED here is my code : <html> <head> <title>Guestbook</title> </head> <body bgcolor="white" text="black"> <% 'Dimension variables Dim adoCon 'Holds the Database Connection Object Dim rsGuestbook 'Holds the recordset for the records in the database Dim strSQL 'Holds the SQL query for the database 'Create an ADO connection odject Set adoCon = Server.CreateObject("ADODB.Connection") 'Set an active connection to the Connection object using a DSN-less connection adoCon.Open "ODBC;Driver={SQL Native Client};" & _ "Server=localhost\SQLSERVER3;" & _ "Database=examples;" & _ "Uid=raj;" & _ "Pwd=love1987" 'Set an active connection to the Connection object using DSN connection 'adoCon.Open "DSN=guestbook" 'Create an ADO recordset object Set rsGuestbook = Server.CreateObject("ADODB.Recordset") 'Initialise the strSQL variable with an SQL statement to query the database strSQL = "SELECT name FROM dbo.cars;" 'Open the recordset with the SQL query rsGuestbook.Open strSQL, adoCon 'Loop through the recordset Do While not rsGuestbook.EOF 'Write the HTML to display the current record in the recordset Response.Write ("<br>") Response.Write (rsGuestbook("Name")) 'Response.Write ("<br>") 'Response.Write (rsGuestbook("Comments")) 'Response.Write ("<br>") 'Move to the next record in the recordset rsGuestbook.MoveNext Loop 'Reset server objects rsGuestbook.Close Set rsGuestbook = Nothing Set adoCon = Nothing %> </body> </html> A: I am able to connect using the following connection string on my local dev machine (with SQL 2008 R2 Express): Driver={SQL Server}; Server=hostname\instancename; Database=dbname; Uid=user; Pwd=password One thing I noticed in your code: you are trying to establish a DSN-less connection, then you run a query on it without USE dbname or anything. That may be the issue, or a least an issue. A: Try creating a DSN, and then refer to it by name in your connection string. * *Open the ODBC icon in your Control Panel. *Choose the System DSN tab. *Click on Add in the System DSN tab. *Select the Microsoft Access Driver. Click Finish. *In the next screen, click Select to locate the database. *Give the database a Data Source Name (DSN). *Click OK. set conn=Server.CreateObject("ADODB.Connection") conn.Open "northwind" http://www.w3schools.com/ado/ado_connect.asp
{ "language": "en", "url": "https://stackoverflow.com/questions/7603295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I write a PDF file from NSData source I have a method that returns NSData from a CGPathRef like so ... + (NSData *) createPDFDataWithCGPath: (CGPathRef) path mediaBox: (CGRect) mediaBox { CFMutableDataRef data = NULL; if (path) { CFAllocatorRef allocator = NULL; data = CFDataCreateMutable(allocator, 0); CGDataConsumerRef consumer = CGDataConsumerCreateWithCFData(data); CGContextRef context = CGPDFContextCreate(consumer, &mediaBox, NULL); CFTypeRef keys[1] = { kCGPDFContextMediaBox }; CFTypeRef values[1] = { CFDataCreate(allocator, (const UInt8 *)&mediaBox, sizeof(CGRect)) }; CFDictionaryRef pageInfo = CFDictionaryCreate(allocator, keys, values, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CGPDFContextBeginPage(context, pageInfo); CGContextScaleCTM(context, 1, -1); CGContextTranslateCTM(context, 0, -mediaBox.size.height); CGContextAddPath(context, path); CGContextSetRGBFillColor(context, 0, 0, 0, 1); CGContextFillPath(context); CGPDFContextEndPage(context); CFRelease(pageInfo); CFRelease(values[0]); CGPDFContextClose(context); CGContextRelease(context); CGDataConsumerRelease(consumer); } return (NSData *)data; } When I attempt to use this and write a PDF file from the data I get my file at the correct size but the paths are not drawn into the PDF ... it's an empty document basically. Is it enough to just write the file like so ... [maskData writeToFile: DOCUMENTS_PATH_WITH_STRING(@"maskData.pdf") atomically: YES]; or are their more hoops to jump though to write it as a PDF? A: You're right. If you have data in an NSData object then you can just write it on the disk. But you should add the correct extension (in your case .pdf). It works for everything (videos, pictures, etc...) A: This was a bit of a red herring. The paths were being drawn but had no strokes or fills. The code in my question above is sound and works as expected.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603298", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can I get Android Marketplace to recognize my updates? I updated my Android app, and uploaded it to the Android Marketplace, increasing the VersionCode and VersionName in my manifest file. But it never shows up on my HTC Droid Incredible as there being an update available. Is there something else I have to do? A: No, you've taken the correct steps. If you just uploaded it to the market place. And checked right after. You wont see that there has been an update. As it takes time to work through the system to each device. Especially considering all the other many applications with updates. Give it some time and it should go through.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: TortoiseSVN on Windows Server 2008 - Error Option 200 when checking out I have recently setup a repository on one of my servers with TortoiseSVN. I have created a repository in the following directory: /C:\inetpub\wwwroot\Dev On my local machine, when I try to check out this repository from the following URL, which I put in the URL of Repository, I get the following message. http://the.path.tomyserver:21133/Dev/ The reason for the port number is because it is running on a virtual instance, and port identification is required for access to the instance. I am getting the following error: Error OPTIONS of 'http://the.path.tomyserver:21133/Dev/: 200 OK(http://the.path.tomyserver:21133) It doesn't tell me anything additional. I am lost on what to do next. A: This usually happens if the server isn't set up correctly. Either WebDAV isn't configured or the location does not point to an SVN repository - either way, the WebDAV response to an OPTIONS request must not be "200". A: I was able to figure out the problem, it turns out I did not have the web server actually configured to run Subversion even though I was running the service. This turned out to be the first problem which was corrected by accessing the repository using the following path: svn://the.path.tomyserver/dev Additionally, my webserver was not configured to allow port 3699 through which is the default used by Subversion. Once I opened this port, I was able to successfully checkout my repository.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: pass column in INSERT query I want to update and insert to (in 1 query) my table. I've 1 new row and 2 old records. I use this query (topic): INSERT INTO table (id, title, url) VALUES (1, "test", "http://"), (2, [it is an old record. I don't want to change its title], "https://"), (3, "helloworld", "mms://") ON DUPLICATE KEY UPDATE title = VALUES(title), url = VALUES(url) I don't want to change the second record (id = 2) title column, but if I put NULL, DEFAULT or title after comma, title will change to NULL (also if i put nothing after comma, an error will occur) What can I do? should I use 2 or more queries? Thank you. A: Not 100% clear on your goal but could you not nest a SELECT that would pull back the old title for in place of the text in square brackets? A: You can use something like: INSERT INTO table (id, title, url) VALUES (1, "test", "http://"), (2, "", "https://"), (3, "helloworld", "mms://") ON DUPLICATE KEY UPDATE title = IF(VALUES(title)="",title,VALUES(title)), url = VALUES(url)
{ "language": "en", "url": "https://stackoverflow.com/questions/7603311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Use in XML schema's complexType? I have the following XML complexTypes defined: <xs:complexType name="loss"> <xs:all> <xs:element name="lossCause" type="xs:string"/> <xs:element name="lossDate" type="xs:dateTime"/> <xs:element name="lossDescription" type="xs:string"/> <xs:element name="lossLocation" type="address" minOccurs="0"/> <xs:element name="lossTime" type="xs:string" minOccurs="0"/> <xs:element name="officials" minOccurs="0"> <xs:complexType> <xs:sequence> <xs:element name="official" type="official" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> </xs:element> </xs:all> <xs:attribute name="incidentOnly" type="xs:boolean" use="required"/> <xs:attribute name="lawsuit" type="xs:boolean" use="required"/> </xs:complexType> and: <xs:complexType name="propLoss"> <xs:complexContent> <xs:extension base="loss"> <xs:all> <xs:element name="damageDescription" type="xs:string"/> <xs:element name="property" type="property"/> <xs:element name="responsibleParty" type="contact" minOccurs="0"/> </xs:all> <xs:attribute name="businessOperational" type="xs:boolean" use="required"/> <xs:attribute name="propertyLivable" type="xs:boolean" use="required"/> <xs:attribute name="weatherRelated" type="xs:boolean" use="required"/> </xs:extension> </xs:complexContent> </xs:complexType> However, upon validation, I get an error stating that the all model group isn't allowed within the loss complexType nor its extension propLoss definition. What is it that I'm doing wrong? Thanks! A: A problem with propLoss is that you can't extend an all group in XML Schema (1.0). From the spec: Note: This specification allows only appending, and not other kinds of extensions. This decision simplifies application processing required to cast instances from derived to base type. Future versions may allow more kinds of extension, requiring more complex transformations to effect casting. Not sure what the problem with loss is unless it collateral damage from the propLoss error. A: Note that in XSD 1.1 all groups can be extended in the way shown here, with the meaning being that all of the children mentioned in either all-group must be present in any order. (That is, all-group 1 and all-group 2 get merged together into a single all-group with the concatenation of their children.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7603317", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Simple Webserver for Windows for any Scripting Language I am searching for a simple webserver that runs on windows and which runs code written in a scripting language. A requirement I have is that it supports HTTPS. On Linux I could use a simple python script and load the OpenSSL module, but that does not work on Windows. Also I have found a Powershell server, but it has no HTTPS suppport. So, maybe someone of you has a recommendation. A: I'd suggest IIS 5.x, 6.x, or 7.x which comes with Windows Server 2003 or 2008 all depending on what version of Windows you're running. It supports https, but it's hardly simple. It has powerful capabilities, and can do classic ASP Server side scripting as well as a full blown .NET web apps. It all depends on what you want to do. A: Maybe Manos http://jacksonh.tumblr.com/post/1159500924/manos-de-mono-the-manifesto is an option.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Minimum item processing time for using Parallel.Foreach Suppose I have a list of items that are currently processed in a normal foreach loop. Assume the number of items is significantly larger than the number of cores. How much time should each item take, as a rule of thumb, before I should consider refactoring the for-loop into a Parallel.ForEach? A: This is one of the core problems of parallel programming. For an accurate answer you would still have to measure in the exact situation. The big advantage of the TPL however is that the treshold is a lot smaller than it used to be, and that you're not punished (as much) when your workitems are too small. I once made a demo with 2 nested loops and I wanted to show that only the outer one should be made to run in parallel. But the demo failed to show a significant disadvantage of turning both into a Parallel.For(). So if the code in you loop is independent, go for it. The #items / #cores ratio is not very relevant, TPL wil partition the ranges and use the 'right' amount of threads. A: On a large data processing project I'm working on any loop that I used that contained more than two or three statements benefited greatly from the Parallel.Foreach. If the data your loop is working on is atomic then I see very little downside compared to the tremendous benefit the Parallel library offers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I upgrade from Ruby 1.8.7 to Ruby 1.9.2 for Rails 2.3.8 app? I have searched all over and cannot find anyone with the same problem. I am testing upgrading a large Rails app running Rails 2.3.8 with Ruby 1.9.2 using rvm and nginx+passenger (currently running on 1.8.7 in production). I'm using the mysql2 gem, and my database uses UTF-8 encoding. When I login to the app (standard restful-auth), the db lookup finds a match but when the controller tries to save an attribute change on the User model, it raises a validation error from validates_length_of. I added some debugging output to ActiveRecord and it looks like it thinks all my database record's string values are empty (show up as "[]" in the logs...) I was seeing the same behavior in script/console: User.first.login => "[]", but it was fixed after switching to the mysql2 gem (and updating database.yml adapter value). Why would the console work but not via the website? ActionController / ActiveSupport bug?? Clarification: This is a stable app that has been live for 1+ years in 1.8.7 with hundreds of specs. A: The solution was to disable the xss_terminate plugin. It is old but was quite useful for me to deal with various user input types and roles.. Obviously hooks way to close to ActiveRecord operations dealing with strings to be useful in Ruby 1.9.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Perform action based on hash tag in URL On my page, I have: <a href="#1">Link 1</a> <div></div> <a href="#2">Link 2</a> <div></div> <a href="#3">Link 3</a> <div></div> Say a user goes to this page: http://www.mysite.com/vendors#3 Then I'd like to add a css class to the link with href="#3". How can I do that with jQuery? A: Something like this should do it. You check the window hash value. $(document).ready( function() { $('a[href="' +window.location.hash + '"]').addClass('activeLink'); }); You might need to add the # in there manually. Forget if it is included in hash value. A: window.onhashchange = (function() { var newHash = window.location.hash; $('a[href="' + newHash + '"]').addClass("yourClass"); return arguments.callee; })(); This will run when the document has been accessed and when you click on a link referencing a hash.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603334", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Confused about initialization of SQLite database in Android To implement database access in my application I followed Lars Vogel tutorial, but I'm very confused about a couple of things... The TodoDbAdapter class has the following constructor and open method: public TodoDbAdapter(Context context) { this.context = context; } public TodoDbAdapter open() throws SQLException { dbHelper = new TodoDatabaseHelper(context); database = dbHelper.getWritableDatabase(); return this; } And then this adapter should be initialized like this: dbAdapter = new TodoDbAdapter(this); dbAdapter.open(); 1) The getWriteableDatabase method is the one responsible by throwing a possible SQLException. Why do we need to rethrow in our open method? Is there a reason for this? 2) What's the point of the whole constructor/open pair? Why not initialize dbHelper and get a database ready for writing in the constructor? 3) Why do we return the instance of the object in the open method with return this? If the open method code were to be moved to the constructor, we no would no longer need to return this, it would be implicit, right? What am I missing here? A: 1) The getWriteableDatabase method is the one responsible by throwing a possible SQLException. Why do we need to rethrow in our open method? Is there a reason for this? It's a matter of style to explicitly declare runtime exception like this to highlight that open() might fail. If you don't want to handle it, remove the throws clause. 2) What's the point of the whole constructor/open pair? Why not initialize dbHelper and get a database ready for writing in the constructor? This allows you to create the instance (fast operation) without being forced to do the probably slow operation (disk IO, etc.) of opening the database; most of the time this won't matter because you'll do both in one go as in your code snippet. Also, this keeps the constructor exception-free which some people prefer. 3) Why do we return the instance of the object in the open method with return this? If the open method code were to be moved to the constructor, we no would no longer need to return this, it would be implicit, right? What am I missing here? If it were moved into the constructor, then yes the return this would be implicit. As the usual way to use a DB helper class in Android is to create and open it in one go, open() just does some little builder pattern so you can go TodoDbAdapter helper = new TodoDbAdapter(this).open(); for the most common use case. To sum up: These three points of yours are mainly about style, there's little functional reason I can think of and definitely other ways to do it that are correct.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Open source JavaScript interpreter written in Scala Is there any JavaScript interpreter written in Scala? A: For parsing the actual code, the best thing to start with would probably be parser combinators: http://www.codecommit.com/blog/scala/the-magic-behind-parser-combinators Beyond that you'd need to then build the actual library along with the runtime code to take the parsed elements and execute them, which I'm afraid are out of my realm of knowledge. A: Have you looked at parboiled, a PEG parser in scala.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Jquery Cycle: Can't navigate through slides I'm trying to make a slider with jQuery Cycle where, when you click on one of 5 thumbnails, you switch to the right slide in the slider. Those thumbs are external to the slider. Thing is, for some reason, the startingSlide argument doesn't work and just doing .cycle(number) doesn't either, even if the slider is clearly running. Here's a peek at the code: JS jQuery(document).ready(function(){ var current_slide; jQuery('#slider_accueil').cycle({ fx: 'fade', timeout: 3000, after: onAfter, startingSlide: 0, pager: '#nav', next: '.next_btn_slider', prev: '.prev_btn_slider' }); function onAfter(curr,next,opts){ jQuery('.indicator').removeClass('current') current_slide=opts.currSlide + 1 jQuery('#thumb'+current_slide+' .indicator').addClass('current') } jQuery('#thumb1').click(function(){ jQuery('#slider_accueil').cycle(0); return false; }) jQuery('#thumb2').click(function(){ jQuery('#slider_accueil').cycle(1); return false; }) jQuery('#thumb3').click(function(){ jQuery('#slider_accueil').cycle(2); return false; }) jQuery('#thumb4').click(function(){ jQuery('#slider_accueil').cycle(3); return false; }) jQuery('#thumb5').click(function(){ jQuery('#slider_accueil').cycle(4); return false; }) }) html <div id="sliderAccueil"> <div id="nav" style="display:none;"></div> <img src="/wp-content/themes/customtheme/images/slider_previous.png" class="prev_btn_slider"> <img src="/wp-content/themes/customtheme/images/slider_next.png" class="next_btn_slider"> <div id="slider_accueil" style="position: relative;"> <div style="position: absolute; top: 0px; left: 0px; z-index: 5; opacity: 0; display: none;"> <img src="/wp-content/uploads/2011/09/slider1.jpg"> <div> <div class="maintext"> <h2>Slide 1</h2> <p>Slide 1</p> </div> <div class="link"> <b href="/"></a> <b class="call_slide" href="/"><ig src="/wp-content/themes/customtheme/images/call_slider.png"></a> </div> </div> </div> <div style="position: absolute; top: 0px; left: 0px; z-index: 4; display: none; opacity: 0;"> <ig src="/wp-content/uploads/2011/09/slider2.jpg"> <div> <div class="maintext"> <h2>Slide 2</h2> <p>Slide 2</p> </div> <div class="link"> <b href="/"></a> <b class="call_slide" href="/"><img src="/wp-content/themes/customtheme/images/call_slider.png"></a> </div> </div> </div> <div style="position: absolute; top: 0px; left: 0px; z-index: 3; display: block; opacity: 0.942616;"> <img src="/wp-content/uploads/2011/09/slider3.jpg"> <div> <div class="maintext"> <h2>Reprise des travaux majeurs</h2> <p>Slide 3</p> </div> <div class="link"> <b href="/"></a> <b class="call_slide" href="/"><img src="/wp-content/themes/customtheme/images/call_slider.png"></a> </div> </div> </div> <div style="position: absolute; top: 0px; left: 0px; z-index: 2; display: block; opacity: 0.0573843;"> <img src="/wp-content/uploads/2011/09/slider4.jpg"> <div> <div class="maintext"> <h2>Slide 4</h2> <p>Slide 4</p> </div> <div class="link"> <b href="/"></a> <b class="call_slide" href="/"><img src="/wp-content/themes/customtheme/images/call_slider.png"></a> </div> </div> </div> <div style="position: absolute; top: 0px; left: 0px; z-index: 1; display: none; opacity: 0;"> <img src="/wp-content/uploads/2011/09/slider5.jpg"> <div> <div class="maintext"> <h2>Slide 5</h2> <p>Slide 5</p> </div> <div class="link"> <b href="/"></a> <b class="call_slide" href="/"><img src="/wp-content/themes/customtheme/images/call_slider.png"></a> </div> </div> </div> </div> <div id="thumbnails_slider_accueil"> <ul> <li> <b id="thumb1" href="#1"> <div class="indicator"></div> <div style="background-image:url(/wp-content/uploads/2011/09/thumb1.png)" class="thumbnail"> <p>Voies retranchées trains ajoutés</p> </div> <div class="clear"></div> </a> </li> <li> <b id="thumb2" href="#2"> <div class="indicator"></div> <div style="background-image:url(/wp-content/uploads/2011/09/thumb2.jpg)" class="thumbnail"> <p>Événements</p> </div> <div class="clear"></div> </a> </li> <li> <b id="thumb3" href="#3"> <div class="indicator current"></div> <div style="background-image:url(/wp-content/uploads/2011/09/thumb3.jpg)" class="thumbnail"> <p></p> </div> <div class="clear"></div> </a> </li> <li> <b id="thumb4" href="#4"> <div class="indicator"></div> <div style="background-image:url(/wp-content/uploads/2011/09/thumb4.jpg)" class="thumbnail"> <p>Appels d'offres</p> </div> <div class="clear"></div> </a> </li> <li> <b id="thumb5" href="#5"> <div class="indicator"></div> <div style="background-image:url(/wp-content/uploads/2011/09/thumb5.jpg)" class="thumbnail"> <p>Environnement</p> </div> <div class="clear"></div> </a> </li> </ul> </div> <div class="clear"></div> </div> ^check source, seems I cant put that cleaner than this. Anybody have an idea? PS, It's on purpose that all img are ig and all links are ... Stackoverflow wouldn't let me post. A: I found the answer to my own question... Seems that to use jQuery('#slider_accueil').cycle(0); you need to have the full version linked, and not the lite. Seems like that function is one of those who have been taken out from the conversion from full to lite... Note to self: The lite versions may not have the function you want to do... just spent 2 hours trying all kinds of stuff on that. :p
{ "language": "en", "url": "https://stackoverflow.com/questions/7603340", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JIRA - Send email to anonymous user I'm trying to figure out a way to send an email to an anonymous user when one creates an issue through the email. What I need is for this anonymous user to receive a notification email when the issue was opened,commented and closed. According to their official documentation this can only be done if the creator is already a user in JIRA or if a user will be created on the fly. None of which works for me. The work-arounds that I found so far are: * *JEMH - which promises this functionality but looks unstable, meaning it seems to break (at least for a little bit) with every JIRA update and no downtime is acceptable for me. *Writing my own script as was recommended in the similar thread I have no problems writing my own script but I just wanted to be sure I won't be reinventing the wheel. Are there any other ways of doing this? I'll be very greatful for any help. A: I just noticed this question. JEMH has now evolved into a fully fledged commercial plugin, and has a mass of new features, some of which actually address supporting remote 'anonymous' users for issue creation, essentially turning JIRA into a fully capable email helpdesk solution. Specific template customization is available for this on a per-event basis. Regarding breakages, staying at the 'latest' release gives developers absolutely no time to catchup. Play smart, give all developers a chance to catchup. With the depths of JIRA API's that JEMH plumbs, breakages were unfortunately common, but now are less likely thanks to Atlassian stabilizing some core API's in 5.0+. Work also also underway to provide end-end integration testing, which is a mission in its own right! A: Here is how I did it using the Script Runner pluging, I've told Jira to get emails from my mailbox, and create issues from them. Than, on the workflow, I saved the sender's email and name to a custom fields using the following script: from com.atlassian.jira import ComponentManager import re cfm = ComponentManager.getInstance().getCustomFieldManager() # read issue description description = issue.getDescription() if (description is not None) and ('Created via e-mail received from' in description): # extract email and name: if ('<' in description) and ('>' in description): # pattern [Created via e-mail received from: name <email@company.com>] # split it to a list description_list = re.split('<|>|:',description) list_length = len(description_list) for index in range(list_length-1, -1, -1): if '@' in description_list[index]: customer_email = description_list[index] customer_name = description_list[index - 1] break else: # pattern [Created via e-mail received from: email@company.com] customer_name = "Sir or Madam" # split it to a list description_list = re.split(': |]',description) list_length = len(description_list) for index in range(list_length-1, -1, -1): if '@' in description_list[index]: customer_email = description_list[index] break # if the name isn't in the right form, switch it's places: if (customer_name[0] == '"') and (customer_name[-1] == '"') and (',' in customer_name): customer_name = customer_name[1:-1] i = customer_name.index(',') customer_name = customer_name[i+2:]+" "+customer_name[:i] # insert data to issue fields issue.setCustomFieldValue(cfm.getCustomFieldObject("customfield_10401"),customer_email) issue.setCustomFieldValue(cfm.getCustomFieldObject("customfield_10108"),customer_name) than, send the mail using the following script: import smtplib,email from smtplib import SMTP from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email import Encoders import os import re from com.atlassian.jira import ComponentManager customFieldManager = ComponentManager.getInstance().getCustomFieldManager() cfm = ComponentManager.getInstance().getCustomFieldManager() # read needed fields from the issue key = issue.getKey() #status = issue.getStatusObject().name summary = issue.getSummary() project = issue.getProjectObject().name # read customer email address toAddr = issue.getCustomFieldValue(cfm.getCustomFieldObject("customfield_10401")) # send mail only if a valid email was entered if (toAddr is not None) and (re.match('[A-Za-z0-9._%+-]+@(?:[A-Za-z0-9-]+\.)+[A-Za-z]{2,4}',toAddr)): # read customer name customerName = issue.getCustomFieldValue(cfm.getCustomFieldObject("customfield_10108")) # read template from the disk template_file = 'new_case.template' f = open(template_file, 'r') htmlBody = "" for line in f: line = line.replace('$$CUSTOMER_NAME',customerName) line = line.replace('$$KEY',key) line = line.replace('$$PROJECT',project) line = line.replace('$$SUMMARY',summary) htmlBody += line + '<BR>' smtpserver = 'smtpserver.com' to = [toAddr] fromAddr = 'jira@email.com' subject = "["+key+"] Thank You for Contacting Support team" mail_user = 'jira@email.com' mail_password = 'password' # create html email html = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ' html +='"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">' html +='<body style="font-size:12px;font-family:Verdana">' html +='<p align="center"><img src="http://path/to/company_logo.jpg" alt="logo"></p> ' html +='<p>'+htmlBody+'</p>' html +='</body></html>' emailMsg = email.MIMEMultipart.MIMEMultipart('alternative') emailMsg['Subject'] = subject emailMsg['From'] = fromAddr emailMsg['To'] = ', '.join(to) emailMsg.attach(email.mime.text.MIMEText(html,'html')) # Send the email s = SMTP(smtpserver) # ip or domain name of smtp server s.login(mail_user, mail_password) s.sendmail(fromAddr, [to], emailMsg.as_string()) s.quit() # add sent mail to comments cm = ComponentManager.getInstance().getCommentManager() email_body = htmlBody.replace('<BR>','\n') cm.create(issue,'anonymous','Email was sent to the customer ; Subject: '+subject+'\n'+email_body,False) content of new_case.template: Dear $$CUSTOMER_NAME, Thank you for contacting support team. We will address your case as soon as possible and respond with a solution very quickly. Issue key $$KEY has been created as a reference for future correspondence. If you need urgent support please refer to our Frequently Asked Questions page at http://www.example.com/faq. Thank you, Support Team Issue key: $$KEY Issue subject: $$PROJECT Issue summary: $$SUMMARY All scripts should be attach to the workflow, to Create transition.The scripts are written using Jython, so it needs to be installed to use it. A: I doubt this functionality is available already built-in to JIRA, and I have not seen a plugin that will do it. I looked into this in the past and came up empty. I suspect it is not built in because for many potential customers it would allow them to get away with a 10 user license and yet still support thousands of users. We went with the unlimited user license instead. Update: I meant to add to this that you could write a script that would do this, I think. But it looks like it would be a PITA with having to create a custom listener for it to capture changes to the issue https://developer.atlassian.com/display/DOCS/Plugin+Tutorial+-+Writing+event+listeners+with+the+atlassian-event+library A: You can send notification to email stored in Jira custom field using Raley Email Notifications The configuration is trivial, here's an example how to do it: https://wiki.raleyapps.com/display/RAL/Sending+email+to+value+from+JIRA+issue+custom+field
{ "language": "en", "url": "https://stackoverflow.com/questions/7603342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Set JavaScript 'this' to an element on click I am looking for a way similar to jQuery's .attr() method, where when I click on an element (a li tag in this case) I can get the tags attributes. So my question is, how can I make a function that when an li is click, the this variable in the function is equal to that DOM element. I am trying to do this without the use of jQuery. This is what I have that I was thinking would work but it doesn't: function selected(){ this.title = this.getAttribute("title"); } Assuming there is an element li with the attribute title and an onclick with the function selected() as the choice. A: This is a confusing question, but something like: $this = event.target; $this.title = $this.getAttribute("title") || $this['title']; might work, but check that this is referencing the element. A: If you assign the onclick in-line (inside the html), then you would need to handle it like this. HTML <li onclick="selected(this)">Click Me</li> Javascript function selected(element){ alert(element.title); } If you assign the onclick from JavaScript then this will work: HTML <li id="myli">Click Me</li> Javascript function selected(){ alert(this.title); } document.getElementById("myli").onclick = selected; A: May I suggest the following: document.onclick = function(e){ if (e.target.tagName.toLowerCase() == 'li'){ alert(e.target.title); } }; JS Fiddle demo. A: <script> function itemSelected(listItem) { // listItem is your HTMLLIElement alert(listItem.title); } </script> <ul> <li title="test1" onclick="itemSelected(this);">Test 1</li> <li title="test2" onclick="itemSelected(this);">Test 2</li> </ul> A: In JavaScript, the value of this varies based on how a function is invoked. There are basically 3 patterns of invocation: * *Using the new operator e.g. new Foo(). In this case when Foo is being executed this refers to the new object that is being created. *Dereferencing a method on an object e.g. foo.bar(). In this case when bar is being executed this refers to foo. When a method isn't dereferenced from another object, for example when just invoking a global method, the this refers to the global scope, or global object. *Using apply or call e.g. foo.apply(bar). By using call or apply you can tell the interpreter what this should refer to during an invocation. *As a somewhat special case, this refers to the node for event handlers. In your case if you have a global function called selected that is invoked from an event handler such as the following: <li onclick="selected()"> then during the invocation of selected, since it wasn't dereferenced from anywhere this will refer to the global object. If you want this to refer to the object whose event handler is firing then you need to invoke selected using the call or apply pattern and pass the value this (which will refer to the node) in as the context parameter. <li onclick="selected.call(this)"> I usually try to shy away from using the call or apply since it isn't obvious from looking at the function what this will refer to. Therefore, in this case I would suggest passing in the node as a parameter. <script> ... function selected(node) { node.title = node.getAttribute('title'); } </script> ... <li onclick="selected(this)"> With all this being said, the implementation of your selected function doesn't make a ton of sense since it is essentially a no-op (in many cases).
{ "language": "en", "url": "https://stackoverflow.com/questions/7603345", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: POST/REDIRECT/GET vs custom implementation I have some forms, and am currently using an implementation as described below: <form action="/formpost.php" method="post" name="form1" id="form1"> <input type="hidden" name="to" id="to" value="__COMMENT1" /> <!-- rest of form --> </form> __COMMENT1 refers to the page where I want the user to be redirected after the form posts. Pretty much what happens is that the form is posted to formpost.php, the $_POST array is converted to $_SESSION['POST'], the $_POST is unset, and then the user is redirected to the location referenced in the value of the hidden input field ([id = to] always the same ID/name.) I can then continue to use the user's form submitted values (referenced from the $_SESSION array) regardless of whether they go 'back', refresh, etc. Is there anything wrong with this? Are there any benefits to using the POST/REDIRECT/GET pattern instead? A: Nothing wrong with your method, it's more convenient than PRG. though, I see no point in keeping POST variables unless in case of error. and there is no point in unsetting $_POST, of course. Well, after some explanation it seems that your setup is quite wrong. there is no point in making single action for all forms as well as in unnecessary redirect. make your form action the actual script that validates the form. * *on success, redirect wherever you want. *on error: * *save POST data and error messages into session and redirect to the same URL *populate the form and unset POST data and errors *show the form
{ "language": "en", "url": "https://stackoverflow.com/questions/7603352", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android ListAdapter or Possibly ListView Updating Text at Runtime Hello folkes I have this little problem for which I cannot find a suitable answer looking around the web and on these forums. Please don't direct me to articles in which people have requested list view text color changes at run time, as I read lots of them and not found one to help me out. I have a simple ListView that displays an array of String objects via the use of a ListAdapter. I need to update some of ListView Strings at run time, based on their contents. Using a global reference to the list adapter used in the lists views creation I can get the contents of each list view String using following code below. However, in addition to retrieval I'd like to be able to modify each string in turn, then put it back in the same index position and have the list view reflect the changes. How? for (int x = 0; x <= listAdapter.getCount();x++) { Object o = this.listAdapter.getItem(x); if (o.getClass().getSimpleName().equals("String")) { String s = (String) o; s = modifyString(s); //s is the string I want to modify then put back in the same place. }//end if }//end for A: As far as I know you cannot change the items in an Adapter - unless you are using a custom Adapter (by extending a BaseAdapter etc...) So, I think you will have to: * *make sure you Adapter's constructor takes in the data structure that holds your strings *make sure your data structure is global *make the changes in that data structure whenever you need to *call myAdapter.notifyDataSetChanged(); This will tell adapter that there were changes done in the list and listview should be recreated. And after your listview is renewed you can even take the user back to the index by: list.setSelection(positionWhereTheUserClicked); I hope this helps, let me know if you need more code references. Here is some code private ArrayList<String> results = new ArrayList<String>(); //global private BaseAdapter searchAdapter = new BaseAdapter (results, this); //global private void updateResults(final ArrayList<String> updatedList){ results = updatedList; final ListView list = (ListView)findViewById(R.id.search_results); list.setAdapter(searchAdapter); list.setOnItemClickListener(new ListView.OnItemClickListener(){ // implementation of what happens when you click on an item // }); searchAdapter.notifyDataSetChanged(); } This code works just fine on my end, I hope it helps. A: Just stumbled on this problem and found a solution. I'm using a m_ListAdapter = new SimpleAdapter(this, m_List, R.layout.option_list_row, columns, renderTo); Each item in my listView is a manu option causing a dialog to show, once data is received through the dialog, all I have to do is just create a new SimpleAdapter with an updated ArrayList that includes the new data, then just setAdapter to the new adapter. The ListView will update instantly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603358", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: cURL script works when run from one server but not another I recently moved a cURL script from one server (Ubuntu) to another (Mac OS X). The script worked when run from the Ubuntu server but it doesn't work on the OS X server. I get error 35 and this: error:14077417:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert illegal parameter Any ideas? Edit: Here's what's probably a really good clue. This doesn't work: curl -v https://foo.com/OA_HTML/RF.jsp?function_id=123 But this does: curl -v -sslv3 https://foo.com/OA_HTML/RF.jsp?function_id=123 Now I just need to know how to do the equivalent of the second command from within PHP. A: Could be some php.ini setting or apache follow or openbasedir setting ! A: I know I'm late but the equivalent of curl -v -sslv3 https://foo.com/OA_HTML/RF.jsp?function_id=123 is $ch = curl_init(); curl_setopt($ch, CURLOPT_SSLVERSION, 3); //set to force SSL3 curl_setopt($ch, CURLOPT_URL, "https://foo.com/OA_HTML/RF.jsp?function_id=123"); $result = curl_exec ($ch); //execute the request A: Most of the time CURL over SSL uses OpenSSL, more than likely either CURL or OpenSSL is not installed or enabled on the new server. Save a file on the server with: <?php phpinfo(); ?> and check if these are enabled ADD Either that or your SSL Certificates where not created on the machine you are trying to use them on. Each SSL certificate has specific information about each machine (if received from an online vendor)
{ "language": "en", "url": "https://stackoverflow.com/questions/7603359", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Removing elements after DOM is ready I have a few fields that a user can fill in (e.g., name, number, address), then they can click "Add" which creates a div that displays the information they just entered with a "Remove" button (a href) for each entry. The problem I'm having is that once the DOM is ready, the remove buttons do not work. I've hardcoded a remove button that removes the 3rd div (3rd is arbitrary), and that works, but not the ones that are generated after the page is loaded. My question is how can I have the remove buttons work after the DOM is ready? Here is the remove function (id is passed in, so it knows which div to remove): function remove(id) { $("div.reviewSub"+id).remove(); } And here is the handler to call the function: $(".remove").click(function(event) {remove(event.target.id);}); The way I display the data after it has been retrieved is with .append(): $(".reviewSub"+num).append("<a href=\"#\" class=\"remove\" id=\"" + num + "\">Remove</a>"); A: You can use the live method in jQuery. $('.remove').live('click', function(event){ remove(event.target.id); }); I suspect that you have the code $(".remove").click(function(event) {remove(event.target.id);}); before you are appending the DOM. As a result, jQuery has not been able to bind the click event to the element as the element doesnt exist yet. More documentation here http://api.jquery.com/live/
{ "language": "en", "url": "https://stackoverflow.com/questions/7603360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Architecture for Phone to Cloud to Tablet I want to send messages from an Android handset (and possibly from embedded devices) to the Cloud, and then from the Cloud to an Android app running on a Tablet. Does anybody have ideas/suggestions for the architecture? Gotchas? Recommendations on what or which cloud services/providers are best? IOW, which Cloud services have both a good API and make it easy/cheap for the end user (MY end user, that is)? A: Just replace overhyped word 'Cloud' to 'Server' and you will google tons of answers. I will give you one here: use simple rest over http, once you got this working you can move your app to any cloud you want (depending on the server technology you'll choose of course). A: If you want to send messages between two devices all you need to do is have a server to centralize the communication. Server could be anything, but generally a webapp is best. Python, PHP, Ruby, Java. The Android application, on either phone or tablet, would send a message to the server over HTTP. The server would receive the message and store that to some persistence storage (DB, Cassandra, MongoDB, etc). In fact here is an article discussing just that: http://www.rackspace.com/cloud/blog/2010/05/12/cassandra-by-example/ Then your other Android application would periodically poll for messages from the server by hitting a different URL. On polling the server it would look up in it's topic bucket had it received any messages since the last time it checked. If so the server would reply with the messages it has. For deployment you can deploy this server to the cloud or regular old web hosting service. By cloud I mean a virtualized hosting server like Amazon EC2, Rackspace, Google App Engine, Slicehost, etc. There are plenty of them. But, you don't have to live in the cloud for this to work. You can just as easily deploy to a traditional web hosting service. Rackspace offers both virtual hosting, and non-virtual hosting with renting models for physical hardware.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unknown Padding on Containing Element There is what appears to be a 2px bottom padding on the image to the containing element. I am able to resolve this by removing the z-index. I need the z-index arrangement however to provide an inset box shadow on the image. It can be seen here: http://jsfiddle.net/JkLAP/ A: just add .photo{display:block} demo: http://jsfiddle.net/JkLAP/2/
{ "language": "en", "url": "https://stackoverflow.com/questions/7603367", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: $.get() function called three times when triggered, how to prevent it I have got main html page called myitem.html, then I used ajax to display the itembox which is loaded from itembox.php file, And When I scroll down inside the itembox, the new content from the new.php file are appended in the end of the itembox, However the newcontent in the itembox are appended thress time which all the same, How can I only append one times, here is part of the html code in itembox.php <div id="itemscrollbox"> <ul id = "scroll"> <li>0 item</li> <li>0 item</li> <li>0 item</li> <li>0 item</li> <li>0 item</li> </ul> </div> here is part of the javascript code for scrolling update in the itembox.php file: function scroll() { var scrolltop = $('#itemscrollbox').attr('scrollTop'); var scrollheight = $('#itemscrollbox').attr('scrollHeight'); var windowheight = $('#itemscrollbox').attr('clientHeight'); var scrolloffset = 0; if (scrolltop >= (scrollheight - (windowheight + scrolloffset))) { var ID = $("#myscroll li:last").attr("id"); $('#status').text('Loading more items...'); $.get('picturedata.php', 'id=' + ID + '', function(newitem) { $('#scroll').append(newitem); updateitemstatus(); }); } setTimeout('scroll();', 2500); } here is part of the code in new.php file: *first items *second items the output should give me: first item second item but it gives me: first item second item first item second item first item second item Any one could tell me how to resolve this problem, thanks a lot! here is how the scroll function called: $(document).ready(function(){ updateitemstatus(); scroll(); }); i assume that because the main html page which is myitem.html load itembox inside it, and itembox append new content from new.php while scrolling down, so that the function $.get are called three times, but I couldn't figure out how to avoid that. A: You should $.clear() your result div before appending. $('#scroll').clear(); $.get('picturedata.php', 'id='+ ID+'', function(newitem){ $('#scroll').append(newitem); updateitemstatus(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7603371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: java ee api is missing on project classpath while using httpunit for servlet testing in maven I want to run the servlet testing example available here using maven. Javaee web api should be declared as provided: <dependency> <groupId>javax</groupId> <artifactId>javaee-web-api</artifactId> <version>6.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>httpunit</groupId> <artifactId>httpunit</artifactId> <version>1.7</version> <scope>test</scope> </dependency> However, one of the tests in the example throws ServletException. NetBeans complains that java ee api is missing on project classpath. How does one solve this issue? EDIT It is not a NetBeans issue, it is a maven issue. A: Now this is the most debilitating issue I have ever faced in my Java days. And it is followed by the most ridiculous workaround I have ever seen, ever: <dependency> <groupId>httpunit</groupId> <artifactId>httpunit</artifactId> <version>1.7</version> <scope>test</scope> </dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-web-api</artifactId> <version>6.0</version> <scope>provided</scope> </dependency> Yes, permute the declaration of dependencies in the pom.xml (see here for "why") and make javaee-web-api last. A: It means that maven (or netbeans...I haven't used netbeans in 10 years), couldn't download or find that artifact in the local repository. The scope provided means: I need the jar to compile my source code, but don't bundle the jar in the final package.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603373", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to properly encode contentUrl in MPMoviePlayerController to allow for spaces? I'm using the MPMoviePlayerController to play video in an iPad app. When I set contentUrl to a local file with a space in the name, the player won't acknowledge or play the file, not even an error. IF I urlEncode the path, it fails with an error ("can't play file"). Does anyone know how to properly encode contentUrl in MPMoviePlayerController to allow for spaces? A: How are you constructing the URL? If you use [NSURL fileURLWithPath:myPath] that should give you an NSURL* that's correct.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Database Design: Categories in their own table? I am redesigning a few databases into one encompassing database, and I have noticed the previous designer(s) of the old databases like to store categories in their own tables. For example, say that there is a table boats(bid: integer, bname: string, color: integer), and in the application there is a drop-down box allowing the user to specify the colour of the boat, then there is a table color(cid: integer, cname: string). I would have not included the color table, and just put the colours as strings in the boats table. I realize that this decreases redundant storage of colour names, but is the added run-time cost of joining the boat table with the colour table "worth it"? Also the drop-downs are populated with SELECT cname FROM color statements, while I would have defined a view on SELECT DISTINCT color FROM boats to populate the drop-downs. The example is simple, but this happens multiple times in the system I am redesigning, even for categories with only two options. This has resulted in many tables with only 2 fields. Some only have 1 field (I haven't figured out what those are for yet, but I think they are only to populate the drop-downs, and the actual tables contain the values as well). A: I would personally keep them in their own table if this were my DB. If you get into a situation where you get the requirement that Boats a,b and c can only come in silver and black then you will be thankful that you did. I've seen these types of requests bubble up down the road in a lot of projects. If you are just concerned about the query complexity you could create a view that joins the information you need so you only need to query it once and with no JOIN. If you are worried about the performance implications of the JOIN then I would look at creating the appropriate indexes or possibly an indexed view. Good luck! A: When you know a column should have a limited set of values, you should tell the dbms to enforce that limited set. The three most common ways to deal with that kind of requirement are * *ignore it, *set a foreign key reference to a table of colors, and *use a CHECK() constraint against a list of colors. Of those three, setting a foreign key to a table of colors tends to make life easiest. I realize that this decreases redundant storage of colour names, but is the added run-time cost of joining the boat table with the colour table "worth it"? This is a different issue. First, storing foreign key values is a form of data integrity, not a form of redundancy. Keys exist for two reasons: 1) to identify things in the real world, and 2) to be stored in other tables. (Because the thing the key identifies is relevant to the other table.) Second, if you identify colors by assigning an arbitrary id number to them, you have to use a JOIN to get human-readable information. But colors, like many attributes, carry their identity with them. If you use the color's name itself ("red", "orange", etc.) or use a human-readable code for the name ("R", "O", etc.) you don't need a join. You do still need a table of colors (or a CHECK() constraint), because the column in boats has a limited set of values, and the dbms should enforce use of that limited set of values. So you could do something like this. create table boats ( boat_id integer primary key, registered_name varchar(35) not null, hull_color varchar(10) not null references hull_colors (color) ); create table hull_colors ( color varchar(10) primary key ); insert into hull_colors values ('red'),('orange'),('yellow') etc. Both those tables are in 5NF. A: It is generally better to have a normalized database. However, in your example, you can use a Categories(ID, Type, Name) table and store the colors as ( 3, "Color", "Blue" ), ( 4, "Color", "Red" ), ... This way, you can store more categories in the same table and in the same time, store them separately. Populating a drop-down list will require a simple select of the form select ID, Name from Categories where Type = 'Color'. EDIT: Note that this solution violates the first rule of database normalization, as @Catcall said. A 3NF table would be Colors(ID, Name). This way, you can refer to a certain color using its ID. Using select distinct color from boats to populate a drop-down list has many disadvantages, for example, what if the Boats table contains no records. Then, your select will return nothing and the drop-down control will not be populated with any value. Another problem is when you have fields containing 'Red' and 'red' or similar. See more details on Database Normalization here A: It sounds like those are lookup tables so that if the end user want's to add an additional color then they can add it to the database and it will then propagate down the UI. This also gets into normalization. If there is only one place where colors is referenced then the lookup table is not really necessary. However if there are multiple tables where colors are referenced for different things then the lookup table will save you a huge headache down the road.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Verify HTTP Post Notification from Polldaddy with PHP I have a PHP script that gathers variables from a HTTP Post notification sent by PollDaddy. See here for more info on PollDaddy's API: http://support.polldaddy.com/http-post-notifications/ I am worried that if someone finds the URL to my PHP script, it could potentially be taken advantage of. (e.g. sending fake http post requests, or spamming with http post requests) What are the best ways to secure this script and ensure that valid requests are only coming from PollDaddy? Any help is appreciated! A: It looks like you control the url that it goes to. You could add a ?super_secret_key=randomstring at the end of the url and check to make sure that exists in the $_GET array on ever request. However, at the end of the day, this security is based only on "Security Through Obscurity". There isn't really anything inherently "secure" about this method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to unit test on Customer Transformer implementation of Solr How can I do unit test on Customer Transformer implementation of Solr ? Thanks A: A starting point would be to check the Transformers test @ http://svn.apache.org/repos/asf/lucene/dev/branches/lucene_solr_3_3/solr/contrib/dataimporthandler/src/test/java/org/apache/solr/handler/dataimport/ and emulate them For unit testing you can probably do it standalone by including the jars, or include the tests within the solr source code and run the complete test suite.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Any good cocoa libraries that include both salt and IV AES Encryption? I am just polishing up my encryption tool, but I noticed I am missing the salt, which is importnat in order to make the encryption more secure. I am using some built in cocoa methods, but they don't include either. I don't want to write this from scratch because it would be hard to get right. Are there any good cocoa libraries out there that include salt and IVs for AES Encryption? Thanks for the help A: Yes, Rob Napier has written such an implementation. For decryption, you'll have to write that yourself: I will leave the decrypt method as an exercise for the reader. It’s almost identical, and it’s a good idea to actually understand this code, not just copy it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603385", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Facebooks new auth dialog not working? Not sure if Facebooks new auth dialog (beta) as described here is working. I have enabled it in my apps advanced settings, but it still shows the old dialog. Url is constructed like this: https://www.facebook.com/dialog/permissions.request?app_id=XXX&display=popup&next=XXX8&response_type=token%2Csigned_request&fbconnect=1&perms=create_event%2Cpublish_actions&sdk=joey Am I missing something here? A: Currently publish_actions permission only works for game apps even if you enabled the new Auth dialog. For your users to see the new OAuth dialog, you need to add them to your app's testers. Otherwise, they will still get the old dialog.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603389", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create a web template editor with rails I'm pretty new to rails, and i'm trying to build a web template editor in rails where users can come in and create their websites without having any programming knowledge. something similar to: http://imcreator.com/ muse.adobe.com www.wix.com www.squarespace.com I'm wondering if there are any gems or plugins I was also told that i should look for a control library? any ideas? A: There are a number of CMS kits like Refinery, Radiant, or you can use something like Comfortable Mexican Sofa which is maintained by an associate of mine. Building a CMS isn't especially tricky, but getting a good general-purpose one built can be fussy. A: Would a CMS work for this? Like RefineryCMS.com? I'm going to be doing this too - but will be taking another approach. More of a 'showcase/showroom' direction where the templates are pre-made but they can upload artwork and change content. Anyhow - good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7603390", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Solr query based on a string field's subset I'd like to send a string to Solr and let it answer with all records which are a subset of that string. The string I would send has integer numbers separated by spaces. I wanna make solr give me all records where a specific string field is a subset of the numbers I provide as the request string. An example... Imagine I have an string field indexed in Solr which is in reality a set of integers separated by space. For example, let's say I have the following record's field indexed in Solr: * *"888110" *"888110 888120" *"888110 888120 888130" *"888110 888120 888130 888140" *"888110 888130 888140" *"888110 888140" *"888140" *"888120 888130" I wanna Solr to receive a query with, for example, "888110 888140" and reply with the following records: * *"888110" *"888110 888140" *"888140" If I query by "888110 888120 888130" the retrieved records would be... * *"888110" *"888110 888120" *"888110 888120 888130" *"888120 888130" The retrieved records must be exactly a subset of the numbers provided as a string. Is it possible to make Solr behave like this? A: I'm a bit confused why in the first example "888110" is not returned, but it is in the second example. Anyways, if I understand generally what you are trying to do, I would be making a new field multi valued and use your boolean operators (AND ,OR) on the query. eg in the schema <field name="code_string" ... /> <field name="codes" ... multiValued="true"/> so you have a document like <doc> <arr name="codes"> <str>811001</str> <str>811002</str> </arr> and in your query ?=codes=811001 OR codes=811002 OR .... In my experience with solr it is generally cleaner / more maintainable to sacrifice a little memory rather than creating debilitatingly complex chains of filters etc
{ "language": "en", "url": "https://stackoverflow.com/questions/7603393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I display "Only X left Threshold" on my Magento product grid? I’m using a custom template I created, and I’m trying to display “Only X left Threshold” set at 1 on the category list(grid) page. Magento ver. 1.4.1 - Can anyone help me out? EDIT Thanks Alan, solved. To those who need this for configurable products, here is the code for 'Less than 4 products remaining" <?php if($_product->getTypeId() == "configurable"): $total = 0; $ids = $_product->getTypeInstance()->getUsedProductIds(); ?> <ul> <?php foreach ($ids as $id) : $simpleproduct = Mage::getModel('catalog/product')->load($id); ?> <li><?php $simpleproduct->getName()." - ".(int)Mage::getModel('cataloginventory/stock_item') ->loadByProduct($simpleproduct)->getQty(); ?> </li> <?php $total = $total + (int)Mage::getModel('cataloginventory/stock_item')->loadByProduct($simpleproduct)->getQty(); ?> <?php endforeach; ?> <li><?php if ($total < 4) { echo ("Only ".$total." Left!"); }?></li> </ul> <?php endif; ?> A: if($product->getQty() < $some_num) { echo 'Only' . $product->getQty() . ' left'; } A: $qtyStock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty(); if($qtyStock < 10) { echo 'Only' . $qtyStock . ' left'; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7603397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: UIPicker crashing My UIPicker is crashing if the NSArray of objects is greater than 3, with the following error: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSAutoreleasePool pickerView:titleForRow:forComponent:]: unrecognized selector sent to instance Here is my code for the functions: - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. self.glassPickerOptions = [[NSArray alloc] initWithObjects:@"3mm",@"4mm",@"DG4+4",@"DG4+6",nil]; [glassPicker setFrame:CGRectMake(0, 0, 320, 162)]; [glassPicker selectRow:1 inComponent:0 animated:NO]; } - (NSInteger) numberOfComponentsInPickerView:(UIPickerView *)pickerView { return 1; } - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component { NSInteger glassPickerOptionsCount = self.glassPickerOptions.count; NSLog(@"%i", glassPickerOptionsCount); return glassPickerOptionsCount; } - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { return (NSString*) [self.glassPickerOptions objectAtIndex:row]; } Hopefully I havent missed anything. Thanks in advance A: It seems that you overrelease your picker view, you can see this because the message is being sent to an autoreleasepool and not the object you expect, you should check out your retain/releases for your picker see whats going on, cant really tell from the code posted...
{ "language": "en", "url": "https://stackoverflow.com/questions/7603399", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make a rounded corner image in Java I want to make a image with rounded corners. A image will come from input and I will make it rounded corner then save it. I use pure java. How can I do that? I need a function like public void makeRoundedCorner(Image image, File outputFile){ ..... } Edit : Added an image for information. A: I suggest this method that takes an image and produces an image and keeps the image IO outside: Edit: I finally managed to make Java2D soft-clip the graphics with the help of Java 2D Trickery: Soft Clipping by Chris Campbell. Sadly, this isn't something Java2D supports out of the box with some RenderhingHint. public static BufferedImage makeRoundedCorner(BufferedImage image, int cornerRadius) { int w = image.getWidth(); int h = image.getHeight(); BufferedImage output = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = output.createGraphics(); // This is what we want, but it only does hard-clipping, i.e. aliasing // g2.setClip(new RoundRectangle2D ...) // so instead fake soft-clipping by first drawing the desired clip shape // in fully opaque white with antialiasing enabled... g2.setComposite(AlphaComposite.Src); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setColor(Color.WHITE); g2.fill(new RoundRectangle2D.Float(0, 0, w, h, cornerRadius, cornerRadius)); // ... then compositing the image on top, // using the white shape from above as alpha source g2.setComposite(AlphaComposite.SrcAtop); g2.drawImage(image, 0, 0, null); g2.dispose(); return output; } Here's a test driver: public static void main(String[] args) throws IOException { BufferedImage icon = ImageIO.read(new File("icon.png")); BufferedImage rounded = makeRoundedCorner(icon, 20); ImageIO.write(rounded, "png", new File("icon.rounded.png")); } This it what the input/output of the above method looks like: Input: Ugly, jagged output with setClip(): Nice, smooth output with composite trick: Close up of the corners on gray background (setClip() obviously left, composite right): A: I am writing a follow up to Philipp Reichart's answer. the answer of as an answer. To remove the white background (seems to be black in the pictures), change g2.setComposite(AlphaComposite.SrcAtop); to g2.setComposite(AlphaComposite.SrcIn); This was a big problem for me because I have different images with transparency that I don't want to lose. My original image: If I use g2.setComposite(AlphaComposite.SrcAtop);: When I use g2.setComposite(AlphaComposite.SrcIn); the background is transparent. A: I found another way using TexturePaint: ImageObserver obs = ...; int w = img.getWidth(obs); int h = img.getHeight(obs); // any shape can be used Shape clipShape = new RoundRectangle2D.Double(0, 0, w, h, 20, 20); // create a BufferedImage with transparency BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics2D bg = bi.createGraphics(); // make BufferedImage fully transparent bg.setComposite(AlphaComposite.Clear); bg.fillRect(0, 0, w, h); bg.setComposite(AlphaComposite.SrcOver); // copy/paint the actual image into the BufferedImage bg.drawImage(img, 0, 0, w, h, obs); // set the image to be used as TexturePaint on the target Graphics g.setPaint(new TexturePaint(bi, new Rectangle2D.Float(0, 0, w, h))); // activate AntiAliasing g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // translate the origin to where you want to paint the image g.translate(x, y); // draw the Image g.fill(clipShape); // reset paint g.setPaint(null); This code can be simplified if you have a non-animated image, by creating the BufferedImage only once and keeping it for each paint. If your image is animated though you have to recreate the BufferedImage on each paint. (Or at least i have not found a better solution for this yet.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7603400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Compiling Objective-C files into object files (.o) I have been tasked to create object .o files for an iOS project in Xcode 4. I have tried the following command which works on NSObject classes gcc -c implemtationfile.m but if I try to run the command on a class inherited from UIViewController for example I get a ton of errors starting with UIKit/UIKit.h: No such file or directory Secondly, since there are multiple files in the project, is it possible to create one .o file for all source files? A: Not surprised you've got errors. You are trying to compile iOS code from OSX. If you invoke GCC from the terminal, you'll get the Mac OS X compiler. Even if it can produce .o files, those object files are Mach-O object files, meaning they are compiled as object-files against the Mac OS X compiler tool-chain. No iOS here. Your object files will have the Intel (x86) or PPC architecture. iPhone is ARM, so you're wasted. You should be able to proceed ARM object files using the right GCC compiler tool-chain. Something like: /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/arm-apple-darwin10-gcc-4.0.1 I haven't tested, but that's clear that you need to use the iPhone ARM version of GCC. Just invoking GCC will invoke the Mac OS X version (in /usr/bin/). A compiler like GCC needs to be compiled for a host and a target architecture. The host architecture is the architecture in which you will invoke the compiler. The target one is the architecture for which you'll build binaries, or object files. So try to compile your code with the correct version of GCC, which suits the iPhone target architecture. Also note that, if compiling against a framework, you should use the -framework GCC argument.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: MVC 3 - Display collection of items in rows I have a collection that I'm displaying, like so: @foreach (var employee in Model.Employees) { <a href="#">@employee.Name</a> } This just displays everything in one long row. I'd like to display the collection in rows of 3, so that I have 3 items displayed, break to a new line, the next 3 items displayed, another break to a new line, and so on. Is there a simple way to do this? A: Mystere Man is right, and I typically use list items as the semantic markup elements for collections of links. <ul> @foreach (var employee in Model.Employees) { <li><a href="#">@employee.Name</a></li> } </ul> Then use CSS styling to make your list look how you want it to use (no bullet points, etc.) If you make the ul have a fixed with, and each li inside of each have a width of 1/3 of that, then make the lis show up as inline blocks, that ought to give you what you're going for. (jsfiddle) A: This has nothing to do with MVC, it's an HTML problem. You need to render HTML to make it do what you want. Look at the rendered output. Typically you would wrap rows in divs or other elements in order to create the semantic markup you want. A: not using css, here's a simpleish way of doing this. @{ var i = 0; } @foreach (var employee in Model.Employees) { @{ i++; } <a href="#">@employee.Name</a> @if(i%3 == 2) { <br/> } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7603409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: QT Widget Slot Call Not Activated by Separate Thread Signal I have 5 classes that interact (maintaining professionally, not author). My problem is that the code that is emitting the signal (there is just one, code below) is never activating the slot (MyWidget::HandleMeasurementChanged). This system has a large degree of complexity. I have tried to reduce that, but think the complexity likely contributes to the problem. There is also a high rate of calls to Observer::notify, but most of these will get filtered out by code that I have not posted here and the Emit calls are fairly rare. If anyone could help point me to why the slot is not getting activated, I'd really appreciate it. It is almost acting like the MyWidget class instance is not processing its event loop. I have had a little success setting the connect type to Direct Connection, but since the emit is in a separate thread and the production code for the slot will update the UI I have ruled that out as a final solution. class IObserver { public: virtual void notify()=0; }; class ExternalMeasurement { ... }; class Measurement { public: Measurement(ExternalMeasurement source); }; class Observer : public QThread, public IObserver { signals: void MeasurementChanged(boost::shared_ptr<Measurement> measurement); public: //called by 3rd party in separate thread virtual void notify(ExternalMeasurement measurement) { _measurement_ = boost::shared_ptr<Measurement>(new Measurement(measurement)); emit MeasurementChanged(_measurement); } private: boost::shared_ptr<Measurement> _measurement_; }; class MyWidget : public QWidget { private: Component _component_; public slots: void HandleMeasurementChanged(boost::shared_ptr<Measurement> measurement); public: MyWidget(Component * component_) }; MyWidget::MyWidget(Component * component_) { _component_ = component_; connect( _component_->_observer_, MeasurementChanged(boost::shared_ptr<Measurement> measurement), this, HandleMeasurementChanged(boost::shared_ptr<Measurement> measurement)); } class Component { private: QApplication * _application_; MyWidget * _widget_; Observer * _observer_; public: void MainFunc(); } void Component::MainFunc() { _observer_ = new Observer(); ... _application_ = new QApplication(...); ... _widget_ = new MyWidget(...); ... _widget_->show(); _application_->exec(); } A: This was referenced in the link that Jeremy added in a comment to my question, but just for clarity: The solution was to add: qRegisterMetaType<shared_ptr<Measurement> >("shared_ptr<Measurement>"); immediately before the call to connect.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to avoid a switch block with 300 cases? I am trying to add 300 Challenges into my program, but only display them if the CompletionValue.IsChecked = false; If you were creating this program. How would you store the Challenges? I am using a switch but having 300 cases is overkill, is there a better way? Any recommendation on to improve the code is well appreciated. I am somewhat new to this. Random rand = new Random(); // Constructor public MainPage() { InitializeComponent(); AnswerValue.Visibility = Visibility.Collapsed; Load(); } private void Load() { int random = rand.Next(1, 4); switch (random) { case 1: Challenge1(); break; case 2: Challenge2(); break; case 3: Challenge3(); break; } } private void Challenge1() { DifficultyValue.Text = "20%"; CompletionValue.IsChecked = false; TitleValue.Text = "Chicken or Egg?"; QuestionValue.Text = "Can you answer the ancient question: Which came first the chicken of the egg?"; bmp.UriSource = new Uri("Images/Challenge1.png", UriKind.Relative); ImageValue.Source = bmp; ImageValue.Visibility = Visibility.Visible; ResourceValue.Text = "Resource: Brain Games"; AnswerValue.Text = "The Egg. According to paleontologists, reptiles and dinosaurs existed long before birds and chickens. Fossilized eggs dating back on hundred millions years have been uncovered. Thus it can be said that eggs came before chickens."; } private void Challenge2() { DifficultyValue.Text = "25%"; CompletionValue.IsChecked = false; TitleValue.Text = "Halving Seven"; QuestionValue.Text = "Can you prove that seven is half of twelve?"; bmp.UriSource = new Uri("Images/Challenge2.png", UriKind.Relative); ImageValue.Source = bmp; ImageValue.Visibility = Visibility.Visible; ResourceValue.Text = "Resource: Yahoo Questions"; AnswerValue.Text = "Roman numeral for 12 - XII \n Cut the roman numeral in half. you will get VII, which is 7."; } private void Challenge3() { DifficultyValue.Text = "25%"; CompletionValue.IsChecked = false; TitleValue.Text = "Three-coin flip"; QuestionValue.Text = "You ask a friend about probability, and he tells you the following: The odds of three tossed coins turning up all heads or all tails is one in two, that is, fifty-fifty. That’s because anytime you toss three coins, at least two must match, either two heads or two tails. So that means the third coin—which is equally likely to be heads or tails—determines the odds.” Is your friend right? If not, what are the odds of three tossed coins turning up all heads or all tails?"; bmp.UriSource = new Uri("Images/Challenge3.png", UriKind.Relative); ImageValue.Source = bmp; ImageValue.Visibility = Visibility.Visible; ResourceValue.Text = "Resource: Brain Games"; AnswerValue.Text = "Answer will be available soon"; } A: Your challenges look awfully similar to each other, right? This is a case where you want to extract out a common data structure, and have each challenge represented as a piece of data. With a uniform representation for your challenges, you set up the UI based on the challenge data for a particular challenge ID. It is always possible to move your data into XML files, JSON files, or a database, but first see if the simple C# solution works for you: // Note: This example is simplified for readability // Here is the common data structure that can represent all challenges private class Challenge { public string Title { get; set; } public string Question { get; set; } public string ImagePath { get; set; } } // All of the challenges are defined right here, as simple data private Challenge[] _allChallenges = new Challenge[] { new Challenge { Title = "Chicken or Egg?", Question = "Can you answer the ancient question: Which came first the chicken of the egg?", ImagePath = "Images/Challenge1.png", }, new Challenge { Title = "Halving Seven?", Question = "Can you prove that seven is half of twelve?", ImagePath = "Images/Challenge1.png", }, } // Choosing challenges is as simple as indexing into the array private void Load() { int random = rand.Next(1, 4); Challenge chosenChallenge = _allChallenges[random]; LoadChallenge(chosenChallenge); } // Setting up the UI for a challenge means extracting information from the data structure private void LoadChallenge(Challenge chosenChallenge) { TitleValue.Text = chosenChallenge.Title; QuestionValue.Text = chosenChallenge.Text; bmp.UriSource = new Uri(chosenChallenge.ImagePath, UriKind.Relative); ImageValue.Source = bmp; ImageValue.Visibility = Visibility.Visible; } You can consider this as a form of declarative programming. An important part of your program, the challenges themselves, have been converted from imperative statements (setting UI properties) into very simple data declarations. By making this conversion, you can even check each challenge to make sure that all of the parts are filled out. Then you'll be sure that the title, question, resource, answer, etc. is set for each of your 300 challenges. A: You can save the challenges in a database or a file. I do see you are using a random number and display only 1 challenge. The DB can be something like ChallengeId, DifficultyValue, TitleValue ... The ChallengeId will be the questionId number. So depending on the random number generated you can choose the particular ChallengeId and the relevant data. A: What you should really look into is encapsulation and polymorphic code. By encapsulating your like properties into a single class, you have a better way of representing the "Challenge" as a whole, and being able to reuse the parts that you have to type over and over again (.Text = "...") will make your future coding life infinitely better. Granted, even coding the list of Challenge entities, as I have below, would be not fun, you have to enter that data somewhere sometime. We're just going to consider this a coding exercise, you could easily adapt the code below to populate _challenges from a database or serialized file. public class Challenge { public int Id {get;set;} public int Difficulty {get;set;} public bool IsCompleted {get;set;} public string Title {get;set;} public string Question {get;set;} public string Answer {get;set;} } public class MainPage { private List<Challenge> _challenges; private Random rand = new Random(); public MainPage() { _challenges = new List<Challenge> { new Challenge { Id = 1, Difficulty = 20, Title = "What came first?", Question = "The chicken or the egg?", Answer = "The egg." }, new Challenge { Id = 2, Difficulty = 30, Title = "Make 7 from 12?", Question = "Can you prove 7 is half of 12?", Answer = "VII" }}; } public void LoadChallenge(Challenge challenge) { Difficulty.Test = String.Format("%{0}", callenge.Difficulty); Completeted.Value = challenge.IsCompleted; Title.Test = challenge.Title; // etc } public void StartNewChallenge() { Challenge nextChallenge = null; while(nextChallenge == null) { var nextId = rand.Next(1,2); nextChallenge = _challenges .Where(x => x.Id == nextId && !x.IsCompleted) .SingleOrDefault(); // default to null if completed == true } LoadChallenge(nextChallenge); } } A: Yet another alternative might be some kind of factory method: MyForm.cs public class MyForm { Random rand = new Random(); // Constructor public MainPage() { InitializeComponent(); AnswerValue.Visibility = Visibility.Collapsed; Load(); } private void Load() { int random = rand.Next(1, 4); DisplayChallenge(ChallengeFactory.GetChallenge(random)); } private void DisplayChallenge(ChallengeFactory.Challenge challengeToDisplay) { DifficultyValue.Text = String.Format("{0}%", challengeToDisplay.Difficulty); CompletionValue.IsChecked = challengeToDisplay.IsChecked; TitleValue.Text = challengeToDisplay.Title; QuestionValue.Text = challengeToDisplay.Question; ImageValue.Source = challengeToDisplay.ImageSource; ImageValue.Visibility = challengeToDisplay.Visible; ResourceValue.Text = challengeToDisplay.ResourceValue; AnswerValue.Text = challengeToDisplay.Answer; } } ChallengeFactory.cs public static class ChallengeFactory { public class Challenge { public int Difficulty { get; set; } public bool IsChecked { get; set; } public string Title { get; set; } public string Question { get; set; } public Uri ImageSource { get; set; } public bool Visible { get; set; } public string ResourceValue { get; set; } public string Answer { get; set; } private Challenge(int difficulty, bool isChecked, string title, string question, Uri imageSource, bool visible, string resourceValue, string answer) { // assign each of the arguments to the instance properties } } public static Challenge GetChallenge(int challengeNumber) { switch(challengeNumber) { case 1: return new Challenge(20, false, "Chicken or Egg?", "Can you answer the ancient question: Which came first the chicken of the egg?", new Uri("Images/Challenge1.png", UriKind.Relative), true, "Resource: Brain Games", "The Egg..."); break; case 2: // new challenge for challenge #2 break; case 3: // new challenge for challenge #3 break; } } } Note that I have made the Challenge class a nested class inside of the Factory class. The good thing about doing this is that you can make the constructor of the challenge private (meaning that you cannot create "invalid" types of challenges through anything but the factory method. The bad thing about doing this is that you have to further qualify the Challenge class by prefixing it with it's containing class, that is, ChallengeFactory. I think it's worth the extra qualifier in this case. Ultimately I think you are stuck having to create a switch SOMEWHERE if you plan on defining all of your challenges in code. As others have said, you can significantly reduce the amount of code you need to write (and thus, the switch) by defining your challenges in an external data source (such as a database) and having a single method to read, parse, and create a Challenge instance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Why does std::fopen and std::filebuf::open trim trailing space characters on Windows? I stumbled on a strange problem when trying to port a piece of C++ code from MSWindows to linux (Mint10). I discovered that there was a little typo in a hard-coded filename : a trailing space char (\x20). The code worked like a charm under Windows (Windows Vista/7), but it had trouble to deal with the erroneous filename under linux. I discovered that both std::filebuf::open and std::fopen (and also boost::filesystem::filebuf) allow trailing space chars in filename under Windows (which I think is an incorrect behavior). I tested the following code using MSVC2010 and MinGW under Win7 : # include <iostream> # include <fstream> # include <string> # include <cstdlib> const std::string filename = "Z:\\Path\\To\\A\\File " ; // one trailing space int main(int, char * []) { std::cout << "Testing with file : \"" << filename << "\"" << std::endl ; // Testing with std::filebuf::open std::filebuf fb ; fb.open(filename.c_str(), std::ios::in | std::ios::binary) ; if( fb.is_open() ) { std::cout << "Using std::filebuf : Opened" << std::endl ; fb.close() ; } else { std::cout << "Using std::filebuf : Not opened" << std::endl ; } // Testing with std::fopen std::FILE * fp = std::fopen(filename.c_str(), "rb") ; if( fp ) { std::cout << "Using std::fopen : Opened" << std::endl ; std::fclose(fp) ; } else { std::cout << "Using std::fopen : Not opened" << std::endl ; } return 0 ; } I verified that the file on the harddrive has no trailing space characters in the name. The file was successfully opened on Windows, but no luck to access it under linux if the filename isn't an exact match. So I have a couple of questions : * *Is this a normal behavior of the file API under Windows ? And is there some other gotchas ? I googled but found no reference on this case. (Maybe I'm a bad googler :)) *How to write a code that works in a strict fashion with filenames ? Always trimming filenames before passing them to some file function isn't the solution for my case ; my current app have to list directories (using boost::filesystem::directory_iterator) and trimming filenames will break the app if the user provides filenames with trailing space chars (which is rare but allowed on many file systems). Thanks for any advice ! A: Windows itself will strip the trailing blanks from a filename, it has nothing to do with the C++ function you use to open the file. Here's one reference to this behavior in the Windows API function CreateFile: INFO: Filenames Ending with Space or Period Not Supported
{ "language": "en", "url": "https://stackoverflow.com/questions/7603420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Passing JSON with Django I'm passing information to a Processing sketch from a Django backend. The problem arises with "lectures", it seems that it is not serializable. I'm missing something very basic methinks. def get(request, last_update = None): timestamp = time.time() if last_update: last_update = datetime.fromtimestamp(float(last_update)) lectures = Lecture.objects.all().filter(datetime_edit__gt=last_update) else: lectures = Lecture.objects.all() updates = {'timestamp': timestamp, 'lectures': lectures} print updates return HttpResponse(json.dumps(updates), mimetype="application/json") Here is the response that I'm getting in the browser. [<Lecture: whales>, <Lecture: cats>, <Lecture: rain>, <Lecture: china>] is not JSON serializable A: QuerySet cannot be serialized in this manner. Use .values() and list() to turn it into a basic Python structure (i.e. a list of dicts) first. A: The JSON serialize does not support serialization of arbitrary class instances. You should convert Lecture records into dictionaries before serializing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android application need to detect if the user came back from Google Maps Intent I'm making an App and I use the Google Maps navigation Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?saddr=" + mLat + "," + mLng + "&daddr=" + mLatitude + " , " + mLongitude + "")); And if the user come back from this intent I want to show the rating bar for the place the user has navigated to. Is startActivityForResult something I can use on Intent not from my application? Or is there another way to detect the user did came back to my App? A: I don't know if you can get back something from an Intent you just throw up in the air for Android to handle but... I'd recommend showing the map within one of your own activity; this way you'd exactly know what the user has done and which pin they've selected. You can then setResult in that Activity and get back the information. I know it involves little bit more of development but you'd have total control of the map view and what the user do there. I'm sure you've seen this but take a look. http://developer.android.com/resources/tutorials/views/hello-mapview.html -serkan
{ "language": "en", "url": "https://stackoverflow.com/questions/7603440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I get OpenEars to recognize spoken numbers on iOS? I'm looking for API to convert spoken items into text on iOS, but mainly for numbers and letters like 1, 2, 3, 4 and a, b, c, d. I've tried OpenEars as many people suggested, but it appears to only support certain ords, such as "GO FORWARD BACKWARD LEFT RIGHT START STOP TURN". Can it be used to recognize generic words or spoken numbers? I have also tried the iSpeech API, but when I speak a string of numbers like 12345, it can only return the text "one two three four five", and it can only give me the result of the recognition instead of a list of guesses (like the Google voice recognition API on Android). How can I use either of these APIs (or another alternative) to recognize spoken numbers or letters? A: To learn how to create custom language models and how to dynamically create language models with OpenEars (a language model is your custom set of words), read the OpenEars docs here: http://www.politepix.com/openears/yourapp To learn how to use an acoustic model with OpenEars which is oriented towards recognizing spoken digits, read this discussion in the OpenEars forum: http://www.politepix.com/forums/topic/way-to-see-phonemes-openears-heard You can also look at the code in the OpenEars sample app, which is heavily commented and shows an example of changing the apps "vocabulary" inline. If you have more questions about implementing OpenEars, I recommend making an account on the OpenEars forums (I'm the OpenEars developer). A: I used the following JSGF based on the sphinx unit tests. <int0> = (ZERO | OH); <int10> = TEN; <int100> = HUNDRED; <int1to9> = ONE | TWO | THREE | FOUR | FIVE | SIX | SEVEN | EIGHT | NINE; <int0to9> = ( <int0> | <int1to9> ); <int01to09> = <int0> <int1to9>; <int11to19> = ELEVEN | TWELVE | THIRTEEN | FOURTEEN | FIFTEEN | SIXTEEN | SEVENTEEN | EIGHTEEN | NINETEEN; <tens> = TWENTY | THIRTY | FORTY | FIFTY | SIXTY | SEVENTY | EIGHTY | NINETY; <int20to99> = ( <tens> [<int1to9>] ); <int10to99> = ( <int10> | <int11to19> | <int20to99> ); <int1to99> = ( <int1to9> | <int10to99> ); <int0to99> = ( <int0> | <int1to99> ); <int01to99> = ( <int01to09> | <int10to99> ); <int1to9hundreds> = ((A | <int1to9>) <int100>); <int101to999> = (<int1to9> (<int01to09> | <int10> | <int11to19> | <int20to99> )); <int100to999> = (<int1to9hundreds> [[AND] <int1to99> ]); <int1to999> = ( <int1to99> | <int100to999> | <int101to999> );
{ "language": "en", "url": "https://stackoverflow.com/questions/7603441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to convert date/time strings into Java Calendar objects? Possible Duplicate: How to convert a date String to a Date or Calendar object? I'm in a pinch here... I have a series of date/time strings formatted like this:"9-29-2011 9:05 PM PDT" and I need to convert this string into a java Calendar object. Once I have this Calendar object it must represent exactly this date and time (including the AM or PM). Please, what is the best way to accomplish this? A: Use DateFormat to parse the String. Pass the Date to the Calendar.setTime() method. A: Check out http://joda-time.sourceforge.net/ . Joda Time makes a lot of tricky date/time operations simple! You will probably want to construct a custom formatter: http://joda-time.sourceforge.net/userguide.html#Input_and_Output DateTimeFormat.forPattern("dd-MM-yyyy hh:mm a z"); should be close. You can then convert the Joda DateTime to Date or to a Calendar.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603442", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JPA root get in Hibernate not working with IdClass attribute I'm trying to do a multiselect on an entity with an IdClass. I can't get a column that is mapped as part of the ID. It's clear why I can't, as none of the columns that are marked as @Ids are a part of the attributes in the EntityType that hibernate is creating, they are a part of the IdAttributes map. This bit of code worked fine in openJPA, but I've decided to make the move to hibernate for various reasons. The code that fails: CriteriaBuilder queryBuilder = getEntityManager().getCriteriaBuilder(); CriteriaQuery<Tuple> query = queryBuilder.createTupleQuery(); Root<ProductSearchFilter> productSearchFilterRoot = query.from(ProductSearchFilter.class); query.multiselect(productSearchFilterRoot.get("productId").alias("productId"), productSearchFilterRoot.get("category").alias("category"), productSearchFilterRoot.get("name").alias("name"), productSearchFilterRoot.get("fdaStatus").alias("fdaStatus")); query.distinct(true); The error: java.lang.IllegalArgumentException: Unable to resolve attribute [productId] against path My Mapping setup: @Table(name = "PRODUCT_SEARCH_FILTER") @Entity() @IdClass(ProductSearchFilterPK.class) public class ProductSearchFilter { private String source; private String productId; private String name; private String category; private String searchColumn; private String fdaStatus; @Column(name = "SOURCE", length = 11) public String getSource() { return source; } public void setSource(String source) { this.source = source; } @Column(name = "PRODUCT_ID", length = 46, insertable = false, updatable = false) @Id public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; } @Column(name = "NAME", length = 510) public String getName() { return name; } public void setName(String name) { this.name = name; } @Column(name = "CATEGORY", length = 10) public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } @Column(name = "SEARCH_COLUMN", length = 1088, insertable = false, updatable = false) @Id public String getSearchColumn() { return searchColumn; } public void setSearchColumn(String searchColumn) { this.searchColumn = searchColumn; } @Column(name = "FDA_STATUS", insertable = false, updatable = false) @Id public String getFdaStatus() { return fdaStatus; } public void setFdaStatus(String fdaStatus) { this.fdaStatus = fdaStatus; } } public class ProductSearchFilterPK implements Serializable { private String productId; private String searchColumn; private String fdaStatus; public String getFdaStatus() { return fdaStatus; } public void setFdaStatus(String fdaStatus) { this.fdaStatus = fdaStatus; } public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; } public String getSearchColumn() { return searchColumn; } public void setSearchColumn(String searchColumn) { this.searchColumn = searchColumn; } } A: There is workaround, which is using canonical metamodel. Unfortunately EntityModel we get from productSearchFilterRoot does not help us much, because it only gives us view as a set. So we cannot query Attributes of IdClass right away by name of attribute from there. But there they are anyway: //following will contain three attributes that are part of id. Set<SingularAttribute<? super ProductSearchFilter, ?>> s = model.getIdClassAttributes(); Instead we we will go for canonical metamodel. For that we need one new class which we can implement by ourselves, or let Hibenate do it: @StaticMetamodel(ProductSearchFilter.class) public abstract class ProductSearchFilter_ { public static volatile SingularAttribute<ProductSearchFilter, String> category; public static volatile SingularAttribute<ProductSearchFilter, String> fdaStatus; public static volatile SingularAttribute<ProductSearchFilter, String> source; public static volatile SingularAttribute<ProductSearchFilter, String> name; public static volatile SingularAttribute<ProductSearchFilter, String> searchColumn; public static volatile SingularAttribute<ProductSearchFilter, String> productId; } And then we will use fields of ProductSearchFilter_ as argument to get in productSearchFilterRoot: CriteriaBuilder queryBuilder = getEntityManager().getCriteriaBuilder(); CriteriaQuery<Tuple> query = queryBuilder.createTupleQuery(); Root<ProductSearchFilter> productSearchFilterRoot = query.from(ProductSearchFilter.class); query.multiselect( productSearchFilterRoot.get(ProductSearchFilter_.productId).alias("productId"), productSearchFilterRoot.get(ProductSearchFilter_.category).alias("category"), productSearchFilterRoot.get(ProductSearchFilter_.name).alias("name"), productSearchFilterRoot.get(ProductSearchFilter_.fdaStatus).alias("fdaStatus")); query.distinct(true); Because we now have metamodel, I used it also to create selection for name, but because that one is not part of id, we could have left it as it was: productSearchFilterRoot.get("name").alias("name"),
{ "language": "en", "url": "https://stackoverflow.com/questions/7603443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: VIM Insert PHPdoc automatically Is there a way to insert PHPDoc in VIM using a command or key combination? For example, I have a class: class MyClass { public function __construct() { } public function __destruct() { } /* command here to insert PHP doc */ public function abc() { } } I would like to insert something like: /** * method() * * description * * @access * @author * @param type $varname description * @return type description * @copyright * @version */ And then I can full out the rest manually. Thank you A: This can be done pretty effectively with the lightweight phpDocumentor plugin. Edit Here's a modified version with more recent development. Edit Here's version 2 of the phpDocumentor plugin. It is more recent than the above two links. Install the plugin into your $VIMFILES/plugin directory and add this to your .vimrc: " PHP documenter script bound to Control-P autocmd FileType php inoremap <C-p> <ESC>:call PhpDocSingle()<CR>i autocmd FileType php nnoremap <C-p> :call PhpDocSingle()<CR> autocmd FileType php vnoremap <C-p> :call PhpDocRange()<CR> The above binds phpDocumentor to Ctrlp in insert, normal, and visual modes. Place your cursor on a class, function, or variable definition, press Ctrlp, and the plugin will attempt to form a doc block based on the definition. Example function doc block: /** * testDocBlock * * @param mixed $param1 * @param mixed $param2 * @static * @access public * @return boolean */ public static function testDocBlock($param1, $param2) { // Pressed Ctl-p while cursor was on the function definition line above... } Example class doc block Copyright, version, author, etc are included by default in a class doc block. You can modify the plugin to include your own default values for these: /** * TestClass * * @package * @version $id$ * @copyright * @author Michael <me@exmaple.com> * @license */ class TestClass { } Full abstract class example: <?php /** * TestClass * * @abstract * @package * @version $id$ * @copyright * @author Michael <email@example.com> * @license */ abstract class TestClass { /** * publicProp * * @var string * @access public */ public $publicProp; /** * privateProp * * @var string * @access private */ private $privateProp; /** * testDocBlock * * @param string $param1 * @param string $param2 * @static * @access public * @return boolean */ public static function testDocBlock($param1, $param2) { // code here... } } ?> A: Assume you place your template at ~/templates/phpdoc.php. With the below abbreviation, if you type ,p, you will read the contents of your phpdoc.php into the current file, ( at or below the current line - one of those ). map ,p :r ~/templates/phpdoc.php<cr> Then just add the line to your .vimrc file, replacing the file-path and ,p to your liking. A: I can't speak for PHP specifically but you have a couple of options. You can use abbreviations (maybe not good for the specific example) or you can look for a plugin. I can suggest https://github.com/garbas/vim-snipmate ( I use it and it works fine).
{ "language": "en", "url": "https://stackoverflow.com/questions/7603446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: Rails after_save callback being called multiple times I'm trying to inject an after_save callback via a mixin, but my rspec tests are telling me that the callback is being called twice when the create method is called. Why is the method being called twice? The following rspec test fails it 'should call callback' do Product.any_instance.should_receive(:update_linkable_attachments).once Product.create(:name=>'abc') end The failure message is: Failure/Error: Unable to find matching line from backtrace (#<Product:0xb7db738>).update_linkable_attachments(any args) expected: 1 time received: 2 times Here's the code module MainModuleSupport def self.included(base) base.instance_eval("after_save :update_linkable_attachments") end def update_linkable_attachments LinkedAttachment.delay.create_from_attachment self end end class Product < ActiveRecord::Base include MainModuleSupport ... end The Product class has other code, but does not have any other callbacks. A: after_save is part of the transaction and therefore may be called more than once provided that you have other associated objects that need to be saved as well. In cases like this I typically move from the after_save callback to the after_commit callback which runs only after the transaction has completed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603448", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: How should I test class objects inside mailer files? I am using Ruby on Rails 3.1.0, rspec-rails 2 and DelajdJob gems. In order to test if an e-mail is sent when a user signed up I am trying to test a delayed email but I have some trouble\doubt (not directly related to the DelayedJob gem). In my controller I have: def create ... Users::Mailer.delay.sign_up(@user) ... end In my mailer file I have: class Users::Mailer def sign_up(user) @user = user # Note: 'authentication' refers to an associated model @authentication = user.authentication.user_token ... end end In my spec file I have: describe "POST create" do it "sends e-mail" do post :create, { :email => 'foo@bar.com' } # Here I would like to test # (1) if the e-mail is send # (2) if the e-mail is send to the 'foo@bar.com' address end end If I run the spec I get the following error: Failure/Error: post :create, NoMethodError: undefined method `user_token' for nil:NilClass How can I solve that and test if the e-mail was sent? Should I mock or stub the user class object instance? What do you advice to make in my case? A: def create ... # whatever is going on here is not setting @user.authentication Users::Mailer.delay.sign_up(@user) ... end Edit: I realized that I answered the problem that you were having with getting an error. As for mocking the user object, I would lean against using a mock in this case. What is important to test in this case is that an email was sent and it went to foo@bar.com. I would instead post what you need to create a user and then verify.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603452", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Determining visible area/invisible area of a masked object I have a movie clip named circle_mc(see the image on the link below) and a mask object(movie clip) which determines visible area of the circle. User can change the portion which is visible (extend the red area and make it red+blue, gray area is invisible). I need to find proportion of visible area to invisible area (red+blue/gray) so that I can calculate angle. A: Here is a working example of a formula.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }