text
stringlengths
8
267k
meta
dict
Q: How to create an X++ batch job in Axapta 3.0? I'd like to create a batch job in X++ for Microsoft Axapta 3.0 (Dynamics AX). How can I create a job which executes an X++ function like this one? static void ExternalDataRead(Args _args) { ... } A: Here's the bare minimum needed to create a batch job in AX: Create a batch job by creating a new class that extends the RunBaseBatch class: class MyBatchJob extends RunBaseBatch { } Implement the abstract method pack(): public container pack() { return connull(); } Implement the abstract method unpack(): public boolean unpack(container packedClass) { return true; } Override the run() method with the code you want to execute: public void run() { ; ... info("MyBatchJob completed"); } Add a static main method to your class to create an instance of your class and call the standard RunBaseBatch dialog: static void main(Args _args) { MyBatchJob myBatchJob = new MyBatchJob(); ; if(myBatchJob.prompt()) { myBatchJob.run(); } } If you want your batch job to have a description in the batch list, add a static description method to your class: server client static public ClassDescription description() { return "My batch job"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/170088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Adding gdb to MinGW I've gone to http://sourceforge.net/project/showfiles.php?group_id=2435, downloaded the Automated MinGW Installer for MinGW 5.1.4 and at the same time the GNU Source-Level Debugger Release Candidate: GDB 6.8-3. I've then installed MinGW base tools into C:\MinGW. No problem so far. However when I come to install the gdb debugger it has a lot of files and folders with the same names as some already installed but the files are different to those already installed. e.g C:\MinGW\include\bfd.h is 171 KB but gdb-6.8-mingw-3\include\bfd.h is 184 KB. How do I add gdb to MinGW without breaking what's already installed? A: In a command prompt I browsed to C:\MinGW\bin and ran: mingw-get.exe install gdb That fixed it for me. Not sure if it matters but I have C:\MinGW\bin in my path (guess I probably didn't need to browse to C:\MinGW\bin). A: Get Wascana Desktop Developer. It combines MinGW, gcc, Eclipse and gdb in one package. A: You can safely overwrite the files prepackaged with MinGW with the (newer) ones from the gdb tarball. You can also choose not to overwrite them - just make sure to pick either one set, i.e. avoid mixing files from the older and the newer package. Most of the offending files are probably not really relevant to you anyway. For example, the files belonging to the libbfd library aren't required for gdb's day to day operation, they're used if you want to extend the debugger or write debugging tools yourself. At any rate, make a backup of the mingw directory before untarring the new release. It's very easy since MinGW is self-contained in that directory. That way, if anything should malfunction, you can just delete the directory and restore from the backup. A: Usually for installing gdb in windows, You have to 2 ways to install: 1) use ready-made binaries that were build and compiled from GNU gdb by some provider (easy to install) * *use TDM-GCC binaries provided from the following URL and that is including inturn the gcc complier and also gdb debugger. http://tdm-gcc.tdragon.net/ *use Equation package inside which GNU GDB was already compiled and built. http://www.equation.com/servlet/equation.cmd?fa=gdb 2) use minimal mingw or cygwin package then after install gdb inside it. * *Install either mingw or cygwin inside which GDB is already shipped *Open cygwin or mingw terminal and just type the following to make sure it is already installed $ gdb --version * *Hint: if you did not find gdb installed, simply open the cygwin or mingw package installer and make sure you already check gdb *Hint: getting and installing a debug build of the OHRRPGCE is providing useful information about crashes. *From cygwin or mingw terminal, Start gdb using the following c:\mingw\bin\gdb.exe program_to_debug.exe REF: http://rpg.hamsterrepublic.com/ohrrpgce/GDB_on_Windows A: The Current Release (5.2.1) version of gdb at the project files page has always worked for me. The download is a stand-alone .exe, you don't need anything else. But I'll bet the .exe in the 6.8 package will work, too. I'd try using just the .exe, and then if there are problems, try extracting the other files from the 6.8 package. (Though that may cause problems with the rest of the MinGW installation.) Update: There seems to be a 7.something version. I haven't tested it thoroughly, but it seems to work, even with gcc 3. A: The TDM GCC/MinGW32 builds installer includes gdb. It's gcc 4.4.x with all the core binary packages required for basic Windows development, and is widely used without any unusual problems.
{ "language": "en", "url": "https://stackoverflow.com/questions/170097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: what are strategies for shielding off web resources based on business logic I have a scenario where I'm not really sure my approach is the best one, and I would appreciate feedback / suggestions. scenario: I have a bunch of flash based (swf) 'modules' which are hosted in my aspnet application. Each flash has it's own directory on the filesystem, which contains assets for the flash. Consider this simplified site structure: /webapp/index.aspx /webapp/flash/flash1/flash.swf /webapp/flash/flash1/someimage.jpg /webapp/flash/flash1/someclip.mp3 /webapp/flash/flash2/flash.swf /webapp/flash/flash2/someimage.jpg /webapp/flash/flash2/someclip.mp3 etcetera where the naming convention is /webapp/flash/flash[ID]/ I want to implement a security mechanism which checks whether the user should be allowed access* to the files in the subfolder '[ID]' and it's contents. **insert business logic based on information stored in a SQL database here* I was considering writing a HttpModule which does something like ProcessRequest(){ if(Request.RawUrl.Contains("/webapp/flash") && !userHasValidLicenseForModule(1)){ Redirect("login.aspx"); } } But there's the drawback that HttpModule only works for file extension which are mapped to aspnet (in IIS6). That means I would have to map all possible extensions to that process (.mp3, .jpg etc) which is something I would rather avoid. I was also considering to use a HttpHandler instead, but the flash file needs to be able to link to it's resources using relative URLs. (so a proxy-like pattern like /webapp/getprotectedstuff.ashx?file=flash1234/flash.swf is not prefered) Perhaps it's wiser to store the flash files and assets outside of the web root completely. Perhaps there are other strategies I havent thought of. Use aspnet security and write a custom membership provider? Any thoughts? A: Have you considered simply validating resource access through an HTTP request to the server after the swf loads? Where I work we provide online trainings to users through flash but rather than verify the HTTP request itself, we allow the swf's to load first and then make a request to the server to verify that the user should have access to the swf and that they are accessing the swf from within our site and not from another location. If any step of validation fails (either it fails to find an auth file in the necessary location or the user does not have a valid session or does not have access to the particular training) then they receive an error within flash and none of the important content ever loads. As another note, if you do decide that you want to strictly limit access to the files so that they can only be loaded by those who should have access, then I would probably suggest using your second option of storing the files in a separate, non-public location and then using a handler script to load the swf. A: Why not go with an ISAPI filter? Okay, dont answer that - plenty of reasons ;-). But seriously, if you have the dev power for it, you might want to consider that route. Otherwise, HTTP Module does seem the better route, IF you have a short, closed list of extensions you have to deal with (GIF, JPG, MP3). If its long, or open-ended, I would agree and forgo that. Another option you might want to look into, if applicable, is role-based NTFS access lists. If this fits, it is probably the easiest and cleanest way to do it.
{ "language": "en", "url": "https://stackoverflow.com/questions/170115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Benefits of using a Case statement over an If statement in a stored procedure? Hi are there any pros / cons relating to the speed that a stored procedure executes when using an IF statement or choosing to use a CASE statement instead? A: I try not to use IFs if I can avoid it, because they are non transactional, i.e. you have generally no guarantee that the condition of the IF will still be valid inside the BEGIN... END block of the IF. I assume that you mean using CASE statements inside a SQL SELECT, for example. If the usage is meant to avoid an IF then, by all means, do it. The golden rule of SQL is: let the server figure out HOW to do things, tell the server what you WANT. A: Don't concern yourself with any speed difference between a case and an IF statement. Because you're dealing with a database, the amount of time it takes to write or read from disk is going to dwarf the time it takes the CPU to branch via an IF or Case. You should focus instead on which makes your code more readable and maintainable.
{ "language": "en", "url": "https://stackoverflow.com/questions/170130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I add the interactive user to a directory in a localized Windows using WiX? How do I add the Swedish interactive user, NT INSTANS\INTERAKTIV or the English interactive user, NT AUTHORITY\INTERACTIVE or any other localised user group with write permissions to a program folder's ACL? Is this question actually "How do I use secureObject"? I cannot use the LockPermissions Table because I undestand inheritance is removed. secureObject permissions seem to require CreateDirectory rather than Directory... A: With recent releases of Wix, you can retrieve the localized names of often-used built-in user and group names via a property. For example, WIX_ACCOUNT_NETWORKSERVICE contains the localized name of the Network Service account. Unfortunately, as of 3.0.4513 NT AUTHORITY\INTERACTIVE is not among them. There exists a sample MSI custom action that creates properties for many of the built-in user and group names. Get it here. Add the CA to your Wix installer and schedule it early in the install execute sequence. Once you have the localized account name, add a PermissionEx element to modify your directory's ACL. For example: <Directory ...> <Component ...> <CreateFolder> <PermissionEx User="[SID_INTERACTIVE]" .../> </CreateFolder> </Component ...> </Directory ...> A: There is no way as such to add both account names to an ACL since they are one and the same. The name you see corresponds to a SID, and that SID is identical in both the English and Swedish localizations. In the case of the INTERACTIVE group, that SID is S-1-5-4. I haven't followed WiX in a long while, but I expect there has to be a way to specify SIDs for ACLs instead of account names. You should never, ever rely on the account name for well-known accounts unless there is absolutely no way to avoid it. Here is a list of well-known SIDs for reference. Edit: This post seems to provide a solution to your problem using a custom action to translate the SIDs to account names - apparently WiX doesn't out of the box support using SIDs for Permission or PermissionEx objects. Here is a more authoritative list of well-known SIDs in Q243330 of the Microsoft Knownledge Base.
{ "language": "en", "url": "https://stackoverflow.com/questions/170140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to run a script in WiX with a custom action - simplest possible example? Newbie WiX question: How do I 1. Copy a single-use shell script to temp along with the installer e.g. <Binary Id='permissions.cmd' src='permissions.cmd'/> 2. Find and run that script at the end of the install. e.g. <CustomAction Id='SetFolderPermissions' BinaryKey='permissions.cmd' ExeCommand='permissions.cmd' Return='ignore'/> <InstallExecuteSequence> <Custom Action="SetFolderPermissions" Sequence='1'/> </InstallExecuteSequence> I think I have at least three problems: * *I can't find permissions.cmd to run it - do I need [TEMPDIR]permissions.cmd or something? *My Sequence comes too soon, before the program is installed. *I need cmd /c permissions.cmd somewhere in here, probably near ExeCommand? In this example permissions.cmd uses cacls.exe to add the interactive user with write permissions to the %ProgramFiles%\Vendor ACL. I could also use secureObject - that question is "How do I add the interactive user to a directory in a localized Windows"? A: Here's a working example (for setting permissions, not for running a script): <Directory Id="TARGETDIR" Name="SourceDir"> <Directory Id="ProgramFilesFolder" Name="PFiles"> <Directory Id="BaseDir" Name="MyCo"> <Directory Id="INSTALLDIR" Name="MyApp" LongName="MyProd"> <!-- Create the folder, so that ACLs can be set to NetworkService --> <Component Id="TheDestFolder" Guid="{333374B0-FFFF-4F9F-8CB1-D9737F658D51}" DiskId="1" KeyPath="yes"> <CreateFolder Directory="INSTALLDIR"> <Permission User="NetworkService" Extended="yes" Delete="yes" GenericAll="yes"> </Permission> </CreateFolder> </Component> </Directory> </Directory> </Directory> </Directory> Note that this is using 'Extended="Yes"' in the Permission tag, so it's using the SecureObjects table and custom action not the LockPermissions table (see WiX docs for Permission Element). In this example the permissions applied to the MyProd directory by SecureObjects are inherited by subdirectories, which is not the case when LockPermissions is used. A: I found the blog post From MSI to WiX, Part 5 - Custom actions: Introduction helpful when I wanted to understand CustomActions in WiX. You can also find the definition of CustomAction and its attributes in CustomAction Element. You need to do something like this <CustomAction Id="CallCmd" Value="[SystemFolder]cmd.exe" /> <CustomAction Id="RunCmd" ExeCommand="/c permission.cmd" /> <InstallExecuteSequence> <Custom Action="CallCmd" After="InstallInitialize" /> <Custom Action="RunCmd" After="CallCmd" /> </InstallExecuteSequence> A: Rather than running custom action you can try using Permission element as a child of CreateFolder element, e.g.: <CreateFolder> <Permission User='INTERACTIVE' GenericRead='yes' GenericWrite='yes' GenericExecute='yes' Delete='yes' DeleteChild='yes' /> <Permission User='Administrators' GenericAll='yes' /> </CreateFolder> Does this overwrite or just edit the ACL of the folder? According to MSDN documentation it overwrites: Every file, registry key, or directory that is listed in the LockPermissions Table receives an explicit security descriptor, whether it replaces an existing object or not. I just confirmed that by running test installation on Windows 2000. A: Have you got an example of how this is used? I mean, do use CreateFolder nested under the directory whose ACL I want to change? Or do I use CreateFolder first, separately? Is the following even close? <Wix xmlns="http://schemas.microsoft.com/wix/2003/01/wi"> <Fragment> <DirectoryRef Id="TARGETDIR"> <Directory Id='ProgramFilesFolder' Name='PFiles'> <Directory Id="directory0" Name="MyApp" LongName="My Application"> <Component Id="component0" DiskId="1" Guid="AABBCCDD-EEFF-1122-3344-556677889900"> <CreateFolder> <Permission User='INTERACTIVE' GenericRead='yes' GenericWrite='yes' GenericExecute='yes' Delete='yes' DeleteChild='yes' /> <Permission User='Administrators' GenericAll='yes' /> </CreateFolder> <File Id="file0" Name="myapp.exe" Vital="yes" Source="myapp.exe"> <Shortcut Id="StartMenuIcon" Directory="ProgramMenuFolder" Name="MyApp" LongName="My Application" /> </File> </Component> <Directory Id="directory1" Name="SubDir" LongName="Sub Directory 1"> <Component Id="component1" DiskId="1" Guid="A9B4D6FD-B67A-40b1-B518-A39F1D145FF8"> etc... etc... etc... </Component> </Directory> </Directory> </DirectoryRef> </Fragment> A: Most people tend to steer clear of the lockPermissions table as it is not additive, meaning it will overwrite your current permissions (from a managed environment perspective, this is bad). I would suggest you use a tool which supports ACL inheritance such as SUBINACL or SETACL or one of the many ACL tools. In relation to why your earlier posts failed there is a few reasons. There are four locations where you can put your custom actions (CAs): UI, Immediate, Deferred, and Commit/Rollback. You need your CA to set permissions in the deferred sequence, because the files are not present until midway through the deferred sequence. As such, anything prior will fail. * *Your setup is in immediate (so will fail) *Your setup is at sequence of 1 (which is not possible to be deferred so will fail) You need to add an attribute of Execute="Deferred" and change sequence from "1" to: <Custom Action="CallCmd" Execute="Deferred" Before="InstallFinalize" /> This will ensure it's done after the files are installed, but prior to the end of the deferred phase (the desired location). I would also suggest you call the EXE file directly and not from a batch file. The installer service will launch and the EXE file directly in the context you need. Using a batch file will launch the batch file in the correct context and potentially lose context to an undesired account while executing.
{ "language": "en", "url": "https://stackoverflow.com/questions/170144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Prevent users from starting multiple accounts? I know that in the end it, can't be done. But, what are the options to:   a) limit the options for persons to create multiple accounts,   b) increase the chance of detecting multiple accounts / person for a blog-like web service? (people can sign up for their own blog) Update: I think the 'limit the options' has been answered nicely. (there is no reliable method, but we can raise the bar) However, I would still like to know what other options there are to detect multiple accounts? A: You can set a cross browser cookie e.g. http://samy.pl/evercookie/ (flash cookies) The can not be deleted by the browser cookie deletetion they stay 4 ever and you can read the cookie cross browsers. Its the ultimate solution if the user uses the same computer. With more than 1 computer the IP address is your only way to find out, but (in my case) sometimes 2 real people in the same house with 2 computers login 2 my website A: I'm assuming you're talking about a free service? I can't think of any ways that don't either have serious drawbacks or would be trivial to defeat. Things like setting a cookie, requiring a unique e-mail address are easy to defeat. Requiring a unique IP address is not foolproof but might work to some degree, up to the point that you have lots of users and get complaints from people behind proxies. The best ways are to charge money or require people provide some kind of personal information, like real name/phone/address that you verify, or a CC number, but that's invasive (then again maybe you only want serious users who are willing to provide this sort of info). I guess I would turn the question around and ask "Why don't you want to let people have multiple accounts?" There may be some other ways of mitigating whatever your underlying reason is, i.e. if you're worried about lots of orphaned blogs you could scan for a period of inactivity and disable them or at least schedule them to be looked at by a human. If you're worried about spam blogs you could periodically scan all blog content for spammy stuff. If you're worried about bots and are using some generic software like WordPress, change the names of the form variables and otherwise protect your forms from bots. Definitely think of other ways of dealing with the problem, because you are not going to be able to block people from registering multiple accounts if it's a typical free service like Blogger. As for detecting multiple accounts by one person, the first thing you need to do is have a log file store complete data on every user login (username, timestamp, IP, user-agent etc.), that you can then analyze later. I'll list a few things to look out for, but just by poring over the log file you will likely discover other patterns. Some ideas of things to look for are: * *Set a tracking cookie (i.e. random hash) and log its value on login, look for multiple logins from the same cookie value *Logins from same IP address/user-agent combination *Logins from same IP address only (less reliable than the previous two bullets) *Accounts with email addresses from free webmail services (Gmail etc.) *Accounts with same password If you're worried about spam blogs, you could try doing some analysis of blog content, i.e. extract all the <a href>s and look for correlations between blogs. You could run the blog content itself though something like SpamAssassin or otherwise filter for spammy words like "viagra" and "rolex." A: Ask users to register with a credit card. You don't have to charge anything to the card, you can just check that the card is valid. A: You can't and you shouldn't. You are not dealing with the real world guys, but with accounts, so treat them as abstract entities which have the equal rights to live. Some options I can imagine on the fly: -- Only one account for email address. But I can create more then one email... or use Mailinator. -- Long and tedious verification procedure. But that will discourage the users from registration -- bind the IP to the account and block(temporarily?) that IP from creation of another account. But two different users with the same gateway will be blocked... -- Use the cookies. But the user can delete them. A: The most difficult to break methods I've seen implemented in real life are to use a separate hardware medium for confirmation (sending a confirmation code via SMS for a public service, or mailing an RSA token for something more sensitive, like intranet access), or to ask for a financially-bound piece of identification, for example a bank account number (Paypal deposits a few cents to your account and the sum of the amounts is your passcode) or a valid credit card number. A: I think an alternative direction to take with this is to let the "big boys" do it. http://oauth.net/ Offload the authentication of your site to a well-known 3rd party like Google or Facebook. It won't prevent duplicate accounts, but it's nice to think that the latest in spam prevention and whatnot is automatically implemented for you. A: I think the best method would be to remove the incentives for creating multiple accounts. Do you limit the users in any way? Can those limits be overcome (easily) by creating multiple accounts? If so, then maybe you should think about removing those limits. A: You could send users a SMS message to verify before creating the account. Since people can't get cell phone numbers as easily as they can get email addresses, this might work. Some people might be able to get two or three accounts, but not an unlimited number. There are a number of services that let you send SMS messages programmaticly, including Gizmo SMS, Text4Free and TxtDrop. Of course, this requires users to have cell phones, and be willing to provide you with the number. A: One common option is to verify the persons identity through their e-mail. Actually make them respond to an e-mail sent to their account. Some sites take this a step further and don't allow addresses from domains such as yahoo, g-mail, hotmail, etc ... A: I think, as many people have mentioned above, one of the best ways is to verify mobile numbers and that's what I wanted to use in teh first place, if it wasnt so damn expensive ... I have found this site here and I think it can be used for this purpose but I havent tested it myself, but it seems pretty modern and cheap
{ "language": "en", "url": "https://stackoverflow.com/questions/170152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }
Q: How to debug JavaScript in IE? Is there a better way to debug JavaScript than MS Script Editor? I am searching for something like Firebug. Firebug Lite doesn't offer this functionality, though. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ A: Use Visual Studio 2008. The Web Development Helper from Nikhilk is useful as is the Internet Explorer Developer Toolbar (http://www.microsoft.com/en-us/download/details.aspx?id=18359). They are not as good as FireBug though :-( A: Though not strictly debuggers, these are useful tools for your arsenal * *http://www.debugbar.com/ *http://projects.nikhilk.net/WebDevHelper/ A: I've used IE WebDeveloper. It's not free and not as nice as Firebug, but got the job done for me. http://www.ieinspector.com/dominspector/index.html A: The only other debugger for JavaScript in the IE context is Visual Studio, but it'll cost you. What problems are you having with the script debugger that leads to think you need a better debugger? I suspect that what you are after are the additional features that aren't specifically about debugging JavaScript but analysing the HTML DOM that has been modified by the JavaScript and the monitoring of the conversation with the server. The IE developer toolbar I find particularly invaluable for debugging web apps as is Fiddler. A: I would try and go for DebugBar. It's not as nice as Firebug, but it's very useful for javascript debugging... A: There is a blog post that goes over most of the known ways to debug javascript in IE, with pros and cons. A: Great article mkoryak I used visual studio web developer as in this linked article http://www.berniecode.com/blog/2007/03/08/how-to-debug-javascript-with-visual-web-developer-express/ A: You can download the Microsoft Visual Web Developer 2008 Express Edition for free. A: In newer versions of Internet Explorer (10.0+ I guess) the developer tools are integrated. The debugger panel there allows you to debug your JavaScript like in Firebug, the Firefox DevTools or the Chrome DevTools.
{ "language": "en", "url": "https://stackoverflow.com/questions/170164", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: jQuery templating engines I am looking for a template engine to use client side. I have been trying a few like jsRepeater and jQuery Templates. While they seem to work OK in FireFox they all seem to break down in IE7 when it comes down to rendering HTML tables. I also took a look at MicrosoftAjaxTemplates.js (from http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=16766) but turns out that has the same problem. Any advice on other templating engines to use? A: It depends on how you define "best", please see my post here on the topic If you look for the fastest, here is a nice benchmark, it seems that DoT wins, and leaves everyone else behind If you are looking for the most official JQuery plugin, here is what I found out Part I: JQuery Templates The beta, temporarily-official JQuery template plugin was this http://api.jquery.com/category/plugins/templates/ But apparently, not too long ago it was decided to keep it in Beta... Note: The jQuery team has decided not to take this plugin past beta. It is no longer being actively developed or maintained. The docs remain here for the time being (for reference) until a suitable replacement template plugin is ready. Part II: The next step The new roadmap seem to aim for a new set of plugins, JSRender (independent of DOM and even JQuery template rendering engine) and JSViews which have some nice data binding and observer / observable pattern implementation Here is the blog post on the topic http://www.borismoore.com/2011/10/jquery-templates-and-jsviews-roadmap.html And here is the latest source * *JSViews https://github.com/BorisMoore/jsviews *JSRender https://github.com/BorisMoore/jsrender Other resources * *A nice presentation on the topic http://www.slideshare.net/BorisMoore/jsviews-next-generation-jquery-templates *Working demos: http://borismoore.github.com/jsviews/demos/index.html Note it's still not even in beta, and only a road map item, but seems like a good candidate to become an official JQuery/JQueryUI extension for templates and UI binding A: Just did some research on this and I'll be using jquery-tmpl. Why? * *It's written by John Resig. *It'll be maintained by the core jQuery team as an "official" plugin. EDIT: The jQuery team have deprecated this plugin. *It strikes a perfect balance between simplicity and functionality. *It has a very clean and well thought out syntax. *It HTML-encodes by default. *It's highly extensible. More here: http://forum.jquery.com/topic/templating-syntax A: Only to be the foolish ^^ // LighTest TPL $.tpl = function(tpl, val) { for (var p in val) tpl = tpl.replace(new RegExp('({'+p+'})', 'g'), val[p] || ''); return tpl; }; // Routine... var dataObj = [{id:1, title:'toto'}, {id:2, title:'tutu'}], tplHtml = '<div>N°{id} - {title}</div>', newHtml = ''; $.each(dataObj, function(i, val) { newHtml += $.tpl(tplHtml, val); }); var $newHtml = $(newHtml).appendTo('body'); http://jsfiddle.net/molokoloco/w8xSx/ ;) A: This isn't jsquery specific, but here's a JS-based templating library released by google as open source: http://code.google.com/p/google-jstemplate/ This allows using DOM elements as templates, and is re-entrant (in that the output of a template rendering is still a template that can be re-rendered with a different data model). A: jQote: http://aefxx.com/jquery-plugins/jqote/ Someone took Resig's micro-templating solution and packaged it into a jQuery plugin. I'll be using this until Resig releases his own (if he releases his own). Thanks for the tip, ewbi. A: Others have pointed jquery-tmpl, and I have upvoted those answer. But be sure to have a look at github forks. There are important fixes out there and interesting features too. http://github.com/jquery/jquery-tmpl/network A: jQuery Nano: Template Engine Basic Usage Assuming you have following JSON response: data = { user: { login: "tomek", first_name: "Thomas", last_name: "Mazur", account: { status: "active", expires_at: "2009-12-31" } } } you can make: nano("<p>Hello {user.first_name} {user.last_name}! Your account is <strong>{user.account.status}</strong></p>", data) and you get ready string: <p>Hello Thomas Mazur! Your account is <strong>active</strong></p> Test page... A: jQuery-tmpl will be in the jQuery core beginning in jQuery 1.5: http://blog.jquery.com/2010/10/04/new-official-jquery-plugins-provide-templating-data-linking-and-globalization/ The official documentation is here: http://api.jquery.com/category/plugins/templates/ EDIT: It's been left out of jQuery 1.5 and will now be coordinated by the jQuery UI team, as it will be a dependency of the upcoming jQuery UI Grid. http://blog.jquery.it/2011/04/16/official-plugins-a-change-in-the-roadmap/ A: Not sure how it handles your specific problem, but there's also the PURE template engine. A: Check out Rick Strahl's post Client Templating with jQuery. He explores jTemplates, but then makes a better case for John Resig's micro-templating solution, even improving it some. Good comparisons, lots of samples. A: John Resig has one that's he's posted on his blog. http://ejohn.org/blog/javascript-micro-templating/ A: If you're working in the .NET Framework 2.0/3.5, you should take a look at JBST as implemented by http://JsonFx.net. It has a client-side templating solution that has familiar JSP/ASP syntax but is precompiled at build-time for compact cache-able templates that don't need to be parsed at runtime. It works well with jQuery and other JavaScript libraries as the templates themselves are compiled to pure JavaScript. A: I was using jtemplates jquery pluging but the performance was really bad. I switched to trimpath (http://code.google.com/p/trimpath/wiki/JavaScriptTemplates) which has much better performance. I haven't noticed any issues with IE7 or FF. A: For very light work jquery-tmpl is adequate, but it requires in some cases that the data know how to format itself (bad thing!). If you're looking for a more full featured templating plugin I'd suggest Orange-J. It was inspired by Freemarker. It supports if, else, loops over objects & arrays, inline javascript, including templates within templates and has excellent formatting options for output (maxlen, wordboundary, htmlentities, etc). Oh, and easy syntax. A: You may want to think a bit how you want to design your templates. One issue with many of the listed template solutions (jQote, jquery-tmpl, jTemplates) is they require you to insert non-HTML in your HTML, which can be a pain to work with in HTML tools or in a development process with HTML designers. I personally don't like the feel of that approach, though it has its pros and cons. There is another class of template approaches that use normal HTML, but allow you to indicate data bindings with element attributes, CSS classes, or external mappings. Knockout is a good example of this approach, but I have not used it myself so I am leaving it to the votes to decide if others like it or not. At least until I have time to play with it more. PURE listed as another answer is another example of this approach. For reference you can also look at chain.js, but it doesn't seem to have been updated much since its original release. For more background on it see http://javascriptly.com/2008/08/a-better-javascript-template-engine/. A: Dropbox using John Resig's template engine on website. They have little bit modified it you can check in this js file of dropbox. Search in this file for tmpl and you will code of template engine. Thanks. Hope it will be useful for someone. A: I'm currently using a multi HTML templating framework. This framework makes it a lot easier to import templated data in your DOM. Also great MVC modeling. http://www.enfusion-framework.org/ (look at the samples!) A: There is also an rewrite of PURE by beebole - jquery pure html templates - https://github.com/mpapis/jquery-pure-templates It should allow a lot more automatic rendering mostly using jquery selectors, whats more important it does not require to put fancy things into HTML.
{ "language": "en", "url": "https://stackoverflow.com/questions/170168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "205" }
Q: Looping over elements in jQuery I want to loop over the elements of an HTML form, and store the values of the <input> fields in an object. The following code doesn't work, though: function config() { $("#frmMain").children().map(function() { var child = $("this"); if (child.is(":checkbox")) this[child.attr("name")] = child.attr("checked"); if (child.is(":radio, checked")) this[child.attr("name")] = child.val(); if (child.is(":text")) this[child.attr("name")] = child.val(); return null; }); Neither does the following (inspired by jobscry's answer): function config() { $("#frmMain").children().each(function() { var child = $("this"); alert(child.length); if (child.is(":checkbox")) { this[child.attr("name")] = child.attr("checked"); } if (child.is(":radio, checked")) this[child.attr("name")] = child.val(); if (child.is(":text")) this[child.attr("name")] = child.val(); }); } The alert always shows that child.length == 0. Manually selecting the elements works: >>> $("#frmMain").children() Object length=42 >>> $("#frmMain").children().filter(":checkbox") Object length=3 Any hints on how to do the loop correctly? A: don't think you need quotations on this: var child = $("this"); try: var child = $(this); A: I have used the following before: var my_form = $('#form-id'); var data = {}; $('input:not([type=checkbox]), input[type=checkbox]:selected, select, textarea', my_form).each( function() { var name = $(this).attr('name'); var val = $(this).val(); if (!data.hasOwnProperty(name)) { data[name] = new Array; } data[name].push(val); } ); This is just written from memory, so might contain mistakes, but this should make an object called data that contains the values for all your inputs. Note that you have to deal with checkboxes in a special way, to avoid getting the values of unchecked checkboxes. The same is probably true of radio inputs. Also note using arrays for storing the values, as for one input name, you might have values from several inputs (checkboxes in particular). A: jQuery has an excellent function for looping through a set of elements: .each() $('#formId').children().each( function(){ //access to form element via $(this) } ); A: Depending on what you need each child for (if you're looking to post it somewhere via AJAX) you can just do... $("#formID").serialize() It creates a string for you with all of the values automatically. As for looping through objects, you can also do this. $.each($("input, select, textarea"), function(i,v) { var theTag = v.tagName; var theElement = $(v); var theValue = theElement.val(); }); A: if you want to use the each function, it should look like this: $('#formId').children().each( function(){ //access to form element via $(this) } ); Just switch out the closing curly bracket for a close paren. Thanks for pointing it out, jobscry, you saved me some time. A: for me all these didn't work. What worked for me was something really simple: $("#formID input[type=text]").each(function() { alert($(this).val()); }); A: This is the simplest way to loop through a form accessing only the form elements. Inside the each function you can check and build whatever you want. When building objects note that you will want to declare it outside of the each function. EDIT JSFIDDLE The below will work $('form[name=formName]').find('input, textarea, select').each(function() { alert($(this).attr('name')); });
{ "language": "en", "url": "https://stackoverflow.com/questions/170180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: Set a database value to null with a SqlCommand + parameters I was previously taught today how to set parameters in a SQL query in .NET in this answer (click). Using parameters with values are fine, but when I try to set a field in the database to null I'm unsuccessful. Either the method thinks I am not setting a valid parameter or not specifying a parameter. e.g. Dim dc As New SqlCommand("UPDATE Activities SET [Limit] = @Limit WHERE [Activity] = @Activity", cn) If actLimit.ToLower() = "unlimited" Then ' It's not nulling :( dc.Parameters.Add(New SqlParameter("Limit", Nothing)) Else dc.Parameters.Add(New SqlParameter("Limit", ProtectAgainstXSS(actLimit))) End If Is there something I'm missing? Am I doing it wrong? A: I use a SqlParameterCollection extension method that allows me to add a parameter with a nullable value. It takes care of converting null to DBNull. (Sorry, I'm not fluent in VB.) public static class ExtensionMethods { public static SqlParameter AddWithNullable<T>(this SqlParameterCollection parms, string parameterName, T? nullable) where T : struct { if (nullable.HasValue) return parms.AddWithValue(parameterName, nullable.Value); else return parms.AddWithValue(parameterName, DBNull.Value); } } Usage: string? optionalName = "Bozo"; cmd.Parameters.AddWithNullable("@Name", optionalName); A: you want DBNull.Value. In my shared DAL code, I use a helper method that just does: foreach (IDataParameter param in cmd.Parameters) { if (param.Value == null) param.Value = DBNull.Value; } A: Try setting it to DbNull.Value.
{ "language": "en", "url": "https://stackoverflow.com/questions/170186", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "33" }
Q: Minimum directory structure and ant build file contents for Java web app What is the minimal conventional directory structure for a Java web app? What do I need to put in a build.xml file to get ant to build it and make a WAR file? My goal is to deploy a Wicket app to Tomcat without using an IDE. I want to do it with only ant and my favourite text editor. A: Maybe not the most minimalist possible, but the Tomcat project has an Application Developer's Guide with a section on source layout and a sample build.xml Also, if you are starting a new project, you might want to check out Maven. With Maven, rather than crafting your own build scripts, you adhere to standard layout to do stuff, and then Maven figures out all the rest. It also manages dependencies, including its own. Learning curve is a bit steep, though. A: Ours look like this: web/ web/WEB-INF/ (sometimes we use a conf/ dir at the top level but this is minimal) src/ lib/ The build.xml has three targets: * *jsp: copies everything from web/ into the tomcat webapp folder and from lib/ into WEB-INF/lib *compile: compiles everything from src/ into WEB-INF/classes in the webapp *war: runs compile, jsp, and then zips the contents of the tomcat webapp into a warfile This structure is a little bit informal and you can do it more cleanly by having a separate build directory for the warfile, and/or a separate compile directory, etc. Some people don't like the idea of deploying directly to the webapp instead of building a war first. But to get something up and running quickly, the above will do nicely. A: You should check out maven. It's really complicated, but to build a war file it's simple, and there are plugins that will deploy the war to tomcat.
{ "language": "en", "url": "https://stackoverflow.com/questions/170192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How do you make Flash not render an object on the Stage? This discussion started over here but I thought it would be nice to have a definitive answer... So let's say you have MovieClip on the Stage (or a UIComponent for the Flex audience) - what do you have to do to not make it so that the user can't see the object but also so that the AVM2 doesn't even factor it in when rendering the stage for the user? I always thought the answer was to set visible = false but there is an argument out there that the object has to placed outside the boundaries of the Stage (like x = 2000 which seems like a hack IMO). Does anyone know the real answer? EDIT: I imagine the need for having flash not render the item would be to help performance. A: As other answers have noted, the "hack" for moving clips outside the stage is no longer necessary. However, setting visible = false; is not a smart thing to do if performance is important. Clips that are part of the display list, but set to be invisible, can still incur a significant rendering overhead if you have enough of them. If you remove them from the playlist with removeChild(), they incur no rendering overhead (although they still take up memory). A: The hack is for Flash 8 (Actionscript 2) or below. With the upgrades to Actionscript 3 and Flex 2/3 setting the visible property is enough. A: Yeah, as design said, just remove it from the display list: var s:MovieClip = new MovieClip(); s.lineStyle(1, 0xFFFFFF); addChild(s);//shows in moviea removeChild(s);//removes from display list, but you still have a reference to it I havent tested that, but it should give you the general idea. mike A: If you're using Flex and its container layout system, the includeInLayout property in the UIComponent class is also useful when you don't want to display something: it specifies whether or not to factor the component in when measuring the layout. A: Remove it from the display list completely (removeChild(), removeChildAt(), etc.). As long as you don't actually set the reference to the MovieClip to "null", it will still remain in memory and can be re-added to the display list when you need it again (addChild(), atChildAt(), etc.)
{ "language": "en", "url": "https://stackoverflow.com/questions/170203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to improve garbage collection performance? What kind of optimization patterns can be used to improve the performance of the garbage collector? My reason for asking is that I do a lot of embedded software using the Compact Framework. On slow devices the garbage collection can become a problem, and I would like to reduce the times the garbage collector kicks in, and when it does, I want it to finish quicker. I can also see that working with the garbage collector instead of against it could help improve any .NET or Java application, especially heavy duty web applications. Here are some of my thoughts, but I haven’t done any benchmarks. * *reusing temporary classes/arrays (keep down allocation count) *keeping the amount of live objects to a minimum (faster collections) *try to use structs instead of classes A: The single most important aspect is to minimize the allocation rate. Whenever an object is allocated, it needs GC later. Now of course, if the object is small or shortlived it will get nailed in the young generation (provided that the GC is generational). Large objects tend to go directly into the tenured arena. But avoiding having to collect at all is even better. Also, if you can throw things on the stack, you will enjoy much less pressure on the GC. You could attempt toying with GC-options, but I think you would be much better helped with an allocation profiler in hand, so you can find the spots that makes the problems. The thing one should beware is the weight of standard libraries and frameworks. You wrap a couple of objects and it will fill up pretty quickly. Remember, whenever something goes on the GC-heap, it usually uses a bit more space for GC-bookkeeping. So your 1000 pointers allocated individually is much bigger than an array/vector of the same pointers since the latter can share the GC-bookkeeping. On the other hand, the latter will probably stay alive for much longer. A: One important fact is to keep the lifetime of your objects as short as possible. A: The struct vs class issue is a complex one... you might easily end up using a lot more stack space, for example. And you certainly don't want mutable structs. But the other points seem sensible, as long as you aren't bending the design out of shape to accomodate it. [edit] One other common gotcha is string concatenation; if you are doing concatenation in a loop, use StringBuilder, which will remove a lot of intermediate strings. It might be that GC is busy collecting all the abandoned vesions of your strings? A: Another option would be to manually collect the garbage during non-peak times in your application using GC.Collect() (assuming this is available in CF). This could reduce the objects required for cleanup later in your application. A: The key is to understand how the CF GC works for allocations. It's a simple mark-and-sweep, non-generational GC with specific algorithms for what will trigger a GC, and what will cause compaction and/or pitching after collection. There is almost nothing you can do at an app level to control the GC (the only method available is Collect, and it's use is pretty limited, as you can't force compaction anyway). Object re-use is a good start, but simply keeping the object count low is probably one of the best tools, as all roots have to be walked for any collection operation. Keeping that walk short is a good idea. If compaction is killing you, then preventing segment fragmentation will help. Objects >64k can be helpful in that regard as they get their own segment and are treated differently than smaller objects. To really understand how the CF GC works, I'd recommend watching the MSDN Webcast on CF memory management. A: I heard a .NET Rocks show on Rotor 2.0. If you are really hardcore, you could download Rotor, tweak the source, and use your own modified garbage collector. In any case, that podcast has some great info on the GC. I highly recommend listening to it.
{ "language": "en", "url": "https://stackoverflow.com/questions/170207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Hashes of Hashes Idiom in Ruby? Creating hashes of hashes in Ruby allows for convenient two (or more) dimensional lookups. However, when inserting one must always check if the first index already exists in the hash. For example: h = Hash.new h['x'] = Hash.new if not h.key?('x') h['x']['y'] = value_to_insert It would be preferable to do the following where the new Hash is created automatically: h = Hash.new h['x']['y'] = value_to_insert Similarly, when looking up a value where the first index doesn't already exist, it would be preferable if nil is returned rather than receiving an undefined method for '[]' error. looked_up_value = h['w']['z'] One could create a Hash wrapper class that has this behavior, but is there an existing a Ruby idiom for accomplishing this task? A: You can pass the Hash.new function a block that is executed to yield a default value in case the queried value doesn't exist yet: h = Hash.new { |h, k| h[k] = Hash.new } Of course, this can be done recursively. There's an article explaining the details. For the sake of completeness, here's the solution from the article for arbitrary depth hashes: hash = Hash.new(&(p = lambda{|h, k| h[k] = Hash.new(&p)})) The person to originally come up with this solution is Kent Sibilev. A: Autovivification, as it's called, is both a blessing and a curse. The trouble can be that if you "look" at a value before it's defined, you're stuck with this empty hash in the slot and you would need to prune it off later. If you don't mind a bit of anarchy, you can always just jam in or-equals style declarations which will allow you to construct the expected structure as you query it: ((h ||= { })['w'] ||= { })['z']
{ "language": "en", "url": "https://stackoverflow.com/questions/170223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "34" }
Q: Errors when trying to update ruby gems from 2.0.1 I am trying to set myself up on a mac to learn Ruby on Rails, however I seem to be having some problems. If I try to run commands such as ./script/server, i get this: Rails requires RubyGems >= 0.9.4 (you have 0.9.2). Please gem update --system and try again. When I run "gem update.." I get this: Updating RubyGems... Attempting remote update of rubygems-update ERROR: While executing gem ... (Errno::EACCES) Permission denied - /opt/local/lib/ruby/gems/1.8/cache/rubygems-update-1.3.0.gem A: got it. sudo gem update --system A: Starting with El Capitan, Apple prevents user applications to modify /usr/bin for security reasons. So better install/update rubygems in the recommended folder, /usr/local/bin: sudo gem update -n /usr/local/bin --system (recommendation taken from https://stackoverflow.com/a/39928447/1033581)
{ "language": "en", "url": "https://stackoverflow.com/questions/170267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# Generic Class with "specialized" constructor I have a class like the following: public class DropDownControl<T, Key, Value> : BaseControl where Key: IComparable { private IEnumerable<T> mEnumerator; private Func<T, Key> mGetKey; private Func<T, Value> mGetValue; private Func<Key, bool> mIsKeyInCollection; public DropDownControl(string name, IEnumerable<T> enumerator, Func<T, Key> getKey, Func<T, Value> getValue, Func<Key, bool> isKeyInCollection) : base(name) { mEnumerator = enumerator; mGetKey = getKey; mGetValue = getValue; mIsKeyInCollection = isKeyInCollection; } And I want to add a convenience function for Dictionaries (because they support all operations efficiently on their own). But the problem is that such a constructor would only specify Key and Value but not T directly, but T is just KeyValuePair. Is there a way to tell the compiler for this constructor T is KeyValuePair, like: public DropDownControl<KeyValuePair<Key, Value>>(string name, IDictionary<Key, Value> dict) { ... } Currently I use a static Create function as workaround, but I would like a direct constructor better. public static DropDownControl<KeyValuePair<DKey, DValue>, DKey, DValue> Create<DKey, DValue>(string name, IDictionary<DKey, DValue> dictionary) where DKey: IComparable { return new DropDownControl<KeyValuePair<DKey, DValue>, DKey, DValue>(name, dictionary, kvp => kvp.Key, kvp => kvp.Value, key => dictionary.ContainsKey(key)); } A: No, basically. The static method in a non-generic class (such as DropDownControl [no <>]) is the best approach, as you should be able to use type-inference when you call Create() - i.e. var control = DropDownControl.Create(name, dictionary); C# 3.0 helps here both via "var" (very welcome here) and by the much-improved generic type inference rules. In some (more general) case, another similar option is an extension method, but an extension method to create a very specific control from a dictionary doesn't feel very natural - I'd use a non-extension method. Something like: public static class DropDownControl { public static DropDownControl<KeyValuePair<TKey,TValue>, TKey, TValue> Create<TKey,TValue>(IDictionary<TKey, TValue> value, string name) where TKey : IComparable { return new DropDownControl<KeyValuePair<TKey, TValue>, TKey, TValue> (name, value, pair => pair.Key, pair => pair.Value, key => value.ContainsKey(key) ); } } Another option is inheritance, but I don't like it much... public class DropDownControl<TKey, TValue> : DropDownControl<KeyValuePair<TKey, TValue>, TKey, TValue> where TKey : IComparable { public DropDownControl(IDictionary<TKey, TValue> lookup, string name) : base(name, lookup, pair => pair.Key, pair => pair.Value, key => lookup.ContainsKey(key)) { } } This adds complexity and reduces your flexibility... I wouldn't do this... Overall, it sounds like you want to be working with just IDictionary<,> - I wonder if you can't simplify your control to just use this, and force non-dictionary callers to wrap themselves in an IDictionary<,> facade? A: If T will always be KeyValuePair<TKey,TValue> there's no need for it to be a generic type parameter at all. Just use the actual type everyplace you use T. Otherwise, if the type may sometimes have to be something else, I would suggest that you should perhaps have a base type DropDownControl<TKey, TValue> : BaseControl with a protected field Helper of the same type, and virtual implementations of nearly all methods which simply invoke their counterparts on Helper; within that define a derived class HeldAs<TPair> which overrides all the methods with "real" implementations. The constructor for DropDownControl<TKey,TValue> would construct a new instance of DropDownControl<TKey,TValue>.HeldAs<KeyValuePair<TKey,TValue>> and store a reference to that in Helper. Outside code could then hold references of type DropDownControl<TKey,TValue> and use them without having to know or care how keys and values were held. Code which needs to create something that stores things a different way and uses different methods to extract keys and values could call the constructor of DropDownControl<TKey,TValue>.HeldAs<actualStorageType>, passing functions which can convert actualStorageType to keys or values as appropriate. If any of the methods of DropDownControl<TKey,TValue> would be expected to pass this, then the constructor of DropDownControl<TKey,TValue>.HeldAs<TStorage> should set Helper to itself, but the constructor of the base type, after constructing the derived-type instance, should set the derived instance's Helper reference to itself (the base-class wrapper). The methods which would pass this should then pass Helper. That will ensure that when a derived-class instance is constructed purely for the purpose of being wrapped, the outside world will never receive a reference to that derived instance, but will instead consistently see the wrapper.
{ "language": "en", "url": "https://stackoverflow.com/questions/170272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: USB Driver Development on a Mac using Python I would like to write a driver to talk to my Suunto t3 watch in Python on a Mac. My day job is doing basic web work in C# so my familiarity with Python and developing on a Mac is limited. Can you suggest how one would start doing driver development in general and then more specifically on a Mac. I.e. how to easily see what data is being transmitted to the device? I have Python 2.5 (MacPorts) up and running. A: The Mac already has the underlying infrastructure to support USB, so you'll need a Python library that can take advantage of it. For any Python project that needs serial support, whether it's USB, RS-232 or GPIB, I'd recommend the PyVisa library at SourceForge. See http://pyvisa.sourceforge.net/. If your device doesn't have a VISA driver, you'll have to deal with the USB system directly. You can use another library on SourceForge for that: http://pyusb.berlios.de/ A: If the watch supports a standard USB device class specification such as HID or serial communication, there might already be a Macintosh driver for it built into the OS. Otherwise, you're going to have to get information about the vendor commands used to communicate with it from one of three sources: the manufacturer; reverse engineering the protocol used by the Windows driver; or from others who have already reverse engineered the protocol in order to support the device on Linux or BSD. USB is a packet-based bus and it's very important to understand the various transaction types. Reading the USB specification is a good place to start. You can see what data is being transmitted to the device using a USB bus analyzer, which is an expensive proposition for a hobbyist but is well within the reach of most businesses doing USB development. For example, the Catalyst Conquest is $1199. Another established manufacturer is LeCroy (formerly CATC). There are also software USB analyzers that hook into the OS's USB stack, but they don't show all of the traffic on the bus, and may not be as reliable. I'm not a Mac expert, so take this paragraph with a grain of salt: Apple has a driver development kit called the I/O Kit, which apparently requires you to write your driver in C++, unless they also have some sort of user-mode driver framework. If you're writing it in Python, it will probably be more like a Python library that interfaces to someone else's (Apple's?) generic USB driver.
{ "language": "en", "url": "https://stackoverflow.com/questions/170278", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Delphi 2009 Ribbon Controls - Glass Frame I've been starting to use the new inbuilt Ribbon controls in Delphi 2009 and use the custom frame so the Application button and Mini-toolbar slide up onto the Window Frame, but I'm wondering if on Vista it should use the glass effect like Office 2007 does, and if so how I would enable this setting. Thanks for any help. A: Unfortunately it doesn't appear that that CodeGear implementation of the Ribbon control is compatible with the glass frame. Something about the way it draws disables it. A: You can try this http://www.bilsen.com/windowsribbon/index.shtml It interfaces the Native Ribbon Framework and works beautifully.
{ "language": "en", "url": "https://stackoverflow.com/questions/170282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Change Sound (or other) System Preferences in Mac OS X I'd like to be able to switch the sound output source in Mac OS X without any GUI interaction. There are tools to do control the sound output, such as SoundSource and an applescript to open the preferences dialog. What I am looking for is something that switches the preference instantly, like SoundSource but it has to be scriptable. The goal is to switch between my digital and analog output with one keystroke. I have a helper application that will launch a program or applescript on one keypress. All I need now is the applescript or application that switches the sound source quickly without any user interaction. I'm willing to write some Objective-C if that is what it takes, but I'm pretty much a newbie at Cocoa development. Do you have a one-click solution or can point me to a good tutorial on controlling sound system preferences from a Cocoa App or command line? EDIT: I created a command-line application to do exactly this. You may download it at http://code.google.com/p/switchaudio-osx/downloads. Source code is available on the project site as well. A: I created a command-line application to do exactly this. You may download it at http://code.google.com/p/switchaudio-osx/downloads. Source code is available on the project site as well. UPDATE (Dec. 2014): the code is now hosted on github -- https://github.com/deweller/switchaudio-osx. And works just fine in Yosemite. A: Don’t think of it in terms of preferences; there’s no centralized system preference framework for this sort of thing. I believe what you need to do is use Core Audio to set the kAudioHardwarePropertyDefaultOutputDevice and kAudioHardwarePropertyDefaultSystemOutputDevice properties of the AudioSystemObject (using AudioHardwareSetProperty()).
{ "language": "en", "url": "https://stackoverflow.com/questions/170294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: "Code covered" vs. "Code tested"? Converting my current code project to TDD, I've noticed something. class Foo { public event EventHandler Test; public void SomeFunction() { //snip... Test(this, new EventArgs()); } } There are two dangers I can see when testing this code and relying on a code coverage tool to determine if you have enough tests. * *You should be testing if the Test event gets fired. Code coverage tools alone won't tell you if you forget this. *I'll get to the other in a second. To this end, I added an event handler to my startup function so that it looked like this: Foo test; int eventCount; [Startup] public void Init() { test = new Foo(); // snip... eventCount = 0; test.Test += MyHandler; } void MyHandler(object sender, EventArgs e) { eventCount++; } Now I can simply check eventCount to see how many times my event was called, if it was called. Pretty neat. Only now we've let through an insidious little bug that will never be caught by any test: namely, SomeFunction() doesn't check if the event has any handlers before trying to call it. This will cause a null dereference, which will never be caught by any of our tests because they all have an event handler attached by default. But again, a code coverage tool will still report full coverage. This is just my "real world example" at hand, but it occurs to me that plenty more of these sorts of errors can slip through, even with 100% 'coverage' of your code, this still doesn't translate to 100% tested. Should we take the coverage reported by such a tool with a grain of salt when writing tests? Are there other sorts of tools that would catch these holes? A: I wouldn't say "take it with a grain of salt" (there is a lot of utility to code coverage), but to quote myself TDD and code coverage are not a panacea: · Even with 100% block coverage, there still will be errors in the conditions that choose which blocks to execute. · Even with 100% block coverage + 100% arc coverage, there will still be errors in straight-line code. · Even with 100% block coverage + 100% arc coverage + 100% error-free-for-at-least-one-path straight-line code, there will still be input data that executes paths/loops in ways that exhibit more bugs. (from here) While there may be some tools that can offer improvement, I think the higher-order bit is that code coverage is only part of an overall testing strategy to ensure product quality. A: <100% code coverage is bad, but it doesn't follow that 100% code coverage is good. It's a necessary but not sufficient condition, and should be treated as such. Also note that there's a difference between code coverage and path coverage: void bar(Foo f) { if (f.isGreen()) accountForGreenness(); if (f.isBig()) accountForBigness(); finishBar(f); } If you pass a big, green Foo into that code as a test case, you get 100% code coverage. But for all you know a big, red Foo would crash the system because accountForBigness incorrectly assumes that some pointer is non-null, that is only made non-null by accountForGreenness. You didn't have 100% path coverage, because you didn't cover the path which skips the call to accountForGreenness but not the call to accountForBigness. It's also possible to get 100% branch coverage without 100% path coverage. In the above code, one call with a big, green Foo and one with a small, red Foo gives the former but still doesn't catch the big, red bug. Not that this example is the best OO design ever, but it's rare to see code where code coverage implies path coverage. And even if it does imply that in your code, it doesn't imply that all code or all paths in library or system are covered, that your program could possibly use. You would in principle need 100% coverage of all the possible states of your program to do that (and hence make sure that for example in no case do you call with invalid parameters leading to error-catching code in the library or system not otherwise attained), which is generally infeasible. A: Should we take the coverage reported by such a tool with a grain of salt when writing tests? Absolutely. The coverage tool only tells you what proportion of lines in your code were actually run during tests. It doesn't say anything about how thoroughly those lines were tested. Some lines of code need to be tested only once or twice, but some need to be tested over a wide range of inputs. Coverage tools can't tell the difference. A: Also, a 100% test coverage as such does not mean much if the test driver just exercised the code without meaningful assertions regarding the correctness of the results. A: Coverage is only really useful for identifying code that hasn't been tested at all. It doesn't tell you much about code that has been covered. A: Yes, this is the primary different between "line coverage" and "path coverage". In practice, you can't really measure code path coverage. Like static compile time checks, unit tests and static analysis -- line coverage is just one more tool to use in your quest for quality code. A: Testing is absolutly necessary. What must be consitent too is the implementation. If you implement something in a way that have not been in your tests... it's there that the problem may happen. Problem may also happen when the data you test against is not related to the data that is going to be flowing through your application. So Yes, code coverage is necessary. But not as much as real test performed by real person.
{ "language": "en", "url": "https://stackoverflow.com/questions/170297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Seeing project dependancies from MSBuild Is there a mode, some switch or a programmatic way that I can ask MSBuild to display or output it's calculated dependencies for a given build file? Some background - I have a large project that requires splitting up to speed up the build time and want to remove the slow changing infrastructure code into it's own release area. Not all of the information is contained in the build file itself, as some sub-projects are referenced by their vcproj or csproj files. I'd really like to see what MSBuild thinks needs doing (either worse-case [rebuild all] and perhaps for a make) without actually doing the rebuild. A: The MSBuild Profiler project should be able to help you in seeing where time is being taken on the build. It doesn't directly show dependencies. With or without build dependencies, just profiling the builds can probably give some insight and help speed up the process. I did just come across this application, but I have not used it myself yet, Dependency Visualizer that looks to have just added MSBuild-compatible project files. There have also been posts about doing this previously, but no code (see A, B). A: Whilst I asked the original question quite a long time ago, I have moved on in jobs and surprisingly encountered the same need. In this case I was more successful in my pursuit of a tool and discovered Microsoft Build Sidekick which offers: * *view *edit *build *debug of Microsoft Visual Studio© 2005, 2008 and 2010 project files. As well as debugging and logging features I haven't yet used, it has a diagramming mode where you can select the "Target" and it shows all of the dependent Targets and steps within them. Apparently this diagram can be viewed when stepping through the build process (debugging)!
{ "language": "en", "url": "https://stackoverflow.com/questions/170327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Executing a stored procedure within a stored procedure I would like to execute a stored procedure within a stored procedure, e.g. EXEC SP1 BEGIN EXEC SP2 END But I only want SP1 to finish after SP2 has finished running so I need to find a way for SP1 to wait for SP2 to finish before SP1 ends. SP2 is being executed as part of SP1 so I have something like: CREATE PROCEDURE SP1 AS BEGIN EXECUTE SP2 END A: T-SQL is not asynchronous, so you really have no choice but to wait until SP2 ends. Luckily, that's what you want. CREATE PROCEDURE SP1 AS EXEC SP2 PRINT 'Done' A: Thats how it works stored procedures run in order, you don't need begin just something like exec dbo.sp1 exec dbo.sp2 A: Here is an example of one of our stored procedures that executes multiple stored procedures within it: ALTER PROCEDURE [dbo].[AssetLibrary_AssetDelete] ( @AssetID AS uniqueidentifier ) AS SET NOCOUNT ON SET TRANSACTION ISOLATION LEVEL READ COMMITTED EXEC AssetLibrary_AssetDeleteAttributes @AssetID EXEC AssetLibrary_AssetDeleteComponents @AssetID EXEC AssetLibrary_AssetDeleteAgreements @AssetID EXEC AssetLibrary_AssetDeleteMaintenance @AssetID DELETE FROM AssetLibrary_Asset WHERE AssetLibrary_Asset.AssetID = @AssetID RETURN (@@ERROR) A: Inline Stored procedure we using as per our need. Example like different Same parameter with different values we have to use in queries.. Create Proc SP1 ( @ID int, @Name varchar(40) -- etc parameter list, If you don't have any parameter then no need to pass. ) AS BEGIN -- Here we have some opereations -- If there is any Error Before Executing SP2 then SP will stop executing. Exec SP2 @ID,@Name,@SomeID OUTPUT -- ,etc some other parameter also we can use OutPut parameters like -- @SomeID is useful for some other operations for condition checking insertion etc. -- If you have any Error in you SP2 then also it will stop executing. -- If you want to do any other operation after executing SP2 that we can do here. END
{ "language": "en", "url": "https://stackoverflow.com/questions/170328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "48" }
Q: Django signals vs. overriding save method I'm having trouble wrapping my head around this. Right now I have some models that looks kind of like this: def Review(models.Model) ...fields... overall_score = models.FloatField(blank=True) def Score(models.Model) review = models.ForeignKey(Review) question = models.TextField() grade = models.IntegerField() A Review is has several "scores", the overall_score is the average of the scores. When a review or a score is saved, I need to recalculate the overall_score average. Right now I'm using a overridden save method. Would there be any benefits to using Django's signal dispatcher? A: Save/delete signals are generally favourable in situations where you need to make changes which aren't completely specific to the model in question, or could be applied to models which have something in common, or could be configured for use across models. One common task in overridden save methods is automated generation of slugs from some text field in a model. That's an example of something which, if you needed to implement it for a number of models, would benefit from using a pre_save signal, where the signal handler could take the name of the slug field and the name of the field to generate the slug from. Once you have something like that in place, any enhanced functionality you put in place will also apply to all models - e.g. looking up the slug you're about to add for the type of model in question, to ensure uniqueness. Reusable applications often benefit from the use of signals - if the functionality they provide can be applied to any model, they generally (unless it's unavoidable) won't want users to have to directly modify their models in order to benefit from it. With django-mptt, for example, I used the pre_save signal to manage a set of fields which describe a tree structure for the model which is about to be created or updated and the pre_delete signal to remove tree structure details for the object being deleted and its entire sub-tree of objects before it and they are deleted. Due to the use of signals, users don't have to add or modify save or delete methods on their models to have this management done for them, they just have to let django-mptt know which models they want it to manage. A: Small addition from Django docs about bulk delete (.delete() method on QuerySet objects): Keep in mind that this will, whenever possible, be executed purely in SQL, and so the delete() methods of individual object instances will not necessarily be called during the process. If you’ve provided a custom delete() method on a model class and want to ensure that it is called, you will need to “manually” delete instances of that model (e.g., by iterating over a QuerySet and calling delete() on each object individually) rather than using the bulk delete() method of a QuerySet. https://docs.djangoproject.com/en/1.11/topics/db/queries/#deleting-objects And bulk update (.update() method on QuerySet objects): Finally, realize that update() does an update at the SQL level and, thus, does not call any save() methods on your models, nor does it emit the pre_save or post_save signals (which are a consequence of calling Model.save()). If you want to update a bunch of records for a model that has a custom save() method, loop over them and call save() https://docs.djangoproject.com/en/2.1/ref/models/querysets/#update A: If you'll use signals you'd be able to update Review score each time related score model gets saved. But if don't need such functionality i don't see any reason to put this into signal, that's pretty model-related stuff. A: You asked: Would there be any benefits to using Django's signal dispatcher? I found this in the django docs: Overridden model methods are not called on bulk operations Note that the delete() method for an object is not necessarily called when deleting objects in bulk using a QuerySet or as a result of a cascading delete. To ensure customized delete logic gets executed, you can use pre_delete and/or post_delete signals. Unfortunately, there isn’t a workaround when creating or updating objects in bulk, since none of save(), pre_save, and post_save are called. From: Overriding predefined model methods A: It is a kind sort of denormalisation. Look at this pretty solution. In-place composition field definition.
{ "language": "en", "url": "https://stackoverflow.com/questions/170337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "111" }
Q: What are the performance improvement of Sequential Guid over standard Guid? Has someone ever measured performance of Sequential Guid vs. Standard Guid when used as Primary Keys inside a database? I do not see the need for unique keys to be guessable or not, passing them from a web UI or in some other part seems a bad practice by itself and I do not see, if you have security concerns, how using a guid can improve things (if this is the matter use a real random number generator using the proper crypto functions of the framework). The other items are covered by my approach, a sequential guid can be generated from code without need for DB access (also if only for Windows) and it's unique in time and space. And yes, question was posed with the intent of answering it, to give people that have choosen Guids for their PK a way to improve database usage (in my case has allowed the customers to sustain a much higher workload without having to change servers). It seems that security concerns are a lot, in this case do not use Sequential Guid or, better still, use standard Guid for PK that are passed back and forward from your UI and sequential guid for everything else. As always there is no absolute truth, I've edited also main answer to reflect this. A: I may be missing something here (feel free to correct me if I am), but I can see very little benefit in using sequential GUID/UUIDs for primary keys. The point of using GUIDs or UUIDs over autoincrementing integers is: * *They can be created anywhere without contacting the database *They are identifiers that are entirely unique within your application (and in the case of UUIDs, universally unique) *Given one identifier, there is no way to guess the next or previous (or even any other valid identifiers) outside of brute-forcing a huge keyspace. Unfortunately, using your suggestion, you lose all those things. So, yes. You've made GUIDs better. But in the process, you've thrown away almost all of the reasons to use them in the first place. If you really want to improve performance, use a standard autoincrementing integer primary key. That provides all the benefits you described (and more) while being better than a 'sequential guid' in almost every way. This will most likely get downmodded into oblivion as it doesn't specifically answer your question (which is apparently carefully-crafted so you could answer it yourself immediately), but I feel it's a far more important point to raise. A: See This article: (http://www.shirmanov.com/2010/05/generating-newsequentialid-compatible.html) Even though MSSql uses this same function to generate NewSequencialIds ( UuidCreateSequential(out Guid guid) ), MSSQL reverses the 3rd and 4th byte patterns which does not give you the same result that you would get when using this function in your code. Shirmanov shows how to get the exact same results that MSSQL would create. A: I messured difference between Guid (clustered and non clustered), Sequential Guid and int (Identity/autoincrement) using Entity Framework. The Sequential Guid was surprisingly fast compared to the int with identity. Results and code of the Sequential Guid here. A: Check out COMBs by Jimmy Nilsson: a type of GUID where a number of bits have been replaced with a timestamp-like value. This means that the COMBs can be ordered, and when used as a primary key result in less index page splits when inserting new values. See also: Is it OK to use a uniqueidentifier (GUID) as a Primary Key? Yes, a uniqueidentifier (GUID) column can be fine as a Primary Key, BUT it is not a particularly good choice for the clustered index. In many cases, you will be better off creating the clustered index on a column (or columns) that are likely be used in range searches, and create a non-clustered index on the GUID column. A: If you need to use sequential GUIds, SQL Server 2005 can generate them for you with the NEWSEQUENTIALID() function. However since the basic usage of GUIds is to generate keys (or alternate keys) that cannot be guessed (for example to avoid people passing guessed keys on GETs), I don't see how applicable they are because they are so easily guessed. From MSDN: Important: If privacy is a concern, do not use this function. It is possible to guess the value of the next generated GUID and, therefore, access data associated with that GUID. A: OK, I finally got to this point in design and production myself. I generate a COMB_GUID where the upper 32 bits are based on the bits 33 through 1 of Unix time in milliseconds. So, there are 93 bits of randomness every 2 milliseconds and the rollover on the upper bits happens every 106 years. The actual physical representation of the COMB_GUID (or type 4 UUID) is a base64 encoded version of the 128 bits, which is a 22 char string. When inserting in postgres the ratio of speed between a fully random UUID and a COMB _GUID holds as beneficial for the COMB_GUID. The COMB_GUID is 2X faster on my hardware over multiple tests, for a one million record test. The records contain the id(22 chars), a string field (110 chars), a double precision, and an INT. In ElasticSearch, there is NO discernible difference between the two for indexing. I'm still going to use COMB_GUIDS in case content goes to BTREE indexes anywhere in the chain as the content is fed time related, or can be presorted on the id field so that it IS time related and partially sequential, it will speed up. Pretty interesting. The Java code to make a COMB_GUID is below. import java.util.Arrays; import java.util.UUID; import java.util.Base64; //Only avail in Java 8+ import java.util.Date; import java.nio.ByteBuffer; private ByteBuffer babuffer = ByteBuffer.allocate( (Long.SIZE/8)*2 ); private Base64.Encoder encoder = Base64.getUrlEncoder(); public String createId() { UUID uuid = java.util.UUID.randomUUID(); return uuid2base64( uuid ); } public String uuid2base64(UUID uuid){ Date date= new Date(); int intFor32bits; synchronized(this){ babuffer.putLong(0,uuid.getLeastSignificantBits() ); babuffer.putLong(8,uuid.getMostSignificantBits() ); long time=date.getTime(); time=time >> 1; // makes it every 2 milliseconds intFor32bits = (int) time; // rolls over every 106 yers + 1 month from epoch babuffer.putInt( 0, intFor32bits); } //does this cause a memory leak? return encoder.encodeToString( babuffer.array() ); } } A: As massimogentilini already said, Performance can be improved when using UuidCreateSequential (when generating the guids in code). But a fact seems to be missing: The SQL Server (at least Microsoft SQL 2005 / 2008) uses the same functionality, BUT: the comparison/ordering of Guids differ in .NET and on the SQL Server, which would still cause more IO, because the guids will not be ordered correctly. In order to generate the guids ordered correctly for sql server (ordering), you have to do the following (see comparison details): [System.Runtime.InteropServices.DllImport("rpcrt4.dll", SetLastError = true)] static extern int UuidCreateSequential(byte[] buffer); static Guid NewSequentialGuid() { byte[] raw = new byte[16]; if (UuidCreateSequential(raw) != 0) throw new System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error()); byte[] fix = new byte[16]; // reverse 0..3 fix[0x0] = raw[0x3]; fix[0x1] = raw[0x2]; fix[0x2] = raw[0x1]; fix[0x3] = raw[0x0]; // reverse 4 & 5 fix[0x4] = raw[0x5]; fix[0x5] = raw[0x4]; // reverse 6 & 7 fix[0x6] = raw[0x7]; fix[0x7] = raw[0x6]; // all other are unchanged fix[0x8] = raw[0x8]; fix[0x9] = raw[0x9]; fix[0xA] = raw[0xA]; fix[0xB] = raw[0xB]; fix[0xC] = raw[0xC]; fix[0xD] = raw[0xD]; fix[0xE] = raw[0xE]; fix[0xF] = raw[0xF]; return new Guid(fix); } or this link or this link. A: GUID vs.Sequential GUID A typical pattern it's to use Guid as PK for tables, but, as referred in other discussions (see Advantages and disadvantages of GUID / UUID database keys) there are some performance issues. This is a typical Guid sequence f3818d69-2552-40b7-a403-01a6db4552f7 7ce31615-fafb-42c4-b317-40d21a6a3c60 94732fc7-768e-4cf2-9107-f0953f6795a5 Problems of this kind of data are:< - * *Wide distributions of values *Almost randomically ones *Index usage is very, very, very bad *A lot of leaf moving *Almost every PK need to be at least on a non clustered index *Problem happens both on Oracle and SQL Server A possible solution is using Sequential Guid, that are generated as follows: cc6466f7-1066-11dd-acb6-005056c00008 cc6466f8-1066-11dd-acb6-005056c00008 cc6466f9-1066-11dd-acb6-005056c00008 How to generate them From C# code: [DllImport("rpcrt4.dll", SetLastError = true)] static extern int UuidCreateSequential(out Guid guid); public static Guid SequentialGuid() { const int RPC_S_OK = 0; Guid g; if (UuidCreateSequential(out g) != RPC_S_OK) return Guid.NewGuid(); else return g; } Benefits * *Better usage of index *Allow usage of clustered keys (to be verified in NLB scenarios) *Less disk usage *20-25% of performance increase at a minimum cost Real life measurement: Scenario: * *Guid stored as UniqueIdentifier types on SQL Server *Guid stored as CHAR(36) on Oracle *Lot of insert operations, batched together in a single transaction *From 1 to 100s of inserts depending on table *Some tables > 10 millions rows Laboratory Test – SQL Server VS2008 test, 10 concurrent users, no think time, benchmark process with 600 inserts in batch for leaf table Standard Guid Avg. Process duration: 10.5 sec Avg. Request for second: 54.6 Avg. Resp. Time: 0.26 Sequential Guid Avg. Process duration: 4.6 sec Avg. Request for second: 87.1 Avg. Resp. Time: 0.12 Results on Oracle (sorry, different tool used for test) 1.327.613 insert on a table with a Guid PK Standard Guid, 0.02 sec. elapsed time for each insert, 2.861 sec. of CPU time, total of 31.049 sec. elapsed Sequential Guid, 0.00 sec. elapsed time for each insert, 1.142 sec. of CPU time, total of 3.667 sec. elapsed The DB file sequential read wait time passed from 6.4 millions wait events for 62.415 seconds to 1.2 million wait events for 11.063 seconds. It's important to see that all the sequential guid can be guessed, so it's not a good idea to use them if security is a concern, still using standard guid. To make it short... if you use Guid as PK use sequential guid every time they are not passed back and forward from a UI, they will speed up operation and do not cost anything to implement.
{ "language": "en", "url": "https://stackoverflow.com/questions/170346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "70" }
Q: How do I write to a log from mod_python under apache? I seem to only be able to write to the Apache error log via stderr. Anyone know of a more structured logging architecture that I could use from my python web project, like commons? A: This must have changed in the past four years. If you come across this question and want to do this then you can do it through the request object, i.e def handler(req) : req.log_error('Hello apache') A: There isn't any built in support for mod_python logging to Apache currently. If you really want to work within the Apache logs you can check out this thread (make sure you get the second version of the posted code, rather than the first): * *http://www.dojoforum.com/node/13239 *http://www.modpython.org/pipermail/mod_python/2005-October/019295.html If you're just looking to use a more structured logging system, the Python standard logging module referred to by Blair is very feature complete. Aside from the Python.org docs Blair linked, here's a more in-depth look at the module's features from onLamp: * *http://www.onlamp.com/pub/a/python/2005/06/02/logging.html And for a quickie example usage: * *http://hackmap.blogspot.com/2007/06/note-to-self-using-python-logging.html A: I've used the builtin Python logging module in (non-web) projects in the past, with success - it should work in a web-hosted environment as well. A: I concur with Blair Conrad's post about the Python logging module. The standard log handlers sometimes drop messages however. It's worth using the logging module's SocketHandler and building a receiver to listen for messages and write them to file. Here's mine: Example SocketHandler receiver.
{ "language": "en", "url": "https://stackoverflow.com/questions/170353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to detect user inactivity in an Excel workbook I want to take an action in an Excel workbook macro after a period of inactivity (hide/protect some worksheets). What is the best/simplest way to achieve this? Í'm assuming I'll use Application.OnTime to periodically check if the user has been active. But what events should I handle to see if the user was "active" (i.e. has does something - anything - with the workbook)? Clarification: I want to detect all activity, not just changes. I.e. including mouse clicks, selecting, copying, navigating with the keyboard, changing worksheets, ... I'm assuming that when a UI event happens that represents user activity, I will set a variable thus: LastActivityTime = Now and the macro run by Application.OnTime will check this variable to see if the user has been active recently. Which events (other than SheetChange) would I need to handle to set this variable? I had kind of hoped there would be KeyUp and MouseUp events, these two would probably have been enough. Update: I have implemented this by handling Workbook_SheetActivate, Workbook_SheetSelectionChange and Workbook_WindowActivate. Realistically this is probably enough. A: I have implemented this by handling Workbook_SheetActivate, Workbook_SheetSelectionChange and Workbook_WindowActivate. Realistically this is probably enough. A: I can only see two solutions -- either handle evary single event the Application object has or use GetLastInputInfo function. A: One simple way is to compare the content of the workbook with that of the last time you check. I believe combining this with Application.OnTime will solve your concern.
{ "language": "en", "url": "https://stackoverflow.com/questions/170355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Does tomcat 5.5 treat .jsp and .jspx files in the same way? I'm working on a java web-application, trying to be xml-friendly and writing my jsp files using the jspx/xml syntax. It took me hours of dissecting examples and configuration files to find out that with tomcat 5.5 files using the new syntax should end in .jspx, or tomcat won't translate tag libraries and stuff. Both file extensions map to the same servlet in tomcat's configuration file, so I thought everything was fine with my .jsp files. Am I missing something? A: There are additional configurations for servlets that can affect behavior. I haven't tried it, but would assume that you could just override some of the default configurations for *.jsp to use that of *.jspx. Try adding a jsp-property-group definition for *.jsp with is-xml set to true: <jsp-property-group> <url-pattern>*.jsp</url-pattern> <is-xml>true</is-xml> </jsp-property-group> Some information on configuring property groups. A: Not one to give up easily, I found this explanation in the Java5 EE Tutorial, Although the jsp:root element is not required, it is still useful in these cases: * *When you want to identify the document as a JSP document to the JSP container without having to add any configuration attributes to the deployment descriptor or name the document with a .jspx extension So I guess I should have read the docs more carefully :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/170377", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why do thread functions need to be declared as '__cdecl'? Sample code that shows how to create threads using MFC declares the thread function as both static and __cdecl. Why is the latter required? Boost threads don't bother with this convention, so is it just an anachronism? For example (MFC): static __cdecl UINT MyFunc(LPVOID pParam) { ... } CWinThread* pThread = AfxBeginThread(MyFunc, ...); Whereas Boost: static void func() { ... } boost::thread t; t.create(&func); (the code samples might not be 100% correct as I am nowhere near an IDE). What is the point of __cdecl? How does it help when creating threads? A: __cdecl tells the compiler to use the C calling convention (as opposed to the stdcall, fastcall or whatever other calling convention your compiler supports). I believe, VC++ uses stdcall by default. The calling convention affects things such as how arguments are pushed onto the stack (or registers, in the case of fastcall) and who pops arguments off the stack (caller or callee). In the case of Boost. I believe it uses template specialization to figure out the appropriate function type and calling convention. A: Look at the prototype for AfxBeginThread(): CWinThread* AfxBeginThread( AFX_THREADPROC pfnThreadProc, LPVOID pParam, int nPriority = THREAD_PRIORITY_NORMAL, UINT nStackSize = 0, DWORD dwCreateFlags = 0, LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL ); AFX_THREADPROC is a typedef for UINT(AFX_CDECL*)(LPVOID). When you pass a function to AfxBeginThread(), it must match that prototype, including the calling convention. The MSDN pages on __cdecl and __stdcall (as well as __fastcall and __thiscall) explain the pros and cons of each calling convention. The boost::thread constructor uses templates to allow you to pass a function pointer or callable function object, so it doesn't have the same restrictions as MFC. A: Because your thread is going to be called by a runtime function that manages this for you, and that function expects it to be that way. Boost designed it a different way. Put a breakpoint at the start of your thread function and look at the stack when it gets called, you'll see the runtime function that calls you. A: C/C++ compilers by default use the C calling convention (pushing rightmost param first on the stack) for it allows working with functions with variable argument number as printf. The Pascal calling convention (aka "fastcall") pushes leftmost param first. This is quicker though costs you the possibility of easy variable argument functions (I read somewhere they're still possible, though you need to use some tricks). Due to the speed resulting from using the Pascal convention, both Win32 and MacOS APIs by default use that calling convention, except in certain cases. If that function has only one param, in theory using either calling convention would be legal, though the compiler may enforce the same calling convention is used to avoid any problem. The boost libraries were designed with an eye on portability, so they should be agnostic as to which caller convention a particular compiler is using. A: The real answer has to do with how windows internally calls the thread proc routine, and it is expecting the function to abide by a specific calling convention, which in this case is a macro, WINAPI, which according to my system is defined as: #define WINAPI __stdcall This means that the called function is responsible for cleaning up the stack. The reason why boost::thread is able to support arbitrary functions is that it passes a pointer to the function object used in the call to thread::create function to CreateThread. The threadproc associated with the thread simply calls operator() on the function object. The reason MFC requires __cdecl therefore has to do with the way it internally calls the function passed in to the call to AfxBeginThread. There is no good reason to do this unless they were planning on allowing vararg parameters...
{ "language": "en", "url": "https://stackoverflow.com/questions/170380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: An implementation of the fast Fourier transform (FFT) in C# Where can I find a free, very quick, and reliable implementation of FFT in C#? That can be used in a product? Or are there any restrictions? A: Here's another; a C# port of the Ooura FFT. It's reasonably fast. The package also includes overlap/add convolution and some other DSP stuff, under the MIT license. https://github.com/hughpyle/inguz-DSPUtil/blob/master/Fourier.cs A: An old question but it still shows up in Google results... A very un-restrictive MIT Licensed C# / .NET library can be found at, https://www.codeproject.com/articles/1107480/dsplib-fft-dft-fourier-transform-library-for-net This library is fast as it parallel threads on multiple cores and is very complete and ready to use. A: The guy that did AForge did a fairly good job but it's not commercial quality. It's great to learn from but you can tell he was learning too so he has some pretty serious mistakes like assuming the size of an image instead of using the correct bits per pixel. I'm not knocking the guy, I respect the heck out of him for learning all that and show us how to do it. I think he's a Ph.D now or at least he's about to be so he's really smart it's just not a commercially usable library. The Math.Net library has its own weirdness when working with Fourier transforms and complex images/numbers. Like, if I'm not mistaken, it outputs the Fourier transform in human viewable format which is nice for humans if you want to look at a picture of the transform but it's not so good when you are expecting the data to be in a certain format (the normal format). I could be mistaken about that but I just remember there was some weirdness so I actually went to the original code they used for the Fourier stuff and it worked much better. (ExocortexDSP v1.2 http://www.exocortex.org/dsp/) Math.net also had some other funkyness I didn't like when dealing with the data from the FFT, I can't remember what it was I just know it was much easier to get what I wanted out of the ExoCortex DSP library. I'm not a mathematician or engineer though; to those guys it might make perfect sense. So! I use the FFT code yanked from ExoCortex, which Math.Net is based on, without anything else and it works great. And finally, I know it's not C#, but I've started looking at using FFTW (http://www.fftw.org/). And this guy already made a C# wrapper so I was going to check it out but haven't actually used it yet. (http://www.sdss.jhu.edu/~tamas/bytes/fftwcsharp.html) OH! I don't know if you are doing this for school or work but either way there is a GREAT free lecture series given by a Stanford professor on iTunes University. https://podcasts.apple.com/us/podcast/the-fourier-transforms-and-its-applications/id384232849 A: http://www.exocortex.org/dsp/ is an open-source C# mathematics library with FFT algorithms. A: AForge.net is a free (open-source) library with Fast Fourier Transform support. (See Sources/Imaging/ComplexImage.cs for usage, Sources/Math/FourierTransform.cs for implemenation) A: The Numerical Recipes website (http://www.nr.com/) has an FFT if you don't mind typing it in. I am working on a project converting a Labview program to C# 2008, .NET 3.5 to acquire data and then look at the frequency spectrum. Unfortunately the Math.Net uses the latest .NET framework, so I couldn't use that FFT. I tried the Exocortex one - it worked but the results to match the Labview results and I don't know enough FFT theory to know what is causing the problem. So I tried the FFT on the numerical recipes website and it worked! I was also able to program the Labview low sidelobe window (and had to introduce a scaling factor). You can read the chapter of the Numerical Recipes book as a guest on thier site, but the book is so useful that I highly recomend purchasing it. Even if you do end up using the Math.NET FFT. A: Math.NET's Iridium library provides a fast, regularly updated collection of math-related functions, including the FFT. It's licensed under the LGPL so you are free to use it in commercial products. A: I see this is an old thread, but for what it's worth, here's a free (MIT License) 1-D power-of-2-length-only C# FFT implementation I wrote in 2010. I haven't compared its performance to other C# FFT implementations. I wrote it mainly to compare the performance of Flash/ActionScript and Silverlight/C#. The latter is much faster, at least for number crunching. /** * Performs an in-place complex FFT. * * Released under the MIT License * * Copyright (c) 2010 Gerald T. Beauregard * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ public class FFT2 { // Element for linked list in which we store the // input/output data. We use a linked list because // for sequential access it's faster than array index. class FFTElement { public double re = 0.0; // Real component public double im = 0.0; // Imaginary component public FFTElement next; // Next element in linked list public uint revTgt; // Target position post bit-reversal } private uint m_logN = 0; // log2 of FFT size private uint m_N = 0; // FFT size private FFTElement[] m_X; // Vector of linked list elements /** * */ public FFT2() { } /** * Initialize class to perform FFT of specified size. * * @param logN Log2 of FFT length. e.g. for 512 pt FFT, logN = 9. */ public void init( uint logN ) { m_logN = logN; m_N = (uint)(1 << (int)m_logN); // Allocate elements for linked list of complex numbers. m_X = new FFTElement[m_N]; for (uint k = 0; k < m_N; k++) m_X[k] = new FFTElement(); // Set up "next" pointers. for (uint k = 0; k < m_N-1; k++) m_X[k].next = m_X[k+1]; // Specify target for bit reversal re-ordering. for (uint k = 0; k < m_N; k++ ) m_X[k].revTgt = BitReverse(k,logN); } /** * Performs in-place complex FFT. * * @param xRe Real part of input/output * @param xIm Imaginary part of input/output * @param inverse If true, do an inverse FFT */ public void run( double[] xRe, double[] xIm, bool inverse = false ) { uint numFlies = m_N >> 1; // Number of butterflies per sub-FFT uint span = m_N >> 1; // Width of the butterfly uint spacing = m_N; // Distance between start of sub-FFTs uint wIndexStep = 1; // Increment for twiddle table index // Copy data into linked complex number objects // If it's an IFFT, we divide by N while we're at it FFTElement x = m_X[0]; uint k = 0; double scale = inverse ? 1.0/m_N : 1.0; while (x != null) { x.re = scale*xRe[k]; x.im = scale*xIm[k]; x = x.next; k++; } // For each stage of the FFT for (uint stage = 0; stage < m_logN; stage++) { // Compute a multiplier factor for the "twiddle factors". // The twiddle factors are complex unit vectors spaced at // regular angular intervals. The angle by which the twiddle // factor advances depends on the FFT stage. In many FFT // implementations the twiddle factors are cached, but because // array lookup is relatively slow in C#, it's just // as fast to compute them on the fly. double wAngleInc = wIndexStep * 2.0*Math.PI/m_N; if (inverse == false) wAngleInc *= -1; double wMulRe = Math.Cos(wAngleInc); double wMulIm = Math.Sin(wAngleInc); for (uint start = 0; start < m_N; start += spacing) { FFTElement xTop = m_X[start]; FFTElement xBot = m_X[start+span]; double wRe = 1.0; double wIm = 0.0; // For each butterfly in this stage for (uint flyCount = 0; flyCount < numFlies; ++flyCount) { // Get the top & bottom values double xTopRe = xTop.re; double xTopIm = xTop.im; double xBotRe = xBot.re; double xBotIm = xBot.im; // Top branch of butterfly has addition xTop.re = xTopRe + xBotRe; xTop.im = xTopIm + xBotIm; // Bottom branch of butterly has subtraction, // followed by multiplication by twiddle factor xBotRe = xTopRe - xBotRe; xBotIm = xTopIm - xBotIm; xBot.re = xBotRe*wRe - xBotIm*wIm; xBot.im = xBotRe*wIm + xBotIm*wRe; // Advance butterfly to next top & bottom positions xTop = xTop.next; xBot = xBot.next; // Update the twiddle factor, via complex multiply // by unit vector with the appropriate angle // (wRe + j wIm) = (wRe + j wIm) x (wMulRe + j wMulIm) double tRe = wRe; wRe = wRe*wMulRe - wIm*wMulIm; wIm = tRe*wMulIm + wIm*wMulRe; } } numFlies >>= 1; // Divide by 2 by right shift span >>= 1; spacing >>= 1; wIndexStep <<= 1; // Multiply by 2 by left shift } // The algorithm leaves the result in a scrambled order. // Unscramble while copying values from the complex // linked list elements back to the input/output vectors. x = m_X[0]; while (x != null) { uint target = x.revTgt; xRe[target] = x.re; xIm[target] = x.im; x = x.next; } } /** * Do bit reversal of specified number of places of an int * For example, 1101 bit-reversed is 1011 * * @param x Number to be bit-reverse. * @param numBits Number of bits in the number. */ private uint BitReverse( uint x, uint numBits) { uint y = 0; for (uint i = 0; i < numBits; i++) { y <<= 1; y |= x & 0x0001; x >>= 1; } return y; } } A: For a multi-threaded implementation tuned for Intel processors I'd check out Intel's MKL library. It's not free, but it's afforable (less than $100) and blazing fast - but you'd need to call it's C dll's via P/Invokes. The Exocortex project stopped development 6 years ago, so I'd be careful using it if this is an important project.
{ "language": "en", "url": "https://stackoverflow.com/questions/170394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "77" }
Q: Maven: Missing: org.apache.maven.wagon:wagon-ftp:jar:1.0-rc1-SNAPSHOT I'm new to Maven so I may be missing something obvious, but I've got a maven project and when I try to "mvn package" this project it fails with ERROR BUILD ERROR INFO ------------------------------------------------------------------------ [INFO] Failed to resolve artifact. Missing: ---------- 1) org.apache.maven.wagon:wagon-ftp:jar:1.0-rc1-SNAPSHOT Try downloading the file manually from the project website. Then, install it using the command: mvn install:install-file -DgroupId=org.apache.maven.wagon -DartifactId=wagon-ftp -Dversion=1.0-rc1-SNAPSHOT -Dpackaging=ja r -Dfile=/path/to/file Alternatively, if you host your own repository you can deploy the file there: mvn deploy:deploy-file -DgroupId=org.apache.maven.wagon -DartifactId=wagon-ftp -Dversion=1.0-rc1-SNAPSHOT -Dpackaging=jar -Dfile=/path/to/file -Durl=[url] -DrepositoryId=[id] Path to dependency: 1) com.cgs:domain:jar:1.0-SNAPSHOT 2) org.apache.maven.wagon:wagon-ftp:jar:1.0-rc1-SNAPSHOT ---------- 1 required artifact is missing. for artifact: com.cgs:domain:jar:1.0-SNAPSHOT from the specified remote repositories: ibiblio.org (http://mirrors.ibiblio.org/pub/mirrors/maven2) The first thing I don't understand is the version it requires 1.0-rc1-SNAPSHOT. The projects' site says the current version is 1.0-beta-5. And I suppose beta goes before RC. Anyway, I've tried to download the latest wagon-ftp JAR (1.0 beta 6 jar) and deploy it according to the instructions in the error message. But guess what, this gave me the same error. A: I've just found the solution as I was typing the end of this question. The problem was that I was running "mvn install:install-file" from the same directory the failing project POM was in. It installed fine when I run it from another directory without a pom.xml.
{ "language": "en", "url": "https://stackoverflow.com/questions/170395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Scrubyt gives 404 Error when clicking link using _details method This might be a similar problem to my earlier two questions - see here and here but I'm trying to use the _detail command to automatically click the link so I can scrape the details page for each individual event. The code I'm using is: require 'rubygems' require 'scrubyt' nuffield_data = Scrubyt::Extractor.define do fetch 'http://www.nuffieldtheatre.co.uk/cn/events/event_listings.php' event do title 'The Coast of Mayo' link_url event_detail do dates "1-4 October" times "7:30pm" end end next_page "Next Page", :limit => 20 end nuffield_data.to_xml.write($stdout,1) Is there any way to print out the URL that using the event_detail is trying to access? The error doesn't seem to give me the URL that gave the 404. Update: I think the link may be a relative link - could this be causing problems? Any ideas how to deal with that? A: sudo gem install ruby-debug This will give you access to a nice ruby debugger, start the debugger by altering your script: require 'rubygems' require 'ruby-debug' Debugger.start Debugger.settings[:autoeval] = true if Debugger.respond_to?(:settings) require 'scrubyt' nuffield_data = Scrubyt::Extractor.define do fetch 'http://www.nuffieldtheatre.co.uk/cn/events/event_listings.php' event do title 'The Coast of Mayo' link_url event_detail do dates "1-4 October" times "7:30pm" end end next_page "Next Page", :limit => 2 end nuffield_data.to_xml.write($stdout,1) Then find out where scrubyt is throwing an exception - in this case: /Library/Ruby/Gems/1.8/gems/scrubyt-0.3.4/lib/scrubyt/core/navigation/fetch_action.rb:52:in `fetch' Find the scrubyt gem on your system, and add a rescue clause to the method in question so that the end of the method looks like this: if @@current_doc_protocol == 'file' @@hpricot_doc = Hpricot(PreFilterDocument.br_to_newline(open(@@current_doc_url).read)) else @@hpricot_doc = Hpricot(PreFilterDocument.br_to_newline(@@mechanize_doc.body)) store_host_name(self.get_current_doc_url) # in case we're on a new host end rescue debugger self # the self is here because debugger doesn't like being at the end of a method end Now run the script again and you should be dropped into a debugger when the exception is raised. Just try typing this a the debug prompt to see what the offending URL is: @@current_doc_url You can also add a debugger statement anywhere in that method if you want to check what is going on - for example you may want to add one between line 51 and 52 of this method to check how the url that is being called changes and why. This is basically how I figured out the answer to your previous questions. Good luck. A: I had the same issue with relative links and fixed it like this... you have to set the :resolve param to the correct base url event do title 'The Coast of Mayo' link_url event_detail :resolve => 'http://www.nuffieldtheatre.co.uk/cn/events' do dates "1-4 October" times "7:30pm" end end A: Sorry I have no idea why this would be nil - every time I have run this it returns a url - the method self.fetch requires a URL which you should be able to access as the local variable doc_url. If this returns nil also may you should post the code where you have included the debugger call. A: I've tried to access doc_url but that seems to also return nil. When I have access to my server (later in the day) I'll post the code with the debugging bit in it.
{ "language": "en", "url": "https://stackoverflow.com/questions/170405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Do you know what may cause memory leaks in JavaScript? Do you know what may cause memory leaks in JavaScript? I am interested in browsers: IE 7, FireFox 3, Safari 3 A: There is a nice article about JavaScript and memory leaks. It does not specific about on browser, it rather describes the whole problematic of memory leaks and JavaScript. * *JavaScript and memory leaks *Introducing the closure *More leakage patterns *Conclusion I think it is a better approach to be as browser unspecific as possible insted of optimizing for a few browsers, when developing a website for the public. A: In general; circular references are the cause of many problems. I remember IE 6 (not sure if it applies to 7) leaking quite badly with XMLHTTP... setting onreadystatechange = null once it was finished with fixed it. A: Here is a classic memory leak in IE:- function body_onload() { var elem = document.getElementById('someElementId'); // do stuff with elem elem.onclick = function() { //Some code that doesn't need the elem variable } } After this code has run there is circular reference because an element has a function assigned its onclick event which references a scope object which in turn holds a reference to element. someElement->onclick->function-scope->elem->someElement In IE DOM elements are COM based reference counting objects that the Javascript GC can't cleanup. The addition of a final line in the above code would clean it up:- var elem = null; A: You're dealing with 2 kinds of objects (and 2 garbage collectors), javascript and DOM objects, which can reference each other (the circular reference), and then neither GC can take care of all its objects even when the page unloads. Here's a good description: http://getben.com/archive/2006/05/30/Resolving-JavaScript-Memory-Leaks.aspx http://www.josh-davis.org/2007/04/11/javascript-built-in-listeners-and-memory-leaks/ A: You can check this MSDN article for Internet Explorer memory leak patterns. Also there are some tools for detecting memory leaks: * *sIEve *JavaScript memory leak detector *Leak Monitor FireFox plugin
{ "language": "en", "url": "https://stackoverflow.com/questions/170415", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: HowTo: Parse the UninstallString reg entry In HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\ is the list of installed programs in my machine (at least most of them). There, there's a String Value called UninstallString which has what you need to run in order to uninstall the program. The thing is not every installer writes the same kind of info, yet Windows knows how to parse that string to run the uninstaller. My questions are: does anybody know how to parse that string?, meaning what are the possible values it might get? and if not, where can I find that kind of info? I googled around with no luck, I guess I'm not looking for the right terms. A: Have a look at this link from MSDN explaining install/unistall procedures, specifically item #6 "Support Add/Remove Programs Properly". As an excerpt from the table there: Key Name | Key Type | Description UninstallPath | REG_EXPAND_SZ | Full path to the application's uninstall program Despite the fact it says 'full path', alot of applications seem to shorten it if the program is in $PATH, especially with things like msiexec.exe.
{ "language": "en", "url": "https://stackoverflow.com/questions/170420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Performance: Python 3.x vs Python 2.x On a question of just performance, how does Python 3 compare to Python 2.x? A: I'd say any difference will be below trivial. For example, looping over a list will be the exact same. The idea behind Python 3 is to clean up the language syntax itself - remove ambigious stuff like except Exception1, Exception2, cleanup the standard modules (no urllib, urllib2, httplib etc). There really isn't much you can do to improve it's performance, although I imagine stuff like the garbage collection and memory management code will have had some tweaks, but it's not going to be a "wow, my database statistic generation code completes in half the time!" improvement - that's something you get by improving the code, rather than the language! Really, performance of the language is irrelevant - all interpreted languages basically function at the same speed. Why I find Python "faster" is all the built-in moudles, and the nice-to-write syntax - something that has been improved in Python3, so I guess in those terms, yes, python3's performance is better then python2.x.. A: The IO library has been completely redesigned, and the new implementation is in pure Python. Whilst this is a functional improvement, it is at present much slower. Work is afoot to rewrite the bulk of the new system in C. For details see these bug reports. A: I think ultimately it is too early to make that kind of comparison just yet. Wait until it is out of beta before benchmarking it. The interpreter will probably be polished enormously before the release but overall i think for most uses the performance would be comparable and if you are running a really speed conscious app is python really the right language to be using? A: Unless there are plans for a new VM of some kind (and I haven't heard of any such plans), there is all the reason to believe that in the long run the performance of Py3K will, at least asymptotically, equal that of 2.5 It may take a few months, but will eventually happen, as nothing in the new features of Py3k is inherently less performant. To conclude, I don't think there's place to worry about it. Neither to hope for a major improvement of some kind. A: 3.0 is slower than 2.5 on official benchmarks. From "What’s New in Python 3.0": The net result of the 3.0 generalizations is that Python 3.0 runs the pystone benchmark around 10% slower than Python 2.5. Most likely the biggest cause is the removal of special-casing for small integers. There’s room for improvement, but it will happen after 3.0 is released! A: I don't if it faster now, but I have to expect that it eventually will be because that is where new performance work will happen and not all of that will be backported.
{ "language": "en", "url": "https://stackoverflow.com/questions/170426", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: Stored procedure not being executed within another stored procedure I have found that SP2 doesn't execute from within SP1 when SP1 is executed. Below is the structure of SP1: ALTER PROCEDURE SP1 AS BEGIN Declare c1 cursor.... open c1 fetch next from c1 ... while @@fetch_status = 0 Begin ... Fetch Next from c1 end close c1 deallocate c1 exec sp2 end I see non of the PRINT statement outputs if they are printed in the 'Output window' in SQL Server 2005 management studio as the 'Output Window'is empty. A: What happens if you run the Stored Procedure code as a single query? If you put a PRINT statement before and after the exec, do you see both outputs? * *If you do, then the stored procedure must have been executed. Probably it's not doing what you would like. *If you don't see any print output, then there's something wrong in the cycle *If you don't see the second output but you see the first, there's something wrong in the second Stored Procedure. A: I am not sure if it helps you, but from my experience the most popular reasons are: * *sp2 gets some parameter which makes it null value -- i.e. you build its name from the strings and one of them is null. *sp2 has some conditions inside and none of them is true, so sp2 executes no code at all -- i.e. one of the parameters is type varchar, you pass value VALUE, check for it inside, but the real value passed to sp2 is V (because there are no varchar length defined). *sp2 builds query from parameters where one of them is null and the whole query becomes null too. Do you see any output if you put PRINT before and after call of sp2? A: you could use @@error to see if there was an error when executing the previous statement.
{ "language": "en", "url": "https://stackoverflow.com/questions/170440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Anyone implemented Endeca with .NET? Would you recommend Endeca or FAST? Which search engine would you recommend for a Commerce website? We have millions of products in a catalog and we want it to be as quick as possible. We would also want to make sure that the marketing driven through the search engine will be fast and effective. What are your opinions? A: This is only half the answer to your question. I've used it with Java and not .NET. Fast is said to be the better search engine. I don't know. However for Commerce Endeca is considered to be the best. I've used it with a catalog of 5Mil. products and queries are very very fast. If you use .NET or Java does not matter in the end solution the Search Engine stays the same. And what search engine to be used is not answered easily. it all depends on what you want/can spend. My experiences with Endeca are very positive. A: We've been using Endeca for several .NET ecommerce website, surely I think it give us faster full text search with little coding in compare with SQL Server, but Endeca is over complexity, it cost us lots of time to update and configure. Its query capability is quite limited, it lacks of flexibility as we get used to with SQL query. I'm going to reduce Endeca dependency by utilize Lucene.Net for search part. A: I have been involved in several .NET implementations of Endeca and have been happy every time. The biggest advantage of Endeca over FAST is the cost and time of implementation. My recommendation is to document your requirements and send out an RFP. Make sure you include the following as part of the RFP: * *A demo of the proposed solution (make sure they clearly explain within the Demo what features are included in the cost of the proposal and what features cost extra). *Examples of existing customers that have implemented this solution on top of the same commerce software you are using. *Software Licensing cost (you will need to provide details about the number of records you have in your commerce catalog as both companies price based on this) *A detailed list of available modules / plugins and their respective costs. *Implementation cost. *Implementation schedule. Hope this helps. A: Endeca is the best commercial product in my own honest opinion. We've been using it for our millions of catalogs data. Or you can try Lucene.NET A: One thing to consider before buying Endeca is that Oracle licenses the product by physical CPU present in a server. So if you were considering virtualizing Endeca servers into a VCE or other blade virtualization server, you would have to pay for licenses for all of the CPUs blades in the appliance, even if you were only utilizing one of them for Endeca. This makes Endeca only suitable for physical server installations, strictly because of Oracle licensing issues.
{ "language": "en", "url": "https://stackoverflow.com/questions/170442", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Theory: "Lexical Encoding" I am using the term "Lexical Encoding" for my lack of a better one. A Word is arguably the fundamental unit of communication as opposed to a Letter. Unicode tries to assign a numeric value to each Letter of all known Alphabets. What is a Letter to one language, is a Glyph to another. Unicode 5.1 assigns more than 100,000 values to these Glyphs currently. Out of the approximately 180,000 Words being used in Modern English, it is said that with a vocabulary of about 2,000 Words, you should be able to converse in general terms. A "Lexical Encoding" would encode each Word not each Letter, and encapsulate them within a Sentence. // An simplified example of a "Lexical Encoding" String sentence = "How are you today?"; int[] sentence = { 93, 22, 14, 330, QUERY }; In this example each Token in the String was encoded as an Integer. The Encoding Scheme here simply assigned an int value based on generalised statistical ranking of word usage, and assigned a constant to the question mark. Ultimately, a Word has both a Spelling & Meaning though. Any "Lexical Encoding" would preserve the meaning and intent of the Sentence as a whole, and not be language specific. An English sentence would be encoded into "...language-neutral atomic elements of meaning ..." which could then be reconstituted into any language with a structured Syntactic Form and Grammatical Structure. What are other examples of "Lexical Encoding" techniques? If you were interested in where the word-usage statistics come from : http://www.wordcount.org A: This question impinges on linguistics more than programming, but for languages which are highly synthetic (having words which are comprised of multiple combined morphemes), it can be a highly complex problem to try to "number" all possible words, as opposed to languages like English which are at least somewhat isolating, or languages like Chinese which are highly analytic. That is, words may not be easily broken down and counted based on their constituent glyphs in some languages. This Wikipedia article on Isolating languages may be helpful in explaining the problem. A: It's easy enough to invent one for yourself. Turn each word into a canonical bytestream (say, lower-case decomposed UCS32), then hash it down to an integer. 32 bits would probably be enough, but if not then 64 bits certainly would. Before you ding for giving you a snarky answer, consider that the purpose of Unicode is simply to assign each glyph a unique identifier. Not to rank or sort or group them, but just to map each one onto a unique identifier that everyone agrees on. A: Their are several major problems with this idea. In most languages, the meaning of a word, and the word associated with a meaning change very swiftly. No sooner would you have a number assigned to a word, before the meaning of the word would change. For instance, the word "gay" used to only mean "happy" or "merry", but it is now used mostly to mean homosexual. Another example is the morpheme "thank you" which originally came from German "danke" which is just one word. Yet another example is "Good bye" which is a shortening of "God bless you". Another problem is that even if one takes a snapshot of a word at any point of time, the meaning and usage of the word would be under contention, even within the same province. When dictionaries are being written, it is not uncommon for the academics responsible to argue over a single word. In short, you wouldn't be able to do it with an existing language. You would have to consider inventing a language of your own, for the purpose, or using a fairly static language that has already been invented, such as Interlingua or Esperanto. However, even these would not be perfect for the purpose of defining static morphemes in an ever-standard lexicon. Even in Chinese, where there is rough mapping of character to meaning, it still would not work. Many characters change their meanings depending on both context, and which characters either precede or postfix them. The problem is at its worst when you try and translate between languages. There may be one word in English, that can be used in various cases, but cannot be directly used in another language. An example of this is "free". In Spanish, either "libre" meaning "free" as in speech, or "gratis" meaning "free" as in beer can be used (and using the wrong word in place of "free" would look very funny). There are other words which are even more difficult to place a meaning on, such as the word beautiful in Korean; when calling a girl beautiful, there would be several candidates for substitution; but when calling food beautiful, unless you mean the food is good looking, there are several other candidates which are completely different. What it comes down to, is although we only use about 200k words in English, our vocabularies are actually larger in some aspects because we assign many different meanings to the same word. The same problems apply to Esperanto and Interlingua, and every other language meaningful for conversation. Human speech is not a well-defined, well oiled-machine. So, although you could create such a lexicon where each "word" had it's own unique meaning, it would be very difficult, and nigh on impossible for machines using current techniques to translate from any human language into your special standardised lexicon. This is why machine translation still sucks, and will for a long time to come. If you can do better (and I hope you can) then you should probably consider doing it with some sort of scholarship and/or university/government funding, working towards a PHD; or simply make a heap of money, whatever keeps your ship steaming. A: How would the system handle pluralization of nouns or conjugation of verbs? Would these each have their own "Unicode" value? A: As a translations scheme, this is probably not going to work without a lot more work. You'd like to think that you can assign a number to each word, then mechanically translate that to another language. In reality, languages have the problem of multiple words that are spelled the same "the wind blew her hair back" versus "wind your watch". For transmitting text, where you'd presumably have an alphabet per language, it would work fine, although I wonder what you'd gain there as opposed to using a variable-length dictionary, like ZIP uses. A: This is an interesting question, but I suspect you are asking it for the wrong reasons. Are you thinking of this 'lexical' Unicode' as something that would allow you to break down sentences into language-neutral atomic elements of meaning and then be able to reconstitute them in some other concrete language? As a means to achieve a universal translator, perhaps? Even if you can encode and store, say, an English sentence using a 'lexical unicode', you can not expect to read it and magically render it in, say, Chinese keeping the meaning intact. Your analogy to Unicode, however, is very useful. Bear in mind that Unicode, whilst a 'universal' code, does not embody the pronunciation, meaning or usage of the character in question. Each code point refers to a specific glyph in a specific language (or rather the script used by a group of languages). It is elemental at the visual representation level of a glyph (within the bounds of style, formatting and fonts). The Unicode code point for the Latin letter 'A' is just that. It is the Latin letter 'A'. It cannot automagically be rendered as, say, the Arabic letter Alif (ﺍ) or the Indic (Devnagari) letter 'A' (अ). Keeping to the Unicode analogy, your Lexical Unicode would have code points for each word (word form) in each language. Unicode has ranges of code points for a specific script. Your lexical Unicode would have to a range of codes for each language. Different words in different languages, even if they have the same meaning (synonyms), would have to have different code points. The same word having different meanings, or different pronunciations (homonyms), would have to have different code points. In Unicode, for some languages (but not all) where the same character has a different shape depending on it's position in the word - e.g. in Hebrew and Arabic, the shape of a glyph changes at the end of the word - then it has a different code point. Likewise in your Lexical Unicode, if a word has a different form depending on its position in the sentence, it may warrant its own code point. Perhaps the easiest way to come up with code points for the English Language would be to base your system on, say, a particular edition of the Oxford English Dictionary and assign a unique code to each word sequentially. You will have to use a different code for each different meaning of the same word, and you will have to use a different code for different forms - e.g. if the same word can be used as a noun and as a verb, then you will need two codes Then you will have to do the same for each other language you want to include - using the most authoritative dictionary for that language. Chances are that this excercise is all more effort than it is worth. If you decide to include all the world's living languages, plus some historic dead ones and some fictional ones - as Unicode does - you will end up with a code space that is so large that your code would have to be extremely wide to accommodate it. You will not gain anything in terms of compression - it is likely that a sentence represented as a String in the original language would take up less space than the same sentence represented as code. P.S. for those who are saying this is an impossible task because word meanings change, I do not see that as a problem. To use the Unicode analogy, the usage of letters has changed (admittedly not as rapidly as the meaning of words), but it is not of any concern to Unicode that 'th' used to be pronounced like 'y' in the Middle ages. Unicode has a code point for 't', 'h' and 'y' and they each serve their purpose. P.P.S. Actually, it is of some concern to Unicode that 'oe' is also 'œ' or that 'ss' can be written 'ß' in German A: This is an interesting little exercise, but I would urge you to consider it nothing more than an introduction to the concept of the difference in natural language between types and tokens. A type is a single instance of a word which represents all instances. A token is a single count for each instance of the word. Let me explain this with the following example: "John went to the bread store. He bought the bread." Here are some frequency counts for this example, with the counts meaning the number of tokens: John: 1 went: 1 to: 1 the: 2 store: 1 he: 1 bought: 1 bread: 2 Note that "the" is counted twice--there are two tokens of "the". However, note that while there are ten words, there are only eight of these word-to-frequency pairs. Words being broken down to types and paired with their token count. Types and tokens are useful in statistical NLP. "Lexical encoding" on the other hand, I would watch out for. This is a segue into much more old-fashioned approaches to NLP, with preprogramming and rationalism abound. I don't even know about any statistical MT that actually assigns a specific "address" to a word. There are too many relationships between words, for one thing, to build any kind of well thought out numerical ontology, and if we're just throwing numbers at words to categorize them, we should be thinking about things like memory management and allocation for speed. I would suggest checking out NLTK, the Natural Language Toolkit, written in Python, for a more extensive introduction to NLP and its practical uses. A: Actually you only need about 600 words for a half decent vocabulary.
{ "language": "en", "url": "https://stackoverflow.com/questions/170452", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can I read multiple tables into a dataset? I have a stored procedure that returns multiple tables. How can I execute and read both tables? I have something like this: SqlConnection conn = new SqlConnection(CONNECTION_STRING); SqlCommand cmd = new SqlCommand("sp_mult_tables",conn); cmd.CommandType = CommandType.StoredProcedure); IDataReader rdr = cmd.ExecuteReader(); I'm not sure how to read it...whats the best way to handle this type of query, I am guessing I should read the data into a DataSet? How is the best way to do this? Thanks. A: Adapted from MSDN: using (SqlConnection conn = new SqlConnection(connection)) { SqlDataAdapter adapter = new SqlDataAdapter(); adapter.SelectCommand = new SqlCommand(query, conn); adapter.Fill(dataset); return dataset; } A: If you want to read the results into a DataSet, you'd be better using a DataAdapter. But with a DataReader, first iterate through the first result set, then call NextResult to advance to the second result set. A: the reader will deal with the result sets in the order returned; when done processing the first result set, call rdr.NextResult() to set for the next one note also that a table adapter will automatically read all result sets into tables in a dataset on fill, but the datatables will be untyped and named Table1, Table2, etc. A: * Reading All Excel sheet names and adding multiple sheets into single dataset with table names as sheet names.* 'Global variables Dim excelSheetNames As String() Dim DtSet As System.Data.DataSet = New DataSet() Private Sub btnLoadData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoadData.Click Dim MyConnection As OleDbConnection Dim da As System.Data.OleDb.OleDbDataAdapter Dim i As Integer MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; data source=SStatus.xls;Extended Properties=""Excel 8.0;HDR=NO;IMEX=1"" ") 'following method gets all the Excel sheet names in the gloabal array excelSheetNames GetExcelSheetNames("SStatus.xls") For Each str As String In excelSheetNames da = New OleDbDataAdapter("select * from [" & str & "]", MyConnection) da.Fill(DtSet, excelSheetNames(i)) i += 1 Next DataGridView1.DataSource = DtSet.Tables(0) End Sub Public Function GetExcelSheetNames(ByVal excelFileName As String) Dim con As OleDbConnection = Nothing Dim dt As DataTable = Nothing Dim conStr As String = ("Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=") + excelFileName & ";Extended Properties=Excel 8.0;" con = New OleDbConnection(conStr) con.Open() dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing) excelSheetNames = New String(dt.Rows.Count - 1) {} Dim i As Integer = 0 For Each row As DataRow In dt.Rows excelSheetNames(i) = row("TABLE_NAME").ToString() i += 1 Next End Function
{ "language": "en", "url": "https://stackoverflow.com/questions/170455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Application Object and Concurrency Concerns In some asp tutorials, like this, i observe the following pattern: Application.Lock 'do some things with the application object Application.Unlock However, since web pages can have multiple instances, there is an obvious concurrency problem. So my questions are the following: What if one page tries to lock while the object is already locked? Is there a way to detect whether the application object is locked? Is it better to just work on an unlocked application object or does that have other consequences? What if there is only one action involving the application object? ~Is there a reason to lock/unlock in that case? A: From the MSDN documentation: The Lock method blocks other clients from modifying the variables stored in the Application object, ensuring that only one client at a time can alter or access the Application variables. If you do not call the Application.Unlock method explicitly, the server unlocks the locked Application object when the .asp file ends or times out. A lock on the Application object persists for a very short time because the application object is unlocked when the page completes processing or times out. If one page locks the application object and a second page tries to do the same while the first page still has it locked, the second page will wait for the first to finish, or until the Server.ScriptTimeout limit is reached. An example: <%@ Language="VBScript" %> <% Application.Lock Application("PageCalls") = Application("PageCalls") + 1 Application("LastCall") = Now() Application.Unlock %> This page has been called <%= Application("PageCalls") %> times. In the example above, the Lock method prevents more than one client at a time from accessing the variable PageCalls. If the application had not been locked, two clients could simultaneously try to increment the variable PageCalls. A: There will be consequences if you use the application object unlocked. For example if you want to implement a global counter:- Application("myCounter") = Application("myCounter") + 1 The above code will at times miscount. This code reads, adds and assigns. If two threads try to perform this at the same time they may read the same value and then subsequently write the same value incrementing myCounter by 1 instead of 2. Whats needed is to ensure that the second thread can't read myCounter until the second thread has written to it. Hence this is better:- Application.Lock Application("myCounter") = Application("myCounter") + 1 Application.Unlock Of course there are concurrency issues if the lock is held for a long time especially if there are other uses for application which are unaffected by the code holding the lock. Hence you should avoid a design that would require a long lock on the application. A: If one page tries to lock the Application object while it is already locked, it will wait until the page holding the lock has released it. This will normally be quick (ASP code should only generally hold the lock for long enough to access the shared object that's stored in Application).
{ "language": "en", "url": "https://stackoverflow.com/questions/170458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a caching script for classic asp? PHP has a number of opcode caches, which as i understand it are scripts that handle the caching aspects of an application. Is there something similar for classic asp, especially something that does not require component installation? Regarding the IIS caching behaviour, it seems from reading here that the behaviour is relevant to some sort of pre-compilation step rather than finished pages. please correct me if i am wrong A: Looking at your comments to the answers here so far and at your edit of your question you seem a little confused over caching. There are two types of caching we could be be talking about. * *Opcode or Template caching *Output caching Opcode or Template caching is the caching that takes place when a raw script file which is merely a text file is transformed to an in memory set of opcodes that can be executed by the script engine. PHP has some additional tools which allow such a set of opcodes be reused when the script file is requested subsequently. Similarly ASP keeps a cache of 'compilied' opcodes in memory and on disk so that it can serve subsequent requests for the same script without going through the whole parsing process again. Output caching is where the generated output of script that is sent to a response buffer is cached so that subsequent requests for an identical URL (and possible matching other headers as well) would not re-run the script at all but resend the previously cached output. ASP has no facility for output caching whereas ASP.NET does. I'm not familiar enough with PHP or its normal platforms to comment on whether such a facility is available for it. You can configure ASPs 'opcode' caching (which it calls template caching) in IIS manager (IIS6) open the properties window on the Web Sites node go to home directory tab and click Configuration... then select the cache options tab. By default 500 'compilied' pages will be cached in memory and 2000 will be cached on disk. In a comment to my original version of this answer you seem to asking whether PHP hosted by IIS would also benefit from template caching. That would depend how PHP is added to the platform. I hardly know anything about PHP but I would imagine it is simply another dll which IIS script mapping maps files with the extension PHP to. That being that case it won't be benefiting from ASPs template caching. The following is probably fiction but just to try to round out the picture:- Another unlikely possiblity would be if PHP were some how added as ASP Script language. In this case files with PHP extension would be mapped to the ASP.DLL and the files would either contain <%@ language="PHP" or the default language in the application configuration would be set to PHP. In this unlikely set up ASP would build a template that would be cached, however whether that template contains 'compilied' opcode etc would be up to PHP. A: It depends on what you mean by "cache". In IIS 6.0 there is template caching, described here (MS Windows 2003 TechCenter): "ASP processes the templates or template files that contain ASP scripts. ASP stores these templates in a template cache and then serves the cached templates for subsequent client requests. Caching ASP templates enhances performance and scalability, because cached templates are not compiled each time they are called." You can find other distinctions of caching here. A simple mechanism for data caching is presented in this article about Improving ASP Performance With Data Caching: "Unfortunately there is no built in caching system in classic ASP, but it is easy to build one by using the Application object to store data. As such the techniques described in this article can be used to bring useful performance enhancements to legacy websites where upgrading the database or porting the code to ASP.NET is not a viable option." A: Maybe this class helps you caching some stuff. http://www.webdevbros.net/2006/11/18/cache-object-for-classic-asp/ It does not require any installed components and uses the application object as storage. Therefore the same cache is used by all ALL your visitors. You can use it for scenarios like e.g: Caching a heavy SQL query, ...
{ "language": "en", "url": "https://stackoverflow.com/questions/170465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What is the simplest, most maintainable way to create a SQL Server ODBC Data Source? I need a programmatic way of creating a SQL Server ODBC Data Source. I can do this by directly accessing the Registry. It would be better if this could be done via an available (SQL Server/Windows) API to protect against changes in the registry keys or values with updated SQL Server drivers. Accepted Answer Note: Using SQLConfigDataSource abstracts the code from the details of Registry keys etc. so this is more robust. I was hoping, however, that SQL Server would have wrapped this with a higher level function which took strongly typed attributes (rather than a delimited string) and exposed it through the driver. A: SQLConfigDataSource() does the job. MSDN article Just in case here is a VB6 example: Const ODBC_ADD_DSN = 1 'user data source Const ODBC_ADD_SYS_DSN = 4 'system data source Private Declare Function SQLConfigDataSource Lib "ODBCCP32.DLL" (ByVal hwndParent As Long, ByVal fRequest As Long, ByVal lpszDriver As String, ByVal lpszAttributes As String) As Long strDriver = "SQL Server" strAttributes = "DSN=Sample" & Chr$(0) _ & "Database=Northwind" & Chr$(0) _ & "Description= Sample Data Source" & Chr$(0) _ & "Server=(local)" & Chr$(0) _ & "Trusted_Connection=No" & Chr$(0) SQLConfigDataSource(0, ODBC_ADD_SYS_DSN, strDriver, strAttributes) A: For VB.NET it can be done this way: Import for 'DllImport': Imports System.Runtime.InteropServices Declaration of SQLConfigDataSource: <DllImport("ODBCCP32.DLL")> Shared Function SQLConfigDataSource _ (ByVal hwndParent As Integer, ByVal fRequest As Integer, _ ByVal lpszDriver As String, _ ByVal lpszAttributes As String) As Boolean End Function Example usage: Const ODBC_ADD_DSN = 1 'User data source Const ODBC_ADD_SYS_DSN = 4 'System data source Public Function CreateSqlServerDataSource Dim strDriver As String : strDriver = "SQL Server" Dim strAttributes As String : strAttributes = _ "DSN=Sample" & Chr(0) & _ "Database=Northwind" & Chr(0) & _ "Description= Sample Data Source" & Chr(0) & _ "Server=(local)" & Chr(0) & _ "Trusted_Connection=No" & Chr(0) SQLConfigDataSource(0, ODBC_ADD_SYS_DSN, strDriver, strAttributes) End Function A: I'd use odbcad32.exe which is located in your system32 folder. This will add your odbc data sources to the correcct location, which won't be effected by any patches. A: To do this directly in the registry you can add a String Value to: HKLM\SOFTWARE\Microsoft\ODBC\ODBC.INI\ODBC Data Sources to add a System DSN, or: HKCU\Software\ODBC\ODBC.INI\ODBC Data Sources to add a User DSN. The Name of the Value is the name of the Data Source you want to create and the Data must be 'SQL Server'. At the same level as 'ODBC Data Sources' in the Registry create a Key with the name of the Data Source you want to create. This key needs the following String Values: Database - Name of default database to which to connect Description - A description of the Data Source Driver - C:\WINDOWS\system32\SQLSRV32.dll LastUser - Name of a database user (e.g. sa) Server - Hostname of machine on which database resides For example, using the reg.exe application from the command line to add a User Data Source called 'ExampleDSN': reg add "HKCU\Software\ODBC\ODBC.INI\ODBC Data Sources" /v ExampleDSN /t REG_SZ /d "SQL Server" reg add HKCU\Software\ODBC\ExampleDSN /v Database /t REG_SZ /d ExampleDSN reg add HKCU\Software\ODBC\ExampleDSN /v Description /t REG_SZ /d "An Example Data Source" reg add HKCU\Software\ODBC\ExampleDSN /v Driver /t REG_SZ /d "C:\WINDOWS\system32\SQLSRV32.DLL" reg add HKCU\Software\ODBC\ExampleDSN /v LastUser /t REG_SZ /d sa reg add HKCU\Software\ODBC\ExampleDSN /v Server /t REG_SZ /d localhost A: Sample Using C#: ( Detailed SQL Server param reference at http://msdn.microsoft.com/en-us/library/aa177860.aspx ) using System.Runtime.InteropServices; private enum RequestFlags : int { ODBC_ADD_DSN = 1, ODBC_CONFIG_DSN = 2, ODBC_REMOVE_DSN = 3, ODBC_ADD_SYS_DSN = 4, ODBC_CONFIG_SYS_DSN = 5, ODBC_REMOVE_SYS_DSN = 6, ODBC_REMOVE_DEFAULT_DSN = 7 } [DllImport("ODBCCP32.DLL", CharSet = CharSet.Unicode, SetLastError = true)] private static extern bool SQLConfigDataSource(UInt32 hwndParent, RequestFlags fRequest, string lpszDriver, string lpszAttributes); public static void CreateDSN() { string strDrivername = "SQL Server"; string strConfig = "DSN=StackOverflow\0" + "Database=Northwind\0" + "Description=StackOverflow Sample\0" + "Server=(local)\0" + "Trusted_Connection=No\0"; bool success = SQLConfigDataSource(0, RequestFlags.ODBC_ADD_SYS_DSN, strDrivername, strConfig); }
{ "language": "en", "url": "https://stackoverflow.com/questions/170466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: makefiles - compile all c files at once I want to experiment with GCC whole program optimizations. To do so I have to pass all C-files at once to the compiler frontend. However, I use makefiles to automate my build process, and I'm not an expert when it comes to makefile magic. How should I modify the makefile if I want to compile (maybe even link) using just one call to GCC? For reference - my makefile looks like this: LIBS = -lkernel32 -luser32 -lgdi32 -lopengl32 CFLAGS = -Wall OBJ = 64bitmath.o \ monotone.o \ node_sort.o \ planesweep.o \ triangulate.o \ prim_combine.o \ welding.o \ test.o \ main.o %.o : %.c gcc -c $(CFLAGS) $< -o $@ test: $(OBJ) gcc -o $@ $^ $(CFLAGS) $(LIBS) A: LIBS = -lkernel32 -luser32 -lgdi32 -lopengl32 CFLAGS = -Wall # Should be equivalent to your list of C files, if you don't build selectively SRC=$(wildcard *.c) test: $(SRC) gcc -o $@ $^ $(CFLAGS) $(LIBS) A: SRCS=$(wildcard *.c) OBJS=$(SRCS:.c=.o) all: $(OBJS) A: You need to take out your suffix rule (%.o: %.c) in favour of a big-bang rule. Something like this: LIBS = -lkernel32 -luser32 -lgdi32 -lopengl32 CFLAGS = -Wall OBJ = 64bitmath.o \ monotone.o \ node_sort.o \ planesweep.o \ triangulate.o \ prim_combine.o \ welding.o \ test.o \ main.o SRCS = $(OBJ:%.o=%.c) test: $(SRCS) gcc -o $@ $(CFLAGS) $(LIBS) $(SRCS) If you're going to experiment with GCC's whole-program optimization, make sure that you add the appropriate flag to CFLAGS, above. On reading through the docs for those flags, I see notes about link-time optimization as well; you should investigate those too.
{ "language": "en", "url": "https://stackoverflow.com/questions/170467", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "64" }
Q: HTML Data exceeds field length after being hex-sanitized The problem is you can't tell the user how many characters are allowed in the field because the escaped value has more characters than the unescaped one. I see a few solutions, but none looks very good: * *One whitelist for each field (too much work and doesn't quite solve the problem) *One blacklist for each field (same as above) *Use a field length that could hold the data even if all characters are escaped (bad) *Uncap the size for the database field (worse) *Save the data hex-unescaped and pass the responsibility entirely to output filtering (not very good) *Let the user guess the maximum size (worst) Are there other options? Is there a "best practice" for this case? Sample code: $string = 'javascript:alert("hello!");'; echo strlen($string); // outputs 27 $escaped_string = filter_var('javascript:alert("hello!");', FILTER_SANITIZE_ENCODED); echo strlen($escaped_string); // outputs 41 If the length of the database field is, say, 40, the escaped data will not fit. A: Don't build your application around the database - build the database for the application! Design how you want the interface to work for the user first, work out the longest acceptable field length, and use that. In general, don't escape before storing in the database - store raw data in the database and format it for display. If something is going to be output many times, then store the processed version. Remember disk space is relatively cheap - don't waste effort trying to make your database compact. A: making some wild assumptions about the context here: * *if the field can hold 32 characters, that is 32 unescaped characters *let the user enter 32 characters *escape/unescape is not the user's problem *why is this an issue? * *if this is form data-entry it won't matter, and *if you are for some reason escaping the data and passing it back then unescape it before storage without further context, it looks like you are fighting a problem that doesn't really exist, or that doesn't need to exist A: This is an interesting problem. I think the solution will be a problem if you assign any responsibility to them because of the sanitization. If they are responsible for guessing the maximum length, then they may well give up and pick something else (and not understand why their input was invalid). Here's my idea: make the database field 150% the size of the input. This extra size serves as "padding" for the space of the hex-sanitization, and the maximum size shown to the user and validator is the actual desired size. Thus if you check the input length before sanitization and it is below that 66% limit on the length your sanitized data should be good to go. If they exceed that extra 34% field space for the buffer, then the input probably should not be accepted. The only trouble is that your database tables will be larger. If you want to avoid this, well, you could always escape only the SQL sensitive characters and handle everything else on output. Edit: Given your example, I think you're escaping far too much. Either use a smaller range of sanitization with HTMLSpecialChars() on output, or make your database fields as much as 200% of their present size. That's just bloated if you ask me. A: * *Why are you allowing users to type in escaped characters? *If you do need to allow explicitly escaped characters, then interpolate the escaped character before sanity-checking it You should pretty much never do any significant work on any string if it is somehow still encoded. Decode it first, then do your work. I find some people have a tendancy to use escaping functions like addSlashes() (or whatever it is in PHP) too early, or decode stuff (like removing HTML-entities) too late. Decode first, do your stuff, then apply any encoding you need to store/output/etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/170479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Out of Memory - Infinite Loop - ASP.NET AJAX Framework We're running on .NET 3.5 SP1. Recently, in IE, some of our users started getting "Out of Memory" errors once in a while. This doesn't happen all the time. I managed to replicate it a couple times and I found that this code, from the AjaxControlToolkit.Common.Common.js file, was causing an infinite loop: AjaxControlToolkit.TextBoxWrapper.registerClass('AjaxControlToolkit.TextBoxWrapper', Sys.UI.Behavior);AjaxControlToolkit.TextBoxWrapper.validatorGetValue = function(id) { var control = $get(id);if (control && control.AjaxControlToolkitTextBoxWrapper) { return control.AjaxControlToolkitTextBoxWrapper.get_Value();} return AjaxControlToolkit.TextBoxWrapper._originalValidatorGetValue(id);} The last line (which calls _originalValidatorGetValue) basically calls back this exact function over and over because control.AjaxControlToolkitTextBoxWrapper is undefined. The function defined right above it is AjaxControlToolkit.TextBoxWrapper.get_Wrapper(control) and could be use to create the wrapper if it doesn't exist, but I don't get the feeling I want to be changing the framework if I'm the only one who's seen this bug in the wild. The bug does not always occur. It seems to occur when the first URL that is loaded contains an AJAX history point. If you open up a page and play with it, causing history points to be added, it works fine. But if you copy-paste the URL into another browser windows, you will get this problem. Therefore, my guess is I am doing something wrong with the history control that doesn't setup the wrappers properly. Even so, there appears to be an infinite loop in there. Any ideas/clues? I filled out a bug report on Microsoft Connect. While filling it out and testing various scenarios, I noticed it was working fine locally but not remotely. Comparing my production/development environment, I noticed CombineScripts was false locally. Deploying that to my production server seems to have resolved the issue. https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=373171 A: If you remove LoadScriptsBeforeUI='false' from ScriptManager, this problem is solved. A: You might want to post a bug report on Microsoft Connect.
{ "language": "en", "url": "https://stackoverflow.com/questions/170483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Either OR non-null constraints in MySQL What's the best way to create a non-NULL constraint in MySQL such that fieldA and fieldB can't both be NULL. I don't care if either one is NULL by itself, just as long as the other field has a non-NULL value. And if they both have non-NULL values, then it's even better. A: This isn't an answer directly to your question, but some additional information. When dealing with multiple columns and checking if all are null or one is not null, I typically use COALESCE() - it's brief, readable and easily maintainable if the list grows: COALESCE(a, b, c, d) IS NULL -- True if all are NULL COALESCE(a, b, c, d) IS NOT NULL -- True if any one is not null This can be used in your trigger. A: @Sklivvz: Testing with MySQL 5.0.51a, I find it parses a CHECK constraint, but does not enforce it. I can insert (NULL, NULL) with no error. Tested both MyISAM and InnoDB. Subsequently using SHOW CREATE TABLE shows that a CHECK constraint is not in the table definition, even though no error was given when I defined the table. This matches the MySQL manual which says: "The CHECK clause is parsed but ignored by all storage engines." So for MySQL, you would have to use a trigger to enforce this rule. The only problem is that MySQL triggers have no way of raising an error or aborting an INSERT operation. One thing you can do in the trigger to cause an error is to set a NOT NULL column to NULL. CREATE TABLE foo ( FieldA INT, FieldB INT, FieldA_or_FieldB TINYINT NOT NULL; ); DELIMITER // CREATE TRIGGER FieldABNotNull BEFORE INSERT ON foo FOR EACH ROW BEGIN IF (NEW.FieldA IS NULL AND NEW.FieldB IS NULL) THEN SET NEW.FieldA_or_FieldB = NULL; ELSE SET NEW.FieldA_or_FieldB = 1; END IF; END// INSERT INTO foo (FieldA, FieldB) VALUES (NULL, 10); -- OK INSERT INTO foo (FieldA, FieldB) VALUES (10, NULL); -- OK INSERT INTO foo (FieldA, FieldB) VALUES (NULL, NULL); -- gives error You also need a similar trigger BEFORE UPDATE. A: MySQL 5.5 introduced SIGNAL, so we don't need the extra column in Bill Karwin's answer any more. Bill pointed out you also need a trigger for update so I've included that too. CREATE TABLE foo ( FieldA INT, FieldB INT ); DELIMITER // CREATE TRIGGER InsertFieldABNotNull BEFORE INSERT ON foo FOR EACH ROW BEGIN IF (NEW.FieldA IS NULL AND NEW.FieldB IS NULL) THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '\'FieldA\' and \'FieldB\' cannot both be null'; END IF; END// CREATE TRIGGER UpdateFieldABNotNull BEFORE UPDATE ON foo FOR EACH ROW BEGIN IF (NEW.FieldA IS NULL AND NEW.FieldB IS NULL) THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '\'FieldA\' and \'FieldB\' cannot both be null'; END IF; END// DELIMITER ; INSERT INTO foo (FieldA, FieldB) VALUES (NULL, 10); -- OK INSERT INTO foo (FieldA, FieldB) VALUES (10, NULL); -- OK INSERT INTO foo (FieldA, FieldB) VALUES (NULL, NULL); -- gives error UPDATE foo SET FieldA = NULL; -- gives error A: This is the standard syntax for such a constraint, but MySQL blissfully ignores the constraint afterwards ALTER TABLE `generic` ADD CONSTRAINT myConstraint CHECK ( `FieldA` IS NOT NULL OR `FieldB` IS NOT NULL ) A: I've done something similar in SQL Server, I'm not sure if it will work directly in MySQL, but: ALTER TABLE tableName ADD CONSTRAINT constraintName CHECK ( (fieldA IS NOT NULL) OR (fieldB IS NOT NULL) ); At least I believe that's the syntax. However, keep in mind that you cannot create check constraints across tables, you can only check the columns within one table. A: I accomplished this using a GENERATED ALWAYS column with COALESCE ... NOT NULL: DROP TABLE IF EXISTS `error`; CREATE TABLE IF NOT EXISTS `error` ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, left_id BIGINT UNSIGNED NULL, right_id BIGINT UNSIGNED NULL, left_or_right_id BIGINT UNSIGNED GENERATED ALWAYS AS (COALESCE(left_id, right_id)) NOT NULL, when_occurred TIMESTAMP DEFAULT CURRENT_TIMESTAMP, message_text LONGTEXT NOT NULL, INDEX id_index (id), INDEX when_occurred_index (when_occurred), INDEX left_id_index (left_id), INDEX right_id_index (right_id) ); INSERT INTO `error` (left_id, right_id, message_text) VALUES (1, 1, 'Some random text.'); -- Ok. INSERT INTO `error` (left_id, right_id, message_text) VALUES (null, 1, 'Some random text.'); -- Ok. INSERT INTO `error` (left_id, right_id, message_text) VALUES (1, null, 'Some random text.'); -- Ok. INSERT INTO `error` (left_id, right_id, message_text) VALUES (null, null, 'Some random text.'); -- ER_BAD_NULL_ERROR: Column 'left_or_right_id' cannot be null on MySQL version 8.0.22
{ "language": "en", "url": "https://stackoverflow.com/questions/170492", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Language features to implement relational algebra I've been trying to encode a relational algebra in Scala (which to my knowlege has one of the most advanced type systems) and just don't seem to find a way to get where I want. As I'm not that experienced with the academic field of programming language design I don't really know what feature to look for. So what language features would be needed, and what language has those features, to implement a statically verified relational algebra? Some of the requirements: A Tuple is a function mapping names from a statically defined set of valid names for the tuple in question to values of the type specified by the name. Lets call this name-type set the domain. A Relation is a Set of Tuples with the same domain such that the range of any tuple is uniqe in the Set So far the model can eaisly be modeled in Scala simply by trait Tuple trait Relation[T<Tuple] extends Set[T] The vals, vars and defs in Tuple is the name-type set defined above. But there should'n be two defs in Tuple with the same name. Also vars and impure defs should probably be restricted too. Now for the tricky part: A join of two relations is a relation where the domain of the tuples is the union of the domains from the operands tuples. Such that only tuples having the same ranges for the intersection of their domains is kept. def join(r1:Relation[T1],r2:Relation[T2]):Relation[T1 with T2] should do the trick. A projection of a Relation is a Relation where the domain of the tuples is a subset of the operands tuples domain. def project[T2](r:Relation[T],?1):Relation[T2>:T] This is where I'm not sure if it's even possible to find a sollution. What do you think? What language features are needed to define project? Implied above offcourse is that the API has to be usable. Layers and layers of boilerplate is not acceptable. A: What your asking for is to be able to structurally define a type as the difference of two other types (the original relation and the projection definition). I honestly can't think of any language which would allow you to do that. Types can be structurally cumulative (A with B) since A with B is a structural sub-type of both A and B. However, if you think about it, a type operation A less B would actually be a supertype of A, rather than a sub-type. You're asking for an arbitrary, contravariant typing relation on naturally covariant types. It hasn't even been proven that sort of thing is sound with nominal existential types, much less structural declaration-point types. I've worked on this sort of modeling before, and the route I took was to constraint projections to one of three domains: P == T, P == {F} where F in T, P == {$_1} where $_1 anonymous. The first is where the projection is equivalent to the input type, meaning it is a no-op (SELECT *). The second is saying that the projection is a single field contained within the input type. The third is the tricky one. It is saying that you are allowing the declaration of some anonymous type $_1 which has no static relationship to the input type. Presumably it will consist of fields which delegate to the input type, but we can't enforce that. This is roughly the strategy that LINQ takes. Sorry I couldn't be more helpful. I wish it were possible to do what you're asking, it would open up a lot of very neat possibilities. A: I think I have settled on just using the normal facilities for mapping collection for the project part. The client just specify a function [T<:Tuple](t:T) => P With some java trickery to get to the class of P I should be able to use reflection to implement the query logic. For the join I'll probably use DynamicProxy to implement the mapping function. As a bonus I might be able to get the API to be usable with Scalas special for-syntax.
{ "language": "en", "url": "https://stackoverflow.com/questions/170500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Frame expert system What's the best way to write a simple frame-based expert system, which determines if object is relative to some group? It's a kind of lab work for Intelligent Systems course in university. Or are there any OpenSource projects to study it's realization? A: We used LPA's Flex which is a toolkit that sits on top of win-prolog. It does frame based expert systems and they have an education programme.
{ "language": "en", "url": "https://stackoverflow.com/questions/170529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Reset @@FETCH_STATUS stored procedure How can I reset the @@FETCH_STATUS variable or set it to 0 in a stored procedure? Also, can you bind FETCH_STATUS to a particular cursor? A: I am able to reproduce the @@FETCH_STATUS issue you describe, this is once you DECLARE a CURSOR and iterate through the rows by calling FETCH NEXT until your @@FETCH_STATUS = -1. Then even if you CLOSE and DEALLOCATE your cursor, if you call that CURSOR back your @@FETCH_STATUS = -1 and if your basing a loop condition on the @@FETCH_STATUS <> -1, your loop never executes. My solution was to basically tell the CURSOR to go back to FIRST, changing the @@FETCH_STATUS back to 0, then exiting. Take note that one must enable to CURSOR to be scrolling by adding the keyword SCROLL after the CURSOR name when you declare it. Here's an example. I used three columns from an orderitems (items people placed orders for) table to create my cursor: USE transact_Sales; GO DECLARE @isOrderNumber INT; DECLARE @isOrderTotal MONEY; DECLARE test SCROLL CURSOR FOR SELECT Oi.order_num, SUM(Oi.quantity@item_price) FROM orderitems AS Oi GROUP BY order_num; OPEN test; WHILE @@FETCH_STATUS = 0 BEGIN FETCH NEXT FROM test INTO @isOrderNumber, @isOrderTotal PRINT CAST(@isOrderNumber AS VARCHAR(20)) + ' ' +CAST(@isOrderTotal AS VARCHAR(20)) + ' ' +CAST(@@FETCH_STATUS AS VARCHAR(5)) END FETCH FIRST FROM test INTO @isOrderNumber, @isOrderTotal CLOSE test; DEALLOCATE test; These are the results: 20005 149.87 0 20006 55.00 0 20007 1000.00 0 20008 125.00 0 20009 38.47 0 20009 38.47 -1 The cursor can be run over and over and will product the same results each time. A: You can reset it by reading a cursor which is not at the end of a table. A: You need to close the cursor and then Open the cursor again. DECLARE @IDs int DECLARE MyCursor CURSOR FOR(SELECT ID FROM Table) OPEN MyCursor FETCH NEXT FROM MyCursor INTO @IDs WHILE @@FETCH_STATUS=0 BEGIN --Do your work(First loop) FETCH NEXT FROM MyCursor INTO @IDs END CLOSE MyCursor --Run the cursor again OPEN MyCursor FETCH NEXT FROM MyCursorINTO @IDs WHILE @@FETCH_STATUS=0 BEGIN --Other work (Second loop) FETCH NEXT FROM MyCursor INTO @IDs END CLOSE MyCursor DEALLOCATE MyCursor A: An old thread I know but an answer found elsewhere that worked for me was: WHILE (1 = 1) BEGIN FETCH NEXT FROM mycursor INTO @somevar IF (@@FETCH_STATUS <> 0) BREAK -- do stuff here END A: You can't: @@FETCH_STATUS (Transact-SQL) Returns the status of the last cursor FETCH statement issued against any cursor currently opened by the connection. So basically it's not bound to any cursor. A: Typically you have a @@FETCH_STATUS immediately after a FETCH, so why would you want to reset it? Try to store its result in a temporary variable if you do not evaluate immediately. A: If you want to break cursor You can use BREAK But this only only replace function from 0 to 1. fetch next While @@fetch_Status = 0 begin if (my condition) break fetch next ; end A: I had what I thought was a need to reset my cursor. I was doing some testing with cursors and I kept coming back with a @@fetch_status being = -1, even after I had coded a close and deallocation to the cursor I was testing. What had happened was I had opened a global cursor in another procedure after a logical test and never closed that cursor after iterating through it. So the Fetch was seeing the @@Fetch_status of that cursor. Close your cursors, deallocate your cursors.
{ "language": "en", "url": "https://stackoverflow.com/questions/170536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java: Save objects in a textfile? Are there readymade solutions? I want to save the objects I generated in a program. After restart the App should load automaticly all Objects in an Array. I want to write them in a file and parse them after restart. Are the other smarter possibilities than do it by hand? Thank you A: You can use the Berkeley DB PersistentMap class to save your (Serializable) objects in a Map implementation (a cache) which persists them to a file. It's pretty simple to use and means you don't have to worry about what to save where. Three things to note about serialization: * *How are you going to cope with schema changes (i.e. changing what data your classes consist of - adding a new field for example) *What happens if your file(s) become corrupted? Depending on how reliable your program's storage needs to be will affect your decision of how you save the data which your objects implicitly contain. Remember, you can always use a relational database such as MySQL and then convert this data into your objects *Do you need to be able to view or query the data outside of your program? What if you want to answer some simple question like "How many object's have property X?" Easy to do if you've used a (relational) database; not so easy if you've serialized stuff to files! A: You may want to check out Effective Java for some gotchas with respect to serialization. These are generally advanced but if this feature is a core part of your app, you'll want to know about them in advance. Examples include security concerns, inheritance, and most importantly the potential to publicly 'freeze' an API with realizing it (e.g. across versions of software). Again, these are all advanced and should not deter you per se. A: Yes, the concept you are looking for is called serialization. There's a fine tutorial at Sun here. The idea is that classes you want to persist have to implement the Serializable interface. After that you use java.io.ObjectOutputStream.writeObject() to write the object to a file and java.io.ObjectInputStream.readObject() to read it back. You can't serialize everything, as there are things that don't make sense to serialize, but you can work around them. Here's a quote about that: The basic mechanism of Java serialization is simple to use, but there are some more things to know. As mentioned before, only objects marked Serializable can be persisted. The java.lang.Object class does not implement that interface. Therefore, not all the objects in Java can be persisted automatically. The good news is that most of them -- like AWT and Swing GUI components, strings, and arrays -- are serializable. On the other hand, certain system-level classes such as Thread, OutputStream and its subclasses, and Socket are not serializable. Indeed, it would not make any sense if they were. For example, thread running in my JVM would be using my system's memory. Persisting it and trying to run it in your JVM would make no sense at all. Another important point about java.lang.Object not implementing the Serializable interface is that any class you create that extends only Object (and no other serializable classes) is not serializable unless you implement the interface yourself (as done with the previous example). That situation presents a problem: what if we have a class that contains an instance of Thread? In that case, can we ever persist objects of that type? The answer is yes, as long as we tell the serialization mechanism our intentions by marking our class's Thread object as transient. A: java.io.Object[Input/Output]Stream are the two classes you need to look at. Any class you wish to persist to file needs to implement the java.io.Serializable interface. A: You might also want to consider using XML encoding, which seems to me to have more durability than serialization. Use java.beans.XMLEncoder/XMLDecoder classes. A: I have not used it but Google Code released protobuf recently. A: I concur with mjlee that Protocol Buffers from Google is a better way to do store objects than the original serialization way. Take a look and you will love it. A: I wonder why no one mentioned JSON and, for instance, Jackson JSON serializer.
{ "language": "en", "url": "https://stackoverflow.com/questions/170554", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Maintaining consistency when using temp backup tables This is related to the accepted answer for What’s your #1 way to be careful with a live database? Suppose you create a temp table for backup purpose and make your changes in the original. The changes break the system and you want to restore the backup. In the meantime some other records have also changed in the original table (it is a live db). Now if you restore the backup, the system will be in an inconsistent state. Whats the best way to tackle this A: I don't think that's desirable, I'd test harder before putting the table in production, but supposing it happened anyway, you'd have two options: 1.- Create an ON INSERT trigger which updates the temporary backup table with the rows inserted into the new table, massaging the data to fit into the old table or 2.- Find the difference in the data like this SELECT * FROM faultyTable EXCEPT SELECT * FROM backupTable You'd have to adjust the columns to be selected to the common subset of course. And EXCEPT is called MINUS sometimes too. After that you can insert the difference into the backed up table and restore the combination. This gets harder and harder the more relationships the table has... depending on the way used to restore the table you might drop the related data, thus you'd have to select it too. A: I usually do BEGIN TRANSACTION -- SQL CODE At the end, if everything is OK, do my SELECTs and whatnot COMMIT otherwise ROLLBACK A: Your database may provide this funcionality. For example in Oracle: Export (Your options) consistent = y Of course, doing a consistent backup in a production online environment will have a performance penalty for the system.
{ "language": "en", "url": "https://stackoverflow.com/questions/170556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: When will most libraries be Python 3 compliant? Does anyone have an idea how long it will take before "almost all" widely used Python libraries work with Python 3.0? I am planning to stay on 2.X for a while because I don't want to start porting stuff over and then find that some library I already rely on or a new library I might start using doesn't work yet with py3k. My understanding is that the py3k beta process was drawn out specifically to give library developers time to move their stuff over. Has this been happening? Examples of the sorts of libraries I am talking about would be PIL, numpy/ scipy, SQLAlchemy, BeautifulSoup, CherryPy... A: The examples you have listed will probably be ported very quickly, as they are so widely used. I would be surprised if BeautifulSoup takes more than a month (In fact, I'm surprised it hasn't been ported already using the py3k betas), more complex things like numpy may take a big longer, especially because 2to3 only works on python sources, not C modules.. It's hard to generalise - some modules may never be ported, some may take days, others may take years. It could end up being a situation along the lines of "well I'm not porting my library to Python3, no one is using it!"/"Well I'm not porting my project to python3, no libraries have been updated yet!", but I hope not! A: Actually, the reply to your question depends on the actions of so many different people (all the maintainers of libraries outside the Python std lib), that I think that no-one can give you a reliable answer to your question. That said, you've had already some answers, and you will have more. We agree on one thing, though: as a rule of thumb, I typically suggest that important projects (related to work, mainly) should not be ported immediately to new development technologies (Python 3, .Net 3.x, etc) until such answers as yours have already been answered and many of the initial bugs have been solved. For pet or test projects, though, I'm all in for updates and experimentation. A: Some comments I saw in the CherryPy repository is that some of the changes to the sockets module are going to require an extensive reworking of the logic. I expect CherryPy will be slower than some of the other projects to get ported to 3.0. A: The general idea in the migration plan is to stay on 2.x and then slowly change the code to 3.x. You will have at least 1.5 years to worry about it in. Of course there's the chicken and egg problem though. A: I remember Adrian (BFDL of django) saying that Guido had given them a time frame of 5 years to port. A: The libraries you mention will be ported once someone puts some serious time into porting them. In the specific case of NumPy/SciPy, a large part of the code is written as C extensions. There is no 2to3 tool for C extensions and so it will take a large amount of man hours to port the code over to the format that cPython3 C extensions need to use. A: As of 2013-05-01, all of the libraries you mentioned now support Python 3: * *PIL, as a fork named Pillow (the original PIL project hasn't been updated since 2009) *NumPy and SciPy *SQLAlchemy *BeautifulSoup *CherryPy Porting work has been going on gradually; some major libraries like Django were ported fairly recently.
{ "language": "en", "url": "https://stackoverflow.com/questions/170563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Operation must use an updatable query. (Error 3073) Microsoft Access On some Microsoft Access queries, I get the following message: Operation must use an updatable query. (Error 3073). I work around it by using temporary tables, but I'm wondering if there's a better way. All the tables involved have a primary key. Here's the code: UPDATE CLOG SET CLOG.NEXTDUE = ( SELECT H1.paidthru FROM CTRHIST as H1 WHERE H1.ACCT = clog.ACCT AND H1.SEQNO = ( SELECT MAX(SEQNO) FROM CTRHIST WHERE CTRHIST.ACCT = Clog.ACCT AND CTRHIST.AMTPAID > 0 AND CTRHIST.DATEPAID < CLOG.UPDATED_ON ) ) WHERE CLOG.NEXTDUE IS NULL; A: I had a similar problem where the following queries wouldn't work; update tbl_Lot_Valuation_Details as LVD set LVD.LGAName = (select LGA.LGA_NAME from tbl_Prop_LGA as LGA where LGA.LGA_CODE = LVD.LGCode) where LVD.LGAName is null; update tbl_LOT_VALUATION_DETAILS inner join tbl_prop_LGA on tbl_LOT_VALUATION_DETAILS.LGCode = tbl_prop_LGA.LGA_CODE set tbl_LOT_VALUATION_DETAILS.LGAName = [tbl_Prop_LGA].[LGA_NAME] where tbl_LOT_VALUATION_DETAILS.LGAName is null; However using DLookup resolved the problem; update tbl_Lot_Valuation_Details as LVD set LVD.LGAName = dlookup("LGA_NAME", "tbl_Prop_LGA", "LGA_CODE="+LVD.LGCode) where LVD.LGAName is null; This solution was originally proposed at https://stackoverflow.com/questions/537161/sql-update-woes-in-ms-access-operation-must-use-an-updateable-query A: The problem defintely relates to the use of (in this case) the max() function. Any aggregation function used during a join (e.g. to retrieve the max or min or avg value from a joined table) will cause the error. And the same applies to using subqueries instead of joins (as in the original code). This is incredibly annoying (and unjustified!) as it is a reasonably common thing to want to do. I've also had to use temp tables to get around it (pull the aggregated value into a temp table with an insert statement, then join to this table with your update, then drop the temp table). Glenn A: There is no error in the code. But the error is Thrown because of the following reason. - Please check weather you have given Read-write permission to MS-Access database file. - The Database file where it is stored (say in Folder1) is read-only..? suppose you are stored the database (MS-Access file) in read only folder, while running your application the connection is not force-fully opened. Hence change the file permission / its containing folder permission like in C:\Program files all most all c drive files been set read-only so changing this permission solves this Problem. A: I know my answer is 7 years late, but here's my suggestion anyway: When Access complains about an UPDATE query that includes a JOIN, just save the query, with RecordsetType property set to Dynaset (Inconsistent Updates). This will sometimes allow the UPDATE to work. A: Thirteen years later I face the same issue. DISTINCTROW did not solve my problem, but dlookup did. I need to update a table from an aggregate query. As far as I understand, MS Access always assumes that de junction between the to-update table and the aggregate query is one-to-many., even though unique records are assured in the query. The use of dlookup is: DLOOKUP(Field, SetOfRecords, Criteria) Field: a string that identifies the field from which the data is retrieved. SetOfRecords: a string that identifies the set o record from which the field is retrieved, being a table name or a (saved) query name (that doesn’t require parameters). Criteria: A string used to restrict the range of data on which the DLookup function is performed, equivalent to the WHERE clause in an SQL expression, without the word WHERE. Remark If more than one field meets criteria, the DLookup function returns the first occurrence. You should specify criteria that will ensure that the field value returned by the DLookup function is unique. The query that worked for me is: UPDATE tblTarifaDeCorretagem SET tblTarifaDeCorretagem.ValorCorretagem = [tblTarifaDeCorretagem].[TarifaParteFixa]+ DLookUp( "[ParteVariável]", "cstParteVariavelPorOrdem", "[IdTarifaDeCorretagem] = " & [tblTarifaDeCorretagem].[IdTarifaDeCorretagem] ); A: Since Jet 4, all queries that have a join to a SQL statement that summarizes data will be non-updatable. You aren't using a JOIN, but the WHERE clause is exactly equivalent to a join, and thus, the Jet query optimizer treats it the same way it treats a join. I'm afraid you're out of luck without a temp table, though maybe somebody with greater Jet SQL knowledge than I can come up with a workaround. BTW, it might have been updatable in Jet 3.5 (Access 97), as a whole lot of queries were updatable then that became non-updatable when upgraded to Jet 4. -- A: I would try building the UPDATE query in Access. I had an UPDATE query I wrote myself like UPDATE TABLE1 SET Field1 = (SELECT Table2.Field2 FROM Table2 WHERE Table2.UniqueIDColumn = Table1.UniqueIDColumn) The query gave me that error you're seeing. This worked on my SQL Server though, but just like earlier answers noted, Access UPDATE syntax isn't standard syntax. However, when I rebuilt it using Access's query wizard (it used the JOIN syntax) it worked fine. Normally I'd just make the UPDATE query a passthrough to use the non-JET syntax, but one of the tables I was joining with was a local Access table. A: This occurs when there is not a UNIQUE MS-ACCESS key for the table(s) being updated. (Regardless of the SQL schema). When creating MS-Access Links to SQL tables, you are asked to specify the index (key) at link time. If this is done incorrectly, or not at all, the query against the linked table is not updatable When linking SQL tables into Access MAKE SURE that when Access prompts you for the index (key) you use exactly what SQL uses to avoid problem(s), although specifying any unique key is all Access needs to update the table. If you were not the person who originally linked the table, delete the linked table from MS-ACCESS (the link only gets deleted) and re-link it specifying the key properly and all will work correctly. A: (A little late to the party...) The three ways I've gotten around this problem in the past are: * *Reference a text box on an open form *DSum *DLookup A: I had the same issue. My solution is to first create a table from the non updatable query and then do the update from table to table and it works. A: You can always write the code in VBA that updates similarly. I had this problem too, and my workaround was making a select query, with all the joins, that had all the data I was looking for to be able to update, making that a recordset and running the update query repeatedly as an update query of only the updating table, only searching the criteria you're looking for Dim updatingItems As Recordset Dim clientName As String Dim tableID As String Set updatingItems = CurrentDb.OpenRecordset("*insert SELECT SQL here*");", dbOpenDynaset) Do Until updatingItems .EOF clientName = updatingItems .Fields("strName") tableID = updatingItems .Fields("ID") DoCmd.RunSQL "UPDATE *ONLY TABLE TO UPDATE* SET *TABLE*.strClientName= '" & clientName & "' WHERE (((*TABLE*.ID)=" & tableID & "))" updatingItems.MoveNext Loop I'm only doing this to about 60 records a day, doing it to a few thousand could take much longer, as the query is running from start to finish multiple times, instead of just selecting an overall group and making changes. You might need ' ' around the quotes for tableID, as it's a string, but I'm pretty sure this is what worked for me. A: Mine failed with a simple INSERT statement. Fixed by starting the application with 'Run as Administrator' access. A: MS Access - joining tables in an update query... how to make it updatable * *Open the query in design view *Click once on the link b/w tables/view *In the “properties” window, change the value for “unique records” to “yes” *Save the query as an update query and run it. A: In essence, while your SQL looks perfectly reasonable, Jet has never supported the SQL standard syntax for UPDATE. Instead, it uses its own proprietary syntax (different again from SQL Server's proprietary UPDATE syntax) which is very limited. Often, the only workarounds "Operation must use an updatable query" are very painful. Seriously consider switching to a more capable SQL product. For some more details about your specific problems and some possible workarounds, see Update Query Based on Totals Query Fails. A: I kept getting the same error until I made the connecting field a unique index in both connecting tables. Only then did the query become updatable. Philip Stilianos A: I kept getting the same error, but all SQLs execute in Access very well. and when I amended the permission of AccessFile. the problem fixed!! I give 'Network Service' account full control permission, this account if for IIS A: When I got this error, it may have been because of my UPDATE syntax being wrong, but after I fixed the update query I got the same error again...so I went to the ODBC Data Source Administrator and found that my connection was read-only. After I made the connection read-write and re-connected it worked just fine. A: Today in my MS-Access 2003 with an ODBC tabla pointing to a SQL Server 2000 with sa password gave me the same error. I defined a Primary Key on the table in the SQL Server database, and the issue was gone. A: There is another scenario here that would apply. A file that was checked out of Visual Source Safe, for anyone still using it, that was not given "Writeablity", either in the View option or Check Out, will also recieve this error message. Solution is to re-acquire the file from Source Safe and apply the Writeability setting. A: To further answer what DRUA referred to in his/her answer... I develop my databases in Access 2007. My users are using access 2007 runtime. They have read permissions to a database_Front (front end) folder, and read/write permissions to the database_Back folder. In rolling out a new database, the user did not follow the full instructions of copying the front end to their computer, and instead created a shortcut. Running the Front-end through the shortcut will create a condition where the query is not updateable because of the file write restrictions. Copying the front end to their documents folder solves the problem. Yes, it complicates things when the users have to get an updated version of the front-end, but at least the query works without having to resort to temp tables and such. A: check your DB (Database permission) and give full permission Go to DB folder-> right click properties->security->edit-> give full control & Start menu ->run->type "uac" make it down (if it high) A: The answer given above by iDevlop worked for me. Note that I wasn't able to find the RecordsetType property in my update query. However, I was able to find that property by changing my query to a select query, setting that property as iDevlop noted and then changing my query to an update query. This worked, no need for a temp table. I'd have liked for this to just be a comment to what iDevlop posted so that it flowed from his solution, but I don't have a high enough score. A: I solved this by adding "DISTINCTROW" so here this would be UPDATE DISTINCTROW CLOG SET CLOG.NEXTDUE
{ "language": "en", "url": "https://stackoverflow.com/questions/170578", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: Is the C# 2.0 to C# 3.0 transition worth it for this project? I have read on Stack Overflow some people that have converting to C#2.0 to C#3, but is it really worth it? I have a project that is done at 75% before going in maintenance phase. I am asking to myself if it is worth it to switch to C#3.0? Update: The project will have a web interface now so before entering the maintenance phase we have to develop the web part (all was done for internal purposes with Windows Forms). Most parts will be resused (back-end). Most people have said that it wasn't worth it in the past because it was already at 75%... but now do you still think it's not worth it? What have been done finally Finally since we are continuing the project with the web interface we will update to 3.5 for the new year. Thank you everybody for all your input. A: I think a lot of this will come down to your personal style. IMHO, the best features of C# 3.5 really come down to the following * *Lambda Expressions *LINQ *Extension Methods My OO code still tends to look a bit functional oriented. Therefore I see 3.5 as a huge benefit and it's definately worth the upgrade. What's even better is it's possible to use the 3.5 compiler to down target CLR 2.0. This allows you to deploy based on a 2.0 install (vs a 3.0/3.5 install) using the new framework. All of the above can be done in this scenario if you're willing to add the appropriate types into your program. A: Clarification C# 3.5 doesn't exist. There is C#1.0, C#2.0 and C#3.0. Then there is .NET 1.0, .NET 1.1, .NET 2.0, .NET 3.0, and .NET 3.5. We should not confuse the two. C# 3.0 vs C#2.0 Now, is C#3.0 worth the move? I would say that with the existence of Extension methods and Lambda expressions, the answer is yes. These two features alone make for easier to read and quicker to write code. Add that to auto-implemented properties, LINQ, and partial methods, and C#3.0 shows itself to be an advantageous move. However, it is not necessarily beneficial to move an existing project. You have to weigh the pros and the cons, especially with regards to introducing new bugs and instability, before deciding to migrate existing work. For new projects, I'd say start with C#3.0. A: In my opinion, there's no good reason not to switch to 3.5. The real killer feature is that you can continue to target older versions of the runtime (2.0+) while using all the new language features. So you can use the new lambda expressions, extension methods, anonymous types, and all the other good stuff. And if your customers are still primarily using the 2.0 framework, you can continue targeting the earlier runtime. (Just don't use any of the classes from the 3.5 framework, if you have to target earlier runtime versions.) Personally, I think if you're doing a desktop GUI app, your best bet is to use the 3.0 or 3.5 framework, since WPF is the best user interface library I've ever worked with (by a long shot). On the other hand, if you've already written most of your GUI in WinForms, then you might be interested in the 3.5 framework, which allows (limited) intermingling of WinForms and WPF GUI elements. You can keep the work you've already done, but add a few nice touches here and there, wherever it makes sense, with WPF controls. Another handy feature of the 3.5 framework is "Collection Initializers". Check this out: var myDictionary = new Dictionary<String, String> { { "key-1", "value-1" }, { "key-2", "value-2" }, { "key-3", "value-3" }, }; Neat, huh? I'd have liked it a little better if it was a little more JSON-like. But it's very convenient functionality anyhow. Any you can event target that code for the 2.0 runtime! A: No, I would advise not. I would advise starting 3.5 on new projects only, unless there is a specific reason otherwise. You will not have any benefit from 3.5 by just recompiling, since your code is already written (or at least 75% of it). If you need to migrate to 3.5 in the future, you can easily do it. Of course, you will have code in 2.0 style, but what is done is done. * *Be conservative, don't do something unless you need it. *An application which is 75% in C#2.0 and 25% in C#3.0 is not exactly a nice beast to maintain. A 100% C#2.0 application is certainly more maintainable. When you are going to start a new project, then by all means switch! The new framework version is very interesting and the switch is hotly recommended. A: If your project is nearly complete, you will probably not benefit from the new features of 3.5. For new projects, it is certainly worth a look. A: It really depends on the project, who it's intended for, and what it does. It would be safe to guess that the .NET Framework 2.0 is on many more computers than version 3.5. Additionally, is there anything you need from .NET 3.5 that isn't available in 2.0 (such as LINQ)? If you are dealing with a lot of queries and data, I would switch. But again, depends on the customer and if you intended to maintain this application for the foreseeable future. A: From a technology standpoint, it's all framework version 2 and it's very little effort to achieve. The differences in 2.0, 3.0 and 3.5 are just additional library code and some compiler syntactic sugar. It's not like you need to change anything over; by targeting framework 3.5 you have more options. From your teams point of view: Yes it's worth it. Nobody wants to work on old code-bases. While you're in the heat of development, you might as well utilize the most current stable technology. A: It really depends on what you need to do. If your project requires Lambda Expressions where you're query objects with a clear syntax, you should look at 3.0. I am currently reading C# In Depth by Jon Skeet, and he takes the approach of laying out a solution in C# 1.15, then evolves the solution to depict the new and useful functionality that you get in 2.0 and 3.0. This type of progression would be a perfect means to answer your questions. The book reads well too so I am finding I am getting through it quickly. A: You have to weigh cost versus benefit. You don't provide enough information about your project to allow us to advice you here, but consider: * *cost of conversion is pretty small. C# 3.0 is almost completely backwardly compatible with 2.0 and run on framework 2.0 *benefit is also pretty small if the coding is almost finished, but might grow in the long run. A new feature you might have to implement in the future might turn out to be much easier implemented using Linq, for example. A: I've made the conversion many times. Mostly because the clear syntax from lambda expressions makes the code easier to follow (for me anyway). I do use ReSharper which makes using new 3.5 features a snap as quite a few show up as refactoring suggestions by ReSharper. Using a tool like that makes this transition so much easier. A: Is there any C# 3.5 feature you want badly at this stage? :) If it is LINQ, you can give LINQBridge a try.. With Studio's multi-targeting and LINQBridge, you'll be able to write local (LINQ to Objects) queries using the full power of the C# 3.0 compiler—and yet your programs will require only Framework 2.0. A: 3.5 builds on top of 2.0, so you have no issues jumping directly to 3.5. A: I would... there's no harm and you get some benefits from the new features A: I don't understand all you people saying don't do it. .NET 2.0 is the current (CLR) runtime. .NET 3.0 and .NET 3.5 both run on the 2.0 runtime. Moving to .NET 3.5 to get the C# 3.0 features is literally a matter of changing a single dropdown in your project properties. (OK, and deploying the 3.5 runtime to your target machines if you use some 3.5 features such as LINQ, etc. If installing 3.5 is an issue then it's not such an easy answer.) A: I wouldn't change anything unless you have a good reason to do so; i.e. there is a bug that you can't work-around in 2.0. Upgrading the framework at such a late point in the project is likely to cause some problems which you really don't need at the moment. A: If you have an extension to the project, it might be a good thing to switch now to the newest version of .NET, otherwise I wouldn't.
{ "language": "en", "url": "https://stackoverflow.com/questions/170584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: UNIX socket implementation for Java? I realize that since UNIX sockets are platform-specific, there has to be some non-Java code involved. Specifically, we're interested in using JDBC to connect to a MySQL instance which only has UNIX domain sockets enabled. It doesn't look like this is supported, but from what I've read it should be at least possible to write a SocketFactory for JDBC based on UNIX sockets if we can find a decent implementation of UNIX sockets for Java. Has anyone tried this? Does anyone know of such an implementation? A: As of Java 16, Unix domain sockets are supported natively by java through SocketChannel and ServerSocketChannel API. You can find more information about it in JEP380 proposal and implementation example here. A: The MariaDB JDBC driver now supports this and is compatible with the MySQL JDBC driver. Use a JDBC url like: jdbc:mariadb://localhost:3306/revmgt?localSocket=/var/run/mysqld/mysqld.sock Worth noting that this library require including the JNA library as it uses JNA to access native unix domain sockets. It works pretty well in my testing. I saw speed improvements on CPU bound java processes from the offload to native code. A: Checkout the JUDS library. It is a Java Unix Domain Socket library... https://github.com/mcfunley/juds A: Check out the JNA library. It's a halfway house between pure Java and JNI native code https://github.com/twall/jna/ A: You could use junixsocket: https://github.com/kohlschutter/junixsocket It already provides code for connecting to MySQL from Java (Connector/J) via Unix sockets. One big advantage compared to other implementations is that junixsocket uses the standard Java Socket API. A: The JNR project (which is a loose basis for project panama) has a unix socket implementation. A: no one has yet mentioned: https://github.com/sbt/ipcsocket has worked for me A: Some searching on the internet has uncovered the following useful-looking library: http://www.nfrese.net/software/gnu_net_local/overview.html Wayback Link Writing a socket factory should be easy enough. Once you've done so, you can pass it to your driver THUSLY.(Wayback Link). import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import com.mysql.management.driverlaunched.ServerLauncherSocketFactory; public class ConnectorMXJTestExample { public static void main(String[] args) throws Exception { String hostColonPort = "localhost:3336"; String driver = com.mysql.jdbc.Driver.class.getName(); String url = "jdbc:mysql://" + hostColonPort + "/" + "?" + "socketFactory=" + ServerLauncherSocketFactory.class.getName(); String userName = "root"; String password = ""; Class.forName(driver); Connection conn = null; try { conn = DriverManager.getConnection(url, userName, password); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT VERSION()"); rs.next(); String version = rs.getString(1); rs.close(); stmt.close(); System.out.println("------------------------"); System.out.println(version); System.out.println("------------------------"); } finally { try { conn.close(); } catch (Exception e) { e.printStackTrace(); } ServerLauncherSocketFactory.shutdown(hostColonPort); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/170600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "51" }
Q: Objective-C Tidy I have a somewhat messily-formatted Objective-C code base. Is there a way to have Xcode reformat an entire project to conform to a coding standard (i.e., properly indent, spaces v. tabs, etc.)? Are there other tools that might accomplish this? A: A simple, but limited, solution is Edit->Format->Re-Indent in Xcode, which will apply your current indentation settings (Xcode->Preferences…->Indentation). A: According to this blog post, bcpp works with Objective-C. In addition, the tool indent might help you. It's aimed at plain C but has a gazillion options that could help. I don't know if it comes by default on OS X though. NAME indent - changes the appearance of a C program by inserting or deleting whitespace. SYNOPSIS indent [options] [input-files] indent [options] [single-input-file] [-o output-file] indent --version DESCRIPTION This man page is generated from the file indent.texinfo. This is Ediâ tion of "The indent Manual", for Indent Version , last updated . The indent program can be used to make code easier to read. It can also convert from one style of writing C to another. indent understands a substantial amount about the syntax of C, but it also attempts to cope with incomplete and misformed syntax. A: From Xcode: 1) Change the Indentation preferences to match what you want. 2) Select a file to work on and Select All (cmd-A) 3) Shift Left (cmd-[) several times until all lines are at the left edge of the window. 4) Use Re-Indent Selection (from Edit->Format-> or from the right-click contextual menu) Only works on one file at a time, not the whole project. Also only deals with indentation. A: Uncrustify: http://uncrustify.sourceforge.net/ Source Code Beautifier for C, C++, C#, ObjectiveC, D, Java, Pawn and VALA If you want something simpler, you could probably get some way by simply stripping out all the white-space/line-breaks, and adding a new line-break on ; { }, and manually re-indenting the code. It won't be anywhere near perfectly laid out code, and reindenting could be a pain on large code, but it will be consistent. A: After tinkering with multiple external formatters and the weak internal xcode formatter, I finally settled with uncrustify. Uncrustify has fairly good Objective-C support, can easily be integrated with xcode as a user script, and provides a centralized formatter for pretty much all languages that xcode natively supports. The biggest hurdle with uncrustify is the daunting configuration file. My recommendation, take one of the supplied sample configs (ben2.cfg is very good), merge in the objc.cfg sample, and tweak as necessary. A: One way to go that uses uncrustify in a different context is http://universalindent.sourceforge.net/ A: The sole feature of the "GTMXcodePlugin", aka Google Toolbox For Mac Xcode Plugin - does a great job of tidying objective-c code, by effectively, and safely trimming whitespaces. The GTM Xcode 4 plugin currently only adds a "Clean Up Whitespace" menu item to the end of the "Edit" menu to remove unnecessary end of line white space from text files. Hopefully we will add more features soon. It has only been tested against Xcode 4.2. A: The newest, bestest way of doing this, as of this writing, is SpaceCommander. It's based on top of clang, and has lots of other neat features, and is maintained and active as of this writing.
{ "language": "en", "url": "https://stackoverflow.com/questions/170601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: What are the best-practices around resource list authorization? Publishing and/or collaborative applications often involve the sharing of access to resources. In a portal a user may be granted access to certain content as a member of a group or because of explicit access. The complete set of content could include public content, group membership content, and private user content. Or, with collaborative applications, we may want to pass along resources as part of a workflow or share custody of a document for editing purposes. Since most applications store these resources in a database you typically create queries like 'Get all the documents that I can edit' or 'Get all the content I can see'. Where 'can edit' and 'can see' are the user's privileges. I have two questions: * *It's quite easy to authorize the user once you've retrieved a resource, but how do you efficiently perform authorization on the list of available resources? And, *Can this kind of authorization be separated from the core of the application? Perhaps into a separate service? Once separated, how could you filter queries like 'Get me all the documents I can see with title like [SomeSearchTerm]'? It seems to me your separate system would have to copy over a lot of reference data. A: You may be interested in reading this article by Steffen Bartsch. It summarizes all authorization plugins for Ruby on Rails, and I am sure it will help you find your solution (although this article is about Rails plugins, the concepts are easily exportable outside Rails). Steffen also built his own plugin, called "Declarative Authorization" which seems to match your needs, IMHO: * *on the one hand, you define roles (such as "visitor", "admin"...). Your users are associated to these roles (in a many-to-many relationship). You map these roles to privileges (again in a many-to-many relationship). Each privilege is linked to a given context. For example, the role "visitor" may have privilege "read documents". In this example, "read" is the privilege, and it is applied to the "documents" context. * *Note: in Steffen's plugin, you can define a hierarchy of roles. For example you might want to have the "global_admin" role include the "document_admin" role, as well as the "comment_admin" role, etc. *You can also defines hierarchies of privileges: for example, the "manage" privilege could include the "read", "update", "add" and "delete" privileges. *on the other hand, you code your application thinking in terms of privileges and contexts, not in terms of roles. For example, the action to display a document should only check whether the user has the privilege to "read" in the "documents" context (no need to check whether the user has the "visitor" role or any other role). This greatly simplifies your code, since most of the authorization logic is extracted elsewhere (and perhaps even defined by someone else). This separation between the definition of the user roles and the definition of the application-level privileges guarantees that your code will not change every time you define a new role. For example, here is how simple the access-control would look like in a controller : class DocumentController [...] filter_access_to :display, :require => :read def display ... end end And inside a view: <html> [...] <% permitted_to?(:create, :documents) do %> <%= link_to 'New', new_document_path %> <% end %> </html> Steffen's plugin also allows for object-level (ie. row-level) access-control. For example, you might want to define a role such as "document_author" and give it "manage" privilege on "documents", but only if the user is the author of the document. The declaration of this rule would probably look like this: role :document_author do has_permission.on :documents do to :manage if_attribute :author => is {user} end end That's all there is to it! You can now get all the documents that the user is allowed to update like this: Document.with_permissions_to(:update) Since the "manage" privilege includes the "update" privilege, this will return the list of documents whose author is the current user. Of course, not every application will need this level of flexibility... but yours might. A: I generally have a schema like this Users −−∈ UserDocuments ∋−− Documents Then I create a view "ProfiledDocuments" SELECT <fields> FROM Documents d INNER JOIN UserDocuments ud on ud.DocumentId = d.Id INNER JOIN Users u ON u.Id = ud.UserId Then run the search queries on ProfiledDocuments always using a UserId filter. With appropriate indexes it works well enough. If you need more complex permissions, you can do it with an extra field in the UserDocuments many to many table which specifies the kind of permission. A: Though your question is quite elaborated, there is actually some missing context. What defines the documents a user has privileges for? Can a user only edit his "own" files? Is there a role-based mechanism here? Is it more MAC-oriented (i.e. a user can see a level of security)? Is there a defining attribute to the data (e.g. department)? All these questions together may give a better picture, and allow a more specific answer. If documents are "owned" by a specific user, its pretty straightforward - have an "owner" field for the document. Then, query for all documents owned by the user. Similarly, if you can pre-define the list of named users (or roles) that have access, you can query for a joined list between the documents, the list of authorized users/roles, and the user (or his roles). If a user gets permissions according to his department (or other similar document's attribute), you can query on that. Similarly, you can query for all documents with a level of security equal or lower to that of the user's privileges. If this is dynamic workflow, each document should typically be marked with its current state, and/or next expected step; which users can perform that next step is simply another privilege/role (treat the same as above). Then, of course, you'll want to do a UNION ALL between all those and public documents... Btw, if I have not made it clear, this is not a simple issue - do yourself a favor and find pre-built infrastructure to do it for you. Even at the cost of simplifying your authorization schemata.
{ "language": "en", "url": "https://stackoverflow.com/questions/170606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How do I compile to x64 binary from a x86 platform running VS2008 Pro? I am trying to compile my apps (which uses 3rd party libraries) for the x64 platform. However selecting x64 from Build Configuration Manager from my VS2008 Pro doesn't seem to work. The binary does get created but my client wasn't able to get it to run on x64. I wonder if the 3rd party DLLs could be the cause. Anyone has any idea on this? A: Do you have x64 versions of the third party libraries? If not you are out of luck. A process must either be fully x86 or x64, you can't mix and match libraries. If the libraries are DLLs then you still need the export libraries from an x64 build. In what way does selecting the x64 configuration in VS not work? Updated: If your app is .NET and architecture neutral, then it will be loaded as 64 bit on 64 bit OS'es. However, if it relies on 32 bit DLLs then this will fail at run time. You can force your exe to always load 32 bit using the corflags utility. A: As Rob Walker said. You can find out more by using the "depends" program by SysInternals on an x64 machine. A: Managed to pinpoint the source of the problem. It was one of the setting (Encrypt IL Code) in the source code obfuscating tool (Intellilock 1.1.0.4) that made the binary failed to run in x64 environment. Disabling this setting fixed the issue. A: "selecting x64 from Build Configuration Manager from my VS2008 Pro doesn't seem to work" I'm not sure why you would be getting binaries at all but remember that the x64 tools are not installed by default. Go back and re-run your VC2008 installer, do a custom install, and, under the VC++ bit of the tree, make sure the checkbox for the 64-bit compiler is checked. If it is not, check it and run the install. Then try your build. You do need the 64-bit versions of the 3rd party dlls and you do need to get all your include and lib paths right and your output folders straight, but having the tool installed is the first step. A: My application does not has an installer. I created it in as a "portable app" with .NET2.0 as a pre-requisite. I have posted the same request to the vendor. Still awaiting for them to revert if they have the x64 bit. In the meantime I am in the process to purchase a copy of x64 Vista to personally test it out. I can't be sacrificing my users to test this out for me. I will keep this thread posted once I have new updates. Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/170616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I find the install time and date of Windows? This might sound like a little bit of a crazy question, but how can I find out (hopefully via an API/registry key) the install time and date of Windows? The best I can come up with so far is to look at various files in C:\Windows and try to guess... but that's not exactly a nice solution. A: In regedit.exe go to: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\InstallDate It's given as the number of seconds since January 1, 1970. (Note: for Windows 10, this date will be when the last feature update was installed, not the original install date.) To convert that number into a readable date/time just paste the decimal value in the field "UNIX TimeStamp:" of this Unix Time Conversion online tool. A: Windows 10 OS has yet another registry subkey, this one in the SYSTEM hive file: Computer\HKEY_LOCAL_MACHINE\SYSTEM\Setup\ The Install Date information here is the original computer OS install date/time. It also tells you when the update started, ie Computer\HKEY_LOCAL_MACHINE\SYSTEM\Setup\Source OS (Updated on xxxxxx)." This may of course not be when the update ends, the user may choose to turn off instead of rebooting when prompted, etc... The update can actually complete on a different day, and Computer\HKEY_LOCAL_MACHINE\SYSTEM\Setup\Source OS (Updated on xxxxxx)" will reflect the date/time it started the update. A: We have enough answers here but I want to put my 5 cents. I have Windows 10 installed on 10/30/2015 and Creators Update installed on 04/14/2017 on top of my previous installation. All of the methods described in the answers before mine gives me the date of the Creators Update installation. I've managed to find few files` date of creation which matches the real (clean) installation date of my Windows 10: * *in C:\Windows * *in C:\ By the way, an easy way to get the 10 oldest (by creation) files in C:\ and C:\windows is to run these 2 commands on an administrative powershell session: dir -Force C:\ | sort -Property creationtime | select -Property name, creationtime -First 10 dir -Force C:\windows | sort -Property creationtime | select -Property name, creationtime -First 10 A: I find the creation date of c:\pagefile.sys can be pretty reliable in most cases. It can easily be obtained using this command (assuming Windows is installed on C:): dir /as /t:c c:\pagefile.sys The '/as' specifies 'system files', otherwise it will not be found. The '/t:c' sets the time field to display 'creation'. A: Open command prompt, type "systeminfo" and press enter. Your system may take few mins to get the information. In the result page you will find an entry as "System Installation Date". That is the date of windows installation. This process works in XP ,Win7 and also on win8. A: HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\InstallDate and systeminfo.exe produces the wrong date. The definition of UNIX timestamp is timezone independent. The UNIX timestamp is defined as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970 and not counting leap seconds. In other words, if you have installed you computer in Seattle, WA and moved to New York,NY the HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\InstallDate will not reflect this. It's the wrong date, it doesn't store timezone where the computer was initially installed. The effect of this is, if you change the timezone while running this program, the date will be wrong. You have to re-run the executable, in order for it to account for the timezone change. But you can get the timezone info from the WMI Win32_Registry class. InstallDate is in the UTC format (yyyymmddHHMMSS.xxxxxx±UUU) as per Microsoft TechNet article "Working with Dates and Times using WMI" where notably xxxxxx is milliseconds and ±UUU is number of minutes different from Greenwich Mean Time. private static string RegistryInstallDate() { DateTime InstallDate = new DateTime(1970, 1, 1, 0, 0, 0); //NOT a unix timestamp 99% of online solutions incorrect identify this as!!!! ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Registry"); foreach (ManagementObject wmi_Windows in searcher.Get()) { try { ///CultureInfo ci = CultureInfo.InvariantCulture; string installdate = wmi_Windows["InstallDate"].ToString(); //InstallDate is in the UTC format (yyyymmddHHMMSS.xxxxxx±UUU) where critically // // xxxxxx is milliseconds and // ±UUU is number of minutes different from Greenwich Mean Time. if (installdate.Length==25) { string yyyymmddHHMMSS = installdate.Split('.')[0]; string xxxxxxsUUU = installdate.Split('.')[1]; //±=s for sign int year = int.Parse(yyyymmddHHMMSS.Substring(0, 4)); int month = int.Parse(yyyymmddHHMMSS.Substring(4, 2)); int date = int.Parse(yyyymmddHHMMSS.Substring(4 + 2, 2)); int hour = int.Parse(yyyymmddHHMMSS.Substring(4 + 2 + 2, 2)); int mins = int.Parse(yyyymmddHHMMSS.Substring(4 + 2 + 2 + 2, 2)); int secs = int.Parse(yyyymmddHHMMSS.Substring(4 + 2 + 2 + 2 + 2, 2)); int msecs = int.Parse(xxxxxxsUUU.Substring(0, 6)); double UTCoffsetinMins = double.Parse(xxxxxxsUUU.Substring(6, 4)); TimeSpan UTCoffset = TimeSpan.FromMinutes(UTCoffsetinMins); InstallDate = new DateTime(year, month, date, hour, mins, secs, msecs) + UTCoffset; } break; } catch (Exception) { InstallDate = DateTime.Now; } } return String.Format("{0:ddd d-MMM-yyyy h:mm:ss tt}", InstallDate); } A: How to find out Windows 7 installation date/time: just see this... * *start > enter CMD *enter systeminfo that's it; then you can see all information about your machine; very simple method A: Determine the Windows Installation Date with WMIC wmic os get installdate A: Very simple way from PowerShell: (Get-CimInstance -Class Win32_OperatingSystem).InstallDate Extracted from: https://www.sysadmit.com/2019/10/windows-cuando-fue-instalado.html A: TLDR IMPORTANT NOTE if Windows was "installed" using a disk image both methods fail. Method 1 works if windows haven't been upgraded to a new major version (e.g. Windows 10 to Windows 11). You execute the command systeminfo and look for a line beginning with "Original Install Date" (or something like that in your local language). You can get the same version by querying WMI and by looking at the registry. if windows was upgraded to a new major version this method unfortunately gives you the date of installation of the new major version. Here's an example to check the version by running systeminfo from PowerShell: systeminfo | sls "original" Method 2 This seems to work correctly even after a major update. You get the installation date by checking the creation time of the file system.ini which seems to stay untouched. e.g. with PowerShell: (Get-Item "C:\Windows\system.ini").CreationTime Details Another question eligible for a 'code-challenge': here are some source code executables to answer the problem, but they are not complete. Will you find a VBScript that anyone can execute on his/her computer, with the expected result? systeminfo|find /i "original" would give you the actual date... not the number of seconds ;) But (caveat), as noted in the 2021 comments by Salman A and AutoMattTick If Windows was updated to a newer version, this seems to give the date on which Windows was RE-installed. As Sammy comments, find /i "install" gives more than you need. And this only works if the locale is English: It needs to match the language. For Swedish this would be "ursprungligt" and "ursprüngliches" for German. Andy Gauge proposes in the comments: shave 5 characters off with systeminfo|find "Original" In Windows PowerShell script, you could just type: PS > $os = get-wmiobject win32_operatingsystem PS > $os.ConvertToDateTime($os.InstallDate) -f "MM/dd/yyyy" By using WMI (Windows Management Instrumentation) If you do not use WMI, you must read then convert the registry value: PS > $path = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' PS > $id = get-itemproperty -path $path -name InstallDate PS > $d = get-date -year 1970 -month 1 -day 1 -hour 0 -minute 0 -second 0 ## add to hours (GMT offset) ## to get the timezone offset programatically: ## get-date -f zz PS > ($d.AddSeconds($id.InstallDate)).ToLocalTime().AddHours((get-date -f zz)) -f "MM/dd/yyyy" The rest of this post gives you other ways to access that same information. Pick your poison ;) In VB.Net that would give something like: Dim dtmInstallDate As DateTime Dim oSearcher As New ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem") For Each oMgmtObj As ManagementObject In oSearcher.Get dtmInstallDate = ManagementDateTimeConverter.ToDateTime(CStr(oMgmtO bj("InstallDate"))) Next In Autoit (a Windows scripting language), that would be: ;Windows Install Date ; $readreg = RegRead("HKLM\SOFTWARE\MICROSOFT\WINDOWS NT\CURRENTVERSION\", "InstallDate") $sNewDate = _DateAdd( 's',$readreg, "1970/01/01 00:00:00") MsgBox( 4096, "", "Date: " & $sNewDate ) Exit In Delphy 7, that would go as: Function GetInstallDate: String; Var di: longint; buf: Array [ 0..3 ] Of byte; Begin Result := 'Unknown'; With TRegistry.Create Do Begin RootKey := HKEY_LOCAL_MACHINE; LazyWrite := True; OpenKey ( '\SOFTWARE\Microsoft\Windows NT\CurrentVersion', False ); di := readbinarydata ( 'InstallDate', buf, sizeof ( buf ) ); // Result := DateTimeToStr ( FileDateToDateTime ( buf [ 0 ] + buf [ 1 ] * 256 + buf [ 2 ] * 65535 + buf [ 3 ] * 16777216 ) ); showMessage(inttostr(di)); Free; End; End; As an alternative, CoastN proposes in the comments: As the system.ini-file stays untouched in a typical windows deployment, you can actually get the install-date by using the following oneliner: (PowerShell): (Get-Item "C:\Windows\system.ini").CreationTime A: Ever wanted to find out your PC’s operating system installation date? Here is a quick and easy way to find out the date and time at which your PC operating system installed(or last upgraded). Open the command prompt (start-> run -> type cmd-> hit enter) and run the following command systeminfo | find /i "install date" In couple of seconds you will see the installation date A: In Powershell run the command: systeminfo | Select-String "Install Date:" A: Use speccy. It shows the installation date in Operating System section. http://www.piriform.com/speccy A: You can also check the check any folder in the system drive like "windows" and "program files". Right click the folder, click on the properties and check under the general tab the date when the folder was created. A: In RunCommand write "MSINFO32" and hit enter It will show All information related to system A: You can simply check the creation date of Windows Folder (right click on it and check properties) :) A: Try this powershell command: Get-ChildItem -Path HKLM:\System\Setup\Source* | ForEach-Object {Get-ItemProperty -Path Registry::$_} | Select-Object ProductName, ReleaseID, CurrentBuild, @{n="Install Date"; e={([DateTime]'1/1/1970').AddSeconds($_.InstallDate)}} | Sort-Object "Install Date" A: After trying a variety of methods, I figured that the NTFS volume creation time of the system volume is probably the best proxy. While there are tools to check this (see this link ) I wanted a method without an additional utility. I settled on the creation date of "C:\System Volume Information" and it seemed to check out in various cases. One-line of PowerShell to get it is: ([DateTime](Get-Item -Force 'C:\System Volume Information\').CreationTime).ToString('MM/dd/yyyy') A: Press WindowsKey + R and enter cmd In the command window type: systeminfo | find /i "Original" (for older versions of windows, type "ORIGINAL" in all capital letters). A: You can do this with PowerShell: Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\' -Name InstallDate | Select-Object -Property @{n='InstallDate';e={[DateTime]::new(1970,1,1,0,0,0,0,'UTC').AddSeconds($_.InstallDate).ToLocalTime()}}
{ "language": "en", "url": "https://stackoverflow.com/questions/170617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "150" }
Q: Javascript Image Resize Does anyone know how to resize images proportionally using JavaScript? I have tried to modify the DOM by adding attributes height and width on the fly, but seems did not work on IE6. A: I have answered this question here: How to resize images proportionally / keeping the aspect ratio?. I am copying it here because I really think it is a very reliable method :) /** * Conserve aspect ratio of the original region. Useful when shrinking/enlarging * images to fit into a certain area. * * @param {Number} srcWidth width of source image * @param {Number} srcHeight height of source image * @param {Number} maxWidth maximum available width * @param {Number} maxHeight maximum available height * @return {Object} { width, height } */ function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) { var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight); return { width: srcWidth*ratio, height: srcHeight*ratio }; } A: To modify an image proportionally, simply only alter one of the width/height css properties, leave the other set to auto. image.style.width = '50%' image.style.height = 'auto' This will ensure that its aspect ratio remains the same. Bear in mind that browsers tend to suck at resizing images nicely - you'll probably find that your resized image looks horrible. A: Instead of modifying the height and width attributes of the image, try modifying the CSS height and width. myimg = document.getElementById('myimg'); myimg.style.height = "50px"; myimg.style.width = "50px"; One common "gotcha" is that the height and width styles are strings that include a unit, like "px" in the example above. Edit - I think that setting the height and width directly instead of using style.height and style.width should work. It would also have the advantage of already having the original dimensions. Can you post a bit of your code? Are you sure you're in standards mode instead of quirks mode? This should work: myimg = document.getElementById('myimg'); myimg.height = myimg.height * 2; myimg.width = myimg.width * 2; A: Tried the following code, worked OK on IE6 on WinXP Pro SP3. function Resize(imgId) { var img = document.getElementById(imgId); var w = img.width, h = img.height; w /= 2; h /= 2; img.width = w; img.height = h; } Also OK in FF3 and Opera 9.26. A: Example: How To resize with a percent <head> <script type="text/javascript"> var CreateNewImage = function (url, value) { var img = new Image; img.src = url; img.width = img.width * (1 + (value / 100)); img.height = img.height * (1 + (value / 100)); var container = document.getElementById ("container"); container.appendChild (img); } </script> </head> <body> <button onclick="CreateNewImage ('http://www.medellin.gov.co/transito/images_jq/imagen5.jpg', 40);">Zoom +40%</button> <button onclick="CreateNewImage ('http://www.medellin.gov.co/transito/images_jq/imagen5.jpg', 60);">Zoom +50%</button> <div id="container"></div> </body> A: This works for all cases. function resizeImg(imgId) { var img = document.getElementById(imgId); var $img = $(img); var maxWidth = 110; var maxHeight = 100; var width = img.width; var height = img.height; var aspectW = width / maxWidth; var aspectH = height / maxHeight; if (aspectW > 1 || aspectH > 1) { if (aspectW > aspectH) { $img.width(maxWidth); $img.height(height / aspectW); } else { $img.height(maxHeight); $img.width(width / aspectH); } } } A: You don't have to do it with Javascript. You can just create a CSS class and apply it to your tag. .preview_image{ width: 300px; height: auto; border: 0px; } A: okay it solved, here is my final code if($(this).width() > $(this).height()) { $(this).css('width',MaxPreviewDimension+'px'); $(this).css('height','auto'); } else { $(this).css('height',MaxPreviewDimension+'px'); $(this).css('width','auto'); } Thanks guys A: Use JQuery var scale=0.5; minWidth=50; minHeight=100; if($("#id img").width()*scale>minWidth && $("#id img").height()*scale >minHeight) { $("#id img").width($("#id img").width()*scale); $("#id img").height($("#id img").height()*scale); } A: Try this.. <html> <body> <head> <script type="text/javascript"> function splitString() { var myDimen=document.getElementById("dimen").value; var splitDimen = myDimen.split("*"); document.getElementById("myImage").width=splitDimen[0]; document.getElementById("myImage").height=splitDimen[1]; } </script> </head> <h2>Norwegian Mountain Trip</h2> <img border="0" id="myImage" src="..." alt="Pulpit rock" width="304" height="228" /><br> <input type="text" id="dimen" name="dimension" /> <input type="submit" value="Submit" Onclick ="splitString()"/> </body> </html> In the text box give the dimension as ur wish, in the format 50*60. Click submit. You will get the resized image. Give your image path in place of dots in the image tag. A: function resize_image(image, w, h) { if (typeof(image) != 'object') image = document.getElementById(image); if (w == null || w == undefined) w = (h / image.clientHeight) * image.clientWidth; if (h == null || h == undefined) h = (w / image.clientWidth) * image.clientHeight; image.style['height'] = h + 'px'; image.style['width'] = w + 'px'; return; } just pass it either an img DOM element, or the id of an image element, and the new width and height. or you can pass it either just the width or just the height (if just the height, then pass the width as null or undefined) and it will resize keeping aspect ratio A: to resize image in javascript: $(window).load(function() { mitad();doble(); }); function mitad(){ imag0.width=imag0.width/2; imag0.height=imag0.height/2; } function doble(){ imag0.width=imag0.width*2; imag0.height=imag0.height*2;} imag0 is the name of the image: <img src="xxx.jpg" name="imag0"> A: Here is my cover fill solution (similar to background-size: cover, but it supports old IE browser) <div class="imgContainer" style="height:100px; width:500px; overflow:hidden; background-color: black"> <img src="http://dev.isaacsonwebdevelopment.com/sites/development/files/views-slideshow-settings-jquery-cycle-custom-options-message.png" id="imgCat"> </div> <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js"></script> <script> $(window).load(function() { var heightRate =$("#imgCat").height() / $("#imgCat").parent(".imgContainer").height(); var widthRate = $("#imgCat").width() / $("#imgCat").parent(".imgContainer").width(); if (window.console) { console.log($("#imgCat").height()); console.log(heightRate); console.log(widthRate); console.log(heightRate > widthRate); } if (heightRate <= widthRate) { $("#imgCat").height($("#imgCat").parent(".imgContainer").height()); } else { $("#imgCat").width($("#imgCat").parent(".imgContainer").width()); } }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/170624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "50" }
Q: Eclipse plugin manifest problem - empty package inconsistency between mac and PC I am developing a collection of plugins on Eclipse 3.4 (official) on both mac and a PC. At present (I'm aware it is not the best practice) some of my common plugins export all of their packages. The problem is this: many of the listed packages are empty because subpackages are not, for example: prefix.core may be empty while prefix.core.model may not be. Even though I use the same manifest file, having the empty packages listed on one platform raises an error in the manifest file on the other platform. If I omit the packages in that platform, then when I come to the other platform I'm told that the plugin does not export everything. Any idea what is going on? I have no idea why there would be differences between the PC and the Mac on a non-UI related issue. The only significant difference is that the mac is running Java 5 (still not Eclipse for Java 6) while the PC is running Java 6, but the manifests should have nothing to do with it. A: It's usually a good practice to use the same version of the JVM if you're developing plugins across multiple machines and platforms. If you are going to build the plugins on a PC and expect them to run on the Mac, you should standardize on Java 5. You can easily install and add additional JREs to Eclipse by going to Window->Preferences->Installed JREs. You can even configure which JRE each project and launch configuration uses, if you don't want the rest of your PC Java coding to use 5. I wouldn't be surprised if this fixes your manifest problem, as well. A: The problem could be the error/warning levels set in the preferences for Plug-In development. It could be that you have different settings in both machines, and that creates the problem. Under Preferences -> Plug-in Development -> Compilers there are several options regarding error and warning levels for different issues, such as references to non-existent resources. Is there any differences that you might see?
{ "language": "en", "url": "https://stackoverflow.com/questions/170635", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why have object oriented databases not been successful (yet)? That's the question. Give only one reason you think why have OODB failed or why many systems nowadays still use relational databases. A: Well, it's strange isn't it? There is such a push towards domain driven design as the zenith of object orientated analysis and design, and there are enterprise patterns out there to leverage ORM systems to persist our objects. It just makes total sense to me that if your application DESIGN is object orientated and domain focussed at heart, that an OODB will greatly benefit your application. Aside from the issues around maturity and uptake, from a philosophical perspective an OODB would appear beneficial or an OO application. not having to maintain that mapping layer for starters;) But look, if you aren't doing domain drive design and use objects as data objects and like your stored procs, then you're not really going to get it;) A: RDBMs are (built on a strong theoretical foundation, have been in the market for a much longer time, can model data more faithfully than OODBs in many cases, can be used by more DBAs than OODBs). That's one reason in the form of a relational tuple. A: If I can amplify Phil's point: the standardization of SQL. OODB's have tried query languages such as OQL but they never seemed to follow a true standard. Also the quality of the query languages were suspect, arguably due to lack of standardization. Standards foster competition, which spawns quality. A: The main reason is SQL. It is very useful to be able to use the data from a database in other contexts outside of the application, and often with object databases the data is stored in a format that can't easily be queried. With a relational database the data can become part of a data warehouse, for instance, or just queried by sys admins etc. A: Can we answer more than once? Another reason is that relational DB's have a strong foundation in mathematics: from the definition of a relation, right through to the normal forms, the theory is rock solid. It is true that the relational model does not map well to OO, but IMHO the benefits and stability of that model outweigh the mapping problem. A: That, and o/r-mappers. Through them, the difference to true OO-DBs becomes way smaller, while the aforementioned benefits stay valid. A: One reason is that databases are about data, and objects are about structures and algorithms. Once you take the data and embed it in classes, you characterize the relationships and operations in a static structure. Databases, on the other hand, are about unstructuring the data into a bunch of instances of atomic tables that can be reassembled into different structures (usually with classes) without disturbing the integrity of the atoms. Databases are somewhat analogous to hexahexaflexagons. A: Expensive technology decisions are not made by people with technical knowledge. Companies using relational databases employ lots of people who feel threatened by OODBs and therefore will avoid learning about them. A: I think it's because "object databases" are solving a problem that (almost)nobody really has. For simple persistence of object graphs, the serialization built into most OO environments is "good enough". If you want to do sophisticated operations on a subset of your data, then a relational database and SQL are a perfect fit. Other than some fringe applications (enormous object graphs that can't be kept in memory, but for which the relationships don't simplify down well for RDBMS use), there really isn't any need for these tools. A: Just because OODB are not the mainstream we should still consider the successes that they have had. Cache and Zope are both widely used (relatively) but would be considered successful by some standards. Perhaps the biggest reason that OODB have not taken hold dramatically is because of the success of the hybrid object-relational systems that take most of the potential marketshare from OODB: PostgreSQL and Informix. I know that this does not directly answer the question but it is, I think, part of the equation. Overall, though, I think that momentum and the heavily ingrained thought processes supporting relation databases make it difficult for people to switch. Currently the DB profession is trained almost exclusively in relational theory making your DB professionals very interested in avoiding OODB and academia teaches DB theory for practitioners almost exclusively on relational. Until large, corporate DBAs and mainstream professors and curriculum and turning out staff beyond developers prepared to managed OODB I feel that it is unlikely to see mass appeal no matter how good it is from the development side. A: I think that there are two philosophical reasons. First, people traditionally tend to separate persistence from real functionality. Once you strip away an object's "life" away from it and keep it primarily for persistence, it becomes a record, and then there is a tendency to treat it as a "lifeless" data object. Following on that, when people think of a large collection of very similar things, they start thinking of them as tables rather than objects. I think with O/R the distinction is starting to disappear. For example, I use hibernate to dump really complex class hierarchies into a MySQL database. However, I don't write performance-critical stuff for my project so I'm sure it's not done efficiently. A: The reason for the slow adoption of OODB's are based largely on a few key factors that make the relational SQL databases more popular and/or more appropriate. While pure object-oriented databases are now in a state where they overcome much of the drawbacks of the relational model, there are some key pieces missing. For one they tend to lack support for central database management, though this is rapidly being rectified in various products. A second reason is that very few systems implement a standard query language and instead relies on the programming language or specialized query languages to retrieve and manipulate the data in store. This is a show stopper for many if they have to learn a new query language on top of the totally different mindset of a programmer used to NoSQL based solutions. On top of that, most SQL based / Relational databases now have some support for Object Oriented Design, plus we have wrappers like ORM that many use to "bypass" the problems of relational databases not being readily available in the programming language of choice. But these problems exist mostly in corporate environments. As embedded databases in small devices, as web site storage and in fields like aerospace they have become very popular and in many cases totally replaced the need for regular relational databases. Who knows what the future holds? A: Serialization provided by the most of Language lets you flaten the Object attributes and thus storing easily them into the RDBMS and similarly retrieving objects is not a big issue. The wide and solid foundation still lacks which hinders the use of OODBMS to be implemented. I currently thinking of doing this as my Master Thesis project to provide a general framework for OODBMS that supports almost all the components which is commonly used in now a day RDBMS thus providing a non-linear structured DBMS. While studying I came across a project called db4o which is an approach (implemented) of using OODBMS for Java and .net only, so this could be another reason of lack of generality for all types of platforms and languages. A: I think that's because big guys like Oracle had been investing in relational databases while object oriented movement was getting momentum...may be they will become mainstream if Oracle / Microsoft invest in it in a big way...which seems unlikely because they don't have a strong reason to do so...it will simplify lives of many programmers...but "making programmers lives simpler" is not a very good business goal for them!
{ "language": "en", "url": "https://stackoverflow.com/questions/170649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Rich Text in Windows Forms application I would like to update a Windows Forms application to provide the following features: * *spell checking *limited formatting of text: bold, italics, bulleted lists Ideally the formatted text could be accessed in a plain text way for reporting through tools that don't support the formatting, but could also be rendered as HTML for tools that support HTML tags when rendering text. It seems to me that the WPF RichTextBox would provide this functionality. What is the best way to incorporate it? Would you suggest other alternatives? A: You can add / create a drop-in spell checker for the Window Forms RichTextBox. A ready to go richtextbox custom control with spell checking. An app for checking spelling that could be easily integrated Also here is a article on adding a WPF RichTextBox to your application, as well as getting spell checking working. (Requires .NET 3.0+) A: I haven't check yet if it will work in a RichTextBox but it should... try the following attached property <TextBox SpellCheck.IsEnabled="True" /> Read more about this here A: Windows Forms has a RichTextBox also. If you're in a Windows Forms application, it will be easier to incorporate that than incorporate the WPF control.
{ "language": "en", "url": "https://stackoverflow.com/questions/170650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Library Error for Ruby/QT Trying to create a QtRuby application, I get the following error: /usr/lib64/ruby/site_ruby/1.8/Qt/qtruby4.rb:2144: [BUG] Segmentation fault ruby 1.8.6 (2008-03-03) [x86_64-linux] I am running a 64-bit version of Novell OpenSUSE 11 with DKE4 and Qt A: The issue is with: require 'Qt' Because of the 64bit libraries, instead you need to use: require 'korundum4' Reference: http://www.sheepguardingllama.com/?p=2661
{ "language": "en", "url": "https://stackoverflow.com/questions/170653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Can I put a caching server in front of my web site? I have a web site using apache httpd as the server and mysql as the backend. It publishes a "thought for the day" that has gotten so popular that the server is crashing due to the number of requests. Since the same page is been requested (the thought only changes once a day), is it possible to put a caching server in front of my main server, so that when the same request is made by different clients, the caching server returns the page without having to go to the database? A: Absolutely. There are many products that will work well for this. Apache itself can be configured to function this way although, if you are on Linux or UNIX, Squid is the better option as it is specifically designed to do this very job. On Windows, MS has always offered cache/proxy products that will do this function. Currently this is ISA Server 2006. Although this is dramatically overkill for this type of application. Squid is my recommendation. A: Yes. You are talking about a reverse proxy (or "http accelerator" which is an imprecise term for the same thing). It can be very efficient, and very many high throughput sites use the technique. The key element to get right is the caching-related HTTP headers. So I strongly recommend reading the HTTP RFC (it can actually be done). If you don't get headers right, you can have little effect, or maybe even security problems (if personalized pages are cached and presented to the wrong people). Also: You may have to split up your page into parts, to gain best caching effect. Example: If you insist of having a clock in a corner of your pages showing current server time down to the second, then the whole page becomes cacheable for only a second. So 1) drop the stupid clock, or 2) have it be generated by a client-side script - or 3) have the client side script pull that particular part of the page from a special URL which then only outputs a small ever-changing, non-cacheable HTML fragment. I've once used Squid as a reverse proxy for a large web site. Nowadays, if I were to do it again, I'd try out Varnish. A: I would definitely recommend Javier's solution, which is the simplest, most robust, and easiest to maintain. Just don't forget to send the proper Expires header 24 hours into the future and set ETags properly. A: For slow changing pages, a cache will definitely reduce CPU usage; but in your extreme case, where the page changes once a day, and it's perfectly predictable, it would be far easier to use a simple and fast static file server (lighthttp, nginx, etc) and a cron job to change your "thought of the day" every night. In fact, a lot of non-interactive web pages can be done this way: periodically rebuild html files from database or any other source, and use simple, fast static web servers. A: If your "thought for the day" page never change except once a day, maybe the simple thing to do is to launch something like that once a day wget http://your_site/your_page.php -O /var/www/your_site_directory/your_page.html (and change links to this page from your_page.php to your_page.html) Then you will reduce the load on your apache server AND your SQL server... A: You could also try memcached. That's what my company uses and I think LiveJournal uses it too. It caches DB requests and makes a serious dent in DB access. A: I could't agree more with Javier's suggestion (generate a static web page). I just want to add one remark to clarify it a little: Store the static file as ".html", not ".php" or whatever language is used to pull the data from DB. Using static files is much faster than starting up an parser or executable. Static files (HTML, GIF, ...) are just put through to the network while scripts, CGIs and all other things are started, parsed, executed and whatever else... That will require much more server ressources than real static files. A: A static file just has the I/O as overhead. Objects cached in memory are great but you still have the overhead of managing those objects, and with heavy usage this becomes tricky. Hence the ease and beauty of static files. Another benefit is that you can have processes that are NOT a part of web server threads perform updates and maintenance. If you update service locks, you will not lock up your web server.
{ "language": "en", "url": "https://stackoverflow.com/questions/170660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do you design a good permgen space string in Java? I'm wondering how you would go about designing a good permgen space string in Java. Based on my research and understanding I've come up with the following: example: JAVA_OPTS='-Xmx512m -XX:MaxPermSize=256m -server -Djava.awt.headless=true' Sorry the example didn't paste when I first posted the question...... A: I am also a bit unclear on the question, but if you mean what is a good number to use for max permgen size, it will depend on your app and the number of classes/methods loaded. To help determine them, you could run your application with its typical and most intense use cases and use JConsole and see what your app actually ends up using. JConsole can display all of your heaps and your permanent generation space, so you can determine what number is required for MaxPermSize that way. Since it's class + method data, it will be a function of how many classes your application loads, not how many instances. Note that it is also separate from heap size (and in fact, JConsole categorizes the memory use as non-heap-memory use). At the JConsole page I linked, see Figure 5. It is the right-most non-heap and can be clicked. In Java 6, apps will allow connections from JConsole with no additional configuration. In Java 5, you may need to set some flags. It is included with the JDK. For reference, for an application that has ~10,000 classes loaded our MaxPermSize is 96m
{ "language": "en", "url": "https://stackoverflow.com/questions/170663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Helper functions for safe conversion from strings Back in VB6, I wrote a few functions that would let me code without having to care about the difference between null and '' for strings, null and 0 for numbers, etc. Nothing kills my productivity more when coding than having to add special case code for dealing with data that might cause some irrelevant error; 9999/10000 if something I'm using as a number is null, then really I treat it as 0. I'm now in C#, and the difference between VB6 and C# 2005 is quite extensive...so I don't really know where to start to write my new set of helper functions, or if I even need to do them at all. So, I need to write a function that would accept a string, a database field, a request form/querysting field, ???, and then do whatever it could do to turn that into a Double, and return that to the calling procedure. I'd also need to do this for shorts, int16, int32, long, everything else I could possibly care about. Then I'd do this for strings. And Dates. Is this a worthwhile pursuit? Is there something in the framework or C# that I can use instead? I really desire something that would allow me to use data inline in calling other functions, and not having to create temporary variables, etc. A: In C# most data types are not nullable (numbers, dates, etc), only strings are nullables. If you are getting data from a DB, then you will probable be working with Nullable, or its syntactic-sugared version, int?, double?, DateTime?, etc. All nullables have a method that allow you to get their actual value, or a default value if they are null. This should help you avoid creating those functions. As for strings, you have the String.IsNullOrEmpty(str) function. You also can add extension methods if you want some special not-available functionality. Note that extension methods can be applied to null values, as long as you handle it in the code. For example: public static string ValueOrDefault(this string str) { if (String.IsNullOrEmpty(str)) return MY_DEFAULT_VALUE; else return str; } A: There are scads of conversion functions built-in. But... i'm not sure any of them do exactly what you want. Generally, .NET methods err on the side of caution when passed invalid input, and throw an exception. Fortunately, you can easily write a utility method to convert a string representation of a numeric value, an empty string empty, or null string to any output type: public static T SafeConvert<T>(string s, T defaultValue) { if ( string.IsNullOrEmpty(s) ) return defaultValue; return (T)Convert.ChangeType(s, typeof(T)); } Use: SafeConvert(null, 0.0) == 0.0; SafeConvert("", 0.0) == 0.0; SafeConvert("0", 0.0) == 0.0; This generic method takes its return type from the type of the second argument, which is used as the default value when the passed string is null or empty. Pass 0 and you'd get an In32 back. Pass 0L, Int64. And so on... A: There is a class called Convert in the .NET library. It has functions that allow you to convert to whatever you need from any base type and a few of the common classes (like DateTime.) It basically works like Convert.ToInt32(val); EDIT: I really need to learn to read all the words. Didn't catch the worry about null... there is an operator for this. You can use the ?? to check for null and provide a default however so that might work. You might also want to just look into LINQ, it handles a lot of that sort of mapping for you. A: I think it similar to @Shog9. I just add a try catch to handle user unusual input. I send the type in which I want to convert the input and take the input as object. public static class SafeConverter { public static T SafeConvert<T>(object input, T defaultValue) { if (input == null) return defaultValue; //default(T); T result; try { result = (T)Convert.ChangeType(input.ToString(), typeof(T)); } catch { result = defaultValue; //default(T); } return result; } } Now call them like below SafeConverter.SafeConvert<ushort>(null, 0); SafeConverter.SafeConvert<ushort>("", 0); SafeConverter.SafeConvert<ushort>("null", 0); SafeConverter.SafeConvert<ushort>("-1", 0); SafeConverter.SafeConvert<ushort>("6", 0); SafeConverter.SafeConvert<ushort>(-1, 0); SafeConverter.SafeConvert<ushort>(0, 0); SafeConverter.SafeConvert<ushort>(1, 0); SafeConverter.SafeConvert<ushort>(9, 0);
{ "language": "en", "url": "https://stackoverflow.com/questions/170665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: What is the best open XML parser for C++? I am looking for a simple, clean, correct XML parser to use in my C++ project. Should I write my own? A: TinyXML can be best for simple XML work but if you need more features then try Xerces from the apache project. Go to the following page to read more about its features. http://xerces.apache.org/xerces-c/ A: TinyXML, and also Boost.PropertyTree. The latter does not fulfill all official requirements, but is very simple. A: I am a C++ newbie and after trying a couple different suggestions on this page I must say I like pugixml the most. It has easy to understand documentation and a high level API which was all I was looking for. A: I like the Gnome xml parser. It's open source (MIT License, so you can use it in commercial products), fast and has DOM and SAX based interfaces. http://xmlsoft.org/ A: Try TinyXML. http://sourceforge.net/projects/tinyxml A: Try TinyXML or IrrXML...Both are lightweight XML parsers ( I'd suggest you to use TinyXML, anyway ). A: TiCPP is a "more c++" version of TinyXML. 'TiCPP' is short for the official name TinyXML++. It is a completely new interface to TinyXML (http://www.grinninglizard.com/tinyxml/) that uses MANY of the C++ strengths. Templates, exceptions, and much better error handling. It is also fully documented in doxygen. It is really cool because this version let's you interface tiny the exact same way as before or you can choose to use the new 'ticpp' classes. All you need to do is define TIXML_USE_TICPP. It has been tested in VC 6.0, VC 7.0, VC 7.1, VC 8.0, MinGW gcc 3.4.5, and in Linux GNU gcc 3+ A: try this one: http://www.applied-mathematics.net/tools/xmlParser.html it's easier and faster than RapidXML or PUGXML. TinyXML is the worst of the "simple parser". A: How about RapidXML? RapidXML is a very fast and small XML DOM parser written in C++. It is aimed primarily at embedded environments, computer games, or any other applications where available memory or CPU processing power comes at a premium. RapidXML is licensed under Boost Software License and its source code is freely available. Features * *Parsing speed (including DOM tree building) approaching speed of strlen function executed on the same data. *On a modern CPU (as of 2008) the parser throughput is about 1 billion characters per second. See Performance section in the Online Manual. *Small memory footprint of the code and created DOM trees. *A headers-only implementation, simplifying the integration process. *Simple license that allows use for almost any purpose, both commercial and non-commercial, without any obligations. *Supports UTF-8 and partially UTF-16, UTF-32 encodings. *Portable source code with no dependencies other than a very small subset of C++ Standard Library. *This subset is so small that it can be easily emulated manually if use of standard library is undesired. Limitations * *The parser ignores DOCTYPE declarations. *There is no support for XML namespaces. *The parser does not check for character validity. *The interface of the parser does not conform to DOM specification. *The parser does not check for attribute uniqueness. Source: wikipedia.org://Rapidxml Depending on you use, you may use an XML Data Binding? CodeSynthesis XSD is an XML Data Binding compiler for C++ developed by Code Synthesis and dual-licensed under the GNU GPL and a proprietary license. Given an XML instance specification (XML Schema), it generates C++ classes that represent the given vocabulary as well as parsing and serialization code. One of the unique features of CodeSynthesis XSD is its support for two different XML Schema to C++ mappings: in-memory C++/Tree and stream-oriented C++/Parser. The C++/Tree mapping is a traditional mapping with a tree-like, in-memory data structure. C++/Parser is a new, SAX-like mapping which represents the information stored in XML instance documents as a hierarchy of vocabulary-specific parsing events. In comparison to C++/Tree, the C++/Parser mapping allows one to handle large XML documents that would not fit in memory, perform stream-oriented processing, or use an existing in-memory representation. Source: wikipedia.org://CodeSynthesis XSD A: Do not use TinyXML if you're concerned about efficiency/memory management (it tends to allocate lots of tiny blocks). My personal favourite is RapidXML. A: pugixml - Light-weight, simple and fast XML parser for C++ Very small (comparable to RapidXML), very fast (comparable to RapidXML), very easy to use (better than RapidXML). A: How about gSOAP? It is open source and freely available under the GPL license. Despite its name, the gSOAP toolkit is a generic XML data binding tool and allows you to bind your C and C++ data to XML automatically. There is no need to use an XML parser API, just let it read/write your data in XML format for you. If you really need a super-simple C++ XML parser then gSOAP may be an overkill. But for everything else it has worked well as testimonials show for many industrial applications since gSOAP was introduced in 2001. Here is a brief list of features: * *Portable: Windows, Linux, Mac OS X, Unix, VxWorks, Symbian, Palm OS, WinCE, etc. *Small footprint: 73KB code and less than 2K data to implement an XML web service client app (no DOM to limit memory usage). *Fast: do not believe what other tools claim, the true speed should be measured with I/O. For gSOAP it is over 3000 roundtrip XML messages over TCP/IP. XML parsing overhead is negligible as it is a simple linear scan of the input/output while (de)serialization takes place. *XML support: XML schema (XSD) import/export, WSDL import/export, XML namespaces, XML canonicalization, XML with attachments (MIME), optional use of DOM, many options to produce XML with indentation, use UTF8 strings, etc. *XML validation: partial and full (option) *WS support: WS-Security, WS-ReliableMessaging, WS-Addressing, WS-Policy, WS-SecurityPolicy, and other. *Debugging: integrated memory management with leak detection, logging. *API: no API to learn, only "soap" engine context initialization, then use the read/write interface for your data, and "soap" engine context destruction. For example: class Address { std::string name; std::vector<LONG64> number; time_t date; }; Then run "soapcpp2" on the Address class declaration above to generate the soap_read_Address and soap_write_Address XML reader and writer, for example: Address *a = new Address(); a = ...; soap ctx = soap_new(); soap_write_Address(ctx, a); soap_end(ctx); soap_free(ctx);` This produces an XML representation of the Address a object. By annotating the header file declarations with XML namespace details (not shown here), the tools also generate schemas. This is a simple example. The gSOAP tools can handle a very broad range of C and C++ data types, including pointer-based linked structures and even (cyclic) graphs (rather than just trees). Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/170686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "252" }
Q: Row Level Security with Entity Framework I've been trying to consider how Row Level Security could be implemented with the Entity Framework. The idea is to have a database agnostic means that would offer methods to restrict the rows coming from the ObjectContext. Some of my inital ideas have involved modifying the partial classes created by the EDMGEN tool and that has offered some limited support. Users are still able to get around this solution by using their own eSQL statements and a QueryObject. I've been looking for a comprehensive solution that would exist above the database providers so that it would remain agnostic. A: The place where you add security really depends on who you're trying to secure against. If, for example, you were securing a web site, then adding the filtering at the context level would be sufficient, because the "users" in this case are on the web site. They have no choice but to go through your context, since you would write the application entirely against the context. In your case, it sounds like the "users" you're trying to secure against are developers. That's quite a bit more difficult. If the developers don't have access to make modifications to the database itself, then you'll have to put the security at the database level. No amount of eSQL access is going to be able to get around the database saying "no". A: Sure you can do it. The important thing to do is to block direct access to the object context (preventing users from building their own ObjectQuery), and instead give the client a narrower gateway within which to access and mutate entities. We do it with the Entity Repository pattern. You can find an example implementation of this pattern for the entity framework in this blog post. Again, the key is blocking access to the object context. Note that the object context class is partial. So you should be able to prevent "unauthorized" means of instantiating it, namely, outside of your repository assembly. However, there are subtleties to consider. If you implement row-level view security on a certain entity type via the repository pattern, then you must consider other means by which a client could access the same entities. For example, via navigational relationships. You may need to make some of those relationships private, which you can do in your model. You also have the option of specifying a custom query or stored procedure for loading/saving entities. Stored procedures tend to be DB server specific, but SQL can be written in a generic manner. While I don't agree that this cannot be done with the Entity Framework, I do agree with the "do it on the DB server" comments insofar as you should implement defense in depth. A: What you're trying to achieve is, by definition, not possible. If the security is not handled explicitly by the underlying database application (SQL Server, Oracle, whatever) then the standard tools like SQL Management Studio will blow right past it. The best you can do is enforce row level security by users of the application ONLY if those users do not have access to the database via another mechanism. A: You might find this article useful: http://msdn.microsoft.com/en-us/magazine/ff898427.aspx "Deny Table Access to the Entity Framework Without Causing a Mutiny" A: I found a way to do it using Postgres and an Extension called Veil. It actually works (designed for) using Views for all operations (select, update,delete,insert) and verifying permissions in WHERE clauses. But Veil just adds the maths for efficiently managing permission's information in memory instead of querying it every time. So with Veil, although you connect directly to DBMS you have just the row level access granted for you. I modify my style with veil in some ways, for example, I began to use Triggers instead of Views for applying permissions restrictions. I recommend you to study this solution and try to apply it's logic here. i.e.: You make a select * from table query and you get just what you're intent to (row level speaking).
{ "language": "en", "url": "https://stackoverflow.com/questions/170689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: PHP $_GET problems with www.example.com/folder/file?id=2 type URLs I'm changing my site to show friendly URLs like this: www.example.com/folder/topic Works fine! But when I add a parameter to the URL: www.example.com/folder/topic?page=2 $_GET stops working. It doesn't recognise the parameter at all. Am I missing something? The parameter worked fine before using full URLs. A: If it's a mod_rewrite problem, which it sounds like, you could add the [QSA] flag to your mod_rewrite rule, to append the query string to the rewritten URL instead of throwing it away. Your rule will end up looking like: RewriteRule from to [QSA] A: If you are using mod_rewrite then it is your rules that are broken. Either the query string is not being passed, or the mod_rewrite is discarding everything past /topic. Try adding a rule that you can do: www.example.com/folder/topic/2 A: If you want to make your PHP URLs "friendly" you need to use something like Apache's mod_rewrite. Google something like "apache mod_write friendly url" and you will get plenty of articles on the subject. A: I'm changing my site to show friendly URLs Are you doing this using mod_rewrite or by reorganising your file structure? If the former, it's likely that your rules may need tweaking. If it's a file re-organisation, what do you get when you print_r($_GET) in www.example.com/folder/topic?page=2? A: MrZebra's answer is the correct one. It will allow you to continue to use query string as you do at the end of a URL, and you don't have to anticipate its presence one way or the other.
{ "language": "en", "url": "https://stackoverflow.com/questions/170697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: To host or not to host? What are the pros and cons of using a hosting provider for a Subversion repository versus maintaining it in-house? I'm sure there are benefits in terms of ease of set up and use. And it would be nice to have somebody else make sure that our code is backed up properly. However, Visual SVN Server is dirt simple to set up, and we already have a pre-established set of servers that are maintained by another department and backed up regularly. So with that said, what are the big pros and cons of using a hosted service versus maintaining it ourselves? Cross links: * *What Are Some Decent ISPs That Host Subversion *Where Should a Subversion Repository Be *Should I use software hosting solution for my personal projects A: Here's my personal experience with this problem. I ran my own SVN server for 2+ years and CVS 2+ years before that. SVN is dirt simple to admin but over time more and more of my code was making it's way into the repository. I literally have everything I ever wrote from college up until today my respository (work projects of course excluded). I truly fretted way to often that I had my life's work sitting on some random server in my house. 5 years of code is quite a bit. Occasionally I would get paranoid enough to run a backup and take a CD to work and throw it in the desk. But the time between backups frankly was lacking. There was also the security concerns of self hosting a server. I was pretty diligent about installing updates (debian is so so easy to that with). But over time I found I had less and less time to admin the server. Eventually I researched some providers and took a stab at using wush.net. You won't be able to make me go back to self hosting. Wush.net is an incredible host. I've been using them for 2-3 years now and in all of that time there has been a single (yes single) instance that I wasn't able to get my source. They do nightly offsite backups so I feel good about the security of my code. And not having to admin anymore I have that much more time to actually get some coding done. A: If you already have the infrastructure in place and are confident in your ability to host, backup and provide accessibility to your repositories then I would say that hosting SVN yourself is the way to go. This allows you relatively unlimited growth and total control over your source. If you have a primarily mobile development workforce that are small in number then the cost and limitations of using a hosted provider might make it far more convenient for you. But this applies to very few companies. A: How important is your SVN repository? Vital? Then you do not want to trust it to a host that promises to back it up regularly. Its easy to become a host, you rent a server and you're a host, so its attracted a lot of less-businesslike providers, and you won't generally be able to tell the good from the bad until the bad one goes out of business and you suddenly can't connect, or contact them for those backups, and their host turns your server off because they've not been paid and won't talk to you because they have no business relationship with you. So, if you do go with a host, make sure those backups find their way into your hands regularly, and you can restore from them. Anything less is simply blind trust that you'll always be able to get at them. A: Several previous SO threads have discussed this: What Are Some Decent ISPs That Host Subversion Where Should a Subversion Repository Be Should I use software hosting solution for my personal projects I am sure I've seen couple more, but I can't find them right now.
{ "language": "en", "url": "https://stackoverflow.com/questions/170726", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Best way to use sessions with MVC and OO PHP I've been working with sessions, MVC design and object oriented PHP. Where should I save or retrieve data from a session? I would like to retrieve it from within methods so I don't have to pass the data to the methods. Whats the best practice? A: I typically put this inside the controller. It just makes sense.. The controller decides what happens and why not let it decide if people are allowed to do the requested actions. Typically you have multiple controllers in a MVC system. Eg. BaseController (abstract - common), NonSessionController extends BaseController (eg: used for static pages), SessionController extends BaseController (primary session handing here - this could be abstract). If you have for example different user types, you may want to polymorph this controller ones such as: AdminController, UserController, Etc. A: Personally, I'm a huge fan of the Zend_Session wrapper class. I prefer to work with data in an object-oriented style and the namespacing advantage to using a wrapper is a huge plus. Which of these looks better to you? $_SESSION['Zend_Auth']['user'] = "myusername"; or $authNamespace = new Zend_Session_Namespace('Zend_Auth'); $authNamespace->user = "myusername"; I prefer the look that using the accessors gives you. Note: In an MVC system, no matter what method you choose, you should always be getting/setting session data in your controller. A: I've tried it a few ways, including using a static wrapper class to handle it, but I always come back to just using the superglobal array by itself. I still use a wrapper for authentication checks and other repetitive tasks, but, ultimately, it's just easier and less verbose for me to use the stock setup. A: I think it is depend on the scope of where the retrived data will be used, if it is only used inside a method then why you should retrive it outside, and session is always available in superglobal variables it is better to localize it only when needed. A: I wouldn't bother with session wrappers. You won't gain enough to merit the limitations. Going through the superglobal allows you to use any sort of (hopefully sane) data structure you want. My session data always ends up being 2 or more levels of array data, which is too tedious to manage through a session wrapper. The superglobal doesn't even limit you from having PHP store your session data in a database using a save handler, which is quite nice for scalability.
{ "language": "en", "url": "https://stackoverflow.com/questions/170730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: is it time to try merb? With Merb 1.0 rapidly approaching, I would like to know what Merb/Rails users recommend? Is it time to try Merb? What was downside for you when you switched to Merb from Rails? A: Yes. Downsides: * *Lack of documentation, although this is getting better (not really a problem for some, as the code is very well documented). *Rails plugins, Merb uses Gems, and not all have been ported (the most used ones have) *Doing a straight port of a Rails app, will not utilize some of the cool features in Merb (plus syntax differs in places) But, the Advantages: * *Faster & Thread-safe (added advantage if using DM or Sequel as they are thread-safe too) *Modular (can pick what you need along with your fav ORM, JS Lib, Templating Lang) *Less Magic *Good for green field projects or exposing your API *Merb has a stable API (1.0 comes out in a few weeks) Overall, if you're comfortable with Rails switching to Merb isn't hard at all. I personally prefer Merb over Rails, as it adopts more Ruby conventions. A: I've been waiting for the 1.0 release so that the API is frozen. It's a little tough keeping up with the Merb changes (I can only speak for myself though, and this was during the pre-merb-core/more days up till the 0.9.x releases) and figuring out why stuff breaks. If all things go according to schedule, Merb 1.0 will be released soon at MerbCamp (Oct 11-12). So if I were completely new to Merb, I'd wait until then. A: Everyone, including many from the Merb Core team have been recommended to wait for 1.0. But if you're at all curious, grab the latest Gem and start toying. Just don't expect to put it into production and hold off on any production work till 1.0 is out. A: The biggest downside was figuring out what's different between Merb and Rails. The biggest upside is that when I ask for help on the Merb IRC or mailing lists, I get help, not insulted -- unlike Rails. A: The spam filtering service Defensio has been running on Merb for a few months now. Merb seems to be working very well for them :-) Disclaimer (even if I'm not trying to sell you anything): I've worked on Defensio in the past. A: I think it's safe to now use Merb, as they've pretty much frozen the API. I recently rebuilt my weblog using Merb (and version 0.9.7 or so) and it works like a champ. I will have to make some adjustments for bringing it up to the 1.0 API, but I don't anticipate much work. I say go for it. Merb is nice. A: About a month has passed and now that Merb has reached 1.0, yes, it is finally time to try Merb and feel comfortable about it if you're the more conservative sort :)
{ "language": "en", "url": "https://stackoverflow.com/questions/170734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What techniques have you actually used successfully to improve code coverage? I regularly achieve 100% coverage of libraries using TDD, but not always, and there always seem to be parts of applications left over that are untested and uncovered. Then there are the cases when you start with legacy code that has very few tests and very little coverage. Please say what your situation is and what has worked that at least improved coverage. I'm assuming that you are measuring coverage during unit testing, but say if you are using other techniques. A: Delete code. This isn't snarky, but actually serious. Any time I would see the smallest amount of code duplication or even code that I couldn't get to execute, I deleted it. This increased coverage and increased maintainability. I should note that this is more applicable to increasing the coverage of old code bases vs. new code bases. A: I do assume you read "Code covered vs. Code Tested", right ? As stated in that question, Even with 100% block coverage + 100% arc coverage + 100% error-free-for-at-least-one-path straight-line code, there will still be input data that executes paths/loops in ways that exhibit more bugs. Now, I use eclemma, based on EMMA and that code-coverage tool explains why 100% code is not always possible: because of partially covered lines due to: * *Implicit branches on the same line. *Shared constructor code. *Implicit branches due to finally blocks. *Implicit branches due to a hidden Class.forName(). So all those 4 cases might be good candidates for refactoring leading to a better code coverage. Now, I agree with Frank Krueger's answer. Some non-covered code might also be an indication of some refactoring to be done, including some code to actually delete ;) A: We use Perl, so Devel::Cover has been very useful for us. Shows per-statement coverage, branch coverage and conditional coverage during unit testing, as well as things like POD coverage. We use HTML output with easy-to-recognize greens for "100%", through yellow and red for lower levels of coverage. EDIT: To expand on things a little: * *If conditional coverage isn't complete, examine the conditions for interdependence. If it's there, refactor. If it isn't you should be able to extend your tests to hit all of the conditions. *If conditional and branch coverage looks complete but statement coverage isn't, you've either written the conditionals wrong (e.g. always returning early from a sub when you didn't mean to) or you've got extra code that can be safely removed. A: The two things that had the greatest impact on projects I've worked on were: * *Periodically "reminding" the development team to actualy implement unit tests, and reviewing how to write effective tests. *Generating a report of overall test coverage, and circulating that among the development managers. A: FIT testing has improved our code coverage. It has been great because it is an entirely different tack. Background: we have a mix of legacy and new code. We try to unit/integration test the new stuff as much as possible, but because we are migrating to Hibernate/Postgres and away from an OODB, there isn't much point to testing the legacy code. For those who don't know, FIT is a way to test software from the user perspective. Essentially, you can specify desired behaviour in HTML tables: the tables specify the actions against the software and the desired results. Our team writes 'glue code' (aka FIT test) that map the actions to calls against the code. Note that these tests operate in a view 'from space' compared to unit tests. Using this approach, we have increased our code-coverage by several percentage points. An added bonus is that these tests will bridge across versions: they will test legacy code but then, later, new code. i.e. they serve as regression tests, in a sense.
{ "language": "en", "url": "https://stackoverflow.com/questions/170751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Where can i find a good in depth guide to C# 3? It seems that C# 3 hit me without me even noticing, could you guys tell me about good in depth guides to C# 3? from lambda to linq to everything else that was introduced with the third version of the language. Printed books would be nice, but online guides would be even better! A: There are some high quality blogs out there. some of my favorites: Eric Lippert, Eric White, Scott Gu A: I've been told this is a good book C# in Depth. MS Training kits Visual Studio 2008 and .NET Framework 3.5 Training Kit and .NET Framework 3.5 Enhancements Training Kit Channel 9 presentation\videos A: I've read the first 4 chapters from 'C# In Depth' by Jon Skeet so far and would recommend this book. A: Just another recommendation for C# in Depth; not only will it fully explain C# 3.0 - but it will also significantly improve your understanding of C# 2.0 - for example, a lot of the more subtle nuances of iterator blocks or captured variables. Definitely worth a read. A: ScottGu has some great posts on C# 3: * *The C# ?? null coalescing operator (and using it with LINQ) *LINQ to SQL: Part 8 (this is an 8 part series, check the top of the post for links to the first 7) *Automatic Properties, Object Initializers, and Collection Initializers *Extension Methods *Lambda Expressions *Query Syntax *Anonymous Types Some more useful links: * *MSDN: Overview of C# 3.0 *David Hayden: C# 3.0 Tutorials and Examples A: http://msdn.microsoft.com/en-us/library/bb308966.aspx A: If your looking for some dead tree reference, I recommend Pro C# 2008 and the .NET 3.5 Platform by Andrew Troelsen. http://www.amazon.co.uk/gp/reader/1590598849/ref=sib_rdr_toc?ie=UTF8&p=S006&j=0#reader-page A: I've found C# 3.0 in a Nutshell to be very useful. A: I found Pro LINQ: Language Integrated Query in C# 2008 to be very helpful for this. It has a chapter which covers all the new language features in 3, and of course the rest of the book goes into a deep dive on LINQ. I would highly recommend it. A: The C# 3 specification gives a complete description of the language, however this might be too much detail for your needs.
{ "language": "en", "url": "https://stackoverflow.com/questions/170772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: CruiseControl.net failing with HTTP Error 500 on Vista x64 I installed CruiseControl.net ( from the CruiseControl.NET-1.4-Setup.exe installer ) on my Vista x64 development machine. The server portion is running fine; however, the webdashboard piece is not working. The first error message I saw when I tried to pull up http://localhost/ccnet squawked about not being able to run in integrated pipeline mode. Easily fixed. I opened up the IIS7 admin panel and changed the ccnet application to use the "Classic .NET App Pool" application pool. However, I am now getting a persistent HTTP Error 500 when I try to connect. I set the NTFS permissions on the webdashboard folder wide open in the hopes that maybe it was a file permissions issue. No joy. After a bit of digging and trial and error I found a set of steps which seems to fix the problem. I'll post a follow up answer right after this, but wanted to share this out on stackoverflow in the hopes that it might aid someone else down the line. Also, if there's a better configuration solution I'm all ears :) A: Here's the top of the HTTP 500 error dump I was getting: HTTP Error 500.0 - Internal Server Error Description: The page cannot be displayed because an internal server error has occurred. Error Code: 0x800700c1 Notification: ExecuteRequestHandler Module: IsapiModule Requested URL: http://localhost/ccnet/default.aspx Physical Path: C:\Program Files (x86)\CruiseControl.NET\webdashboard\default.aspx Logon User: Anonymous Logon Method: Anonymous Handler: AboMapperCustom-80778 Most likely causes: IIS received the request; however, an internal error occurred during the processing of the request. The root cause of this error depends on which module handles the request and what was happening in the worker process when this error occurred. IIS was not able to access the web.config file for the Web site or application. This can occur if the NTFS permissions are set incorrectly. IIS was not able to process configuration for the Web site or application. The authenticated user does not have permission to use this DLL. The request is mapped to a managed handler but the .NET Extensibility Feature is not installed. The key to fixing this for me was the Handler line. For some reason the ccnet web application was configured with two handlers vying for control over *.aspx. The real handler, from Thoughtworks, is set in the web.config file. However, when I opened the Handler Mappings section of the IIS7 control panel for the ccnet app I saw that there was another handler named AboMapperCustom-80778 already created and set to look for *.aspx. I right clicked the handler and selected "Remove". After that the ccnet app started running fine for me. A: This post seems to indicate that a host of problems can occur w/ IIS and 64-bit OS. Check out the link for some ideas on resolving it: http://blog.danbartels.com/archive/2005/05/18/662.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/170777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to serialize SettingsContext and SettingsPropertyCollection I need to serialize the System.Configuration.SettingsContext and System.Configuration.SettingsPropertyCollection types as i am implementing my own profile provider. Any suggestions on how to do it in the most simplest way. A: You have two options: Create DTOs with a DataContract attribute and "translate" from the non-data contract objects to the DTOs and back again when the service is called. This will take advantage of the Data Contract serializer and your service hums along as normal. It can be tedious if you are using a lot of fields out of these objects (I would try to limit the fields used if possible to ONLY ones you know you are going to need) Use the XML serializer on calls that send/return them. The XML serializer is a bit slower than the Data Contract serializer, but provides more control over how data gets serialized. Your clients wont see (or care about) a difference. There a many examples on the web on how to do this (like this one: http://msdn.microsoft.com/en-us/library/ms733901.aspx), so I'm not going to repeat them here. :) It's not too hard though. Good luck
{ "language": "en", "url": "https://stackoverflow.com/questions/170786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I know if Windows has just recovered from a BSOD? From http://support.microsoft.com/kb/317277: If Windows XP restarts because of a serious error, the Windows Error Reporting tool prompts you... How can my app know that "Windows XP has restarted because of a serious error"? A: Note: this is a good question for a code-challenge Here are some executable codes, but feel free to add other solutions, in other languages: The uptime might be a good indication: net stats workstation | find /i "since" Now link that information with a way to read the windows event logs, like, say in PowerShell: Get-EventLog -list | Where-Object {$_.logdisplayname -eq "System"} And look for the last "Save Dump" messages As Michael Petrotta said, WMI is a good way to retrieve that information. Based on the update time, you can make a query like: Set colEvents = objWMIService.ExecQuery _ ("Select * from Win32_NTLogEvent Where LogFile = 'System' AND TimeWritten >= '" _ & dtmStartDate & "' and TimeWritten < '" & dtmEndDate & "'") to easily spot an event log with a "Save Dump" message in it, confirming the crash. More in the Win32_NTLogEvent Class WMI class. Actually, this Microsoft article Querying the Event Log for Stop Events does give it to you (the complete request): strComputer = "." Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") Set colLoggedEvents = objWMIService.ExecQuery _ ("SELECT * FROM Win32_NTLogEvent WHERE Logfile = 'System'" _ & " AND SourceName = 'Save Dump'") For Each objEvent in colLoggedEvents Wscript.Echo "Event date: " & objEvent.TimeGenerated Wscript.Echo "Description: " & objEvent.Message Next A: Restarts resulting from a BSOD are reported in the event log. Use the libraries in your favorite language to search the log for errors. In .NET, for instance, you'll want to look to the System.Diagnostics.EventLog class. WMI may offer a more flexible way to search the log. A: You can look for a memory or kernel dump file with a recent creation time, if dump file generation has been enabled (or, rather, not disabled since it's on by default.)
{ "language": "en", "url": "https://stackoverflow.com/questions/170787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can I get an OpenFileDialog in a custom control's property grid? I'm creating a .net custom control and it should be able to load multiple text files. I have a public property named ListFiles with those properties set : [Browsable(true), Category("Configuration"), Description("List of Files to Load")] public string ListFiles { get { return m_oList; } set { m_oList = value; } } Depending upon the type of object, (string, string[], List, ...), the property grid will allow the user to enter some data.. My goal would be to have a filtered openfiledialog in the Properties Grid of my component that would enable the user to choose multiple files and return it as an array or string (or something else...). Sooo... Here's my question : How can I get an OpenFileDialog in a custom control's property grid? Thanks a lot! A: Here's another example comes with customizing File Dialog : CustomFileEditor.cs using System.Windows.Forms; using System.Windows.Forms.Design; namespace YourNameSpace { class CustomFileBrowser : FileNameEditor { protected override void InitializeDialog(OpenFileDialog openFileDialog) { base.InitializeDialog(openFileDialog); openFileDialog.Title = "Select Project File : "; openFileDialog.Filter = "Project File (*.proj)|*.proj"; ; } } } Usage : [Category("Settings"), DisplayName("Project File:")] [EditorAttribute(typeof(CustomFileBrowser), typeof(System.Drawing.Design.UITypeEditor))] public string Project_File { get; set; } A: You can use built-in UITypeEditor. It is called FileNameEditor [EditorAttribute(typeof(System.Windows.Forms.Design.FileNameEditor), typeof(System.Drawing.Design.UITypeEditor))] public string SomeFilePath { get; set; } A: You can do this by adding a UITypeEditor. Here is an example of a UITypeEditor that gives you the OpenFileDialog for chossing a filename.
{ "language": "en", "url": "https://stackoverflow.com/questions/170791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: .NET WCSF as UI stack choice for portal based sites? We are building a website which will display news headlines and news. It will be a public site initially, but will evolve include portal content like personalized web pages. The site also needs to build web 2.0 features around the news stories being displayed, and needs to be extensible and highly customizable, allowing the business to change templates in which the stories are defined and use different templates based on business logic etc.. The core business logic is being built using Windows work flow and Windows communication foundation, we are now looking for a suitable UI stack, is WCSF a good choice? A: WCSF might be a good choice, but probably for reasons that have nothing to do with the possible feature needs you've listed. The best things in my opinion that WCSF has going for it is that it's built on the Model-View-Presenter-[Controller] pattern which gives you the separation of concerns between the view and presenter (just like MVC)... BUT at the same time it's not a total paradigm shift from the "Page Control" model that many .net'ers are used to. This means you can still use a lot of third party controls like Telerik or Infragistics pretty much like you did before (much more challenging with MVC). Because the MVP pattern uses a dependency injection container (ObjectBuilder) and inversion of control you get a pretty nice way to write unit tests without a web context (easy to mock objects). Also the container supports service location, so you can easily write WCSF services that will be shared (and WCF and or the WSSF fit in nicely here). It's highly modularized from a programatic standpoint and has many extensibility points. All that being said... it kind of sounds like you're looking for more of a templating, personalization, dynamic framework. You might check out WSS/SharePoint in this case, because it may get you further down the field out of the box. A: I use wcsf and I'm very happy with it. I too want to have the whole template/dynamic content thing. I will be programming it, though. MVC is too much of a paradigm shift, and will make it difficult to do what I want to do - partly because the framework is still in beta. Good luck! A: We're using WCSF on a new project and so far it is really help us to deliver good quality work very quickly. It has really helped us as we are using SCRUM as agile method. Therefore the flexibility that the Dependency injection pattern provides us is awesome. We had a few grey hairs to start with, namely developers getting buying into the WCSF and getting around thier learning curve but now it's really paying dividends for us A: WCSF + (WSSF | WCF) are good platform together. We have positive experiences with WCSF(but I have to say, only in small projects as front-end). AJAX supported. You find valuable discussions about performance or achitecural ideas on http://websf.codeplex.com/Thread/List.aspx.
{ "language": "en", "url": "https://stackoverflow.com/questions/170799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Embedding HWND into external process using SetParent I'm trying to embed a window from my process into the window of an external process using the SetParent function and have encountered a few problems that I'm hoping someone can help me out with. First off, here is an outline of what I am currently doing to embed my window into the application: HWND myWindow; //Handle to my application window HWND externalWindow; //Handle to external application window SetParent(myWindow,externalWindow); //Remove WS_POPUP style and add WS_CHILD style DWORD style = GetWindowLong(myWindow,GWL_STYLE); style = style & ~(WS_POPUP); style = style | WS_CHILD; SetWindowLong(myWindow,GWL_STYLE,style); This code works and my window appears in the other application, but introduces the following issues: * *When my window gains input focus, the main application window of the external process loses focus (i.e. title bar changes color) *Keyboard shortcut commands of the main application do not work while my window has focus Does anybody know a workaround for this? I would like my window to be treated as just another child window of the main application. A: I am not sure if you are still interested in this topic after almost three years. I am working on a similar application. My solution is to modify the window style before you call SetParent. With this solution, I don't have to call AttachThreadInput. However, one major issue of hosting child windows from an external process is that if the external process hangs while responding to a user keyboard or mouse input, the main application also freezes. The message loop in the main application is still running. However, it no longer receives user input events. Therefore, it appears as if it is hanging. I believe that's the direct result of AttachThreadInput since the input events of the two threades are now synchronized. If one of them is blocked, both are blocked. A: I ran into the same issue, after reading MSDN doc carefully, I found it an easy fix. You should remove WS_POPUP and add WS_CHILD BEFORE you call setParent It's stated in MSDN: For compatibility reasons, SetParent does not modify the WS_CHILD or WS_POPUP window styles of the window whose parent is being changed. Therefore, if hWndNewParent is NULL, you should also clear the WS_CHILD bit and set the WS_POPUP style after calling SetParent. Conversely, if hWndNewParent is not NULL and the window was previously a child of the desktop, you should clear the WS_POPUP style and set the WS_CHILD style before calling SetParent. https://msdn.microsoft.com/en-us/library/windows/desktop/ms633541(v=vs.85).aspx A: Well, I finally found the answer to my question. To fix the issue with the main app losing focus you need to use the AttachThreadInput function to attach the embedded window thread to the main app thread. Also, one can use the TranslateAccelerator function in response to WM_KEYDOWN messages to ensure accelerator messages of the main app are triggered.
{ "language": "en", "url": "https://stackoverflow.com/questions/170800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Date class different in Ruby stdlib and Rails stdlib I want to use the Date::ABBR_MONTHS constant in my rails application. I see the Ruby stdlib documentation at http://www.ruby-doc.org/stdlib/ which does not seem to have this constant. However, this constant is there at http://stdlib.rubyonrails.org/ What is the difference between these two libraries? This constant is working on my unix deployment machine but not on my dev machine on windows. Can anybody explain whats going on? A: ABBR_MONTHS is something you get given to you by ActiveSupport and it's just added into the Date class. The first library is for ruby, where the second one is for ruby on rails. The constant may not be working because of different versions of Rails. A: ABBR_MONTHS is added to Date by ActiveSupport. Rails is in fact a set of a few gems. ActiveSupport's role is mostly to add niceties to the Ruby language and other agnostic tools like the Inflector and the 2.days way of creating Time instances and so on. So if you need this kind of capability outside of your rails app for some reason, you're in luck: require 'rubygems' #If not already done require 'activesupport' puts Date::Format::ABBR_MONTHS.inspect #=> {"oct"=>10, "jul"=>7, "jan"=>1, "dec"=>12, "jun"=>6, "apr"=>4, "feb"=>2, "may"=>5, "sep"=>9, "aug"=>8, "mar"=>3, "nov"=>11}
{ "language": "en", "url": "https://stackoverflow.com/questions/170824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to serialize System.Configuration.SettingsProperty I need to serialize the System.Configuration.SettingsProperty and System.Configuration.SettingsPropertyValue class object through WCF. A: Using your own class is reasonable option. You can also use the VS designer settings if you want. The VS designer keeps property settings in the ApplicationSettingsBase class. By default, these properties are serialized/deserialized into a per user XML file. Because there is no user context for a WCF service, this will not work. You can override this behavior by using a custom SettingsProvider which makes it pretty easy to keep the properties where ever you want. Just add the SettingsProvider attribute to the VS generated Settings class: [SettingsProvider(typeof(CustomSettingsProvider))] internal sealed partial class Settings { ... } A good example of this is the RegistrySettingsProvider. Edit: My initial read of your question thought you were asking how to persist settings in a WCF service. I see now you want to pass settings through WCF. The SettingsProvider class could also be used for this purpose. A: I guess you're asking because you can't return a list of SettingProperty. I would create a serializable class myself and load the properties there.
{ "language": "en", "url": "https://stackoverflow.com/questions/170825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Anyone really using Code Access Security to protect their assemblies and/or methods? Seems to me most of developers completely ignore this features. People prefer handling security exceptions as generic ones relying on standard windows roles and rights instead of learning to use CAS ways of enhancing security - probably because CAS is quite confusing in its logic and naming. Can anyone suggest any general rule-of-thumb/best practices for using CAS at his best in a clean way? A: Yes and no. Unfortunately, you're right - developers rarely use CAS at all, let alone utilize it to it's fullest. In very few situations do I see them actually doing this (okay, its not really the programmers but the organization forcing them....) Besides being used to allow users to limit assemblies downloaded from the Internet (for example) - though this is rarely deployed outside of Silverlight - I have seen two main uses of CAS. First is general policy limitations, generally the easiest way to get your feet wet with CAS (esp. since VS can auto-generate the policy file for you). I have seen this in use (rarely) when a sensitive enterprise (e.g. banks) have a third-party custom development of a system that must be secure. This can benefit them by adding additional limitations on what they dont know their programmers are doing. Second is very specific link demands, in the (again rare) situation that you have a module running at relatively high privileges, and want only specific assemblies calling into your module. For instance, just last week I had a client with a module writing to ActiveDirectory, and wanted to limit access to this function only from a specific system. Of course, CAS is much bigger than this, but those are really the two best places to start from. As a general rule, and this is of course true for everything, dont decide to use it just because its there, unless it answers a need you have. Policy is the simplest, and makes the most sense to put in place ahead of time. A: See also this discussion. The problem is exacibated because a lot of code (perhaps too much) runs at full trust. And then the only checks that get done are things like PrincipalPermissionAttribute checks - most of the rest are simply bypassed. So in many cases there isn't much point! Unless you are loading in external (untrusted) files [and so need CAS], it simply doesn't add a lot in many cases (and yes, there are plenty of exceptions). CAS is much more useful for clients running in the sandbox (for example downloaded from the internet). Sliverlight takes this to the extreme, with stricter rules (especially around reflection) than regular .NET.
{ "language": "en", "url": "https://stackoverflow.com/questions/170844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Parsing T-SQL to Parameterize a Query The application I am currently working on generates a lot of SQL inline queries. All generated SQL is then handed off to a database execution class. I want to write a parsing service for the data execution class that will take a query like this: SELECT field1, field2, field3 FROM tablename WHERE foo=1 AND bar="baz" and turn it into something like this: SELECT field1, field2, field3 FROM tablename WHERE foo=@p1 AND bar=@p2 blah blah blah Any thing already written that will accomplish this for me in c# or vb.net? This is intended as a stop gap prior to refactoring the DAL for this project. UPDATE: Guys I have a huge application that was ported from Classic ASP to ASP.NET with literally thousands of lines of inline SQL. The only saving grace is all of the generated sql is handed off to a data execution class. I want to capture the sql prior to execution and parameterize them on the fly as a stop gap to rewriting the whole app. A: Don't do this. This is way too much work. Plus, there are loads of security risks with this approach. Look into Command objects and parameterized queries, at the minimum. Here is a small tutorial. A: Refactor now. You're fooling yourself if you think this one abstraction layer is going to be able to come in quicker and easier. Deep down, you know it increases risk and uncertainty on the project, but you want to kill the SQL injection problem or whatever problem you are fighting with a magic bullet. The time you would be taking to write this new parsing subsystem and regression testing the system, you could probably replace all the inline code with calls to relatively fewer code-generated and tested SPs on your DB. Plus you can do it piece by piece. Why build a significant piece of throwaway code which will be hard to debug and isn't really inline with what you want the final architecture to look like? A: I would second the suggestion to use the Command parameters to do what you want. Any kind of SQL query string parsing is just asking for someone do play an SQL injection game with you. A sample code is below. The Parameters collection is easy to manipulate in the normal way command.CommandText = "SELECT * FROM table WHERE key_field='?'" command.Parameters.Append command.CreateParameter(, 8, , , "value") '8 is adBSTR value set rsTemp = command.Execute A: o think your task is too much honerous... you should create a very robust parser... i think it's better and easier starting to rewrite application, finding points where queries are generated and refactoring code. Good Loock! A: I can only think of one benefit that parameterizing queries on the fly would bring: it would reduce your application's current vulnerability to SQL injection attacks. In every other way, the best you could possibly hope for is that this hypothetical on-the-fly parser/interpreter wouldn't break anything. Even if you didn't have to write such a thing yourself (and I bet you do), that's a pretty significant risk to introduce into a production system, especially since it's a stopgap measure that will be discarded when you refactor the app. Is the risk of a SQL injection attack high enough to justify that? A: Have you considered running a substitution regex on the old code? Something that will extract values from the current queries, replace them with parameters, and append after the query line a Command.Parameters.AddWithValue(paramName, paramValue) call might be possible if the current inline SQL all follow the same value (or if nearly all of them do, and you can fix up the remainder in your favorite editor).
{ "language": "en", "url": "https://stackoverflow.com/questions/170850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Emulating user input for java.util.Scanner I'm writing a game in Java, and I want the user to be able to provide input from both the command line and my GUI. Currently, I use this method to get input: static String getInput(){ System.out.println("Your move:"); Scanner sc = new Scanner(System.in); return sc.nextLine(); } I want to keep using this, but let a mousePressed event emulate the user actually typing in their input as well. It's not that efficient of a solution, but it makes sense in my application. So the question is: how do I simulate a user typing to System.in from the code side? A: This is possible - the easiest substitution for System.in would be a PipedInputStream. This must be hooked up to a PipedOutputStream that writes from another thread (in this case, the Swing thread). public class GameInput { private Scanner scanner; /**CLI constructor*/ public GameInput() { scanner = new Scanner(System.in); } /**GUI constructor*/ public GameInput(PipedOutputStream out) throws IOException { InputStream in = new PipedInputStream(out); scanner = new Scanner(in); } public String getInput() { return scanner.nextLine(); } public static void main(String[] args) throws IOException { GameInput gameInput; PipedOutputStream output = new PipedOutputStream(); final PrintWriter writer = new PrintWriter(output); gameInput = new GameInput(output); final JTextField textField = new JTextField(30); final JButton button = new JButton("OK"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String data = textField.getText(); writer.println(data); writer.flush(); } }); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(new FlowLayout()); frame.getContentPane().add(textField); frame.getContentPane().add(button); frame.pack(); frame.setVisible(true); String data = gameInput.getInput(); System.out.println("Input=" + data); System.exit(0); } } However, it might be better to rethink your game logic to cut out the streams altogether in GUI mode. A: I made an application once that could run via the command line or using a GUI. The way I did this was to define an Interface (named IODevice) which defined the following methods: * public String getInput(); * public void showOutput(String output); I then had two classes which implemented this interface - One used the host computer's terminal (as you are doing now) and one used a JTextArea (output) / JOptionPane (input). Perhaps you could do something similar - To change the input device used, simply change the instance of the IODevice. Hope this is of some use. A: To be honest, after re-reading your question I'm not exactly sure what you want. Anyway, perhaps you need to check out the method java.lang.System.setIn(InputStream in). This will allow you to change what reader is used to read input from the terminal (i.e. changing it from the actual terminal to what ever you like) A: Assuming you have many operations like the given example, you might consider the interface approach described by Richie_W but make one routine per operation rather than generic "in/out" methods. For example: public interface IGameInteraction { public String askForMove( String prompt ); public boolean askAreYouSure( String prompt ); } Your command-line implementation is clear; now your GUI implementation could use an appropriate dialog for each logical operation rather than just be a text area that's really just the command-line version. Furthermore this is easier to write unit tests against because in your tests you can stub out these routines in any manner.
{ "language": "en", "url": "https://stackoverflow.com/questions/170854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a way to maximise the current tab in Visual Studio? I sometimes need to use Visual Studio when I have limited screen real estate (remote desktopping from a laptop for example). It would be really useful to be able to make the currently selected code tab maximise to take the whole screen for a limited time. Is that possible? Is there a keyboard shortcut? A: View->Full Screen (Shift + Alt + Enter) Does that work? A: I use Shift-Alt-Enter to activate full screen mode.
{ "language": "en", "url": "https://stackoverflow.com/questions/170866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: How can I avoid duplicate content in ASP.NET MVC due to case-insensitive URLs and defaults? Edit: Now I need to solve this problem for real, I did a little more investigation and came up with a number of things to reduce duplicate content. I posted detailed code samples on my blog: Reducing Duplicate Content with ASP.NET MVC First post - go easy if I've marked this up wrong or tagged it badly :P In Microsoft's new ASP.NET MVC framework it seems there are two things that could cause your content to be served up at multiple URLs (something which Google penalize for and will cause your PageRank to be split across them): * *Case-insensitive URLs *Default URL You can set the default controller/action to serve up for requests to the root of your domain. Let's say we choose HomeController/Index. We end up with the following URLs serving up the same content: * *example.com/ *example.com/Home/Index Now if people start linking to both of these then PageRank would be split. Google would also consider it duplicate content and penalize one of them to avoid duplicates in their results. On top of this, the URLs are not case sensitive, so we actually get the same content for these URLs too: * *example.com/Home/Index *example.com/home/index *example.com/Home/index *example.com/home/Index *(the list goes on) So, the question... How do I avoid these penalties? I would like: * *All requests for the default action to be redirected (301 status) to the same URL *All URLs to be case sensitive Possible? A: As well as posting here, I emailed ScottGu to see if he had a good response. He gave a sample for adding constraints to routes, so you could only respond to lowercase urls: public class LowercaseConstraint : IRouteConstraint { public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { string value = (string)values[parameterName]; return Equals(value, value.ToLower()); } And in the register routes method: public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "home", action = "index", id = "" }, new { controller = new LowercaseConstraint(), action = new LowercaseConstraint() } ); } It's a start, but 'd want to be able to change the generation of links from methods like Html.ActionLink and RedirectToAction to match. A: Bump! MVC 5 Now Supports producing only lowercase URLs and common trailing slash policy. public static void RegisterRoutes(RouteCollection routes) { routes.LowercaseUrls = true; routes.AppendTrailingSlash = false; } Also on my application to avoid duplicate content on different Domains/Ip/Letter Casing etc... http://yourdomain.example/en https://yourClientIdAt.YourHostingPacket.example/ I tend to produce Canonical URLs based on a PrimaryDomain - Protocol - Controller - Language - Action public static String GetCanonicalUrl(RouteData route,String host,string protocol) { //These rely on the convention that all your links will be lowercase! string actionName = route.Values["action"].ToString().ToLower(); string controllerName = route.Values["controller"].ToString().ToLower(); //If your app is multilanguage and your route contains a language parameter then lowercase it also to prevent EN/en/ etc.... //string language = route.Values["language"].ToString().ToLower(); return String.Format("{0}://{1}/{2}/{3}/{4}", protocol, host, language, controllerName, actionName); } Then you can use @Gabe Sumner's answer to redirect to your action's canonical URL if the current request URL doesn't match it. A: I believe there is a better answer to this. If you put a canonical link in your page head like: <link rel="canonical" href="http://example.com/Home/Index"/> Then Google only shows the canonical page in their results and more importantly all of the Google goodness goes to that page with no penalty. A: I was working on this as well. I will obviously defer to ScottGu on this. I humbly offer my solution to this problem as well though. Add the following code to global.asax: protected void Application_BeginRequest(Object sender, EventArgs e) { // If upper case letters are found in the URL, redirect to lower case URL. if (Regex.IsMatch(HttpContext.Current.Request.Url.ToString(), @"[A-Z]") == true) { string LowercaseURL = HttpContext.Current.Request.Url.ToString().ToLower(); Response.Clear(); Response.Status = "301 Moved Permanently"; Response.AddHeader("Location",LowercaseURL); Response.End(); } } A great question! A: Like you, I had the same question; except I was unwilling to settle for an all-lowercase URL limitation, and did not like the canonical approach either (well, it's good but not on its own). I could not find a solution, so we wrote and open-sourced a redirect class. Using it is easy enough: each GET method in the controller classes needs to add just this one line at the start: Seo.SeoRedirect(this); The SEO rewrite class automatically uses C# 5.0's Caller Info attributes to do the heavy lifting, making the code above strictly copy-and-paste. As I mention in the linked SO Q&A, I'm working on a way to get this converted to an attribute, but for now, it gets the job done. The code will force one case for the URL. The case will be the same as the name of the controller's method - you choose if you want all caps, all lower, or a mix of both (CamelCase is good for URLs). It'll issue 301 redirects for case-insensitive matches, and caches the results in memory for best performance. It'll also redirect trailing backslashes (enforced for index listings, enforced off otherwise) and remove duplicate content accessed via the default method name (Index in a stock ASP.NET MVC app). A: i really don't know how you are going to feel after 8 years but Now ASP MVC 5 supports attribute routing for easy to remember routes and to solved duplicate content problems for SEO Friendly sites just add routes.MapMvcAttributeRoutes(); in your RouteConfig and then define one and only route for each action like [Route("~/")] public ActionResult Index(int? page) { var query = from p in db.Posts orderby p.post_date descending select p; var pageNumber = page ?? 1; ViewData["Posts"] = query.ToPagedList(pageNumber, 7); return View(); } [Route("about")] public ActionResult About() { return View(); } [Route("contact")] public ActionResult Contact() { return View(); } [Route("team")] public ActionResult Team() { return View(); } [Route("services")] public ActionResult Services() { return View(); } A: Based on the answer from Gabe Sumner, but without redirects for JS, images and other content. Works only on controller actions. The idea is to do the redirect later in the pipeline when we already know its a route. For this we can use an ActionFilter. public class RedirectFilterAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { var url = filterContext.HttpContext.Request.Url; var urlWithoutQuery = url.GetLeftPart(UriPartial.Path); if (Regex.IsMatch(urlWithoutQuery, @"[A-Z]")) { string lowercaseURL = urlWithoutQuery.ToString().ToLower() + url.Query; filterContext.Result = new RedirectResult(lowercaseURL, permanent: true); } base.OnActionExecuting(filterContext); } } Note that the filter above does not redirect or change the casing for the query string. Then bind the ActionFilter globally to all actions by adding it to the GlobalFilterCollection. filters.Add(new RedirectFilterAttribute()); It is a good idea to still set the LowercaseUrls property to true on the RouteCollection.
{ "language": "en", "url": "https://stackoverflow.com/questions/170900", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: Is there a downside to adding an anonymous empty delegate on event declaration? I have seen a few mentions of this idiom (including on SO): // Deliberately empty subscriber public event EventHandler AskQuestion = delegate {}; The upside is clear - it avoids the need to check for null before raising the event. However, I am keen to understand if there are any downsides. For example, is it something that is in widespread use and is transparent enough that it won't cause a maintenance headache? Is there any appreciable performance hit of the empty event subscriber call? A: If you are doing it a /lot/, you might want to have a single, static/shared empty delegate that you re-use, simply to reduce the volume of delegate instances. Note that the compiler caches this delegate per event anyway (in a static field), so it is only one delegate instance per event definition, so it isn't a huge saving - but maybe worthwhile. The per-instance field in each class will still take the same space, of course. i.e. internal static class Foo { internal static readonly EventHandler EmptyEvent = delegate { }; } public class Bar { public event EventHandler SomeEvent = Foo.EmptyEvent; } Other than that, it seems fine. A: Instead of inducing performance overhead, why not use an extension method to alleviate both problems: public static void Raise(this EventHandler handler, object sender, EventArgs e) { if(handler != null) { handler(sender, e); } } Once defined, you never have to do another null event check again: // Works, even for null events. MyButtonClick.Raise(this, EventArgs.Empty); A: For systems that make heavy use of events and are performance-critical, you will definitely want to at least consider not doing this. The cost for raising an event with an empty delegate is roughly twice that for raising it with a null check first. Here are some figures running benchmarks on my machine: For 50000000 iterations . . . No null check (empty delegate attached): 530ms With null check (no delegates attached): 249ms With null check (with delegate attached): 452ms And here is the code I used to get these figures: using System; using System.Diagnostics; namespace ConsoleApplication1 { class Program { public event EventHandler<EventArgs> EventWithDelegate = delegate { }; public event EventHandler<EventArgs> EventWithoutDelegate; static void Main(string[] args) { //warm up new Program().DoTimings(false); //do it for real new Program().DoTimings(true); Console.WriteLine("Done"); Console.ReadKey(); } private void DoTimings(bool output) { const int iterations = 50000000; if (output) { Console.WriteLine("For {0} iterations . . .", iterations); } //with anonymous delegate attached to avoid null checks var stopWatch = Stopwatch.StartNew(); for (var i = 0; i < iterations; ++i) { RaiseWithAnonDelegate(); } stopWatch.Stop(); if (output) { Console.WriteLine("No null check (empty delegate attached): {0}ms", stopWatch.ElapsedMilliseconds); } //without any delegates attached (null check required) stopWatch = Stopwatch.StartNew(); for (var i = 0; i < iterations; ++i) { RaiseWithoutAnonDelegate(); } stopWatch.Stop(); if (output) { Console.WriteLine("With null check (no delegates attached): {0}ms", stopWatch.ElapsedMilliseconds); } //attach delegate EventWithoutDelegate += delegate { }; //with delegate attached (null check still performed) stopWatch = Stopwatch.StartNew(); for (var i = 0; i < iterations; ++i) { RaiseWithoutAnonDelegate(); } stopWatch.Stop(); if (output) { Console.WriteLine("With null check (with delegate attached): {0}ms", stopWatch.ElapsedMilliseconds); } } private void RaiseWithAnonDelegate() { EventWithDelegate(this, EventArgs.Empty); } private void RaiseWithoutAnonDelegate() { var handler = EventWithoutDelegate; if (handler != null) { handler(this, EventArgs.Empty); } } } } A: The only downside is a very slight performance penalty as you are calling extra empty delegate. Other than that there is no maintenance penalty or other drawback. A: It is my understanding that the empty delegate is thread safe, whereas the null check is not. A: There is no meaningful performance penalty to talk about, except, possibly, for some extreme situations. Note, however, that this trick becomes less relevant in C# 6.0, because the language provides an alternative syntax to calling delegates that may be null: delegateThatCouldBeNull?.Invoke(this, value); Above, null conditional operator ?. combines null checking with a conditional invocation. A: I would say it's a bit of a dangerous construct, because it tempts you to do something like : MyEvent(this, EventArgs.Empty); If the client throws an exception, the server goes with it. So then, maybe you do: try { MyEvent(this, EventArgs.Empty); } catch { } But, if you have multiple subscribers and one subscriber throws an exception, what happens to the other subscribers? To that end, I've been using some static helper methods that do the null check and swallows any exception from the subscriber side (this is from idesign). // Usage EventHelper.Fire(MyEvent, this, EventArgs.Empty); public static void Fire(EventHandler del, object sender, EventArgs e) { UnsafeFire(del, sender, e); } private static void UnsafeFire(Delegate del, params object[] args) { if (del == null) { return; } Delegate[] delegates = del.GetInvocationList(); foreach (Delegate sink in delegates) { try { sink.DynamicInvoke(args); } catch { } } } A: Instead of "empty delegate" approach one can define a simple extension method to encapsulate the conventional method of checking event handler against null. It is described here and here. A: One thing is missed out as an answer for this question so far: It is dangerous to avoid the check for the null value. public class X { public delegate void MyDelegate(); public MyDelegate MyFunnyCallback = delegate() { } public void DoSomething() { MyFunnyCallback(); } } X x = new X(); x.MyFunnyCallback = delegate() { Console.WriteLine("Howdie"); } x.DoSomething(); // works fine // .. re-init x x.MyFunnyCallback = null; // .. continue x.DoSomething(); // crashes with an exception The thing is: You never know who will use your code in which way. You never know, if in some years during a bug fix of your code the event/handler is set to null. Always, write the if check. Hope that helps ;) ps: Thanks for the performance calculation. pps: Edited it from a event case to and callback example. Thanks for the feedback ... I "coded" the example w/o Visual Studio and adjusted the example I had in mind to an event. Sorry for the confusion. ppps: Do not know if it still fits to the thread ... but I think it is an important principle. Please also check another thread of stackflow
{ "language": "en", "url": "https://stackoverflow.com/questions/170907", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "85" }
Q: Making a Nonblocking socket for WinSocks and *nix In C/C++, how would I turn a blocking socket into a non blocking socket in both WinSocks and *nix; so that select() would work correctly. You can use the pre-processor for the platform specific code. A: On linux: fcntl(fd, F_SETFL, O_NONBLOCK); Windows: u_long on = 1; ioctlsocket(fd, FIONBIO, &on); A: select() is supposed to work on blocking sockets. It returns when a read() would return immediately, which is always the case with non-blocking sockets.
{ "language": "en", "url": "https://stackoverflow.com/questions/170909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Is SVNAutoversioning directive in apache subversion imporant? If so why? I know setting this on will result in more number of automatically committed revisions. Is it good to have more auto commits? A: You can turn this on to offer WebDav mappings, most OSes can make network mappings to http(s):// URLs. If SVNAutoversioning is off, files cannot be saved to these mappings.
{ "language": "en", "url": "https://stackoverflow.com/questions/170913", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Replace an item in a list in Common Lisp? I have a list of things (I'll call it L), an index(N) and a new thing(NEW). If I want to replace the thing in L at N with NEW, what is the best way to do this? Should I get the sublist up to N and from N to the end of the list and then glue together a new list from the first part, NEW, and the last part using list? Or is there a better way to do this? A: How often are you going to do this; if you really want an array, you should use an array. Otherwise, yes, a function that makes a new list consisting of a copy of the first N elements, the new element, and the tail will be fine. I don't know of a builtin off the top of my head, but I haven't programmed in Lisp in a while. Here is a solution in Scheme (because I know that better than Common Lisp, and have an interpreter for checking my work): (define (replace-nth list n elem) (cond ((null? list) ()) ((eq? n 0) (cons elem (cdr list))) (#t (cons (car list) (replace-nth (cdr list) (- n 1) elem))))) A: (setf (nth N L) T) is the clearest, most succinct, and fastest way, if what you want to do is a "destructive" modification, i.e. actually change the existing list. It does not allocate any new memory. A: I just try to fix hazzen's code: (define (replace-nth list n elem) (cond ((null? list) ()) ((eq? n 0) (cons elem list)) (#t (cons(car list) (replace-nth (cdr list) (- n 1) elem))))) > (replace-nth (list 3 2 9 2) 2 8) (3 2 8 9 2) This code inserted new element in the list. If we want to replace an element: (define (replace-nth list n elem) (cond ((null? list) ()) ((eq? n 0) (cons elem (cdr list))) (#t (cons(car list) (replace-nth (cdr list) (- n 1) elem))))) > (replace-nth (list 3 2 9 2) 2 8) (3 2 8 2) 0 <= n <= length(list) - 1 A: hazzen's advice is good (use arrays) since you probably want to do a lot of these destructive updates and lists are very inefficient at random access. The easiest way to do this (setq A (make-array 5) :initial-contents '(4 3 0 2 1)) (setf (elt 2 A) 'not-a-number) where A is an array (although elt works for any sequence). * *The elt definition, with examples of setf. *The make-array definition, with examples However, if you must be functional, that is * *You want to keep around both the old and new lists *You want the old and new to share as much memory as possible. Then you should use the Common Lisp equivalent of hazzen's code: (defun replace1 (list n elem) (cond ((null list) ()) ((= n 0) (cons elem list)) (t (cons (car list) (replace1 (cdr list) (1- n) elem))))) This looks slow because it is, and that's probably why it's not included in the standard. hazzen's code is the Scheme version, which is useful is that's what you're using. A: (setf (nth N L) NEW) should do the trick. A: Sounds like you want either rplaca or replace. See http://www.lispworks.com/documentation/HyperSpec/Body/f_rplaca.htm or http://www.lispworks.com/documentation/HyperSpec/Body/f_replac.htm#replace A: Use [REPLACE][1] (I use X instead of your T as T is the true value in Lisp): (replace L (list X) :start1 N) [1]: http://www.lispworks.com/documentation/HyperSpec/Body/f_replac.htm REPLACE A: The obvious solution is slow and uses memory, as noted by others. If possible, you should try to defer replacing the element(s) until you need to perform another element-wise operation on the list, e.g. (loop for x in list do ...). That way, you'll amortize away the consing (memory) and the iteration (cpu). A: quickly you can do it with JS on list-replace A: (defun replace-nth-from-list (list n elem) (cond ((null list) ()) (t (append (subseq list 0 n) elem (subseq list (+ 1 n)(length list)))))) A: You can use the standard functions substitute-if (for immutable operation) or nsubstitute-if (for side effecting operation) to replace an item in a list: > (substitute-if 42 #'(lambda (x) (declare (ignore x)) t) '(1 2 3) :start 1 :count 1) (1 42 3) If you need a function often, which returns T no matter its argument, you could pretty this up by defining (defun aye (x) (declare (ignore x)) t) > (substitute-if 42 #'aye '(1 2 3) :start 1 :count 1) (1 42 3) Or just use this to write your own function: (defun replace-at (new-item index sequence) (substitute-if new-item #'aye sequence :start index :count 1))
{ "language": "en", "url": "https://stackoverflow.com/questions/170931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: Is it reasonable to use John Resig's Processing.js? I am thinking about making a website with some fairly intense JavaScript/canvas usage and I have been looking at Processing.js and it seems to me that it would make manipulating the canvas significantly easier. Does anyone know any reasons why I shouldn't use Processing.js? I understand that older browsers won't be able to use it, but for now that's ok. A: If you're OK with it not working in IE7, then go for it. I've had it working in Firefox 3. It's a slick way to bring Silverlight/Flash effects to your page. My hunch is that libraries like Processing.js will change or be upgraded on a fast track path, so get ready to run when they do and keep up with the new features. A: As mentioned, IE is not supported by Processing.js (including IE8 beta). I've also found processing.js to be a bit slow in terms of performance, compared to just using canvas (especially if you're parsing a string with Processing language, instead of using the javascript API). I personally prefer the canvas API over the processing wrapper, because it gives more me control. For example: The processing line() function is implemented like this (roughly): function line (x1, y1, x2, y2) { context.beginPath(); context.moveTo(x1, y1); context.lineTo(x2, y2); context.closePath(); context.stroke(); }; And you'd use it like this (assuming you're using the javascript-exposed API): var p = Processing("canvas") p.stroke(255) ////Draw lines.../// p.line(0,0,10,10) p.line(10,10,20,10) //...and so on p.line(100,100,200,200) ////End lines//// Notice that every line() call has to open and close a new path, whereas with the canvas API you can draw all the lines within a single beginPath/endPath block, improving performance significantly: context.strokeStyle = "#fff"; context.beginPath(); ////Draw lines.../// context.moveTo(0, 0); context.lineTo(10, 10); context.lineTo(20, 10); //...so on context.lineTo(200, 200); ////End lines.../// context.closePath(); context.stroke(); A: It doesn't simplify drawing on your canvas. What it does do is simplify the task of animation if you are using canvas. If you are doing animation and you don't care about full browser support then use Processing.js. If you are not doing animation (if you are doing charting or rounded corners for example) then don't add the overhead of Processing.js. Either way, I recommend that you learn how to use the canvas API directly. Understanding the canvas api, especially transformations, will greatly help you even if you are using Processing.js. A: I'd say use Flash instead. More browsers have Flash installed, than the number of browsers that work with processing.js. In addition, you'll get much better performance from Flash versus using JavaScript (at least for now, though there are projects in the works to speed up JS a lot, but it's still a little ways off) A: Try the new javascript implementation p5js p5js.org Oh and in response to Leo's answer, you actually don't have to use the line function in processing or p5js, there are separate beingShape and beingPath functions similar to the canvas api.
{ "language": "en", "url": "https://stackoverflow.com/questions/170937", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: What is the default time after which an HTTP request is deemed to have timed out? For PHP, what is the default time after which an HTTP request is deemed to have timed out? I'm using the PECL HTTP extension to make HTTP requests. I can set a timeout limit when making a request, however I'd like to know what the default is if nothing is explicitly specified. I've hunted through the PHP manual to no avail. I'd appreciate answers supported by evidence, such as a link to the relevant manual page, as opposed to speculative suggestions. I'm keen to find out what the default timeout actually is not just what it probably is. I can guess it may probably be 30 seconds as this seems a reasonable value, however I can find nothing to confirm or deny this. A: I'm quite sure what you're looking for is the default_socket_timeout php.ini option. It appears the default is 60 seconds. A: Just for future reference: http://svn.php.net/viewvc/pecl/http/trunk/http_request_api.c?view=markup If I understood it correctly, the default timeout options values are: * *timeout = CURLOPT_TIMEOUT_MS | CURLOPT_TIMEOUT = 0 (means "waits indefinitely") *connecttimeout = CURLOPT_CONNECTTIMEOUT_MS | CURLOPT_CONNECTTIMEOUT = 3 *dns_cache_timeout = CURLOPT_DNS_CACHE_TIMEOUT = 60
{ "language": "en", "url": "https://stackoverflow.com/questions/170938", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to specify the hardware your software needs? That is a problem I'm facing right now. I need to specify the hardware that will run my piece of software. The thing is: the project isn't finished yet, and I need it running in "real" conditions before I can go on, conditions which I cannot reproduce at home; what I can test at home barely scratches them. We don't have much money to spend (it's a research at college). Feels like a catch-22. How can one get a good approximation of what setup is needed without having the means to simulate accurate work conditions? A: If you need to test your setup on a machine with less specifications then your own machine then you could use a virtual pc setup to test it and just keep reducing the virtual pc settings until your software stops performing adequately. If its the other way around, then I think, as Paul said, its a case of begging or borrowing until you get what you need. A: Can't you beg, borrow or steal the biggest hardware you can get, and then once it's in those "real" conditions, start reducing the capacity either by hardware changes (removing memory, underclocking) or by software (running other programs that consume memory or CPU cycles) until you find a point where it doesn't work as well as desired, and then specify a minimum hardware level that will meet or exceed those conditions? A: Not sure why this popped to the top of my list today, but allow me to also suggest: Rent an Amazon | RackSpace cloud instance that “sounds big enough” and try your app out on it. You can get a pretty good approximation of whatever hardware scale you'd like — if you're talking in the range of PC-type hardware, and not, “I think we're gonna need a couple of Crays in here…”
{ "language": "en", "url": "https://stackoverflow.com/questions/170939", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Find out what is the new data from an RSS feed, compared with entries already in the database. Then put new entries in db. How? Let's say I have a database, and an RSS feed. I have to find out what is the new data from an RSS feed, that isn't already in the database. How would you go about approaching this problem? A: How about generating a hashcode or some unique identifier to each RSS item, then storing it in the database? Then you just generate the hashcode for each item in the new RSS, and check it against the database. A: First you have to uniquely identify each item. This is problematic because some sites use the guid element and some sites don't, and for some items the link element never changes and for some it does. I think that the general rule of thumb is that if an item has a guid you use that as the key, otherwise you use the link as the key and hope. Once you've established the key for an item, you can (probably) determine whether the item you're looking at has been updated by examining the pubDate element, which ought to be updated if the story gets updated. This approach will handle most cases, though as with everything related to RSS it breaks down if the feed provider isn't behaving properly. A: Most RSS feeds will have a date with each story - so, make a query to pull the latest story's date from the database, pull all of the latest stories from the RSS feed, and compare dates. It also depends on whether this is for one particular feed or if you are writing something that will work for many feeds. If it's supposed to work for all feeds, use one of the hashing methods; create a hash of the title and date and use this as a unique identifier. A: Pull from a unique field of a particular item in the rss feed. Then check to see if that item is already in the db. Run this logic in a loop. A: Off hand, a few suggestions: * *Perform a check sum on each item in the feed, store the result in the database. Compare the results in database with each new file / stream from the RSS source. *Hash the title. date and time for each item and store in the database. Compare with each refreshed RSS stream.
{ "language": "en", "url": "https://stackoverflow.com/questions/170950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I find which operating system my Ruby program is running on? I want my Ruby program to do different things on a Mac than on Windows. How can I find out on which system my program is running? A: Try the Launchy gem (gem install launchy): require 'launchy' Launchy::Application.new.host_os_family # => :windows, :darwin, :nix, or :cygwin A: For something readily accessible in most Ruby installations that is already somewhat processed for you, I recommend these: * *Gem::Platform.local.os #=> eg. "mingw32", "java", "linux", "cygwin", "aix", "dalvik" (code) *Gem.win_platform? #=> eg. true, false (code) Both these and every other platform checking script I know is based on interpreting these underlying variables: * *RbConfig::CONFIG["host_os"] #=> eg. "linux-gnu" (code 1, 2) *RbConfig::CONFIG["arch"] #=> eg. "i686-linux", "i386-linux-gnu" (passed as parameter when the Ruby interpreter is compiled) *RUBY_PLATFORM #=> eg. "i386-linux-gnu", "darwin" - Note that this returns "java" in JRuby! (code) * *These are all Windows variants: /cygwin|mswin|mingw|bccwin|wince|emx/ *RUBY_ENGINE #=> eg. "ruby", "jruby" Libraries are available if you don't mind the dependency and want something a little more user-friendly. Specifically, OS offers methods like OS.mac? or OS.posix?. Platform can distinguish well between a variety of Unix platforms. Platform::IMPL will return, eg. :linux, :freebsd, :netbsd, :hpux. sys-uname and sysinfo are similar. utilinfo is extremely basic, and will fail on any systems beyond Windows, Mac, and Linux. If you want more advanced libraries with specific system details, like different Linux distributions, see my answer for Detecting Linux distribution in Ruby. A: Update! Addition! Rubygems nowadays ships with Gem.win_platform?. Example usages in the Rubygems repo, and this one, for clarity: def self.ant_script Gem.win_platform? ? 'ant.bat' : 'ant' end A: require 'rbconfig' include Config case CONFIG['host_os'] when /mswin|windows/i # Windows when /linux|arch/i # Linux when /sunos|solaris/i # Solaris when /darwin/i #MAC OS X else # whatever end A: (Warning: read @Peter Wagenet's comment ) I like this, most people use rubygems, its reliable, is cross platform irb(main):001:0> Gem::Platform.local => #<Gem::Platform:0x151ea14 @cpu="x86", @os="mingw32", @version=nil> irb(main):002:0> Gem::Platform.local.os => "mingw32" update use in conjunction with "Update! Addition! Rubygems nowadays..." to mitigate when Gem::Platform.local.os == 'java' A: We have been doing pretty good so far with the following code def self.windows? return File.exist? "c:/WINDOWS" if RUBY_PLATFORM == 'java' RUBY_PLATFORM =~ /mingw32/ || RUBY_PLATFORM =~ /mswin32/ end def self.linux? return File.exist? "/usr" if RUBY_PLATFORM == 'java' RUBY_PLATFORM =~ /linux/ end def self.os return :linux if self.linux? return :windows if self.windows? nil end A: Either irb(main):002:0> require 'rbconfig' => true irb(main):003:0> Config::CONFIG["arch"] => "i686-linux" or irb(main):004:0> RUBY_PLATFORM => "i686-linux" A: Use the RUBY_PLATFORM constant, and optionally wrap it in a module to make it more friendly: module OS def OS.windows? (/cygwin|mswin|mingw|bccwin|wince|emx/ =~ RUBY_PLATFORM) != nil end def OS.mac? (/darwin/ =~ RUBY_PLATFORM) != nil end def OS.unix? !OS.windows? end def OS.linux? OS.unix? and not OS.mac? end def OS.jruby? RUBY_ENGINE == 'jruby' end end It is not perfect, but works well for the platforms that I do development on, and it's easy enough to extend. A: I have a second answer, to add more options to the fray. The os rubygem, and their github page has a related projects list. require 'os' >> OS.windows? => true # or OS.doze? >> OS.bits => 32 >> OS.java? => true # if you're running in jruby. Also OS.jruby? >> OS.ruby_bin => "c:\ruby18\bin\ruby.exe" # or "/usr/local/bin/ruby" or what not >> OS.posix? => false # true for linux, os x, cygwin >> OS.mac? # or OS.osx? or OS.x? => false A: Using the os gem, when loading different binaries for IMGKit # frozen_string_literal: true IMGKit.configure do |config| if OS.linux? && OS.host_cpu == "x86_64" config.wkhtmltoimage = Rails.root.join("bin", "wkhtmltoimage-linux-amd64").to_s elsif OS.mac? && OS.host_cpu == "x86_64" config.wkhtmltoimage = Rails.root.join("bin", "wkhtmltoimage-macos-amd64").to_s else puts OS.report abort "You need to add a binary for wkhtmltoimage for your OS and CPU" end end A: When I just need to know if it is a Windows or Unix-like OS it is often enough to is_unix = is_win = false File::SEPARATOR == '/' ? is_unix = true : is_win = true
{ "language": "en", "url": "https://stackoverflow.com/questions/170956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "95" }
Q: What's the strategy for handling CRLF (carriage return, line feed) with Git? I tried committing files with CRLF-ending lines, but it failed. I spent a whole work day on my Windows computer trying different strategies and was almost drawn to stop trying to use Git and instead try Mercurial. How to properly handle CRLF line endings? A: You almost always want autocrlf=input unless you really know what you are doing. Some additional context below: It should be either core.autocrlf=true if you like DOS ending or core.autocrlf=input if you prefer unix-newlines. In both cases, your Git repository will have only LF, which is the Right Thing. The only argument for core.autocrlf=false was that automatic heuristic may incorrectly detect some binary as text and then your tile will be corrupted. So, core.safecrlf option was introduced to warn a user if a irreversable change happens. In fact, there are two possibilities of irreversable changes -- mixed line-ending in text file, in this normalization is desirable, so this warning can be ignored, or (very unlikely) that Git incorrectly detected your binary file as text. Then you need to use attributes to tell Git that this file is binary. The above paragraph was originally pulled from a thread on gmane.org, but it has since gone down. A: Almost four years after asking this question, I have finally found an answer that completely satisfies me! See the details in github:help's guide to Dealing with line endings. Git allows you to set the line ending properties for a repo directly using the text attribute in the .gitattributes file. This file is committed into the repo and overrides the core.autocrlf setting, allowing you to ensure consistent behaviour for all users regardless of their git settings. And thus The advantage of this is that your end of line configuration now travels with your repository and you don't need to worry about whether or not collaborators have the proper global settings. Here's an example of a .gitattributes file # Auto detect text files and perform LF normalization * text=auto *.cs text diff=csharp *.java text diff=java *.html text diff=html *.css text *.js text *.sql text *.csproj text merge=union *.sln text merge=union eol=crlf *.docx diff=astextplain *.DOCX diff=astextplain # absolute paths are ok, as are globs /**/postinst* text eol=lf # paths that don't start with / are treated relative to the .gitattributes folder relative/path/*.txt text eol=lf There is a convenient collection of ready to use .gitattributes files for the most popular programming languages. It's useful to get you started. Once you've created or adjusted your .gitattributes, you should perform a once-and-for-all line endings re-normalization. Note that the GitHub Desktop app can suggest and create a .gitattributes file after you open your project's Git repo in the app. To try that, click the gear icon (in the upper right corner) > Repository settings ... > Line endings and attributes. You will be asked to add the recommended .gitattributes and if you agree, the app will also perform a normalization of all the files in your repository. Finally, the Mind the End of Your Line article provides more background and explains how Git has evolved on the matters at hand. I consider this required reading. You've probably got users in your team who use EGit or JGit (tools like Eclipse and TeamCity use them) to commit their changes. Then you're out of luck, as @gatinueta explained in this answer's comments: This setting will not satisfy you completely if you have people working with Egit or JGit in your team, since those tools will just ignore .gitattributes and happily check in CRLF files https://bugs.eclipse.org/bugs/show_bug.cgi?id=342372 One trick might be to have them commit their changes in another client, say SourceTree. Our team back then preferred that tool to Eclipse's EGit for many use cases. Who said software is easy? :-/ A: These are the two options for Windows and Visual Studio users that share code with Mac or Linux users. For an extended explanation, read the gitattributes manual. * text=auto In your repo's .gitattributes file add: * text=auto This will normalize all the files with LF line endings in the repo. And depending on your operating system (core.eol setting), files in the working tree will be normalized to LF for Unix based systems or CRLF for Windows systems. This is the configuration that Microsoft .NET repos use. Example: Hello\r\nWorld Will be normalized in the repo always as: Hello\nWorld On checkout, the working tree in Windows will be converted to: Hello\r\nWorld On checkout, the working tree in Mac will be left as: Hello\nWorld Note: If your repo already contains files not normalized, git status will show these files as completely modified the next time you make any change on them, and it could be a pain for other users to merge their changes later. See refreshing a repository after changing line endings for more information. core.autocrlf = true If text is unspecified in the .gitattributes file, Git uses the core.autocrlf configuration variable to determine if the file should be converted. For Windows users, git config --global core.autocrlf true is a great option because: * *Files are normalized to LF line endings only when added to the repo. If there are files not normalized in the repo, this setting will not touch them. *All text files are converted to CRLF line endings in the working directory. The problem with this approach is that: * *If you are a Windows user with autocrlf = input, you will see a bunch of files with LF line endings. Not a hazard for the rest of the team, because your commits will still be normalized with LF line endings. *If you are a Windows user with core.autocrlf = false, you will see a bunch of files with LF line endings and you may introduce files with CRLF line endings into the repo. *Most Mac users use autocrlf = input and may get files with CRLF file endings, probably from Windows users with core.autocrlf = false. A: Two alternative strategies to get consistent about line-endings in mixed environments (Microsoft + Linux + Mac): A. Global All Repositories Setup * *Convert all to one format find . -type f -not -path "./.git/*" -exec dos2unix {} \; git commit -a -m 'dos2unix conversion' *Set core.autocrlf to input on Linux/UNIX or true on MS Windows (repository or global) git config --global core.autocrlf input *Optionally, set core.safecrlf to true (to stop) or warn (to sing:) to add extra guard comparing if the reversed newline transformation would result in the same file git config --global core.safecrlf true B. Or per Repository Setup * *Convert all to one format find . -type f -not -path "./.git/*" -exec dos2unix {} \; git commit -a -m 'dos2unix conversion' *Add a .gitattributes file to your repository echo "* text=auto" > .gitattributes git add .gitattributes git commit -m 'adding .gitattributes for unified line-ending' Don't worry about your binary files—Git should be smart enough about them. More about safecrlf/autocrlf variables A: This is just a workaround solution: In normal cases, use the solutions that are shipped with git. These work great in most cases. Force to LF if you share the development on Windows and Unix based systems by setting .gitattributes. In my case there were >10 programmers developing a project in Windows. This project was checked in with CRLF and there was no option to force to LF. Some settings were internally written on my machine without any influence on the LF format; thus some files were globally changed to LF on each small file change. My solution: Windows-Machines: Let everything as it is. Care about nothing, since you are a default windows 'lone wolf' developer and you have to handle like this: "There is no other system in the wide world, is it?" Unix-Machines * *Add following lines to a config's [alias] section. This command lists all changed (i.e. modified/new) files: lc = "!f() { git status --porcelain \ | egrep -r \"^(\?| ).\*\\(.[a-zA-Z])*\" \ | cut -c 4- ; }; f " *Convert all those changed files into dos format: unix2dos $(git lc) *Optionally ... * *Create a git hook for this action to automate this process *Use params and include it and modify the grep function to match only particular filenames, e.g.: ... | egrep -r "^(\?| ).*\.(txt|conf)" | ... *Feel free to make it even more convenient by using an additional shortcut: c2dos = "!f() { unix2dos $(git lc) ; }; f " ... and fire the converted stuff by typing git c2dos A: --- UPDATE 3 --- (does not conflict with UPDATE 2) Considering the case that windows users prefer working on CRLF and linux/mac users prefer working on LF on text files. Providing the answer from the perspective of a repository maintainer: For me the best strategy(less problems to solve) is: keep all text files with LF inside git repo even if you are working on a windows-only project. Then give the freedom to clients to work on the line-ending style of their preference, provided that they pick a core.autocrlf property value that will respect your strategy (LF on repo) while staging files for commit. Staging is what many people confuse when trying to understand how newline strategies work. It is essential to undestand the following points before picking the correct value for core.autocrlf property: * *Adding a text file for commit (staging it) is like copying the file to another place inside .git/ sub-directory with converted line-endings (depending on core.autocrlf value on your client config). All this is done locally. *setting core.autocrlf is like providing an answer to the question (exact same question on all OS): "Should git-client: * *a. convert LF-to-CRLF when checking-out (pulling) the repo changes from the remote? *b. convert CRLF-to-LF when adding a file for commit?" *and the possible answers (values) are: * *false: "do none of the above", *input: "do only b" *true: "do a and and b" *note that there is NO "do only a" Fortunately * *git client defaults (windows: core.autocrlf: true, linux/mac: core.autocrlf: false) will be compatible with LF-only-repo strategy. Meaning: windows clients will by default convert to CRLF when checking-out the repository and convert to LF when adding for commit. And linux clients will by default not do any conversions. This theoretically keeps your repo lf-only. Unfortunately: * *There might be GUI clients that do not respect the git core.autocrlf value *There might be people that don't use a value to respect your lf-repo strategy. E.g. they use core.autocrlf=false and add a file with CRLF for commit. To detect ASAP non-lf text files committed by the above clients you can follow what is described on --- update 2 ---: (git grep -I --files-with-matches --perl-regexp '\r' HEAD, on a client compiled using: --with-libpcre flag) And here is the catch:. I as a repo maintainer keep a git.autocrlf=input so that I can fix any wrongly committed files just by adding them again for commit. And I provide a commit text: "Fixing wrongly committed files". As far as .gitattributes is concearned. I do not count on it, because there are more ui clients that do not understand it. I only use it to provide hints for text and binary files, and maybe flag some exceptional files that should everywhere keep the same line-endings: *.java text !eol # Don't do auto-detection. Treat as text (don't set any eol rule. use client's) *.jpg -text # Don't do auto-detection. Treat as binary *.sh text eol=lf # Don't do auto-detection. Treat as text. Checkout and add with eol=lf *.bat text eol=crlf # Treat as text. Checkout and add with eol=crlf Question: But why are we interested at all in newline handling strategy? Answer: To avoid a single letter change commit, appear as a 5000-line change, just because the client that performed the change auto-converted the full file from crlf to lf (or the opposite) before adding it for commit. This can be rather painful when there is a conflict resolution involved. Or it could in some cases be the cause of unreasonable conflicts. --- UPDATE 2 --- The dafaults of git client will work in most cases. Even if you only have windows only clients, linux only clients or both. These are: * *windows: core.autocrlf=true means convert lines to CRLF on checkout and convert lines to LF when adding files. *linux: core.autocrlf=input means don't convert lines on checkout (no need to since files are expected to be committed with LF) and convert lines to LF (if needed) when adding files. (-- update3 -- : Seems that this is false by default, but again it is fine) The property can be set in different scopes. I would suggest explicitly setting in the --global scope, to avoid some IDE issues described at the end. git config core.autocrlf git config --global core.autocrlf git config --system core.autocrlf git config --local core.autocrlf git config --show-origin core.autocrlf Also I would strongly discourage using on windows git config --global core.autocrlf false (in case you have windows only clients) in contrast to what is proposed to git documentation. Setting to false will commit files with CRLF in the repo. But there is really no reason. You never know whether you will need to share the project with linux users. Plus it's one extra step for each client that joins the project instead of using defaults. Now for some special cases of files (e.g. *.bat *.sh) which you want them to be checked-out with LF or with CRLF you can use .gitattributes To sum-up for me the best practice is: * *Make sure that every non-binary file is committed with LF on git repo (default behaviour). *Use this command to make sure that no files are committed with CRLF: git grep -I --files-with-matches --perl-regexp '\r' HEAD (Note: on windows clients works only through git-bash and on linux clients only if compiled using --with-libpcre in ./configure). *If you find any such files by executing the above command, correct them. This in involves (at least on linux): * *set core.autocrlf=input (--- update 3 --) *change the file *revert the change(file is still shown as changed) *commit it *Use only the bare minimum .gitattributes *Instruct the users to set the core.autocrlf described above to its default values. *Do not count 100% on the presence of .gitattributes. git-clients of IDEs may ignore them or treat them differrently. As said some things can be added in git attributes: # Always checkout with LF *.sh text eol=lf # Always checkout with CRLF *.bat text eol=crlf I think some other safe options for .gitattributes instead of using auto-detection for binary files: * *-text (e.g for *.zip or *.jpg files: Will not be treated as text. Thus no line-ending conversions will be attempted. Diff might be possible through conversion programs) *text !eol (e.g. for *.java,*.html: Treated as text, but eol style preference is not set. So client setting is used.) *-text -diff -merge (e.g for *.hugefile: Not treated as text. No diff/merge possible) --- PREVIOUS UPDATE --- One painful example of a client that will commit files wrongly: netbeans 8.2 (on windows), will wrongly commit all text files with CRLFs, unless you have explicitly set core.autocrlf as global. This contradicts to the standard git client behaviour, and causes lots of problems later, while updating/merging. This is what makes some files appear different (although they are not) even when you revert. The same behaviour in netbeans happens even if you have added correct .gitattributes to your project. Using the following command after a commit, will at least help you detect early whether your git repo has line ending issues: git grep -I --files-with-matches --perl-regexp '\r' HEAD I have spent hours to come up with the best possible use of .gitattributes, to finally realize, that I cannot count on it. Unfortunately, as long as JGit-based editors exist (which cannot handle .gitattributes correctly), the safe solution is to force LF everywhere even on editor-level. Use the following anti-CRLF disinfectants. * *windows/linux clients: core.autocrlf=input *committed .gitattributes: * text=auto eol=lf *committed .editorconfig (http://editorconfig.org/) which is kind of standardized format, combined with editor plugins: * *https://github.com/editorconfig/ *https://github.com/welovecoding/editorconfig-netbeans/ A: Don't convert line endings. It's not the VCS's job to interpret data -- just store and version it. Every modern text editor can read both kinds of line endings anyway. A: Using core.autocrlf=false stopped all the files from being marked updated as soon as I checked them out in my Visual Studio 2010 project. The other two members of the development team are also using Windows systems so a mixed environment didn't come into play, yet the default settings that came with the repository always marked all files as updated immediately after cloning. I guess the bottom line is to find what CRLF setting works for your environment. Especially since in many other repositories on our Linux boxes setting autocrlf = true produces better results. 20+ years later and we're still dealing with line ending disparities between OSes... sad. A: Try setting the core.autocrlf configuration option to true. Also have a look at the core.safecrlf option. Actually it sounds like core.safecrlf might already be set in your repository, because (emphasis mine): If this is not the case for the current setting of core.autocrlf, git will reject the file. If this is the case, then you might want to check that your text editor is configured to use line endings consistently. You will likely run into problems if a text file contains a mixture of LF and CRLF line endings. Finally, I feel that the recommendation to simply "use what you're given" and use LF terminated lines on Windows will cause more problems than it solves. Git has the above options to try to handle line endings in a sensible way, so it makes sense to use them.
{ "language": "en", "url": "https://stackoverflow.com/questions/170961", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "673" }
Q: What's the difference between session.Merge and session.SaveOrUpdate? I notice sometimes with my parent/child objects or many-to-many relationships, I need to call either SaveOrUpdate or Merge. Usually, when I need to call SaveOrUpdate, the exception I get on calling Merge has to do with transient objects not being saved first. Please explain the difference between the two. A: As I understand it, merge() will take an object that may not be associated with the current session, and copy its state (property values, etc.) to an object that is associated with the current session (with the same PK value/identifier, of course). saveOrUpdate() will call Save or Update on your session, based on a given object's identity value. A: SaveOrUpdateCopy() is now deprecated as of NHibernate 3.1. Merge() should be used instead. A: ** Update()** :- if you are sure that the session does not contains an already persistent instance with the same identifier then use update to save the data in hibernate ** Merge()** :-if you want to save your modifications at any time with out knowing about the state of an session then use merge() in hibernate. A: This is from section 10.7. Automatic state detection of the Hibernate Reference Documentation: saveOrUpdate() does the following: * *if the object is already persistent in this session, do nothing *if another object associated with the session has the same identifier, throw an exception *if the object has no identifier property, save() it *if the object's identifier has the value assigned to a newly instantiated object, save() it *if the object is versioned (by a <version> or <timestamp>), and the version property value is the same value assigned to a newly instantiated object, save() it *otherwise update() the object and merge() is very different: * *if there is a persistent instance with the same identifier currently associated with the session, copy the state of the given object onto the persistent instance *if there is no persistent instance currently associated with the session, try to load it from the database, or create a new persistent instance *the persistent instance is returned *the given instance does not become associated with the session, it remains detached You should use Merge() if you are trying to update objects that were at one point detached from the session, especially if there might be persistent instances of those objects currently associated with the session. Otherwise, using SaveOrUpdate() in that case would result in an exception. A: I found this link that did a pretty good job explaining this type of exception: What worked for me is the following: * *In the mapping Myclass.hbm.xml file, set cascade="merge" *SaveOrUpdate the child/dependent object first before assigning it to the parent object. *SaveOrUpdate the parent object. However, this solution has limitations. i.e., you have to take care of saving your child/dependent object instead of letting hibernate doing that for you. If anyone has a better solution, I'd like to see. A: @Entity @Table(name="emp") public class Employee implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="emp_id") private int id; @Column(name="emp_name") private String name; @Column(name="salary") private int Salary; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSalary() { return Salary; } public void setSalary(int salary) { this.Salary = salary; } public int getId() { return id; } public void setId(int id) { this.id = id; } } public enum HibernateUtil { INSTANCE; HibernateUtil(){ buildSessionFactory(); } private SessionFactory sessionFactory=null; public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } private void buildSessionFactory() { Configuration configuration = new Configuration(); configuration.addAnnotatedClass (TestRefresh_Merge.Employee.class); configuration.setProperty("connection.driver_class","com.mysql.jdbc.Driver"); configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/hibernate"); configuration.setProperty("hibernate.connection.username", "root"); configuration.setProperty("hibernate.connection.password", "root"); configuration.setProperty("dialect", "org.hibernate.dialect.MySQLDialect"); configuration.setProperty("hibernate.hbm2ddl.auto", "update"); configuration.setProperty("hibernate.show_sql", "true"); configuration.setProperty(" hibernate.connection.pool_size", "10"); /* configuration.setProperty(" hibernate.cache.use_second_level_cache", "true"); configuration.setProperty(" hibernate.cache.use_query_cache", "true"); configuration.setProperty(" cache.provider_class", "org.hibernate.cache.EhCacheProvider"); configuration.setProperty("hibernate.cache.region.factory_class" ,"org.hibernate.cache.ehcache.EhCacheRegionFactory"); */ // configuration StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()); sessionFactory = configuration.buildSessionFactory(builder.build()); setSessionFactory(sessionFactory); } public static SessionFactory getSessionFactoryInstance(){ return INSTANCE.getSessionFactory(); } } public class Main { public static void main(String[] args) { HibernateUtil util=HibernateUtil.INSTANCE; SessionFactory factory=util.getSessionFactory(); //save(factory); retrieve(factory); } private static void retrieve(SessionFactory factory) { Session sessionOne=factory.openSession(); Employee employee=(Employee)sessionOne.get(Employee.class, 5); sessionOne.close(); // detached Entity employee.setName("Deepak1"); Session sessionTwo=factory.openSession(); Employee employee1=(Employee)sessionTwo.get(Employee.class, 5); sessionTwo.beginTransaction(); sessionTwo.saveOrUpdate(employee); // it will throw exception //sessionTwo.merge(employee); // it will work sessionTwo.getTransaction().commit(); sessionTwo.close(); } private static void save(SessionFactory factory) { Session sessionOne=factory.openSession(); Employee emp=new Employee(); emp.setName("Abhi"); emp.setSalary(10000); sessionOne.beginTransaction(); try{ sessionOne.save(emp); sessionOne.getTransaction().commit(); }catch(Exception e){ e.printStackTrace(); }finally{ sessionOne.close(); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/170962", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "89" }
Q: One to One database relation? In my free time I started writing a small multiplayer game with a database backend. I was looking to separate player login information from other in game information (inventory, stats, and status) and a friend brought up this might not be the best idea. Would it be better to lump everything together in one table? A: Relational databases work on sets, a database query is there to deliver none ("not found") or more results. A relational database is not intended to deliver always exactly one result by executing a query (on relations). Said that I want to mention that there is real life, too ;-) . A one-to-one relation might make sense, i.e. if the column count of the table reaches a critical level it might be faster to split this table. But these kind of conditions really are rare. If you do not really need to split the table just don't do it. At least I assume that in your case you would have to do a select over two tables to get all data. This probably is slower than storing all in one table. And your programming logic will at least get a little bit less readable by doing so. Edith says: Commenting on normalization: Well, I never saw a database normalized to it's max and no-one is really recommending that as an option. Anyway, if you do not exactly know if any columns will be normalized (i.e. put in other tables) later on, then it too is easier to do this with one table instead of "table"-one-to-one-"other table" A: Whether to keep player login information [separate] from other in game information (inventory, stats, and status) is often a question of normalization. You may want to take a quick look at the wikipedia (Third Normal Form, Denormalization) definitions. Whether you separate these into multiple tables depends on what data is stored. Expanding your question will make this concrete. Data that we want to store is: * *username: unique name that allows a user to login to the system *passwd: password: associated with the username that guarantees the user is unique *email: email address for the user; so the game can "poke" the user when they haven't played recently *character: possibly separate ingame name for the character *status: is the player and/or character currently active *hitpoints: an example stat for the character We could store this as a single table or as multiple tables. Single Table Example If players have a single character in this game world, then a single table may be appropriate. For example, CREATE TABLE players( id INTEGER NOT NULL, username VARCHAR2(32) NOT NULL, password VARCHAR2(32) NOT NULL, email VARCHAR2(160), character VARCHAR2(32) NOT NULL, status VARCHAR2(32), hitpoints INTEGER, CONSTRAINT pk_players PRIMARY KEY (uid) ); This would allow you to find all of the pertinent information about a player with a single query on the players table. Multiple Table Example However, if you wanted to allow a single player to have multiple different characters you would want to split this data across two different tables. For example you might do the following: -- track information on the player CREATE TABLE players( id INTEGER NOT NULL, username VARCHAR2(32) NOT NULL, password VARCHAR2(32) NOT NULL, email VARCHAR2(160), CONSTRAINT pk_players PRIMARY KEY (id) ); -- track information on the character CREATE TABLE characters( id INTEGER NOT NULL, player_id INTEGER NOT NULL, character VARCHAR2(32) NOT NULL, status VARCHAR2(32), hitpoints INTEGER, CONSTRAINT pk_characters PRIMARY KEY (id) ); -- foreign key reference ALTER TABLE characters ADD CONSTRAINT characters__players FOREIGN KEY (player_id) REFERENCES players (id); This format does require joins when looking at information for both the player and character; however, it makes updating records less likely to result in inconsistency. This latter argument is typically used when advocating for multiple tables. For example, if you had a player (LotRFan) with two characters (gollum, frodo) in the single table format you would have the username, password, email fields duplicated. If the player wanted to change his email/password, you would need to modify both records. If only one record was modified the table will become inconsistent. However, if LotRFan wanted to change his password in the multiple table format a single row in the table is updated. Other Considerations Whether to use a single table or multiple tables depends on the underlying data. What hasn't been described here but was noted in other answers is that optimizations often will take two tables and combine them into a single table. Also of interest is knowing the types of changes that will be made. For example, if you were to choose to use a single table for players who might have multiple characters and wanted to keep track of total number of commands issued by the player by incrementing a field in the players table; this would result in more rows being updated in the single table example. A: Inventory is a many-to-one relationship anyway, so probably deserves its own table (indexed on its foreign key at least). You may also want to have personal stuff for each user separate from public stuff (i.e., what others can see of you). That may provide better cache-hits, since many people will see your public attributes, but only you see your personal attributes. A: Start by ignoring performance, and just create the most logical and easy-to-understand database design that you can. If players and game objects (swords? chess pieces?) are separate things conceptually, then put them in separate tables. If a player can carry things, you put a foreign key in the "things" table that references the "players" table. And so on. Then, when you have hundreds of players and thousands of things, and the players run around in the game and do things that require database searches, well, your design will still be fast enough, if you just add the appropriate indexes. Of course, if you plan for thousands of simultaneous players, each of them inventorying his things every second, or perhaps some other enormous load of database searches (a search for each frame rendered by the graphics engine?) then you will need to think about performance. But in that case, a typical disk-based relational database will not be fast enough anyway, no matter how you design your tables. A: A 1-1 relationship is just a vertical split. Nothing else. do it if you for some reason you won't store all the data in the same table (say for partitioning across multiple servers etc) A: As you can see, the general consensus on this is that "it depends". Performance/query optimisation easily comes to mind - as mentioned by @Campbell and others. But I think for the kind of application-specific database you are building, it is best to start by considering the overall application design. For application-specific databases (as opposed to databases designed to be used with many apps or reporting tools), the 'ideal' data model is probably the one that best maps to your domain model as implemented in your application code. You may not call your design MVC, and I don't know what language you are using, but I expect you have some code or classes that wraps the data access with a logical model. How you view the application design at this level is I think the best indicator of how your database should ideally be structured. In general, this means a one-to-one mapping of domain objects to database tables is the best place to start. I think best to illustrate what I mean by example: Case 1: One Class / One Table You think in terms of a Player class. Player.authenticate, Player.logged_in?, Player.status, Player.hi_score, Player.gold_credits. As long as all these are actions on a single user, or represent single-value attributes of a user, then a single table should be your starting point from a logical application design perspective. Single class (Player), single table (players). Case 2: Multiple Class / One or more tables Maybe I don't like the swiss-army-knife Player class design, but prefer to think in terms of User, Inventory, Scoreboard and Account. User.authenticate, User.logged_in?, User->account.status, Scoreboard.hi_score(User), User->account.gold_credits. I'm probably doing this because I think separating these concepts in the domain model is going to make my code clearer and easier to write. In this case, the best starting point is a direct mapping of the domain classes to individual tables: Users, Inventory, Scores, Accounts etc. Making the 'Ideal' Practical I slipped some words in above to indicate that the one-one mapping of domain objects to tables is the ideal, logical design. That is my preferred starting point. Trying to be too smart off the bat - like mapping multiple classes back to a single table - tends to just invite trouble I'd prefer to avoid (deadlocks and concurrency issues especially). But it's not always the end of the story. There are practical considerations that can mean a separate activity to optimize the physical data model is needed e.g. concurrency/locking issues? row size getting too large? indexing overhead? query performance etc. Be careful when thinking about performance though: just because it may be one row in one table, probably doesn't mean it is queried just once to get the whole row. I imagine the multiuser game scenario may involve a whole series of calls to get different player information at different times, and the player always want the 'current value' which may be quite dynamic. That may translate into many calls for just a few columns in the table each time (in which case, a multiple-table design could be faster than a single-table design). A: I recommend separating them. Not for any database reasons, but for development reasons. When you're coding your player login module, you don't want to think about any of the game information. And visa-versa. It will be easier to maintain a separation of concerns if the tables are distinct. It boils down to the fact that your game information module ain't got no business messin' around with the player login table. A: Probably as well to put it in one table in this situation as your query performance will be better. You really only want to use the next table when there will be an element of duplicate data by which you should look to normalization to reduce your data storage overheads. A: I would suggest that you keep each record type in its own table. Player Logins are one type of record. Inventory is another. They should not share a table as most of the information isn't shared. Keep your tables simple by separating out unrelated information. A: i agree with Thomas Padron-McCarthy's answer: Solving for the case of thousands of simultaneous users is not your problem. Getting people to play your game is the problem. Start with the simplest design - get the game done, working, playable, and easily expandable. If the game takes off, then you de-normalize. It's also worth mentioning that indexes can be looked at as separate tables that contain a narrower view of the data. People have been able to infer a design used by Blizzard for World of Warcraft. It seems that the quests a player is on is stored with the character. e.g.: CREATE TABLE Players ( PlayerID int, PlayerName varchar(50), ... Quest1ID int, Quest2ID int, Quest3ID int, ... Quest10ID int, ... ) Initially you could be on at most 10 quests, later it was expanded to 25, e.g.: CREATE TABLE Players ( PlayerID int, PlayerName varchar(50), ... Quest1ID int, Quest2ID int, Quest3ID int, ... Quest25ID int, ... ) This is in contrast to a split design: CREATE TABLE Players ( PlayerID int, PlayerName varchar(50), ... ) CREATE TABLE PlayerQuests ( PlayerID int, QuestID int ) The latter is much easier conceptually to deal with, and it allows the arbitrary number of quests. On the other hand you have to join Players and PlayerQuests in order to get all that information.
{ "language": "en", "url": "https://stackoverflow.com/questions/170964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }