source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
117,262 | MySQL's explain output is pretty straightforward. PostgreSQL's is a little more complicated. I haven't been able to find a good resource that explains it either. Can you describe what exactly explain is saying or at least point me in the direction of a good resource? | Explaining_EXPLAIN.pdf could help too. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/117262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38359/"
]
} |
117,293 | How far do you go with const ? Do you just make functions const when necessary or do you go the whole hog and use it everywhere? For example, imagine a simple mutator that takes a single boolean parameter: void SetValue(const bool b) { my_val_ = b; } Is that const actually useful? Personally I opt to use it extensively, including parameters, but in this case I wonder if it's worthwhile? I was also surprised to learn that you can omit const from parameters in a function declaration but can include it in the function definition, e.g.: .h file void func(int n, long l); .cpp file void func(const int n, const long l) Is there a reason for this? It seems a little unusual to me. | The reason is that const for the parameter only applies locally within the function, since it is working on a copy of the data. This means the function signature is really the same anyways. It's probably bad style to do this a lot though. I personally tend to not use const except for reference and pointer parameters. For copied objects it doesn't really matter, although it can be safer as it signals intent within the function. It's really a judgement call. I do tend to use const_iterator though when looping on something and I don't intend on modifying it, so I guess to each his own, as long as const correctness for reference types is rigorously maintained. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/117293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
]
} |
117,337 | Let's assume that some developer in my team shelved his changes that he did in branch A. And I am working on branch B. Can I unshelve his changes into branch B? (By GUI or command prompt) | The Visual Studio Power Tools should let you do this. C:\src\2\Merlin\Main>tfpt unshelve /?tfpt unshelve - Unshelve into workspace with pending changesAllows a shelveset to be unshelved into a workspace with pending changes.Merges content between local and shelved changes. Allows migration of shelvedchanges from one branch into another by rewriting server paths.Usage: tfpt unshelve [shelvesetname[;username]] [/nobackup] [/migrate /source:serverpath /target:serverpath] shelvesetname The name of the shelveset to unshelve /nobackup Skip the creation of a backup shelveset /migrate Rewrite the server paths of the shelved items (for example to unshelve into another branch) /source:serverpath Source location for path rewrite (supply with /migrate) /target:serverpath Target location for path rewrite (supply with /migrate) /nobackup Skip the creation of a backup shelveset For example to merge a shelve set called "Shelve Set Name" created on Branch1 to Branch2 use this: >tfpt unshelve "Shelve Set Name";domain\userName /migrate /source:"$/Project/Branch1/" /target:"$/Project/Branch2/" | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/117337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11374/"
]
} |
117,347 | I'm using Express currently. What extra features do I get with the full edition? | There are no differences in Management Studio. The differences are in the database engine LIMITATIONS! The engine is the same but it will deny you some features. Import/Export wizard in the express edition can be found at:C:\Program Files\Microsoft SQL Server\90\DTS\Binn\DTSWizard.exe If you dont have it, dowload it from Microsoft: http://go.microsoft.com/fwlink/?LinkId=65111 You could install the Microsoft SQL Server 2005 Express Edition Toolkit to get the cool toys, like the Import/Export wizard and the reports. The profiler is not part of Management Studio. It is one more application that comes with the full version of the SQL Server. Even if you have it installed your express edition server engine will refuse to work with it. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/117347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13578/"
]
} |
117,355 | I'm trying to find the most reusable, yet elegant, piece of code possible for determining if an IEnumerable. In the ideal, this should be a function I can call absolutely any time I need to tell if an IEnumerable is empty. While I have developed an answer for .NET 3.5 that has worked well for me so far, my current thought is that there is no perfect answer, since an IEnumerable can technically encapsulate a collection (or queue of iterators) that modifies the underlying results as it iterates, which would cause problems. However, this would also be an impediment to implementing IEnumerable.Count(), and that didn't stop MS from providing it. So I thought I'd put it to SO to see if someone has a better one, and in case someone else should find it useful. Edit: Wow, I can't believe I didn't know about IEnumerable.Any. I knew it existed, but never bothered to check what it did. Let this be a lesson. Read the documentation. Just because a method name doesn't imply it does what you want, doesn't mean it doesn't do what you want. | !enumerable.Any() Will attempt to grab the first element only. To expand on how/why this works, any determines if any of the components of an IEnumerable match a given function, if none is given, then any component will succeed, meaning the function will return true if an element exists in the enumerable. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/117355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2729/"
]
} |
117,407 | You can use App.config; but it only supports key/value pairs. You can use .Net configuration, configuration sections; but it can be really complex. You can use Xml Serialization/Deserialization by yourself; your classes-your way. You can use some other method; what can they be? ... Which of these or other methods (if there are) do you prefer? Why? | When key value pairs are not enough I use Configuration Sections as they are not complex to use (unless you need a complex section): Define your custom section: public class CustomSection : ConfigurationSection { [ConfigurationProperty("LastName", IsRequired = true, DefaultValue = "TEST")] public String LastName { get { return (String)base["LastName"]; } set { base["LastName"] = value; } } [ConfigurationProperty("FirstName", IsRequired = true, DefaultValue = "TEST")] public String FirstName { get { return (String)base["FirstName"]; } set { base["FirstName"] = value; } } public CustomSection() { } } Programmatically create your section (if it doesn't already exist): // Create a custom section. static void CreateSection() { try { CustomSection customSection; // Get the current configuration file. System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(@"ConfigurationTest.exe"); // Create the section entry // in the <configSections> and the // related target section in <configuration>. if (config.Sections["CustomSection"] == null) { customSection = new CustomSection(); config.Sections.Add("CustomSection", customSection); customSection.SectionInformation.ForceSave = true; config.Save(ConfigurationSaveMode.Full); } } catch (ConfigurationErrorsException err) { //manage exception - give feedback or whatever } } Following CustomSection definition and actual CustomSection will be created for you: <?xml version="1.0" encoding="utf-8" ?><configuration> <configSections> <section name="CustomSection" type="ConfigurationTest.CustomSection, ConfigurationTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" allowLocation="true" allowDefinition="Everywhere" allowExeDefinition="MachineToApplication" overrideModeDefault="Allow" restartOnExternalChanges="true" requirePermission="true" /> </configSections> <CustomSection LastName="TEST" FirstName="TEST" /></configuration> Now Retrieve your section properties: CustomSection section = (CustomSection)ConfigurationManager.GetSection("CustomSection"); string lastName = section.LastName; string firstName = section.FirstName; | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/117407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11374/"
]
} |
117,422 | My Virtual Machine's clock drifts pretty significantly. There's documentation out there about dealing with this, but nothing seems to be working very well. Anyone have any suggestions, things that worked well for them, ... Supposedly updating regularly via ntp is not a good solution. | vmware have a really good PDF doc on this problem. Basically, the host will slew the ticks delivered to your guests as it can. Don't run NTP or timed or junk like that. Just install vmware-guestd and let the host slew your ticks. If you still lose ticks, then any other solution will have major drift too. If you can, use a guest OS that has a low frequency tick rate. Newer versions of Linux come with 1000Hz ticks, but it used only to be 100Hz. That seems easier for the host to deliver. A kernel rebuild is usually needed to change the HZ value. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/117422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20498/"
]
} |
117,426 | I am working on a project that has grown to a decent size, and I am the only developer. We currently don't use any version control, but I definitely need to start. I want to use Subversion. What would be the best way to transfer an existing project to it? I have a test server that I use for developing new features, then transfer those files to the 2 production servers. Is there a tool that will automate the upload to the test, then the deployment to the live servers? All this is developed in ASP.NET using Visual Studio (if that matters) | To expand a little on the previous answer... 1) Create a new SVN repository 2) Commit all the code you've worked on so far to it 3) Check all that code OUT again, to create a working copy on your dev machine 4) Work! It's definitely not a hurdle, really. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/117426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18234/"
]
} |
117,469 | Could anyone recommend a good BAML Decompiler / Viewer besides BAML Viewer plugin for Reflector, which doesn't handle path geometry/data? | You might like to have another look at the BAML addin for reflector as it's been recently updated by Andrew Smith. Have a look at his at blog post you'll note that he has fixed the issue with path data. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/117469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19268/"
]
} |
117,508 | Like the title says, how do you create custom code snippets in Visual Studio 2008? | Here's a link to a utility for Creating/editing Snippets. It works for more languages than just VB despite the classification in the link. http://msdn.microsoft.com/en-us/vbasic/bb973770.aspx | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/117508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/299/"
]
} |
117,514 | How do I properly represent a different timezone in my timezone? The below example only works because I know that EDT is one hour ahead of me, so I can uncomment the subtraction of myTimeZone() import datetime, refrom datetime import tzinfoclass myTimeZone(tzinfo): """docstring for myTimeZone""" def utfoffset(self, dt): return timedelta(hours=1)def myDateHandler(aDateString): """u'Sat, 6 Sep 2008 21:16:33 EDT'""" _my_date_pattern = re.compile(r'\w+\,\s+(\d+)\s+(\w+)\s+(\d+)\s+(\d+)\:(\d+)\:(\d+)') day, month, year, hour, minute, second = _my_date_pattern.search(aDateString).groups() month = [ 'JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC' ].index(month.upper()) + 1 dt = datetime.datetime( int(year), int(month), int(day), int(hour), int(minute), int(second) ) # dt = dt - datetime.timedelta(hours=1) # dt = dt - dt.tzinfo.utfoffset(myTimeZone()) return (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, 0, 0, 0)def main(): print myDateHandler("Sat, 6 Sep 2008 21:16:33 EDT")if __name__ == '__main__': main() | I recommend babel and pytz when working with timezones. Keep your internal datetime objects naive and in UTC and convert to your timezone for formatting only. The reason why you probably want naive objects (objects without timezone information) is that many libraries and database adapters have no idea about timezones. Babel pytz | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/117514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9338/"
]
} |
117,551 | My website makes a lot of requests. I often need to cancel all current requests, so that the browser is not blocking relevant new requests. I have 3 kinds of requests: Ajax inserted script-tags (which do JSONP-Communication) inserted image-tags (which cause the browser to request data from various servers) For Ajax its no problem as the XMLHttpRequest object supports canceling.What I need is a way to make any browser stop loading resources, from DOM-Objects. Looks like simply removing an object (eg. an image-tag) from the DOM only helps avoiding an request, if the request is not already running. UPDATE: a way to cancel all requests, which are irrelevant, instead of really any request would be perfect. | window.stop() should cancel any pending image or script requests. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/117551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20711/"
]
} |
117,598 | Is there a tool to integrate Mercurial into Visual Studio? I am just curious. Mercurial is pretty nice, even with 'just' TortoiseHG , but integration with Visual Studio would be better. | VisualHG Way to go, me. (Found the answer myself afterwards. Oh well, someone might find this useful.) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/117598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2145/"
]
} |
117,623 | Backstory: I'm using log4net to handle all logging for a project I'm working on. One particular method can be called under several different circumstances -- some that warrant the log messages to be errors and others that warrant the log messages to be warnings. So, as an example, how could I turn Public Sub CheckDifference(ByVal A As Integer, ByVal B As Integer) If (B - A) > 5 Then log.ErrorFormat("Difference ({0}) is outside of acceptable range.", (B - A)) End IfEnd Sub Into something more along the lines of: Public Sub CheckDifference(ByVal A As Integer, ByVal B As Integer, "Some delegate info here") If (B - A) > 5 Then **delegateinfo**.Invoke("Difference ({0}) is outside of acceptable range.", (B - A)) End IfEnd Sub So that I could call it and pass either log.ErrorFormat or log.WarnFormat as the delegate? I'm using VB.NET with VS 2008 and .NET 3.5 SP1. Also, I'm fairly new to delegates in general, so if this question should be worded differently to remove any ambiguities, let me know. EDIT: Also, how could I initialize the delegate to either the ErrorFormat or the WarnFormat in the class constructor? Would it be as easy as myDelegate = log.ErrorFormat ? I would imagine there is more to it than that (pardon my ignorance on the subject -- delegates are really something I want to learn more about, but so far they have eluded my understanding). | Declare your delegate signature: Public Delegate Sub Format(ByVal value As String) Define your Test function: Public Sub CheckDifference(ByVal A As Integer, _ ByVal B As Integer, _ ByVal format As Format) If (B - A) > 5 Then format.Invoke(String.Format( _ "Difference ({0}) is outside of acceptable range.", (B - A))) End IfEnd Sub Somewhere in your code call your Test function: CheckDifference(Foo, Bar, AddressOf log.WriteWarn) Or CheckDifference(Foo, Bar, AddressOf log.WriteError) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/117623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1108/"
]
} |
117,665 | I got this bad feeling about how I insert larger amounts of HTML.Lets assume we got: var html="<table>..<a-lot-of-other-tags />..</table>" and I want to put this into $("#mydiv") previously I did something like var html_obj = $(html); $("#mydiv").append(html_obj); Is it correct that jQuery is parsing html to create DOM-Objects ? Well this is what I read somewhere (UPDATE: I meant that I have read, jQuery parses the html to create the whole DOM tree by hand - its nonsense right?! ) , so I changed my code: $("#mydiv").attr("innerHTML", $("#mydiv").attr("innerHTML") + html); Feels faster, is it ? And is it correct that this is equivalent to: document.getElementById("mydiv").innerHTML += html ? or is jquery doing some additional expensive stuff in the background ? Would love to learn alternatives as well. | innerHTML is remarkably fast, and in many cases you will get the best results just setting that (I would just use append). However, if there is much already in "mydiv" then you are forcing the browser to parse and render all of that content again (everything that was there before, plus all of your new content). You can avoid this by appending a document fragment onto "mydiv" instead: var frag = document.createDocumentFragment();frag.innerHTML = html;$("#mydiv").append(frag); In this way, only your new content gets parsed (unavoidable) and the existing content does not. EDIT: My bad... I've discovered that innerHTML isn't well supported on document fragments. You can use the same technique with any node type. For your example, you could create the root table node and insert the innerHTML into that: var frag = document.createElement('table');frag.innerHTML = tableInnerHtml;$("#mydiv").append(frag); | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/117665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20711/"
]
} |
117,690 | I have few asynchronous tasks running and I need to wait until at least one of them is finished (in the future probably I'll need to wait util M out of N tasks are finished).Currently they are presented as Future, so I need something like /** * Blocks current thread until one of specified futures is done and returns it. */public static <T> Future<T> waitForAny(Collection<Future<T>> futures) throws AllFuturesFailedException Is there anything like this? Or anything similar, not necessary for Future. Currently I loop through collection of futures, check if one is finished, then sleep for some time and check again. This looks like not the best solution, because if I sleep for long period then unwanted delay is added, if I sleep for short period then it can affect performance. I could try using new CountDownLatch(1) and decrease countdown when task is complete and do countdown.await() , but I found it possible only if I control Future creation. It is possible, but requires system redesign, because currently logic of tasks creation (sending Callable to ExecutorService) is separated from decision to wait for which Future. I could also override <T> RunnableFuture<T> AbstractExecutorService.newTaskFor(Callable<T> callable) and create custom implementation of RunnableFuture with ability to attach listener to be notified when task is finished, then attach such listener to needed tasks and use CountDownLatch, but that means I have to override newTaskFor for every ExecutorService I use - and potentially there will be implementation which do not extend AbstractExecutorService. I could also try wrapping given ExecutorService for same purpose, but then I have to decorate all methods producing Futures. All these solutions may work but seem very unnatural. It looks like I'm missing something simple, like WaitHandle.WaitAny(WaitHandle[] waitHandles) in c#. Are there any well known solutions for such kind of problem? UPDATE: Originally I did not have access to Future creation at all, so there were no elegant solution. After redesigning system I got access to Future creation and was able to add countDownLatch.countdown() to execution process, then I can countDownLatch.await() and everything works fine.Thanks for other answers, I did not know about ExecutorCompletionService and it indeed can be helpful in similar tasks, but in this particular case it could not be used because some Futures are created without any executor - actual task is sent to another server via network, completes remotely and completion notification is received. | simple, check out ExecutorCompletionService . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/117690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5507/"
]
} |
117,691 | Given an array of integers, what is the simplest way to iterate over it and figure out all the ranges it covers? for example, for an array such as: $numbers = array(1,3,4,5,6,8,11,12,14,15,16); The ranges would be: 1,3-6,8,11-12,14-16 | If the array is sorted in ascending order, then the problem is easy. Define a Range structure or class, which has a beginning and an end. Then go through the array. If the current element is one more than the previous, update Range.end , otherwise create a new range with this element as Range.begin . Store the ranges to a dynamic array or a linked list. Or just print them out as you go. If the array may not be sorted, then sort it first. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/117691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10585/"
]
} |
117,751 | I have a web application using JPA and JTA with Spring. I would like to support both JBoss and Tomcat. When running on JBoss, I'd like to use JBoss' own TransactionManager, and when running on Tomcat, I'd like to use JOTM. I have both scenarios working, but I now find that I seem to need two separate Spring configurations for the two cases. With JOTM, I need to use Spring's JotmFactoryBean : <bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"> <property name="userTransaction"> <bean class="org.springframework.transaction.jta.JotmFactoryBean"/> </property></bean> In JBoss, though, I just need to fetch "TransactionManager" from JNDI: <bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"> <property name="transactionManager"> <bean class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="resourceRef" value="true" /> <property name="jndiName" value="TransactionManager" /> <property name="expectedType" value="javax.transaction.TransactionManager" /> </bean> </property></bean> Is there a way to configure this so that the appropriate TransactionManager - JBoss or JOTM - is used, without the need for two different configuration files? | I think you have missed the point of JNDI. JNDI was pretty much written to solve the problem you have! I think you can take it up a level, so instead of using the "userTransaction" or "transactionManager from JNDI" depending on your situation. Why not add the "JtaTransactionManager" to JNDI. That way you push the configuration to the JNDI where it is supposed to be instead of creating even more configuration files [ like there aren't enough already ;) ]. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/117751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7034/"
]
} |
117,774 | I've recently inherited the job of maintaining a database that wasn't designed very well and the designers aren't available to ask any questions. And I have a couple more coming my way in the near future. It's been tough trying to figure out the relationships between the tables without any kind of visual aid or database diagram. I was wondering what tools are recommended for this. I know about Visio, but I was hoping there were some good open source/freeware applications out there. I don't need it to change the database at all. Just read it and create some kind of visual aid to help me understand how things are laid out and try to figure out what the designer was thinking about how the data should relate. Additional answer data: SchemaSpy was the kind of thing I was looking for, but having not done a lot with the command line in ages, I opted to use SchemaSpyGUI . There was also some configuration to get used to since I don't work with Java much, but the end result was what I was looking for (on open-source replacement for Visio's ER diagrams). | Try SchemaSpy . I ran it against a rather complex database and I was quite pleased by the result, with advice on optimization. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/117774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3442/"
]
} |
117,800 | For our Django App, we'd like to get an AutoField to start at a number other than 1. There doesn't seem to be an obvious way to do this. Any ideas? | Like the others have said, this would be much easier to do on the database side than the Django side. For Postgres, it'd be like so : ALTER SEQUENCE sequence_name RESTART WITH 12345; Look at your own DB engine's docs for how you'd do it there. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/117800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9845/"
]
} |
117,810 | My ASP.NET MVC application will take a lot of bandwidth and storage space. How can I setup an ASP.NET upload page so the file the user uploaded will go straight to Amazon S3 without using my web server's storage and bandwidth? | Update Feb 2016: The AWS SDK can handle a lot more of this now. Check out how to build the form , and how to build the signature . That should prevent you from needing the bandwidth on your end, assuming you need to do no processing of the content yourself before sending it to S3. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/117810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20067/"
]
} |
117,812 | Anybody have any good FizzBuzz type questions that are not the FizzBuzz problem? I am interviewing someone and FB is relatively well known and not that hard to memorize, so my first stop in a search for ideas is my new addiction SO. | I've seen a small list of relatively simple programming problems used to weed out candidates, just like FizzBuzz. Here are some of the problems I've seen, in order of increasing difficulty: Reverse a string Reverse a sentence ("bob likes dogs" -> "dogs likes bob") Find the minimum value in a list Find the maximum value in a list Calculate a remainder (given a numerator and denominator) Return distinct values from a list including duplicates (i.e. "1 3 5 3 7 3 1 1 5" -> "1 3 5 7") Return distinct values and their counts (i.e. the list above becomes "1(3) 3(3) 5(2) 7(1)") Given a string of expressions (only variables, +, and -) and a set of variable/value pairs (i.e. a=1, b=7, c=3, d=14) return the result of the expression ("a + b+c -d" would be -3). These were for Java, and you could use the standard libraries so some of them can be extremely easy (like 6). But they work like FizzBuzz. If you have a clue about programming you should be able to do most pretty quickly. Even if you don't know the language well you should at least be able to give the idea behind how to do something. Using this test one of my previous bosses saw everything from people who aced it all pretty quick, to people who could do most pretty quick, to one guy who couldn't answer a single one after a half hour. I should also note: he let people use his computer while they were given these tasks. They were specifically instructed that they could use Google and the like. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/117812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3683/"
]
} |
117,844 | I'm trying to convert an incoming sting of 1s and 0s from stdin into their respective binary values (where a string such as "11110111" would be converted to 0xF7). This seems pretty trivial but I don't want to reinvent the wheel so I'm wondering if there's anything in the C/C++ standard libs that can already perform such an operation? | #include <stdio.h>#include <stdlib.h>int main(void) { char * ptr; long parsed = strtol("11110111", & ptr, 2); printf("%lX\n", parsed); return EXIT_SUCCESS;} For larger numbers, there as a long long version, strtoll . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/117844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1582/"
]
} |
117,864 | I'm a total newbie, but I was writing a little program that worked on strings in C# and I noticed that if I did a few things differently, the code executed significantly faster. So it had me wondering, how do you go about clocking your code's execution speed? Are there any (free)utilities? Do you go about it the old-fashioned way with a System.Timer and do it yourself? | What you are describing is known as performance profiling. There are many programs you can get to do this such as Jetbrains profiler or Ants profiler , although most will slow down your application whilst in the process of measuring its performance. To hand-roll your own performance profiling, you can use System.Diagnostics.Stopwatch and a simple Console.WriteLine, like you described. Also keep in mind that the C# JIT compiler optimizes code depending on the type and frequency it is called, so play around with loops of differing sizes and methods such as recursive calls to get a feel of what works best. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/117864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10288/"
]
} |
117,952 | I have two tables containing Tasks and Notes, and want to retrieve a list of tasks with the number of associated notes for each one. These two queries do the job: select t.TaskId, (select count(n.TaskNoteId) from TaskNote n where n.TaskId = t.TaskId) 'Notes'from Task t-- orselect t.TaskId, count(n.TaskNoteId) 'Notes'from Task tleft join TaskNote non t.TaskId = n.TaskIdgroup by t.TaskId Is there a difference between them and should I be using one over the other, or are they just two ways of doing the same job? Thanks. | On small datasets they are wash when it comes to performance. When indexed, the LOJ is a little better. I've found on large datasets that an inner join (an inner join will work too.) will outperform the subquery by a very large factor (sorry, no numbers). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/117952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14072/"
]
} |
117,962 | I have two tables, both with start time and end time fields. I need to find, for each row in the first table, all of the rows in the second table where the time intervals intersect. For example: <-----row 1 interval-------><---find this--> <--and this--> <--and this--> Please phrase your answer in the form of a SQL WHERE -clause, AND consider the case where the end time in the second table may be NULL . Target platform is SQL Server 2005, but solutions from other platforms may be of interest also. | SELECT * FROM table1,table2 WHERE table2.start <= table1.end AND (table2.end IS NULL OR table2.end >= table1.start) | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/117962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9345/"
]
} |
118,068 | Systems demand that certain primitives be aligned to certain points within the memory (ints to bytes that are multiples of 4, shorts to bytes that are multiples of 2, etc.). Of course, these can be optimized to waste the least space in padding. My question is why doesn't GCC do this automatically? Is the more obvious heuristic (order variables from biggest size requirement to smallest) lacking in some way? Is some code dependent on the physical ordering of its structs (is that a good idea)? I'm only asking because GCC is super optimized in a lot of ways but not in this one, and I'm thinking there must be some relatively cool explanation (to which I am oblivious). | gcc does not reorder the elements of a struct, because that would violate the C standard. Section 6.7.2.1 of the C99 standard states: Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/118068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10307/"
]
} |
118,073 | At a previous place where I worked a colleague figured out how to configure MediaWiki so that, for example, a string like #12345 in the wiki markup could be expanded into a hypertext link to ticket 12345 in the ticket system. I would like to do something similar in TWiki. I have not yet figured out how, though. So, if I do, I'll try and answer this question, then. :) -danny | gcc does not reorder the elements of a struct, because that would violate the C standard. Section 6.7.2.1 of the C99 standard states: Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/118073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
118,096 | I need to be able to take a string like: '''foo, bar, "one, two", three four''' into: ['foo', 'bar', 'one, two', 'three four'] I have an feeling (with hints from #python) that the solution is going to involve the shlex module. | The shlex module solution allows escaped quotes, one quote escape another, and all fancy stuff shell supports. >>> import shlex>>> my_splitter = shlex.shlex('''foo, bar, "one, two", three four''', posix=True)>>> my_splitter.whitespace += ','>>> my_splitter.whitespace_split = True>>> print list(my_splitter)['foo', 'bar', 'one, two', 'three', 'four'] escaped quotes example: >>> my_splitter = shlex.shlex('''"test, a",'foo,bar",baz',bar \xc3\xa4 baz''', posix=True) >>> my_splitter.whitespace = ',' ; my_splitter.whitespace_split = True >>> print list(my_splitter)['test, a', 'foo,bar",baz', 'bar \xc3\xa4 baz'] | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/118096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18866/"
]
} |
118,100 | do you use a tool? or just manually make them? | Google charts api/server can make one fairly easily You specify everything in the URL so it's easy to update: http://chart.apis.google.com/chart?chs=600x250& // the size of the chartchtt=Burndown& // Titlecht=lc& // The chart type - "lc" means a line chart that only needs Y valueschdl=estimated|actual& // The two legendschco=FF0000,00FF00& // The colours in hex of the two lineschxr=0,0,30,2|1,0,40,2& // The data range for the x,y (index,min,max,interval)chds=0,40 // The min and max values for the data. i.e. amount of featureschd=t:40,36,32,28,24,20,16,12,8,4,0|40,39,38,37,36,35,30,25,23,21,18,14,12,9,1 // Data The URL above plots in intervals of 2 - so work every 2 days. You'll need a bigger size chart for every day. To do this make the data have 30 values for estimated and actual, and change the "chxr" so the interval is 1, not two. You can plot only the days done more clearly with the "lxy" chart type (the first image). This needs you to enter the X data values too (so a vector). Use -1 for unknown. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/118100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10431/"
]
} |
118,130 | I'm using Windows Vista and C#.net 3.5, but I had my friend run the program on XP and has the same problem. So I have a C# program that I have running in the background with an icon in the SystemTray. I have a low level keyboard hook so when I press two keys (Ctr+windows in this case) it'll pull of the application's main form. The form is set to be full screen in the combo key press even handler: this.FormBorderStyle = FormBorderStyle.None;this.WindowState = FormWindowState.Maximized; So it basically works. When I hit CTR+Windows it brings up the form, no matter what program I have given focus to. But sometimes, the taskbar will still show up over the form, which I don't want. I want it to always be full screen when I hit that key combo. I figure it has something to do with what application has focus originally. But even when I click on my main form, the taskbar sometimes stays there. So I wonder if focus really is the problem. It just seems like sometimes the taskbar is being stubborn and doesn't want to sit behind my program. Anyone have any ideas how I can fix this? EDIT: More details-I'm trying to achieve the same effect that a web browser has when you put it into fullscreen mode, or when you put powerpoint into presentation mode. In a windows form you do that by putting the border style to none and maximizing the window. But sometimes the window won't cover the taskbar for some reason. Half the time it will. If I have the main window topmost, the others will fall behind it when I click on it, which I don't want if the taskbar is hidden. | Try this (where this is your form): this.Bounds = Screen.PrimaryScreen.Bounds;this.TopMost = true; That'll set the form to fullscreen, and it'll cover the taskbar. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/118130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13713/"
]
} |
118,141 | I understand that Parrot is a virtual machine, but I feel like I'm not completely grasping the idea behind it. As I understand, it's a virtual machine that's being made to handle multiple languages. Is this correct? What are the advantages of using a virtual machine instead of just an interpreter? What specifically is Parrot doing that makes it such a big deal? | Parrot is a virtual machine specifically designed to handle several languages, especially the dynamic languages. Despite some of the interesting technology involved, since it can handle more than one language, it will be able to cross language boundaries. For instance, once it can compile Ruby, Perl, and Python, it should be easy to cross those boundaries to let me use a Ruby library in Python, a Perl library from Python, so whatever combination that I like. Parrot started in the Perl world and many of the people working on it are experienced Perl people. Instead of using the current Perl interpreter, which is showing its age, Parrot allows Perl to have features such as distributable pre-compiled modules (which everyone else has had for a long time) and a smarter garbage collector. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/118141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20805/"
]
} |
118,144 | What's the most efficient way to select the last n number of rows in a table using mySQL? The table contains millions of rows, and at any given time I don't know how large the table is (it is constantly growing). The table does have a column that is automatically incremented and used as a unique identifier for each row. | SELECT * FROM table_name ORDER BY auto_incremented_id DESC LIMIT n | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/118144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9076/"
]
} |
118,190 | I have a SQL script that creates a package with a comment containing an ampersand (&). When I run the script from SQL Plus, I am prompted to enter a substitute value for the string starting with &. How do I disable this feature so that SQL Plus ignores the ampersand? | This may work for you: set define off Otherwise the ampersand needs to be at the end of a string, 'StackOverflow &' || ' you' EDIT: I was click-happy when saving... This was referenced from a blog . | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/118190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20625/"
]
} |
118,199 | I have an application where 2 threads are running... Is there any certanty that when I change a global variable from one thread, the other will notice this change? I don't have any syncronization or Mutual exclusion system in place... but should this code work all the time (imagine a global bool named dataUpdated ): Thread 1: while(1) { if (dataUpdated) updateScreen(); doSomethingElse();} Thread 2: while(1) { if (doSomething()) dataUpdated = TRUE;} Does a compiler like gcc optimize this code in a way that it doesn't check for the global value, only considering it value at compile time (because it nevers get changed at the same thred)? PS: Being this for a game-like application, it really doen't matter if there will be a read while the value is being written... all that matters is that the change gets noticed by the other thread. | Yes. No. Maybe. First, as others have mentioned you need to make dataUpdated volatile; otherwise the compiler may be free to lift reading it out of the loop (depending on whether or not it can see that doSomethingElse doesn't touch it). Secondly, depending on your processor and ordering needs, you may need memory barriers. volatile is enough to guarentee that the other processor will see the change eventually, but not enough to guarentee that the changes will be seen in the order they were performed. Your example only has one flag, so it doesn't really show this phenomena. If you need and use memory barriers, you should no longer need volatile Volatile considered harmful and Linux Kernel Memory Barriers are good background on the underlying issues; I don't really know of anything similar written specifically for threading. Thankfully threads don't raise these concerns nearly as often as hardware peripherals do, though the sort of case you describe (a flag indicating completion, with other data presumed to be valid if the flag is set) is exactly the sort of thing where ordering matterns... | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/118199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2731698/"
]
} |
118,205 | At work, we have a windows server 2003 with IIS and Subversion installed. We use it to publish and test locally our ASP.NET websites. Every programmer has Tortoise installed on his PC and can update/commit content to the server. Hosting the repositories is working fine.But the files kept in those repositories needs then to be copied to our local IIS (virtual directories). What is an easy way to publish those subversion repositories to our local IIS? Edit: Thanks to puetzk I added a simple bat file that gets executed every time a commit occurs (check the subversion documentation about hooks). My bat file only contains: echo offsetlocal:: Localize the working copy where IIS points)pushd E:\wwwroot\yourapp\trunk:: Update your working copysvn updateendlocalexit | Just keep the web server's file area as a working copy, and perform an svn up in it whenever you want to "publish". Configure it to hide the contents of the .svn folders if they seem untidy to you (I don't specifically know how to do this, but I assume it can be done). They will already have the filesystem hidden bit, which may take care of this. If you want it really automatic (updates as soon as someone commits), use a post-commit hook script on the SVN server to kick off the first process. Others in the comments have suggested using export instead of checkout. That can work too, and avoids the .svn clutter, but has two drawbacks. One, it has to redownload the entire contents every time, not just the modified files (since it didn't keep the .svn dir to remember what it has). If you have a lot of files, this will be much slower. Two, update replaces the file atomically (writes the new version in .svn/tmp, then moves it into place). Export writes the file gradually into it's destination as it downloads. That means export could deliver an incomplete file to someone who browsed it at just the wrong time. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/118205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/296/"
]
} |
118,241 | I'd like to use JavaScript to calculate the width of a string. Is this possible without having to use a monospace typeface? If it's not built-in, my only idea is to create a table of widths for each character, but this is pretty unreasonable especially supporting Unicode and different type sizes (and all browsers for that matter). | Create a DIV styled with the following styles. In your JavaScript, set the font size and attributes that you are trying to measure, put your string in the DIV, then read the current width and height of the DIV. It will stretch to fit the contents and the size will be within a few pixels of the string rendered size. var fontSize = 12;var test = document.getElementById("Test");test.style.fontSize = fontSize;var height = (test.clientHeight + 1) + "px";var width = (test.clientWidth + 1) + "px"console.log(height, width); #Test{ position: absolute; visibility: hidden; height: auto; width: auto; white-space: nowrap; /* Thanks to Herb Caudill comment */} <div id="Test"> abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</div> | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/118241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8119/"
]
} |
118,243 | How can I open multiple Eclipse workspaces at the same time on the Mac? On other platforms, I can just launch extra Eclipse instances, but the Mac will not let me open the same application twice. Is there a better way than keeping two copies of Eclipse? | EDIT: Milhous's answer seems to be the officially supported way to do this as of 10.5. Earlier version of OS X and even 10.5 and up should still work using the following instructions though. Open the command line (Terminal) Navigate to your Eclipse installation folder, for instance: cd /Applications/eclipse/ cd /Developer/Eclipse/Eclipse.app/Contents/MacOS/eclipse cd /Applications/eclipse/Eclipse.app/Contents/MacOS/eclipse cd /Users/<usernamehere>/eclipse/jee-neon/Eclipse.app/Contents/MacOS Launch Eclipse: ./eclipse & This last command will launch eclipse and immediately background the process. Rinse and repeat to open as many unique instances of Eclipse as you want. Warning You might have to change the Tomcat server ports in order to run your project in different/multiple Tomcat instances , see Tomcat Server Error - Port 8080 already in use | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/118243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14955/"
]
} |
118,260 | I'm trying to teach Komodo to fire up IDLE when I hit the right keystrokes. I can use the exact path of the shortcut in start menu in the Windows Explorer location bar to launch IDLE so I was hoping Komodo would be able to use it as well. But, giving this path to Komodo causes it to say that 1 is returned. This appears to be a failure as IDLE doesn't start up. I thought I'd avoid the shortcut and just use the exact path. I go to the start menu, find the shortcut for IDLE, right click to look at the properties. The target is grayed out, but says "Python 2.5.2". The "Start in" is set to, "C:\Python25\". The "Open File Location" button is also grayed out. How do I find out where this shortcut is really pointing? I have tried starting python.exe and pythonw.exe both in C:\Python25, but neither starts up IDLE. | There's a file called idle.py in your Python installation directory in Lib\idlelib\idle.py . If you run that file with Python, then IDLE should start. c:\Python25\pythonw.exe c:\Python25\Lib\idlelib\idle.py | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/118260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5113/"
]
} |
118,289 | I have a string with possible command line arguments (using an Read-Eval-Print-Loop program) and I want it to be parsed similar to the command line arguments when passed to Getopt::Long. To elaborate: I have a string $str = '--infile /tmp/infile_location --outfile /tmp/outfile' I want it to be parsed by GetOptions so that it is easier for me to add new options. One workaround I could think of is to split the string on whitespace and replace @ARGV with new array and then call GetOptions. something like ... my @arg_arr = split (/\s/, $input_line);# This is done so that GetOptions reads these new arguments@ARGV = @arg_arr;print "ARGV is : @ARGV\n";GetOptions ( 'infile=s' => \$infile, 'outfile=s' => \$outfile ); Is there any good/better way? | Check out the section parsing options from an arbitrary string in the man page for Getopt::Long , I think it does exactly what you're looking for. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/118289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4406/"
]
} |
118,292 | So I was writing some code today that basically looks like this: string returnString = s.Replace("!", " ") .Replace("@", " ") .Replace("#", " ") .Replace("$", " ") .Replace("%", " ") .Replace("^", " ") .Replace("*", " ") .Replace("_", " ") .Replace("+", " ") .Replace("=", " ") .Replace("\", " ") Which isn't really nice. I was wondering if there's a regex or something that I could write that would replace all the calls to the Replace() function? | You can use Regex.Replace() . All of the characters can be placed between square brackets, which matches any character between the square brackets. Some special characters have to be escaped with backslashes, and I use a @verbatim string here, so I don't have to double-escape them for the C# compiler. The first parameter is the input string and the last parameter is the replacement string. var returnString = Regex.Replace(s,@"[!@#\$%\^*_\+=\\]"," "); | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/118292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
]
} |
118,307 | Tools like 'ps' and 'top' report various kinds of memory usages, such as the VM size and the Resident Set Size. However, none of those are the "real" memory usage: Program code is shared between multiple instances of the same program. Shared library program code is shared between all processes that use that library. Some apps fork off processes and share memory with them (e.g. via shared memory segments). The virtual memory system makes the VM size report pretty much useless. RSS is 0 when a process is swapped out, making it not very useful. Etc etc. I've found that the private dirty RSS, as reported by Linux, is the closest thing to the "real" memory usage. This can be obtained by summing all Private_Dirty values in /proc/somepid/smaps . However, do other operating systems provide similar functionality? If not, what are the alternatives? In particular, I'm interested in FreeBSD and OS X. | On OSX the Activity Monitor gives you actually a very good guess. Private memory is for sure memory that is only used by your application. E.g. stack memory and all memory dynamically reserved using malloc() and comparable functions/methods (alloc method for Objective-C) is private memory. If you fork, private memory will be shared with you child, but marked copy-on-write. That means as long as a page is not modified by either process (parent or child) it is shared between them. As soon as either process modifies any page, this page is copied before it is modified. Even while this memory is shared with fork children (and it can only be shared with fork children), it is still shown as "private" memory, because in the worst case, every page of it will get modified (sooner or later) and then it is again private to each process again. Shared memory is either memory that is currently shared (the same pages are visible in the virtual process space of different processes) or that is likely to become shared in the future (e.g. read-only memory, since there is no reason for not sharing read-only memory). At least that's how I read the source code of some command line tools from Apple. So if you share memory between processes using mmap (or a comparable call that maps the same memory into multiple processes), this would be shared memory. However the executable code itself is also shared memory, since if another instance of your application is started there is no reason why it may not share the code already loaded in memory (executable code pages are read-only by default, unless you are running your app in a debugger). Thus shared memory is really memory used by your application, just like private one, but it might additionally be shared with another process (or it might not, but why would it not count towards your application if it was shared?) Real memory is the amount of RAM currently "assigned" to your process, no matter if private or shared. This can be exactly the sum of private and shared, but usually it is not. Your process might have more memory assigned to it than it currently needs (this speeds up requests for more memory in the future), but that is no loss to the system. If another process needs memory and no free memory is available, before the system starts swapping, it will take that extra memory away from your process and assign it another process (which is a fast and painless operation); therefor your next malloc call might be somewhat slower. Real memory can also be smaller than private and physical memory; this is because if your process requests memory from the system, it will only receive "virtual memory". This virtual memory is not linked to any real memory pages as long as you don't use it (so malloc 10 MB of memory, use only one byte of it, your process will get only a single page, 4096 byte, of memory assigned - the rest is only assigned if you actually ever need it). Further memory that is swapped may not count towards real memory either (not sure about this), but it will count towards shared and private memory. Virtual memory is the sum of all address blocks that are consider valid in your apps process space. These addresses might be linked to physical memory (that is again private or shared), or they might not, but in that case they will be linked to physical memory as soon as you use the address. Accessing memory addresses outside of the known addresses will cause a SIGBUS and your app will crash. When memory is swapped, the virtual address space for this memory remains valid and accessing those addresses causes memory to be swapped back in. Conclusion: If your app does not explicitly or implicitly use shared memory, private memory is the amount of memory your app needs because of the stack size (or sizes if multithreaded) and because of the malloc() calls you made for dynamic memory. You don't have to care a lot for shared or real memory in that case. If your app uses shared memory, and this includes a graphical UI, where memory is shared between your application and the WindowServer for example, then you might have a look at shared memory as well. A very high shared memory number may mean you have too many graphical resources loaded in memory at the moment. Real memory is of little interest for app development. If it is bigger than the sum of shared and private, then this means nothing other than that the system is lazy at taken memory away from your process. If it is smaller, then your process has requested more memory than it actually needed, which is not bad either, since as long as you don't use all of the requested memory, you are not "stealing" memory from the system. If it is much smaller than the sum of shared and private, you may only consider to request less memory where possible, as you are a bit over-requesting memory (again, this is not bad, but it tells me that your code is not optimized for minimal memory usage and if it is cross platform, other platforms may not have such a sophisticated memory handling, so you may prefer to alloc many small blocks instead of a few big ones for example, or free memory a lot sooner, and so on). If you are still not happy with all that information, you can get even more information. Open a terminal and run: sudo vmmap <pid> where is the process ID of your process. This will show you statistics for EVERY block of memory in your process space with start and end address. It will also tell you where this memory came from (A mapped file? Stack memory? Malloc'ed memory? A __DATA or __TEXT section of your executable?), how big it is in KB, the access rights and whether it is private, shared or copy-on-write. If it is mapped from a file, it will even give you the path to the file. If you want only "actual" RAM usage, use sudo vmmap -resident <pid> Now it will show for every memory block how big the memory block is virtually and how much of it is really currently present in physical memory. At the end of each dump is also an overview table with the sums of different memory types. This table looks like this for Firefox right now on my system: REGION TYPE [ VIRTUAL/RESIDENT]=========== [ =======/========]ATS (font support) [ 33.8M/ 2496K]CG backing stores [ 5588K/ 5460K]CG image [ 20K/ 20K]CG raster data [ 576K/ 576K]CG shared images [ 2572K/ 2404K]Carbon [ 1516K/ 1516K]CoreGraphics [ 8K/ 8K]IOKit [ 256.0M/ 0K]MALLOC [ 256.9M/ 247.2M]Memory tag=240 [ 4K/ 4K]Memory tag=242 [ 12K/ 12K]Memory tag=243 [ 8K/ 8K]Memory tag=249 [ 156K/ 76K]STACK GUARD [ 101.2M/ 9908K]Stack [ 14.0M/ 248K]VM_ALLOCATE [ 25.9M/ 25.6M]__DATA [ 6752K/ 3808K]__DATA/__OBJC [ 28K/ 28K]__IMAGE [ 1240K/ 112K]__IMPORT [ 104K/ 104K]__LINKEDIT [ 30.7M/ 3184K]__OBJC [ 1388K/ 1336K]__OBJC/__DATA [ 72K/ 72K]__PAGEZERO [ 4K/ 0K]__TEXT [ 108.6M/ 63.5M]__UNICODE [ 536K/ 512K]mapped file [ 118.8M/ 50.8M]shared memory [ 300K/ 276K]shared pmap [ 6396K/ 3120K] What does this tell us? E.g. the Firefox binary and all library it loads have 108 MB data together in their __TEXT sections, but currently only 63 MB of those are currently resident in memory. The font support (ATS) needs 33 MB, but only about 2.5 MB are really in memory. It uses a bit over 5 MB CG backing stores, CG = Core Graphics, those are most likely window contents, buttons, images and other data that is cached for fast drawing. It has requested 256 MB via malloc calls and currently 247 MB are really in mapped to memory pages. It has 14 MB space reserved for stacks, but only 248 KB stack space is really in use right now. vmmap also has a good summary above the table ReadOnly portion of Libraries: Total=139.3M resident=66.6M(48%) swapped_out_or_unallocated=72.7M(52%)Writable regions: Total=595.4M written=201.8M(34%) resident=283.1M(48%) swapped_out=0K(0%) unallocated=312.3M(52%) And this shows an interesting aspect of the OS X: For read only memory that comes from libraries, it plays no role if it is swapped out or simply unallocated; there is only resident and not resident. For writable memory this makes a difference (in my case 52% of all requested memory has never been used and is such unallocated, 0% of memory has been swapped out to disk). The reason for that is simple: Read-only memory from mapped files is not swapped. If the memory is needed by the system, the current pages are simply dropped from the process, as the memory is already "swapped". It consisted only of content mapped directly from files and this content can be remapped whenever needed, as the files are still there. That way this memory won't waste space in the swap file either. Only writable memory must first be swapped to file before it is dropped, as its content wasn't stored on disk before. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/118307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20816/"
]
} |
118,320 | I'm creating a login page. I want to create ASP.NET TextBox controls that have "Username" and "Password" as their Text, but as soon as they receive focus, these words should disappear and whatever the user types should appear, just like normal textbox. If the user leaves it blank and tabs to the next textbox, then these words appear again. This will eliminate the need for having separate labels in front of the text boxes. I would appreciate if someone can share their expertise for doing this. | Use the TextBox Watermark Extender that's in Microsoft's AJAX Toolkit. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/118320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20818/"
]
} |
118,341 | I have a Linq to objects statement var confirm = from l in lines.Lines where (l.LineNumber == startline.LineNumber) || (l.LineNumber == endline.LineNumber) select l; The confirm object is returning an 'Object Null or Not A Reference' at at System.Linq.Enumerable.WhereListIterator`1.MoveNext() If the result of the query was empty, it would just return an empty enumerator. I know for a fact that there are no null objects in the statement. Is it possible to step through the LINQ statement to see where it is falling over? EDIT When I said I know for a fact that there are no null objects it turns out I was lying :[, but the question remains, though I am asuming the answer will be 'you can't really' LINQPad is a good idea, I used it to teach myself LINQ, but I may start looking at it again as a debug / slash and burn style tool | I'm not sure if it's possible to debug from VS, but I find LINQPad to be quite useful. It'll let you dump the results of each part of the LINQ query. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/118341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
]
} |
118,370 | This came up in Hidden features of Python , but I can't see good documentation or examples that explain how the feature works. | Ellipsis , or ... is not a hidden feature, it's just a constant. It's quite different to, say, javascript ES6 where it's a part of the language syntax. No builtin class or Python language constuct makes use of it. So the syntax for it depends entirely on you, or someone else, having written code to understand it. Numpy uses it, as stated in the documentation . Some examples here . In your own class, you'd use it like this: >>> class TestEllipsis(object):... def __getitem__(self, item):... if item is Ellipsis:... return "Returning all items"... else:... return "return %r items" % item... >>> x = TestEllipsis()>>> print x[2]return 2 items>>> print x[...]Returning all items Of course, there is the python documentation , and language reference . But those aren't very helpful. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/118370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15677/"
]
} |
118,371 | When a class field is accessed via a getter method by multiple threads, how do you maintain thread safety? Is the synchronized keyword sufficient? Is this safe: public class SomeClass { private int val; public synchronized int getVal() { return val; } private void setVal(int val) { this.val = val; }} or does the setter introduce further complications? | If you use 'synchronized' on the setter here too, this code is threadsafe. However it may not be sufficiently granular; if you have 20 getters and setters and they're all synchronized, you may be creating a synchronization bottleneck. In this specific instance, with a single int variable, then eliminating the 'synchronized' and marking the int field 'volatile' will also ensure visibility (each thread will see the latest value of 'val' when calling the getter) but it may not be synchronized enough for your needs. For example, expecting int old = someThing.getVal(); if (old == 1) { someThing.setVal(2); } to set val to 2 if and only if it's already 1 is incorrect. For this you need an external lock, or some atomic compare-and-set method. I strongly suggest you read Java Concurrency In Practice by Brian Goetz et al , it has the best coverage of Java's concurrency constructs. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/118371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1119/"
]
} |
118,374 | For years, maybe 10, I've been fascinated with cryptography. I read a book about XOR bit-based encryption, and have been hooked ever since thing. I guess it's more fair to say that I'm fascinated by those who can break various encryption methods, but I digress. To the point -- what methods do you use when writing cryptography? Is obfuscation good in cryptography? I use two key-based XOR encryption, various hashing techniques (SHA1) on the keys, and simple things such as reversing strings here and there, etc. I'm interested to see what others think of and try when writing a not-so-out-of-the-box encryption method. Also -- any info on how the pros go about "breaking" various cryptography techniques would be interesting as well. To clarify -- I have no desire to use this in any production code, or any code of mine for that matter. I'm interesting in learning how it works through toying around, not reinventing the wheel. :) Ian | To contradict what everyone else has said so far, go for it! Yeah, your code might have buffer overflow vulnerabilities in it, and may be slow, buggy, etc, but you're doing this for FUN ! I completely understand the recreational enjoyment found in playing with crypto. That being said, cryptography isn't based on obfuscation at all (or at least shouldn't be). Good crypto will continue to work, even once Eve has slogged through your obfuscated code and completely understands what is going on. IE: Many newspapers have substitution code puzzles that readers try and break over breakfast. If they started doing things like reversing the whole string, yes, it'd be harder, but Joe Reader would still be able to break it, neve tuohtiw gnieb dlot. Good crypto is based on problems that are assumed to be (none proven yet, AFAIK) really difficult. Examples of this include factoring primes , finding the log , or really any other NP-complete problem. [Edit: snap, neither of those are proven NP-complete. They're all unproven, yet different. Hopefully you still see my point: crypto is based on one-way functions. Those are operations that are easy to do, but hard to undo. ie multiply two numbers vs find the prime factors of the product. Good catch tduehr ] More power to you for playing around with a really cool branch of mathematics, just remember that crypto is based on things that are hard, not complicated. Many crypto algorithms, once you really understand them, are mindbogglingly simple, but still work because they're based on something that is hard, not just switching letters around. Note: With this being said, some algorithms do add in extra quirks (like string seversal) to make brute forcing them that much more difficult. A part of me feels like I read this somewhere referencing DES , but I don't believe it... [EDIT: I was right, see 5th paragraph of this article for a reference to the permutations as useless.] BTW: If you haven't found it before, I'd guess the TEA / XTEA / XXTEA series of algorithms would be of interest. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/118374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10853/"
]
} |
118,423 | I've been impressed by the screencasts for Rails that demonstrate the built-in web server, and database to allow development and testing to occur on the local machine. How can I get an instance of Apache to execute a project directory as its DocumentRoot, and maybe serve up the files on port 8080 (or something similar)? The reason why I'm asking is that I'm going to be trying out CodeIgniter, and I would like to use it for multiple projects. I would rather not clutter up my machine's DocumentRoot with each one. Suggestions on how to do database migrations are also welcome. Thank you for your responses so far. I should clarify that I'm on Mac OS X. It looks like WAMP is Windows-only. Also, XAMPP looks like a great way to install Apache and many other web tools, but I don't see a way of loading up an instance to serve up a project directory. Mac OS X has both Apache and PHP installed - I'm just looking for a way to get it to serve up a project on a non-standard port. I just found MAMP Pro which does what I want, but a more minimalist approach would be better if it's possible. Does anyone have a httpd.conf file that can be edited and dropped into a project directory? Also, sorry that I just threw in that database migration question. What I'm hoping to find is something that will enable me to push schema changes onto a live server without losing the existing data. I suspect that this is difficult and highly dependent on environmental factors. | Your Mac comes with both an Apache Web Server and a build of PHP. It's one of the big reasons the platform is well loved by web developers. Since you're using Code Igniter, you'll want PHP 5, which is the default version of PHP shipped with 10.5. If you're on a previous version of the OS hop on over to entropy.ch and install the provided PHP5 package. Next, you'll want to turn Apache on. In the sharing preferences panel, turn on personal web sharing. This will start up apache on your local machine. Next, you'll want to setup some fake development URLs to use for your sites. Long standing tradition was that we'd use the fake TLD .dev for this (ex. stackoverflow.dev). However, .dev is now an actual TLD so you probably don't want to do this -- .localhost seems like an emerging defacto standard. Edit your /etc/hosts file and add the following lines 127.0.0.1 www.example.localhost127.0.0.1 example.localhost This points the above URLs at your local machine. The last step is configuring apache. Specifically, enabling named virtual hosting, enabling PHP and setting up a few virtual hosts. If you used the entropy PHP package, enabling PHP will already be done. If not, you'll need to edit your http.conf file as described here . Basically, you're uncommenting the lines that will load the PHP module. Whenever you make a change to your apache config, you'll need to restart apache for the changes to take effect. At a terminal window, type the following command sudo apachectl graceful This will gracefully restart apache. If you've made a syntax error in the config file apache won't restart. You can highlight config problems with sudo apachectl configtest So,with PHP enabled, you'll want to turn on NamedVirtualHosts. This will let apache respond to multiple URLs. Look for the following (or similar) line in your http.conf file and uncomment it. #NameVirtualHost * Finally, you'll need to tell apache where it should look for the files for your new virtual hosts. You can do so by adding the following to your http.conf file. NOTE: I find it's a good best practice to break out config rules like this into a separate file and use the include directive to include your changes. This will stop any automatic updates from wiping out your changes. <VirtualHost *> DocumentRoot /Users/username/Sites/example.localhost ServerName example.localhost ServerAlias www.example.localhost</VirtualHost> You can specify any folder as the DocumentRoot, but I find it convenient to use your personal Sites folder, as it's already been configured with the correct permissions to include files. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/118423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/658/"
]
} |
118,463 | We are looking to do some heavy security requirements on our project, and we need to do a lot of encryption that is highly performant. I think that I know that PKI is much slower and more complex than symmetric encryption, but I can't find the numbers to back up my feelings. | Yes, purely asymmetric encryption is much slower than symmetric cyphers (like DES or AES), which is why real applications use hybrid cryptography : the expensive public-key operations are performed only to encrypt (and exchange) an encryption key for the symmetric algorithm that is going to be used for encrypting the real message. The problem that public-key cryptography solves is that there is no shared secret. With a symmetric encryption you have to trust all involved parties to keep the key secret. This issue should be a much bigger concern than performance (which can be mitigated with a hybrid approach) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/118463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20150/"
]
} |
118,474 | Has anybody established a good naming convention for action in MVC? I was specifically looking at ASP.net MVC but it is a general question. For instance I have an action which displays the login screen (Login) and one which process the login request from that page (LoginTest). I'm not keen on the names and I have a lot of the applicaiton left to write. | Rob Conery at MS suggested some useful RESTful style naming for actions. * Index - the main "landing" page. This is also the default endpoint.* List - a list of whatever "thing" you're showing them - like a list of Products.* Show - a particular item of whatever "thing" you're showing them (like a Product)* Edit - an edit page for the "thing"* New - a create page for the "thing"* Create - creates a new "thing" (and saves it if you're using a DB)* Update - updates the "thing"* Delete - deletes the "thing" results in URLs along the lines of (for a forum) * http://mysite/forum/group/list - shows all the groups in my forum* http://mysite/forum/forums/show/1 - shows all the topics in forum id=1* http://mysite/forums/topic/show/20 - shows all the posts for topic id=20 Rob Conery on RESTful Architecture for MVC | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/118474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/361/"
]
} |
118,516 | My issue is below but would be interested comments from anyone with experience with xlrd. I just found xlrd and it looks like the perfect solution but I'm having a little problem getting started. I am attempting to extract data programatically from an Excel file I pulled from Dow Jones with current components of the Dow Jones Industrial Average (link: http://www.djindexes.com/mdsidx/?event=showAverages ) When I open the file unmodified I get a nasty BIFF error (binary format not recognized) However you can see in this screenshot that Excel 2008 for Mac thinks it is in 'Excel 1997-2004' format (screenshot: http://skitch.com/alok/ssa3/componentreport-dji.xls-properties ) If I instead open it in Excel manually and save as 'Excel 1997-2004' format explicitly, then open in python usig xlrd, everything is wonderful. Remember, Office thinks the file is already in 'Excel 1997-2004' format. All files are .xls Here is a pastebin of an ipython session replicating the issue: http://pastie.textmate.org/private/jbawdtrvlrruh88mzueqdq Any thoughts on:How to trick xlrd into recognizing the file so I can extract data?How to use python to automate the explicit 'save as' format to one that xlrd will accept?Plan B? | FWIW, I'm the author of xlrd, and the maintainer of xlwt (a fork of pyExcelerator). A few points: The file ComponentReport-DJI.xls is misnamed; it is not an XLS file, it is a tab-separated-values file. Open it with a text editor (e.g. Notepad) and you'll see what I mean. You can also look at the not-very-raw raw bytes with Python: >>> open('ComponentReport-DJI.xls', 'rb').read(200)'COMPANY NAME\tPRIMARY EXCHANGE\tTICKER\tSTYLE\tICB SUBSECTOR\tMARKET CAP RANGE\tWEIGHT PCT\tUSD CLOSE\t\r\n3M Co.\tNew York SE\tMMM\tN/A\tDiversified Industrials\tBroad\t5.15676229508\t50.33\t\r\nAlcoa Inc.\tNew York SE\tA' You can read this file using Python's csv module ... just use delimiter="\t" in your call to csv.reader() . xlrd can read any file that pyExcelerator can, and read them better—dates don't come out as floats, and the full story on Excel dates is in the xlrd documentation. pyExcelerator is abandonware—xlrd and xlwt are alive and well. Check out http://groups.google.com/group/python-excel HTHJohn | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/118516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
118,526 | How do you support optimistic / pessimistic concurrency using NHibernate? | NHibernate, by default, supports optimistic concurrency. Pessimistic concurrency, on the other hand, can be accomplished through the ISession.Lock() method. These issues are discussed in detail in this document . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/118526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1574/"
]
} |
118,528 | I've actually solved this, but I'm posting it for posterity. I ran into a very odd issue with the DataGridView on my dual-monitor system. The issue manifests itself as an EXTREMELY slow repaint of the control ( like 30 seconds for a full repaint ), but only when it is on one of my screens. When on the other, the repaint speed is fine. I have an Nvidia 8800 GT with the latest non-beta drivers (175. something). Is it a driver bug? I'll leave that up in the air, since I have to live with this particular configuration. (It does not happen on ATI cards, though...) The paint speed has nothing to do with the cell contents, and custom drawing doesn't improve the performance at all - even when just painting a solid rectangle. I later find out that placing a ElementHost (from the System.Windows.Forms.Integration namespace) on the form corrects the problem. It doesn't have to be messed with; it just needs to be a child of the form the DataGridView is also on. It can be resized to (0, 0) as long as the Visible property is true. I don't want to explicitly add the .NET 3/3.5 dependency to my application; I make a method to create this control at runtime (if it can) using reflection. It works, and at least it fails gracefully on machines that don't have the required library - it just goes back to being slow. This method also lets me apply to fix while the app is running, making it easier to see what the WPF libraries are changing on my form (using Spy++). After a lot of trial and error, I notice that enabling double buffering on the control itself (as opposed to just the form) corrects the issue! So, you just need to make a custom class based off of DataGridView so you can enable its DoubleBuffering. That's it! class CustomDataGridView: DataGridView{ public CustomDataGridView() { DoubleBuffered = true; }} As long as all of my instances of the grid are using this custom version, all is well. If I ever run into a situation caused by this where I'm not able to use the subclass solution (if I don't have the code), I suppose I could try to inject that control onto the form :) ( although I'll be more likely to try using reflection to force the DoubleBuffered property on from the outside to once again avoid the dependency ). It is sad that such a trivially simple thing ate up so much of my time... | You just need to make a custom class based off of DataGridView so you can enable its DoubleBuffering. That's it! class CustomDataGridView: DataGridView{ public CustomDataGridView() { DoubleBuffered = true; } } As long as all of my instances of the grid are using this custom version, all is well. If I ever run into a situation caused by this where I'm not able to use the subclass solution (if I don't have the code), I suppose I could try to inject that control onto the form :) (although I'll be more likely to try using reflection to force the DoubleBuffered property on from the outside to once again avoid the dependency). It is sad that such a trivially simple thing ate up so much of my time... Note: Making the answer an answer so the question can be marked as answered | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/118528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5927/"
]
} |
118,531 | What is the best way to test my webforms applications? Looks like people are loving Watin, and selenium. | UPDATE : Given WatiN has been stagnant for over a year now, I would direct anyone that needs web ui tests towards selenium , it is in continuous use & development by many contributors, and is actively used by Google. WatiN is the best that I've found. It integrates into Visual Studio unit testing or nunit & you can do pretty much anything you need in the browser (click links, submit forms, look for text/images, etc.) See the following questions for similar answers: What is the best way to do unit testing for ASP web pages (C#)? Web Application Testing for .Net (watin Test Recorder) How do you programmatically fill in a form and ‘POST’ a web page? | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/118531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
]
} |
118,565 | Say I have a web service http://www.example.com/webservice.pl?q=google which returns text "google.com". I need to call this web service ( http://www.example.com/webservice.pl ) from a JavaScript module with a parameter (q=google) and then use the return value ("google.com") to do further processing. What's the simplest way to do this? I am a total JavaScript newbie, so any help is much appreciated. | Take a look at one of the many javascript libraries out there. I'd recommend jQuery , personally. Aside from all the fancy UI stuff they can do, it has really good cross-browser AJAX libraries . $.get( "http://xyz.com/webservice.pl", { q : "google" }, function(data) { alert(data); // "google.com" }); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/118565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5734/"
]
} |
118,633 | Although I do understand the serious implications of playing with this function (or at least that's what I think), I fail to see why it's becoming one of these things that respectable programmers wouldn't ever use, even those who don't even know what it is for. Let's say I'm developing an application where memory usage varies extremely depending on what the user is doing. The application life cycle can be divided into two main stages: editing and real-time processing. During the editing stage, suppose that billions or even trillions of objects are created; some of them small and some of them not, some may have finalizers and some may not, and suppose their lifetimes vary from a very few milliseconds to long hours. Next, the user decides to switch to the real-time stage. At this point, suppose that performance plays a fundamental role and the slightest alteration in the program's flow could bring catastrophic consequences. Object creation is then reduced to the minimum possible by using object pools and the such but then, the GC chimes in unexpectedly and throws it all away, and someone dies. The question: In this case, wouldn't it be wise to call GC.Collect() before entering the second stage? After all, these two stages never overlap in time with each other and all the optimization and statistics the GC could have gathered would be of little use here... Note: As some of you have pointed out, .NET might not be the best platform for an application like this, but that's beyond the scope of this question. The intent is to clarify whether a GC.Collect() call can improve an application's overall behaviour/performance or not. We all agree that the circumstances under which you would do such a thing are extremely rare but then again, the GC tries to guess and does it perfectly well most of the time, but it's still about guessing. Thanks. | From Rico's Blog... Rule #1 Don't. This is really the most importantrule. It's fair to say that mostusages of GC.Collect() are a bad ideaand I went into that in some detail inthe orginal posting so I won't repeatall that here. So let's move on to... Rule #2 Consider calling GC.Collect() if somenon-recurring event has just happenedand this event is highly likely tohave caused a lot of old objects todie. A classic example of this is if you'rewriting a client application and youdisplay a very large and complicatedform that has a lot of data associatedwith it. Your user has justinteracted with this form potentiallycreating some large objects... thingslike XML documents, or a large DataSetor two. When the form closes theseobjects are dead and so GC.Collect()will reclaim the memory associatedwith them... So it sounds like this situation may fall under Rule #2, you know that there's a moment in time where a lot of old objects have died, and it's non-recurring. However, don't forget Rico's parting words. Rule #1 should trump Rule #2 withoutstrong evidence. Measure, measure, measure. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/118633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7839/"
]
} |
118,643 | I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into a properly indented representation that the Python interpreter could use? | There's a solution to your problem that is distributed with python itself. pindent.py , it's located in the Tools\Scripts directory in a windows install (my path to it is C:\Python25\Tools\Scripts), it looks like you'd have to grab it from svn.python.org if you are running on Linux or OSX. It adds comments when blocks are closed, or can properly indent code if comments are put in. Here's an example of the code outputted by pindent with the command: pindent.py -c myfile.py def foobar(a, b): if a == b: a = a+1 elif a < b: b = b-1 if b > a: a = a-1 # end if else: print 'oops!' # end if# end def foobar Where the original myfile.py was: def foobar(a, b): if a == b: a = a+1 elif a < b: b = b-1 if b > a: a = a-1 else: print 'oops!' You can also use pindent.py -r to insert the correct indentation based on comments (read the header of pindent.py for details), this should allow you to code in python without worrying about indentation. For example, running pindent.py -r myfile.py will convert the following code in myfile.py into the same properly indented (and also commented) code as produced by the pindent.py -c example above: def foobar(a, b):if a == b:a = a+1elif a < b:b = b-1if b > a: a = a-1# end ifelse:print 'oops!'# end if# end def foobar I'd be interested to learn what solution you end up using, if you require any further assistance, please comment on this post and I'll try to help. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/118643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14744/"
]
} |
118,654 | Does beautiful soup work with iron python?If so with which version of iron python?How easy is it to distribute a windows desktop app on .net 2.0 using iron python (mostly c# calling some python code for parsing html)? | I was asking myself this same question and after struggling to follow advice here and elsewhere to get IronPython and BeautifulSoup to play nicely with my existing code I decided to go looking for an alternative native .NET solution. BeautifulSoup is a wonderful bit of code and at first it didn't look like there was anything comparable available for .NET, but then I found the HTML Agility Pack and if anything I think I've actually gained some maintainability over BeautifulSoup. It takes clean or crufty HTML and produces a elegant XML DOM from it that can be queried via XPath. With a couple lines of code you can even get back a raw XDocument and then craft your queries in LINQ to XML . Honestly, if web scraping is your goal, this is about the cleanest solution you are likely to find. Edit Here is a simple (read: not robust at all) example that parses out the US House of Representatives holiday schedule: using System;using System.Collections.Generic;using HtmlAgilityPack;namespace GovParsingTest{ class Program { static void Main(string[] args) { HtmlWeb hw = new HtmlWeb(); string url = @"http://www.house.gov/house/House_Calendar.shtml"; HtmlDocument doc = hw.Load(url); HtmlNode docNode = doc.DocumentNode; HtmlNode div = docNode.SelectSingleNode("//div[@id='primary']"); HtmlNodeCollection tableRows = div.SelectNodes(".//tr"); foreach (HtmlNode row in tableRows) { HtmlNodeCollection cells = row.SelectNodes(".//td"); HtmlNode dateNode = cells[0]; HtmlNode eventNode = cells[1]; while (eventNode.HasChildNodes) { eventNode = eventNode.FirstChild; } Console.WriteLine(dateNode.InnerText); Console.WriteLine(eventNode.InnerText); Console.WriteLine(); } //Console.WriteLine(div.InnerHtml); Console.ReadKey(); } }} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/118654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7883/"
]
} |
118,659 | I am building a physics simulation engine and editor in Windows. I want to build the editor part using Qt and I want to run the engine using SDL with OpenGL. My first idea was to build the editor using only Qt and share as much code with the engine (the resource manager, the renderer, the maths). But, I would also like to be able to run the simulation inside the editor. This means I also have to share the simulation code which uses SDL threads. So, my question is this: Is there a way to have an the render OpenGL to a Qt window by using SDL? I have read on the web that it might be possible to supply SDL with a window handle in which to render. Anybody has experience dong that? Also, the threaded part of the simulator might pose a problem since it uses SDL threads. | This is a simplification of what I do in my project. You can use it just like an ordinary widget, but as you need, you can using it's m_Screen object to draw to the SDL surface and it'll show in the widget :) #include "SDL.h"#include <QWidget>class SDLVideo : public QWidget { Q_OBJECTpublic: SDLVideo(QWidget *parent = 0, Qt::WindowFlags f = 0) : QWidget(parent, f), m_Screen(0){ setAttribute(Qt::WA_PaintOnScreen); setUpdatesEnabled(false); // Set the new video mode with the new window size char variable[64]; snprintf(variable, sizeof(variable), "SDL_WINDOWID=0x%lx", winId()); putenv(variable); SDL_InitSubSystem(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE); // initialize default Video if((SDL_Init(SDL_INIT_VIDEO) == -1)) { std:cerr << "Could not initialize SDL: " << SDL_GetError() << std::endl; } m_Screen = SDL_SetVideoMode(640, 480, 8, SDL_HWSURFACE | SDL_DOUBLEBUF); if (m_Screen == 0) { std::cerr << "Couldn't set video mode: " << SDL_GetError() << std::endl; } } virtual ~SDLVideo() { if(SDL_WasInit(SDL_INIT_VIDEO) != 0) { SDL_QuitSubSystem(SDL_INIT_VIDEO); m_Screen = 0; } }private: SDL_Surface *m_Screen;}; Hope this helps Note: It usually makes sense to set both the min and max size of this widget to the SDL surface size. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/118659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17087/"
]
} |
118,685 | On my blog I use some CSS classes which are defined in my stylesheet, but in RSS readers those styles don't show up. I had been searching for class="whatever" and replacing with style="something: something;" . But this means whenever I modify my CSS I need to modify my RSS-generating code too, and it doesn't work for a tag which belongs to multiple classes (i.e. class="snapshot accent" ). Is there any way to point to my stylesheet from my feed? | The popular RSS readers WILL NOT bother downloading a style sheet, even if you provide one and link to it using <?xml-stylesheet?> . Many RSS readers simply strip all inline style attributes from your tags. From testing today, I discovered that Outlook 2007 seems to strip out all styles, for example, even if they are inline. Good RSS readers allow a limited set of inline style attributes. See, for example, this article at Bloglines about what CSS they won't strip. From experimentation, Google Reader seems to pass through certain styles unharmed. The philosophy of RSS is indeed that the reader is responsible for presentation. Many people think that RSS should be plain text and that CSS in RSS feeds is inappropriate. It's probably not appropriate to impose a different font on your RSS feeds. However, certain types of content (for example, images floated on the left, with captions positioned carefully) require a minimal amount of styling in order to maintain their semantic meaning. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/118685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18511/"
]
} |
118,686 | I'm using GDI+ in C++. (This issue might exist in C# too). I notice that whenever I call Graphics::MeasureString() or Graphics::DrawString(), the string is padded with blank space on the left and right. For example, if I am using a Courier font, (not italic!) and I measure "P" I get 90, but "PP" gives me 150. I would expect a monospace font to give exactly double the width for "PP". My question is: is this intended or documented behaviour, and how do I disable this? RectF Rect(0,0,32767,32767);RectF Bounds1, Bounds2;graphics->MeasureString(L"PP", 1, font, Rect, &Bounds1);graphics->MeasureString(L"PP", 2, font, Rect, &Bounds2);margin = Bounds1.Width * 2 - Bounds2.Width; | It's by design, that method doesn't use the actual glyphs to measure the width and so adds a little padding in the case of overhangs. MSDN suggests using a different method if you need more accuracy: To obtain metrics suitable for adjacent strings in layout (for example, when implementing formatted text), use the MeasureCharacterRanges method or one of the MeasureString methods that takes a StringFormat , and pass GenericTypographic . Also, ensure the TextRenderingHint for the Graphics is AntiAlias . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/118686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10592/"
]
} |
118,693 | Dynamically creating a radio button using eg var radioInput = document.createElement('input');radioInput.setAttribute('type', 'radio');radioInput.setAttribute('name', name); works in Firefox but not in IE. Why not? | Taking a step from what Patrick suggests, using a temporary node we can get rid of the try/catch: function createRadioElement(name, checked) { var radioHtml = '<input type="radio" name="' + name + '"'; if ( checked ) { radioHtml += ' checked="checked"'; } radioHtml += '/>'; var radioFragment = document.createElement('div'); radioFragment.innerHTML = radioHtml; return radioFragment.firstChild;} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/118693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6370/"
]
} |
118,698 | In JavaScript, you can use Lazy Function Definitions to optimize the 2nd - Nth call to a function by performing the expensive one-time operations only on the first call to the function. I'd like to do the same sort of thing in PHP 5, but redefining a function is not allowed, nor is overloading a function. Effectively what I'd like to do is like the following, only optimized so the 2nd - Nth calls (say 25-100) don't need to re-check if they are the first call. $called = false;function foo($param_1){ global $called; if($called == false){ doExpensiveStuff($param_1); $called = true; } echo '<b>'.$param_1.'</b>';} PS I've thought about using an include_once() or require_once() as the first line in the function to execute the external code just once, but I've heard that these too are expensive. Any Ideas? or is there a better way to tackle this? | Use a local static var: function foo() { static $called = false; if ($called == false) { $called = true; expensive_stuff(); }} Avoid using a global for this. It clutters the global namespace and makes the function less encapsulated. If other places besides the innards of the function need to know if it's been called, then it'd be worth it to put this function inside a class like Alan Storm indicated. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/118698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6144/"
]
} |
118,728 | I find the autoindent style of Notepad++ a little weird: when I am typing on an indented line, I do want it to indent the next line after I press Enter (this it does properly). However, when I am on an empty line (no indentation, no characters) and I press Enter, it indents the next line, using the same indentation as the last non-empty line. I find this extremely annoying; have you ever encountered this problem and do you know how to fix it? (Note: I'm editing HTML/PHP files.) | 1) First install NppAutoIndent plugin if you don't have it. Plugins > Plugin Manager > Show Plugin Manager, then install NppAutoIndent from the "Available" tab of that menu. 2) This behavior can be turned off by doing: Plugins > NppAutoIndent > Previous line 3) If this option is disabled, you may need to first check this option: Plugins > NppAutoIndent > Ignore language | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/118728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10786/"
]
} |
118,730 | Does anyone know how I can get rid of the following assembler warning? Code is x86, 32 bit: int test (int x){ int y; // do a bit-rotate by 8 on the lower word. leave upper word intact. asm ("rorw $8, %0\n\t": "=q"(y) :"0"(x)); return y;} If I compile it I get the following (very valid) warning: Warning: using `%ax' instead of `%eax' due to `w' suffix What I'm looking for is a way to tell the compiler/assembler that I want to access the lower 16 bit sub-register of %0. Accessing the byte sub-registers (in this case AL and AH) would be nice to know as well. I've already chosen the "q" modifier, so the compiler is forced to use EAX, EBX, ECX or EDX. I've made sure the compiler has to pick a register that has sub-registers. I know that I can force the asm-code to use a specific register (and its sub-registers), but I want to leave the register-allocation job up to the compiler. | You can use %w0 if I remember right. I just tested it, too. :-) inttest(int x){ int y; asm ("rorw $8, %w0" : "=q" (y) : "0" (x)); return y;} Edit: In response to the OP, yes, you can do the following too: inttest(int x){ int y; asm ("xchg %b0, %h0" : "=Q" (y) : "0" (x)); return y;} For x86 it's documented in the x86 Operand Modifiers section of the Extended Asm part of the manual. For non-x86 instruction sets, you may have to dig through their .md files in the GCC source. For example, gcc/config/i386/i386.md was the only place to find this before it was officially documented. (Related: In GNU C inline asm, what are the size-override modifiers for xmm/ymm/zmm for a single operand? for vector registers.) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/118730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15955/"
]
} |
118,774 | Deep down in WinDef.h there's this relic from the segmented memory era: #define far#define near This obviously causes problems if you attempt to use near or far as variable names. Any clean workarounds? Other then renaming my variables? | You can safely undefine them, contrary to claims from others. The reason is that they're just macros's. They only affect the preprocessor between their definition and their undefinition. In your case, that will be from early in windows.h to the last line of windows.h. If you need extra windows headers, you'd include them after windows.h and before the #undef. In your code, the preprocessor will simply leave the symbols unchanged, as intended. The comment about older code is irrelevant. That code will be in a separate library, compiled independently. Only at link time will these be connected, when macros are long gone. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/118774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1841/"
]
} |
118,813 | I want to use the macports version of python instead of the one that comes with Leopard. | I have both installed: $ which python/usr/bin/python$ which python2.5/opt/local/bin/python2.5 I also added the following line to my .profile : export PATH=/opt/local/bin:/opt/local/sbin:$PATH | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/118813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6013/"
]
} |
118,839 | I would like to replace only the group in parenthesis in this expression : my_string.gsub(/<--MARKER_START-->(.)*<--MARKER_END-->/, 'replace_text') so that I get : <--MARKER_START-->replace_text<--MARKER_END--> I know I could repeat the whole MARKER_START and MARKER_END blocks in the substitution expression but I thought there should be a more simple way to do this. | You could do something like this: my_string.gsub(/(<--MARKER_START-->)(.*)(<--MARKER_END-->)/, '\1replace_text\3') | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/118839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20871/"
]
} |
118,863 | When is it appropriate to use a class in Visual Basic for Applications (VBA)? I'm assuming the accelerated development and reduction of introducing bugs is a common benefit for most languages that support OOP. But with VBA, is there a specific criterion? | It depends on who's going to develop and maintain the code. Typical "Power User" macro writers hacking small ad-hoc apps may well be confused by using classes. But for serious development, the reasons to use classes are the same as in other languages. You have the same restrictions as VB6 - no inheritance - but you can have polymorphism by using interfaces. A good use of classes is to represent entities, and collections of entities. For example, I often see VBA code that copies an Excel range into a two-dimensional array, then manipulates the two dimensional array with code like: Total = 0For i = 0 To NumRows-1 Total = Total + (OrderArray(i,1) * OrderArray(i,3))Next i It's more readable to copy the range into a collection of objects with appropriately-named properties, something like: Total = 0For Each objOrder in colOrders Total = Total + objOrder.Quantity * objOrder.PriceNext i Another example is to use classes to implement the RAII design pattern (google for it). For example, one thing I may need to do is to unprotect a worksheet, do some manipulations, then protect it again. Using a class ensures that the worksheet will always be protected again even if an error occurs in your code: --- WorksheetProtector class module ---Private m_objWorksheet As WorksheetPrivate m_sPassword As StringPublic Sub Unprotect(Worksheet As Worksheet, Password As String) ' Nothing to do if we didn't define a password for the worksheet If Len(Password) = 0 Then Exit Sub ' If the worksheet is already unprotected, nothing to do If Not Worksheet.ProtectContents Then Exit Sub ' Unprotect the worksheet Worksheet.Unprotect Password ' Remember the worksheet and password so we can protect again Set m_objWorksheet = Worksheet m_sPassword = PasswordEnd SubPublic Sub Protect() ' Protects the worksheet with the same password used to unprotect it If m_objWorksheet Is Nothing Then Exit Sub If Len(m_sPassword) = 0 Then Exit Sub ' If the worksheet is already protected, nothing to do If m_objWorksheet.ProtectContents Then Exit Sub m_objWorksheet.Protect m_sPassword Set m_objWorksheet = Nothing m_sPassword = ""End SubPrivate Sub Class_Terminate() ' Reprotect the worksheet when this object goes out of scope On Error Resume Next ProtectEnd Sub You can then use this to simplify your code: Public Sub DoSomething() Dim objWorksheetProtector as WorksheetProtector Set objWorksheetProtector = New WorksheetProtector objWorksheetProtector.Unprotect myWorksheet, myPassword ... manipulate myWorksheet - may raise an errorEnd Sub When this Sub exits, objWorksheetProtector goes out of scope, and the worksheet is protected again. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/118863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3155/"
]
} |
118,884 | I have noticed that some browsers (in particular, Firefox and Opera ) are very zealous in using cached copies of .css and .js files, even between browser sessions. This leads to a problem when you update one of these files, but the user's browser keeps on using the cached copy. What is the most elegant way of forcing the user's browser to reload the file when it has changed? Ideally, the solution would not force the browser to reload the file on every visit to the page. I have found John Millikin's and da5id's suggestion to be useful. It turns out there is a term for this: auto-versioning . I have posted a new answer below which is a combination of my original solution and John's suggestion. Another idea that was suggested by SCdF would be to append a bogus query string to the file. (Some Python code, to automatically use the timestamp as a bogus query string, was submitted by pi. .) However, there is some discussion as to whether or not the browser would cache a file with a query string. (Remember, we want the browser to cache the file and use it on future visits. We only want it to fetch the file again when it has changed.) | This solution is written in PHP, but it should be easily adapted to other languages. The original .htaccess regex can cause problems with files like json-1.3.js . The solution is to only rewrite if there are exactly 10 digits at the end. (Because 10 digits covers all timestamps from 9/9/2001 to 11/20/2286.) First, we use the following rewrite rule in .htaccess: RewriteEngine onRewriteRule ^(.*)\.[\d]{10}\.(css|js)$ $1.$2 [L] Now, we write the following PHP function: /** * Given a file, i.e. /css/base.css, replaces it with a string containing the * file's mtime, i.e. /css/base.1221534296.css. * * @param $file The file to be loaded. Must be an absolute path (i.e. * starting with slash). */function auto_version($file){ if(strpos($file, '/') !== 0 || !file_exists($_SERVER['DOCUMENT_ROOT'] . $file)) return $file; $mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $file); return preg_replace('{\\.([^./]+)$}', ".$mtime.\$1", $file);} Now, wherever you include your CSS, change it from this: <link rel="stylesheet" href="/css/base.css" type="text/css" /> To this: <link rel="stylesheet" href="<?php echo auto_version('/css/base.css'); ?>" type="text/css" /> This way, you never have to modify the link tag again, and the user will always see the latest CSS. The browser will be able to cache the CSS file, but when you make any changes to your CSS the browser will see this as a new URL, so it won't use the cached copy. This can also work with images, favicons, and JavaScript. Basically anything that is not dynamically generated. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/118884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18511/"
]
} |
118,931 | Does adding a Web Service to my ASP.NET MVC project break the whole concept of MVC? That Web Service (WCF) depends on the Model layer from my MVC project to communicate with the back-end (so it looks to me like it needs to be part of the MVC solution). Should I add this to the Controller or Model layer? | It sounds like you should split out your model into its own assembly and reference it from your MVC-application and WCF-application. YourApp.Data -- Shared model and data access maybe YourApp.Web -- If you want to share more across your web-apps YourApp.Web.Mvc YourApp.Web.WebService If you want to do WebServices MVC-style maybe you should use MVC to build your own REST-application. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/118931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2721/"
]
} |
118,935 | Know of an OCAML/CAML IDE? Especially one that runs on Linux? | Emacs in Caml mode , or Tuareg mode , or TypeRex mode . TypeRex adds auto-completion to Taureg in emacs - a really nice feature for people who prefer the more graphical IDE's. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/118935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7888/"
]
} |
118,955 | For various reasons, we are writing a new business objects/data storage library. One of the requirements of this layer is to separate the logic of the business rules, and the actual data storage layer. It is possible to have multiple data storage layers that implement access to the same object - for example, a main "database" data storage source that implements most objects, and another "ldap" source that implements a User object. In this scenario, User can optionally come from an LDAP source, perhaps with slightly different functionality (eg, not possible to save/update the User object), but otherwise it is used by the application the same way. Another data storage type might be a web service, or an external database. There are two main ways we are looking at implementing this, and me and a co-worker disagree on a fundamental level which is correct. I'd like some advice on which one is the best to use. I'll try to keep my descriptions of each as neutral as possible, as I'm looking for some objective view points here. Business objects are base classes, and data storage objects inherit business objects. Client code deals with data storage objects. In this case, common business rules are inherited by each data storage object, and it is the data storage objects that are directly used by the client code. This has the implication that client code determines which data storage method to use for a given object, because it has to explicitly declare an instance to that type of object. Client code needs to explicitly know connection information for each data storage type it is using. If a data storage layer implements different functionality for a given object, client code explicitly knows about it at compile time because the object looks different. If the data storage method is changed, client code has to be updated. Business objects encapsulate data storage objects. In this case, business objects are directly used by client application. Client application passes along base connection information to business layer. Decision about which data storage method a given object uses is made by business object code. Connection information would be a chunk of data taken from a config file (client app does not really know/care about details of it), which may be a single connection string for a database, or several pieces connection strings for various data storage types. Additional data storage connection types could also be read from another spot - eg, a configuration table in a database that specifies URLs to various web services. The benefit here is that if a new data storage method is added to an existing object, a configuration setting can be set at runtime to determine which method to use, and it is completely transparent to the client applications. Client apps do not need to be modified if data storage method for a given object changes. Business objects are base classes, data source objects inherit from business objects. Client code deals primarily with base classes. This is similar to the first method, but client code declares variables of the base business object types, and Load()/Create()/etc static methods on the business objects return the appropriate data source-typed objects. The architecture of this solution is similar to the first method, but the main difference is the decision about which data storage object to use for a given business object is made by the business layer, not the client code. I know there are already existing ORM libraries that provide some of this functionality, but please discount those for now (there is the possibility that a data storage layer is implemented with one of these ORM libraries) - also note I'm deliberately not telling you what language is being used here, other than that it is strongly typed. I'm looking for some general advice here on which method is better to use (or feel free to suggest something else), and why. | might i suggest another alternative, with possibly better decoupling: business objects use data objects, and data objects implement storage objects. This should keep the business rules in the business objects but without any dependence on the storage source or format, while allowing the data objects to support whatever manipulations are required, including changing the storage objects dynamically (e.g. for online/offline manipulation) this falls into the second category above (business objects encapsulate data storage objects), but separates data semantics from storage mechanisms more clearly | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/118955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7913/"
]
} |
118,984 | Sight is one of the senses most programmers take for granted. Most programmers would spend hours looking at a computer monitor (especially during times when they are in the zone ), but I know there are blind programmers (such as T.V. Raman who currently works for Google). If you were a blind person (or slowly becoming blind), how would you set up your development environment to assist you in programming? (One suggestion per answer please. The purpose of this question is to bring the good ideas to the top. In addition, screen readers can read the good ideas earlier.) | I am a totally blind college student who’s had several programming internships so my answer will be based off these. I use windows xp as my operating system and Jaws to read what appears on the screen to me in synthetic speech. For java programming I use eclipse, since it’s a fully featured IDE that is accessible. In my experience as a general rule java programs that use SWT as the GUI toolkit are more accessible then programs that use Swing which is why I stay away from netbeans. For any .net programming I use visual studio 2005 since it was the standard version used at my internship and is very accessible using Jaws and a set of scripts that were developed to make things such as the form designer more accessible. For C and C++ programming I use cygwin with gcc as my compiler and emacs or vim as my editor depending on what I need to do. A lot of my internship involved programming for Z/OS. I used an rlogin session through Cygwin to access the USS subsystem on the mainframe and C3270 as my 3270 emulator to access the ISPF portion of the mainframe. I usually rely on synthetic speech but do have a Braille display. I find I usually work faster with speech but use the Braille display in situations where punctuation matters and gets complicated. Examples of this are if statements with lots of nested parenthesis’s and JCL where punctuation is incredibly important. Update I'm playing with Emacspeak under cygwin http://emacspeak.sourceforge.net I'm not sure if this will be usable as a programming editor since it appears to be somewhat unresponsive but I haven't looked at any of the configuration options yet. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/118984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1599/"
]
} |
119,008 | I recently installed MySQL 5 on Windows 2003 and tried configuring an instance. Everything worked fine until I got to "Applying Security settings", at which point it gave me the above error ( Can't connect to MySQL server on 'localhost' (10061) ). I do have a port 3306 exception in my firewall for 'MySQL Server'. | You'll probably have to grant 'localhost' privileges to on the table to the user. See the 'GRANT' syntax documentation. Here's an example (from some C source). "GRANT ALL PRIVILEGES ON %s.* TO '%s'@'localhost' IDENTIFIED BY '%s'"; That's the most common access problem with MySQL. Other than that, you might check that the user you have defined to create your instance has full privileges, else the user cannot grant privileges. Also, make sure the mysql service is started. Make sure you don't have a third party firewall or Internet security service turned on. Beyond that, there's several pages of the MySQL forum devoted to this: http://forums.mysql.com/read.php?11,9293,9609#msg-9609 Try reading that. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/119008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1748529/"
]
} |
119,009 | In our Java applications we typically use the maven conventions (docs, src/java, test, etc.). For Perl we follow similar conventions only using a top level 'lib' which is easy to add to Perl's @INC. I'm about to embark on creating a service written in Erlang, what's a good source layout for Erlang applications? | The Erlang recommended standard directory structure can be found here . In addition you may need a few more directories depending on your project, common ones are (credit to Vance Shipley): lib: OS driver libraries bin: OS executables c_src: C language source files (e.g. for drivers) java_src: Java language source files examples: Example code mibs: SNMP MIBs Other projects such as Mochiweb have their own structures, Mochiweb even have a script to create it all for you. Other projects such as Erlware overlay on the standard structure. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/119009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19784/"
]
} |
119,098 | In new C++ code, I tend to use the C++ iostream library instead of the C stdio library. I've noticed some programmers seem to stick to stdio, insisting that it's more portable. Is this really the case? What is better to use? | To answer the original question: Anything that can be done using stdio can be done using the iostream library. Disadvantages of iostreams: verboseAdvantages of iostreams: easy to extend for new non POD types. The step forward the C++ made over C was type safety. iostreams was designed to be explicitly type safe. Thus assignment to an object explicitly checked the type (at compiler time) of the object being assigned too (generating an compile time error if required). Thus prevent run-time memory over-runs or writing a float value to a char object etc. scanf()/printf() and family on the other hand rely on the programmer getting the format string correct and there was no type checking (I believe gcc has an extension that helps). As a result it was the source of many bugs (as programmers are less perfect in their analysis than compilers [not going to say compilers are perfect just better than humans]). Just to clarify comments from Colin Jensen. The iostream libraries have been stable since the release of the last standard (I forget the actual year but about 10 years ago). To clarify comments by Mikael Jansson. The other languages that he mentions that use the format style have explicit safeguards to prevent the dangerous side effects of the C stdio library that can (in C but not the mentioned languages) cause a run-time crash. N.B. I agree that the iostream library is a bit on the verbose side. But I am willing to put up with the verboseness to ensure runtime safety. But we can mitigate the verbosity by using Boost Format Library . #include <iostream>#include <iomanip>#include <boost/format.hpp>struct X{ // this structure reverse engineered from // example provided by 'Mikael Jansson' in order to make this a running example char* name; double mean; int sample_count;};int main(){ X stats[] = {{"Plop",5.6,2}}; // nonsense output, just to exemplify // stdio version fprintf(stderr, "at %p/%s: mean value %.3f of %4d samples\n", stats, stats->name, stats->mean, stats->sample_count); // iostream std::cerr << "at " << (void*)stats << "/" << stats->name << ": mean value " << std::fixed << std::setprecision(3) << stats->mean << " of " << std::setw(4) << std::setfill(' ') << stats->sample_count << " samples\n"; // iostream with boost::format std::cerr << boost::format("at %p/%s: mean value %.3f of %4d samples\n") % stats % stats->name % stats->mean % stats->sample_count;} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/119098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4086/"
]
} |
119,107 | This is what I have so far: myArray.map!{ rand(max) } Obviously, however, sometimes the numbers in the list are not unique. How can I make sure my list only contains unique numbers without having to create a bigger list from which I then just pick the n unique numbers? Edit: I'd really like to see this done w/o loop - if at all possible. | This uses Set: require 'set'def rand_n(n, max) randoms = Set.new loop do randoms << rand(max) return randoms.to_a if randoms.size >= n endend | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/119107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/781/"
]
} |
119,123 | Why does the sizeof operator return a size larger for a structure than the total sizes of the structure's members? | This is because of padding added to satisfy alignment constraints. Data structure alignment impacts both performance and correctness of programs: Mis-aligned access might be a hard error (often SIGBUS ). Mis-aligned access might be a soft error. Either corrected in hardware, for a modest performance-degradation. Or corrected by emulation in software, for a severe performance-degradation. In addition, atomicity and other concurrency-guarantees might be broken, leading to subtle errors. Here's an example using typical settings for an x86 processor (all used 32 and 64 bit modes): struct X{ short s; /* 2 bytes */ /* 2 padding bytes */ int i; /* 4 bytes */ char c; /* 1 byte */ /* 3 padding bytes */};struct Y{ int i; /* 4 bytes */ char c; /* 1 byte */ /* 1 padding byte */ short s; /* 2 bytes */};struct Z{ int i; /* 4 bytes */ short s; /* 2 bytes */ char c; /* 1 byte */ /* 1 padding byte */};const int sizeX = sizeof(struct X); /* = 12 */const int sizeY = sizeof(struct Y); /* = 8 */const int sizeZ = sizeof(struct Z); /* = 8 */ One can minimize the size of structures by sorting members by alignment (sorting by size suffices for that in basic types) (like structure Z in the example above). IMPORTANT NOTE: Both the C and C++ standards state that structure alignment is implementation-defined. Therefore each compiler may choose to align data differently, resulting in different and incompatible data layouts. For this reason, when dealing with libraries that will be used by different compilers, it is important to understand how the compilers align data. Some compilers have command-line settings and/or special #pragma statements to change the structure alignment settings. | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/119123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6386/"
]
} |
119,167 | I'm taking a look at how the model system in django works and I noticed something that I don't understand. I know that you create an empty __init__.py file to specify that the current directory is a package. And that you can set some variable in __init__.py so that import * works properly. But django adds a bunch of from ... import ... statements and defines a bunch of classes in __init__.py . Why? Doesn't this just make things look messy? Is there a reason that requires this code in __init__.py ? | All imports in __init__.py are made available when you import the package (directory) that contains it. Example: ./dir/__init__.py : import something ./test.py : import dir# can now use dir.something EDIT: forgot to mention, the code in __init__.py runs the first time you import any module from that directory. So it's normally a good place to put any package-level initialisation code. EDIT2: dgrant pointed out to a possible confusion in my example. In __init__.py import something can import any module, not necessary from the package. For example, we can replace it with import datetime , then in our top level test.py both of these snippets will work: import dirprint dir.datetime.datetime.now() and import dir.some_module_in_dirprint dir.datetime.datetime.now() The bottom line is: all names assigned in __init__.py , be it imported modules, functions or classes, are automatically available in the package namespace whenever you import the package or a module in the package. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/119167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3935/"
]
} |
119,197 | I have a question about how to do something "The Rails Way". With an application that has a public facing side and an admin interface what is the general consensus in the Rails community on how to do it? Namespaces, subdomains or forego them altogether? | There's no real "Rails way" for admin interfaces, actually - you can find every possible solution in a number of applications. DHH has implied that he prefers namespaces (with HTTP Basic authentication), but that has remained a simple implication and not one of the official Rails Opinions. That said, I've found good success with that approach lately (namespacing + HTTP Basic). It looks like this: routes.rb: map.namespace :admin do |admin| admin.resources :users admin.resources :postsend admin/users_controller.rb: class Admin::UsersController < ApplicationController before_filter :admin_required # ...end application.rb class ApplicationController < ActionController::Base # ... protected def admin_required authenticate_or_request_with_http_basic do |user_name, password| user_name == 'admin' && password == 's3cr3t' end if RAILS_ENV == 'production' || params[:admin_http] endend The conditional on authenticate_or_request_with_http_basic triggers the HTTP Basic auth in production mode or when you append ?admin_http=true to any URL, so you can test it in your functional tests and by manually updating the URL as you browse your development site. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/119197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20899/"
]
} |
119,271 | Just wondering if someone could help me with some msbuild scripts that I am trying to write. What I would like to do is copy all the files and sub folders from a folder to another folder using msbuild. {ProjectName} |----->Source |----->Tools |----->Viewer |-----{about 5 sub dirs} What I need to be able to do is copy all the files and sub folders from the tools folder into the debug folder for the application. This is the code that I have so far. <ItemGroup> <Viewer Include="..\$(ApplicationDirectory)\Tools\viewer\**\*.*" /></ItemGroup><Target Name="BeforeBuild"> <Copy SourceFiles="@(Viewer)" DestinationFolder="@(Viewer->'$(OutputPath)\\Tools')" /></Target> The build script runs but doesn't copy any of the files or folders. Thanks | I was searching help on this too. It took me a while, but here is what I did that worked really well. <Target Name="AfterBuild"> <ItemGroup> <ANTLR Include="..\Data\antlrcs\**\*.*" /> </ItemGroup> <Copy SourceFiles="@(ANTLR)" DestinationFolder="$(TargetDir)\%(RecursiveDir)" SkipUnchangedFiles="true" /></Target> This recursively copied the contents of the folder named antlrcs to the $(TargetDir) . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/119271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6335/"
]
} |
119,284 | I would like to be able to override the default behaviour for positioning the caret in a masked textbox. The default is to place the caret where the mouse was clicked, the masked textbox already contains characters due to the mask. I know that you can hide the caret as mentioned in this post , is there something similar for positioning the caret at the beginning of the textbox when the control gets focus. | This should do the trick: private void maskedTextBox1_Enter(object sender, EventArgs e) { this.BeginInvoke((MethodInvoker)delegate() { maskedTextBox1.Select(0, 0); }); } | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/119284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4490/"
]
} |
119,286 | Consider the following ruby code test.rb: begin puts thisFunctionDoesNotExist x = 1+1rescue Exception => e p eend For debugging purposes, I would like the rescue block to know that the error occurred in line 4 of this file. Is there a clean way of doing that? | p e.backtrace I ran it on an IRB session which has no source and it still gave relevant info. => ["(irb):11:in `foo'", "(irb):17:in `irb_binding'", "/usr/lib64/ruby/1.8/irb/workspace.rb:52:in `irb_binding'", "/usr/lib64/ruby/1.8/irb/workspace.rb:52"] If you want a nicely parsed backtrace, the following regex might be handy: p x.backtrace.map{ |x| x.match(/^(.+?):(\d+)(|:in `(.+)')$/); [$1,$2,$4] }[ ["(irb)", "11", "foo"], ["(irb)", "48", "irb_binding"], ["/usr/lib64/ruby/1.8/irb/workspace.rb", "52", "irb_binding"], ["/usr/lib64/ruby/1.8/irb/workspace.rb", "52", nil]] ( Regex /should/ be safe against weird characters in function names or directories/filenames ) ( If you're wondering where foo camefrom, i made a def to grab the exception out : >>def foo>> thisFunctionDoesNotExist>> rescue Exception => e >> return e >>end >>x = foo >>x.backtrace | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/119286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17674/"
]
} |
119,312 | Is it better convention to use hyphens or underscores in your URLs? Should it be /about_us or /about-us ? From usability point of view, I personally think /about-us is much better for end-user yet Google and most other websites (and javascript frameworks) use underscore naming pattern. Is it just matter of style? Are there any compatibility issues with dashes? | From Google Webmaster Central Consider using punctuation in your URLs. The URL http://www.example.com/green-dress.html is much more useful to us than http://www.example.com/greendress.html . We recommend that you use hyphens (-) instead of underscores (_) in your URLs. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/119312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/275/"
]
} |
119,328 | How do I truncate a java String so that I know it will fit in a given number of bytes storage once it is UTF-8 encoded? | Here is a simple loop that counts how big the UTF-8 representation is going to be, and truncates when it is exceeded: public static String truncateWhenUTF8(String s, int maxBytes) { int b = 0; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); // ranges from http://en.wikipedia.org/wiki/UTF-8 int skip = 0; int more; if (c <= 0x007f) { more = 1; } else if (c <= 0x07FF) { more = 2; } else if (c <= 0xd7ff) { more = 3; } else if (c <= 0xDFFF) { // surrogate area, consume next char as well more = 4; skip = 1; } else { more = 3; } if (b + more > maxBytes) { return s.substring(0, i); } b += more; i += skip; } return s;} This does handle surrogate pairs that appear in the input string. Java's UTF-8 encoder (correctly) outputs surrogate pairs as a single 4-byte sequence instead of two 3-byte sequences, so truncateWhenUTF8() will return the longest truncated string it can. If you ignore surrogate pairs in the implementation then the truncated strings may be shorted than they needed to be. I haven't done a lot of testing on that code, but here are some preliminary tests: private static void test(String s, int maxBytes, int expectedBytes) { String result = truncateWhenUTF8(s, maxBytes); byte[] utf8 = result.getBytes(Charset.forName("UTF-8")); if (utf8.length > maxBytes) { System.out.println("BAD: our truncation of " + s + " was too big"); } if (utf8.length != expectedBytes) { System.out.println("BAD: expected " + expectedBytes + " got " + utf8.length); } System.out.println(s + " truncated to " + result);}public static void main(String[] args) { test("abcd", 0, 0); test("abcd", 1, 1); test("abcd", 2, 2); test("abcd", 3, 3); test("abcd", 4, 4); test("abcd", 5, 4); test("a\u0080b", 0, 0); test("a\u0080b", 1, 1); test("a\u0080b", 2, 1); test("a\u0080b", 3, 3); test("a\u0080b", 4, 4); test("a\u0080b", 5, 4); test("a\u0800b", 0, 0); test("a\u0800b", 1, 1); test("a\u0800b", 2, 1); test("a\u0800b", 3, 1); test("a\u0800b", 4, 4); test("a\u0800b", 5, 5); test("a\u0800b", 6, 5); // surrogate pairs test("\uD834\uDD1E", 0, 0); test("\uD834\uDD1E", 1, 0); test("\uD834\uDD1E", 2, 0); test("\uD834\uDD1E", 3, 0); test("\uD834\uDD1E", 4, 4); test("\uD834\uDD1E", 5, 4);} Updated Modified code example, it now handles surrogate pairs. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/119328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4220/"
]
} |
119,336 | I've got a customer trying to access one of my sites, and they keep getting this error > ssl_error_rx_record_too_long They're getting this error on all browsers, all platforms. I can't reproduce the problem at all. My server and myself are located in the USA, the customer is located in India. I googled on the problem, and the main source seems to be that the SSL port is speaking in HTTP. I checked my server, and this is not happening. I tried the solution mentioned here , but the customer has stated it did not fix the issue. Can anyone tell me how I can fix this, or how I can reproduce this??? THE SOLUTION Turns out the customer had a misconfigured local proxy! Hope that helps anyone finding this question trying to debug it in the future. | The link mentioned by Subimage was right on the money for me. It suggested changing the virtual host tag, ie, from <VirtualHost myserver.example.com:443> to <VirtualHost _default_:443> Error code: ssl_error_rx_record_too_long This usually means the implementation of SSL on your server is not correct. The error is usually caused by a server side problem which the server administrator will need to investigate. Below are some things we recommend trying. Ensure that port 443 is open and enabled on your server. This is the standard port for https communications. If SSL is using a non-standard port then FireFox 3 can sometimes give this error. Ensure SSL is running on port 443. If using Apache2 check that you are using port 443 for SSL. This can be done by setting the ports.conf file as follows Listen 80Listen 443 https Make sure you do not have more than one SSL certificate sharing the same IP. Please ensure that all SSL certificates utilise their own dedicated IP. If using Apache2 check your vhost config. Some users have reported changing <VirtualHost> to _default_ resolved the error. That fixed my problem. It's rare that I google an error message and get the first hit with the right answer! :-) In addition to the above , these are some other solutions that other folks have found were causing the issue: Make sure that your SSL certificate is not expired Try to specify the Cipher: SSLCipherSuite ALL:!aNULL:!ADH:!eNULL:!LOW:!EXP:RC4+RSA:+HIGH:+MEDIUM:+SSLv3 | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/119336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10596/"
]
} |
119,387 | Whenever I type a (, [, or {, Notepad++ completes it with the corresponding closing bracket. I find this 'feature' annoying and would like to disable it. It doesn't seem to be listed in the Preferences dialog and a search of the online documentation didn't yield any useful result. Does anybody here know where the option for this is hidden? I'm currently using Notepad++ 5.0.3. | From version 6.6.8 onward: Go to Settings -> Preferences -> Auto-Completion In the second grouping called "Auto-Insert", check/un-check the appropriate auto completion/inserts. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/119387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8127/"
]
} |
119,390 | Does anyone know how to change the from user when sending email using the mail command? I have looked through the man page and can not see how to do this. We are running Redhat Linux 5. | http://www.mindspill.org/962 seems to have a solution. Essentially: echo "This is the main body of the mail" | mail -s "Subject of the Email" [email protected] -- -f [email protected] | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/119390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5360/"
]
} |
119,404 | What is the simplest way to determine the length (in seconds) of a given mp3 file, without using outside libraries ? (python source highly appreciated) | You can use pymad . It's an external library, but don't fall for the Not Invented Here trap. Any particular reason you don't want any external libraries? import madmf = mad.MadFile("foo.mp3")track_length_in_milliseconds = mf.total_time() Spotted here . -- If you really don't want to use an external library, have a look here and check out how he's done it. Warning: it's complicated. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/119404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9440/"
]
} |
119,414 | There's a lot of people today who sell unittesting as bread-and-butter of development. That might even work for strongly algorithmically-oriented routines. However, how would you unit-test, for example, a memory allocator (think malloc()/realloc()/free()). It's not hard to produce a working (but absolutely useless) memory allocator that satisfies the specified interface. But how to provide the proper context for unit-testing functionality that is absolutely desired, yet not part of the contract: coalescing free blocks, reusing free blocks on next allocations, returning excess free memory to the system, asserting that the allocation policy (e.g. first-fit) really is respected, etc. My experience is that assertions, even if complex and time-consuming (e.g. traversing the whole free list to check invariants) are much less work and are more reliable than unit-testing, esp. when coding complex, time-dependent algorithms. Any thoughts? | Highly testable code tends to be structured differently than other code. You describe several tasks that you want an allocator to do: coalescing free blocks reusing free blocks on nextallocations returning excess free memory to thesystem asserting that the allocation policy(e.g. first-fit) really is respected While you might write your allocation code to be very coupled, as in doing several of those things inside one function body, you could also break each task out into code that is a testable chunk. This is almost an inversion of what you may be used to. I find that testable code tends to be very transparent and built from more small pieces. Next, I would say is that within reason automated testing of any sort is better than no automated testing. I would definitely focus more on making sure your tests do something useful than worrying if you've properly used mocks, whether you've ensured it's properly isolated and whether it's a true unit test. Those are all admirable goals that will hopefully make 99% of tests better. On the other hand, please use common sense and your best engineering judgment to get the job done. Without code samples I don't think I can be more specific. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/119414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2583/"
]
} |
119,426 | Are there any industry standard conventions for naming jar files? | I have been using *Informative*-*name*-*M*.*m*.*b*.jar Where: M = major version number (changed when backward compatibility is not necessarily maintained) m = minor version number (feature additions etc) b = build number (for releases containing bug fixes) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/119426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/939/"
]
} |
119,432 | Im running a ASP.NET Site where I have problems to find some JavaScript Errors just with manual testing. Is there a possibility to catch all JavaScript Errors on the Clientside and log them on the Server i.e. in the EventLog (via Webservice or something like that)? | You could try setting up your own handler for the onerror event and use XMLHttpRequest to tell the server what went wrong, however since it's not part of any specification, support is somewhat flaky . Here's an example from Using XMLHttpRequest to log JavaScript errors : window.onerror = function(msg, url, line){ var req = new XMLHttpRequest(); var params = "msg=" + encodeURIComponent(msg) + '&url=' + encodeURIComponent(url) + "&line=" + line; req.open("POST", "/scripts/logerror.php"); req.send(params);}; | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/119432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17558/"
]
} |
119,441 | I basically need to highlight a particular word in a block of text. For example, pretend I wanted to highlight the word "dolor" in this text: <p> Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p><p> Quisque bibendum sem ut lacus. Integer dolor ullamcorper libero. Aliquam rhoncus eros at augue. Suspendisse vitae mauris.</p> How do I convert the above to something like this: <p> Lorem ipsum <span class="myClass">dolor</span> sit amet, consectetuer adipiscing elit.</p><p> Quisque bibendum sem ut lacus. Integer <span class="myClass">dolor</span> ullamcorper libero. Aliquam rhoncus eros at augue. Suspendisse vitae mauris.</p> Is this possible with jQuery? Edit : As Sebastian pointed out , this is quite possible without jQuery - but I was hoping there might be a special method of jQuery which would let you do selectors on the text itself. I'm already using jQuery heavily on this site, so keeping everything wrapped up in jQuery would make things perhaps a bit more tidy. | Try highlight: JavaScript text highlighting jQuery plugin . Warning: The source code available on this page contains a cryptocurrency mining script, either use the code below or remove the mining script from the script downloaded from the website. /*highlight v4Highlights arbitrary terms.<http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>MIT license.Johann Burkard<http://johannburkard.de><mailto:[email protected]>*/jQuery.fn.highlight = function(pat) { function innerHighlight(node, pat) { var skip = 0; if (node.nodeType == 3) { var pos = node.data.toUpperCase().indexOf(pat); if (pos >= 0) { var spannode = document.createElement('span'); spannode.className = 'highlight'; var middlebit = node.splitText(pos); var endbit = middlebit.splitText(pat.length); var middleclone = middlebit.cloneNode(true); spannode.appendChild(middleclone); middlebit.parentNode.replaceChild(spannode, middlebit); skip = 1; } } else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) { for (var i = 0; i < node.childNodes.length; ++i) { i += innerHighlight(node.childNodes[i], pat); } } return skip; } return this.length && pat && pat.length ? this.each(function() { innerHighlight(this, pat.toUpperCase()); }) : this;};jQuery.fn.removeHighlight = function() { return this.find("span.highlight").each(function() { this.parentNode.firstChild.nodeName; with (this.parentNode) { replaceChild(this.firstChild, this); normalize(); } }).end();}; Also try the "updated" version of the original script . /* * jQuery Highlight plugin * * Based on highlight v3 by Johann Burkard * http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html * * Code a little bit refactored and cleaned (in my humble opinion). * Most important changes: * - has an option to highlight only entire words (wordsOnly - false by default), * - has an option to be case sensitive (caseSensitive - false by default) * - highlight element tag and class names can be specified in options * * Usage: * // wrap every occurrance of text 'lorem' in content * // with <span class='highlight'> (default options) * $('#content').highlight('lorem'); * * // search for and highlight more terms at once * // so you can save some time on traversing DOM * $('#content').highlight(['lorem', 'ipsum']); * $('#content').highlight('lorem ipsum'); * * // search only for entire word 'lorem' * $('#content').highlight('lorem', { wordsOnly: true }); * * // don't ignore case during search of term 'lorem' * $('#content').highlight('lorem', { caseSensitive: true }); * * // wrap every occurrance of term 'ipsum' in content * // with <em class='important'> * $('#content').highlight('ipsum', { element: 'em', className: 'important' }); * * // remove default highlight * $('#content').unhighlight(); * * // remove custom highlight * $('#content').unhighlight({ element: 'em', className: 'important' }); * * * Copyright (c) 2009 Bartek Szopka * * Licensed under MIT license. * */jQuery.extend({ highlight: function (node, re, nodeName, className) { if (node.nodeType === 3) { var match = node.data.match(re); if (match) { var highlight = document.createElement(nodeName || 'span'); highlight.className = className || 'highlight'; var wordNode = node.splitText(match.index); wordNode.splitText(match[0].length); var wordClone = wordNode.cloneNode(true); highlight.appendChild(wordClone); wordNode.parentNode.replaceChild(highlight, wordNode); return 1; //skip added node in parent } } else if ((node.nodeType === 1 && node.childNodes) && // only element nodes that have children !/(script|style)/i.test(node.tagName) && // ignore script and style nodes !(node.tagName === nodeName.toUpperCase() && node.className === className)) { // skip if already highlighted for (var i = 0; i < node.childNodes.length; i++) { i += jQuery.highlight(node.childNodes[i], re, nodeName, className); } } return 0; }});jQuery.fn.unhighlight = function (options) { var settings = { className: 'highlight', element: 'span' }; jQuery.extend(settings, options); return this.find(settings.element + "." + settings.className).each(function () { var parent = this.parentNode; parent.replaceChild(this.firstChild, this); parent.normalize(); }).end();};jQuery.fn.highlight = function (words, options) { var settings = { className: 'highlight', element: 'span', caseSensitive: false, wordsOnly: false }; jQuery.extend(settings, options); if (words.constructor === String) { words = [words]; } words = jQuery.grep(words, function(word, i){ return word != ''; }); words = jQuery.map(words, function(word, i) { return word.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); }); if (words.length == 0) { return this; }; var flag = settings.caseSensitive ? "" : "i"; var pattern = "(" + words.join("|") + ")"; if (settings.wordsOnly) { pattern = "\\b" + pattern + "\\b"; } var re = new RegExp(pattern, flag); return this.each(function () { jQuery.highlight(this, re, settings.element, settings.className); });}; | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/119441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
]
} |
119,444 | For one and a half years, I have been keeping my eyes on the git community in hopes of making the switch away from SVN. One particular issue holding me back is the inability to lock binary files. Throughout the past year I have yet to see developments on this issue. I understand that locking files goes against the fundamental principles of distributed source control, but I don't see how a web development company can take advantage of git to track source code and image file changes when there is the potential for binary file conflicts. To achieve the effects of locking, a "central" repository must be identified. Regardless of the distributed nature of git, most companies will have a "central" repository for a software project. We should be able to mark a file as requiring a lock from the governing git repository at a specified address. Perhaps this is made difficult because git tracks file contents not files? Do any of you have experience in dealing with git and binary files that should be locked before modification? NOTE: It looks like Source Gear's new open source distributed version control project, Veracity, has locking as one of its goals. | Subversion has locks, and they aren't just advisory. They can be enforced using the svn:needs-lock attribute (but can also be deliberately broken if necessary). It's the right solution for managing non-mergeable files. The company I work for stores just about everything in Subversion, and uses svn:needs-lock for all non-mergeable files. I disagree with "locks are just a communication method". They are a much more effective method than push-notifications such as phone or e-mail. Subversion locks are self-documenting (who has the lock). On the other hand, if you have to communicate by other traditional push-notification channels, such as e-mail, who do you send the notification to? You don't know in advance who might want to edit the file, especially on open-source projects, unless you have a complete list of your entire development team. So those traditional communication methods aren't nearly as effective. A central lock server, while against the principles of DVCS, is the only feasible method for non-mergeable files. As long as DVCS don't have a central lock feature, I think it will keep the company I work for using Subversion. The better solution would be to make a merge tool for all your binary file formats, but that's a longer-term and ongoing goal that will never be "finished". Here's an interesting read on the topic. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/119444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/472/"
]
} |
119,506 | I'm getting a warning from ReSharper about a call to a virtual member from my objects constructor. Why would this be something not to do? | When an object written in C# is constructed, what happens is that the initializers run in order from the most derived class to the base class, and then constructors run in order from the base class to the most derived class ( see Eric Lippert's blog for details as to why this is ). Also in .NET objects do not change type as they are constructed, but start out as the most derived type, with the method table being for the most derived type. This means that virtual method calls always run on the most derived type. When you combine these two facts you are left with the problem that if you make a virtual method call in a constructor, and it is not the most derived type in its inheritance hierarchy, that it will be called on a class whose constructor has not been run, and therefore may not be in a suitable state to have that method called. This problem is, of course, mitigated if you mark your class as sealed to ensure that it is the most derived type in the inheritance hierarchy - in which case it is perfectly safe to call the virtual method. | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/119506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1865/"
]
} |
119,540 | The age old question. Where should you put your business logic, in the database as stored procedures ( or packages ), or in the application/middle tier? And more importantly, Why? Assume database independence is not a goal. | Put enough of the business logic in the database to ensure that the data is consistent and correct. But don't fear having to duplicate some of this logic at another level to enhance the user experience. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/119540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3839/"
]
} |
119,548 | I have created a webservice in .net 2.0, C#. I need to log some information to a file whenever different methods are called by the web service clients. The problem comes when one user process is writing to a file and another process tries to write to it. I get the following error: The process cannot access the file because it is being used by another process. The solutions that I have tried to implement in C# and failed are as below. Implemented singleton class that contains code that writes to a file. Used lock statement to wrap the code that writes to the file. I have also tried to use open source logger log4net but it also is not a perfect solution. I know about logging to system event logger, but I do not have that choice. I want to know if there exists a perfect and complete solution to such a problem? | The locking is probably failing because your webservice is being run by more than one worker process.You could protect the access with a named mutex, which is shared across processes, unlike the locks you get by using lock(someobject) {...} : Mutex lock = new Mutex("mymutex", false);lock.WaitOne();// access filelock.ReleaseMutex(); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/119548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20933/"
]
} |
119,559 | Is there an easy way to programmatically determine the number of lines within a text file? | Seriously belated edit: If you're using .NET 4.0 or later The File class has a new ReadLines method which lazily enumerates lines rather than greedily reading them all into an array like ReadAllLines . So now you can have both efficiency and conciseness with: var lineCount = File.ReadLines(@"C:\file.txt").Count(); Original Answer If you're not too bothered about efficiency, you can simply write: var lineCount = File.ReadAllLines(@"C:\file.txt").Length; For a more efficient method you could do: var lineCount = 0;using (var reader = File.OpenText(@"C:\file.txt")){ while (reader.ReadLine() != null) { lineCount++; }} Edit: In response to questions about efficiency The reason I said the second was more efficient was regarding memory usage, not necessarily speed. The first one loads the entire contents of the file into an array which means it must allocate at least as much memory as the size of the file. The second merely loops one line at a time so it never has to allocate more than one line's worth of memory at a time. This isn't that important for small files, but for larger files it could be an issue (if you try and find the number of lines in a 4GB file on a 32-bit system, for example, where there simply isn't enough user-mode address space to allocate an array this large). In terms of speed I wouldn't expect there to be a lot in it. It's possible that ReadAllLines has some internal optimisations, but on the other hand it may have to allocate a massive chunk of memory. I'd guess that ReadAllLines might be faster for small files, but significantly slower for large files; though the only way to tell would be to measure it with a Stopwatch or code profiler. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/119559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1816/"
]
} |
119,578 | What is the best way to disable the warnings generated via _CRT_SECURE_NO_DEPRECATE that allows them to be reinstated with ease and will work across Visual Studio versions? | If you don't want to pollute your source code (after all this warning presents only with Microsoft compiler), add _CRT_SECURE_NO_WARNINGS symbol to your project settings via "Project"->"Properties"->"Configuration properties"->"C/C++"->"Preprocessor"->"Preprocessor definitions". Also you can define it just before you include a header file which generates this warning.You should add something like this #ifdef _MSC_VER#define _CRT_SECURE_NO_WARNINGS#endif And just a small remark, make sure you understand what this warning stands for, and maybe, if you don't intend to use other compilers than MSVC, consider using safer version of functions i.e. strcpy_s instead of strcpy. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/119578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8516/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.