source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
159,006 | Is there a way to find the maximum and minimum defined values of an enum in c++? | No, there is no way to find the maximum and minimum defined values of any enum in C++. When this kind of information is needed, it is often good practice to define a Last and First value. For example, enum MyPretendEnum{ Apples, Oranges, Pears, Bananas, First = Apples, Last = Bananas}; There do not need to be named values for every value between First and Last . | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/159006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17693/"
]
} |
159,015 | What is the use of a Dispatcher Object in WPF? | A dispatcher is often used to invoke calls on another thread. An example would be if you have a background thread working, and you need to update the UI thread, you would need a dispatcher to do it. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/159015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2744/"
]
} |
159,017 | Is there any way to format a string by name rather than position in C#? In python, I can do something like this example (shamelessly stolen from here ): >>> print '%(language)s has %(#)03d quote types.' % \ {'language': "Python", "#": 2}Python has 002 quote types. Is there any way to do this in C#? Say for instance: String.Format("{some_variable}: {some_other_variable}", ...); Being able to do this using a variable name would be nice, but a dictionary is acceptable too. | There is no built-in method for handling this. Here's one method string myString = "{foo} is {bar} and {yadi} is {yada}".Inject(o); Here's another Status.Text = "{UserName} last logged in at {LastLoginDate}".FormatWith(user); A third improved method partially based on the two above , from Phil Haack | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/159017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
]
} |
159,034 | Are C++ enums signed or unsigned? And by extension is it safe to validate an input by checking that it is <= your max value, and leave out >= your min value (assuming you started at 0 and incremented by 1)? | You shouldn't rely on any specific representation. Read the following link . Also, the standard says that it is implementation-defined which integral type is used as the underlying type for an enum, except that it shall not be larger than int, unless some value cannot fit into int or an unsigned int. In short: you cannot rely on an enum being either signed or unsigned. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/159034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17693/"
]
} |
159,038 | Are disabling and enabling foreign key constraints supported in SQL Server? Or is my only option to drop and then re- create the constraints? | If you want to disable all constraints in the database just run this code: -- disable all constraintsEXEC sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all" To switch them back on, run: (the print is optional of course and it is just listing the tables) -- enable all constraintsexec sp_MSforeachtable @command1="print '?'", @command2="ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all" I find it useful when populating data from one database to another. It is much better approach than dropping constraints. As you mentioned it comes handy when dropping all the data in the database and repopulating it (say in test environment). If you are deleting all the data you may find this solution to be helpful. Also sometimes it is handy to disable all triggers as well, you can see the complete solution here . | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/159038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
]
} |
159,076 | I have a c# application that runs as a windows service controlling socket connections and other things.Also, there is another windows forms application to control and configure this service (systray with start, stop, show form with configuration parameters). I'm using .net remoting to do the IPC and that was fine, but now I want to show some real traffic and other reports and remoting will not meet my performance requirements. So I want to combine both applications in one. Here is the problem: When I started the form from the windows service, nothing happened. Googling around I've found that I have to right click the service, go to Log on and check the "Allow service to interact with desktop" option. Since I don't want to ask my users to do that, I got some code googling again to set this option in the user's regedit during installation time. The problem is that even setting this option, it doesn't work. I have to open the Log On options of the service (it is checked), uncheck and check again. So, how to solve that? How is the best way to have a windows service with a systray control in the same process, available to any user logging in? UPDATE: Thanks for the comments so far, guys. I agree it is better to use IPC and I know that it is bad to mix windows services and user interfaces. Even though, I want to know how to do that. | Two separate processes that communicate using your technology of choice. Services with UI is a bad idea . Don't go down this road - you'll regret it. I've had very good results having service communication through a simple socket connection - document your service protocol well, keep it as simple as possible, and it'll be easier than you think. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/159076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22693/"
]
} |
159,087 | I inherited a database built with the idea that composite keys are much more ideal than using a unique object ID field and that when building a database, a single unique ID should never be used as a primary key. Because I was building a Rails front-end for this database, I ran into difficulties getting it to conform to the Rails conventions (though it was possible using custom views and a few additional gems to handle composite keys). The reasoning behind this specific schema design from the person who wrote it had to do with how the database handles ID fields in a non-efficient manner and when it's building indexes, tree sorts are flawed. This explanation lacked any depth and I'm still trying to wrap my head around the concept (I'm familiar with using composite keys, but not 100% of the time). Can anyone offer opinions or add any greater depth to this topic? | Most of the commonly used engines (MS SQL Server, Oracle, DB2, MySQL, etc.) would not experience noticeable issues using a surrogate key system. Some may even experience a performance boost from the use of a surrogate, but performance issues are highly platform-specific. In general terms, the natural key (and by extension, composite key) verses surrogate key debate has a long history with no likely “right answer” in sight. The arguments for natural keys (singular or composite) usually include some the following: 1) They are already available in the data model. Most entities being modeled already include one or more attributes or combinations of attributes that meet the needs of a key for the purposes of creating relations. Adding an additional attribute to each table incorporates an unnecessary redundancy. 2) They eliminate the need for certain joins. For example, if you have customers with customer codes, and invoices with invoice numbers (both of which are "natural" keys), and you want to retrieve all the invoice numbers for a specific customer code, you can simply use "SELECT InvoiceNumber FROM Invoice WHERE CustomerCode = 'XYZ123'" . In the classic surrogate key approach, the SQL would look something like this: "SELECT Invoice.InvoiceNumber FROM Invoice INNER JOIN Customer ON Invoice.CustomerID = Customer.CustomerID WHERE Customer.CustomerCode = 'XYZ123'" . 3) They contribute to a more universally-applicable approach to data modeling. With natural keys, the same design can be used largely unchanged between different SQL engines. Many surrogate key approaches use specific SQL engine techniques for key generation, thus requiring more specialization of the data model to implement on different platforms. Arguments for surrogate keys tend to revolve around issues that are SQL engine specific: 1) They enable easier changes to attributes when business requirements/rules change. This is because they allow the data attributes to be isolated to a single table. This is primarily an issue for SQL engines that do not efficiently implement standard SQL constructs such as DOMAINs. When an attribute is defined by a DOMAIN statement, changes to the attribute can be performed schema-wide using an ALTER DOMAIN statement. Different SQL engines have different performance characteristics for altering a domain, and some SQL engines do not implement DOMAINS at all, so data modelers compensate for these situations by adding surrogate keys to improve the ability to make changes to attributes. 2) They enable easier implementations of concurrency than natural keys. In the natural key case, if two users are concurrently working with the same information set, such as a customer row, and one of the users modifies the natural key value, then an update by the second user will fail because the customer code they are updating no longer exists in the database. In the surrogate key case, the update will process successfully because immutable ID values are used to identify the rows in the database, not mutable customer codes. However, it is not always desirable to allow the second update – if the customer code changed it is possible that the second user should not be allowed to proceed with their change because the actual “identity” of the row has changed – the second user may be updating the wrong row. Neither surrogate keys nor natural keys, by themselves, address this issue. Comprehensive concurrency solutions have to be addressed outside of the implementation of the key. 3) They perform better than natural keys. Performance is most directly affected by the SQL engine. The same database schema implemented on the same hardware using different SQL engines will often have dramatically different performance characteristics, due to the SQL engines data storage and retrieval mechanisms. Some SQL engines closely approximate flat-file systems, where data is actually stored redundantly when the same attribute, such as a Customer Code, appears in multiple places in the database schema. This redundant storage by the SQL engine can cause performance issues when changes need to be made to the data or schema. Other SQL engines provide a better separation between the data model and the storage/retrieval system, allowing for quicker changes of data and schema. 4) Surrogate keys function better with certain data access libraries and GUI frameworks. Due to the homogeneous nature of most surrogate key designs (example: all relational keys are integers), data access libraries, ORMs, and GUI frameworks can work with the information without needing special knowledge of the data. Natural keys, due to their heterogeneous nature (different data types, size etc.), do not work as well with automated or semi-automated toolkits and libraries. For specialized scenarios, such as embedded SQL databases, designing the database with a specific toolkit in mind may be acceptable. In other scenarios, databases are enterprise information resources, accessed concurrently by multiple platforms, applications, report systems, and devices, and therefore do not function as well when designed with a focus on any particular library or framework. In addition, databases designed to work with specific toolkits become a liability when the next great toolkit is introduced. I tend to fall on the side of natural keys (obviously), but I am not fanatical about it. Due to the environment I work in, where any given database I help design may be used by a variety of applications, I use natural keys for the majority of the data modeling, and rarely introduce surrogates. However, I don’t go out of my way to try to re-implement existing databases that use surrogates. Surrogate-key systems work just fine – no need to change something that is already functioning well. There are some excellent resources discussing the merits of each approach: http://www.google.com/search?q=natural+key+surrogate+key http://www.agiledata.org/essays/keys.html http://www.informationweek.com/news/software/bi/201806814 | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/159087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23909/"
]
} |
159,088 | In WPF: Can someone please explain the relationship between DependencyProperty and Databinding? I have a property in my code behind I want to be the source of my databinding.When does a DependencyProperty (or does it) come into play if I want to bind this object to textboxes on the XAML. | The target in a binding must always be a DependencyProperty , but any property (even plain properties) can be the source. The problem with plain properties is that the binding will only pick up the value once and it won't change after that because change notification is missing from the plain source property. To provide that change notification without making it a DependencyProperty , one can: Implement INotifyPropertyChanged on the class defining the property. Create a PropertyName Changed event. (Backward compatibility.) WPF will work better with the first choice. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/159088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2744/"
]
} |
159,118 | For example, this regex (.*)<FooBar> will match: abcde<FooBar> But how do I get it to match across multiple lines? abcdefghij<FooBar> | It depends on the language, but there should be a modifier that you can add to the regex pattern. In PHP it is: /(.*)<FooBar>/s The s at the end causes the dot to match all characters including newlines. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/159118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2108/"
]
} |
159,137 | I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of another program doesn't seem very elegant not to mention error prone. Does anyone know a cross platform method (windows and linux) method to get the MAC address? If not, does anyone know any more elegant methods then those I listed above? | Python 2.5 includes an uuid implementation which (in at least one version) needs the mac address. You can import the mac finding function into your own code easily: from uuid import getnode as get_macmac = get_mac() The return value is the mac address as 48 bit integer. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/159137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9940/"
]
} |
159,148 | Groovy adds the execute method to String to make executing shells fairly easy; println "ls".execute().text but if an error happens, then there is no resulting output. Is there an easy way to get both the standard error and standard out? (other than creating a bunch of code to; create two threads to read both inputstreams, then using a parent stream to wait for them to complete then convert the strings back to text?) It would be nice to have something like; def x = shellDo("ls /tmp/NoFile") println "out: ${x.out} err:${x.err}" | Ok, solved it myself; def sout = new StringBuilder(), serr = new StringBuilder()def proc = 'ls /badDir'.execute()proc.consumeProcessOutput(sout, serr)proc.waitForOrKill(1000)println "out> $sout\nerr> $serr" displays: out> err> ls: cannot access /badDir: No such file or directory | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/159148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6580/"
]
} |
159,255 | Bearing in mind that I'll be performing calculations on lat / long pairs, what datatype is best suited for use with a MySQL database? | Use MySQL's spatial extensions with GIS. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/159255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12037/"
]
} |
159,261 | Does anyone have an example of script that can work reliably well across IE/Firefox to detect if the browser is capable of displaying embedded flash content. I say reliably because I know its not possible 100% of the time. | SWFObject is very reliable. I have used it without trouble for quite a while. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/159261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7280/"
]
} |
159,280 | I simply could not make it work, and I am wondering if I am wasting my time, or if I am simply stupid! Sorry I don't have the exact error I have right now. But I just want to know if it work or not! | I don't know whether OCUnit works with iPhone, but there is an iPhoneUnitTesting framework available from Google Code. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/159280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7419/"
]
} |
159,296 | I've got a (poorly written) base class that I want to wrap in a proxy object. The base class resembles the following: public class BaseClass : SomeOtherBase { public BaseClass() {} public BaseClass(int someValue) {} //...more code, not important here} and, my proxy resembles: public BaseClassProxy : BaseClass{ public BaseClassProxy(bool fakeOut){}} Without the "fakeOut" constructor, the base constructor is expected to be called. However, with it, I expected it to not be called. Either way, I either need a way to not call any base class constructors, or some other way to effectively proxy this (evil) class. | If you do not explicitly call any constructor in the base class, the parameterless constructor will be called implicitly. There's no way around it, you cannot instantiate a class without a constructor being called. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/159296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5619/"
]
} |
159,393 | I want to create a script that parses or makes sense of apache's error log to see what the most recent error was. I was wondering if anyone out there has something that does this or has any ideas where to start? | There are a few things to consider first: Firstly, your PHP user may not have access to Apache's log files. Secondly, PHP and Apache aren't going to tell you where said log file is, Lastly, Apache log files can get quite large. However, if none of these apply, you can use the normal file reading commands to do it.The easiest way to get the last error is $contents = @file('/path/to/error.log', FILE_SKIP_EMPTY_LINES);if (is_array($contents)) { echo end($contents);}unset($contents); There's probably a better way of doing this that doesn't oink up memory, but I'll leave that as an exercise for the reader. One last comment: PHP also has an ini setting to redirect PHP errors to a log file: error_log = /path/to/error.log You can set this in httpd.conf or in an .htaccess file (if you have access to one) using the php_flag notation: php_flag error_log /web/mysite/logs/error.log | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/159393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5261/"
]
} |
159,456 | I have a database in the following format: ID TYPE SUBTYPE COUNT MONTH 1 A Z 1 7/1/2008 1 A Z 3 7/1/2008 2 B C 2 7/2/2008 1 A Z 3 7/2/2008 Can I use SQL to convert it into this: ID A_Z B_C MONTH1 4 0 7/1/20082 0 2 7/2/20081 0 3 7/2/2008 So, the TYPE , SUBTYPE are concatenated into new columns and COUNT is summed where the ID and MONTH match. Any tips would be appreciated. Is this possible in SQL or should I program it manually? The database is SQL Server 2005. Assume there are 100s of TYPES and SUBTYPES so and 'A' and 'Z' shouldn't be hard coded but generated dynamically. | SQL Server 2005 offers a very useful PIVOT and UNPIVOT operator which allow you to make this code maintenance-free using PIVOT and some code generation/dynamic SQL /*CREATE TABLE [dbo].[stackoverflow_159456]( [ID] [int] NOT NULL, [TYPE] [char](1) NOT NULL, [SUBTYPE] [char](1) NOT NULL, [COUNT] [int] NOT NULL, [MONTH] [datetime] NOT NULL) ON [PRIMARY]*/DECLARE @sql AS varchar(max)DECLARE @pivot_list AS varchar(max) -- Leave NULL for COALESCE techniqueDECLARE @select_list AS varchar(max) -- Leave NULL for COALESCE techniqueSELECT @pivot_list = COALESCE(@pivot_list + ', ', '') + '[' + PIVOT_CODE + ']' ,@select_list = COALESCE(@select_list + ', ', '') + 'ISNULL([' + PIVOT_CODE + '], 0) AS [' + PIVOT_CODE + ']'FROM ( SELECT DISTINCT [TYPE] + '_' + SUBTYPE AS PIVOT_CODE FROM stackoverflow_159456) AS PIVOT_CODESSET @sql = ';WITH p AS ( SELECT ID, [MONTH], [TYPE] + ''_'' + SUBTYPE AS PIVOT_CODE, SUM([COUNT]) AS [COUNT] FROM stackoverflow_159456 GROUP BY ID, [MONTH], [TYPE] + ''_'' + SUBTYPE)SELECT ID, [MONTH], ' + @select_list + 'FROM pPIVOT ( SUM([COUNT]) FOR PIVOT_CODE IN ( ' + @pivot_list + ' )) AS pvt'EXEC (@sql) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/159456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23133/"
]
} |
159,521 | I mean 100+ MB big; such text files can push the envelope of editors. I need to look through a large XML file, but cannot if the editor is buggy. Any suggestions? | Free read-only viewers: Large Text File Viewer (Windows) – Fully customizable theming (colors, fonts, word wrap, tab size). Supports horizontal and vertical split view. Also support file following and regex search. Very fast, simple, and has small executable size. klogg (Windows, macOS, Linux) – A maintained fork of glogg . Its main feature is regular expression search. It supports monitoring file changes (like tail ), bookmarks, highlighting patterns using different colors, and has serious optimizations built in. But from a UI standpoint, it's rather minimal. LogExpert (Windows) – "A GUI replacement for tail ." It's really a log file analyzer, not a large file viewer, and in one test it required 10 seconds and 700 MB of RAM to load a 250 MB file. But its killer features are the columnizer (parse logs that are in CSV, JSONL, etc. and display in a spreadsheet format) and the highlighter (show lines with certain words in certain colors). Also supports file following, tabs, multifiles, bookmarks, search, plugins, and external tools. Lister (Windows) – Very small and minimalist. It's one executable, barely 500 KB, but it still supports searching (with regexes), printing, a hex editor mode, and settings. Free editors: Your regular editor or IDE. Modern editors can handle surprisingly large files. In particular, Vim (Windows, macOS, Linux), Emacs (Windows, macOS, Linux), Notepad++ (Windows), Sublime Text (Windows, macOS, Linux), and VS Code (Windows, macOS, Linux) support large (~4 GB) files, assuming you have the RAM. Large File Editor (Windows) – Opens and edits TB+ files, supports Unicode, uses little memory, has XML-specific features, and includes a binary mode. GigaEdit (Windows) – Supports searching, character statistics, and font customization. But it's buggy – with large files, it only allows overwriting characters, not inserting them; it doesn't respect LF as a line terminator, only CRLF; and it's slow. Builtin programs (no installation required): less (macOS, Linux) – The traditional Unix command-line pager tool. Lets you view text files of practically any size. Can be installed on Windows, too. Notepad (Windows) – Decent with large files, especially with word wrap turned off. MORE (Windows) – This refers to the Windows MORE , not the Unix more . A console program that allows you to view a file, one screen at a time. Web viewers: readfileonline.com – Another HTML5 large file viewer. Supports search. Paid editors/viewers: 010 Editor (Windows, macOS, Linux) – Opens giant (as large as 50 GB) files. SlickEdit (Windows, macOS, Linux) – Opens large files. UltraEdit (Windows, macOS, Linux) – Opens files of more than 6 GB, but the configuration must be changed for this to be practical: Menu » Advanced » Configuration » File Handling » Temporary Files » Open file without temp file... EmEditor (Windows) – Handles very large text files nicely (officially up to 248 GB, but as much as 900 GB according to one report). BssEditor (Windows) – Handles large files and very long lines. Don’t require an installation. Free for non commercial use. loxx (Windows) – Supports file following, highlighting, line numbers, huge files, regex, multiple files and views, and much more. The free version can not: process regex, filter files, synchronize timestamps, and save changed files. | {
"score": 12,
"source": [
"https://Stackoverflow.com/questions/159521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17865/"
]
} |
159,523 | When I call Response.Redirect(someUrl) I get the following HttpException: Cannot redirect after HTTP headers have been sent. Why do I get this? And how can I fix this issue? | According to the MSDN documentation for Response.Redirect(string url) , it will throw an HttpException when "a redirection is attempted after the HTTP headers have been sent". Since Response.Redirect(string url) uses the Http "Location" response header ( http://en.wikipedia.org/wiki/HTTP_headers#Responses ), calling it will cause the headers to be sent to the client. This means that if you call it a second time, or if you call it after you've caused the headers to be sent in some other way, you'll get the HttpException. One way to guard against calling Response.Redirect() multiple times is to check the Response.IsRequestBeingRedirected property (bool) before calling it. // Causes headers to be sent to the client (Http "Location" response header)Response.Redirect("http://www.stackoverflow.com");if (!Response.IsRequestBeingRedirected) // Will not be called Response.Redirect("http://www.google.com"); | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/159523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23886/"
]
} |
159,526 | I have a trace setup for SQL Server Profiler to monitor SQL that is executed on a database. I recently discovered that trigger execution is not included in the trace. After looking through available events for a trace, I do not see any that look like they would include trigger execution. Does anyone know how to setup a trace to monitor the execution of triggers? | Stored procedures:- SP:StmtStarting- SP:StmtCompleted | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/159526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3123/"
]
} |
159,547 | Regardless of the layout being used for the tiles, is there any good way to divvy out the tiles so that you can guarantee the user that, at the beginning of the game, there exists at least one path to completing the puzzle and winning the game? Obviously, depending on the user's moves, they can cut themselves off from winning. I just want to be able to always tell the user that the puzzle is winnable if they play well. If you randomly place tiles at the beginning of the game, it's possible that the user could make a few moves and not be able to do any more. The knowledge that a puzzle is at least solvable should make it more fun to play. | Place all the tiles in reverse (ie layout out the board starting in the middle, working out) To tease the player further, you could do it visibly but at very high speed. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/159547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24246/"
]
} |
159,554 | I'm looking for a built-in function/extended function in T-SQL for string manipulation similar to the String.Format method in .NET. | If you are using SQL Server 2012 and above, you can use FORMATMESSAGE . eg. DECLARE @s NVARCHAR(50) = 'World';DECLARE @d INT = 123;SELECT FORMATMESSAGE('Hello %s, %d', @s, @d)-- RETURNS 'Hello World, 123' More examples from MSDN: FORMATMESSAGE SELECT FORMATMESSAGE('Signed int %i, %d %i, %d, %+i, %+d, %+i, %+d', 5, -5, 50, -50, -11, -11, 11, 11);SELECT FORMATMESSAGE('Signed int with leading zero %020i', 5);SELECT FORMATMESSAGE('Signed int with leading zero 0 %020i', -55);SELECT FORMATMESSAGE('Unsigned int %u, %u', 50, -50);SELECT FORMATMESSAGE('Unsigned octal %o, %o', 50, -50);SELECT FORMATMESSAGE('Unsigned hexadecimal %x, %X, %X, %X, %x', 11, 11, -11, 50, -50);SELECT FORMATMESSAGE('Unsigned octal with prefix: %#o, %#o', 50, -50);SELECT FORMATMESSAGE('Unsigned hexadecimal with prefix: %#x, %#X, %#X, %X, %x', 11, 11, -11, 50, -50);SELECT FORMATMESSAGE('Hello %s!', 'TEST');SELECT FORMATMESSAGE('Hello %20s!', 'TEST');SELECT FORMATMESSAGE('Hello %-20s!', 'TEST');SELECT FORMATMESSAGE('Hello %20s!', 'TEST'); NOTES: Undocumented in 2012 Limited to 2044 characters To escape the % sign, you need to double it. If you are logging errors in extended events, calling FORMATMESSAGE comes up as a (harmless) error | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/159554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
159,567 | How do I parse the first, middle, and last name out of a fullname field with SQL? I need to try to match up on names that are not a direct match on full name. I'd like to be able to take the full name field and break it up into first, middle and last name. The data does not include any prefixes or suffixes. The middle name is optional. The data is formatted 'First Middle Last'. I'm interested in some practical solutions to get me 90% of the way there. As it has been stated, this is a complex problem, so I'll handle special cases individually. | Here is a self-contained example, with easily manipulated test data. With this example, if you have a name with more than three parts, then all the "extra" stuff will get put in the LAST_NAME field. An exception is made for specific strings that are identified as "titles", such as "DR", "MRS", and "MR". If the middle name is missing, then you just get FIRST_NAME and LAST_NAME (MIDDLE_NAME will be NULL). You could smash it into a giant nested blob of SUBSTRINGs, but readability is hard enough as it is when you do this in SQL. Edit-- Handle the following special cases: 1 - The NAME field is NULL 2 - The NAME field contains leading / trailing spaces 3 - The NAME field has > 1 consecutive space within the name 4 - The NAME field contains ONLY the first name 5 - Include the original full name in the final output as a separate column, for readability 6 - Handle a specific list of prefixes as a separate "title" column SELECT FIRST_NAME.ORIGINAL_INPUT_DATA ,FIRST_NAME.TITLE ,FIRST_NAME.FIRST_NAME ,CASE WHEN 0 = CHARINDEX(' ',FIRST_NAME.REST_OF_NAME) THEN NULL --no more spaces? assume rest is the last name ELSE SUBSTRING( FIRST_NAME.REST_OF_NAME ,1 ,CHARINDEX(' ',FIRST_NAME.REST_OF_NAME)-1 ) END AS MIDDLE_NAME ,SUBSTRING( FIRST_NAME.REST_OF_NAME ,1 + CHARINDEX(' ',FIRST_NAME.REST_OF_NAME) ,LEN(FIRST_NAME.REST_OF_NAME) ) AS LAST_NAMEFROM ( SELECT TITLE.TITLE ,CASE WHEN 0 = CHARINDEX(' ',TITLE.REST_OF_NAME) THEN TITLE.REST_OF_NAME --No space? return the whole thing ELSE SUBSTRING( TITLE.REST_OF_NAME ,1 ,CHARINDEX(' ',TITLE.REST_OF_NAME)-1 ) END AS FIRST_NAME ,CASE WHEN 0 = CHARINDEX(' ',TITLE.REST_OF_NAME) THEN NULL --no spaces @ all? then 1st name is all we have ELSE SUBSTRING( TITLE.REST_OF_NAME ,CHARINDEX(' ',TITLE.REST_OF_NAME)+1 ,LEN(TITLE.REST_OF_NAME) ) END AS REST_OF_NAME ,TITLE.ORIGINAL_INPUT_DATA FROM ( SELECT --if the first three characters are in this list, --then pull it as a "title". otherwise return NULL for title. CASE WHEN SUBSTRING(TEST_DATA.FULL_NAME,1,3) IN ('MR ','MS ','DR ','MRS') THEN LTRIM(RTRIM(SUBSTRING(TEST_DATA.FULL_NAME,1,3))) ELSE NULL END AS TITLE --if you change the list, don't forget to change it here, too. --so much for the DRY prinicple... ,CASE WHEN SUBSTRING(TEST_DATA.FULL_NAME,1,3) IN ('MR ','MS ','DR ','MRS') THEN LTRIM(RTRIM(SUBSTRING(TEST_DATA.FULL_NAME,4,LEN(TEST_DATA.FULL_NAME)))) ELSE LTRIM(RTRIM(TEST_DATA.FULL_NAME)) END AS REST_OF_NAME ,TEST_DATA.ORIGINAL_INPUT_DATA FROM ( SELECT --trim leading & trailing spaces before trying to process --disallow extra spaces *within* the name REPLACE(REPLACE(LTRIM(RTRIM(FULL_NAME)),' ',' '),' ',' ') AS FULL_NAME ,FULL_NAME AS ORIGINAL_INPUT_DATA FROM ( --if you use this, then replace the following --block with your actual table SELECT 'GEORGE W BUSH' AS FULL_NAME UNION SELECT 'SUSAN B ANTHONY' AS FULL_NAME UNION SELECT 'ALEXANDER HAMILTON' AS FULL_NAME UNION SELECT 'OSAMA BIN LADEN JR' AS FULL_NAME UNION SELECT 'MARTIN J VAN BUREN SENIOR III' AS FULL_NAME UNION SELECT 'TOMMY' AS FULL_NAME UNION SELECT 'BILLY' AS FULL_NAME UNION SELECT NULL AS FULL_NAME UNION SELECT ' ' AS FULL_NAME UNION SELECT ' JOHN JACOB SMITH' AS FULL_NAME UNION SELECT ' DR SANJAY GUPTA' AS FULL_NAME UNION SELECT 'DR JOHN S HOPKINS' AS FULL_NAME UNION SELECT ' MRS SUSAN ADAMS' AS FULL_NAME UNION SELECT ' MS AUGUSTA ADA KING ' AS FULL_NAME ) RAW_DATA ) TEST_DATA ) TITLE ) FIRST_NAME | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/159567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73794/"
]
} |
159,590 | I've used recursion quite a lot on my many years of programming to solve simple problems, but I'm fully aware that sometimes you need iteration due to memory/speed problems. So, sometime in the very far past I went to try and find if there existed any "pattern" or text-book way of transforming a common recursion approach to iteration and found nothing. Or at least nothing that I can remember it would help. Are there general rules? Is there a "pattern"? | Usually, I replace a recursive algorithm by an iterative algorithm by pushing the parameters that would normally be passed to the recursive function onto a stack. In fact, you are replacing the program stack by one of your own. var stack = [];stack.push(firstObject);// while not emptywhile (stack.length) { // Pop off end of stack. obj = stack.pop(); // Do stuff. // Push other objects on the stack as needed. ...} Note: if you have more than one recursive call inside and you want to preserve the order of the calls, you have to add them in the reverse order to the stack: foo(first);foo(second); has to be replaced by stack.push(second);stack.push(first); Edit: The article Stacks and Recursion Elimination (or Article Backup link ) goes into more details on this subject. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/159590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8167/"
]
} |
159,599 | I have a .net project that has a web reference to a service. I would like to update that web reference as part of every build. Is that possible? | You can use MSBuild script with a task that calls wsdl.exe <Target Name="UpdateWebReference"> <Message Text="Updating Web Reference..."/> <Exec Command="wsdl.exe /o "$(OutDir)" /n "$(WebServiceNamespace)" "$(PathToWebServiceURL)""/> </Target> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/159599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15903/"
]
} |
159,627 | We just did a move from storing all files locally to a network drive. Problem is that is where my VS projects are also stored now. (No versioning system yet, working on that.) I know I heard of problems with doing this in the past, but never heard of a work-around. Is there a work around? So my VS is installed locally. The files are on a network drive. How can I get this to work? EDIT: I know what SHOULD be done, but is there a band-aid I can put on right now to fix this and maintain the network drive? EDIT 2: I am sure I am not understanding something, but Bob King has the right idea. I'll work with the lead web developer when he gets back into the office to figure out a temporary solution until we get some sort of version control setup. Thanks for the ideas. | While we do use Source Control, we do also run all our projects from Network Drives (not shared directories, private directories on network drives). The network drives are backed up nightly, and also use Volume Shadow Copy, so if you need to revert to something before it made it's way to SC, then you can. To get projects to run correctly with the right permission, follow these steps . Basically, you've just got to map the shared directory to a drive, and then grant permission, based on that Url, to all code. Say you map to "N:\", then use "N:\*" as your Url pattern. It isn't obvious you need to wildcard, but you do. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/159627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2535/"
]
} |
159,720 | Coming from a C# background the naming convention for variables and method names are usually either camelCase or PascalCase: // C# examplestring thisIsMyVariable = "a"public void ThisIsMyMethod() In Python, I have seen the above but I have also seen underscores being used: # python examplethis_is_my_variable = 'a'def this_is_my_function(): Is there a more preferable, definitive coding style for Python? | See Python PEP 8: Function and Variable Names : Function names should be lowercase, with words separated by underscores as necessary to improve readability. Variable names follow the same convention as function names. mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py ), to retain backwards compatibility. | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/159720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
]
} |
159,744 | Similar questions have been asked, but nothing exactly like mine, so here goes. We have a collection of Microsoft Word documents on an ASP.NET web server with merge fields whose values are filled in as a result of user form submissions. After the field merge, the server must convert the document to PDF and stream it down to the browser. Our first inclination was to use the Visual Studio Tools for Office API; however, we ran into this warning from Microsoft : Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment. It looks like the field manipulation can be done using the Open XML SDK , but what's the best way to convert Word 2007 documents to PDF without opening Word? The optimal solution would be low-cost, scalable, have a low memory footprint, be easy to deploy, and have a .NET API. | It's not exactly Open Source, but Aspose has a couple products which can do that, Aspose.Pdf.Kit Aspose.Pdf.Kit is a non-graphical PDF® document manipulation component that enables both .NET and Java developers to manage existing PDF files as well as manage form fields embedded within PDF files. Aspose.Pdf is perfect for creating new PDF files; however, developers often need to edit already existing PDF documents. Aspose.Pdf.Kit allows them to do just that. Aspose.Pdf.Kit allows developers to create powerful applications for merging data directly into PDF documents as well as for updating and managing PDF documents. Aspose.Pdf.Kit is a wonderful product and works great with the rest of our PDF products. and Aspose.pdf Aspose.Pdf is a non-graphical PDF® document reporting component that enables either .NET or Java applications to create PDF documents from scratch without utilizing Adobe Acrobat®. Aspose.Pdf is very affordably priced and offers a wealth of strong features including: compression, tables, graphs, images, hyperlinks, security and custom fonts. Aspose.Pdf supports the creation of PDF files through API, XML templates and XSL-FO files. Aspose.Pdf is very easy to use and is provided with 14 fully featured demos written in both C# and Visual Basic. Check out the API and demos . You can download a DLL for free to try it out. I've used both before and they work out great. There's also iTextSharp which is a C# port of iText, a Java PDF converter. I've heard some people try it with mixed results. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/159744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2144/"
]
} |
159,768 | I'm working on building a Silverlight application whereas we want to be able to have a client hit a url like: http://{client}.domain.com/ and login, where the {client} part is their business name. so for example, google's would be: http://google.domain.com/ What I was wondering was if anyone has been able, in silverlight, to be able to use this subdomain model to make decisions on the call to the web server so that you can switch to a specific database to run a query? Unfortunately, it's something that is quite necessary for the project, as we are trying to make it easy for their employees to get their company specific information for our software. | It's not exactly Open Source, but Aspose has a couple products which can do that, Aspose.Pdf.Kit Aspose.Pdf.Kit is a non-graphical PDF® document manipulation component that enables both .NET and Java developers to manage existing PDF files as well as manage form fields embedded within PDF files. Aspose.Pdf is perfect for creating new PDF files; however, developers often need to edit already existing PDF documents. Aspose.Pdf.Kit allows them to do just that. Aspose.Pdf.Kit allows developers to create powerful applications for merging data directly into PDF documents as well as for updating and managing PDF documents. Aspose.Pdf.Kit is a wonderful product and works great with the rest of our PDF products. and Aspose.pdf Aspose.Pdf is a non-graphical PDF® document reporting component that enables either .NET or Java applications to create PDF documents from scratch without utilizing Adobe Acrobat®. Aspose.Pdf is very affordably priced and offers a wealth of strong features including: compression, tables, graphs, images, hyperlinks, security and custom fonts. Aspose.Pdf supports the creation of PDF files through API, XML templates and XSL-FO files. Aspose.Pdf is very easy to use and is provided with 14 fully featured demos written in both C# and Visual Basic. Check out the API and demos . You can download a DLL for free to try it out. I've used both before and they work out great. There's also iTextSharp which is a C# port of iText, a Java PDF converter. I've heard some people try it with mixed results. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/159768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24302/"
]
} |
159,769 | I have a complex query with group by and order by clause and I need a sorted row number (1...2...(n-1)...n) returned with every row. Using a ROWNUM (value is assigned to a row after it passes the predicate phase of the query but before the query does any sorting or aggregation) gives me a non-sorted list (4...567...123...45...). I cannot use application for counting and assigning numbers to each row. | Is there a reason that you can't just do SELECT rownum, a.* FROM (<<your complex query including GROUP BY and ORDER BY>>) a | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/159769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4235/"
]
} |
159,797 | Wikipedia says Ruby is a functional language, but I'm not convinced. Why or why not? | I most definitely think you can use functional style in Ruby. One of the most critical aspects to be able to program in a functional style is if the language supports higher order functions... which Ruby does. That said, it's easy to program in Ruby in a non-functional style as well. Another key aspect of functional style is to not have state, and have real mathematical functions that always return the same value for a given set of inputs. This can be done in Ruby, but it is not enforced in the language like something more strictly functional like Haskell. So, yeah, it supports functional style, but it also will let you program in a non-functional style as well. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/159797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/781/"
]
} |
159,821 | In an app I'm working on, I have a plain style UITableView that can contain a section containing zero rows. I want to be able to scroll to this section using scrollToRowAtIndexPath:atScrollPosition:animated: but I get an error when I try to scroll to this section due to the lack of child rows. Apple's calendar application is able to do this, if you look at your calendar in list view, and there are no events in your calendar for today, an empty section is inserted for today and you can scroll to it using the Today button in the toolbar at the bottom of the screen. As far as I can tell Apple may be using a customized UITableView, or they're using a private API... The only workaround I can think of is to insert an empty UITableCell in that's 0 pixels high and scroll to that. But it's my understanding that having cells of varying heights is really bad for scrolling performance. Still I'll try it anyway, maybe the performance hit won't be too bad. Update Since there seems to be no solution to this, I've filed a bug report with apple. If this affects you too, file a duplicate of rdar://problem/6263339 ( Open Radar link) if you want this to get this fixed faster. Update #2 I have a decent workaround to this issue, take a look at my answer below. | UPDATE: Looks like this bug is fixed in iOS 3.0. You can use the following NSIndexPath to scroll to a section containing 0 rows: [NSIndexPath indexPathForRow:NSNotFound inSection:section] I'll leave my original workaround here for anyone still maintaining a project using the 2.x SDK. Found a decent workaround: CGRect sectionRect = [tableView rectForSection:indexOfSectionToScrollTo];[tableView scrollRectToVisible:sectionRect animated:YES]; The code above will scroll the tableview so the desired section is visible but not necessarily at the top or bottom of the visible area. If you want to scroll so the section is at the top do this: CGRect sectionRect = [tableView rectForSection:indexOfSectionToScrollTo];sectionRect.size.height = tableView.frame.size.height;[tableView scrollRectToVisible:sectionRect animated:YES]; Modify sectionRect as desired to scroll the desired section to the bottom or middle of the visible area. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/159821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17188/"
]
} |
159,846 | I'm writing some JNI code in C++ to be called from an applet on Windows XP. I've been able to successfully run the applet and have the JNI library loaded and called, even going so far as having it call functions in other DLLs. I got this working by setting up the PATH system environment variable to include the directory all of my DLLs are in. So, the problem, is that I add another call that uses a new external DLL, and suddenly when loading the library, an UnsatisfiedLinkError is thrown. The message is: 'The specified procedure could not be found'. This doesn't seem to be a problem with a missing dependent DLL, because I can remove a dependent DLL and get a different message about dependent DLL missing. From what I've been able to find online, it appears that this message means that a native Java function implementation is missing from the DLL, but it's odd that it works fine without this extra bit of code. Does anyone know what might be causing this? What kinds of things can give a 'The specified procedure could not be found' messages for an UnsatisifedLinkError? | I figured out the problem. This was a doozy. The message "The specified procedure could not be found" for UnsatisfiedLinkError indicates that a function in the root dll or in a dependent dll could not be found. The most likely cause of this in a JNI situation is that the native JNI function is not exported correctly. But this can apparently happen if a dependent DLL is loaded and that DLL is missing a function required by its parent. By way of example, we have a library named input.dll. The DLL search order is to always look in the application directory first and the PATH directories last. In the past, we always ran executables from the same directory as input.dll. However, there is another input.dll in the windows system directory (which is in the middle of the DLL search order). So when running this from a java applet, if I include the code described above in the applet, which causes input.dll to be loaded, it loads the input.dll from the system directory. Because our code is expecting certain functions in input.dll which aren't there (because it's a different DLL) the load fails with an error message about missing procedures. Not because the JNI functions are exported wrong, but because the wrong dependent DLL was loaded and it didn't have the expected functions in it. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/159846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24307/"
]
} |
159,853 | I have some local changes to an open source project which uses Subversion as its source control. (I do not have commit access on the original project repository.) My change adds a file, but this file is not included in the output of "svn diff". (It may be worth noting that the new file is a binary, not plain text.) How can I make a patch which includes the new files? $ svn st A tests/foo.zip $ svn diff $ | I experienced similar behavior to Pozsar. And his answer worked for me better than the normal svn diff --force. However, if running on a DOS machine (e.g. via Cygwin), you may need to modify his answer slightly. The following diff + patch worked for patching my text + binary files in Cygwin using the --binary arg: svn diff --force --diff-cmd /usr/bin/diff -x "-au --binary" OLD-URL NEW-URL > mybinarydiff.diffpatch -p0 --binary -i mybinarydiff.diff | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/159853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17732/"
]
} |
159,886 | I've seen this is various codebases, and wanted to know if this generally frowned upon or not. For example: public class MyClass{ public int Id; public MyClass() { Id = new Database().GetIdFor(typeof(MyClass)); }} | There are several reasons this is not generally considered good design some of which like causing difficult unit testing and difficulty of handling errors have already been mentioned. The main reason I would choose not to do so is that your object and the data access layer are now very tightly coupled which means that any use of that object outside of it original design requires significant rework. As an example what if you came across an instance where you needed to use that object without any values assigned for instance to persist a new instance of that class? you now either have to overload the constructor and then make sure all of your other logic handles this new case, or inherit and override. If the object and the data access were decoupled then you could create an instance and then not hydrate it. Or if your have a different project that uses the same entities but uses a different persistence layer then the objects are reusable. Having said that I have taken the easier path of coupling in projects in the past :) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/159886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5619/"
]
} |
159,888 | You're stepping through C/C++ code and have just called a Win32 API that has failed (typically by returning some unhelpful generic error code, like 0). Your code doesn't make a subsequent GetLastError() call whose return value you could inspect for further error information. How can you get the error value without recompiling and reproducing the failure? Entering "GetLastError()" in the Watch window doesn't work ("syntax error"). | As mentioned a couple times, the @err pseudo-register will show the last error value, and @err,hr will show the error as a string (if it can). According to Andy Pennell, a member of the Visual Studio team, starting with VS 7 (Visual Studio .NET 2002), using the '@' character to indicate pseudo-registers is deprecated - they prefer to use '$' (as in $err,hr ). Both $ and @ are supported for the time being. You can also use the $err pseudo-register in a conditional breakpoint; so you can break on a line of code only if the last error is non-zero. This can be a very handy trick. Some other pseudo registers that you may find handy (from John Robbins' outstanding book, "Debugging Applications for Microsoft .NET and Microsoft Windows" ): $tib - shows the thread information block $clk - shows a clock count (useful for timing functions). To more easily use this, place a $clk watch then an additional $clk=0 watch. The second watch will clear the pseudo register after the display of the current value, so the next step or step over you do gives you the time for that action only. Note that this is a rough timing that includes a fair bit of debugger overhead, but it can still be very useful. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/159888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4994/"
]
} |
159,889 | I'm developing an iPhone app that uses the built-in SQLite database. I'm trying to view and open the database via the sqlite3 command line tool so I can execute arbitrary SQL against it. When I run my app in the simulator, the .sqlite file it creates is located at ~/Library/Application Support/iPhone Simulator/User/Applications/ . How can I see that file on the physical iPhone? | In Xcode select window->organizer and expand the node next to your application in the applications section on your phone. Select the black downward pointing arrow next to application data and save the file anywhere on your desktop. Your sqlite database should be in there somewhere. As for how to go about getting it back on the phone once your done i have no clue. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/159889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/49611/"
]
} |
159,910 | Is there a way my program can determine when it's running on a Remote Desktop (Terminal Services)? I'd like to enable an "inactivity timeout" on the program when it's running on a Remote Desktop session. Since users are notorious for leaving Remote Desktop sessions open, I want my program to terminate after a specified period of inactivity. But, I don't want the inactivity timeout enabled for non-RD users. | GetSystemMetrics(SM_REMOTESESSION) (as described in http://msdn.microsoft.com/en-us/library/aa380798.aspx ) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/159910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8752/"
]
} |
159,914 | Does anybody know a way with JavaScript or CSS to basically grey out a certain part of a form/div in HTML? I have a ' User Profile ' form where I want to disable part of it for a ' Non-Premium ' member, but want the user to see what is behind the form and place a ' Call to Action ' on top of it. Does anybody know an easy way to do this either via CSS or JavaScript? Edit: I will make sure that the form doesn't work on server side so CSS or JavaScript will suffice. | Add this to your HTML: <div id="darkLayer" class="darkClass" style="display:none"></div> And this to your CSS: .darkClass{ background-color: white; filter:alpha(opacity=50); /* IE */ opacity: 0.5; /* Safari, Opera */ -moz-opacity:0.50; /* FireFox */ z-index: 20; height: 100%; width: 100%; background-repeat:no-repeat; background-position:center; position:absolute; top: 0px; left: 0px;} And finally this to turn it off and on with JavaScript: function dimOff(){ document.getElementById("darkLayer").style.display = "none";}function dimOn(){ document.getElementById("darkLayer").style.display = "";} Change the dimensions of the darkClass to suite your purposes. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/159914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8534/"
]
} |
159,924 | I'm slowly moving all of my LAMP websites from mysql_ functions to PDO functions and I've hit my first brick wall. I don't know how to loop through results with a parameter. I am fine with the following: foreach ($database->query("SELECT * FROM widgets") as $results){ echo $results["widget_name"];} However if I want to do something like this: foreach ($database->query("SELECT * FROM widgets WHERE something='something else'") as $results){ echo $results["widget_name"];} Obviously the 'something else' will be dynamic. | Here is an example for using PDO to connect to a DB, to tell it to throw Exceptions instead of php errors (will help with your debugging), and using parameterised statements instead of substituting dynamic values into the query yourself (highly recommended): // connect to PDO$pdo = new PDO("mysql:host=localhost;dbname=test", "user", "password");// the following tells PDO we want it to throw Exceptions for every error.// this is far more useful than the default mode of throwing php errors$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);// prepare the statement. the placeholders allow PDO to handle substituting// the values, which also prevents SQL injection$stmt = $pdo->prepare("SELECT * FROM product WHERE productTypeId=:productTypeId AND brand=:brand");// bind the parameters$stmt->bindValue(":productTypeId", 6);$stmt->bindValue(":brand", "Slurm");// initialise an array for the results$products = array();$stmt->execute();while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $products[] = $row;} | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/159924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428190/"
]
} |
159,926 | My company unwittingly switched from cvs to subversion and now we're all wishing we had cvs back.I know there's tools to migrate history and changes from cvs to svn and there's no equivalent to do the reverse.Any suggestions or ideas on how to do this? | I originally added this as a comment to someone else's answer, but then realized that it was an answer, of sorts. I have done these sorts of transitions before, where there was no existing way to convert from one SCM system to another. It's not rocket science to write a script that takes the list of commits from your SVN repository, and iterates through them one at a time, merging them into a newly-created CVS repository. Getting all the branches and tags exactly correct might be a bit more work, but if you want to just save revision history for a few branches, it should be pretty easy. I'm also of the opinion that you won't really gain anything by switching back to CVS, but if you want to do so, then you'll likely be writing your own script. The "svn export" command will undoubtedly be useful in this endeavor. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/159926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12386/"
]
} |
159,978 | What are differences between declaring a method in a base type " virtual " and then overriding it in a child type using the " override " keyword as opposed to simply using the " new " keyword when declaring the matching method in the child type? | The "new" keyword doesn't override, it signifies a new method that has nothing to do with the base class method. public class Foo{ public bool DoSomething() { return false; }}public class Bar : Foo{ public new bool DoSomething() { return true; }}public class Test{ public static void Main () { Foo test = new Bar (); Console.WriteLine (test.DoSomething ()); }} This prints false, if you used override it would have printed true. (Base code taken from Joseph Daigle) So, if you are doing real polymorphism you SHOULD ALWAYS OVERRIDE . The only place where you need to use "new" is when the method is not related in any way to the base class version. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/159978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9898/"
]
} |
159,983 | In C++, on Linux, how can I write a function to return a temporary filename that I can then open for writing? The filename should be as unique as possible, so that another process using the same function won't get the same name. | Use one of the standard library "mktemp" functions: mktemp/mkstemp/mkstemps/mkdtemp. Edit: plain mktemp can be insecure - mkstemp is preferred. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/159983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16976/"
]
} |
160,022 | Is there anyway to determine if a ResourceManager contains a named resource? Currently I am catching the MissingManifestResourceException but I hate having to use Exceptions for non-exceptional situations. There must be some way to enumerate the name value pairs of a ResourceManager through reflection, or something? EDIT : A little more detail. The resources are not in executing assembly, however the ResourceManager is working just fine. If I try _resourceMan.GetResourceSet(_defaultCuture, false, true) I get null, whereas if I try _resourceMan.GetString("StringExists") I get a string back. | You can use the ResourceSet to do that, only it loads all the data into memory if you enumerate it. Here y'go: // At startup. ResourceManager mgr = Resources.ResourceManager; List<string> keys = new List<string>(); ResourceSet set = mgr.GetResourceSet(CultureInfo.CurrentCulture, true, true); foreach (DictionaryEntry o in set) { keys.Add((string)o.Key); } mgr.ReleaseAllResources(); Console.WriteLine(Resources.A); | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/160022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3798/"
]
} |
160,032 | I have been adding dependency injection to my code because it makes by code much easier to Unit test through mocking. However I am requiring objects higher up my call chain to have knowledge of objects further down the call chain. Does this break the Law of Demeter? If so does it matter? for example: a class A has a dependency on an interface B, The implementation of this interface to use is injected into the constructor of class A. Anyone wanting to use class A must now also have a reference to an implementation of B. And can call its methods directly meaning and has knowledge of its sub components (interface B) Wikipedia says about the law of Demeter: "The fundamental notion is that a given object should assume as little as possible about the structure or properties of anything else (including its subcomponents)." | Dependency Injection CAN break the Law of Demeter. If you force consumers to do the injection of the dependencies. This can be avoided through static factory methods, and DI frameworks. You can have both by designing your objects in such a way that they require the dependencies be passed in, and at the same time having a mechanism for using them without explicit performing the injection (factory functions and DI frameworks). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/160032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/78561/"
]
} |
160,045 | Is there a way to place a watch on variable and only have Visual Studio break when that value changes? It would make it so much easier to find tricky state issues. Can this be done? Breakpoint conditions still need a breakpoint set, and I'd rather set a watch and let Visual Studio set the breakpoints at state changes. | In the Visual Studio 2005 menu: Debug -> New Breakpoint -> New Data Breakpoint Enter: &myVariable | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/160045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
]
} |
160,097 | Pardon my ASP ignorance, but what's the difference? | These are somewhat informally referred to as "bee stings". There are 4 types: <%# %> is invoked during the DataBinding phase. <%= %> is used to get values from code to the UI layer. Meant for backward compatibility with ASP applications. Shouldn't use in .NET. <%@ %> represents directives and allow behaviors to be set without resorting to code. <%: %> (introduced in ASP.NET 4) is the same as %= , but with the added functionality of HtmlEncoding the output. The intention is for this to be the default usage (over %= ) to help shield against script injection attacks. Directives specify settings that are used by the page and user-control compilers when the compilers process ASP.NET Web Forms pages (.aspx files) and user control (.ascx) files. ASP.NET treats any directive block (<%@ %>) that does not contain an explicit directive name as an @ Page directive (for a page) or as an @ Control directive (for a user control). @Esteban - Added a msdn link to directives. If you need...more explanation, please let me know. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/160097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/781/"
]
} |
160,105 | How do you change controls' Z-order in MFC at design time - i.e. I can't use SetWindowPos or do this at runtime - I want to see the changed z-order in the designer (even if I have to resort to direct-editing the .rc code). I have an MFC dialog to which I am adding controls. If there is overlap between the edges of the controls, I want to bring one to the front of the other. In Windows Forms or WPF, etc. I can Bring to Front, Send to Back, Bring Forward, Send Back. I don't find these options in MFC, nor can I tell how it determines what is in front, as a control just added is often behind a control that was there previously. How can I manipulate the Z-order in MFC? Even if I have to manipulate the .rc file code directly (i.e. end-run around the designer). | I think the control in front will be the last control that occurs in the rc file. In other words, the dialog editor will draw each control as it is encountered from top to bottom in the rc file, overlapping them when necessary. You can edit the rc file to reorder them, or you can change the tab order in the editor, which does the same thing since tab order is also set based on the order that the controls occur in the file. To my knowledge MFC doesn't offer any other way of layering overlapping controls at design time. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/160105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8787/"
]
} |
160,118 | I have a class with both a static and a non-static interface in C#. Is it possible to have a static and a non-static method in a class with the same name and signature? I get a compiler error when I try to do this, but for some reason I thought there was a way to do this. Am I wrong or is there no way to have both static and non-static methods in the same class? If this is not possible, is there a good way to implement something like this that can be applied generically to any situation? EDIT From the responses I've received, it's clear that there is no way to do this. I'm going with a different naming system to work around this problem. | No you can't. The reason for the limitation is that static methods can also be called from non-static contexts without needing to prepend the class name (so MyStaticMethod() instead of MyClass.MyStaticMethod()). The compiler can't tell which you're looking for if you have both. You can have static and non-static methods with the same name, but different parameters following the same rules as method overloading, they just can't have exactly the same signature. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/160118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
]
} |
160,144 | How can I find the XY coordinates of an HTML element (DIV) from JavaScript if they were not explicitly set? | Here's how I do it: // Based on: http://www.quirksmode.org/js/findpos.htmlvar getCumulativeOffset = function (obj) { var left, top; left = top = 0; if (obj.offsetParent) { do { left += obj.offsetLeft; top += obj.offsetTop; } while (obj = obj.offsetParent); } return { x : left, y : top };}; | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/160144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
160,147 | Here's a curious one. I have a class A. It has an item of class B, which I want to initialize in the constructor of A using an initializer list, like so: class A { public: A(const B& b): mB(b) { }; private: B mB;}; Is there a way to catch exceptions that might be thrown by mB's copy-constructor while still using the initializer list method? Or would I have to initialize mB within the constructor's braces in order to have a try/catch? | Have a read of http://weseetips.wordpress.com/tag/exception-from-constructor-initializer-list/ ) Edit: After more digging, these are called "Function try blocks". I confess I didn't know this either until I went looking. You learn something every day! I don't know if this is an indictment of how little I get to use C++ these days, my lack of C++ knowledge, or the often Byzantine features that litter the language. Ah well - I still like it :) To ensure people don't have to jump to another site, the syntax of a function try block for constructors turns out to be: C::C()try : init1(), ..., initn(){ // Constructor}catch(...){ // Handle exception} | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/160147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12193/"
]
} |
160,175 | If you have a hash (or reference to a hash) in perl with many dimensions and you want to iterate across all values, what's the best way to do it. In other words, if we have$f->{$x}{$y}, I want something like foreach ($x, $y) (deep_keys %{$f}){} instead of foreach $x (keys %f) { foreach $y (keys %{$f->{$x}) { }} | Here's an option. This works for arbitrarily deep hashes: sub deep_keys_foreach{ my ($hashref, $code, $args) = @_; while (my ($k, $v) = each(%$hashref)) { my @newargs = defined($args) ? @$args : (); push(@newargs, $k); if (ref($v) eq 'HASH') { deep_keys_foreach($v, $code, \@newargs); } else { $code->(@newargs); } }}deep_keys_foreach($f, sub { my ($k1, $k2) = @_; print "inside deep_keys, k1=$k1, k2=$k2\n";}); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/160175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14167/"
]
} |
160,218 | I'm personally an advocate of the ternary operator : () ? : I do realize that it has its place, but I have come across many programmers that are completely against ever using it, and some that use it too often. What are your feelings on it? What interesting code have you seen using it? | Use it for simple expressions only : int a = (b > 10) ? c : d; Don't chain or nest ternary operators as it hard to read and confusing: int a = b > 10 ? c < 20 ? 50 : 80 : e == 2 ? 4 : 8; Moreover, when using ternary operator, consider formatting the code in a way that improves readability: int a = (b > 10) ? some_value : another_value; | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/160218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21804/"
]
} |
160,233 | I tried this in mysql: mysql> alter table region drop column country_id; And got this: ERROR 1025 (HY000): Error on rename of './product/#sql-14ae_81' to'./product/region' (errno: 150) Any ideas? Foreign key stuff? | You usually get this error if your tables use the InnoDB engine. In that case you would have to drop the foreign key, and then do the alter table and drop the column. But the tricky part is that you can't drop the foreign key using the column name, but instead you would have to find the name used to index it. To find that, issue the following select: SHOW CREATE TABLE region; This should show you the name of the index, something like this: CONSTRAINT region_ibfk_1 FOREIGN KEY ( country_id ) REFERENCES country ( id ) ON DELETE NO ACTION ON UPDATE NO ACTION Now simply issue an: alter table region drop foreign key region_ibfk_1 ; And finally an: alter table region drop column country_id; And you are good to go! | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/160233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2601671/"
]
} |
160,290 | After I call getpwuid(uid) , I have a reference to a pointer. Should I free that pointer when I don't use it anymore? Reading the man pages, it says that it makes reference to some static area, that may be overwritten by subsequent calls to the same functions, so I'm not sure if I should touch that memory area. Thanks. | No. You do not need to free the result. You can only call free(3) on pointers allocated on the heap with malloc(3), calloc(3) or realloc(3). Static data is part of a program's data or bss segments and will persist until the process exits (or is overwritten by exec(2)). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/160290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11384/"
]
} |
160,318 | The kind of simulation game that I have in mind is the kind where you have things to build in various locations and workers/transporters that connect such locations. Something more like the Settlers series. Let's assume I don't want any graphics at the moment, that I think I can manage. So my doubts are the following: Should every entity be a class and each one have a thread? Should entities be grouped in lists inside classes and each one have a thread? If one takes implementation 1, it's going to be very hard to run on low spec machines and does not scale well for large numbers. If one takes implementation 2, it's going to be better in terms of resources but then... How should I group the entities? Have a class for houses in general and have an Interface List to manage that? Have a class for specific groups of houses and have an Object List to manage that? and what about threads? Should I have the simplistic main game loop? Should I have a thread for each class group? How do workers/transporters fit in the picture? | The normal approach does not use threading at all, but rather implements entities as state-machines. Then your mainloop looks like this: while( 1 ){ foreach( entity in entlist ) { entity->update(); } render();} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/160318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8167/"
]
} |
160,335 | I've been playing with the .NET built in localization features and they seem to all rely on putting data in resx files. But most systems can't rely on this because they are database driven. So how do you solve this issue? Is there a built in .NET way, or do you create a translations table in SQL and do it all manually? And if you have to do this on the majority of your sites, is there any reason to even use the resx way of localization? An example of this is I have an FAQ list on my site, I keep this list in the database so I can easily add/remove more, but by putting it in the database, I have no good way have translating this information into multiple languages. | In my opinion, localizing dynamic content (e.g., your FAQ) should be done by you in your database. Depending on how your questions are stored, I would probably create a "locale" column and use that when selecting the FAQ questions from the database. I'm not sure if this would scale very well when you started localizing lots of tables. For static content (e.g, form field labels, static text, icons, etc) you should probably be just fine using file-based resources. If you really wanted to, however, it looks like it wouldn't be super hard to create a custom resource provider implementation that could handle this. Here's some related links: http://channel9.msdn.com/forums/Coffeehouse/250892-Localizing-with-a-database-or-resx-files/ http://weblogs.asp.net/scottgu/archive/2006/05/30/ASP.NET-2.0-Localization-_2800_Video_2C00_-Whitepaper_2C00_-and-Database-Provider-Support_2900_.aspx http://www.arcencus.nl/Blogs/tabid/105/EntryID/20/Default.aspx http://msdn.microsoft.com/en-us/library/aa905797.aspx http://www.codeproject.com/KB/aspnet/customsqlserverprovider.aspx | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/160335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17176/"
]
} |
160,370 | In svn, I have a branch which was created, say at revision 22334. Commits were then made on the branch. How do I get a list of all files that were changed on the branch compared to what's on the trunk? I do not want to see files that were changed on the trunk between when the branch was created and "now". | This will do it I think: svn diff -r 22334:HEAD --summarize <url of the branch> | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/160370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2601671/"
]
} |
160,376 | I've noticed that just in the last year or so, many major websites have made the same change to the way their pages are structured. Each has moved their Javascript files from being hosted on the same domain as the page itself (or a subdomain of that), to being hosted on a differently named domain. It's not simply parallelization Now, there is a well known technique of spreading the components of your page across multiple domains to parallelize downloading. Yahoo recommends it as do many others. For instance, www.example.com is where your HTML is hosted, then you put images on images.example.com and javascripts on scripts.example.com . This gets around the fact that most browsers limit the number of simultaneous connections per server in order to be good net citizens. The above is not what I am talking about. It's not simply redirection to a content delivery network (or maybe it is--see bottom of question) What I am talking about is hosting Javascripts specifically on an entirely different domain. Let me be specific. Just in the last year or so I've noticed that: youtube.com has moved its .JS files to ytimg.com cnn.com has moved its .JS files to cdn.turner.com weather.com has moved its .JS files to j.imwx.com Now, I know about content delivery networks like Akamai who specialize in outsourcing this for large websites. (The name "cdn" in Turner's special domain clues us in to the importance of this concept here). But note with these examples, each site has its own specifically registered domain for this purpose, and its not the domain of a content delivery network or other infrastructure provider. In fact, if you try to load the home page off most of these script domains, they usually redirect back to the main domain of the company. And if you reverse lookup the IPs involved, they sometimes appear point to a CDN company's servers, sometimes not. Why do I care? Having formerly worked at two different security companies, I have been made paranoid of malicious Javascripts. As a result, I follow the practice of whitelisting sites that I will allow Javascript (and other active content such as Java) to run on. As a result, to make a site like cnn.com work properly, I have to manually put cnn.com into a list. It's a pain in the behind, but I prefer it over the alternative. When folks used things like scripts.cnn.com to parallelize, that worked fine with appropriate wildcarding. And when folks used subdomains off the CDN company domains, I could just permit the CDN company's main domain with a wildcard in front as well and kill many birds with one stone (such as *.edgesuite.net and *.akamai.com). Now I have discovered that (as of 2008) this is not enough. Now I have to poke around in the source code of a page I want to whitelist, and figure out what "secret" domain (or domains) that site is using to store their Javascripts on. In some cases I've found I have to permit three different domains to make a site work. Why did all these major sites start doing this? EDIT: OK as "onebyone" pointed out , it does appear to be related to CDN delivery of content. So let me modify the question slightly based on his research... Why is weather.com using j.imwx.com instead of twc.vo.llnwd.net ? Why is youtube.com using s.ytimg.com instead of static.cache.l.google.com ? There has to a reasoning behind this. | Your follow-up question is essentially: Assuming a popular website is using a CDN, why would they use their own TLD like imwx.com instead of a subdomain (static.weather.com) or the CDN's domain? Well, the reason for using a domain they control versus the CDN's domain is that they retain control -- they could potentially even change CDNs entirely and only have to change a DNS record, versus having to update links in 1000s of pages/applications. So, why use nonsense domain names? Well, a big thing with helper files like .js and .css is that you want them to be cached downstream by proxies and people's browsers as much as possible. If a person hits gmail.com and all the .js is loaded out of their browser cache, the site appears much snappier to them, and it also saves bandwidth on the server end (everybody wins). The problem is that once you send HTTP headers for really aggressive caching (i.e. cache me for a week or a year or forever), these files aren't ever reliably loaded from the server any more and you can't make changes/fixes to them because things will break in people's browsers. So, what companies have to do is stage these changes and actually change the URLs of all of these files to force people's browsers to reload them. Cycling through domains like "a.imwx.com", "b.imwx.com" etc. is how this gets done. By using a nonsense domain name, the Javascript developers and their Javascript sysadmin/CDN liaison counterparts can have their own domain name/DNS that they're pushing these changes through, that they're accountable/autonomous for. Then, if any sort of cookie-blocking or script-blocking starts happening on the TLD, they just change from one nonsense TLD to kyxmlek.com or whatever. They don't have to worry about accidentally doing something evil that has countermeasure side effects on all of *.google.com. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/160376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4425/"
]
} |
160,391 | I've got a ListBox control and I'm presenting a fixed number of ListBoxItem objects in a grid layout. So I've set my ItemsPanelTemplate to be a Grid. I'm accessing the Grid from code behind to configure the RowDefinitions and ColumnDefinitions. So far it's all working as I expect. I've got some custom IValueConverter implementations for returning the Grid.Row and Grid.Column that each ListBoxItem should appear in. However I get weird binding errors sometimes, and I can't figure out exactly why they're happening, or even if they're in my code. Here's the error I get: System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=HorizontalContentAlignment; DataItem=null; target element is 'ListBoxItem' (Name=''); target property is 'HorizontalContentAlignment' (type 'HorizontalAlignment') Can anybody explain what's going on? Oh, and, here's my XAML: <UserControl.Resources> <!-- Value Converters --> <v:GridRowConverter x:Key="GridRowConverter" /> <v:GridColumnConverter x:Key="GridColumnConverter" /> <v:DevicePositionConverter x:Key="DevicePositionConverter" /> <v:DeviceBackgroundConverter x:Key="DeviceBackgroundConverter" /> <Style x:Key="DeviceContainerStyle" TargetType="{x:Type ListBoxItem}"> <Setter Property="FocusVisualStyle" Value="{x:Null}" /> <Setter Property="Background" Value="Transparent" /> <Setter Property="Grid.Row" Value="{Binding Path=DeviceId, Converter={StaticResource GridRowConverter}}" /> <Setter Property="Grid.Column" Value="{Binding Path=DeviceId, Converter={StaticResource GridColumnConverter}}" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ListBoxItem}"> <Border CornerRadius="2" BorderThickness="1" BorderBrush="White" Margin="2" Name="Bd" Background="{Binding Converter={StaticResource DeviceBackgroundConverter}}"> <TextBlock FontSize="12" HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding Path=DeviceId, Converter={StaticResource DevicePositionConverter}}" > <TextBlock.LayoutTransform> <RotateTransform Angle="270" /> </TextBlock.LayoutTransform> </TextBlock> </Border> <ControlTemplate.Triggers> <Trigger Property="IsSelected" Value="true"> <Setter TargetName="Bd" Property="BorderThickness" Value="2" /> <Setter TargetName="Bd" Property="Margin" Value="1" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </UserControl.Resources><Border CornerRadius="3" BorderThickness="3" Background="#FF333333" BorderBrush="#FF333333" > <Grid ShowGridLines="False"> <Grid.RowDefinitions> <RowDefinition Height="15" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <StackPanel Grid.Row="0" Orientation="Horizontal"> <Image Margin="20,3,3,3" Source="Barcode.GIF" Width="60" Stretch="Fill" /> </StackPanel> <ListBox ItemsSource="{Binding}" x:Name="lstDevices" Grid.Row="1" ItemContainerStyle="{StaticResource DeviceContainerStyle}" Background="#FF333333" SelectedItem="{Binding SelectedDeviceResult, ElementName=root, Mode=TwoWay}" > <ListBox.ItemsPanel> <ItemsPanelTemplate> <Grid> <Grid.LayoutTransform> <RotateTransform Angle="90" /> </Grid.LayoutTransform> </Grid> </ItemsPanelTemplate> </ListBox.ItemsPanel> </ListBox> </Grid></Border> | The binding problem comes from the default style for ListBoxItem. By default when applying styles to elements WPF looks for the default styles and applies each property that is not specifically set in the custom style from the default style. Refer to this great blog post By Ian Griffiths for more details on this behavior. Back to our problem. Here is the default style for ListBoxItem: <Style xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" TargetType="{x:Type ListBoxItem}"> <Style.Resources> <ResourceDictionary/> </Style.Resources> <Setter Property="Panel.Background"> <Setter.Value> <SolidColorBrush> #00FFFFFF </SolidColorBrush> </Setter.Value> </Setter> <Setter Property="Control.HorizontalContentAlignment"> <Setter.Value> <Binding Path="HorizontalContentAlignment" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=ItemsControl, AncestorLevel=1}"/> </Setter.Value> </Setter> <Setter Property="Control.VerticalContentAlignment"> <Setter.Value> <Binding Path="VerticalContentAlignment" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=ItemsControl, AncestorLevel=1}"/> </Setter.Value> </Setter> <Setter Property="Control.Padding"> <Setter.Value> <Thickness> 2,0,0,0 </Thickness> </Setter.Value> </Setter> <Setter Property="Control.Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ListBoxItem}"> ... </ControlTemplate> </Setter.Value> </Setter> </Style> Note that I have removed the ControlTemplate to make it compact (I have used StyleSnooper - to retrieve the style). You can see that there is a binding with a relative source set to ancestor with type ItemsControl. So in your case the ListBoxItems that are created when binding did not find their ItemsControl. Can you provide more info with what is the ItemsSource for your ListBox? P.S.: One way to remove the errors is to create new setters for HorizontalContentAlignment and VerticalContentAlignment in your custom Style. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/160391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14537/"
]
} |
160,433 | One of your team members has been appointed "technical lead" or "team lead" yet he is technically incompetent and lacks major leadership skills. By technically incompetent, I mean that the person doesn't know the difference between an abstract class and an interface, doesn't understand why coupling should be avoided, doesn't understand the concept of cohesion, provides solutions without taking some time to think, doesn't understand why we should favor composition over inheritance and doesn't get design patterns (except the singleton pattern). Plus that person has over 10 years of "experience" (yes, I did put that word in quotes because he's given a whole different dimension of what experience really is). I'm dealing with such a person at work. It's taking away the passion I have for this profession. How do you react? What do you do? | Brian, This is your team leader. Stop screwing around and get back to work! | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/160433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24346/"
]
} |
160,497 | I'm using subversion (TortoiseSVN) and I want to remove the .svn folders from my project for deployment, is there an automated way of doing this using subversion or do I have to create a custom script for this? | TortoiseSVN has an export function. This will create the entire SVN tree elsewhere without the .svn folders. Also, a lot of FTP clients have filtering, which you can add .svn to just in case you forget one day. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/160497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368/"
]
} |
160,514 | Are there are good uses of Partial Classes outside the webforms/winforms generated code scenarios? Or is this feature basically to support that? | It is in part to support scenarios (WebForms, WinForms, LINQ-to-SQL, etc) mixing generated code with programmer code. There are more reasons to use it. For example, if you have big classes in large, unwieldy files, but the classes have groups of logically related methods, partial classes may be an option to make your file sizes more manageable. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/160514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
]
} |
160,519 | Can this be done w/ linqtosql? SELECT City, SUM(DATEDIFF(minute,StartDate,Completed)) AS DowntimeFROM IncidentsGROUP BY City | It is in part to support scenarios (WebForms, WinForms, LINQ-to-SQL, etc) mixing generated code with programmer code. There are more reasons to use it. For example, if you have big classes in large, unwieldy files, but the classes have groups of logically related methods, partial classes may be an option to make your file sizes more manageable. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/160519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3396/"
]
} |
160,534 | I need to get the "td" element of a table. I do not have the ability to add a mouseover or onclick event to the "td" element, so I need to add them with JQUERY. I need JQUERY to add the mouseover and onclick event to the all "td" elements in the table. Thats what I need, maybe someone can help me out? | $(function() { $("table#mytable td").mouseover(function() { //The onmouseover code }).click(function() { //The onclick code });}); | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/160534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7644/"
]
} |
160,550 | I thought people would be working on little code projects together, but I don't see them, so here's an easy one: Code that validates a valid US Zip Code. I know there are ZIP code databases out there, but there are still uses, like web pages, quick validation, and also the fact that zip codes keep getting issued, so you might want to use weak validation. I wrote a little bit about zip codes in a side project on my wiki/blog: https://benc.fogbugz.com/default.asp?W24 There is also a new, weird type of zip code. https://benc.fogbugz.com/default.asp?W42 I can do the javascript code, but it would be interesting to see how many languages we can get here. | Javascript Regex Literal : US Zip Codes: /(^\d{5}$)|(^\d{5}-\d{4}$)/ var isValidZip = /(^\d{5}$)|(^\d{5}-\d{4}$)/.test("90210"); Some countries use Postal Codes , which would fail this pattern. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/160550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2910/"
]
} |
160,587 | I'm using Console.WriteLine() from a very simple WPF test application, but when I execute the application from the command line, I'm seeing nothing being written to the console. Does anyone know what might be going on here? I can reproduce it by creating a WPF application in VS 2008, and simply adding Console.WriteLine("text") anywhere where it gets executed. Any ideas? All I need for right now is something as simple as Console.WriteLine() . I realize I could use log4net or somet other logging solution, but I really don't need that much functionality for this application. Edit: I should have remembered that Console.WriteLine() is for console applications. Oh well, no stupid questions, right? :-)I'll just use System.Diagnostics.Trace.WriteLine() and DebugView for now. | You can use Trace.WriteLine("text"); This will output to the "Output" window in Visual Studio (when debugging). make sure to have the Diagnostics assembly included: using System.Diagnostics; | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/160587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18505/"
]
} |
160,608 | I've been wondering whether there is a good "git export" solution that creates a copy of a tree without the .git repository directory. There are at least three methods I know of: git clone followed by removing the .git repository directory. git checkout-index alludes to this functionality but starts with "Just read the desired tree into the index..." which I'm not entirely sure how to do. git-export is a third-party script that essentially does a git clone into a temporary location followed by rsync --exclude='.git' into the final destination. None of these solutions really strike me as being satisfactory. The closest one to svn export might be option 1, because both require the target directory to be empty first. But option 2 seems even better, assuming I can figure out what it means to read a tree into the index. | Probably the simplest way to achieve this is with git archive . If you really need just the expanded tree you can do something like this. git archive master | tar -x -C /somewhere/else Most of the time that I need to 'export' something from git, I want a compressed archive in any case so I do something like this. git archive master | bzip2 >source-tree.tar.bz2 ZIP archive: git archive --format zip --output /full/path/to/zipfile.zip master git help archive for more details, it's quite flexible. Be aware that even though the archive will not contain the .git directory, it will, however, contain other hidden git-specific files like .gitignore, .gitattributes, etc. If you don't want them in the archive, make sure you use the export-ignore attribute in a .gitattributes file and commit this before doing your archive. Read more... Note: If you are interested in exporting the index, the command is git checkout-index -a -f --prefix=/destination/path/ (See Greg's answer for more details) | {
"score": 12,
"source": [
"https://Stackoverflow.com/questions/160608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/893/"
]
} |
160,611 | I'm trying to unit test (JUnit) a DAO i've created. I'm using Spring as my framework, my DAO (JdbcPackageDAO) extends SimpleJdbcDaoSupport. The testing class (JdbcPackageDAOTest) extends AbstractTransactionalDataSourceSpringContextTests. I've overridden the configLocations as follows: protected String[] getConfigLocations(){ return new String[] {"classpath:company/dc/test-context.xml"};} My test-context.xml file is defined as follows: <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="dataPackageDao" class="company.data.dao.JdbcPackageDAO"> <property name="dataSource" ref="dataSource" /> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="org.hsqldb.jdbcDriver"/> <property name="url" value="jdbc:hsqldb:hsql://localhost"/> <property name="username" value="sa" /> <property name="password" value="" /> </bean> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>company/data/dao/jdbc.properties</value> </list> </property> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean></beans> I'm using HSQL as my backend, it's running in standalone mode. My IDE of choice is eclipse. When I run the class as a JUnit test here's my error (below). I have no clue as to why its happening. hsql.jar is on my build path according to Eclipse. org.springframework.transaction.CannotCreateTransactionException: Could not open JDBC Connection for transaction; nested exception is java.sql.SQLException: No suitable driver found for jdbc:hsqldb:hsql://localhost at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:219) at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:377) at org.springframework.test.AbstractTransactionalSpringContextTests.startNewTransaction(AbstractTransactionalSpringContextTests.java:387) at org.springframework.test.AbstractTransactionalSpringContextTests.onSetUp(AbstractTransactionalSpringContextTests.java:217) at org.springframework.test.AbstractSingleSpringContextTests.setUp(AbstractSingleSpringContextTests.java:101) at junit.framework.TestCase.runBare(TestCase.java:128) at org.springframework.test.ConditionalTestCase.runBare(ConditionalTestCase.java:76) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:120) at junit.framework.TestSuite.runTest(TestSuite.java:230) at junit.framework.TestSuite.run(TestSuite.java:225) at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestReference.java:130) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)Caused by: java.sql.SQLException: No suitable driver found for jdbc:hsqldb:hsql://localhost at java.sql.DriverManager.getConnection(Unknown Source) at java.sql.DriverManager.getConnection(Unknown Source) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:291) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:277) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:259) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:241) at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:182) ... 18 more | In order to have HSQLDB register itself, you need to access its jdbcDriver class. You can do this the same way as in this example . Class.forName("org.hsqldb.jdbcDriver"); It triggers static initialization of jdbcDriver class, which is: static { try { DriverManager.registerDriver(new jdbcDriver()); } catch (Exception e) {}} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/160611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17337/"
]
} |
160,614 | I have a Dynamic Data website built in Visual Studio 2008 using .NET 3.5 SP1. The site works OK on my Vista machine, but I get the following error when running it on a Windows XP machine: Server Error in '/FlixManagerWeb' Application. -------------------------------------------------------------------------------- The resource cannot be found. Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly. Requested URL: /FlixManagerWeb -------------------------------------------------------------------------------- Version Information: Microsoft .NET Framework Version:2.0.50727.3053; ASP.NET Version:2.0.50727.3053 I have added the .* -> aspnet_isapi.dll mapping in the site config, made sure that it is an "application," but that did not help. Anyone have any luck running a Dynamic Data website on Windows XP? What (if anything) special is required to get it to work? | In order to have HSQLDB register itself, you need to access its jdbcDriver class. You can do this the same way as in this example . Class.forName("org.hsqldb.jdbcDriver"); It triggers static initialization of jdbcDriver class, which is: static { try { DriverManager.registerDriver(new jdbcDriver()); } catch (Exception e) {}} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/160614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2762/"
]
} |
160,633 | Why are flat text files the state of the art for representing source code? Sure - the preprocessor and compiler need to see a flat file representation of the file, but that's easily created. It seems to me that some form of XML or binary data could represent lots of ideas that are very difficult to track, otherwise. For instance, you could embed UML diagrams right into your code. They could be generated semi-automatically, and annotated by the developers to highlight important aspects of the design. Interaction diagrams in particular. Heck, embedding any user drawing might make things more clear. Another idea is to embed comments from code reviews right into the code. There could be all sorts of aids to make merging multiple branches easier. Something I'm passionate about is not just tracking code coverage, but also looking at the parts of code covered by an automated test. The hard part is keeping track of that code, even as the source is modified. For instance, moving a function from one file to another, etc. This can be done with GUIDs, but they're rather intrusive to embed right in the text file. In a rich file format, they could be automatic and unobtrusive. So why are there no IDEs (to my knowledge, anyway) which allow you to work with code in this way? EDIT: On October 7th, 2009. Most of you got very hung up on the word "binary" in my question. I retract it. Picture XML, very minimally marking up your code. The instant before you hand it to your normal preprocessor or compiler, you strip out all of the XML markup, and pass on just the source code. In this form, you could still do all of the normal things to the file: diff, merge, edit, work with in a simple and minimal editor, feed them into thousands of tools. Yes, the diff, merge, and edit, directly with the minimal XML markup, does get a tad more complicated. But I think the value could be enormous. If an IDE existed which respected all of the XML, you could add so much more than what we can do today. For instance, your DOxygen comments could actually look like the final DOxygen output. When someone wanted to do a code review, like Code Collaborator, they could mark up the source code, in place. The XML could even be hidden behind comments. // <comment author="mcruikshank" date="2009-10-07">// Please refactor to Delegate.// </comment> And then if you want to use vi or emacs, you can just skip over the comments. If I want to use a state-of-the-art editor, I can see that in about a dozen different helpful ways. So, that's my rough idea. It's not "building blocks" of pictures that you drag on the screen... I'm not that nuts. :) | you can diff them you can merge them anyone can edit them they are simple and easy to deal with they are universally accessible to thousands of tools | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/160633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8643/"
]
} |
160,666 | I'd like to have an HTML page which displays a single PNG or JPEG image. I want the image to take up the whole screen but when I do this: <img src="whatever.jpeg" width="100%" height="100%" /> It just stretches the image and messes up the aspect ratio. How do I solve this so the image has the correct aspect ratio while scaling to the maximum size possible ? The solution posted by Wayne almost works except for the case where you have a tall image and a wide window. This code is a slight modification of his code which does what I want: <html> <head> <script> function resizeToMax(id){ myImage = new Image() var img = document.getElementById(id); myImage.src = img.src; if(myImage.width / document.body.clientWidth > myImage.height / document.body.clientHeight){ img.style.width = "100%"; } else { img.style.height = "100%"; } } </script> </head> <body> <img id="image" src="test.gif" onload="resizeToMax(this.id)"> </body></html> | Here's a quick function that will adjust the height or width to 100% depending on which is bigger. Tested in FF3, IE7 & Chrome <html><head><script>function resizeToMax(id){ myImage = new Image() var img = document.getElementById(id); myImage.src = img.src; if(myImage.width > myImage.height){ img.style.width = "100%"; } else { img.style.height = "100%"; }}</script></head><body><img id="image" src="test.gif" onload="resizeToMax(this.id)"></body></html> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/160666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5324/"
]
} |
160,694 | What Javascript libraries can you recommend for syntax highlighting <code> blocks in HTML? (One suggestion per answer please). | StackOverflow uses the Prettify library. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/160694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17453/"
]
} |
160,697 | I personally like the exclusive or , ^ , operator when it makes sense in the context of boolean checks because of its conciseness. I much prefer to write if (boolean1 ^ boolean2){ //do it} than if((boolean1 && !boolean2) || (boolean2 && !boolean1)){ //do it} but I often get confused looks from other experienced Java developers (not just the newbies), and sometimes comments about how it should only be used for bitwise operations. I'm curious as to the best practices regarding the usage of the ^ operator. | You can simply use != instead. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/160697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17123/"
]
} |
160,742 | I'm trying to generate some code at runtime where I put in some boiler-plate stuff and the user is allowed to enter the actual working code. My boiler-plate code looks something like this: using System;public class ClassName{ public double TheFunction(double input) { // user entered code here }} Ideally, I think I want to use string.Format to insert the user code and create a unique class name, but I get an exception on the format string unless it looks like this: string formatString = @"using System;public class ClassName{0} public double TheFunction(double input) {0} {2} {1}{1}"; Then I call string.Format like this: string entireClass = string.Format(formatString, "{", "}", userInput); This is fine and I can deal with the ugliness of using {0} and {1} in the format string in place of my curly braces except that now my user input cannot use curly braces either. Is there a way to either escape the curly braces in my format string, or a good way to turn the curly braces in the user code into {0}'s and {1}'s? BTW, I know that this kind of thing is a security problem waiting to happen, but this is a Windows Forms app that's for internal use on systems that are not connected to the net so the risk is acceptable in this situation. | Escape them by doubling them up: string s = String.Format("{{ hello to all }}");Console.WriteLine(s); //prints '{ hello to all }' From http://msdn.microsoft.com/en-us/netframework/aa569608.aspx#Question1 | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/160742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4797/"
]
} |
160,776 | For my server app, I need to check if an ip address is in our blacklist. What is the most efficient way of comparing ip addresses? Would converting the IP address to integer and comparing them efficient? | Depends what language you're using, but an IP address is usually stored as a 32-bit unsigned integer, at least at the network layer, making comparisons quite fast. Even if it's not, unless you're designing a high performance packet switching application it's not likely to be a performance bottleneck. Avoid premature optimization - design your program for testability and scalability and if you have performance problems then you can use a profiler to see where the bottlenecks are. Edit: to clarify, IPv4 addresses are stored as 32-bit integers, plus a netmask (which is not necessary for IP address comparisons). If you're using the newer and currently more rare IPv6, then the addresses will be 128 bits long. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/160776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1599/"
]
} |
160,791 | Maybe this is a dumb question, but I have the following behavior in Visual Studio 2005 while designing forms: 1 - Drop a control onto the form (suppose it's a Label, just for discussion) 2 - Drag that label to a specific location (aligning w/other controls, whatever) 3 - Release the mouse button 4 - The control is still stuck to the mouse!!! To get it un-stuck from the mouse, I have to hit ESC, which restores the Label to it's original location. This is driving me nuts. I literally have to use the arrow keys to move each control into place, pixel-by-pixel. I don't observe this behavior anywhere else in VS2005, nor do I observe it in the OS in general. I am running on Windows XP inside a Parallels Virtual Machine, hosted on OS X. I don't think there is a driver problem though, b/c as I already said, no other apps demonstrate anything like this. Please tell me there is some tiny checkbox buried somewhere that will turn off this behavior. | Depends what language you're using, but an IP address is usually stored as a 32-bit unsigned integer, at least at the network layer, making comparisons quite fast. Even if it's not, unless you're designing a high performance packet switching application it's not likely to be a performance bottleneck. Avoid premature optimization - design your program for testability and scalability and if you have performance problems then you can use a profiler to see where the bottlenecks are. Edit: to clarify, IPv4 addresses are stored as 32-bit integers, plus a netmask (which is not necessary for IP address comparisons). If you're using the newer and currently more rare IPv6, then the addresses will be 128 bits long. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/160791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672/"
]
} |
160,793 | I have an Open Source app and I have it working on Windows, Linux and Macintosh ( it's in C++ and built with gcc ). I've only tested it on a few different flavors of Linux so I don't know if it compiles and runs on all different Linux versions. Is there a place where I can upload my code and have it tested across a bunch of different systems like other Linux flavors and things like, Solaris, FreeBSD and other operating systems? What would be great is if I can have it directly connect to my svn repository and grab the latest code and then email me back any compile errors generated and what the OS was that it had a problem with. I would be happy to just know it compiles as it is a GUI based app so I wouldn't expect it to actually be ran and tested. | There are a few options but there don't appear to be many (any?) free services like this, which isn't surprising considering the amount of effort and resources it requires. Sourceforge used to operate a compile farm like what you describe but it shut down a year or so ago. You might look into some of the following. If you're inclined to pay for a service or roll your own, then some of these links may be useful. If you're just looking for a free open source compile/build farm that covers multiple platforms it looks like you're pretty much out of luck. OpenSuse Build Service Mentioned by Ted first, worth repeating - only for Linux currently but does support a number of distros. GCC Compile Farm Mainly focused on testing builds for GCC but does also host a few other projects such as coLinux, BTG BitTorrent client, ClamAV, and others. May be something you can take advantage of, though I don't see what OSes are in the compile farm (contains at least Linux and Solaris based on the page notes). BuildLocker BuildLocker is a Web-based continuous integration solution for Java and .NET projects. BuildLocker is a virtual dedicated build machine that helps teams find bugs earlier in the development cycle, saving time and money. BuildLocker manages scheduled automated builds of source code in your ProjectLocker Source Control repository. Just check in the source code, and scheduled builds validate the integrity of the code. BuildLocker can even run automated tests, and can alert you anytime a test fails. CruiseControl CruiseControl is a framework for a continuous build process. It includes, but is not limited to, plugins for email notification, Ant, and various source control tools. A web interface is provided to view the details of the current and previous builds. Interesting side note, CruiseControl is actually used by StackOverflow's dev team for automated build testing as well, according to the podcast. Hudson Hudson monitors executions of repeated jobs, such as building a software project or jobs run by cron. RunCodeRun Mentioned in the other linked question, only supports Ruby projects and is in private beta currently. However, if your project is in Ruby, it might be worth keeping an eye on RunCodeRun. CI Feature Matrix There are many Continuous Integration systems available. This page is an attempt to keep an unbiased comparison of as many as possible of them. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/160793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13676/"
]
} |
160,848 | Does the compiler optimize out any multiplications by 1? That is, consider: int a = 1;int b = 5 * a; Will the expression 5 * a be optimized into just 5? If not, will it if a is defined as: const int a = 1; | It will pre-calculate any constant expressions when it compiles, including string concatenation. Without the const it will be left alone. Your first example compiles to this IL: .maxstack 2.locals init ([0] int32, [1] int32)ldc.i4.1 //load 1stloc.0 //store in 1st local variableldc.i4.5 //load 5ldloc.0 //load 1st variablemul // 1 * 5stloc.1 // store in 2nd local variable The second example compiles to this: .maxstack 1.locals init ( [0] int32 )ldc.i4.5 //load 5 stloc.0 //store in local variable | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/160848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16942/"
]
} |
160,859 | I understand what are lambda functions in Python, but I can't find what is the meaning of "lambda binding" by searching the Python docs.A link to read about it would be great.A trivial explained example would be even better.Thank you. | First, a general definition: When a program or function statement is executed, the current values of formal parameters are saved (on the stack) and within the scope of the statement, they are bound to the values of the actual arguments made in the call. When the statement is exited, the original values of those formal arguments are restored. This protocol is fully recursive. If within the body of a statement, something is done that causes the formal parameters to be bound again, to new values, the lambda-binding scheme guarantees that this will all happen in an orderly manner. Now, there is an excellent python example in a discussion here : "...there is only one binding for x : doing x = 7 just changes the value in the pre-existing binding. That's why def foo(x): a = lambda: x x = 7 b = lambda: x return a,b returns two functions that both return 7; if there was a new binding after the x = 7 , the functions would return different values [assuming you don't call foo(7), of course. Also assuming nested_scopes]...." | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/160859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15073/"
]
} |
160,890 | I'm a Java head mainly, and I want a way to generate a pseudo-random number between 0 and 74. In Java I would use the method: Random.nextInt(74) I'm not interested in a discussion about seeds or true randomness, just how you accomplish the same task in Objective-C. I've scoured Google, and there just seems to be lots of different and conflicting bits of information. | You should use the arc4random_uniform() function. It uses a superior algorithm to rand . You don't even need to set a seed. #include <stdlib.h>// ...// ...int r = arc4random_uniform(74); The arc4random man page: NAME arc4random, arc4random_stir, arc4random_addrandom -- arc4 random number generatorLIBRARY Standard C Library (libc, -lc)SYNOPSIS #include <stdlib.h> u_int32_t arc4random(void); void arc4random_stir(void); void arc4random_addrandom(unsigned char *dat, int datlen);DESCRIPTION The arc4random() function uses the key stream generator employed by the arc4 cipher, which uses 8*8 8 bit S-Boxes. The S-Boxes can be in about (2**1700) states. The arc4random() function returns pseudo- random numbers in the range of 0 to (2**32)-1, and therefore has twice the range of rand(3) and random(3). The arc4random_stir() function reads data from /dev/urandom and uses it to permute the S-Boxes via arc4random_addrandom(). There is no need to call arc4random_stir() before using arc4random(), since arc4random() automatically initializes itself.EXAMPLES The following produces a drop-in replacement for the traditional rand() and random() functions using arc4random(): #define foo4random() (arc4random() % ((unsigned)RAND_MAX + 1)) | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/160890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6044/"
]
} |
160,923 | I am pretty sure I have seen this before, but I haven't found out / remembered how to do it. I want to have a line of code that when executed from the Delphi debugger I want the debugger to pop-up like there was a break point on that line. Something like: FooBar := Foo(Bar);SimulateBreakPoint; // Cause break point to occur in Delphi IDE if attachedWriteLn('Value: ' + FooBar); Hopefully that makes sense. I know I could use an exception, but that would be a lot more overhead then I want. It is for some demonstration code. Thanks in advance! | To trigger the debugger from code (supposedly, I don't have a copy of delphi handy to try): asm int 3 end; See this page: http://17slon.com/blogs/gabr/2008/03/debugging-with-lazy-breakpoints.html | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/160923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/255/"
]
} |
160,924 | Sometimes when I try to start Firefox it says "a Firefox process is already running". So I have to do this: jeremy@jeremy-desktop:~$ ps aux | grep firefoxjeremy 7451 25.0 27.4 170536 65680 ? Sl 22:39 1:18 /usr/lib/firefox-3.0.1/firefoxjeremy 7578 0.0 0.3 3004 768 pts/0 S+ 22:44 0:00 grep firefoxjeremy@jeremy-desktop:~$ kill 7451 What I'd like is a command that would do all that for me. It would take an input string and grep for it (or whatever) in the list of processes, and would kill all the processes in the output: jeremy@jeremy-desktop:~$ killbyname firefox I tried doing it in PHP but exec('ps aux') seems to only show processes that have been executed with exec() in the PHP script itself (so the only process it shows is itself.) | pkill firefox More information: http://linux.about.com/library/cmd/blcmdl1_pkill.htm | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/160924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/813/"
]
} |
160,930 | How can I check if a given number is even or odd in C? | Use the modulo (%) operator to check if there's a remainder when dividing by 2: if (x % 2) { /* x is odd */ } A few people have criticized my answer above stating that using x & 1 is "faster" or "more efficient". I do not believe this to be the case. Out of curiosity, I created two trivial test case programs: /* modulo.c */#include <stdio.h>int main(void){ int x; for (x = 0; x < 10; x++) if (x % 2) printf("%d is odd\n", x); return 0;}/* and.c */#include <stdio.h>int main(void){ int x; for (x = 0; x < 10; x++) if (x & 1) printf("%d is odd\n", x); return 0;} I then compiled these with gcc 4.1.3 on one of my machines 5 different times: With no optimization flags. With -O With -Os With -O2 With -O3 I examined the assembly output of each compile (using gcc -S) and found that in each case, the output for and.c and modulo.c were identical (they both used the andl $1, %eax instruction). I doubt this is a "new" feature, and I suspect it dates back to ancient versions. I also doubt any modern (made in the past 20 years) non-arcane compiler, commercial or open source, lacks such optimization. I would test on other compilers, but I don't have any available at the moment. If anyone else would care to test other compilers and/or platform targets, and gets a different result, I'd be very interested to know. Finally, the modulo version is guaranteed by the standard to work whether the integer is positive, negative or zero, regardless of the implementation's representation of signed integers. The bitwise-and version is not. Yes, I realise two's complement is somewhat ubiquitous, so this is not really an issue. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/160930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24391/"
]
} |
160,948 | How can I tell if SP1 has been installed on VS2008? e.g. If I'm working on a co-worker's machine - how can I tell if he/she has installed SP1 for VS2008? | In Help->About, you can view the installed products. You should see something similar to Microsoft Visual Studio Team System 2008 Team Suite - ENU Service Pack 1 (KB945140) KB945140 in the list of entries. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/160948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
]
} |
160,960 | I have a function that takes a struct, and I'm trying to store its variables in array: int detect_prm(Param prm) { int prm_arr[] = {prm.field1, prm.field2, prm.field3}; return 0;} But with gcc -Wall -ansi -pedantic-errors -Werror I get the following error: initializer element is not computable at load time It looks fine to me, what's wrong? | This is illegal in C. Initializer lists must be constant compile time expressions. Do the following instead: int prm_arr[3];prm_arr[0] = prm.field1;prm_arr[1] = prm.field2;prm_arr[2] = prm.field3; | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/160960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9628/"
]
} |
160,970 | If I have two variables: Object obj;String methodName = "getName"; Without knowing the class of obj , how can I call the method identified by methodName on it? The method being called has no parameters, and a String return value. It's a getter for a Java bean . | Coding from the hip, it would be something like: java.lang.reflect.Method method;try { method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);} catch (SecurityException e) { ... } catch (NoSuchMethodException e) { ... } The parameters identify the very specific method you need (if there are several overloaded available, if the method has no arguments, only give methodName ). Then you invoke that method by calling try { method.invoke(obj, arg1, arg2,...);} catch (IllegalArgumentException e) { ... } catch (IllegalAccessException e) { ... } catch (InvocationTargetException e) { ... } Again, leave out the arguments in .invoke , if you don't have any. But yeah. Read about Java Reflection | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/160970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6340/"
]
} |
160,971 | I've read some of the recent language vs. language questions with interest... Perl vs. Python , Python vs. Java , Can one language be better than another? One thing I've noticed is that a lot of us have very superficial reasons for disliking languages. We notice these things at first glance and they turn us off. We shun what are probably perfectly good languages as a result of features that we'd probably learn to love or ignore in 2 seconds if we bothered. Well, I'm as guilty as the next guy, if not more. Here goes: Ruby: All the Ruby example code I see uses the puts command, and that's a sort of childish Yiddish anatomical term. So as a result, I can't take Ruby code seriously even though I should. Python: The first time I saw it, I smirked at the whole significant whitespace thing. I avoided it for the next several years. Now I hardly use anything else. Java: I don't like identifiersThatLookLikeThis. I'm not sure why exactly. Lisp: I have trouble with all the parentheses. Things of different importance and purpose (function declarations, variable assignments, etc.) are not syntactically differentiated and I'm too lazy to learn what's what. Fortran: uppercase everything hurts my eyes. I know modern code doesn't have to be written like that, but most example code is... Visual Basic: it bugs me that Dim is used to declare variables, since I remember the good ol' days of GW-BASIC when it was only used to dimension arrays. What languages did look right to me at first glance? Perl, C, QBasic, JavaScript, assembly language, BASH shell, FORTH. Okay, now that I've aired my dirty laundry... I want to hear yours. What are your language hangups? What superficial features bother you? How have you gotten over them? | I hate Hate HATE "End Function" and "End IF" and "If... Then" parts of VB. I would much rather see a curly bracket instead. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/160971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20789/"
]
} |
160,974 | Basically I have the following class: class StateMachine {...StateMethod stateA();StateMethod stateB();...}; The methods stateA() and stateB() should be able return pointers to stateA() and stateB().How to typedef the StateMethod? | GotW #57 says to use a proxy class with an implicit conversion for this very purpose. struct StateMethod;typedef StateMethod (StateMachine:: *FuncPtr)(); struct StateMethod{ StateMethod( FuncPtr pp ) : p( pp ) { } operator FuncPtr() { return p; } FuncPtr p;};class StateMachine { StateMethod stateA(); StateMethod stateB();};int main(){ StateMachine *fsm = new StateMachine(); FuncPtr a = fsm->stateA(); // natural usage syntax return 0;} StateMethod StateMachine::stateA{ return stateA; // natural return syntax}StateMethod StateMachine::stateB{ return stateB;} This solution has three main strengths: It solves the problem as required. Better still, it's type-safe and portable. Its machinery is transparent: You get natural syntax for the caller/user, and natural syntax for the function's own "return stateA;" statement. It probably has zero overhead: On modern compilers, the proxy class, with its storage and functions, should inline and optimize away to nothing. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/160974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1692070/"
]
} |
160,995 | I tried this XAML: <Slider Width="250" Height="25" Minimum="0" Maximum="1" MouseLeftButtonDown="slider_MouseLeftButtonDown" MouseLeftButtonUp="slider_MouseLeftButtonUp" /> And this C#: private void slider_MouseLeftButtonDown(object sender, MouseButtonEventArgs e){sliderMouseDown = true;}private void slider_MouseLeftButtonUp(object sender, MouseButtonEventArgs e){sliderMouseDown = false;} The sliderMouseDown variable never changes because the MouseLeftButtonDown and MouseLeftButtonUp events are never raised. How can I get this code to work when a user has the left mouse button down on a slider to have a bool value set to true, and when the mouse is up, the bool is set to false? | Sliders swallow the MouseDown Events (similar to the button). You can register for the PreviewMouseDown and PreviewMouseUp events which get fired before the slider has a chance to handle them. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/160995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23939/"
]
} |
161,030 | In .NET is there a way to enable Assembly.Load tracing? I know while running under the debugger it gives you a nice message like "Loaded 'assembly X'" but I want to get a log of the assembly loads of my running application outside the debugger, preferably intermingled with my Debug/Trace log messages. I'm tracing out various things in my application and I basically want to know what action triggered a particular assembly to be loaded. | Get the AppDomain for your application and attach to the AssemblyLoad event. Example (C#): AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(OnAssemblyLoad); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/161030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12784/"
]
} |
161,053 | This question may sound fairly elementary, but this is a debate I had with another developer I work with. I was taking care to stack allocate things where I could, instead of heap allocating them. He was talking to me and watching over my shoulder and commented that it wasn't necessary because they are the same performance wise. I was always under the impression that growing the stack was constant time, and heap allocation's performance depended on the current complexity of the heap for both allocation (finding a hole of the proper size) and de-allocating (collapsing holes to reduce fragmentation, as many standard library implementations take time to do this during deletes if I am not mistaken). This strikes me as something that would probably be very compiler dependent. For this project in particular I am using a Metrowerks compiler for the PPC architecture. Insight on this combination would be most helpful, but in general, for GCC, and MSVC++, what is the case? Is heap allocation not as high performing as stack allocation? Is there no difference? Or are the differences so minute it becomes pointless micro-optimization. | Stack allocation is much faster since all it really does is move the stack pointer. Using memory pools, you can get comparable performance out of heap allocation, but that comes with a slight added complexity and its own headaches. Also, stack vs. heap is not only a performance consideration; it also tells you a lot about the expected lifetime of objects. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/161053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1366/"
]
} |
161,127 | We have a scenario where we want to display a list of items and indicate which is the "current" item (with a little arrow marker or a changed background colour). ItemsControl is no good to us, because we need the context of "SelectedItem". However, we want to move the selection programattically and not allow the user to change it. Is there a simple way to make a ListBox non-interactive? We can fudge it by deliberately swallowing mouse and keyboard events, but am I missing some fundamental property (like setting "IsEnabled" to false without affecting its visual style) that gives us what we want? Or ... is there another WPF control that's the best of both worlds - an ItemsControl with a SelectedItem property? | One option is to set ListBoxItem.IsEnabled to false : <ListBox x:Name="_listBox"> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="IsEnabled" Value="False"/> </Style> </ListBox.ItemContainerStyle></ListBox> This ensures that the items are not selectable, but they may not render how you like. To fix this, you can play around with triggers and/or templates. For example: <ListBox x:Name="_listBox"> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="IsEnabled" Value="False"/> <Style.Triggers> <Trigger Property="IsEnabled" Value="False"> <Setter Property="Foreground" Value="Red" /> </Trigger> </Style.Triggers> </Style> </ListBox.ItemContainerStyle></ListBox> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/161127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615/"
]
} |
161,177 | Does C++ support ' finally ' blocks? What is the RAII idiom ? What is the difference between C++'s RAII idiom and C#'s 'using' statement ? | No, C++ does not support 'finally' blocks. The reason is that C++ instead supports RAII: "Resource Acquisition Is Initialization" -- a poor name † for a really useful concept. The idea is that an object's destructor is responsible for freeing resources. When the object has automatic storage duration, the object's destructor will be called when the block in which it was created exits -- even when that block is exited in the presence of an exception. Here is Bjarne Stroustrup's explanation of the topic. A common use for RAII is locking a mutex: // A class with implements RAIIclass lock{ mutex &m_;public: lock(mutex &m) : m_(m) { m.acquire(); } ~lock() { m_.release(); }};// A class which uses 'mutex' and 'lock' objectsclass foo{ mutex mutex_; // mutex for locking 'foo' objectpublic: void bar() { lock scopeLock(mutex_); // lock object. foobar(); // an operation which may throw an exception // scopeLock will be destructed even if an exception // occurs, which will release the mutex and allow // other functions to lock the object and run. }}; RAII also simplifies using objects as members of other classes. When the owning class' is destructed, the resource managed by the RAII class gets released because the destructor for the RAII-managed class gets called as a result. This means that when you use RAII for all members in a class that manage resources, you can get away with using a very simple, maybe even the default, destructor for the owner class since it doesn't need to manually manage its member resource lifetimes. (Thanks to Mike B for pointing this out.) For those familliar with C# or VB.NET, you may recognize that RAII is similar to .NET deterministic destruction using IDisposable and 'using' statements . Indeed, the two methods are very similar. The main difference is that RAII will deterministically release any type of resource -- including memory. When implementing IDisposable in .NET (even the .NET language C++/CLI), resources will be deterministically released except for memory. In .NET, memory is not deterministically released; memory is only released during garbage collection cycles. † Some people believe that "Destruction is Resource Relinquishment" is a more accurate name for the RAII idiom. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/161177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6386/"
]
} |
161,184 | I have recently been working with Python using Komodo Edit and other simpler editors but now I am doing a project which is to be done in C# using VS 08. I would appreciate any hints on how to get productive on that platform as quickly as possible. | As far as becoming proficient with C# I would highly recommend Programming C# and C# in Depth . For Visual Studio, start poking around in the IDE a lot, play around, get familiar with it. Start with simple projects and explore all the different aspects. Learn how to optimize Visual Studio and get familiar with some of the great keyboard shortcuts / hidden features of the IDE. Definitely do each of the following at least once: Projects: Create a simple console application (e.g. hello world) Create a class library (managed .dll) and use it from another application you create Create a simple windows application Create a simple asp.net web app Debugging: Debug a command line app Get familiar with: breakpoints, the locals and watch windows, step over, step into, step out of, continue, stop debugging Create a command line app which uses a function in a class library. Store the dll and symbol file (.pdb) for the library but delete the source code, debug through app as it goes into the library Debug into a webservice Learn how to use ILDasm and ILAsm Command Line: Get familiar with the Visual Studio command line environment Build using only the command line Debug from the command line using devenv.exe /debugexe Use ILDasm / ILAsm from the command line to disassemble a simple app into .IL, reassemble it into a differently named file, test to see that it still works Testing: Create unit tests (right click in a method, select the option to create a test) Learn how to: run all unit tests, run all unit tests under the debugger, rerun failed unit tests, see details on test failures, run a subset of unit tests Learn how to collect code coverage statistics for your tests Source Control: Learn how to interact with your source control system of choice while developing using VS Refactoring et al: Become familiar with all of the built-in refactorings (especially rename and extract method) Use "Go To Definition" Use "Find All References" Use "Find In Files" (ctrl-shift-F) IDE & Keyboard Shortcuts: Learn how to use the designer well for web and winforms Get very familiar with the Solution Explorer window Experiment with different window layouts until you find one your comfortable with, keep experimenting later to see if that's still the best choice Learn the ins and outs of intellisense, use it to your advantage as much as possible Learn the keyboard shortcut for everything you do | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/161184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9510/"
]
} |
161,224 | Hibernate has a handful of methods that, one way or another, takes your object and puts it into the database. What are the differences between them, when to use which, and why isn't there just one intelligent method that knows when to use what? The methods that I have identified thus far are: save() update() saveOrUpdate() saveOrUpdateCopy() merge() persist() | Here's my understanding of the methods. Mainly these are based on the API though as I don't use all of these in practice. saveOrUpdate Calls either save or update depending on some checks. E.g. if no identifier exists, save is called. Otherwise update is called. save Persists an entity. Will assign an identifier if one doesn't exist. If one does, it's essentially doing an update. Returns the generated ID of the entity. update Attempts to persist the entity using an existing identifier. If no identifier exists, I believe an exception is thrown. saveOrUpdateCopy This is deprecated and should no longer be used. Instead there is... merge Now this is where my knowledge starts to falter. The important thing here is the difference between transient, detached and persistent entities. For more info on the object states, take a look here . With save & update, you are dealing with persistent objects. They are linked to a Session so Hibernate knows what has changed. But when you have a transient object, there is no session involved. In these cases you need to use merge for updates and persist for saving. persist As mentioned above, this is used on transient objects. It does not return the generated ID. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/161224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2238/"
]
} |
161,252 | I'm trying to run some commands in paralel, in background, using bash. Here's what I'm trying to do: forloop { //this part is actually written in perl //call command sequence print `touch .file1.lock; cp bigfile1 /destination; rm .file1.lock;`;} The part between backticks (``) spawns a new shell and executes the commands in succession. The thing is, control to the original program returns only after the last command has been executed. I would like to execute the whole statement in background (I'm not expecting any output/return values) and I would like the loop to continue running. The calling program (the one that has the loop) would not end until all the spawned shells finish. I could use threads in perl to spawn different threads which call different shells, but it seems an overkill... Can I start a shell, give it a set of commands and tell it to go to the background? | I haven't tested this but how about print `(touch .file1.lock; cp bigfile1 /destination; rm .file1.lock;) &`; The parentheses mean execute in a subshell but that shouldn't hurt. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/161252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23780/"
]
} |
161,315 | I wrote a small web app using ruby on rails, its main purpose is to upload, store, and display results from xml(files can be up to several MB) files. After running for about 2 months I noticed that the mongrel process was using about 4GB of memory. I did some research on debugging ruby memory leaks and could not find much. So I have two questions. Are there any good tools that can be used to find memory leaks in Ruby/rails? What type of coding patterns cause memory leaks in ruby? | Some tips to find memory leaks in Rails: use the Bleak House plugin implement Scout monitoring specifically the memory usage profiler try another simple memory usage logger The first is a graphical exploration of memory usage by objects in the ObjectSpace. The last two will help you identify specific usage patterns that are inflating memory usage, and you can work from there. As for specific coding-patterns, from experience you have to watch anything that's dealing with file io, image processing, working with massive strings and the like. I would check whether you are using the most appropriate XML library - ReXML is known to be slow and believed to be leaky (I have no proof of that!). Also check whether you can memoize expensive operations. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/161315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5004/"
]
} |
161,378 | I have a WinForms TreeView with one main node and several sub-nodes. How can I hide the + (plus sign) in the main node? | Treview Property: .ShowRootLines = false When ShowRootLines is false, the Plus/Minus sign will not be shown for the root node, but will still show when necessary on child nodes. With the Plus/Minus sign hidden, you might consider executing the Expand() method of the root node once the tree is populated. That will make sure that the root node shows all first-level child nodes. Note: There is a ShowPlusMinus property on the TreeView, but it works on all nodes. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/161378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
161,404 | I have three tables, A, B, C, where A is many to one B, and B is many to one C. I'd like a list of all C's in A. My tables are something like this: A[id, valueA, lookupB], B[id, valueB, lookupC], C[id, valueC]. I've written a query with two nested SELECTs, but I'm wondering if it's possible to do INNER JOIN with DISTINCT somehow. SELECT valueCFROM CINNER JOIN( SELECT DISTINCT lookupC FROM B INNER JOIN ( SELECT DISTINCT lookupB FROM A ) A2 ON B.id = A2.lookupB) B2 ON C.id = B2.lookupC EDIT:The tables are fairly large, A is 500k rows, B is 10k rows and C is 100 rows, so there are a lot of uneccesary info if I do a basic inner join and use DISTINCT in the end, like this: SELECT DISTINCT valueCFROM C INNER JOIN B on C.id = B.lookupBINNER JOIN A on B.id = A.lookupB This is very, very slow (magnitudes times slower than the nested SELECT I do above. | I did a test on MS SQL 2005 using the following tables: A 400K rows, B 26K rows and C 450 rows. The estimated query plan indicated that the basic inner join would be 3 times slower than the nested sub-queries, however when actually running the query, the basic inner join was twice as fast as the nested queries, The basic inner join took 297ms on very minimal server hardware. What database are you using, and what times are you seeing? I'm thinking if you are seeing poor performance then it is probably an index problem. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/161404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2973/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.