source_id
int64
1
74.7M
question
stringlengths
0
40.2k
response
stringlengths
0
111k
metadata
dict
165,790
I'm used to coding Java Swing UIs, and in those if you have some properties that change, and you want your UI to update, you would implement the observer/observable pattern. In Java you do this normally by having your class maintain a list of listeners that it notifies of different events. I've played with Objective-C on the Mac, and that has KVC and binding which seems to work very nicely, and requires less code. The iPhone SDK doesn't seem to have this functionality though, so my question is:If I have a class that holds data that changes, what's the best way for me to register a UI component with that class so that it can be notified of changes in the data that it needs to display?
There are two built-in ways of doing observation in Cocoa: Key-Value Observing and notifications. In neither system do you need to maintain or notify a collection of observers yourself; the framework will handle that for you. Key-Value Observing (KVO) lets you observe a property of an object — including even a property that represents a collection — and be notified of changes to that property. You just need to send the object -addObserver:forKeyPath:options:context: passing the object you want to receive updates, the key path of the property (relative to the receiver) for which you want to receive updates, and the types of updates you want to receive. (There are similar methods you can use if you want to observe a property representing a collection.) Notifications are older and heavier-weight. You register with an NSNotificationCenter — usually the default center — an object and selector pair to be passed a notification when an event occurs. The notification object itself can contain arbitrary data via its userInfo property, and you can choose to observe all notifications of a specific name rather than those that apply to a particular object. Which should you use in any particular case? In general, if you care about changes to a specific property of a specific object, use Key-Value Observing. That's what it's designed for and it's intentionally lightweight. (Among other uses, it is the foundation on which Cocoa Bindings are built.) If you care about a change in state that isn't represented by a property, then notifications are more appropriate. For example, to stay in sync when the user changes the name of a model object, I'd use KVO. To know when an entire object graph was saved, I'd use notifications.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/165790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6044/" ] }
165,796
I must be getting daft, but I can't seem to find how to read old-fashioned ini files with VB 6.0. All I can seem to find is about reading from and writing to the registry. Can someone push me in the right direction? Mind you, I am not a programmer, just a hobbyist trying to have some harmless fun with his computer, so please don't be to harsh when you point out the bleedin' obvious.
There are two built-in ways of doing observation in Cocoa: Key-Value Observing and notifications. In neither system do you need to maintain or notify a collection of observers yourself; the framework will handle that for you. Key-Value Observing (KVO) lets you observe a property of an object — including even a property that represents a collection — and be notified of changes to that property. You just need to send the object -addObserver:forKeyPath:options:context: passing the object you want to receive updates, the key path of the property (relative to the receiver) for which you want to receive updates, and the types of updates you want to receive. (There are similar methods you can use if you want to observe a property representing a collection.) Notifications are older and heavier-weight. You register with an NSNotificationCenter — usually the default center — an object and selector pair to be passed a notification when an event occurs. The notification object itself can contain arbitrary data via its userInfo property, and you can choose to observe all notifications of a specific name rather than those that apply to a particular object. Which should you use in any particular case? In general, if you care about changes to a specific property of a specific object, use Key-Value Observing. That's what it's designed for and it's intentionally lightweight. (Among other uses, it is the foundation on which Cocoa Bindings are built.) If you care about a change in state that isn't represented by a property, then notifications are more appropriate. For example, to stay in sync when the user changes the name of a model object, I'd use KVO. To know when an entire object graph was saved, I'd use notifications.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/165796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17382/" ] }
165,808
I'm looking for very simple obfuscation (like encrypt and decrypt but not necessarily secure) functionality for some data. It's not mission critical. I need something to keep honest people honest, but something a little stronger than ROT13 or Base64 . I'd prefer something that is already included in the .NET framework 2.0, so I don't have to worry about any external dependencies. I really don't want to have to mess around with public/private keys, etc. I don't know much about encryption, but I do know enough to know that anything I wrote would be less than worthless... In fact, I'd probably screw up the math and make it trivial to crack.
Other answers here work fine, but AES is a more secure and up-to-date encryption algorithm. This is a class that I obtained a few years ago to perform AES encryption that I have modified over time to be more friendly for web applications (e,g. I've built Encrypt/Decrypt methods that work with URL-friendly string). It also has the methods that work with byte arrays. NOTE: you should use different values in the Key (32 bytes) and Vector (16 bytes) arrays! You wouldn't want someone to figure out your keys by just assuming that you used this code as-is! All you have to do is change some of the numbers (must be <= 255) in the Key and Vector arrays (I left one invalid value in the Vector array to make sure you do this...). You can use https://www.random.org/bytes/ to generate a new set easily: generate Key generate Vector Using it is easy: just instantiate the class and then call (usually) EncryptToString(string StringToEncrypt) and DecryptString(string StringToDecrypt) as methods. It couldn't be any easier (or more secure) once you have this class in place. using System;using System.Data;using System.Security.Cryptography;using System.IO;public class SimpleAES{ // Change these keys private byte[] Key = __Replace_Me__({ 123, 217, 19, 11, 24, 26, 85, 45, 114, 184, 27, 162, 37, 112, 222, 209, 241, 24, 175, 144, 173, 53, 196, 29, 24, 26, 17, 218, 131, 236, 53, 209 }); // a hardcoded IV should not be used for production AES-CBC code // IVs should be unpredictable per ciphertext private byte[] Vector = __Replace_Me__({ 146, 64, 191, 111, 23, 3, 113, 119, 231, 121, 2521, 112, 79, 32, 114, 156 }); private ICryptoTransform EncryptorTransform, DecryptorTransform; private System.Text.UTF8Encoding UTFEncoder; public SimpleAES() { //This is our encryption method RijndaelManaged rm = new RijndaelManaged(); //Create an encryptor and a decryptor using our encryption method, key, and vector. EncryptorTransform = rm.CreateEncryptor(this.Key, this.Vector); DecryptorTransform = rm.CreateDecryptor(this.Key, this.Vector); //Used to translate bytes to text and vice versa UTFEncoder = new System.Text.UTF8Encoding(); } /// -------------- Two Utility Methods (not used but may be useful) ----------- /// Generates an encryption key. static public byte[] GenerateEncryptionKey() { //Generate a Key. RijndaelManaged rm = new RijndaelManaged(); rm.GenerateKey(); return rm.Key; } /// Generates a unique encryption vector static public byte[] GenerateEncryptionVector() { //Generate a Vector RijndaelManaged rm = new RijndaelManaged(); rm.GenerateIV(); return rm.IV; } /// ----------- The commonly used methods ------------------------------ /// Encrypt some text and return a string suitable for passing in a URL. public string EncryptToString(string TextValue) { return ByteArrToString(Encrypt(TextValue)); } /// Encrypt some text and return an encrypted byte array. public byte[] Encrypt(string TextValue) { //Translates our text value into a byte array. Byte[] bytes = UTFEncoder.GetBytes(TextValue); //Used to stream the data in and out of the CryptoStream. MemoryStream memoryStream = new MemoryStream(); /* * We will have to write the unencrypted bytes to the stream, * then read the encrypted result back from the stream. */ #region Write the decrypted value to the encryption stream CryptoStream cs = new CryptoStream(memoryStream, EncryptorTransform, CryptoStreamMode.Write); cs.Write(bytes, 0, bytes.Length); cs.FlushFinalBlock(); #endregion #region Read encrypted value back out of the stream memoryStream.Position = 0; byte[] encrypted = new byte[memoryStream.Length]; memoryStream.Read(encrypted, 0, encrypted.Length); #endregion //Clean up. cs.Close(); memoryStream.Close(); return encrypted; } /// The other side: Decryption methods public string DecryptString(string EncryptedString) { return Decrypt(StrToByteArray(EncryptedString)); } /// Decryption when working with byte arrays. public string Decrypt(byte[] EncryptedValue) { #region Write the encrypted value to the decryption stream MemoryStream encryptedStream = new MemoryStream(); CryptoStream decryptStream = new CryptoStream(encryptedStream, DecryptorTransform, CryptoStreamMode.Write); decryptStream.Write(EncryptedValue, 0, EncryptedValue.Length); decryptStream.FlushFinalBlock(); #endregion #region Read the decrypted value from the stream. encryptedStream.Position = 0; Byte[] decryptedBytes = new Byte[encryptedStream.Length]; encryptedStream.Read(decryptedBytes, 0, decryptedBytes.Length); encryptedStream.Close(); #endregion return UTFEncoder.GetString(decryptedBytes); } /// Convert a string to a byte array. NOTE: Normally we'd create a Byte Array from a string using an ASCII encoding (like so). // System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); // return encoding.GetBytes(str); // However, this results in character values that cannot be passed in a URL. So, instead, I just // lay out all of the byte values in a long string of numbers (three per - must pad numbers less than 100). public byte[] StrToByteArray(string str) { if (str.Length == 0) throw new Exception("Invalid string value in StrToByteArray"); byte val; byte[] byteArr = new byte[str.Length / 3]; int i = 0; int j = 0; do { val = byte.Parse(str.Substring(i, 3)); byteArr[j++] = val; i += 3; } while (i < str.Length); return byteArr; } // Same comment as above. Normally the conversion would use an ASCII encoding in the other direction: // System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); // return enc.GetString(byteArr); public string ByteArrToString(byte[] byteArr) { byte val; string tempStr = ""; for (int i = 0; i <= byteArr.GetUpperBound(0); i++) { val = byteArr[i]; if (val < (byte)10) tempStr += "00" + val.ToString(); else if (val < (byte)100) tempStr += "0" + val.ToString(); else tempStr += val.ToString(); } return tempStr; }}
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/165808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/232/" ] }
165,883
Suppose I have a class with some attributes. How is it best (in the Pythonic-OOP) sense to access these attributes ? Just like obj.attr ? Or perhaps write get accessors ? What are the accepted naming styles for such things ? Edit: Can you elaborate on the best-practices of naming attributes with a single or double leading underscore ? I see in most modules that a single underscore is used. If this question has already been asked (and I have a hunch it has, though searching didn't bring results), please point to it - and I will close this one.
The generally accepted way of doing things is just using simple attributes, like so >>> class MyClass:... myAttribute = 0... >>> c = MyClass()>>> c.myAttribute 0>>> c.myAttribute = 1>>> c.myAttribute1 If you do find yourself needing to be able to write getters and setters, then what you want to look for is "python class properties" and Ryan Tomayko's article onGetters/Setters/Fuxors is a great place to start (albeit a little long)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/165883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ] }
165,887
What's the easiest way to compute the amount of working days since a date? VB.NET preferred, but C# is okay. And by "working days", I mean all days excluding Saturday and Sunday. If the algorithm can also take into account a list of specific 'exclusion' dates that shouldn't count as working days, that would be gravy. Thanks in advance for the contributed genius.
This'll do what you want it to. It should be easy enough to convert to VB.NET, it's been too long for me to be able to do it though. DateTime start = DateTime.Now;DateTime end = start.AddDays(9);IEnumerable<DateTime> holidays = new DateTime[0];// basic dataint days = (int)(end - start).TotalDays;int weeks = days / 7;// check for a weekend in a partial week from start.if (7- (days % 7) <= (int)start.DayOfWeek) days--;if (7- (days % 7) <= (int)start.DayOfWeek) days--;// lose the weekendsdays -= weeks * 2;foreach (DateTime dt in holidays){ if (dt > start && dt < end) days--;}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/165887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17235/" ] }
165,938
Is there a way to step through a .bat script? The thing is, I have a build script , which calls a lot of other scripts, and I would like to see what is the order in which they are called, so that I may know where exactly I have to go about and add my modifications.
I don't know of anyway to step through the execution of a .bat file but you can use echo and pause to help with debugging. ECHO Will echo a message in the batch file. Such as ECHO Hello World will print Hello World on the screen when executed. However, without @ECHO OFF at the beginning of the batch file you'll also get "ECHO Hello World" and "Hello World." Finally, if you'd just like to create a blank line, type ECHO. adding the period at the end creates an empty line. PAUSE Prompt the user to press any key to continue. Source: Batch File Help @workmad3: answer has more good tips for working with the echo command. Another helpful resource... DDB: DOS Batch File Tips
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/165938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11234/" ] }
165,949
I noticed the following today: Mono at the PDC 2008 ? My talk will cover new technologies that we have created as part of Mono. Some of them are reusable on .NET (we try to make our code cross platform) and some other are features that specific to Mono's implementation of the CLI. Posted by Miguel de Icaza on 01 Oct 2008 Does anybody know what type of new technologies he is refering too? Sounds like a great talk [ UPDATE ] Here is the video of Miguel's talk Mono's SIMD Support: Making Mono safe for Gaming Static Compilation in Mono Unity on Linux, First Screenshots
These are some of the major libraries that you can use: Gtk# , the Cross platform GUI API Unix, Windows, MacOS X, this is an entire stack of libraries and includes widgets (with Gtk+), Accessibility and international text rendering (with PangoSharp). Mono.DataConvert - System.BitConverter implemented correctly, and well designed. Mono.Addins - Extensibility Framework, similar to MEF. Mono.Cairo - Cairo Graphics Binding. Mono.Cecil - ECMA CIL Image Manipulation. Xml.Relaxng - RelaxNG parsing and validation. Novell.Directory.Ldap - LDAP libraries. Daap.Sharp - An implementation of the DAAP protocol (Music exchange protocol, you can consume or expose music sources) Mono.Upnp - Universal Plug and Play implementation in managed code. Mono.ZeroConf - Cross platform ZeroConf/Bonjour API for .NET apps. BitSharp - Bittorrent client/server library, now called MonoTorrent Mono.Nat - Network Address Translation. Mono.Rocks - Useful Extension methods/Functional features for C#, now superseded by Cadenza SmugMugSharp - Bindings to talk to SmugMug Crimson - Crypto libraries beyond what is available in .NET Mono.WebBrowser - Wrapper for Firefox or WebKit. WebkitSharp - Bindings to use WebKit from C# GtkSharpRibbon - The Ribbon, implemented in Gtk# (cross platform) IPodSharp - Library to communicate and manipulate iPods. TagLibSharp - Library to annotate multimedia files (tagging). Exiv2Sharp - EXIF reading/writing library. Linux Specific: Mono.Posix / Mono.Unix . NDesk.DBus Mono.Fuse - User-space file systems. I am sure I am missing a bunch of other libraries. Most of these (and many more) are linked to via the Libraries page.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/165949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5147/" ] }
165,951
Say I have a third party Application that does background work, but prints out all errors and messages to the console. This means, that currently, we have to keep a user logged on to the server, and restart the application (double-click) every time we reboot. Not so very cool. I was kind of sure, that there was an easy way to do this - a generic service wrapper, that can be configured with a log file for stdout and stderr . I did check svchost.exe , but according to this site , its only for DLL stuff. Pity. EDIT: The application needs to be started from a batch file. FireDaemon seems to do the trick, but I think it is a bit overkill, for something that can be done in <10 lines of python code... Oh well, Not Invented Here ...
Check out srvany.exe from the Resource Kit . This will let run anything as a service. You can pass parameters in the service definition to your executable via srvany.exe so you could run a batch file as a service by seting the registry as follows: [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MyService\Parameters]"Application"="C:\\Windows\\System32\\cmd.exe""AppParameters"="/C C:\\My\\Batch\\Script.cmd""AppDirectory"="C:\\My\\Batch" Note: if you set up these keys in RegEdit rather than using a file you only need single backslashes in the values.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/165951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2260/" ] }
165,975
What is the most reliable and secure way to determine what page either sent, or called (via AJAX), the current page. I don't want to use the $_SERVER['HTTP_REFERER'] , because of the (lack of) reliability, and I need the page being called to only come from requests originating on my site. Edit: I am looking to verify that a script that preforms a series of actions is being called from a page on my website.
The REFERER is sent by the client's browser as part of the HTTP protocol, and is therefore unreliable indeed. It might not be there, it might be forged, you just can't trust it if it's for security reasons. If you want to verify if a request is coming from your site, well you can't, but you can verify the user has been to your site and/or is authenticated. Cookies are sent in AJAX requests so you can rely on that.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/165975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ] }
166,028
I have been working in a web project(asp.net) for around six months. The final product is about to go live. The project uses SQL Server as the database. We have done performance testing with some large volumes of data, results show that performance degrades when data becomes too large, say 2 million rows (timeout issues, delayed reponses, etc). At first we were using fully normailized database, but now we made it partially normalized due to performance issues (to reduce joins). First of all, is it the right decision?Plus what are the possible solutions when data size becomes very large, as the no. of clients increase in future? I would like to add further: 2 million rows are entity tables, tables resolving the relations have much larger rows. Performance degrades when data + no. of users increases. Denormalization was done after identifying the heavily used queries. We are also using some heavy amount of xml columns and xquery. Can this be the cause? A bit off the topic, some folks in my project say that dynamic sql query is faster than a stored procedure approach. They have done some kind of performance testing to prove their point. I think the opposite is true. Some of the heavily used queries are dynamicaly created where as most of other queries are encapsulated in stored procedures.
In the scheme of things, a few million rows is not a particulary large Database. Assuming we are talking about an OLTP database, denormalising without first identifying the root cause of your bottlenecks is a very, very bad idea . The first thing you need to do is profile your query workload over a representative time period to identify where most of the work is being done (for instance, using SQL Profiler, if you are using SQL Server). Look at the number of logical reads a query performs multiplied by the number of times executed. Once you have identified the top ten worst performing queries, you need to examine the query execution plans in detail. I'm going to go out on a limb here (because it is usually the case), but I would be surprised if your problem is not either Absence of the 'right' covering indexes for the costly queries Poorly configured or under specified disk subsystem This SO answer describes how to profile to find the worst performing queries in a workload.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/166028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965628/" ] }
166,033
What is meant by ‘value semantics’, and what is meant by ‘implicit pointer semantics’?
Java is using implicit pointer semantics for Object types and value semantics for primitives. Value semantics means that you deal directly with values and that you pass copies around.The point here is that when you have a value, you can trust it won't change behind your back. With pointer semantics, you don't have a value, you have an 'address'.Someone else could alter what is there, you can't know. Pointer Semantics in C++ : void foo(Bar * b) ...... b->bar() ... You need an * to ask for pointer semantics and -> to call methods on the pointee. Implicit Pointer Semantics in Java : void foo(Bar b) ...... b.bar() ... Since you don't have the choice of using value semantics, the * isn't needed nor the distinction between -> and ., hence the implicit.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/166033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22076/" ] }
166,044
When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it here , which describes a callable "wait.bat", implemented as follows: @ping 127.0.0.1 -n 2 -w 1000 > nul@ping 127.0.0.1 -n %1% -w 1000> nul You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep. Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) Windows NT , is there a better way? I modified the sleep.py script in the accepted answer , so that it defaults to one second if no arguments are passed on the command line: import time, systime.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
The timeout command is available from Windows Vista onwards: c:\> timeout /?TIMEOUT [/T] timeout [/NOBREAK]Description: This utility accepts a timeout parameter to wait for the specified time period (in seconds) or until any key is pressed. It also accepts a parameter to ignore the key press.Parameter List: /T timeout Specifies the number of seconds to wait. Valid range is -1 to 99999 seconds. /NOBREAK Ignore key presses and wait specified time. /? Displays this help message.NOTE: A timeout value of -1 means to wait indefinitely for a key press.Examples: TIMEOUT /? TIMEOUT /T 10 TIMEOUT /T 300 /NOBREAK TIMEOUT /T -1 Note: It does not work with input redirection - trivial example: C:\>echo 1 | timeout /t 1 /nobreakERROR: Input redirection is not supported, exiting the process immediately.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/166044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2193/" ] }
166,051
So most Java resources when speaking of packages mention a com.yourcompany.project setup. However, I do not work for a company, and don't have a website. Are there any naming conventions that are common? An email address, perhaps?
Use a top-level domain like 'bernard' or something else unique. The important part is that the domain is unique so that you avoid clashes, and not that it starts with a real Internet top-level domain like org or com. E.g. import java.util.*;import bernard.myProject.*;import org.apache.commons.lang.*;
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/166051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/61/" ] }
166,089
I'm interested: What is C#'s analog of std::pair in C++? I found System.Web.UI.Pair class, but I'd prefer something template-based. Thank you!
Tuples are available since .NET4.0 and support generics: Tuple<string, int> t = new Tuple<string, int>("Hello", 4); In previous versions you can use System.Collections.Generic.KeyValuePair<K, V> or a solution like the following: public class Pair<T, U> { public Pair() { } public Pair(T first, U second) { this.First = first; this.Second = second; } public T First { get; set; } public U Second { get; set; }}; And use it like this: Pair<String, int> pair = new Pair<String, int>("test", 2);Console.WriteLine(pair.First);Console.WriteLine(pair.Second); This outputs: test2 Or even this chained pairs: Pair<Pair<String, int>, bool> pair = new Pair<Pair<String, int>, bool>();pair.First = new Pair<String, int>();pair.First.First = "test";pair.First.Second = 12;pair.Second = true;Console.WriteLine(pair.First.First);Console.WriteLine(pair.First.Second);Console.WriteLine(pair.Second); That outputs: test12true
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/166089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11256/" ] }
166,132
I want to store the data returned by $_SERVER["REMOTE_ADDR"] in PHP into a DB field, pretty simple task, really. The problem is that I can't find any proper information about the maximum length of the textual representation of an IPv6 address, which is what a webserver provides through $_SERVER["REMOTE_ADDR"] . I'm not interested in converting the textual representation into the 128 bits the address is usually encoded in, I just want to know how many characters maximum are needed to store any IPv6 address returned by $_SERVER["REMOTE_ADDR"] .
45 characters . You might expect an address to be 0000:0000:0000:0000:0000:0000:0000:0000 8 * 4 + 7 = 39 8 groups of 4 digits with 7 : between them. But if you have an IPv4-mapped IPv6 address , the last two groups can be written in base 10 separated by . , eg. [::ffff:192.168.100.228] . Written out fully: 0000:0000:0000:0000:0000:ffff:192.168.100.228 (6 * 4 + 5) + 1 + (4 * 3 + 3) = 29 + 1 + 15 = 45 Note, this is an input/display convention - it's still a 128 bit address and for storage it would probably be best to standardise on the raw colon separated format, i.e. [0000:0000:0000:0000:0000:ffff:c0a8:64e4] for the address above.
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/166132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10024/" ] }
166,134
In PHP, which is quicker; using include('somefile.php') or querying a MySQL database with a simple SELECT query to get the same information? For example, say you had a JavaScript autocomplete search field which needed 3,000 terms to match against. Is it quicker to read those terms in from another file using include or to read them from a MySQL database using a simple SELECT query? Edit: This is assuming that the database and the file I want to include are on the same local machine as my code.
It depends. If your file is stored locally in your server and the database is installed in another machine, then the faster is to include the file. Buuuuut, because it depends on your system it could be not true. I suggest to you to make a PHP test script and run it 100 times from the command line, and repeat the test through HTTP (using cURL) Example: use_include.php <?php start = microtime(true); include( 'somefile.php' ); echo microtime(true)-start;?> use_myphp.php <?php start = microtime(true); __put_here_your_mysql_statements_to_retrieve_the_file__ echo microtime(true)-start;?>
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/166134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21709/" ] }
166,160
How can I scale the content of an iframe (in my example it is an HTML page, and is not a popup) in a page of my web site? For example, I want to display the content that appears in the iframe at 80% of the original size.
Kip's solution should work on Opera and Safari if you change the CSS to: <style> #wrap { width: 600px; height: 390px; padding: 0; overflow: hidden; } #frame { width: 800px; height: 520px; border: 1px solid black; } #frame { -ms-zoom: 0.75; -moz-transform: scale(0.75); -moz-transform-origin: 0 0; -o-transform: scale(0.75); -o-transform-origin: 0 0; -webkit-transform: scale(0.75); -webkit-transform-origin: 0 0; }</style> You might also want to specify overflow: hidden on #frame to prevent scrollbars.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/166160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24765/" ] }
166,174
I have a list of objects, each containing an Id, Code and Description. I need to convert this list into a Hashtable, using Description as the key and Id as the value. This is so the Hashtable can then be serialised to JSON. Is there a way to convert from List<Object> to Hashtable without writing a loop to go through each item in the list?
Let's assume that your List contains objects of type Foo (with an int Id and a string Description). You can use Linq to turn that list into a Dictionary like this: var dict = myList.Cast<Foo>().ToDictionary(o => o.Description, o => o.Id);
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/166174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4734/" ] }
166,212
I might be an exception here but I have never worked on a team with more than three developers and / or five people. Still we could manage to get the job done (somehow). Is there a software development process which fits this "extreme" scenario? And, if you work as a standalone programmer is there something you can adapt to your daily life to make it more predicatable, coherent, documented and still get the job done?
The agile methodologies are a good starting point because, imho, they are better suited for small groups. As for keeping your personal working pace I'd recommend a method based on TODO lists and some tool like Task2Gather . You might want to look at GTD , too. Things I would never give up even for a team of me: source version control backups TODO unit testing/ TDD code documentation refactoring/code reviews
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/166212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23297/" ] }
166,217
I'm trying to create a named_scope that uses a join, but although the generated SQL looks right, the result are garbage. For example: class Clip < ActiveRecord::Base named_scope :visible, { :joins => "INNER JOIN series ON series.id = clips.owner_id INNER JOIN shows on shows.id = series.show_id", :conditions=>"shows.visible = 1 AND clips.owner_type = 'Series' " } (A Clip is owned by a Series, a Series belongs to a Show, a Show can be visible or invisible). Clip.all does: SELECT * FROM `clips` Clip.visible.all does: SELECT * FROM `clips` INNER JOIN series ON series.id = clips.owner_id INNER JOIN shows on shows.id = series.show_id WHERE (shows.visible = 1 AND clips.owner_type = 'Series' ) This looks okay. But the resulting array of Clip models includes a Clip with an ID that's not in the database - it's picked up a show ID instead. Where am I going wrong?
The problem is that "SELECT *" - the query picks up all the columns from clips, series, and shows, in that order. Each table has an id column, and result in conflicts between the named columns in the results. The last id column pulled back (from shows) overrides the one you want. You should be using a :select option with the :joins, like: named_scope :visible, { :select => "episodes.*", :joins => "INNER JOIN series ON series.id = clips.owner_id INNER JOIN shows on shows.id = series.show_id", :conditions=>"shows.visible = 1 AND clips.owner_type = 'Series' "}
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/166217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18666/" ] }
166,220
I have a project in subversion, which I'm developing using Eclipse. I did the original checkout from the svn repository from inside Eclipse. All was well for some weeks then for some unknown reason, Eclipse (specifically: subclipse in Ganymede) no longer recognizes my project as being under svn control. The team context-menu only shows the basic "apply patch" / "share this project" menu options. From the shell, I can still update the project using the svn command line tools, so I know that the svn credentials still work. Other projects under subversion in the same copy of Eclipse still work. I realise that I can delete the local copy and check it out again, but I'd rather understand what has gone wrong - fix the problem, rather than mask the symptoms. Where does Eclipse store its knowledge of which projects are under version control? I looked at the .project file and the .settings directory, but couldn't see any obvious mention of svn nature or anything similar, even in the projects that are still working properly.
If you are using sublipse as your SVN provider I recommend doing the following Team -> Share project is usually enough to connect the metadata. (that is, assuming that the .svn files are still there which they seem to be if you can work on the command line). Hope this helps as to why this would happen I have no idea
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/166220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6716/" ] }
166,221
I would like to upload a file asynchronously with jQuery. $(document).ready(function () { $("#uploadbutton").click(function () { var filename = $("#file").val(); $.ajax({ type: "POST", url: "addFile.do", enctype: 'multipart/form-data', data: { file: filename }, success: function () { alert("Data Uploaded: "); } }); });}); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script><span>File</span><input type="file" id="file" name="file" size="10"/><input id="uploadbutton" type="button" value="Upload"/> Instead of the file being uploaded, I am only getting the filename. What can I do to fix this problem?
With HTML5 you can make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME type) or handle the progress event with the HTML5 progress tag (or a div). Recently I had to make a file uploader, but I didn't want to use Flash nor Iframes or plugins and after some research I came up with the solution. The HTML: <form enctype="multipart/form-data"> <input name="file" type="file" /> <input type="button" value="Upload" /></form><progress></progress> First, you can do some validation if you want. For example, in the .on('change') event of the file: $(':file').on('change', function () { var file = this.files[0]; if (file.size > 1024) { alert('max upload size is 1k'); } // Also see .name, .type}); Now the $.ajax() submit with the button's click: $(':button').on('click', function () { $.ajax({ // Your server script to process the upload url: 'upload.php', type: 'POST', // Form data data: new FormData($('form')[0]), // Tell jQuery not to process data or worry about content-type // You *must* include these options! cache: false, contentType: false, processData: false, // Custom XMLHttpRequest xhr: function () { var myXhr = $.ajaxSettings.xhr(); if (myXhr.upload) { // For handling the progress of the upload myXhr.upload.addEventListener('progress', function (e) { if (e.lengthComputable) { $('progress').attr({ value: e.loaded, max: e.total, }); } }, false); } return myXhr; } });}); As you can see, with HTML5 (and some research) file uploading not only becomes possible but super easy. Try it with Google Chrome as some of the HTML5 components of the examples aren't available in every browser.
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/166221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ] }
166,231
Tcl/Tk is a simple way to script small GUIs. Can anyone give a nice example with a button and a text widget. When the button is pressed should a shell command be executed and the output piped to the text widget. If you have other nice and clean examples for useful tasks, please add them too.
Here's a more complete example using fileevents. This will auto-scroll all the time. For usability purposes you probably only want to auto-scroll if the bottom of the text is visible (ie: if the user hasn't moved the scrollbar) but I'll leave that as an exercise for the reader to keep this already long example from getting any longer. package require Tkproc main {} { if {[lsearch -exact [font names] TkDefaultFont] == -1} { # older versions of Tk don't define this font, so pick something # suitable font create TkDefaultFont -family Helvetica -size 12 } # in 8.5 we can use {*} but this will work in earlier versions eval font create TkBoldFont [font actual TkDefaultFont] -weight bold buildUI}proc buildUI {} { frame .toolbar scrollbar .vsb -command [list .t yview] text .t \ -width 80 -height 20 \ -yscrollcommand [list .vsb set] \ -highlightthickness 0 .t tag configure command -font TkBoldFont .t tag configure error -font TkDefaultFont -foreground firebrick .t tag configure output -font TkDefaultFont -foreground black grid .toolbar -sticky nsew grid .t .vsb -sticky nsew grid rowconfigure . 1 -weight 1 grid columnconfigure . 0 -weight 1 set i 0 foreach {label command} { date {date} uptime {uptime} ls {ls -l} } { button .b$i -text $label -command [list runCommand $command] pack .b$i -in .toolbar -side left incr i }}proc output {type text} { .t configure -state normal .t insert end $text $type "\n" .t see end .t configure -state disabled}proc runCommand {cmd} { output command $cmd set f [open "| $cmd" r] fconfigure $f -blocking false fileevent $f readable [list handleFileEvent $f]}proc closePipe {f} { # turn blocking on so we can catch any errors fconfigure $f -blocking true if {[catch {close $f} err]} { output error $err }}proc handleFileEvent {f} { set status [catch { gets $f line } result] if { $status != 0 } { # unexpected error output error $result closePipe $f } elseif { $result >= 0 } { # we got some output output normal $line } elseif { [eof $f] } { # End of file closePipe $f } elseif { [fblocked $f] } { # Read blocked, so do nothing }}main
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/166231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/842/" ] }
166,298
Is there any substantial difference between those two terms?. I understand that JDK stands for Java Development Kit that is a subset of SDK (Software Development Kit). But specifying Java SDK, it should mean the same as JDK.
From this wikipedia entry : The JDK is a subset of what is loosely defined as a software development kit (SDK) in the general sense. In the descriptions which accompany their recent releases for Java SE, EE, and ME, Sun acknowledge that under their terminology, the JDK forms the subset of the SDK which is responsible for the writing and running of Java programs. The remainder of the SDK is composed of extra software, such as Application Servers, Debuggers, and Documentation. The "extra software" seems to be Glassfish, MySQL, and NetBeans. This page gives a comparison of the various packages you can get for the Java EE SDK.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/166298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/94303/" ] }
166,299
I'm using the jQuery slideToggle function on a site to reveal 'more information' about something. When I trigger the slide, the content is gradually revealed, but is located to the right by about 100 pixels until the end of the animation when it suddenly jumps to the correct position. Going the other way, the content jumps right by the same amount just before it starts its 'hide' animation, then is gradually hidden. Occurs on IE7/8, FF, Chrome. Any ideas on how I would fix this? Thanks in advance.
I have found a workaround, but I'm still not sure of the details. It seemed that when the 'overflow: hidden' style was added by jQuery, the effect that a nearby floated element had changed. The workaround was to place a permanent 'overflow: hidden' on the slideToggle'd div, and also a negative margin-left to counterbalance the effect. I am surprised that changing the overflow value has such an effect on layout, but there you have it...
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/166299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/691/" ] }
166,340
I need to zip and password-protect a file. Is there a good (free) library for this? This needs to be opened by a third party, so the password protection needs to work with standard tools.
UPDATE 2020: There are other choices now, notably Zip4J . After much searching, I've found three approaches: A freely available set of source code, suitable for a single file zip. However, there is no license. Usage is AesZipOutputStream.zipAndEcrypt(...). http://merkert.de/de/info/zipaes/src.zip ( https://forums.oracle.com/forums/thread.jspa?threadID=1526137 ) UPDATE: This code is now Apache licensed and released at https://github.com/mobsandgeeks/winzipaes (exported from original home at Google code ) . It worked for me (one file in the zip), and fills a hole in Java's opens source libraries nicely. A commercial product ($500 at the time of writing). I can't verify if this works, as their trial license approach is complex. Its also a ported .NET app: http://www.nsoftware.com/ipworks/zip/default.aspx A commercial product ($290 at the time of writing). Suitable only for Wnidows as it uses a dll: http://www.example-code.com/java/zip.asp
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/166340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23447/" ] }
166,347
I have some simple shell scripting tasks that I want to do For example: Selecting a file in the working directory from a list of the files matching some regular expression. I know that I can do this sort of thing using standard bash and grep but I would be nice to be able to hack quick scripts that will work in windows and linux without me having to memorize a heap of command line programs and flags etc. I tried to get this going but ended up getting confused about where I should be getting information such as a reference to the current directory So the question is what parts of the Ruby libraries do I need to know to write ruby shell scripts?
By default, you already have access to Dir and File , which are pretty useful by themselves. Dir['*.rb'] #basic globsDir['**/*.rb'] #** == any depth of directory, including current dir.#=> array of relative namesFile.expand_path('~/file.txt') #=> "/User/mat/file.txt"File.dirname('dir/file.txt') #=> 'dir'File.basename('dir/file.txt') #=> 'file.txt'File.join('a', 'bunch', 'of', 'strings') #=> 'a/bunch/of/strings'__FILE__ #=> the name of the current file Also useful from the stdlib is FileUtils require 'fileutils' #I know, no underscore is not ruby-likeinclude FileUtils# Gives you access (without prepending by 'FileUtils.') tocd(dir, options)cd(dir, options) {|dir| .... }pwd()mkdir(dir, options)mkdir(list, options)mkdir_p(dir, options)mkdir_p(list, options)rmdir(dir, options)rmdir(list, options)ln(old, new, options)ln(list, destdir, options)ln_s(old, new, options)ln_s(list, destdir, options)ln_sf(src, dest, options)cp(src, dest, options)cp(list, dir, options)cp_r(src, dest, options)cp_r(list, dir, options)mv(src, dest, options)mv(list, dir, options)rm(list, options)rm_r(list, options)rm_rf(list, options)install(src, dest, mode = <src's>, options)chmod(mode, list, options)chmod_R(mode, list, options)chown(user, group, list, options)chown_R(user, group, list, options)touch(list, options) Which is pretty nice
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/166347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24773/" ] }
166,356
This semester, I took a course in computer graphics at my University. At the moment, we're starting to get into some of the more advanced stuff like heightmaps, averaging normals, tesselation etc. I come from an object-oriented background, so I'm trying to put everything we do into reusable classes. I've had good success creating a camera class, since it depends mostly on the one call to gluLookAt(), which is pretty much independent of the rest of the OpenGL state machine. However, I'm having some trouble with other aspects. Using objects to represent primitives hasn't really been a success for me. This is because the actual render calls depend on so many external things, like the currently bound texture etc. If you suddenly want to change from a surface normal to a vertex normal for a particular class it causes a severe headache. I'm starting to wonder whether OO principles are applicable in OpenGL coding. At the very least, I think that I should make my classes less granular. What is the stack overflow community's views on this? What are your best practices for OpenGL coding?
The most practical approach seems to be to ignore most of OpenGL functionality that is not directly applicable (or is slow, or not hardware accelerated, or is a no longer a good match for the hardware). OOP or not, to render some scene those are various types and entities that you usually have: Geometry (meshes). Most often this is an array of vertices and array of indices (i.e. three indices per triangle, aka "triangle list"). A vertex can be in some arbitrary format (e.g. only a float3 position; a float3 position + float3 normal; a float3 position + float3 normal + float2 texcoord; and so on and so on). So to define a piece of geometry you need: define it's vertex format (could be a bitmask, an enum from a list of formats; ...), have array of vertices, with their components interleaved ("interleaved arrays") have array of triangles. If you're in OOP land, you could call this class a Mesh . Materials - things that define how some piece of geometry is rendered . In a simplest case, this could be a color of the object, for example. Or whether lighting should be applied. Or whether the object should be alpha-blended. Or a texture (or a list of textures) to use. Or a vertex/fragment shader to use. And so on, the possibilities are endless. Start by putting things that you need into materials. In OOP land that class could be called (surprise!) a Material . Scene - you have pieces of geometry, a collection of materials, time to define what is in the scene. In a simple case, each object in the scene could be defined by: - What geometry it uses (pointer to Mesh), - How it should be rendered (pointer to Material), - Where it is located. This could be a 4x4 transformation matrix, or a 4x3 transformation matrix, or a vector (position), quaternion (orientation) and another vector (scale). Let's call this a Node in OOP land. Camera . Well, a camera is nothing more than "where it is placed" (again, a 4x4 or 4x3 matrix, or a position and orientation), plus some projection parameters (field of view, aspect ratio, ...). So basically that's it! You have a scene which is a bunch of Nodes which reference Meshes and Materials, and you have a Camera that defines where a viewer is. Now, where to put actual OpenGL calls is a design question only. I'd say, don't put OpenGL calls into Node or Mesh or Material classes. Instead, make something like OpenGLRenderer that can traverse the scene and issue all calls. Or, even better, make something that traverses the scene independent of OpenGL, and put lower level calls into OpenGL dependent class. So yes, all of the above is pretty much platform independent. Going this way, you'll find that glRotate, glTranslate, gluLookAt and friends are quite useless. You have all the matrices already, just pass them to OpenGL. This is how most of real actual code in real games/applications work anyway. Of course the above can be complicated by more complex requirements. Particularly, Materials can be quite complex. Meshes usually need to support lots of different vertex formats (e.g. packed normals for efficiency). Scene Nodes might need to be organized in a hierarchy (this one can be easy - just add parent/children pointers to the node). Skinned meshes and animations in general add complexity. And so on. But the main idea is simple: there is Geometry, there are Materials, there are objects in the scene. Then some small piece of code is able to render them. In OpenGL case, setting up meshes would most likely create/activate/modify VBO objects. Before any node is rendered, matrices would need to be set. And setting up Material would touch most of remaining OpenGL state (blending, texturing, lighting, combiners, shaders, ...).
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/166356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12828/" ] }
166,379
I'm currently learning functional programming in my spare time with Scala, and I have an idle newbie question. I can see the elegance of having immutable objects when doing something like calculating a Haar wavelet transform - i.e. when the data itself being represented by the objects doesn't change. But I saw a blog where someone had a small game as an example when demonstrating immutability. If a creature object recieved damage, it didn't change its state - it returned a new creature object with the new hitpoints and a new "aggro towards X" flag. But if we were to design something like a MMORPG, World of Warcraft say. A hundred players in a battleground... possibly thousands of attacks and buffing/debuffing spell effects affecting them in different ways. Is it still possible to design the system with completely immutable objects? To me it would seem like there would be a ginormous swarm of new instances each 'tick'. And to get the currently valid instance of objects, all clients would constantly have to go through some sort of central "gameworld" object, or? Does functional programming scale for this, or is this a case of "best tool for best job, probably not immutable here"?
To me it would seem like there would be a ginormous swarm of new instances each 'tick'. Indeed, that is the case. I have a Haskell application that reads a market data feed (about five million messages over the course of a six-hour trading day, for the data in which we're interested) and maintains "current state" for various things, such as the most recent bid and offer prices and quantities for the instruments, how well our model fits the market, etc. etc. It's rather frightening to simulate a run of this program against a recorded feed in profiling mode and watch it allocate and GC close to 288 TB of memory (or close to 50,000 times the size of my machine's RAM) in the first 500 seconds of its run. (The figure would be considerably higher without profiling, since profiling not only slows down the application, but also forces it all to run on one core, as well.) But keep in mind, the garbage collector in pure language implementations is optimized for this sort of behavior. I'm quite happy with the overall speed of my application, and I think that it's fairly demanding, in that we have to parse several hundred messages per second from the market feed, do some fairly extensive calculations to build our model, and use that model to generate orders to go to the exchange as quickly as possible.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/166379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15627/" ] }
166,431
I find it annoying that I can't clear a list. In this example: a = []a.append(1)a.append(2)a = [] The second time I initialize a to a blank list, it creates a new instance of a list, which is in a different place in memory, so I can't use it to reference the first, not to mention it's inefficient. The only way I can see of retaining the same pointer is doing something like the following: for i in range(len(a)): a.pop() This seems pretty long-winded though, is there a better way of solving this?
You are looking for: del L[:]
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/166431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18909/" ] }
166,438
I have been looking for a logging framework for .net (c#) and decided to give log4net a go after reading up on a few question/answer threads here on stackoverflow. I see people mentioning over and over that they use a wrapper class for log4net and I am wonder what that would look like. I have my code split up into different projects (data access/business/webservice/..).How would a log4net wrapper class look like? Would the wrapper class need to be included in all of the projects? Should I build it as a separate project all together? Should the wrapper be a singleton class?
Essentially you create an interface and then a concrete implementation of that interface that wraps the classes and methods of Log4net directly. Additional logging systems can be wrapped by creating more concrete classes which wrap other classes and methods of those systems. Finally use a factory to create instances of your wrappers based on a configuration setting or line of code change. (Note: you can get more flexible - and complex - using an Inversion of Control container such as StructureMap .) public interface ILogger{ void Debug(object message); bool IsDebugEnabled { get; } // continue for all methods like Error, Fatal ...}public class Log4NetWrapper : ILogger{ private readonly log4net.ILog _logger; public Log4NetWrapper(Type type) { _logger = log4net.LogManager.GetLogger(type); } public void Debug(object message) { _logger.Debug(message); } public bool IsDebugEnabled { get { return _logger.IsDebugEnabled; } } // complete ILogger interface implementation}public static class LogManager{ public static ILogger GetLogger(Type type) { // if configuration file says log4net... return new Log4NetWrapper(type); // if it says Joe's Logger... // return new JoesLoggerWrapper(type); }} And an example of using this code in your classes (declared as a static readonly field): private static readonly ILogger _logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); You can get the same slightly more performance friendly effect using: private static readonly ILogger _logger = LogManager.GetLogger(typeof(YourTypeName)); The former example is considered more maintainable. You would not want to create a Singleton to handle all logging because Log4Net logs for the invoking type; its much cleaner and useful to have each type use its own logger rather than just seeing a single type in the log file reporting all messages. Because your implementation should be fairly reusable (other projects in your organization) you could make it its own assembly or ideally include it with your own personal/organization's framework/utility assembly. Do not re-declare the classes separately in each of your business/data/UI assemblies, that's not maintainable.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/166438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15771/" ] }
166,474
In a C++ file, I have a code like this: #if ACTIVATE# pragma message( "Activated" )#else# pragma message( "Not Activated")#endif I want to set this ACTIVE define to 1 with the msbuild command line. It tried this but it doesn't work: msbuild /p:DefineConstants="ACTIVATE=1" Any idea?
I'm a little late to the party (only 4 years or so), but I just had to workaround this problem on a project, and stumbled across this question while searching for a fix. Our solution was to use an environment variable with /D defines in it, combined with the Additional Options box in visual studio. In Visual Studio, add an environment variable macro, $(ExternalCompilerOptions) , to the Additional Options under project options->C/C++->Command Line (remember both Debug and Release configs) Set the environment variable prior to calling msbuild. Use the /D compiler option to define your macros c:\> set ExternalCompilerOptions=/DFOO /DBAR c:\> msbuild Item #1 ends up looking like this in the vcxproj file: <ClCompile> <AdditionalOptions>$(ExternalCompilerOptions) ... </AdditionalOptions> </ClCompile> This works for me with VS 2010. We drive msbuild from various build scripts, so the environment variable ugliness is hidden a bit. Note that I have not tested if this works when you need to set the define to specific value ( /DACTIVATE=1 ). I think it would work, but I'm concerned about having multiple '='s in there. H^2
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/166474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6605/" ] }
166,503
How do I set the code page to UTF-8 in a C Windows program? I have a third party library that uses fopen to open files. I can use wcstombs to convert my Unicode filenames to the current code page, however if the user has a filename with a character outside the code page then this breaks. Ideally I would just call _setmbcp(65001) to set the code page to UTF-8, however the MSDN documentation for _setmbcp states that UTF-8 is not supported. How can I get around this?
Unfortunately, there is no way to make Unicode the current codepage in Windows. The CP_UTF7 and CP_UTF8 constants are pseudo-codepages, used only in MultiByteToWideChar and WideCharToMultiByte conversion functions, like Ben mentioned. Your problem is similar to that of the fstream C++ classes. The fstream constructors accept only char* names, making impossible to open a file with a true Unicode name. The only solution offered by VC was a hack: open the file separately and then set the handle to the stream object. I'm afraid this isn't an option for you, of course, since the third party library probably doesn't accept handles. The only solution I can think of is to create a temporary file with a non-Unicode name, which is hard-linked to the original, and use that as a parameter.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/166503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2651243/" ] }
166,506
How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?
import socketsocket.gethostbyname(socket.gethostname()) This won't work always (returns 127.0.0.1 on machines having the hostname in /etc/hosts as 127.0.0.1 ), a paliative would be what gimel shows, use socket.getfqdn() instead. Of course your machine needs a resolvable hostname.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/166506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ] }
166,508
Is there any way so that i can echo password when asked for in unix shell without use of external binaries ? Something like simple function triggered when password prompt is displayed
import socketsocket.gethostbyname(socket.gethostname()) This won't work always (returns 127.0.0.1 on machines having the hostname in /etc/hosts as 127.0.0.1 ), a paliative would be what gimel shows, use socket.getfqdn() instead. Of course your machine needs a resolvable hostname.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/166508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24789/" ] }
166,545
How can I find the public facing IP for my net work in Python?
This will fetch your remote IP address import urllibip = urllib.urlopen('http://automation.whatismyip.com/n09230945.asp').read() If you don't want to rely on someone else, then just upload something like this PHP script: <?php echo $_SERVER['REMOTE_ADDR']; ?> and change the URL in the Python or if you prefer ASP: <%Dim UserIPAddressUserIPAddress = Request.ServerVariables("REMOTE_ADDR")%> Note: I don't know ASP, but I figured it might be useful to have here so I googled.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/166545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ] }
166,550
This is a minor style question, but every bit of readability you add to your code counts. So if you've got: if (condition) then{ // do stuff}else{ // do other stuff} How do you decide if it's better like that, or like this: if (!condition) then { // do other stuff { else { // do stuff } My heuristics are: Keep the condition positive (lessmental calculation when reading it) Put the most common path into thefirst block
I prefer to put the most common path first, and I am a strong believer in nesting reduction so I will break, continue, or return instead of elsing whenever possible. I generally prefer to test against positive conditions, or invert [and name] negative conditions as a positive. if (condition) return;DoSomething(); I have found that by drastically reducing the usage of else my code is more readable and maintainable and when I do have to use else its almost always an excellent candidate for a more structured switch statement.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/166550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14663/" ] }
166,557
Could you guys recommend me a good db modeling tool? Mainly for SQL Server... thanks!
If it is for SQL Server I like the DB Diagram from SQL Server Management Studio.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/166557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17648/" ] }
166,607
I need to either find a file in which the version is encoded or a way of polling it across the web so it reveals its version. The server is running at a host who will not provide me command line access, although I can browse the install location via FTP. I have tried HEAD and do not get a version number reported. If I try a missing page to get a 404 it is intercepted, and a stock page is returned which has no server information on it. I guess that points to the server being hardened. Still no closer... I put a PHP file up as suggested, but I can't browse to it and can't quite figure out the URL path that would load it. In any case I am getting plenty of access denied messages and the same stock 404 page. I am taking some comfort from knowing that the server is quite robustly protected.
The method Connect to port 80 on the host and send it HEAD / HTTP/1.0 This needs to be followed by carriage-return + line-feed twice You'll get back something like this HTTP/1.1 200 OKDate: Fri, 03 Oct 2008 12:39:43 GMTServer: Apache/2.2.9 (Ubuntu) DAV/2 SVN/1.5.0 PHP/5.2.6-1ubuntu4 with Suhosin-Patch mod_perl/2.0.4 Perl/v5.10.0Last-Modified: Thu, 02 Aug 2007 20:50:09 GMTETag: "438118-197-436bd96872240"Accept-Ranges: bytesContent-Length: 407Connection: closeContent-Type: text/html; charset=UTF-8 You can then extract the apache version from the Server: header Typical tools you can use You could use the HEAD utility which comes with a full install of Perl's LWP library, e.g. HEAD http://your.webserver.com/ Or, use the curl utility, e.g. curl --head http://your.webserver.com/ You could also use a browser extension which lets you view server headers, such as Live HTTP Headers or Firebug for Firefox, or Fiddler for IE Stuck with Windows? Finally. if you're on Windows, and have nothing else at your disposal, open a command prompt (Start Menu->Run, type "cmd" and press return), and then type this telnet your.webserver.com 80 Then type (carefully, your characters won't be echoed back) HEAD / HTTP/1.0 Press return twice and you'll see the server headers. Other methods As mentioned by cfeduke and Veynom, the server may be set to return limited information in the Server: header. Try and upload a PHP script to your host with this in it <?php phpinfo() ?> Request the page with a web browser and you should see the Apache version reported there. You could also try and use PHPShell to have a poke around, try a command like /usr/sbin/apache2 -V
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/166607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24039/" ] }
166,630
I want to insert 'n' spaces (or any string) at the beginning of a string in C++. Is there a direct way to do this using either std::strings or char* strings? E.g., in Python you could simply do >>> "." * 5 + "lolcat"'.....lolcat'
In the particular case of repeating a single character, you can use std::string(size_type count, CharT ch) : std::string(5, '.') + "lolcat" This can't be used to repeat multi-character strings.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/166630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
166,641
In the following example should I expect that values.size() will be called every time around the loop? In which case it might make sense to introduce a temporary vectorSize variable. Or should a modern compiler be able to optimize the calls away by recognising that the vector size cannot change. double sumVector(const std::vector<double>& values) { double sum = 0.0; for (size_t ii = 0; ii < values.size(); ++ii) { sum += values.at(ii); }} Note that I don't care if there are more efficient methods to sum the contents of a vector, this question is just about the use of size() in a for construct.
Here's one way to do it that makes it explicit - size() is called only once. for (size_t ii = 0, count = values.size(); ii < count; ++ii) Edit: I've been asked to actually answer the question, so here's my best shot. A compiler generally won't optimize a function call, because it doesn't know if it will get a different return value from one call to the next. It also won't optimize if there are operations inside the loop that it can't predict the side effects of. Inline functions might make a difference, but nothing is guaranteed. Local variables are easier for the compiler to optimize. Some will call this premature optimization, and I agree that there are few cases where you will ever notice a speed difference. But if it doesn't make the code any harder to understand, why not just consider it a best practice and go with it? It certainly can't hurt. P.S. I wrote this before I read Benoit's answer carefully, I believe we're in complete agreement.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/166641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3229/" ] }
166,658
I am using MailLogger to send a message about a failed/successful release. I would like to make the mail body simple and easy to read. How can I suppress output for some particular tasks?
Here's one way to do it that makes it explicit - size() is called only once. for (size_t ii = 0, count = values.size(); ii < count; ++ii) Edit: I've been asked to actually answer the question, so here's my best shot. A compiler generally won't optimize a function call, because it doesn't know if it will get a different return value from one call to the next. It also won't optimize if there are operations inside the loop that it can't predict the side effects of. Inline functions might make a difference, but nothing is guaranteed. Local variables are easier for the compiler to optimize. Some will call this premature optimization, and I agree that there are few cases where you will ever notice a speed difference. But if it doesn't make the code any harder to understand, why not just consider it a best practice and go with it? It certainly can't hurt. P.S. I wrote this before I read Benoit's answer carefully, I believe we're in complete agreement.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/166658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2361/" ] }
166,712
I have noticed that some apps like Safari and Mail show a loading indicator in the status bar (the bar at the very top of the phone) when they are accessing the network. Is there a way to do the same thing in SDK apps, or is this an Apple only thing?
It's in UIApplication: For Objective C: Start: [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; End: [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; For swift : Start UIApplication.shared.isNetworkActivityIndicatorVisible = true End UIApplication.shared.isNetworkActivityIndicatorVisible = false
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/166712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6044/" ] }
166,744
I'm a .Net developer and would like to investigate building and running our framework on Mono. If the initial project is successful I will happily invest in an OS learning curve, but right now I want to focus on getting things up and running and seeing the code working. What would be the best distribution to start with, assuming that I know very little about Linux, but am an experienced developer? How quickly (hours/days/weeks?) can I expect to achieve this? Some Feedback so far (Thanks for the answers, guys):Decided on CentOS, but this was also because this fits in with a particular implementation of the .Net code that I want to port to Mono.The only issue was that I needed to go to version 4 for an out-the-box install of Mono With some assistance I have been able to get this to a point where I am able to run compiles and start addressing the porting issues. This took a few hours - biggest learning curve is around driving Linux. 20081231: Found the following article for running mono on ubuntu: http://www.ddj.com/windows/212201484
I work for Novell, so I am going to recommend OpenSUSE as the distribution to use for Mono of course. When you use OpenSUSE, not only you get Mono, but there are hundreds of open source libraries and .NET based applications that we have ported and make available through our update system. Additionally, many of the preview features are available as packages that are ready to install on OpenSUSE. Other distributions tend to lag behind in both of the above areas. Besides, the more OpenSUSE out there, the more funds that we get to continue to improve Mono.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/166744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7921/" ] }
166,750
I'm designing a small SQL database to be used by a web application. Let's say a particular table has a Name field for which no two rows will be allowed to have the same value. However, users will be able to change the Name field at any time. The primary key from this table will be used as a foreign key in other tables. So if the Name field was used as the primary key, any changes would need to be propagated to those other tables. On the other hand, the uniqueness requirement would be handled automatically. My instinct would be to add an integer field to act as the primary key, which could be automatically populated by the database. Is there any point in having this field or would it be a waste of time?
I would use a generated PK myself, just for the reasons you mentioned. Also, indexing and comparing by integer is faster than comparing by strings. You can put a unique index on the name field too without making it a primary key.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/166750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15519/" ] }
166,752
Does anyone know the full list of C# compiler number literal modifiers? By default declaring '0' makes it an Int32 and '0.0' makes it a 'Double'. I can use the literal modifier 'f' at the end to ensure something is treated as a 'Single' instead. For example like this... var x = 0; // x is Int32var y = 0f; // y is Single What are the other modifiers I can use? Is there one for forcing to Double, Decimal, UInt32? I tried googling for this but could not find anything. Maybe my terminology is wrong and so that explains why I am coming up blank. Any help much appreciated.
var y = 0f; // y is singlevar z = 0d; // z is doublevar r = 0m; // r is decimalvar i = 0U; // i is unsigned intvar j = 0L; // j is long (note capital L for clarity)var k = 0UL; // k is unsigned long (note capital L for clarity) From the C# specification 2.4.4.2 Integer literals and 2.4.4.3 Real literals. Take note that L and UL are preferred as opposed to their lowercase variants for clarity as recommended by Jon Skeet .
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/166752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6276/" ] }
166,802
Has anyone ever had the issue where trying to "View Designer" on a windows form in Visual Studio .NET causes the error: "Could not load file or assembly…" ? In this case, the assembly in question was XYZ.dll . I managed to fix this by adding XYZ.dll and all its references to my project's references (even though my project doesn't directly depend on them) and rebuilding the whole solution. However, after that, I removed all those references from my project, rebuilt, and it still worked. One other piece of information is that I use Resharper 2.5 . Someone else pointed out that it might be Resharper doing some shadow copying. I'll look into this next time this happens.Does anyone have a understanding of why this error happens in the first place, and possibly the 'correct' way to fix it?
We have same problem. Some Form/UserControl classes can not be viewed in designer and Visual Studio causes various exceptions. There are one typical cause:One of designed component thrown unhandled exception during initialization ( in constructor or in Load event or before ). Not only for this case, you can run another instance of visual studio, open/create some independent project, go to menu -> Debug -> Attach to process ... -> select instance of devenv.exe process with problematic designer. Then press Ctrl+Alt+E , the "Exceptions" windows should be shown. There check "Thrown" in categories of exception. Now active the visual studio with designer and try view designer. If the exception will be thrown, you will see callstack ( and maybe source code, if the exception was thrown from your code ) and other typical information about thrown exception. This information may be very helpful. If you have something like TypeLoadException from Winforms designer, when debugging Visual Studio ( devenv.exe process) with another instance of Visual Studio, have a look at the Debug > Modules panel to see exactly which version of your DLL is loaded. Turned out that it was an unexpected version for us, hence the issue.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/166802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
166,884
Why would someone want to use a linked-list over an array? Coding a linked-list is, no doubt, a bit more work than using an array and one may wonder what would justify the additional effort. I think insertion of new elements is trivial in a linked-list but it's a major chore in an array. Are there other advantages to using a linked list to store a set of data versus storing it in an array? This question is not a duplicate of this question because the other question is asking specifically about a particular Java class while this question is concerned with the general data structures.
It's easier to store data of different sizes in a linked list. An array assumes every element is exactly the same size. As you mentioned, it's easier for a linked list to grow organically. An array's size needs to be known ahead of time, or re-created when it needs to grow. Shuffling a linked list is just a matter of changing what points to what. Shuffling an array is more complicated and/or takes more memory. As long as your iterations all happen in a "foreach" context, you don't lose any performance in iteration.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/166884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2820/" ] }
166,895
Is it possible to have a different set of dependencies in a maven pom.xml file for different profiles? e.g. mvn -P debugmvn -P release I'd like to pick up a different dependency jar file in one profile that has the same class names and different implementations of the same interfaces.
To quote the Maven documentation on this : A profile element contains both an optional activation (a profile trigger) and the set of changes to be made to the POM if that profile has been activated. For example, a project built for a test environment may point to a different database than that of the final deployment. Or dependencies may be pulled from different repositories based upon the JDK version used . (Emphasis is mine) Just put the dependency for the release profile inside the profile declaration itself and do the same for debug . <profiles> <profile> <id>debug</id> … <dependencies> <dependency>…</dependency> </dependencies> … </profile> <profile> <id>release</id> … <dependencies> <dependency>…</dependency> </dependencies> … </profile></profiles>
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/166895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/974/" ] }
166,897
I have a problem similar to the one found here : JSF selectItem label formatting . What I want to do is to accept a double as a value for my and display it with two decimals. Can this be done in an easy way? I've tried using but that seems to be applied on the value from the inputText that is sent to the server and not on the initial value in the input field. My code so far: <h:inputText id="december" value="#{budgetMB.december}" onchange="setDirty()" styleClass="StandardBlack"> <f:convertNumber maxFractionDigits="2" groupingUsed="false" /></h:inputText> EDIT: The above code actually works. I was fooled by JDeveloper that didn't update the jsp page even when I did a explicit rebuild of my project and restarted the embedded OC4J server. However, after a reboot of my computer everything was fine.
If I'm not misunderstanding your requirement, I was able to achieve formatting of the value in the input box during the rendering of the view with: <h:inputText id="text1" value="#{...}"> <f:convertNumber pattern="#,###,##0.00"/></h:inputText> I was using the Standard Faces Components in my vendor-branded Eclipse so I'm assuming the pattern attribute is part of standard JSF.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/166897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24828/" ] }
166,941
I am trying to get Selenium RC working with Firefox 3 on Linux with PHP/Apache but am experiencing problems. Here's what I've done: I have installed the Firefox Selenium-IDE extension. On the web server (which in my case is actually the same machine running Firefox), I've started the Selenium server with: java -jar selenium-server.jar -interactive I have a PHP script as follows: PHP: require_once 'Testing/Selenium.php';$browser = new Testing_Selenium("*custom /usr/lib/firefox-3.0.3/firefox", "https://www.example.com");$browser->start(); When I run the PHP script, it does launch a new Firefox tab, but I get this error message : The requested URL /selenium-server/core/RemoteRunner.html was not found on this server. I have had more success with Firefox 2 (by using "*firefox" instead of "*custom" but don't want to use that for my current project.
I'm not sure of the etiquette of answering your own question... but having experimented in a trial-and-error way, here's how I've managed to get Selenium working with PHP/Firefox3 on Ubuntu. I downloaded RC and copied the php client directory to /usr/share/php as 'Selenium' I navigated to the Selenium Server directory in the download, and started selenium with java -jar selenium-server.jar I created a new Firefox profile (by running firefox -ProfileManager). I called the new Profile 'Selenium' Within that profile, I editing the Firefox Network preferences to proxy all protocols via localhost port 4444. I created my php script and ran it with this command: php -d include_path=".:/usr/share/php:/usr/share/php/Selenium/PEAR" test.php I've listed my (basic, non-PHPUnit, non-OO) first test script below for reference. require_once 'Testing/Selenium.php';$oSelenium = new Testing_Selenium( "*custom /usr/lib/firefox-3.0.3/firefox -P Selenium", "https://www.example.com");$oSelenium->start();$oSelenium->open("/");if (!$oSelenium->isElementPresent("id=login_button")) { $oSelenium->click("logout"); $oSelenium->waitForPageToLoad(10000); if (!$oSelenium->isElementPresent("id=login_button")) { echo "Failed to log out\n\n"; exit; }}$oSelenium->type("login", "my_username");$oSelenium->type("password", "my_password");$oSelenium->click("login_button");$oSelenium->waitForPageToLoad(10000);$oSelenium->click("top_nav_campaigns");$oSelenium->stop();
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/166941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24106/" ] }
166,944
I have a Python script I recently wrote that I call using the command line with some options. I now want a very thin web interface to call this script locally on my Mac. I don't want to go through the minor trouble of installing mod_python or mod_wsgi on my Mac, so I was just going to do a system() or popen() from PHP to call the Python script. Any better ideas? Thanks in advance!
Depending on what you are doing, system() or popen() may be perfect. Use system() if the Python script has no output, or if you want the Python script's output to go directly to the browser. Use popen() if you want to write data to the Python script's standard input, or read data from the Python script's standard output in php. popen() will only let you read or write, but not both. If you want both, check out proc_open() , but with two way communication between programs you need to be careful to avoid deadlocks, where each program is waiting for the other to do something. If you want to pass user supplied data to the Python script, then the big thing to be careful about is command injection. If you aren't careful, your user could send you data like "; evilcommand ;" and make your program execute arbitrary commands against your will. escapeshellarg() and escapeshellcmd() can help with this, but personally I like to remove everything that isn't a known good character, using something like preg_replace('/[^a-zA-Z0-9]/', '', $str)
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/166944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2999/" ] }
167,004
I am attempting to set up an nmake makefile to export our balsamiq mockup files to png files automatically, but I'm afraid I can't make heads nor tails of how to make a generic rule for doing so, without explicitly listing all the files I want exported. This page details the command line syntax for exporting the files, and this page contains an example which looks like it contains a generic rule for .obj files to .exe files. The makefile I have tried so far looks like this: .bmml.png: "C:\Program Files\Balsamiq Mockups\Balsamiq Mockups.exe" export $< $@ But this doesn't work. If I simply run nmake (with some outdated png files), nmake just does this: [C:\Temp] :nmakeMicrosoft (R) Program Maintenance Utility Version 9.00.30729.01Copyright (C) Microsoft Corporation. All rights reserved.[C:\Temp] : If I ask it to build one specific file, it does this: [C:\Temp] :nmake "TestFile.png"Microsoft (R) Program Maintenance Utility Version 9.00.30729.01Copyright (C) Microsoft Corporation. All rights reserved.NMAKE : fatal error U1073: don't know how to make '"TestFile.png"'Stop.[C:\Temp] : Any nmake gurus out there that can set me straight? An example makefile which simply makes .dat files from .txt files by copying them, to experiment with, looks like this: .txt.dat: copy $< $@ this does nothing as well, so clearly I'm not understanding how such generic rules work. Do I need to specify a goal above that somehow lists the files I want?
NMAKE pattern rules are a lot like GNU make old-school suffix rules. In your case, you had it almost right to begin with, but you were missing the .SUFFIXES declaration. For example: .SUFFIXES: .bmml .png.bmml.png: @echo Building $@ from $< I think this is only part of your solution though, because you also mentioned wanting to avoid explicitly listing all of the files to be converted. Unfortunately, I don't know of a very clean way to do that in NMAKE, since it only expands wildcards in dependency lists, and what you really want in your dependency list is not the list of files that already exist (the *.bmml files), but the list of files that will be created from those files (the *.png files). Nevertheless, I think you can achieve your goal with a recursive NMAKE invocation like this: all: *.bmml $(MAKE) $(**:.bmml=.png) Here, NMAKE will expand *.bmml in the prereq list for all into the list of .bmml files in the directory, and then it will start a new NMAKE instance, specifying the goals to build as that list of files with all instances of .bmml replaced by .png . So, putting it all together: .SUFFIXES: .bmml .pngall: *.bmml @echo Converting $(**) to .png... @$(MAKE) $(**:.bmml=.png).bmml.png: @echo Building $@ from $< If I create files Test1.bmml and Test2.bmml and then run this makefile, I get the following output: Converting Test1.bmml Test2.bmml to .png...Building Test1.png from Test1.bmmlBuilding Test2.png from Test2.bmml Of course, if you have very many of these .bmml files, you may run afoul of command-line length limitations, so watch out for that. In that case, I recommend either explicitly listing the source files, or using a more capable make tool, like GNU make (which is available for Windows in a variety of forms).
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/167004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/267/" ] }
167,014
Our team (5-10 developers) plans to adopt Subversion for our .NET (Visual Studio) projects/solutions (VisualSVN Server, TortoiseSVN / VisualSVN). What is the best way to organize a new repository tree ? Is it okay to use one big repository or is it better to create different repositories for every solution / product line etc.? Our projects can be categorized this way (example): Main Product Line Main Web App Library 1 Library 2 ... Windows Client Another Windows Client Windows Service Tools Tool A Tool B Product Line 2 Software 1 Software 2 Product Line 3 App 1 App 2
Generally, you want to use a separate repository in any case where you are expecting different access permissions (i.e. some developers should have commit access to one project, but not another, or one project has a public read-only anonymous interface but another doesn't). You want everything in one repository if you don't need that level of access control, especially if you need to be able to copy or move files between projects (i.e. projects might share code). Put your trunk/tags/branch split at whatever level corresponds to a chunk of code you might release as a single package (i.e. think of where you would tag). This isn't critical to get right at first, since these no different internally from any other folder, so you can just move things around later, though of course it's neater not to have that problem.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/167014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6461/" ] }
167,018
I have been tinkering with BSP trees for a while now and am also playing with threads. When adding a triangle to a BSP tree, an opportunity arises to create a new thread for the purposes of processing data in parallel. insert(triangle, bspnode){ .... else if(triangle spans bspnode) { (frontpiece, backpiece) = plane_split(triangle, bspnode) insert(frontpiece, bspnode.front) insert(backpiece, bspnode.back) } ....} The two insert operations above could be executed by two threads, and since they do not modify the same data, cheap synchronization can be used. insert(triangle, bspnode){ .... else if(triangle spans bspnode) { (frontpiece, backpiece) = split(triangle, bspnode) handle = beginthread(insert(backpiece, bspnode.front)) insert(frontpiece, bspnode.back) if(handle) { waitforthread(handle) } else { insert(backpiece, bspnode.front) } } ....} This new method attempts to create a thread to complete the operation in parallel, but should not fail if the thread cannot be created (it will simply revert to the original algorithm). Is this a sound programming practice, or am I using threads improperly? I have not been able to find any literature on this technique. I like that it tends to use my CPU to its fullest (2 cores), and would theoretically scale to any number of processors available. I don't like that it might be horribly wasteful on CPU and memory.
Threads are great if some part of the processing is waiting on something external (user input, I/O, some other processing) - the thread that's waiting can continue to wait, while a thread that isn't waiting forges on ahead. However, for processing-intensive tasks, more threads than processors actually creates overhead. It seems like your threads are doing all "CPU work", so I'd stick to one thread per core - test to find the optimal number, though. The biggest overhead created is from context switching (freezing one thread and loading the execution context of the next one), as well as cache misses when threads are doing tasks with different memory (if your thread can use the CPU cache effectively).
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/167018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2581/" ] }
167,027
I have a need to display many numerical values in columns. These values need to be easily editable so I cannot just display them in a table. I am using textboxes to display them. Is there a way for me to right-justify the text displayed in a textbox? It would also be nice if when the user is entering data for it to start displaying what they type from the right.
Did you try setting the style: input { text-align:right;} Just tested, this works fine (in FF3 at least): <html> <head> <title>Blah</title> <style type="text/css"> input { text-align:right; } </style> </head> <body> <input type="text" value="2"> </body></html> You'll probably want to throw a class on these inputs, and use that class as the selector. I would shy away from "rightAligned" or something like that. In a class name, you want to describe what the element's function is, not how it should be rendered. "numeric" might be good, or perhaps the business function of the text boxes.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/167027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16292/" ] }
167,031
Does anyone know the API call I can use to change the keyboard layout on a windows machine to Dvorak? Doing it through the UI is easy but I'd like to have a script that I can run on new VM's to automate the process.
I may be four years late to the party, but did you ever find this: Intlcfg Command-Line Options I don't have Windows Vista (very bad habit, Windows), but looking at this page and also at Available Language Packs and Default Input Locales I reckon the command you want might well be: intlcfg.exe -inputlocale:0409:00010409 for English (United States) language with United States Dvorak input locale.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/167031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23283/" ] }
167,079
Having recently discovered this method of development, I'm finding it a rather nice methodology. So, for my first project, I have a small DLL's worth of code (in C#.NET, for what it's worth), and I want to make a set of tests for this code, but I am a bit lost as to how and where to start. I'm using NUnit, and VS 2008, any tips on what sort of classes to start with, what to write tests for, and any tips on generally how to go about moving code across to test based development would be greatly appreciated.
See the book Working Effectively with Legacy Code by Michael Feathers. In summary, it's a lot of work to refactor existing code into testable and tested code; Sometimes it's too much work to be practical. It depends on how large the codebase is, and how much the various classes and functions depend upon each other. Refactoring without tests will introduce changes in behaviour (i.e. bugs). And purists will say it's not really refactoring because of the lack of tests to check that the behaviour doesn't change. Rather than adding test across the board to your whole application at once, add tests when you work in an area of code. Most likely you'll have to return to these "hotspots" again. Add tests from the bottom up: test little, independent classes and functions for correctness. Add tests from the top down: Test whole subsystems as black boxes to see if their behaviour changes with changes in code. And so you can step through them to find out what's going on. This approach will probably get you the most benefit. Don't be too concerned at first with what the "correct" behaviour is while you are adding tests, look to detect and avoid changes in behaviour. Large, untested systems often have internal behaviours that may seem incorrect, but that other parts of the system depend on. Think about isolating dependencies such as database, filesystem, network, so that they can be swapped out for mock data providers during testing. If the program doesn't have internal interfaces, lines which define the boundary between one subsystem/layer and another, then you may have to try to introduce these, and test at them. Also, automatic mocking frameworks like Rhinomocks or Moq might help mock existing classes here. I haven't really found the need for them in code designed for testability.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/167079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15537/" ] }
167,096
Is it safe to assume that two itterations over the same collection will return the objects in the same order? Obviously, it is assumed that the collection has not otherwise been changed.
Short answer - yes. Obviously, though, the order of the items in the collection may not be exactly as they were inserted, depending on the type of collection (a dictionary, for example). But you will get the same results each time you iterate over a single, unmodified collection using a foreach loop.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/167096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18978/" ] }
167,106
In there an easy way to do this in PHP. I want to make sure that only web requests from certain countries are able to access my website. Any ideas?
Use an IP geolocation database (some are free) and $_SERVER["REMOTE_ADDR"] to get the visitor's IP address. http://www.maxmind.com/app/geolitecity is a free (less accurate) version of a commercial one.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/167106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ] }
167,120
This is really only easy to explain with an example, so to remove the intersection of a list from within a dict I usually do something like this: a = {1:'', 2:'', 3:'', 4:''}exclusion = [3, 4, 5]# have to build up a new list or the iteration breakstoRemove = []for var in a.iterkeys(): if var in exclusion: toRemove.append(var)for var in toRemove: del a[var] This might seem like an unusual example, but it's surprising the number of times I've had to do something like this. Doing this with sets would be much nicer, but I clearly want to retain the 'values' for the dict. This method is annoying because it requires two loops and an extra array. Is there a cleaner and more efficient way of doing this.
Consider dict.pop : for key in exclusion: a.pop(key, None) The None keeps pop from raising an exception when key isn't a key.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/167120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18909/" ] }
167,129
What is the functional programming approach to convert an IEnumerable<string> to a delimited string? I know I can use a loop, but I'm trying to wrap my head around functional programming. Here's my example: var selectedValues =from ListItem item in checkboxList.Itemswhere item.Selectedselect item.Value;var delimitedString = ?? .. or could I do this in just the first var assignment (append each result to the previous)?
string.Join(", ", string[] enumerable)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/167129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10693/" ] }
167,199
I've been asked to maintain a large C++ codebase full of memory leaks. While poking around, I found out that we have a lot of buffer overflows that lead to the leaks (how it got this bad, I don't ever want to know). I've decided to removing the buffer overflows first. To make my bug-hunting easier, what tools can be used to check for buffer overruns?
On Linux I'd use Valgrind.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/167199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1599/" ] }
167,224
I have a variable of type Number, and i like to obtain the sign (if is '-' i like to have -1 and if '+' i like to have 1). So, i made this: var sign = Math.abs(n) / n; But, there is any other way? Better than this?
You'll be in trouble if n == 0... how about this: var sign = n < 0 ? -1 : 1;
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/167224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20601/" ] }
167,232
Is there a way to configure a Visual Studio 2005 Web Deployment Project to install an application into a named Application Pool rather than the default app pool for a given web site?
There is a good article describing custom actions here: ScottGu's Blog The question you asked is answered about halfway through the comments by 'Ryan', unfortunately it's in VB, but it shouldn't be hard to translate: Private Sub assignApplicationPool(ByVal WebSite As String, ByVal Vdir As String, ByVal appPool As String) Try Dim IISVdir As New DirectoryEntry(String.Format("IIS://{0}/W3SVC/1/Root/{1}", WebSite, Vdir)) IISVdir.Properties.Item("AppPoolId").Item(0) = appPool IISVdir.CommitChanges() Catch ex As Exception Throw ex End Try End Sub Private strServer As String = "localhost" Private strRootSubPath As String = "/W3SVC/1/Root" Private strSchema As String = "IIsWebVirtualDir" Public Overrides Sub Install(ByVal stateSaver As IDictionary) MyBase.Install(stateSaver) Try Dim webAppName As String = MyBase.Context.Parameters.Item("TARGETVDIR").ToString Dim vdirName As String = MyBase.Context.Parameters.Item("COMMONVDIR").ToString Me.assignApplicationPool(Me.strServer, MyBase.Context.Parameters.Item("TARGETVDIR").ToString, MyBase.Context.Parameters.Item("APPPOOL").ToString) Catch ex As Exception Throw ex End Try End Sub ...Where APPPOOL is supplied as an argument in the Custom Action.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/167232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7872/" ] }
167,238
The question is not how to tell in a oneliner. If you're writing the code in a one-liner, you know you are. But how does a module, included by -MMy::Module::Name know that it all started from a oneliner. This is mine. It's non-portable though and relies on UNIX standard commands (although, it can be made portable more or less.) my $process_info = `ps $$ | tail -1`;my $is_oneliner = $process_info =~ m/perl.*?\s+-[^\P{IsLower}e]*e[^\P{IsLower}e]*\s+/m ; And if you have a snazzier regex, feel free to improve upon mine. A couple of people have asked why I would want to do this. brian correctly guessed that I wanted to change export behavior based on whether it's a script, which we can assume has had some amount of design, or whether it's a oneliner where the user is trying to do as much as possible in a single command line. This sounds bad, because there's this credo that exporters should respect other packages--sometimes known as " @EXPORT is EVIL !" But it seems to me that it's a foolish consistency when applied to oneliners. After all perl itself goes out of it's way to violate the structure of its language and give you easy loops if you ask for them on the command line, I simply want to extend that idea for my operational/business domain. I even want to apply source filters ( gasp! ) if it helps. But this question also suggests that I might want to be a good citizen of Perl as well, because I only to break the community guidelines in certain cases. It is quite awesome to be able to create major business-level actions just by changing the command line in a batch scheduler rather than writing a whole new module. The test cycle is much compressed.
$0 is set to "-e" if you're running from -e .
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/167238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11289/" ] }
167,247
How do I stop a function/procedure in a superclass from been overridden in a subclass in Delphi (2007)? I want to mark it so it can not be altered, I believe there is a final keyword but can not for the life of me find the documentation for it, so I am not 100% sure that's what I need.
The keyword is final as you thought. See http://dn.codegear.com/article/34324 and http://blogs.teamb.com/rudyvelthuis/2005/05/13/4311 . Also you can mark your class as sealed to prevent anyone from inheriting from it. You need a Delphi version higher than 7. type TSomeClass = class protected procedure SomeVirtualMethod; virtual; end; TOtherClass = class(TSomeClass) protected procedure SomeVirtualMethod; override; final; end;
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/167247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2098/" ] }
167,262
I suppose this is a strange question to the huge majority of programmers that work daily with Java. I don't. I know Java-the-language, because I worked on Java projects, but not Java-the-world. I never made a web app from scratch in Java. If I have to do it with Python, Ruby, I know where to go (Django or Rails), but if I want to make a web application in Clojure, not because I'm forced to live in a Java world, but because I like the language and I want to give it a try, what libraries and frameworks should I use?
By far the best Clojure web framework I have yet encountered is Compojure: http://github.com/weavejester/compojure/tree/master It's small but powerful, and has beautifully elegant syntax. (It uses Jetty under the hood, but it hides the Servlet API from you unless you want it, which won't be often). Go look at the README at that URL, then download a snapshot and start playing.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/167262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6068/" ] }
167,304
I am wondering if it is possible to use LINQ to pivot data from the following layout: CustID | OrderDate | Qty1 | 1/1/2008 | 1002 | 1/2/2008 | 2001 | 2/2/2008 | 3502 | 2/28/2008 | 2211 | 3/12/2008 | 2502 | 3/15/2008 | 2150 into something like this: CustID | Jan- 2008 | Feb- 2008 | Mar - 2008 |1 | 100 | 350 | 2502 | 200 | 221 | 2150
Something like this? List<CustData> myList = GetCustData();var query = myList .GroupBy(c => c.CustId) .Select(g => new { CustId = g.Key, Jan = g.Where(c => c.OrderDate.Month == 1).Sum(c => c.Qty), Feb = g.Where(c => c.OrderDate.Month == 2).Sum(c => c.Qty), March = g.Where(c => c.OrderDate.Month == 3).Sum(c => c.Qty) }); GroupBy in Linq does not work the same as SQL. In SQL, you get the key and aggregates (row/column shape). In Linq, you get the key and any elements as children of the key (hierarchical shape). To pivot, you must project the hierarchy back into a row/column form of your choosing.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/167304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2833/" ] }
167,316
I'm trying to achieve the last possible time of a particular day eg for Date of 2008-01-23 00:00:00.000 i would need 2008-01-23 23:59:59.999 perhaps by using the dateadd function on the Date field?
The answer is SELECT DATEADD(ms, -3, '2008-01-24') , the explanation is below. From Marc's blog : But wait, Marc... you said you like to use BETWEEN , but that query doesn't have one... that's because BETWEEN is inclusive , meaning it includes the end-points. If I had an Order that was due at midnight of the first day of the next month it would be included. So how do you get the appropriate value for an end-of-period? It's most certainly NOT by using date-parts to assemble one (but is you must, please remember that it's 23:59:59.997 as a maximum time... don't forget the milliseconds). To do it right, we use the incestuous knowledge that Microsoft SQL Server DATETIME columns have at most a 3 millisecond resolution (something that is not going to change). So all we do is subtract 3 milliseconds from any of those end-of-period formulas given above. For example, the last possible instant of yesterday (local time) is: SELECT DATEADD(ms, -3, DATEADD(dd, DATEDIFF(dd, 0, GetDate()), 0)) So to do the orders due this month as a BETWEEN query, you can use this: SELECT [ID] FROM [dbo].[Orders] WHERE [ShipDue] BETWEEN DATEADD(mm, DATEDIFF(mm, 0, GetUTCDate()), 0) AND DATEADD(ms, -3, DATEADD(mm, DATEDIFF(mm, 0, GetUTCDate()) + 1, 0)) Remember, always make sure that you do math against input parameters, NOT columns, or you will kill the SARG -ability of the query, which means indexes that might have been used aren't.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/167316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21004/" ] }
167,323
I am still having problems with figuring out how to create winforms in a separate UI thread that I discussed here . In trying to figure this out I wrote the following simple test program. I simply want it to open a form on a separate thread named "UI thread" and keep the thread running as long as the form is open while allowing the user to interact with the form (spinning is cheating). I understand why the below fails and the thread closes immediately but am not sure of what I should do to fix it. using System;using System.Windows.Forms;using System.Threading;namespace UIThreadMarshalling { static class Program { [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var tt = new ThreadTest(); ThreadStart ts = new ThreadStart(tt.StartUiThread); Thread t = new Thread(ts); t.Name = "UI Thread"; t.Start(); Thread.Sleep(new TimeSpan(0, 0, 10)); } } public class ThreadTest { Form _form; public ThreadTest() { } public void StartUiThread() { _form = new Form1(); _form.Show(); } }}
On a new thread, call Application.Run passing the form object, this will make the thread run its own message loop while the window is open. Then you can call .Join on that thread to make your main thread wait until the UI thread has terminated, or use a similar trick to wait for that thread to complete. Example: public void StartUiThread(){ using (Form1 _form = new Form1()) { Application.Run(_form); }}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/167323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ] }
167,343
I have quickly read over the Microsoft Lambda Expression documentation. This kind of example has helped me to understand better, though: delegate int del(int i);del myDelegate = x => x * x;int j = myDelegate(5); //j = 25 Still, I don't understand why it's such an innovation. It's just a method that dies when the "method variable" ends, right? Why should I use this instead of a real method?
Lambda expressions are a simpler syntax for anonymous delegates and can be used everywhere an anonymous delegate can be used. However, the opposite is not true; lambda expressions can be converted to expression trees which allows for a lot of the magic like LINQ to SQL. The following is an example of a LINQ to Objects expression using anonymous delegates then lambda expressions to show how much easier on the eye they are: // anonymous delegatevar evens = Enumerable .Range(1, 100) .Where(delegate(int x) { return (x % 2) == 0; }) .ToList();// lambda expressionvar evens = Enumerable .Range(1, 100) .Where(x => (x % 2) == 0) .ToList(); Lambda expressions and anonymous delegates have an advantage over writing a separate function: they implement closures which can allow you to pass local state to the function without adding parameters to the function or creating one-time-use objects. Expression trees are a very powerful new feature of C# 3.0 that allow an API to look at the structure of an expression instead of just getting a reference to a method that can be executed. An API just has to make a delegate parameter into an Expression<T> parameter and the compiler will generate an expression tree from a lambda instead of an anonymous delegate: void Example(Predicate<int> aDelegate); called like: Example(x => x > 5); becomes: void Example(Expression<Predicate<int>> expressionTree); The latter will get passed a representation of the abstract syntax tree that describes the expression x > 5 . LINQ to SQL relies on this behavior to be able to turn C# expressions in to the SQL expressions desired for filtering / ordering / etc. on the server side.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/167343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13913/" ] }
167,371
I just want to see what files were modded/added/deleted between 2 arbitrary revisions. How do I do this? Can I do this in tortoise as well?
svn log -v -rX:Y . The -v for "verbose" switch will give you detailed output on which files were affected on that revision. Note that "." assumes you are currently in a working copy directory, but you can also use a URL such as " http://svn.myawesomesoftwareproject.com/trunk/lib/foo.c ". This information can be found by typing "svn help log", or by reading the SVN Book , available free online. Don't forget to R ead T he F riendly M anual!
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/167371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1946/" ] }
167,414
On POSIX systems rename(2) provides for an atomic rename operation, including overwriting of the destination file if it exists and if permissions allow. Is there any way to get the same semantics on Windows? I know about MoveFileTransacted() on Vista and Server 2008, but I need this to support Win2k and up. The key word here is atomic ... the solution must not be able to fail in any way that leaves the operation in an inconsistent state. I've seen a lot of people say this is impossible on win32, but I ask you, is it really? Please provide reliable citations if possible.
Win32 does not guarantee atomic file meta data operations. I'd provide a citation, but there is none - that fact that there's no written or documented guarantee means as much. You're going to have to write your own routines to support this. It's unfortunate, but you can't expect win32 to provide this level of service - it simply wasn't designed for it.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/167414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14739/" ] }
167,416
Hi I want to have two tables each have an INT "id" column which will auto-increment but I don't want either "id" columns to ever share the same number. What is this called and what's the best way to do it? Sequence? Iterator? Index? Incrementor? Motivation: we're migrating from one schema to a another and have a web-page that reads both tables and shows the (int) ID, but I can't have the same ID used for both tables. I'm using SQL Server 9.0.3068. Thanks!
Just configure the identity increment to be >1 e.g. table one uses IDENTITY (1, 10) [1,11,21...] and table two uses IDENTITY (2, 10) [2,12,22...]. This will also give you some room for expansion if needed later.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/167416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24881/" ] }
167,453
I'm exploring the XML -> XSLT -> HTML meme for producing web content. I have very little XSLT experience. I'm curious what mechanisms are available in XSLT to handle abstractions or "refactoring". For example, with generic HTML and a service side include, many pages can be templated and decomposed to where there are, say, common header, nav, and footer segments, and the page itself is basically the body. The common markup languages, JSP, PHP, ASP, go as far as to allow all of those segments to have dynamic content (such as adding the user name to every header block). JSP goes even farther by allowing you to create Tag files, which can accept arguments to be used when generating the content, and even surround and work on content within the tags themselves. I'm curious similar functionality is done within XSLT. What facilities are there to make reusable block of XSLT for things like creating HTML pages?
For my own project, this is how I divided up my pages. There was a template.xsl file which was importedby each of my XSLs. Most pages just had template.xsl, but some pages such as cart, etc. needed their ownbecause of the different kind of data they were parsing. <page title="Home"> <navigation> <!-- something here --> </navigation> <main> <!-- something here --> </main></page> This is a snippet from my template.xsl. I threw in all the common stuff in here, and then gave the opportunityfor my pages to add their own information through call-template . <xsl:template match="/page" name="page"> <html> <head> <title><xsl:value-of select="(@title)" /></title> <xsl:call-template name="css" /> <xsl:call-template name="script" /> </head> <body> <xsl:call-template name="container" /> </body> </html></xsl:template> An example of how my css tag would respond. Note that it calls css-extended. css onlyhad the the common css' that would apply across all pages. Some pages needed more. Thosecould override css-extended. Note that is needed because call-template will fail if a page calls a template but doesn't define it anywhere. <xsl:template name="css"> <link rel="stylesheet" type="text/css" href="{$cssPath}reset.css" /> <link rel="stylesheet" type="text/css" href="{$cssPath}style.css" /> <link rel="stylesheet" type="text/css" href="{$cssPath}layout.css" /> <xsl:call-template name="css-extended" /> </xsl:template> <!-- This is meant to be blank. It gets overriden by implementing stylesheets --> <xsl:template name="css-extended" /> My container would work in a similar manner-- common stuff was defined and then each pagecould just provide an implementation. A default implementation was in the XSL. (in content ) <xsl:template name="container"> <div id="container"> <xsl:call-template name="header" /> <xsl:call-template name="content" /> <xsl:call-template name="footer" /> </div> </xsl:template> <xsl:template name="content"> <div id="content"> <div id="content-inner"> <xsl:call-template name="sideBar" /> <xsl:call-template name="main" /> </div> </div> </xsl:template> <xsl:template name="main"> <div id="main"> <xsl:apply-templates select="main" /> <xsl:call-template name="main-extended" /> </div> </xsl:template> <!-- This is meant to be blank. It gets overriden by implementing stylesheets --> <xsl:template name="main-extended" /><xsl:template name="footer"> <div id="footer"> <div id="footer-inner"> <!-- Footer content here --> </div> </div></xsl:template> It worked quite beautifully for me. If there are any questions I can answer for you, let me know.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/167453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13663/" ] }
167,464
I am currently investigating how to make a connection to a SQL Server database from my Java EE web application using Windows Authentication instead of SQL Server authentication. I am running this app off of Tomcat 6.0, and am utilizing the Microsoft JDBC driver. My connection properties file looks as follows: dbDriver = com.microsoft.sqlserver.jdbc.SQLServerDriverdbUser = userdbPass = passworddbServer = localhost:1433;databaseName=testDbdbUrl = jdbc:sqlserver://localhost:1433 I have zero problems with connecting to a SQL Server database in this fashion when using SQL Server authentication. Is there any way I can retrieve the credentials of the user's Windows Authentication and use that authentication for SQL Server? UPDATE : I know in ASP.net there is a way to set up Windows Authentication for access to the webapp, which is exactly what I am looking for, except I want to pass that token off to SQL Server for access to the database.
I do not think one can push the user credentials from the browser to the database (and does it makes sense ? I think not) But if you want to use the credentials of the user running Tomcat to connect to SQL Server then you can use Microsoft's JDBC Driver.Just build your JDBC URL like this: jdbc:sqlserver://localhost;integratedSecurity=true; And copy the appropriate DLL to Tomcat's bin directory (sqljdbc_auth.dll provided with the driver) MSDN > Connecting to SQL Server with the JDBC Driver > Building the Connection URL
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/167464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/318/" ] }
167,471
In Oracle, given a simple data table: create table data ( id VARCHAR2(255), key VARCHAR2(255), value VARCHAR2(511)); suppose I want to "insert or update" a value. I have something like: merge into data using dual on (id='someid' and key='testKey')when matched then update set value = 'someValue' when not matched then insert (id, key, value) values ('someid', 'testKey', 'someValue'); Is there a better way than this? This command seems to have the following drawbacks: Every literal needs to be typed twice (or added twice via parameter setting) The "using dual" syntax seems hacky If this is the best way, is there any way around having to set each parameter twice in JDBC?
I don't consider using dual to be a hack. To get rid of binding/typing twice, I would do something like: merge into datausing ( select 'someid' id, 'testKey' key, 'someValue' value from dual) val on ( data.id=val.id and data.key=val.key)when matched then update set data.value = val.value when not matched then insert (id, key, value) values (val.id, val.key, val.value);
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/167471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5309/" ] }
167,491
How do I in SQL Server 2005 use the DateAdd function to add a day to a date
Use the following function: DATEADD(type, value, date) date is the date you want to manipulate value is the integere value you want to add (or subtract if you provide a negative number) type is one of: yy, yyyy: year qq, q: quarter mm, m: month dy, y: day of year dd, d: day wk, ww: week dw, w: weekday hh: hour mi, n: minute ss or s: second ms: millisecond mcs: microsecond ns: nanosecond SELECT DATEADD(dd, 1, GETDATE()) -- will return a current date + 1 day http://msdn.microsoft.com/en-us/library/ms186819.aspx
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/167491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21004/" ] }
167,502
This is the page that I'm having. But the resize part in the section does not seem to be working. I copied most of the code from the Ajax site . I placed a alert() in the tag (line 108) to find the value of 'b._originalHeight' and it shows up as '44'. I have also tried the code in the above-said tutorial (line 132) and that did not work either. (I'm not sure where it is getting this value from. But I need it to show all the controls on the form. <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="AddEditContest.ascx.cs" Inherits="TMPInternational.Spawn2DotComAdmin.Contest.UserControls.AddEditContest" %><%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="uc" %><%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI" TagPrefix="asp" %><%@ Register TagPrefix="ew" Assembly="eWorld.UI, Version=1.9.0.0, Culture=neutral, PublicKeyToken=24d65337282035f2" Namespace="eWorld.UI" %><h1 style="margin-left:8px">Add/Edit Contest</h1><asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" /><div style="text-align:left;width:500px; margin-left:8px"> <div id="PanelContainer"> <asp:UpdatePanel ID="AddEditContestUpdatePanel" runat="server" UpdateMode="Always"> <ContentTemplate> <div id="background" style="text-align:left; height: 44px;"> <asp:Panel ID="ContestList" runat="server"> <asp:datagrid AllowSorting="false" id="ContestGrid" GridLines="None" CellPadding="5" Width="100%" AutoGenerateColumns="False" AlternatingItemStyle-BackColor="#cccccc" HeaderStyle-Font-Size="15px" HeaderStyle-Font-Bold="true" HeaderStyle-BackColor="#888f9b" Runat="server" AllowPaging="True" PageSize="10" PagerStyle-NextPageText="Next >>" PagerStyle-PrevPageText="<< Back" > <Columns> <asp:HyperLinkColumn DataNavigateUrlField="ContestID" DataNavigateUrlFormatString="../?Load=AddEditContest&Type=Edit&ContestID={0}" DataTextField="Title" ItemStyle-width="30%" headertext="Contest Title" /> <asp:BoundColumn DataField="StartDate" ItemStyle-Width="35%" HeaderText="Start Date" /> <asp:BoundColumn DataField="EndDate" ItemStyle-Width="35%" HeaderText="End Date" /> </Columns> </asp:datagrid> <div style="text-align:right;"> <asp:ImageButton ID="AddContest" runat="server" ImageUrl="~/Contest/Images/Add.png" AlternateText="Add Contest" onclick="AddContest_Click" /> </div> </asp:Panel> <asp:Panel ID="FieldsPanel" runat="server"> <p /><b>Title</b> <br /> <asp:TextBox Runat="server" id="TitleText" /> <asp:RequiredFieldValidator id="TitleValidator" runat="server" ForeColor="Red" ErrorMessage="Please add a title" ControlToValidate="TitleText">*</asp:RequiredFieldValidator> <p /><b>Contest Description</b> <br /> Use HTML tags to format this area. Start paragraphs with &lt;p /&gt; tag, bold items with &lt;b&gt;&lt;/b&gt; tags. Create a line-break between lines with one &lt;br /&gt; tag.<br /> <asp:TextBox Runat="server" ID="DescriptionText" TextMode="MultiLine" Width="400" Height="200" /> <asp:RequiredFieldValidator id="DescriptionValidator" runat="server" ErrorMessage="Please add a description" ControlToValidate="DescriptionText" ForeColor="Red">*</asp:RequiredFieldValidator> <p /> <b>Contest Start Date</b> <br /> <ew:CalendarPopup id="StartDate" runat="server" Text="Change Date" Width="75px" MonthYearArrowImageUrl="~/Images/monthchange.gif" CalendarLocation="Left" ControlDisplay="TextBoxImage" ImageUrl="~/Images/calendar.gif" MonthYearPopupApplyText="Select" CalendarWidth="150" UseExternalResource="True" ExternalResourcePath="~/Scripts/CalendarPopup.js" Nullable="False"> <WeekdayStyle Font-Names="Arial" ForeColor="Black" BackColor="White" Font-Size="9pt" /> <MonthHeaderStyle Font-Size="9pt" Font-Names="Arial" Font-Bold="True" ForeColor="White" BackColor="#669AC1" /> <OffMonthStyle ForeColor="Gray" BackColor="White" Font-Size="9pt" /> <GoToTodayStyle Font-Names="Arial" ForeColor="Black" BackColor="White"/> <TodayDayStyle Font-Bold="True" ForeColor="#669AC1" BackColor="White" /> <DayHeaderStyle Font-Size="9pt" Font-Names="Arial" Font-Bold="True" ForeColor="Blue" BackColor="White" /> <WeekendStyle Font-Names="Arial" ForeColor="Blue" BackColor="LightGray" Font-Size="9pt" /> <SelectedDateStyle Font-Bold="True" ForeColor="White" BackColor="#669AC1" Font-Size="9pt"/> <HolidayStyle Font-Names="Arial" ForeColor="Black" BackColor="White" /> </ew:CalendarPopup> &nbsp; <ew:TimePicker id="StartTime" runat="server" ControlDisplay="TextboxImage" Text="Change Time" ImageUrl="~/Images/clock.gif" NumberOfColumns="4" Scrollable="True" Width="75px"> <TimeStyle ForeColor="Blue" BackColor="White" Font-Size="9pt" /> <SelectedTimeStyle ForeColor="Blue" BackColor="Gray" /> </ew:TimePicker> <p/><b>Contest End Date</b> <br /> <ew:CalendarPopup id="EndDate" runat="server" Text="Change Date" Width="75px" MonthYearArrowImageUrl="~/Images/monthchange.gif" CalendarLocation="Left" ControlDisplay="TextBoxImage" ImageUrl="~/Images/calendar.gif" MonthYearPopupApplyText="Select" CalendarWidth="150" UseExternalResource="True" ExternalResourcePath="~/Scripts/CalendarPopup.js" Nullable="False"> <WeekdayStyle Font-Names="Arial" ForeColor="Black" BackColor="White" Font-Size="9pt" /> <MonthHeaderStyle Font-Size="9pt" Font-Names="Arial" Font-Bold="True" ForeColor="White" BackColor="#669AC1" /> <OffMonthStyle ForeColor="Gray" BackColor="White" Font-Size="9pt" /> <GoToTodayStyle Font-Names="Arial" ForeColor="Black" BackColor="White"/> <TodayDayStyle Font-Bold="True" ForeColor="#669AC1" BackColor="White" /> <DayHeaderStyle Font-Size="9pt" Font-Names="Arial" Font-Bold="True" ForeColor="Blue" BackColor="White" /> <WeekendStyle Font-Names="Arial" ForeColor="Blue" BackColor="LightGray" Font-Size="9pt" /> <SelectedDateStyle Font-Bold="True" ForeColor="White" BackColor="#669AC1" Font-Size="9pt"/> <HolidayStyle Font-Names="Arial" ForeColor="Black" BackColor="White" /> </ew:CalendarPopup> &nbsp; <ew:TimePicker id="EndTime" runat="server" ControlDisplay="TextboxImage" Text="Change Time" ImageUrl="~/Images/clock.gif" NumberOfColumns="4" Scrollable="True" Width="75px"> <TimeStyle ForeColor="Blue" BackColor="White" Font-Size="9pt" /> <SelectedTimeStyle ForeColor="Blue" BackColor="Gray" /> </ew:TimePicker> <p /> <asp:ImageButton ID="SaveContestButton" runat="server" AlternateText="Confirm" ImageUrl="~/Contest/Images/Confirm.png" onclick="SaveContestButton_Click" /> </asp:Panel> <br /> <asp:Label ID="MessageLabel" runat="server" /> </div> </ContentTemplate> <Triggers> <asp:AsyncPostBackTrigger ControlID="SaveContestButton" EventName="Click" /> </Triggers> </asp:UpdatePanel> </div> <uc:UpdatePanelAnimationExtender ID="upae" BehaviorID="animation" runat="server" TargetControlID="AddEditContestUpdatePanel"> <Animations> <OnUpdating> <Sequence> <%-- Store the original height of the panel --%> <ScriptAction Script="var b = $find('animation'); b._originalHeight = b._element.offsetHeight;" /> <%-- Disable all the controls --%> <Parallel duration="0"> <EnableAction AnimationTarget="SaveDefaultDescriptionButton" Enabled="false" /> </Parallel> <StyleAction Attribute="overflow" Value="hidden" /> <%-- Do each of the selected effects --%> <Parallel duration=".25" Fps="30"> <FadeOut AnimationTarget="PanelContainer" minimumOpacity=".2" /> <Resize Height="0px" /> </Parallel> </Sequence> </OnUpdating> <OnUpdated> <Sequence> <%-- Do each of the selected effects --%> <Parallel duration=".25" Fps="30"> <FadeIn AnimationTarget="PanelContainer" minimumOpacity=".2" /> <Length duration="2" fps="40" Property="style" PropertyKey="height" StartValue="10" EndValueScript="$get('animation').offsetHeight" AnimationTarget="animation" /> <%--Also tried the below <Resize HeightScript="$find('animation')._originalHeight" /> --%> </Parallel> <%-- Enable all the controls --%> <Parallel duration="0"> <EnableAction AnimationTarget="SaveDefaultDescriptionButton" Enabled="true" /> </Parallel> </Sequence> </OnUpdated> </Animations> </uc:UpdatePanelAnimationExtender></div>
Use the following function: DATEADD(type, value, date) date is the date you want to manipulate value is the integere value you want to add (or subtract if you provide a negative number) type is one of: yy, yyyy: year qq, q: quarter mm, m: month dy, y: day of year dd, d: day wk, ww: week dw, w: weekday hh: hour mi, n: minute ss or s: second ms: millisecond mcs: microsecond ns: nanosecond SELECT DATEADD(dd, 1, GETDATE()) -- will return a current date + 1 day http://msdn.microsoft.com/en-us/library/ms186819.aspx
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/167502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2894/" ] }
167,576
I would like this to be the ultimate discussion on how to check if a table exists in SQL Server 2000/2005 using SQL Statements. Here are two possible ways of doing it. Which one is the standard/best way of doing it? First way: IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' AND TABLE_NAME='mytablename') SELECT 1 AS res ELSE SELECT 0 AS res; Second way: IF OBJECT_ID (N'mytablename', N'U') IS NOT NULL SELECT 1 AS res ELSE SELECT 0 AS res; MySQL provides the simple SHOW TABLES LIKE '%tablename%'; statement. I am looking for something similar.
For queries like this it is always best to use an INFORMATION_SCHEMA view. These views are (mostly) standard across many different databases and rarely change from version to version. To check if a table exists use: IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'TheSchema' AND TABLE_NAME = 'TheTable'))BEGIN --Do StuffEND
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/167576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1508/" ] }
167,577
I am working on a project that requires reliable access to historic feed entries which are not necessarily available in the current feed of the website. I have found several ways to access such data, but none of them give me all the characteristics I need. Look at this as a brainstorm. I will tell you how much I have found and you can contribute if you have any other ideas. Google AJAX Feed API - will limit you to 250 items Unofficial Google Reader API - Perfect but unofficial and therefore unreliable (and perhaps quasi-illegal?). Also, the authentication seems to be tricky. Spinn3r - Costs a lot of money Spidering the internet archive at the site of the feed - Lots of complexity, spotty coverage, only useful as a last resort Yahoo! Feed API or Yahoo! Search BOSS - The first looks more like an aggregator, meaning I'd need a different registration for each feed and the second should give more access to Yahoo's data but I can find no mention of feeds. (thanks to Lou Franco) Bloglines Sync API - Besides the problem of needing an account and being designed more as an aggregator, it does not have a way to add feeds to the account. So no retrieval of arbitrary feeds. You need to manually add them through the reader first. Other search engines/blog search/whatever? This is a really irritating problem as we are talking about semantic information that was once out there, is still (usually) valid, yet is difficult to access reliably, freely and without limits. Anybody know any alternative sources for feed entry goodness?
For queries like this it is always best to use an INFORMATION_SCHEMA view. These views are (mostly) standard across many different databases and rarely change from version to version. To check if a table exists use: IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'TheSchema' AND TABLE_NAME = 'TheTable'))BEGIN --Do StuffEND
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/167577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24461/" ] }
167,602
I have a class which implements UserControl. In .NET 2005, a Dispose method is automatically created in the MyClass.Designer.cs partial class file that looks like this: protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } If I want to add my own Dispose functionality, where would I put it? Since this file is generated, I don't want to add code here and risk it getting blown away.
In such a case I move the generated Dispose method to the main file and extend it. Visual Studio respects this. An other approach would be using a partial method (C# 3.0).
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/167602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22252/" ] }
167,622
What are the major difference between bindable LINQ and continuous LINQ? •Bindable LINQ: www.codeplex.com/bindablelinq •Continuous LINQ: www.codeplex.com/clinq One more project was added basing on the provided feedback: •Obtics: obtics.codeplex.com
Their are 2 problems both these packages try to solve: Lack of a CollectionChanged event and Dynamic result sets. There is one additional problem bindable solves, additional automatic event triggers. The First Problem both packages aim to solve is this: Objects returned by a LINQ query do not provide CollectionChanged events. Continuous LINQ automatically does this to all queries, with no change: from item in theSource select item ; Bindable LINQ does this when you add .asBindable to your query Source Object: from item in theSource.AsBindable() select item ; The Second Problem both packages aim to solve is: Result sets returned from a LINQ Query are static. Normally when you do a LINQ Query your result set is unchanged until you do a new query. With these two packages, your result set is updated whenever the source is updated. (bad for performance, good for realtime updates) Example var theSource = new ContinuousCollection<Customer>();var theResultSet = from item in theSource where item.Age > 25 select item;//theResultSet.Count would equal 0. Because your using Bindable or Continuous LINQ, you could modify theSource , and theResultSet would automatically include the new item. theSource.Add(new Customer("Bob", "Barker" , 35, Gender.Male)); //Age == 35//theResultSet.Count would now equal 1. The Additional Problem Bindable LINQ offers: (Quoting directly from their own page) contactsListBox.ItemsSource = from c in customers where c.Name.StartsWith(textBox1.Text) select c; Bindable LINQ will detect that the query relies on the Text property of the TextBox object, textBox1. Since the TextBox is a WPF control, Bindable LINQ knows to subscribe to the TextChanged event on the control. The end result is that as the user types, the items in the query are re-evaluated and the changes appear on screen. No additional code is needed to handle events.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/167622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19268/" ] }
167,628
We are managing our development with Subversion over HTTPS, Bugzilla, and Mediawiki. Some of our developers have expressed an interest in migrating to Trac, so I have to evaluate what the cost of doing so would be. For both the wiki and bugzilla, we would need to either migrate the existing data into Trac or a way to integrate with trac. Having two apps to create wiki pages or log bugs would not be acceptable. Also, currently each of these applications requires a separate sign on so we would need to map each of these accounts into Trac. So know of any easy methods of importing or integrating these systems with Trac and/or a tutorial for doing so?
Their are 2 problems both these packages try to solve: Lack of a CollectionChanged event and Dynamic result sets. There is one additional problem bindable solves, additional automatic event triggers. The First Problem both packages aim to solve is this: Objects returned by a LINQ query do not provide CollectionChanged events. Continuous LINQ automatically does this to all queries, with no change: from item in theSource select item ; Bindable LINQ does this when you add .asBindable to your query Source Object: from item in theSource.AsBindable() select item ; The Second Problem both packages aim to solve is: Result sets returned from a LINQ Query are static. Normally when you do a LINQ Query your result set is unchanged until you do a new query. With these two packages, your result set is updated whenever the source is updated. (bad for performance, good for realtime updates) Example var theSource = new ContinuousCollection<Customer>();var theResultSet = from item in theSource where item.Age > 25 select item;//theResultSet.Count would equal 0. Because your using Bindable or Continuous LINQ, you could modify theSource , and theResultSet would automatically include the new item. theSource.Add(new Customer("Bob", "Barker" , 35, Gender.Male)); //Age == 35//theResultSet.Count would now equal 1. The Additional Problem Bindable LINQ offers: (Quoting directly from their own page) contactsListBox.ItemsSource = from c in customers where c.Name.StartsWith(textBox1.Text) select c; Bindable LINQ will detect that the query relies on the Text property of the TextBox object, textBox1. Since the TextBox is a WPF control, Bindable LINQ knows to subscribe to the TextChanged event on the control. The end result is that as the user types, the items in the query are re-evaluated and the changes appear on screen. No additional code is needed to handle events.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/167628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9940/" ] }
167,635
Let's say I 've added a library foo.so.1.1.1 to a path that is included in /etc/ld.so.conf When I run ldconfig on the system I get the links foo.so.1.1 and foo.so.1 to foo.so.1.1.1 How can I change the behavior to also get the foo.so link to foo.so.1.1.1?
ldconfig looks inside all shared objects that it finds, to look for the soname. It then creates a link using that soname as the name of the link. It's conventional (but far from universally done) for the soname to be the name and major version of the library, so your library foo.so.1.1 will have a soname of foo.so.1 and ldconfig will make a link called that. No part of the run-time system looks for or knows anything about the name foo.so. That's used when you link your programs to the library. There's no point in having that link unless you also have all the other development files (headers etc) for the library, so there's no point in ldconfig automatically creating it. And since the name of the link to use is only another convention, and in this case isn't stored inside the file at all, there's no way for ldconfig to know what name to create. Normally this would be created manually, in the install target of the Makefile; when a library is packaged for a linux distribution the link normally lives in the -dev package along with the header files.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/167635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6403/" ] }
167,643
How do I write the SQL code to INSERT (or UPDATE) an array of values (with probably an attendant array of fieldnames, or with a matrix with them both) without simple iteration?
I construct the list as an xml string and pass it to the stored procs. In SQL 2005, it has enhanced xml functionalities to parse the xml and do a bulk insert. check this post: Passing lists to SQL Server 2005 with XML Parameters
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/167643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13295/" ] }
167,657
When IE8 is released, will the following code work to add a conditional stylesheet? <!--[if IE 8]> <link rel="stylesheet" type="text/css" href="ie-8.0.css" /><![endif]--> I've read conflicting reports as to whether this works with the beta. I'm hoping someone can share their experience. Thanks.
It worked for me – both in quirks mode and in standards compliance mode. However, it does not work when switching to IE8 compatibility mode.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/167657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13850/" ] }
167,671
Is it possible to use a ".net configuration" file for a .NET console application? I'm looking for an equivalent to web.config, but specifically for console applications... I can certainly roll my own, but If I can use .NET's built in configuration reader then I would like to do that...I really just need to store a connection string... Thanks
Yes - use app.config. Exactly the same syntax, options, etc. as web.config, but for console and WinForms applications. To add one to your project, right-click the project in Solution Explorer, Add..., New Item... and pick "Application Configuration File" from the Templates box.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/167671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ] }
167,705
How do I load the edited .emacs file without restarting Emacs?
M-x eval-buffer
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/167705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8522/" ] }
167,716
I was looking into the possibility of using CouchDB. I heard that it was similar to Lotus Notes which everyone loves to hate. Is this true?
Development of Lotus Notes began over 20 years ago, with version 1 released in 1989 . It was developed by Ray Ozzie, currently Chief Software Architect for Microsoft. Lotus Notes (the client) and Domino (the server) have been around for a long time and are mature well featured products. It has: A full client server stack with rapid application design and deployment of document oriented databases. A full public key infrastructure for security and encryption. A robust replication model and active active clustering across heterogeneous platforms (someone once showed a domino cluster with an xbox and a huge AIX server ). A built in native directory for managing users that can also be accessed over LDAP. A built in native mail system that can scale to manage millions of users with multi GB mail files, with live server access or replicated locally for off-line access. This can interface with standard internet mail through SMTP and also has POP and IMAP access built in. The mail infrastructure is a core feature that is available to all applications built on Notes Domino (any document in a database can be mailed to any other database with a simple doc.send() command). A built in HTTP stack that allows server hosted databases to be accessed over the web. A host of integration options for accessing, transferring and interoperating with RDBMS and ERP systems, with a closely coupled integration with DB2 available allowing Notes databases to be backed by a relational store where desired. Backwards compatibility has always been a strong feature of Notes Domino and it is not uncommon to find databases that were developed for version 3 running flawlessly in the most up to date versions. IBM puts a huge amount of effort into this and it has a large bearing on how the product currently operates. - CouchDB was created by Damien Katz, starting development in 2004. He had previously worked for IBM on Notes Domino, developing templates and eventually completely rewriting one of the core features, the formula engine, for ND6. CouchDB shares a basic concept of a document oriented database with views that Notes Domino has. In this model "documents" are just arbitrary collections of values that are stored some how. In CouchDB the documents are JSON objects of arbitrary complexity. In Notes the values are simple name value pairs, where the values can be strings, numbers, dates or arrays of those. Views are indexes of the documents in the database, displaying certain value, calculating others and excluding undesired docs. Once the index is build they are incrementally updated when any document in the database changes (created updated or deleted). In CouchDB views are build by running a mapping function on each document in the database. The mapping function calls an emit method with a JSON object for every index entry it wants to create for the given document. This JSON object can be arbitrarily complex. CouchDB can then run a second reducing function on the mapped index of the view. In Notes Domino views are built by running a select function (written in Notes Domino formula language) on each document in the database. The select function simply defines if the document should be in the view or not. Notes Domino view design also defines a number of columns for the view. Each column has a formula that is run against the selected document to determine the value for that column. CouchDB is able to produce much more sophisticated view indexes than Notes Domino can. CouchDB also has a replication system. - Summary ( TL;DR ) : CouchDB is brand new software that is developing a core that has a similar conceptual but far more sophisticated design to that used in Lotus Notes Domino. Lotus Notes Domino is a mature fully featured product that is capable of being deployed today. CouchDB is starting from scratch, building a solid foundation for future feature development. Lotus Notes Domino is continuing to develop new features, but is doing so on a 20 year old platform that strives to maintain backwards compatibility. There are features in Notes Domino that you might wish were in CouchDB, but there are also features in Notes Domino that are anachronistic in today's world.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/167716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20714/" ] }
167,735
I am looking for a pseudo random number generator which would be specialized to work fast when it is given a seed before generating each number. Most generators I have seen so far assume you set seed once and then generate a long sequence of numbers. The only thing which looks somewhat similar to I have seen so far is Perlin Noise, but it generates too "smooth" data - for similar inputs it tends to produce similar results. The declaration of the generator should look something like: int RandomNumber1(int seed); Or: int RandomNumber3(int seedX, int seedY, int seedZ); I think having good RandomNumber1 should be enough, as it is possible to implement RandomNumber3 by hashing its inputs and passing the result into the RandomNumber1, but I wrote the 2nd prototype in case some implementation could use the independent inputs. The intended use for this generator is to use it for procedural content generator, like generating a forest by placing trees in a grid and determining a random tree species and random spatial offsets for each location. The generator needs to be very efficient (below 500 CPU cycles), because the procedural content is created in huge quantities in real time during rendering.
Seems like you're asking for a hash-function rather than a PRNG. Googling 'fast hash function' yields several promising-looking results. For example : uint32_t hash( uint32_t a) a = (a ^ 61) ^ (a >> 16); a = a + (a << 3); a = a ^ (a >> 4); a = a * 0x27d4eb2d; a = a ^ (a >> 15); return a;} Edit: Yep, some hash functions definitely look more suitable than others. For your purposes, it should be sufficient to eyeball thefunction and check that a single-bit change in the input will propagate to lots of output bits.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/167735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16673/" ] }
167,752
I would like to add a typing speed indicator just below the textarea we use on our contact form. It is just for fun and to give the user some interactivity with the page while they are completing the form. It should display the average speed while typing and keep the last average when the keystrokes are idle. When they leave the textarea the last average should stick. Ideally I would like to have a jQuery plugin if it is available. [Edit] this was originally for just a few of my websites. But after I posted the question it struck me how this would be a neat feature for SO. If you agree vote here
Here's a tested implementation,which seems ok, but I don't guarantee the math. A Demo: http://jsfiddle.net/iaezzy/pLpx5oLf/ And the code: <?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Type Speed</title> <script type="text/javascript" src="js/jquery-1.2.6.js"></script> <style type="text/css"> form { margin: 20px auto; width: 500px; } #textariffic { width: 400px; height: 400px; font-size: 12px; font-family: monospace; line-height: 15px; } </style> <script type="text/javascript"> $(function() { $('textarea') .keyup(checkSpeed); }); var iLastTime = 0; var iTime = 0; var iTotal = 0; var iKeys = 0; function checkSpeed() { iTime = new Date().getTime(); if (iLastTime != 0) { iKeys++; iTotal += iTime - iLastTime; iWords = $('textarea').val().split(/\s/).length; $('#CPM').html(Math.round(iKeys / iTotal * 6000, 2)); $('#WPM').html(Math.round(iWords / iTotal * 6000, 2)); } iLastTime = iTime; } </script> </head> <body> <form id="tipper"> <textarea id="textariffic"></textarea> <p> <span class="label">CPM</span> <span id="CPM">0</span> </p> <p> <span class="label">WPM</span> <span id="WPM">0</span> </p> </form> </body></html>
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/167752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3747/" ] }
167,791
As a programmer I found it very hard to use my laptop and workstation with two different input devices, Can anyone suggest a good solution to use single mouse and keyboard to control my two machines I am not looking for a Virtual Machine or RDP solution to see my machines in a single monitor,
Synergy. Synergy lets you easily share a single mouse and keyboard between multiple computers with different operating systems, each with its own display, without special hardware. It's intended for users with multiple computers on their desk since each system uses its own monitor(s). Redirecting the mouse and keyboard is as simple as moving the mouse off the edge of your screen. Synergy also merges the clipboards of all the systems into one, allowing cut-and-paste between systems. Furthermore, it synchronizes screen savers so they all start and stop together and, if screen locking is enabled, only one screen requires a password to unlock them all. P. S. See also how to fix Synergy problems on Vista .
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/167791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8091/" ] }
167,812
I've been using Xcode for the usual C/C++/ObjC development. I'm wondering what are practical considerations, opinions of Xcode, Eclipse or NetBeans usage on a Mac for Java development? Please don't include my current usage of Xcode in your analysis.
I like NetBeans on OS X for Java. It seems like I spend more time configuring eclipse to get a decent java programming environment. With NetBeans the setup time is less and I can get down to programming quicker...
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/167812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11994/" ] }
167,835
I'm specifically thinking about the BugMeNot service, which provides user name and password combos to a good number of sites. Now, I realize that pay-for-content sites might be worried about this (and I would suspect that most watch for shared accounts), but how about other sites? Should administrators be on the lookout for these accounts? Should web developers do anything differently to take them into account (and perhaps prevent their use)?
I think it depends on the aim of your site. If usage analytics are all-important, then this is something you'd have to watch out for. If advertising is your only revenue stream, then does it really matter which username someone uses? Probably the best way to discourage use of bugmenot accounts is to make it worthwhile to have an actual account. E.g.: No one would use that here, since we all want rep and a profile, or if you're sending out useful emails, people want to receive them.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/167835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ] }
167,862
One of the vagaries of my development system (Codegear C++Builder) is that some of the auto-generated headers insist on having... using namespace xyzzy ...statements in them, which impact on my code when I least want or expect it. Is there a way I can somehow cancel/override a previous "using" statement to avoid this. Maybe... unusing namespace xyzzy;
Nope. But there's a potential solution: if you enclose your include directive in a namespace of its own, like this... namespace codegear { #include "codegear_header.h"} // namespace codegear ...then the effects of any using directives within that header are neutralized. That might be problematic in some cases. That's why every C++ style guide strongly recommends not putting a "using namespace" directive in a header file.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/167862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1737/" ] }
167,904
Say there are two possible solutions to a problem: the first is quick but hacky; the second is preferable but would take longer to implement. You need to solve the problem fast, so you decide to get the hack in place as quickly as you can, planning to start work on the better solution afterwards. The trouble is, as soon as the problem is alleviated, it plummets down the to-do list. You're still planning to put in the better solution at some point, but it's hard to justify implementing it right now. Suddenly you find you've spent five years using the less-than-perfect solution, cursing it the while. Does this sound familiar? I know it's happened more than once where I work. One colleague describes deliberately making a bad GUI so that it wouldn't be accidentally adopted long-term. Do you have a better strategy?
Write a test case which the hack fails. If you can't write a test which the hack fails, then either there's nothing wrong with the hack after all, or else your test framework is inadequate. If the former, run away quick before you waste your life on needless optimisation. If the latter, seek another approach (either to flagging hacks, or to testing...)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/167904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11575/" ] }
167,909
I hate Physics, but I love software development. When I go back to school after Thanksgiving, I'll be taking two more quarters of Physics before I'm done with the horrid thing. I am currently reading postings on the F# units of measurement feature, but I've never used a language like F#. Would it be suitable to write applications so I can perhaps learn something about Physics while doing something I like? I'm interested in command-line applications (even those that I can just execute and have spit out an answer without needing inputs) for things like kinematics, planar motion, Newton's Laws, gravitation, work, energy, momentum and impulse, systems of particles, rotational kinematics and dynamics, angular momentum, static equilibrium, oscillatory motion, wave motion, sound, physical optics, electrostatics, Gauss' law, electric field and potential, capacitance, resistance, DC circuits, magnetic field, Ampere's law, and inductance. The reason I'm interested in F# is because of the units of measure functionality that the language provides.
In my biased opinion, F# is ideal for physics. It has a feature called Units of Measure which does dimensional analysis for you, providing errors if you get it wrong. For example if you write: let distance : float<meters> = gravity * 3.0<seconds> That would yield a compile-error , since gravity is < meters/seconds^2 > and not < meters >. This prevents a great deal of physics-related programming errors. For more information check out Andrew Kennedy's blog .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/167909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ] }
167,917
There are many techniques to enforce strong passwords on website: Requesting that passwords pass a regex of varying complexity Setting the password autonomously, so that casual users have a strong password Letting passwords expire etc. On the other hands there are drawbacks, because all of them make life less easy for the user, meaning less registrations. So, what techniques do you use? Which provide the best protection vs. inconvenience ratio? To clear things up, I am not referring to banking sites or sites that store credit cards. Think more in terms of popular (or not-so-popular) sites that still require registration.
I don't think it's possible to enforce strong passwords, but there are lots of things you can do to encourage them as much as possible. Rate each password and give the user feedback in the form of a score or a graphical bar, etc. Set a minimum password score to weed out the awful ones Have a list of common words that are either banned, or tank the password score One excellent trick I like to use is to have the password's expiry date tied to the password score. So stronger passwords don't need to be changed so often. This works particularly well if you can give users direct feedback about how long the password they've chosen will live for (and dynamically update it so they can see how adding characters affects the date).
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/167917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7028/" ] }