source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
48,203 | Simply, are there any Java Developer specific Linux distros? | A real Sun geek would chime in here about the virtues of using Solaris as a Java development platform, but I am much more ambivalent. Developing with Java is about the same on any linux distro; you are going to wind up having to install the JDK and tools of your choosing (Eclipse, Sun Studio, Tomcat, etc) so you may as well choose a distro on other criteria... perhaps how comfortable you are with it, how easy package management is, and if the look & feel suit your development habits are all big factors. So, to answer your question more directly, a Java developer would do well with any major linux distro that they are comfortable with using in general. If you want some Java goodness out of the box, Fedora 9 and Ubuntu 8.04 have OpenJDK (and NetBeans) according to a recent announcement . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/48203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4857/"
]
} |
48,235 | I really enjoy Chrome, and the sheer exercise of helping a port would boost my knowledge-base. Where do I start? What are the fundamental similarities and differences between the code which will operated under Windows and Linux? What skills and software do I need? Note: The official website is Visual Studio oriented! Netbeans or Eclipse are my only options. I will not pay Microsoft to help an Open Source project. | EDIT: (2/6/10) A Beta version of Chrome has been released for Linux. Although it is labeled beta, it works great on my Ubuntu box. You can download it from Google: http://www.google.com/chrome?platform=linux EDIT: (5/31/09) Since I answered this question, there have been more new developments in Chrome (actually "Chromium") for Linux: An alpha build has been released. This means it's not fully functional. If you use Ubuntu, you're in luck: add the following lines to your /etc/apt/sources.list deb http://ppa.launchpad.net/chromium-daily/ppa/ubuntu jaunty maindeb-src http://ppa.launchpad.net/chromium-daily/ppa/ubuntu jaunty main Then, at the command line: aptitude updateaptitude install chromium-browser Don't forget to s/jaunty/yourUbuntuVersion/ if necessary. Also, you can s/aptitude/apt-get/, if you insist. And.... Yes , it works. I'm typing this in my freshly installed Chromium browser right now! The build is hosted by launchpad, and gave me some security warnings upon install, which I promptly ignored. Here's the website: https://launchpad.net/~chromium-daily/+archive/ppa The original answer: Linux Build Instructions | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/48235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4857/"
]
} |
48,239 | Is there any way to get the ID of the element that fires an event? I'm thinking something like: $(document).ready(function() { $("a").click(function() { var test = caller.id; alert(test.val()); });}); <script type="text/javascript" src="starterkit/jquery.js"></script><form class="item" id="aaa"> <input class="title"></input></form><form class="item" id="bbb"> <input class="title"></input></form> Except of course that the var test should contain the id "aaa" , if the event is fired from the first form, and "bbb" , if the event is fired from the second form. | In jQuery event.target always refers to the element that triggered the event, where event is the parameter passed to the function. http://api.jquery.com/category/events/event-object/ $(document).ready(function() { $("a").click(function(event) { alert(event.target.id); });}); Note also that this will also work, but that it is not a jQuery object, so if you wish to use a jQuery function on it then you must refer to it as $(this) , e.g.: $(document).ready(function() { $("a").click(function(event) { // this.append wouldn't work $(this).append(" Clicked"); });}); | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/48239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1090/"
]
} |
48,249 | Is there a way to embed a browser in Java? more specifically, is there a library that can emulate a browser? | Since JavaFX 2.0 you can use now webview | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/48249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4857/"
]
} |
48,288 | I've been trying to understand Process.MainWindowHandle . According to MSDN; "The main window is the window that is created when the process is started. After initialization, other windows may be opened, including the Modal and TopLevel windows, but the first window associated with the process remains the main window ." (Emphasis added) But while debugging I noticed that MainWindowHandle seemed to change value... which I wasn't expecting, especially after consulting the documentation above. To confirm the behaviour I created a standalone WinForms app with a timer to check the MainWindowHandle of the "DEVENV" (Visual Studio) process every 100ms. Here's the interesting part of this test app... IntPtr oldHWnd = IntPtr.Zero; void GetMainwindowHandle() { Process[] processes = Process.GetProcessesByName("DEVENV"); if (processes.Length!=1) return; IntPtr newHWnd = processes[0].MainWindowHandle; if (newHWnd != oldHWnd) { oldHWnd = newHWnd; textBox1.AppendText(processes[0].MainWindowHandle.ToString("X")+"\r\n"); } } private void timer1Tick(object sender, EventArgs e) { GetMainwindowHandle(); } You can see the value of MainWindowHandle changing when you (for example) click on a drop-down menu inside VS. Perhaps I've misunderstood the documentation. Can anyone shed light? | @edg, I guess it's an error in MSDN. You can clearly see in Relfector, that "Main window" check in .NET looks like: private bool IsMainWindow(IntPtr handle){ return (!(NativeMethods.GetWindow(new HandleRef(this, handle), 4) != IntPtr.Zero) && NativeMethods.IsWindowVisible(new HandleRef(this, handle)));} When .NET code enumerates windows, it's pretty obvious that first visible window (i.e. top level window) will match this criteria. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/48288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4200/"
]
} |
48,293 | In podcast #15, Jeff mentioned he twittered about how to run a regular event in the background as if it was a normal function - unfortunately I can't seem to find that through twitter. Now I need to do a similar thing and are going to throw the question to the masses. My current plan is when the first user (probably me) enters the site it starts a background thread that waits until the alloted time (hourly on the hour) and then kicks off the event blocking the others (I am a Windows programmer by trade so I think in terms of events and WaitOnMultipleObjects) until it completes. How did Jeff do it in Asp.Net and is his method applicable to the Java web-app world? | I think developing a custom solution for running background tasks doesn't always worth, so I recommend to use the Quartz Scheduler in Java. In your situation (need to run background tasks in a web application) you could use the ServletContextListener included in the distribution to initialize the engine at the startup of your web container . After that you have a number of possibilities to start (trigger) your background tasks (jobs), e.g. you can use Calendars or cron-like expressions. In your situation most probably you should settle with SimpleTrigger that lets you run jobs in fixed, regular intervals. The jobs themselves can be described easily too in Quartz, however you haven't provided any details about what you need to run, so I can't provide a suggestion in that area. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/48293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/342/"
]
} |
48,320 | I'm planning on creating a social networking + MP3 lecture downloading / browsing / commenting / discovery website using Ruby on Rails. Partially for fun and also as a means to learn some Ruby on Rails. I'm looking for a social networking framework that I can use as a basis for my site. I don't want to re-invent the wheel. Searching the web I found three such frameworks. Which of these three would you recommend using and why? http://portal.insoshi.com/ http://www.communityengine.org/ http://lovdbyless.com/ | It depends what your priorities are. If you really want to learn RoR, do it all from scratch . Seriously. Roll your own. It's the best way to learn, far better than hacking through someone else's code. If you do that, sometimes you'll be learning Rails, but sometimes you'll just be learning that specific social network framework. And you won't know which is which... The type of site you're suggesting sounds perfect for a Rails project. If you get stuck, then go browse the repositories of these frameworks. Who cares if you're reinventing the wheel? It's your site, your vision, your rules. If you just want a site up and running, then I would pick Insoshi or LovdbyLess simply because they're out of the box apps so you'll have to do less to do get running. I suggest trying to install them both, and introducing yourself in the Google Groups. That'll give you a good indication of wether you're going to get along. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/48320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5010/"
]
} |
48,426 | My gcc build toolchain produces a .map file. How do I display the memory map graphically? | Here's the beginnings of a script in Python. It loads the map file into a list of Sections and Symbols (first half). It then renders the map using HTML (or do whatever you want with the sections and symbols lists). You can control the script by modifying these lines: with open('t.map') as f:colors = ['9C9F84', 'A97D5D', 'F7DCB4', '5C755E']total_height = 32.0 map2html.py from __future__ import with_statementimport reclass Section: def __init__(self, address, size, segment, section): self.address = address self.size = size self.segment = segment self.section = section def __str__(self): return self.section+""class Symbol: def __init__(self, address, size, file, name): self.address = address self.size = size self.file = file self.name = name def __str__(self): return self.name#===============================# Load the Sections and Symbols#sections = []symbols = []with open('t.map') as f: in_sections = True for line in f: m = re.search('^([0-9A-Fx]+)\s+([0-9A-Fx]+)\s+((\[[ 0-9]+\])|\w+)\s+(.*?)\s*$', line) if m: if in_sections: sections.append(Section(eval(m.group(1)), eval(m.group(2)), m.group(3), m.group(5))) else: symbols.append(Symbol(eval(m.group(1)), eval(m.group(2)), m.group(3), m.group(5))) else: if len(sections) > 0: in_sections = False#===============================# Gererate the HTML File#colors = ['9C9F84', 'A97D5D', 'F7DCB4', '5C755E']total_height = 32.0segments = set()for s in sections: segments.add(s.segment)segment_colors = dict()i = 0for s in segments: segment_colors[s] = colors[i % len(colors)] i += 1total_size = 0for s in symbols: total_size += s.sizesections.sort(lambda a,b: a.address - b.address)symbols.sort(lambda a,b: a.address - b.address)def section_from_address(addr): for s in sections: if addr >= s.address and addr < (s.address + s.size): return s return Noneprint "<html><head>"print " <style>a { color: black; text-decoration: none; font-family:monospace }</style>"print "<body>"print "<table cellspacing='1px'>"for sym in symbols: section = section_from_address(sym.address) height = (total_height/total_size) * sym.size font_size = 1.0 if height > 1.0 else height print "<tr style='background-color:#%s;height:%gem;line-height:%gem;font-size:%gem'><td style='overflow:hidden'>" % \ (segment_colors[section.segment], height, height, font_size) print "<a href='#%s'>%s</a>" % (sym.name, sym.name) print "</td></tr>"print "</table>"print "</body></html>" And here's a bad rendering of the HTML it outputs: | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/48426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445087/"
]
} |
48,442 | Anyone have a good rule of thumb for choosing between different implementations of Java Collection interfaces like List, Map, or Set? For example, generally why or in what cases would I prefer to use a Vector or an ArrayList, a Hashtable or a HashMap? | I really like this cheat sheet from Sergiy Kovalchuk's blog entry, but unfortunately it is offline. However, the Wayback Machine has a historical copy : More detailed was Alexander Zagniotov's flowchart, also offline therefor also a historical copy of the blog : Excerpt from the blog on concerns raised in comments:"This cheat sheet doesn't include rarely used classes like WeakHashMap, LinkedList, etc. because they are designed for very specific or exotic tasks and shouldn't be chosen in 99% cases." | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/48442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1294/"
]
} |
48,458 | I started an application in Google App Engine right when it came out, to play with the technology and work on a pet project that I had been thinking about for a long time but never gotten around to starting. The result is BowlSK . However, as it has grown, and features have been added, it has gotten really difficult to keep things organized - mainly due to the fact that this is my first python project, and I didn't know anything about it until I started working. What I have: Main Level contains: all .py files (didn't know how to make packages work) all .html templates for main level pages Subdirectories: separate folders for css, images, js, etc. folders that hold .html templates for subdirecty-type urls Example: http://www.bowlsk.com/ maps to HomePage (default package), template at "index.html" http://www.bowlsk.com/games/view-series.html?series=7130 maps to ViewSeriesPage (again, default package), template at "games/view-series.html" It's nasty. How do I restructure? I had 2 ideas: Main Folder containing: appdef, indexes, main.py? Subfolder for code. Does this have to be my first package? Subfolder for templates. Folder heirarchy would match package heirarchy Individual subfolders for css, images, js, etc. Main Folder containing appdef, indexes, main.py? Subfolder for code + templates. This way I have the handler class right next to the template, because in this stage, I'm adding lots of features, so modifications to one mean modifications to the other. Again, do I have to have this folder name be the first package name for my classes? I'd like the folder to be "src", but I don't want my classes to be "src.WhateverPage" Is there a best practice? With Django 1.0 on the horizon, is there something I can do now to improve my ability to integrate with it when it becomes the official GAE templating engine? I would simply start trying these things, and seeing which seems better, but pyDev's refactoring support doesn't seem to handle package moves very well, so it will likely be a non-trivial task to get all of this working again. | First, I would suggest you have a look at " Rapid Development with Python, Django, and Google App Engine " GvR describes a general/standard project layout on page 10 of his slide presentation . Here I'll post a slightly modified version of the layout/structure from that page. I pretty much follow this pattern myself. You also mentioned you had trouble with packages. Just make sure each of your sub folders has an __init__.py file. It's ok if its empty. Boilerplate files These hardly vary between projects app.yaml: direct all non-static requests to main.py main.py: initialize app and send it all requests Project lay-out static/*: static files; served directly by App Engine myapp/*.py: app-specific python code views.py, models.py, tests.py, __init__.py, and more templates/*.html: templates (or myapp/templates/*.html) Here are some code examples that may help as well: main.py import wsgiref.handlersfrom google.appengine.ext import webappfrom myapp.views import *application = webapp.WSGIApplication([ ('/', IndexHandler), ('/foo', FooHandler)], debug=True)def main(): wsgiref.handlers.CGIHandler().run(application) myapp/views.py import osimport datetimeimport loggingimport timefrom google.appengine.api import urlfetchfrom google.appengine.ext.webapp import templatefrom google.appengine.api import usersfrom google.appengine.ext import webappfrom models import *class IndexHandler(webapp.RequestHandler): def get(self): date = "foo" # Do some processing template_values = {'data': data } path = os.path.join(os.path.dirname(__file__) + '/../templates/', 'main.html') self.response.out.write(template.render(path, template_values))class FooHandler(webapp.RequestHandler): def get(self): #logging.debug("start of handler") myapp/models.py from google.appengine.ext import dbclass SampleModel(db.Model): I think this layout works great for new and relatively small to medium projects. For larger projects I would suggest breaking up the views and models to have their own sub-folders with something like: Project lay-out static/: static files; served directly by App Engine js/*.js images/*.gif|png|jpg css/*.css myapp/: app structure models/*.py views/*.py tests/*.py templates/*.html: templates | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/48458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/96/"
]
} |
48,470 | Whenever I use a macro in Visual Studio I get an annoying tip balloon in the system tray and an accompanying "pop" sound. It says: Visual Studio .NET macros To stop the macro from running, double-click the spinning cassette. Click here to not show this balloon again. I have trouble clicking the balloon because my macro runs so quickly. Is this controllable by some dialog box option? (I found someone else asking this question on some other site but it's not answered there. I give credit here because I've copied and pasted some pieces from there.) | This will disable the pop up: For Visual Studio 2008: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0 DWORD DontShowMacrosBalloon=6 For Visual Studio 2010 (the DWORD won't be there by default, use New | DWORD value to create it): HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0 DWORD DontShowMacrosBalloon=6 Delete the same key to re-enable it. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/48470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790/"
]
} |
48,474 | I'm a beginner at rails programming, attempting to show many images on a page. Some images are to lay on top of others. To make it simple, say I want a blue square, with a red square in the upper right corner of the blue square (but not tight in the corner). I am trying to avoid compositing (with ImageMagick and similar) due to performance issues. I just want to position overlapping images relative to one another. As a more difficult example, imagine an odometer placed inside a larger image. For six digits, I would need to composite a million different images, or do it all on the fly, where all that is needed is to place the six images on top of the other one. | Ok, after some time, here's what I landed on: .parent { position: relative; top: 0; left: 0;}.image1 { position: relative; top: 0; left: 0; border: 1px red solid;}.image2 { position: absolute; top: 30px; left: 30px; border: 1px green solid;} <div class="parent"> <img class="image1" src="https://via.placeholder.com/50" /> <img class="image2" src="https://via.placeholder.com/100" /></div> As the simplest solution. That is: Create a relative div that is placed in the flow of the page; place the base image first as relative so that the div knows how big it should be; place the overlays as absolutes relative to the upper left of the first image. The trick is to get the relatives and absolutes correct. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/48474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5038/"
]
} |
48,475 | How would you design a database to support the following tagging features: items can have a large number of tags searches for all items that are tagged with a given set of tags must be quick (the items must have ALL tags, so it's an AND-search, not an OR-search) creating/writing items may be slower to enable quick lookup/reading Ideally, the lookup of all items that are tagged with (at least) a set of n given tags should be done using a single SQL statement. Since the number of tags to search for as well as the number of tags on any item are unknown and may be high, using JOINs is impractical. Any ideas? Thanks for all the answers so far. If I'm not mistaken, however, the given answers show how to do an OR-search on tags. (Select all items that have one or more of n tags). I am looking for an efficient AND-search. (Select all items that have ALL n tags - and possibly more.) | About ANDing: It sounds like you are looking for the "relational division" operation. This article covers relational division in concise and yet comprehendible way. About performance: A bitmap-based approach intuitively sounds like it will suit the situation well. However, I'm not convinced it's a good idea to implement bitmap indexing "manually", like digiguru suggests: It sounds like a complicated situation whenever new tags are added(?) But some DBMSes (including Oracle) offer bitmap indexes which may somehow be of use, because a built-in indexing system does away with the potential complexity of index maintenance; additionally, a DBMS offering bitmap indexes should be able to consider them in a proper when when performing the query plan. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/48475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5035/"
]
} |
48,496 | In a few weeks, we'll be teaching a crash course on C++ for Java programmers straight out of college. They have little or no experience yet with C or C++. Previous editions of this course were just 1 or 2 half-day sessions and covered topics including: new language features, e.g. header vs. implementation pointers and references memory management operator overloading templates the standard libraries, e.g. the C library headers basic iostreams basic STL using libraries (headers, linking) they'll be using Linux, so Basic Linux console commands GCC and how to interpret its error messages Makefiles and Autotools basic debugger commands any topic they ask about During the course, each person individually writes, compiles, runs, and debugs simple programs using the newly introduced features. Is this the best way to learn? Which topics do you consider most crucial? Which topics should be added or removed? Which topics just can't be covered adequately in a short time? | I can only once again point to Stroustrup and preach: Don't teach the C subset! It's important, but not for beginners! C++ is complex enough as it is and the standard library classes, especially the STL, is much more important and (at least superficially) easier to understand than the C subset of C++. Same goes for pointers and heap memory allocation, incidentally. Of course they're important but only after having taught the STL containers. Another important concept that new students have to get their head around is the concept of different compilation units, the One Definition Rule (because if you don't know it you won't be able to decypher error messages) and headers. This is actually quite a barrier and one that has to be breached early on. Apart from the language features the most important thing to be taught is how to understand the C++ compiler and how to get help. Getting help (i.e. knowing how to search for the right information) in my experience is the single most important thing that has to be taught about C++. I've had quite good experiences with this order of teaching in the past. /EDIT: If you happen to know any German, take a look at http://madrat.net/coding/cpp/skript , part of a very short introduction used in one of my courses. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/48496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2686/"
]
} |
48,550 | I am trying to publish an Asp.net MVC web application locally using the NAnt and MSBuild. This is what I am using for my NAnt target; <target name="publish-artifacts-to-build"> <msbuild project="my-solution.sln" target="Publish"> <property name="Configuration" value="debug" /> <property name="OutDir" value="builds\" /> <arg line="/m:2 /tv:3.5" /> </msbuild></target> and all I get is this as a response; [msbuild] Skipping unpublishable project. Is it possible to publish web applications via the command line in this way? | The "Publish" target you are trying to invoke is for "OneClick" deployment, not for publishing a website... This is why you are getting the seemingly bizarre message. You would want to use the AspNetCompiler task, rather than the MSBuild task. See http://msdn2.microsoft.com/en-us/library/ms164291.aspx for more info on this task. Your "PublishDir" would correspond to the TargetPath property of the task. Source | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/48550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4642/"
]
} |
48,570 | I would like to implement something similar to a c# delegate method in PHP. A quick word to explain what I'm trying to do overall: I am trying to implement some asynchronous functionality. Basically, some resource-intensive calls that get queued, cached and dispatched when the underlying system gets around to it. When the asynchronous call finally receives a response I would like a callback event to be raised. I am having some problems coming up with a mechanism to do callbacks in PHP. I have come up with a method that works for now but I am unhappy with it. Basically, it involves passing a reference to the object and the name of the method on it that will serve as the callback (taking the response as an argument) and then use eval to call the method when need be. This is sub-optimal for a variety of reasons, is there a better way of doing this that anyone knows of? | (Apart from the observer pattern) you can also use call_user_func() or call_user_func_array() . If you pass an array(obj, methodname) as first parameter it will invoked as $obj->methodname() . <?phpclass Foo { public function bar($x) { echo $x; }}function xyz($cb) { $value = rand(1,100); call_user_func($cb, $value);}$foo = new Foo;xyz( array($foo, 'bar') );?> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/48570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
]
} |
48,605 | Almost every Java book I read talks about using the interface as a way to share state and behaviour between objects that when first "constructed" did not seem to share a relationship. However, whenever I see architects design an application, the first thing they do is start programming to an interface. How come? How do you know all the relationships between objects that will occur within that interface? If you already know those relationships, then why not just extend an abstract class? | Programming to an interface means respecting the "contract" created by using that interface. And so if your IPoweredByMotor interface has a start() method, future classes that implement the interface, be they MotorizedWheelChair , Automobile , or SmoothieMaker , in implementing the methods of that interface, add flexibility to your system, because one piece of code can start the motor of many different types of things, because all that one piece of code needs to know is that they respond to start() . It doesn't matter how they start, just that they must start . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/48605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
48,616 | How do I set a property of a user control in ListView 's LayoutTemplate from the code-behind? <asp:ListView ...><LayoutTemplate><myprefix:MyControl id="myControl" ... /></LayoutTemplate>...</asp:ListView> I want to do this: myControl.SomeProperty = somevalue; Please notice that my control is not in ItemTemplate , it is in LayoutTemplate , so it does not exist for all items, it exists only once. So I should be able to access it once, not for every data bound item. | To set a property of a control that is inside the LayoutTemplate, simply use the FindControl method on the ListView control. var control = (MyControl)myListView.FindControl("myControlId"); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/48616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31505/"
]
} |
48,633 | What is the maximum size for a MySQL table? Is it 2 million at 50GB? 5 million at 80GB? At the higher end of the size scale, do I need to think about compressing the data? Or perhaps splitting the table if it grew too big? | I once worked with a very large (Terabyte+) MySQL database. The largest table we had was literally over a billion rows. It worked. MySQL processed the data correctly most of the time. It was extremely unwieldy though. Just backing up and storing the data was a challenge. It would take days to restore the table if we needed to. We had numerous tables in the 10-100 million row range. Any significant joins to the tables were too time consuming and would take forever. So we wrote stored procedures to 'walk' the tables and process joins against ranges of 'id's. In this way we'd process the data 10-100,000 rows at a time (Join against id's 1-100,000 then 100,001-200,000, etc). This was significantly faster than joining against the entire table. Using indexes on very large tables that aren't based on the primary key is also much more difficult. Mysql stores indexes in two pieces -- it stores indexes (other than the primary index) as indexes to the primary key values. So indexed lookups are done in two parts: First MySQL goes to an index and pulls from it the primary key values that it needs to find, then it does a second lookup on the primary key index to find where those values are. The net of this is that for very large tables (1-200 Million plus rows) indexing against tables is more restrictive. You need fewer, simpler indexes. And doing even simple select statements that are not directly on an index may never come back. Where clauses must hit indexes or forget about it. But all that being said, things did actually work. We were able to use MySQL with these very large tables and do calculations and get answers that were correct. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/48633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/281/"
]
} |
48,642 | I want to write a command that specifies "the word under the cursor" in VIM. For instance, let's say I have the cursor on a word and I make it appear twice. For instance, if the word is "abc" and I want "abcabc" then I could type: :s/\(abc\)/\1\1/ But then I'd like to be able to move the cursor to "def" and use the same command to change it to "defdef": :s/\(def\)/\1\1/ How can I write the command in the commandline so that it does this? :s/\(*whatever is under the commandline*\)/\1\1 | <cword> is the word under the cursor (:help <cword> ). Sorry, I should have been more complete in this answer. You can nmap a command to it, or this series of keystrokes for the lazy will work: b #go to beginning of current wordyw #yank to register Then, when you are typing in your pattern you can hit <control-r>0<enter> which will paste in your command the contents of the 0-th register. You can also make a command for this like: :nmap <leader>w :s/\(<c-r>=expand("<cword>")<cr>\)/ Which will map hitting '\' and 'w' at the same time to replace your command line with :s/\(<currentword>\)/ | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/48642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1084/"
]
} |
48,647 | I came across this article written by Andrei Alexandrescu and Petru Marginean many years ago, which presents and discusses a utility class called ScopeGuard for writing exception-safe code. I'd like to know if coding with these objects truly leads to better code or if it obfuscates error handling, in that perhaps the guard's callback would be better presented in a catch block? Does anyone have any experience using these in actual production code? | It definitely improves your code. Your tentatively formulated claim, that it's obscure and that code would merit from a catch block is simply not true in C++ because RAII is an established idiom. Resource handling in C++ is done by resource acquisition and garbage collection is done by implicit destructor calls. On the other hand, explicit catch blocks would bloat the code and introduce subtle errors because the code flow gets much more complex and resource handling has to be done explicitly. RAII (including ScopeGuard s) isn't an obscure technique in C++ but firmly established best-practice. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/48647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4928/"
]
} |
48,668 | I've seen lots of descriptions how anonymous types work, but I'm not sure how they're really useful. What are some scenarios that anonymous types can be used to address in a well-designed program? | Anonymous types have nothing to do with the design of systems or even at the class level. They're a tool for developers to use when coding. I don't even treat anonymous types as types per-se. I use them mainly as method-level anonymous tuples. If I query the database and then manipulate the results, I would rather create an anonymous type and use that rather than declare a whole new type that will never be used or known outside of the scope of my method. For instance: var query = from item in database.Items // ... select new { Id = item.Id, Name = item.Name };return query.ToDictionary(item => item.Id, item => item.Name); Nobody cares about `a, the anonymous type. It's there so you don't have to declare another class. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/48668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
]
} |
48,680 | Say I have a Textbox nested within a TabControl . When the form loads, I would like to focus on that Textbox (by default the focus is set to the TabControl ). Simply calling textbox1.focus() in the Load event of the form does not appear to work. I have been able to focus it by doing the following: private void frmMainLoad(object sender, EventArgs e) { foreach (TabPage tab in this.tabControl1.TabPages) { this.tabControl1.SelectedTab = tab; } } My question is: Is there a more elegant way to do this? | The following is the solution: private void frmMainLoad(object sender, EventArgs e){ ActiveControl = textBox1;} The better question would however be why... I'm not entirely sure what the answer to that one is. Edit: I suspect it is something to do with the fact that both the form, and the TabControl are containers, but I'm not sure. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/48680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1736/"
]
} |
48,733 | Our design has one jvm that is a jboss/webapp (read/write) that is used to maintain the data via hibernate (using jpa) to the db. The model has 10-15 persistent classes with 3-5 levels of depth in the relationships. We then have a separate jvm that is the server using this data. As it is running continuously we just have one long db session (read only). There is currently no intra-jvm cache involved - so we manually signal one jvm from the other. Now when the webapp changes some data, it signals the server to reload the changed data. What we have found is that we need to tell hibernate to purge the data and then reload it. Just doing a fetch/merge with the db does not do the job - mainly in respect of the objects several layers down the hierarchy. Any thoughts on whether there is anything fundamentally wrong with this design or if anyone is doing this and has had better luck with working with hibernate on the reloads. Thanks,Chris | A Hibernate session loads all data it reads from the DB into what they call the first-level cache . Once a row is loaded from the DB, any subsequent fetches for a row with the same PK will return the data from this cache. Furthermore, Hibernate gaurentees reference equality for objects with the same PK in a single Session. From what I understand, your read-only server application never closes its Hibernate session. So when the DB gets updated by the read-write application, the Session on read-only server is unaware of the change. Effectively, your read-only application is loading an in-memory copy of the database and using that copy, which gets stale in due course. The simplest and best course of action I can suggest is to close and open Sessions as needed. This sidesteps the whole problem. Hibernate Sessions are intended to be a window for a short-lived interaction with the DB. I agree that there is a performance gain by not reloading the object-graph again and again; but you need to measure it and convince yourself that it is worth the pains. Another option is to close and reopen the Session periodically. This ensures that the read-only application works with data not older than a given time interval. But there definitely is a window where the read-only application works with stale data (although the design guarantees that it gets the up-to-date data eventually). This might be permissible in many applications - you need to evaluate your situation. The third option is to use a second level cache implementation, and use short-lived Sessions. There are various caching packages that work with Hibernate with relative merits and demerits. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/48733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/48310/"
]
} |
48,744 | How do you find the phone numbers in 50,000 HTML pages? Jeff Attwood posted 5 Questions for programmers applying for jobs: In an effort to make life simpler for phone screeners, I've put together this list of Five Essential Questions that you need to ask during an SDE screen. They won't guarantee that your candidate will be great, but they will help eliminate a huge number of candidates who are slipping through our process today. 1) Coding The candidate has to write some simple code, with correct syntax, in C, C++, or Java. 2) OO design The candidate has to define basic OO concepts, and come up with classes to model a simple problem. 3) Scripting and regexes The candidate has to describe how to find the phone numbers in 50,000 HTML pages. 4) Data structures The candidate has to demonstrate basic knowledge of the most common data structures. 5) Bits and bytes The candidate has to answer simple questions about bits, bytes, and binary numbers. Please understand: what I'm looking for here is a total vacuum in one of these areas. It's OK if they struggle a little and then figure it out. It's OK if they need some minor hints or prompting. I don't mind if they're rusty or slow. What you're looking for is candidates who are utterly clueless, or horribly confused, about the area in question. >>> The Entirety of Jeff´s Original Post <<< Note: Steve Yegge originally posed the Question. | egrep "(([0-9]{1,2}.)?[0-9]{3}.[0-9]{3}.[0-9]{4})" . -R --include='*.html' | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/48744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4857/"
]
} |
48,755 | In addition, are there any performance advantages to static methods over instance methods? I came across the following recently: http://www.cafeaulait.org/course/week4/22.html : When should a method be static? Neither reads from nor writes to instance fields Independent of the state of the object Mathematical methods that accept arguments, apply an algorithm to those arguments, and return a value Factory methods that serve in lieu of constructors I would be very interested in the feedback of the Stack Overflow community on this. | Make methods static when they are not part of the instance. Don't sweat the micro-optimisations. You might find you have lots of private methods that could be static but you always call from instance methods (or each other). In that case it doesn't really matter that much. However, if you want to actually be able to test your code, and perhaps use it from elsewhere, you might want to consider making those static methods in a different, non-instantiable class. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/48755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3475/"
]
} |
48,772 | I have never "hand-coded" object creation code for SQL Server and foreign key decleration is seemingly different between SQL Server and Postgres. Here is my sql so far: drop table exams;drop table question_bank;drop table anwser_bank;create table exams( exam_id uniqueidentifier primary key, exam_name varchar(50),);create table question_bank( question_id uniqueidentifier primary key, question_exam_id uniqueidentifier not null, question_text varchar(1024) not null, question_point_value decimal, constraint question_exam_id foreign key references exams(exam_id));create table anwser_bank( anwser_id uniqueidentifier primary key, anwser_question_id uniqueidentifier, anwser_text varchar(1024), anwser_is_correct bit); When I run the query I get this error: Msg 8139, Level 16, State 0, Line 9 Number of referencing columns in foreign key differs from number of referenced columns, table 'question_bank'. Can you spot the error? | create table question_bank( question_id uniqueidentifier primary key, question_exam_id uniqueidentifier not null, question_text varchar(1024) not null, question_point_value decimal, constraint fk_questionbank_exams foreign key (question_exam_id) references exams (exam_id)); | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/48772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
]
} |
48,774 | What's the "right" way to do the following as a boolean expression? for i in `ls $1/resources`; do if [ $i != "database.db" ] then if [ $i != "tiles" ] then if [ $i != "map.pdf" ] then if [ $i != "map.png" ] then svn export -q $1/resources/$i ../MyProject/Resources/$i... | The other solutions have a couple of common mistakes: http://www.pixelbeat.org/programming/shell_script_mistakes.html for i in $(ls ...) is redundant/problematicjust do: for i in $1/resources*; do ... [ $i != file1 -a $1 != file2 ] This actually has 2 problems. a. The $i is not quoted, hence names with spaces will cause issues b. -a is inefficient if stat ing files as it doesn't short circuit (I know the above is not stat ing files). So instead try: for i in $1/resources/*; do if [ "$i" != "database.db" ] && [ "$i" != "tiles" ] && [ "$i" != "map.pdf" ] && [ "$i" != "map.png" ]; then svn export -q "$i" "../MyProject/Resources/$(basename $i)" fidone | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/48774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/79/"
]
} |
48,805 | Some e-Marketing tools claim to choose which web page to display based on where you were before. That is, if you've been browsing truck sites and then go to Ford.com, your first page would be of the Ford Explorer. I know you can get the immediate preceding page with HTTP_REFERRER, but how do you know where they were 6 sites ago? | Javascript this should get you started: http://www.dicabrio.com/javascript/steal-history.php There are more nefarius means to: http://ha.ckers.org/blog/20070228/steal-browser-history-without-javascript/ Edit:I wanted to add that although this works it is a sleazy marketing teqnique and an invasion of privacy. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/48805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2757/"
]
} |
48,872 | In Kathleen Dollard's 2008 blog post , she presents an interesting reason to use nested classes in .net. However, she also mentions that FxCop doesn't like nested classes. I'm assuming that the people writing FxCop rules aren't stupid, so there must be reasoning behind that position, but I haven't been able to find it. | Use a nested class when the class you are nesting is only useful to the enclosing class. For instance, nested classes allow you to write something like (simplified): public class SortedMap { private class TreeNode { TreeNode left; TreeNode right; }} You can make a complete definition of your class in one place, you don't have to jump through any PIMPL hoops to define how your class works, and the outside world doesn't need to see anything of your implementation. If the TreeNode class was external, you would either have to make all the fields public or make a bunch of get/set methods to use it. The outside world would have another class polluting their intellisense. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/48872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/100/"
]
} |
48,877 | Ajax , Flex and Silverlight are a few ways to make more interactive web applications. What kinds of factors would you consider when deciding which to use for a new web application? Does any one of them offer better cross-platform compatibility, performance, developer tools or community support? | Here's a quick rundown of each area (with lots of helpful links): Cross-platform compatibility Ajax works in any modern browser that can run JavaScript . Flex requires Flash or anything else that can handle SWF s but, once that's installed, it's a total freeride as far as compatibility. Silverlight is tricky and misunderstood so carefully consider your userbase before going with this MS foray into the rich web applications arms race. Also keep in mind that Silverlight is still in Beta, so it may become more widely used and installed in the future as it is developed. Performance I'm fearful of making too many statements about performance because it really depends on how much you are willing to optimize and the exact nature of your application. Also, some technology stacks are just never going to be very fast. Some people out there have been making comparisons , but again, it depends on a great many factors (even the version of the browser from which you are testing!). It's probably best to choose based on other factors and optimize once you've started to develop. Developer tools There are the "golden standard" dev tools for each of the three: Ajax has basically unlimited options, depending on the rest of your technology and architecture choices. The big questions you're actually faced with are which libraries to rely upon, and Google has voiced a pretty well adopted answer with things like Web Toolkit . When you get right down to it, it's just XML and JavaScript, right? Flex is from Adobe and, just like with Flash development, you'd better stick with their homegrown tools because--well--they're making the standards as they go along. Microsoft has positioned Microsoft Expression Blend versions 2.0 and 2.5 for designing the UI of Silverlight 1.0 and 2 applications respectively. Visual Studio 2008 can be used to develop and debug Silverlight applications ( from Wikipedia ). Community support There is both official and unofficial community, corporate, and open-source support for all three options. Whichever you are already integrated with and which makes you feel most at home are very individual things, but I'll offer this advice: stick with what you know. If you are a MS developer and have MSDN as your homepage, you are probably going to think the Silverlight documentation and forums are really helpful. Flex has a very similar story; the forums are pretty good and if you're a Flash person already, you're going to be right at home with their documentation and user community . On the other hand, Ajax is basically all over the place because you can implement so many different ways and use so many widely-varied libraries. Each library can have it's own forums to visit and mailing lists to lurk within for answers. Once again, all three have corporate giants trying to foster their communities and to get the best support possible to the developers that will give them greater market share in the future. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/48877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
]
} |
48,884 | What Python libraries do folks use for querying Amazon product data? (Amazon Associates Web Service - used to be called E-Commerce API, or something along those lines). Based on my research, PyAWS seems okay, but still pretty raw (and hasn't been updated in a while). Wondering if there's an obvious canonical library that I'm just missing. | I'm using Bottlenose , Dan Loewenherz's "super awesome Python wrapper for the Amazon Product Advertising API". It doesn't parse the XML, so I'm using lxml.objectify : ACCESS_KEY_ID = "..."SECRET_KEY = "..."ASSOC_TAG = "..."import bottlenoseamazon = bottlenose.Amazon(ACCESS_KEY_ID, SECRET_KEY, ASSOC_TAG)response=amazon.ItemLookup(ItemId="B0018AFK38", ResponseGroup="OfferSummary")from lxml import objectifyroot = objectify.fromstring(response)root.Items.Item.OfferSummary.LowestNewPrice.FormattedPrice | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/48884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2678/"
]
} |
48,908 | I am a bit confused about socket programming in C. You create a socket, bind it to an interface and an IP address and get it to listen. I found a couple of web resources on that, and understood it fine. In particular, I found an article Network programming under Unix systems to be very informative. What confuses me is the timing of data arriving on the socket. How can you tell when packets arrive, and how big the packet is, do you have to do all the heavy lifting yourself? My basic assumption here is that packets can be of variable length, so once binary data starts appearing down the socket, how do you begin to construct packets from that? | Short answer is that you have to do all the heavy lifting yourself. You can be notified that there is data available to be read, but you won't know how many bytes are available. In most IP protocols that use variable length packets, there will be a header with a known fixed length prepended to the packet. This header will contain the length of the packet. You read the header, get the length of the packet, then read the packet. You repeat this pattern (read header, then read packet) until communication is complete. When reading data from a socket, you request a certain number of bytes. The read call may block until the requested number of bytes are read, but it can return fewer bytes than what was requested. When this happens, you simply retry the read, requesting the remaining bytes. Here's a typical C function for reading a set number of bytes from a socket: /* buffer points to memory block that is bigger than the number of bytes to be read *//* socket is open socket that is connected to a sender *//* bytesToRead is the number of bytes expected from the sender *//* bytesRead is a pointer to a integer variable that will hold the number of bytes *//* actually received from the sender. *//* The function returns either the number of bytes read, *//* 0 if the socket was closed by the sender, and *//* -1 if an error occurred while reading from the socket */int readBytes(int socket, char *buffer, int bytesToRead, int *bytesRead){ *bytesRead = 0; while(*bytesRead < bytesToRead) { int ret = read(socket, buffer + *bytesRead, bytesToRead - *bytesRead); if(ret <= 0) { /* either connection was closed or an error occurred */ return ret; } else { *bytesRead += ret; } } return *bytesRead;} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/48908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277/"
]
} |
48,916 | I want a splash screen to show while the application is loading. I have a form with a system tray control tied to it. I want the splash screen to display while this form loads, which takes a bit of time since it's accessing a web service API to populate some drop-downs. I also want to do some basic testing for dependencies before loading (that is, the web service is available, the configuration file is readable). As each phase of the startup goes, I want to update the splash screen with progress. I have been reading a lot on threading, but I am getting lost on where this should be controlled from (the main() method?). I am also missing how Application.Run() works, is this where the threads for this should be created from? Now, if the form with the system tray control is the "living" form, should the splash come from there? Wouldn't it not load until the form is completed anyway? I'm not looking for a code handout, more of an algorithm/approach so I can figure this out once and for all :) | Well, for a ClickOnce app that I deployed in the past, we used the Microsoft.VisualBasic namespace to handle the splash screen threading. You can reference and use the Microsoft.VisualBasic assembly from C# in .NET 2.0 and it provides a lot of nice services. Have the main form inherit from Microsoft.VisualBasic.WindowsFormsApplicationBase Override the "OnCreateSplashScreen" method like so: protected override void OnCreateSplashScreen(){ this.SplashScreen = new SplashForm(); this.SplashScreen.TopMost = true;} Very straightforward, it shows your SplashForm (which you need to create) while loading is going on, then closes it automatically once the main form has completed loading. This really makes things simple, and the VisualBasic.WindowsFormsApplicationBase is of course well tested by Microsoft and has a lot of functionality that can make your life a lot easier in Winforms, even in an application that is 100% C#. At the end of the day, it's all IL and bytecode anyway, so why not use it? | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/48916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4246/"
]
} |
48,933 | Does anybody know of a way to list up the "loaded plugins" in Vim ?I know I should be keeping track of this kind of stuff myself butit would always be nice to be able to check the current status. | Not a VIM user myself, so forgive me if this is totally offbase. But according to what I gather from the following VIM Tips site: " where was an option set :scriptnames : list all plugins, _vimrcs loaded (super) :verbose set history? : reveals value of history and where set :function : list functions :func SearchCompl : List particular function | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/48933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4037/"
]
} |
48,934 | I copied some Delphi code from one project to another, and found that it doesn't compile in the new project, though it did in the old one. The code looks something like this: procedure TForm1.CalculateGP(..)const Price : money = 0;begin ... Price := 1.0; ...end; So in the new project, Delphi complains that "left side cannot be assigned to" - understandable! But this code compiles in the old project. So my question is, why ? Is there a compiler switch to allow consts to be reassigned? How does that even work? I thought consts were replaced by their values at compile time? | You need to turn assignable typed constants on.Project -> Options -> Compiler -> Assignable typed Constants Also you can add {$J+} or {$WRITEABLECONST ON} to the pas file, which is probably better, since it'll work even if you move the file to another project. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/48934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369/"
]
} |
48,935 | I'm building an application in C# using WPF. How can I bind to some keys? Also, how can I bind to the Windows key ? | I'm not sure of what you mean by "global" here, but here it goes (I'm assuming you mean a command at the application level, for example, Save All that can be triggered from anywhere by Ctrl + Shift + S .) You find the global UIElement of your choice, for example, the top level window which is the parent of all the controls where you need this binding. Due to "bubbling" of WPF events, events at child elements will bubble all the way up to the root of the control tree. Now, first you need to bind the Key-Combo with a Command using an InputBinding like this you can then hookup the command to your handler (e.g. code that gets called by SaveAll ) via a CommandBinding . For the Windows Key, you use the right Key enumerated member, Key.LWin or Key.RWin public WindowMain(){ InitializeComponent(); // Bind Key var ib = new InputBinding( MyAppCommands.SaveAll, new KeyGesture(Key.S, ModifierKeys.Shift | ModifierKeys.Control)); this.InputBindings.Add(ib); // Bind handler var cb = new CommandBinding( MyAppCommands.SaveAll); cb.Executed += new ExecutedRoutedEventHandler( HandlerThatSavesEverthing ); this.CommandBindings.Add (cb );}private void HandlerThatSavesEverthing (object obSender, ExecutedRoutedEventArgs e){ // Do the Save All thing here.} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/48935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146637/"
]
} |
48,947 | How are callbacks written in PHP? | The manual uses the terms "callback" and "callable" interchangeably, however, "callback" traditionally refers to a string or array value that acts like a function pointer , referencing a function or class method for future invocation. This has allowed some elements of functional programming since PHP 4. The flavors are: $cb1 = 'someGlobalFunction';$cb2 = ['ClassName', 'someStaticMethod'];$cb3 = [$object, 'somePublicMethod'];// this syntax is callable since PHP 5.2.3 but a string containing it// cannot be called directly$cb2 = 'ClassName::someStaticMethod';$cb2(); // fatal error// legacy syntax for PHP 4$cb3 = array(&$object, 'somePublicMethod'); This is a safe way to use callable values in general: if (is_callable($cb2)) { // Autoloading will be invoked to load the class "ClassName" if it's not // yet defined, and PHP will check that the class has a method // "someStaticMethod". Note that is_callable() will NOT verify that the // method can safely be executed in static context. $returnValue = call_user_func($cb2, $arg1, $arg2);} Modern PHP versions allow the first three formats above to be invoked directly as $cb() . call_user_func and call_user_func_array support all the above. See: http://php.net/manual/en/language.types.callable.php Notes/Caveats: If the function/class is namespaced, the string must contain the fully-qualified name. E.g. ['Vendor\Package\Foo', 'method'] call_user_func does not support passing non-objects by reference, so you can either use call_user_func_array or, in later PHP versions, save the callback to a var and use the direct syntax: $cb() ; Objects with an __invoke() method (including anonymous functions) fall under the category "callable" and can be used the same way, but I personally don't associate these with the legacy "callback" term. The legacy create_function() creates a global function and returns its name. It's a wrapper for eval() and anonymous functions should be used instead. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/48947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4960/"
]
} |
48,984 | We're using WatiN for testing our UI, but one page (which is unfortunately not under our teams control) takes forever to finish loading. Is there a way to get WatiN to click a link on the page before the page finishes rendering completely? | Here's the code we found to work: IE browser = new IE(....);browser.Button("SlowPageLoadingButton").ClickNoWait();Link continueLink = browser.Link(Find.ByText("linktext"));continueLink.WaitUntilExists();continueLink.Click(); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/48984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2975/"
]
} |
49,002 | Why prefer composition over inheritance? What trade-offs are there for each approach? When should you choose inheritance over composition? | Prefer composition over inheritance as it is more malleable / easy to modify later, but do not use a compose-always approach. With composition, it's easy to change behavior on the fly with Dependency Injection / Setters. Inheritance is more rigid as most languages do not allow you to derive from more than one type. So the goose is more or less cooked once you derive from TypeA. My acid test for the above is: Does TypeB want to expose the complete interface (all public methods no less) of TypeA such that TypeB can be used where TypeA is expected? Indicates Inheritance . e.g. A Cessna biplane will expose the complete interface of an airplane, if not more. So that makes it fit to derive from Airplane. Does TypeB want only some/part of the behavior exposed by TypeA? Indicates need for Composition. e.g. A Bird may need only the fly behavior of an Airplane. In this case, it makes sense to extract it out as an interface / class / both and make it a member of both classes. Update: Just came back to my answer and it seems now that it is incomplete without a specific mention of Barbara Liskov's Liskov Substitution Principle as a test for 'Should I be inheriting from this type?' | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/49002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
]
} |
49,035 | Given a declaration like this: class A {public: void Foo() const;}; What does it mean? Google turns up this: Member functions should be declared with the const keyword after them if they can operate on a const (this) object. If the function is not declared const, in can not be applied to a const object, and the compiler will give an error message. But I find that somewhat confusing; can anyone out there put it in better terms? Thanks. | Consider a variation of your class A . class A {public: void Foo() const; void Moo();private: int m_nState; // Could add mutable keyword if desired int GetState() const { return m_nState; } void SetState(int val) { m_nState = val; }};const A *A1 = new A();A *A2 = new A();A1->Foo(); // OKA2->Foo(); // OKA1->Moo(); // Error - Not allowed to call non-const function on const object instanceA2->Moo(); // OK The const keyword on a function declaration indicates to the compiler that the function is contractually obligated not to modify the state of A . Thus you are unable to call non- const functions within A::Foo nor change the value of member variables. To illustrate, Foo() may not invoke A::SetState as it is declared non- const , A::GetState however is ok because it is explicitly declared const . The member m_nState may not be changed either unless declared with the keyword mutable . One example of this usage of const is for 'getter' functions to obtain the value of member variables. @1800 Information: I forgot about mutable! The mutable keyword instructs the compiler to accept modifications to the member variable which would otherwise cause a compiler error. It is used when the function needs to modify state but the object is considered logically consistent (constant) regardless of the modification. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/49035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
]
} |
49,046 | Why does n not equal to 8 in the following function? void foo(char cvalue[8]){ int n = sizeof (cvalue);} But n does equal to 8 in this version of the function: void bar(){ char cvalue[8]; int n = sizeof (cvalue);} | Because you can't pass entire arrays as function parameters in C. You're actually passing a pointer to it; the brackets are syntactic sugar. There are no guarantees the array you're pointing to has size 8, since you could pass this function any character pointer you want. // These all do the same thingvoid foo(char cvalue[8])void foo(char cvalue[])void foo(char *cvalue) | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/49046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5065/"
]
} |
49,066 | I have a vs.net project, and after some refactoring, have modified the name of the project. How can I easily rename the underlying windows folder name to match this new project name under a TFS controlled project and solution? Note, I used to be able to do by fiddling with things in the background using SourceSafe ... | Check in all pending changes within the folder and ensure that all other team members to do the same. Ensure that you have a copy of the folder in your working directory (otherwise, you will not have the option to rename the folder in the Source Control Explorer in the next step). Get latest version on the folder to get a copy if you don't already have one. Close the solution . Rename the folder within the Source Control Explorer . This will move all of the files that are tracked in source control from the original folder on your file system to the new one. Note that files not tracked by source control will remain in the original folder - you will probably want to remove this folder once you have confirmed that there are no files there that you need. Open the solution and select ' No ' when prompted to get projects that were newly added to the solution from source control. You will get a warning that one of the projects in the solution could not be loaded. Select the project within Solution Explorer . Note that it will be grayed out and marked as 'Unavailable' . Open the Properties pane. Edit the 'File Path' property either directly or using the ' ... ' button. Note also that this property is only editable in Visual Studio 2010 . In newer versions of Visual Studio, you will need to manually edit the project paths within the solution file. Right-click on the project in the Solution Explore r and select Reload Project from the context menu. If you get an error message saying that the project cannot be loaded from the original folder, try closing the solution, deleting the suo file in the same folder as the solution file then reopening the solution. Check in the changes as a single changeset. Have other team members 'Get latest version' for the solution (right click on the solution within Solution Explorer and select 'Get Latest Version' from the context menu. Note: Other suggested solutions that involve removing and then re-adding the project to the solution will break project references. If you perform these steps then you might also consider renaming the following to suit. Project File Default/Root Namespace Assembly Also, consider modifying the values of the following assembly attributes . AssemblyProductAttribute AssemblyDescriptionAttribute AssemblyTitleAttribute | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/49066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5110/"
]
} |
49,098 | So I have a function that looks something like this: float function(){ float x = SomeValue; return x / SomeOtherValue;} At some point, this function overflows and returns a really large negative value. To try and track down exactly where this was happening, I added a cout statement so that the function looked like this: float function(){ float x = SomeValue; cout << x; return x / SomeOtherValue;} and it worked! Of course, I solved the problem altogether by using a double. But I'm curious as to why the function worked properly when I couted it. Is this typical, or could there be a bug somewhere else that I'm missing? (If it's any help, the value stored in the float is just an integer value, and not a particularly big one. I just put it in a float to avoid casting.) | Welcome to the wonderful world of floating point. The answer you get will likely depend on the floating point model you compiled the code with. This happens because of the difference between the IEEE spec and the hardware the code is running on. Your CPU likely has 80 bit floating point registers that get use to hold the 32-bit float value. This means that there is far more precision while the value stays in a register than when it is forced to a memory address (also known as 'homing' the register). When you passed the value to cout the compiler had to write the floating point to memory, and this results in a lost of precision and interesting behaviour WRT overflow cases. See the MSDN documentation on VC++ floating point switches . You could try compiling with /fp:strict and seeing what happens. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/49098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
]
} |
49,110 | I'm looking for the basic loop like: for(int i = 0; i < MAX; i++) { doSomething(i);} but for Bash. | From this site : for i in $(seq 1 10);do echo $idone | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/49110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3535/"
]
} |
49,134 | I'm looking at using OpenID for my authentication scheme and wanted to know what the best .NET library is to use for MVC specific applications? thx | .Net OpenID project is the best library to use right now that I know of. I think SO used it also. The source includes a sample ASP.NET MVC project using the library. Scott Hanselman did a post on how to use the .Net OpenID project inside of ASP.NET MVC. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/49134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5132/"
]
} |
49,137 | I would like to call python script files from my c++ program. I am not sure that the people I will distribute to will have python installed. | Boost has a python interface library which could help you. Boost.Python | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/49137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
]
} |
49,138 | In SQL Server would a varbinary(16) be the most efficient way of storing an MD5 hash ? Won't be doing anything with it except returning it in a linq query. | Based on the documentation on MSDN and my experience, binary is better, since the md5 hash does not vary in size. The size for a binary data type is n bytes, so the size of the data. The size of a varbinary data type is n bytes + 2 bytes on top of the size of the data. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/49138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2281/"
]
} |
49,146 | I've used several modules to make EXEs for Python, but I'm not sure if I'm doing it right. How should I go about this, and why? Please base your answers on personal experience, and provide references where necessary. | Auto PY to EXE - A .py to .exe converter using a simple graphical interface built using Eel and PyInstaller in Python. py2exe is probably what you want, but it only works on Windows. PyInstaller works on Windows and Linux. Py2app works on the Mac. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/49146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4491/"
]
} |
49,147 | I have just installed C# for the first time, and at first glance it appears to be very similar to VB6. I decided to start off by trying to make a 'Hello, World!' UI Edition. I started in the Form Designer and made a button named "Click Me!" proceeded to double-click it and typed in MessageBox("Hello, World!"); I received the following error: MessageBox is a 'type' but used as a 'variable' Fair enough, it seems in C# MessageBox is an Object. I tried the following MessageBox a = new MessageBox("Hello, World!"); I received the following error:MessageBox does not contain a constructor that takes '1' arguments Now I am stumped. Please help. | MessageBox.Show also returns a DialogResult, which if you put some buttons on there, means you can have it returned what the user clicked. Most of the time I write something like if (MessageBox.Show("Do you want to continue?", "Question", MessageBoxButtons.YesNo) == MessageBoxResult.Yes) { //some interesting behaviour here} which I guess is a bit unwieldy but it gets the job done. See https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.dialogresult for additional enum options you can use here. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/49147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4960/"
]
} |
49,164 | How do I turn a python program into an .egg file? | Setuptools is the software that creates .egg files . It's an extension of the distutils package in the standard library. The process involves creating a setup.py file, then python setup.py bdist_egg creates an .egg package. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/49164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4491/"
]
} |
49,168 | I would like to call Perl script files from my c++ program. I am not sure that the people I will distribute to will have Perl installed. Basically I'm looking for a .lib file that I can use that has an Apache like distribution license. | You can embed perl into your app. Perl Embedding by John Quillan C++ wrapper around Perl C API | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/49168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
]
} |
49,195 | The first language I learnt was PHP, but I have more recently picked up Python. As these are all 'high-level' languages, I have found them a bit difficult to pick up. I also tried to learn Objective-C but I gave up. So, what language should I learn to bridge between Python to C | It's not clear why you need a bridge language. Why don't you start working with C directly? C is a very simple language itself. I think that hardest part for C learner is pointers and everything else related to memory management. Also C lang is oriented on structured programming, so you will need to learn how to implement data structures and algorithms without OOP goodness. Actually, your question is pretty hard, usually people go from low level langs to high level and I can understand frustration of those who goes in other direction. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/49195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2592/"
]
} |
49,196 | Should libraries that the application relies on be stored in source control? One part of me says it should and another part say's no. It feels wrong to add a 20mb library that dwarfs the entire app just because you rely on a couple of functions from it (albeit rather heavily). Should you just store the jar/dll or maybe even the distributed zip/tar of the project? What do other people do? | store everything you will need to build the project 10 years from now.I store the entire zip distribution of any library, just in case Edit for 2017:This answer did not age well:-). If you are still using something old like ant or make, the above still applies. If you use something more modern like maven or graddle (or Nuget on .net for example), with dependency management, you should be running a dependency management server, in addition to your version control server. As long as you have good backups of both, and your dependency management server does not delete old dependencies, you should be ok. For an example of a dependency management server, see for example Sonatype Nexus or JFrog Artifcatory , among many others. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/49196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/342/"
]
} |
49,214 | I need a list of integers from 1 to x where x is set by the user. I could build it with a for loop eg assuming x is an integer set previously: List<int> iList = new List<int>();for (int i = 1; i <= x; i++){ iList.Add(i);} This seems dumb, surely there's a more elegant way to do this, something like the PHP range method | If you're using .Net 3.5, Enumerable.Range is what you need. Generates a sequence of integral numbers within a specified range. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/49214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2975/"
]
} |
49,263 | Here at work, we often need to find a string from the list of strings that is the closest match to some other input string. Currently, we are using Needleman-Wunsch algorithm. The algorithm often returns a lot of false-positives (if we set the minimum-score too low), sometimes it doesn't find a match when it should (when the minimum-score is too high) and, most of the times, we need to check the results by hand. We thought we should try other alternatives. Do you have any experiences with the algorithms?Do you know how the algorithms compare to one another? I'd really appreciate some advice. PS: We're coding in C#, but you shouldn't care about it - I'm asking about the algorithms in general. Oh, I'm sorry I forgot to mention that. No, we're not using it to match duplicate data. We have a list of strings that we are looking for - we call it search-list. And then we need to process texts from various sources (like RSS feeds, web-sites, forums, etc.) - we extract parts of those texts (there are entire sets of rules for that, but that's irrelevant) and we need to match those against the search-list. If the string matches one of the strings in search-list - we need to do some further processing of the thing (which is also irrelevant). We can not perform the normal comparison, because the strings extracted from the outside sources, most of the times, include some extra words etc. Anyway, it's not for duplicate detection. | OK, Needleman-Wunsch(NW) is a classic end-to-end ("global") aligner from the bioinformatics literature. It was long ago available as "align" and "align0" in the FASTA package. The difference was that the "0" version wasn't as biased about avoiding end-gapping, which often allowed favoring high-quality internal matches easier. Smith-Waterman, I suspect you're aware, is a local aligner and is the original basis of BLAST. FASTA had it's own local aligner as well that was slightly different. All of these are essentially heuristic methods for estimating Levenshtein distance relevant to a scoring metric for individual character pairs (in bioinformatics, often given by Dayhoff/"PAM", Henikoff&Henikoff, or other matrices and usually replaced with something simpler and more reasonably reflective of replacements in linguistic word morphology when applied to natural language). Let's not be precious about labels: Levenshtein distance, as referenced in practice at least, is basically edit distance and you have to estimate it because it's not feasible to compute it generally, and it's expensive to compute exactly even in interesting special cases: the water gets deep quick there, and thus we have heuristic methods of long and good repute. Now as to your own problem: several years ago, I had to check the accuracy of short DNA reads against reference sequence known to be correct and I came up with something I called "anchored alignments". The idea is to take your reference string set and "digest" it by finding all locations where a given N-character substring occurs. Choose N so that the table you build is not too big but also so that substrings of length N are not too common. For small alphabets like DNA bases, it's possible to come up with a perfect hash on strings of N characters and make a table and chain the matches in a linked list from each bin. The list entries must identify the sequence and start position of the substring that maps to the bin in whose list they occur. These are "anchors" in the list of strings to be searched at which an NW alignment is likely to be useful. When processing a query string, you take the N characters starting at some offset K in the query string, hash them, look up their bin, and if the list for that bin is nonempty then you go through all the list records and perform alignments between the query string and the search string referenced in the record. When doing these alignments, you line up the query string and the search string at the anchor and extract a substring of the search string that is the same length as the query string and which contains that anchor at the same offset, K. If you choose a long enough anchor length N, and a reasonable set of values of offset K (they can be spread across the query string or be restricted to low offsets) you should get a subset of possible alignments and often will get clearer winners. Typically you will want to use the less end-biased align0-like NW aligner. This method tries to boost NW a bit by restricting it's input and this has a performance gain because you do less alignments and they are more often between similar sequences. Another good thing to do with your NW aligner is to allow it to give up after some amount or length of gapping occurs to cut costs, especially if you know you're not going to see or be interested in middling-quality matches. Finally, this method was used on a system with small alphabets, with K restricted to the first 100 or so positions in the query string and with search strings much larger than the queries (the DNA reads were around 1000 bases and the search strings were on the order of 10000, so I was looking for approximate substring matches justified by an estimate of edit distance specifically). Adapting this methodology to natural language will require some careful thought: you lose on alphabet size but you gain if your query strings and search strings are of similar length. Either way, allowing more than one anchor from different ends of the query string to be used simultaneously might be helpful in further filtering data fed to NW. If you do this, be prepared to possibly send overlapping strings each containing one of the two anchors to the aligner and then reconcile the alignments... or possibly further modify NW to emphasize keeping your anchors mostly intact during an alignment using penalty modification during the algorithm's execution. Hope this is helpful or at least interesting. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/49263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1353085/"
]
} |
49,269 | I have a number of application settings (in user scope) for my custom grid control. Most of them are color settings. I have a form where the user can customize these colors and I want to add a button for reverting to default color settings. How can I read the default settings? For example: I have a user setting named CellBackgroundColor in Properties.Settings . At design time I set the value of CellBackgroundColor to Color.White using the IDE. User sets CellBackgroundColor to Color.Black in my program. I save the settings with Properties.Settings.Default.Save() . User clicks on the Restore Default Colors button. Now, Properties.Settings.Default.CellBackgroundColor returns Color.Black . How do I go back to Color.White ? | @ozgur, Settings.Default.Properties["property"].DefaultValue // initial value from config file Example: string foo = Settings.Default.Foo; // Foo = "Foo" by defaultSettings.Default.Foo = "Boo";Settings.Default.Save();string modifiedValue = Settings.Default.Foo; // modifiedValue = "Boo"string originalValue = Settings.Default.Properties["Foo"].DefaultValue as string; // originalValue = "Foo" | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/49269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/976/"
]
} |
49,274 | I have a string, say '123' , and I want to convert it to the integer 123 . I know you can simply do some_string.to_i , but that converts 'lolipops' to 0 , which is not the effect I have in mind. I want it to blow up in my face when I try to convert something invalid, with a nice and painful Exception . Otherwise, I can't distinguish between a valid 0 and something that just isn't a number at all. EDIT: I was looking for the standard way of doing it, without regex trickery. | Ruby has this functionality built in: Integer('1001') # => 1001 Integer('1001 nights') # ArgumentError: invalid value for Integer: "1001 nights" As noted in answer by Joseph Pecoraro , you might want to watch for strings that are valid non-decimal numbers, such as those starting with 0x for hex and 0b for binary, and potentially more tricky numbers starting with zero that will be parsed as octal. Ruby 1.9.2 added optional second argument for radix so above issue can be avoided: Integer('23') # => 23Integer('0x23') # => 35Integer('023') # => 19Integer('0x23', 10)# => #<ArgumentError: invalid value for Integer: "0x23">Integer('023', 10) # => 23 | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/49274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2018/"
]
} |
49,330 | Is it correct to link a static library (.lib) compiled with VS 2005 with a program which is compiled with VS 2008? Both library and my program are written in C++. This program is run on Windows Mobile 6 Professional emulator. This seems to work, there are no linking errors. However the program crashes during startup because strange things happen inside the linked library. E.g. lib can return a vector of characters with size of big negative number. There are no such problems when the program is compiled with VS 2005. What is even more strange the problem is only when using release configuration for the build. When compiling using debug configuration the problem doesn't occur. | VS2005 and VS2008 use different STL implementations. When the VS2005 code returns a vector, the object has memory layout different from what VS2008 expects. That should be the reason for the broken values you see in the returned date. As a rule of thumb, you should always compile all C++ modules of a project with the same compiler and all settings/#defines equal. One particular #define that causes similar behaviour is the SECURE_SCL #define of VS2008. Two modules compiled with different settings will create exactly your problems, because #defining SECURE_SCL introduces more member variables to various C++ library classes. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/49330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3315/"
]
} |
49,368 | CSS Attribute selectors allow the selection of elements based on attribute values. Unfortunately, I've not used them in years (mainly because they're not supported by all modern browsers). However, I remember distinctly that I was able to use them to adorn all external links with an icon, by using a code similar to the following: a[href=http] { background: url(external-uri); padding-left: 12px;} The above code doesn't work. My question is: How does it work? How do I select all <a> tags whose href attribute starts with "http" ? The official CSS spec (linked above) doesn't even mention that this is possible. But I do remember doing this. ( Note : The obvious solution would be to use class attributes for distinction. I want to avoid this because I have little influence of the way the HTML code is built. All I can edit is the CSS code.) | As for CSS 2.1, see http://www.w3.org/TR/CSS21/selector.html#attribute-selectors Executive summary: Attribute selectors may match in four ways: [att] Match when the element sets the "att" attribute, whatever the value of the attribute. [att=val] Match when the element's "att" attribute value is exactly "val". [att~=val] Match when the element's "att" attribute value is a space-separated list of "words", one of which is exactly "val". If this selector is used, the words in the value must not contain spaces (since they are separated by spaces). [att|=val] Match when the element's "att" attribute value is a hyphen-separated list of "words", beginning with "val". The match always starts at the beginning of the attribute value. This is primarily intended to allow language subcode matches (e.g., the "lang" attribute in HTML) as described in RFC 3066 ([RFC3066]). CSS3 also defines a list of selectors , but the compatibility varies hugely . There's also a nifty test suite that that shows which selectors work in your browser. As for your example, a[href^=http]{ background: url(external-uri); padding-left: 12px;} should do the trick. Unfortunately, it is not supported by IE. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/49368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1968/"
]
} |
49,379 | How do I lock compiled Java classes to prevent decompilation? I know this must be very well discussed topic on the Internet, but I could not come to any conclusion after referring them. Many people do suggest obfuscator, but they just do renaming of classes, methods, and fields with tough-to-remember character sequences but what about sensitive constant values? For example, you have developed the encryption and decryption component based on a password based encryption technique. Now in this case, any average Java person can use JAD to decompile the class file and easily retrieve the password value (defined as constant) as well as salt and in turn can decrypt the data by writing small independent program! Or should such sensitive components be built in native code (for example, VC++) and call them via JNI ? | Some of the more advanced Java bytecode obfuscators do much more than just class name mangling. Zelix KlassMaster , for example, can also scramble your code flow in a way that makes it really hard to follow and works as an excellent code optimizer... Also many of the obfuscators are also able to scramble your string constants and remove unused code. Another possible solution (not necessarily excluding the obfuscation) is to use encrypted JAR files and a custom classloader that does the decryption (preferably using native runtime library). Third (and possibly offering the strongest protection) is to use native ahead of time compilers like GCC or Excelsior JET , for example, that compile your Java code directly to a platform specific native binary. In any case You've got to remember that as the saying goes in Estonian "Locks are for animals". Meaning that every bit of code is available (loaded into memory) during the runtime and given enough skill, determination and motivation, people can and will decompile, unscramble and hack your code... Your job is simply to make the process as uncomfortable as you can and still keep the thing working... | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/49379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/959/"
]
} |
49,403 | I have a filename in a format like: system-source-yyyymmdd.dat I'd like to be able to parse out the different bits of the filename using the "-" as a delimiter. | You can use the cut command to get at each of the 3 'fields', e.g.: $ echo "system-source-yyyymmdd.dat" | cut -d'-' -f2source "-d" specifies the delimiter, "-f" specifies the number of the field you require | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/49403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4003/"
]
} |
49,404 | I have a table containing prices for a lot of different "things" in a MS SQL 2005 table. There are hundreds of records per thing per day and the different things gets price updates at different times. ID uniqueidentifier not null,ThingID int NOT NULL,PriceDateTime datetime NOT NULL,Price decimal(18,4) NOT NULL I need to get today's latest prices for a group of things. The below query works but I'm getting hundreds of rows back and I have to loop trough them and only extract the latest one per ThingID. How can I (e.g. via a GROUP BY) say that I want the latest one per ThingID? Or will I have to use subqueries? SELECT * FROM ThingWHERE ThingID IN (1,2,3,4,5,6) AND PriceDate > cast( convert(varchar(20), getdate(), 106) as DateTime) UPDATE: In an attempt to hide complexity I put the ID column in a an int. In real life it is GUID (and not the sequential kind). I have updated the table def above to use uniqueidentifier. | I think the only solution with your table structure is to work with a subquery: SELECT * FROM Thing WHERE ID IN (SELECT max(ID) FROM Thing WHERE ThingID IN (1,2,3,4) GROUP BY ThingID) (Given the highest ID also means the newest price) However I suggest you add a "IsCurrent" column that is 0 if it's not the latest price or 1 if it is the latest. This will add the possible risk of inconsistent data, but it will speed up the whole process a lot when the table gets bigger (if it is in an index). Then all you need to do is to... SELECT * FROM Thing WHERE ThingID IN (1,2,3,4) AND IsCurrent = 1 UPDATE Okay, Markus updated the question to show that ID is a uniqueid, not an int. That makes writing the query even more complex. SELECT T.* FROM Thing T JOIN (SELECT ThingID, max(PriceDateTime) WHERE ThingID IN (1,2,3,4) GROUP BY ThingID) X ON X.ThingID = T.ThingID AND X.PriceDateTime = T.PriceDateTime WHERE ThingID IN (1,2,3,4) I'd really suggest using either a "IsCurrent" column or go with the other suggestion found in the answers and use "current price" table and a separate "price history" table (which would ultimately be the fastest, because it keeps the price table itself small). (I know that the ThingID at the bottom is redundant. Just try if it is faster with or without that "WHERE". Not sure which version will be faster after the optimizer did its work.) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/49404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008/"
]
} |
49,450 | I'm just about wrapped up on a project where I was using a commercial SVN provider to store the source code. The web host the customer ultimately picked includes a repository as part of the hosting package, so, now that the project is over, I'd like to relocate the repository to their web host and discontinue the commercial account. How would I go about doing this? | If you want to move the repository and keep history, you'll probably need filesystem access on both hosts. The simplest solution, if your backend is FSFS (the default on recent versions), is to make a filesystem copy of the entire repository folder. If you have a Berkley DB backend, if you're not sure of what your backend is, or if you're changing SVN version numbers, you're going to want to use svnadmin to dump your old repository and load it into your new repository. Using svnadmin dump will give you a single file backup that you can copy to the new system. Then you can create the new (empty) repository and use svnadmin load , which will essentially replay all the commits along with its metadata (author, timestamp, etc). You can read more about the dump/load process here: http://svnbook.red-bean.com/en/1.8/svn.reposadmin.maint.html#svn.reposadmin.maint.migrate Also, if you do svnadmin load , make sure you use the --force-uuid option, or otherwise people are going to have problems switching to the new repository. Subversion uses a UUID to identify the repository internally, and it won't let you switch a working copy to a different repository. If you don't have filesystem access, there may be other third party options out there (or you can write something) to help you migrate: essentially you'd have to use the svn log to replay each revision on the new repository, and then fix up the metadata afterwards. You'll need the pre-revprop-change and post-revprop-change hook scripts in place to do this, which sort of assumes filesystem access, so YMMV. Or, if you don't want to keep the history, you can use your working copy to import into the new repository. But hopefully this isn't the case. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/49450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1344/"
]
} |
49,456 | I deleted a branch in TFS and just found out that I need the changes that were on it. How do I recover the branch or the changes done on it? | Specifically in Visual Studio go to "Tools-Options" then Select "Source Control-visual Studio Team Founation Server" and check the "Show deleted items in the Source Control explorer". Having done that - you can then right click a folder and say "Undelete" | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/49456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1583/"
]
} |
49,473 | Is Bouncy Castle API Thread Safe ? Especially, org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipherorg.bouncycastle.crypto.paddings.PKCS7Paddingorg.bouncycastle.crypto.engines.AESFastEngineorg.bouncycastle.crypto.modes.CBCBlockCipher I am planning to write a singleton Spring bean for basic level cryptography support in my app. Since it is a web application, there are greater chances of multiple threads accessing this component at a time. So tread safety is essential here. Please let me know if you have come across such situations using Bouncy Castle. | It really does not matter if the API/Code is thread safe. CBC encryption in itself is not thread safe. Some terminology - E(X) = Enctrypt message XD(X) = Dectrypt X. (Note that D(E(X)) = X)IV = Initialization vector. A random sequence to bootstrap the CBC algorithmCBC = Cipher block chaining. A really simple CBC implementation can look like:P1, P2, P3 = Plain text messages 1. Generate an IV, just random bits.2. Calculate E( P1 xor IV) call this C13. Calculate E( P2 xor C1) call this C24. Calculate E( P3 xor C2) call this C3. As you can see, the result of encrypting P1, P2 and P3 (in that order) is different from encrypting P2, P1 and P3 (in that order). So, in a CBC implementation, order is important. Any algorithm where order is important can not, by definition, be thread safe. You can make a Singleton factory that delivers encryption objects, but you cant trust them to be thread safe. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/49473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/959/"
]
} |
49,478 | Which files should I include in .gitignore when using Git in conjunction with Xcode ? | I was previously using the top-voted answer, but it needs a bit of cleanup, so here it is redone for Xcode 4, with some improvements. I've researched every file in this list, but several of them do not exist in Apple's official Xcode documentation, so I had to go on Apple mailing lists. Apple continues to add undocumented files, potentially corrupting our live projects. This IMHO is unacceptable, and I've now started logging bugs against it each time they do so. I know they don't care, but maybe it'll shame one of them into treating developers more fairly. If you need to customize, here's a gist you can fork: https://gist.github.com/3786883 ########################## .gitignore file for Xcode4 and Xcode5 Source projects## Apple bugs, waiting for Apple to fix/respond:## 15564624 - what does the xccheckout file in Xcode5 do? Where's the documentation?## Version 2.6# For latest version, see: http://stackoverflow.com/questions/49478/git-ignore-file-for-xcode-projects## 2015 updates:# - Fixed typo in "xccheckout" line - thanks to @lyck for pointing it out!# - Fixed the .idea optional ignore. Thanks to @hashier for pointing this out# - Finally added "xccheckout" to the ignore. Apple still refuses to answer support requests about this, but in practice it seems you should ignore it.# - minor tweaks from Jona and Coeur (slightly more precise xc* filtering/names)# 2014 updates:# - appended non-standard items DISABLED by default (uncomment if you use those tools)# - removed the edit that an SO.com moderator made without bothering to ask me# - researched CocoaPods .lock more carefully, thanks to Gokhan Celiker# 2013 updates:# - fixed the broken "save personal Schemes"# - added line-by-line explanations for EVERYTHING (some were missing)## NB: if you are storing "built" products, this WILL NOT WORK,# and you should use a different .gitignore (or none at all)# This file is for SOURCE projects, where there are many extra# files that we want to exclude################################ OS X temporary files that should never be committed## c.f. http://www.westwind.com/reference/os-x/invisibles.html.DS_Store# c.f. http://www.westwind.com/reference/os-x/invisibles.html.Trashes# c.f. http://www.westwind.com/reference/os-x/invisibles.html*.swp## *.lock - this is used and abused by many editors for many different things.# For the main ones I use (e.g. Eclipse), it should be excluded# from source-control, but YMMV.# (lock files are usually local-only file-synchronization on the local FS that should NOT go in git)# c.f. the "OPTIONAL" section at bottom though, for tool-specific variations!## In particular, if you're using CocoaPods, you'll want to comment-out this line:*.lock## profile - REMOVED temporarily (on double-checking, I can't find it in OS X docs?)#profile##### Xcode temporary files that should never be committed# # NB: NIB/XIB files still exist even on Storyboard projects, so we want this...*~.nib##### Xcode build files -## NB: slash on the end, so we only remove the FOLDER, not any files that were badly named "DerivedData"DerivedData/# NB: slash on the end, so we only remove the FOLDER, not any files that were badly named "build"build/###### Xcode private settings (window sizes, bookmarks, breakpoints, custom executables, smart groups)## This is complicated:## SOMETIMES you need to put this file in version control.# Apple designed it poorly - if you use "custom executables", they are# saved in this file.# 99% of projects do NOT use those, so they do NOT want to version control this file.# ..but if you're in the 1%, comment out the line "*.pbxuser"# .pbxuser: http://lists.apple.com/archives/xcode-users/2004/Jan/msg00193.html*.pbxuser# .mode1v3: http://lists.apple.com/archives/xcode-users/2007/Oct/msg00465.html*.mode1v3# .mode2v3: http://lists.apple.com/archives/xcode-users/2007/Oct/msg00465.html*.mode2v3# .perspectivev3: http://stackoverflow.com/questions/5223297/xcode-projects-what-is-a-perspectivev3-file*.perspectivev3# NB: also, whitelist the default ones, some projects need to use these!default.pbxuser!default.mode1v3!default.mode2v3!default.perspectivev3##### Xcode 4 - semi-personal settings## Apple Shared data that Apple put in the wrong folder# c.f. http://stackoverflow.com/a/19260712/153422# FROM ANSWER: Apple says "don't ignore it"# FROM COMMENTS: Apple is wrong; Apple code is too buggy to trust; there are no known negative side-effects to ignoring Apple's unofficial advice and instead doing the thing that actively fixes bugs in Xcode# Up to you, but ... current advice: ignore it.*.xccheckout### OPTION 1: ---------------------------------# throw away ALL personal settings (including custom schemes!# - unless they are "shared")# As per build/ and DerivedData/, this ought to have a trailing slash## NB: this is exclusive with OPTION 2 belowxcuserdata/# OPTION 2: ---------------------------------# get rid of ALL personal settings, but KEEP SOME OF THEM# - NB: you must manually uncomment the bits you want to keep## NB: this *requires* git v1.8.2 or above; you may need to upgrade to latest OS X,# or manually install git over the top of the OS X version# NB: this is exclusive with OPTION 1 above##xcuserdata/**/*# (requires option 2 above): Personal Schemes##!xcuserdata/**/xcschemes/*##### Xcode 4 workspaces - more detailed## Workspaces are important! They are a core feature of Xcode - don't exclude them :)## Workspace layout is quite spammy. For reference:## /(root)/# /(project-name).xcodeproj/# project.pbxproj# /project.xcworkspace/# contents.xcworkspacedata# /xcuserdata/# /(your name)/xcuserdatad/# UserInterfaceState.xcuserstate# /xcshareddata/# /xcschemes/# (shared scheme name).xcscheme# /xcuserdata/# /(your name)/xcuserdatad/# (private scheme).xcscheme# xcschememanagement.plist####### Xcode 4 - Deprecated classes## Allegedly, if you manually "deprecate" your classes, they get moved here.## We're using source-control, so this is a "feature" that we do not want!*.moved-aside##### OPTIONAL: Some well-known tools that people use side-by-side with Xcode / iOS development## NB: I'd rather not include these here, but gitignore's design is weak and doesn't allow# modular gitignore: you have to put EVERYTHING in one file.## COCOAPODS:## c.f. http://guides.cocoapods.org/using/using-cocoapods.html#what-is-a-podfilelock# c.f. http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control##!Podfile.lock## RUBY:## c.f. http://yehudakatz.com/2010/12/16/clarifying-the-roles-of-the-gemspec-and-gemfile/##!Gemfile.lock## IDEA:## c.f. https://www.jetbrains.com/objc/help/managing-projects-under-version-control.html?search=workspace.xml# #.idea/workspace.xml## TEXTMATE:## -- UNVERIFIED: c.f. http://stackoverflow.com/a/50283/153422##tm_build_errors##### UNKNOWN: recommended by others, but I can't discover what these files are# | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/49478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5156/"
]
} |
49,500 | I'm trying to redirect requests for a wildcard domain to a sub-directory. ie. something.blah.example.com --> blah.example.com/something I don't know how to get the subdomain name to use in the rewrite rule. Final Solution: RewriteCond %{HTTP_HOST} !^blah\.example\.comRewriteCond %{HTTP_HOST} ^([^.]+)RewriteRule ^(.*) /%1/$1 [L] Or as pointed out by pilif RewriteCond %{HTTP_HOST} ^([^.]+)\.blah\.example\.com$ | You should have a look at the URL Rewriting Guide from the apache documentation. The following is untested, but it should to the trick: RewriteCond %{HTTP_HOST} ^([^.]+)\.blah\.domain\.com$RewriteRule ^/(.*)$ http://blah.domain.com/%1/$1 [L,R] This only works if the subdomain contains no dots. Otherwise, you'd have to alter the Regexp in RewriteCond to match any character which should still work due to the anchoring, but this certainly feels safer. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/49500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428/"
]
} |
49,510 | How do you set your Cocoa application as the default web browser? I want to create an application that is launched by default when the user clicks on an HTTP or HTTPS link in other applications (Mail, iChat etc.). | There are four steps to making an app that can act as the default web browser. The first three steps allow your app to act as a role handler for the relevant URL schemes (HTTP and HTTPS) and the final step makes it the default role handler for those schemes. 1) Add the URL schemes your app can handle to your application's info.plist file To add support for http:// and https:// you'd need to add the following to your application's info.plist file. This tells the OS that your application is capable of handling HTTP and HTTP URLs. <key>CFBundleURLTypes</key><array> <dict> <key>CFBundleURLName</key> <string>http URL</string> <key>CFBundleURLSchemes</key> <array> <string>http</string> </array> </dict> <dict> <key>CFBundleURLName</key> <string>Secure http URL</string> <key>CFBundleURLSchemes</key> <array> <string>https</string> </array> </dict></array> 2) Write an URL handler method This method will be called by the OS when it wants to use your application to open a URL. It doesn't matter which object you add this method to, that'll be explicitly passed to the Event Manager in the next step. The URL handler method should look something like this: - (void)getUrl:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent{ // Get the URL NSString *urlStr = [[event paramDescriptorForKeyword:keyDirectObject] stringValue]; //TODO: Your custom URL handling code here} 3) Register the URL handler method Next, tell the event manager which object and method to call when it wants to use your app to load an URL. In the code here I'm passed self as the event handler, assuming that we're calling setEventHandler from the same object that defines the getUrl:withReplyEvent: method. You should add this code somewhere in your application's initialisation code. NSAppleEventManager *em = [NSAppleEventManager sharedAppleEventManager];[em setEventHandler:self andSelector:@selector(getUrl:withReplyEvent:) forEventClass:kInternetEventClass andEventID:kAEGetURL]; Some applications, including early versions of Adobe AIR, use the alternative WWW!/OURL AppleEvent to request that an application opens URLs, so to be compatible with those applications you should also add the following: [em setEventHandler:self andSelector:@selector(getUrl:withReplyEvent:) forEventClass:'WWW!' andEventID:'OURL']; 4) Set your app as the default browser Everything we've done so far as told the OS that your application is a browser , now we need to make it the default browser . We've got to use the Launch Services API to do this. In this case we're setting our app to be the default role handler for HTTP and HTTPS links: CFStringRef bundleID = (CFStringRef)[[NSBundle mainBundle] bundleIdentifier];OSStatus httpResult = LSSetDefaultHandlerForURLScheme(CFSTR("http"), bundleID);OSStatus httpsResult = LSSetDefaultHandlerForURLScheme(CFSTR("https"), bundleID);//TODO: Check httpResult and httpsResult for errors (It's probably best to ask the user's permission before changing their default browser.) Custom URL schemes It's worth noting that you can also use these same steps to handle your own custom URL schemes. If you're creating a custom URL scheme it's a good idea to base it on your app's bundle identifier to avoid clashes with other apps. So if your bundle ID is com.example.MyApp you should consider using x-com-example-myapp:// URLs. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/49510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5168/"
]
} |
49,536 | You find plenty of tutorials on menu bars in HTML, but for this specific (though IMHO generic) case, I haven't found any decent solution: # THE MENU ITEMS SHOULD BE JUSTIFIED JUST AS PLAIN TEXT WOULD BE ## ^ ^ # There's an varying number of text-only menu items and the page layout is fluid. The first menu item should be left-aligned, the last menu item should be right-aligned. The remaining items should be spread optimally on the menu bar. The number is varying,so there's no chance to pre-calculate the optimal widths. Note that a TABLE won't work here as well: If you center all TDs, the first and the last item aren’t aligned correctly. If you left-align and right-align the first resp. the last items, the spacing will be sub-optimal. Isn’t it strange that there is no obvious way to implement this in a clean way by using HTML and CSS? | The simplest thing to do is to is to force the line to break by inserting an element at the end of the line that will occupy more than the left available space and then hiding it. I've accomplished this quite easily with a simple span element like so: #menu { text-align: justify;}#menu * { display: inline;}#menu li { display: inline-block;}#menu span { display: inline-block; position: relative; width: 100%; height: 0;} <div id="menu"> <ul> <li><a href="#">Menu item 1</a></li> <li><a href="#">Menu item 3</a></li> <li><a href="#">Menu item 2</a></li> </ul> <span></span></div> All the junk inside the #menu span selector is (as far as I've found) required to please most browsers. It should force the width of the span element to 100%, which should cause a line break since it is considered an inline element due to the display: inline-block rule. inline-block also makes the span possible to block-level style rules like width which causes the element to not fit in line with the menu and thus the menu to line-break. You of course need to adjust the width of the span to your use case and design, but I hope you get the general idea and can adapt it. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/49536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3377/"
]
} |
49,547 | Our investigations have shown us that not all browsers respect the HTTP cache directives in a uniform manner. For security reasons we do not want certain pages in our application to be cached, ever, by the web browser. This must work for at least the following browsers: Internet Explorer 6+ Firefox 1.5+ Safari 3+ Opera 9+ Chrome Our requirement came from a security test. After logging out from our website you could press the back button and view cached pages. | Introduction The correct minimum set of headers that works across all mentioned clients (and proxies): Cache-Control: no-cache, no-store, must-revalidatePragma: no-cacheExpires: 0 The Cache-Control is per the HTTP 1.1 spec for clients and proxies (and implicitly required by some clients next to Expires ). The Pragma is per the HTTP 1.0 spec for prehistoric clients. The Expires is per the HTTP 1.0 and 1.1 specs for clients and proxies. In HTTP 1.1, the Cache-Control takes precedence over Expires , so it's after all for HTTP 1.0 proxies only. If you don't care about IE6 and its broken caching when serving pages over HTTPS with only no-store , then you could omit Cache-Control: no-cache . Cache-Control: no-store, must-revalidatePragma: no-cacheExpires: 0 If you don't care about IE6 nor HTTP 1.0 clients (HTTP 1.1 was introduced in 1997), then you could omit Pragma . Cache-Control: no-store, must-revalidateExpires: 0 If you don't care about HTTP 1.0 proxies either, then you could omit Expires . Cache-Control: no-store, must-revalidate On the other hand, if the server auto-includes a valid Date header, then you could theoretically omit Cache-Control too and rely on Expires only. Date: Wed, 24 Aug 2016 18:32:02 GMTExpires: 0 But that may fail if e.g. the end-user manipulates the operating system date and the client software is relying on it. Other Cache-Control parameters such as max-age are irrelevant if the abovementioned Cache-Control parameters are specified. The Last-Modified header as included in most other answers here is only interesting if you actually want to cache the request, so you don't need to specify it at all. How to set it? Using PHP: header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.header("Pragma: no-cache"); // HTTP 1.0.header("Expires: 0"); // Proxies. Using Java Servlet, or Node.js: response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.response.setHeader("Pragma", "no-cache"); // HTTP 1.0.response.setHeader("Expires", "0"); // Proxies. Using ASP.NET-MVC Response.Cache.SetCacheability(HttpCacheability.NoCache); // HTTP 1.1.Response.Cache.AppendCacheExtension("no-store, must-revalidate");Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.Response.AppendHeader("Expires", "0"); // Proxies. Using ASP.NET Web API: // `response` is an instance of System.Net.Http.HttpResponseMessageresponse.Headers.CacheControl = new CacheControlHeaderValue{ NoCache = true, NoStore = true, MustRevalidate = true};response.Headers.Pragma.ParseAdd("no-cache");// We can't use `response.Content.Headers.Expires` directly// since it allows only `DateTimeOffset?` values.response.Content?.Headers.TryAddWithoutValidation("Expires", 0.ToString()); Using ASP.NET: Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.Response.AppendHeader("Expires", "0"); // Proxies. Using ASP.NET Core v3 // using Microsoft.Net.Http.HeadersResponse.Headers[HeaderNames.CacheControl] = "no-cache, no-store, must-revalidate";Response.Headers[HeaderNames.Expires] = "0";Response.Headers[HeaderNames.Pragma] = "no-cache"; Using ASP: Response.addHeader "Cache-Control", "no-cache, no-store, must-revalidate" ' HTTP 1.1.Response.addHeader "Pragma", "no-cache" ' HTTP 1.0.Response.addHeader "Expires", "0" ' Proxies. Using Ruby on Rails: headers["Cache-Control"] = "no-cache, no-store, must-revalidate" # HTTP 1.1.headers["Pragma"] = "no-cache" # HTTP 1.0.headers["Expires"] = "0" # Proxies. Using Python/Flask: response = make_response(render_template(...))response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" # HTTP 1.1.response.headers["Pragma"] = "no-cache" # HTTP 1.0.response.headers["Expires"] = "0" # Proxies. Using Python/Django: response["Cache-Control"] = "no-cache, no-store, must-revalidate" # HTTP 1.1.response["Pragma"] = "no-cache" # HTTP 1.0.response["Expires"] = "0" # Proxies. Using Python/Pyramid: request.response.headerlist.extend( ( ('Cache-Control', 'no-cache, no-store, must-revalidate'), ('Pragma', 'no-cache'), ('Expires', '0') )) Using Go: responseWriter.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") // HTTP 1.1.responseWriter.Header().Set("Pragma", "no-cache") // HTTP 1.0.responseWriter.Header().Set("Expires", "0") // Proxies. Using Clojure (require Ring utils): (require '[ring.util.response :as r])(-> response (r/header "Cache-Control" "no-cache, no-store, must-revalidate") (r/header "Pragma" "no-cache") (r/header "Expires" 0)) Using Apache .htaccess file: <IfModule mod_headers.c> Header set Cache-Control "no-cache, no-store, must-revalidate" Header set Pragma "no-cache" Header set Expires 0</IfModule> Using HTML: <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate"><meta http-equiv="Pragma" content="no-cache"><meta http-equiv="Expires" content="0"> HTML meta tags vs HTTP response headers Important to know is that when an HTML page is served over an HTTP connection, and a header is present in both the HTTP response headers and the HTML <meta http-equiv> tags, then the one specified in the HTTP response header will get precedence over the HTML meta tag. The HTML meta tag will only be used when the page is viewed from a local disk file system via a file:// URL. See also W3 HTML spec chapter 5.2.2 . Take care with this when you don't specify them programmatically because the webserver can namely include some default values. Generally, you'd better just not specify the HTML meta tags to avoid confusion by starters and rely on hard HTTP response headers. Moreover, specifically those <meta http-equiv> tags are invalid in HTML5. Only the http-equiv values listed in HTML5 specification are allowed. Verifying the actual HTTP response headers To verify the one and the other, you can see/debug them in the HTTP traffic monitor of the web browser's developer toolset. You can get there by pressing F12 in Chrome/Firefox23+/IE9+, and then opening the "Network" or "Net" tab panel, and then clicking the HTTP request of interest to uncover all detail about the HTTP request and response. The below screenshot is from Chrome: I want to set those headers on file downloads too First of all, this question and answer are targeted on "web pages" (HTML pages), not "file downloads" (PDF, zip, Excel, etc). You'd better have them cached and make use of some file version identifier somewhere in the URI path or query string to force a redownload on a changed file. When applying those no-cache headers on file downloads anyway, then beware of the IE7/8 bug when serving a file download over HTTPS instead of HTTP. For detail, see IE cannot download foo.jsf. IE was not able to open this internet site. The requested site is either unavailable or cannot be found . | {
"score": 13,
"source": [
"https://Stackoverflow.com/questions/49547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5182/"
]
} |
49,596 | What is the difference between char str1[32] = "\0"; and char str2[32] = ""; | Since you already declared the sizes, the two declarations are exactly equal. However, if you do not specify the sizes, you can see that the first declaration makes a larger string: char a[] = "a\0";char b[] = "a";printf("%i %i\n", sizeof(a), sizeof(b)); prints 3 2 This is because a ends with two nulls (the explicit one and the implicit one) while b ends only with the implicit one. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/49596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123/"
]
} |
49,601 | I'm trying to find a source control for my own personal use that's as simple as possible. The main feature I need is being able to read/pull a past version of my code. I am the only developer. I've looked at a lot of different version control systems, but they all seem way more complicated than I need. I need one that's simple, runs under Windows, and doesn't expose itself to the network. Specifically, the version control system should not require exposing an HTTP interface, it should interact with the local filesystem only. It just needs to be a version control system geared for one guy and one guy only. Graphical UI is a plus. Does anyone know of software would satisfy what I'm looking for? Thanks! -Mike | Subversion is great -- you can run the server yourself or use something like assembla.com to host your code (although that exposes it to the network). There are numerous gui applications like tortoise svn that would allow you to interact w/ the source control repo | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/49601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5198/"
]
} |
49,652 | Can someone suggest some good automated test suite framework for Perl? | It really depends on what you're trying to do, but here's some background for much of this. First, you would generally write your test programs with Test::More or Test::Simple as the core testing program: use Test::More tests => 2;is 3, 3, 'basic equality should work';ok !0, '... and zero should be false'; Internally, Test::Builder is called to output those test results as TAP ( Test Anything Protocol ). Test::Harness (a thin wrapper around TAP::Harness), reads and interprets the TAP, telling you if your tests passed or failed. The "prove" tool mentioned above is bundled with Test::Harness, so let's say that save the above in the t/ directory (the standard Perl testing directory) as "numbers.t", then you can run it with this command: prove --verbose t/numbers.t Or to run all tests in that directory (recursively, assuming you want to descend into subdirectories): prove --verbose -r t/ (--verbose, of course, is optional). As a side note, don't use TestUnit. Many people recommend it, but it was abandoned a long time ago and doesn't integrate with modern testing tools. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/49652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4406/"
]
} |
49,724 | Is it possible to extract all of the VBA code from a Word 2007 "docm" document using the API? I have found how to insert VBA code at runtime, and how to delete all VBA code, but not pull the actual code out into a stream or string that I can store (and insert into other documents in the future). Any tips or resources would be appreciated. Edit : thanks to everyone, Aardvark 's answer was exactly what I was looking for. I have converted his code to C#, and was able to call it from a class library using Visual Studio 2008. using Microsoft.Office.Interop.Word;using Microsoft.Vbe.Interop;...public List<string> GetMacrosFromDoc(){ Document doc = GetWordDoc(@"C:\Temp\test.docm"); List<string> macros = new List<string>(); VBProject prj; CodeModule code; string composedFile; prj = doc.VBProject; foreach (VBComponent comp in prj.VBComponents) { code = comp.CodeModule; // Put the name of the code module at the top composedFile = comp.Name + Environment.NewLine; // Loop through the (1-indexed) lines for (int i = 0; i < code.CountOfLines; i++) { composedFile += code.get_Lines(i + 1, 1) + Environment.NewLine; } // Add the macro to the list macros.Add(composedFile); } CloseDoc(doc); return macros;} | You'll have to add a reference to Microsoft Visual Basic for Applications Extensibility 5.3 (or whatever version you have). I have the VBA SDK and such on my box - so this may not be exactly what office ships with. Also you have to enable access to the VBA Object Model specifically - see the "Trust Center" in Word options. This is in addition to all the other Macro security settings Office provides. This example will extract code from the current document it lives in - it itself is a VBA macro (and will display itself and any other code as well). There is also a Application.vbe.VBProjects collection to access other documents. While I've never done it, I assume an external application could get to open files using this VBProjects collection as well. Security is funny with this stuff so it may be tricky. I also wonder what the docm file format is now - XML like the docx? Would that be a better approach? Sub GetCode() Dim prj As VBProject Dim comp As VBComponent Dim code As CodeModule Dim composedFile As String Dim i As Integer Set prj = ThisDocument.VBProject For Each comp In prj.VBComponents Set code = comp.CodeModule composedFile = comp.Name & vbNewLine For i = 1 To code.CountOfLines composedFile = composedFile & code.Lines(i, 1) & vbNewLine Next MsgBox composedFile NextEnd Sub | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/49724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2194/"
]
} |
49,737 | Recently I was talking to a co-worker about C++ and lamented that there was no way to take a string with the name of a class field and extract the field with that name; in other words, it lacks reflection. He gave me a baffled look and asked when anyone would ever need to do such a thing. Off the top of my head I didn't have a good answer for him, other than "hey, I need to do it right now". So I sat down and came up with a list of some of the things I've actually done with reflection in various languages. Unfortunately, most of my examples come from my web programming in Python, and I was hoping that the people here would have more examples. Here's the list I came up with: Given a config file with lines like x = "Hello World!" y = 5.0 dynamically set the fields of some config object equal to the values in that file. (This was what I wished I could do in C++, but actually couldn't do.) When sorting a list of objects, sort based on an arbitrary attribute given that attribute's name from a config file or web request. When writing software that uses a network protocol, reflection lets you call methods based on string values from that protocol. For example, I wrote an IRC bot that would translate !some_command arg1 arg2 into a method call actions.some_command(arg1, arg2) and print whatever that function returned back to the IRC channel. When using Python's __getattr__ function (which is sort of like method_missing in Ruby/Smalltalk) I was working with a class with a whole lot of statistics, such as late_total. For every statistic, I wanted to be able to add _percent to get that statistic as a percentage of the total things I was counting (for example, stats.late_total_percent). Reflection made this very easy. So can anyone here give any examples from their own programming experiences of times when reflection has been helpful? The next time a co-worker asks me why I'd "ever want to do something like that" I'd like to be more prepared. | I can list following usage for reflection: Late binding Security (introspect code for security reasons) Code analysis Dynamic typing (duck typing is not possible without reflection) Metaprogramming Some real-world usages of reflection from my personal experience: Developed plugin system based on reflection Used aspect-oriented programming model Performed static code analysis Used various Dependency Injection frameworks ... Reflection is good thing :) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/49737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1694/"
]
} |
49,755 | I'm writing a structural modeling tool for a civil enginering application. I have one huge model class representing the entire building, which include collections of nodes, line elements, loads, etc. which are also custom classes. I have already coded an undo engine which saves a deep-copy after each modification to the model. Now I started thinking if I could have coded differently. Instead of saving the deep-copies, I could perhaps save a list of each modifier action with a corresponding reverse modifier. So that I could apply the reverse modifiers to the current model to undo, or the modifiers to redo. I can imagine how you would carry out simple commands that change object properties, etc. But how about complex commands? Like inserting new node objects to the model and adding some line objects which keep references to the new nodes. How would one go about implementing that? | Most examples I've seen use a variant of the Command-Pattern for this. Every user-action that's undoable gets its own command instance with all the information to execute the action and roll it back. You can then maintain a list of all the commands that have been executed and you can roll them back one by one. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/49755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/976/"
]
} |
49,824 | Besides the dynamic nature of Python (and the syntax), what are some of the major features of the Python language that Java doesn't have, and vice versa? | List comprehensions. I often find myself filtering/mapping lists, and being able to say [line.replace("spam","eggs") for line in open("somefile.txt") if line.startswith("nee")] is really nice. Functions are first class objects. They can be passed as parameters to other functions, defined inside other function, and have lexical scope. This makes it really easy to say things like people.sort(key=lambda p: p.age) and thus sort a bunch of people on their age without having to define a custom comparator class or something equally verbose. Everything is an object. Java has basic types which aren't objects, which is why many classes in the standard library define 9 different versions of functions (for boolean, byte, char, double, float, int, long, Object, short). Array.sort is a good example. Autoboxing helps, although it makes things awkward when something turns out to be null. Properties. Python lets you create classes with read-only fields, lazily-generated fields, as well as fields which are checked upon assignment to make sure they're never 0 or null or whatever you want to guard against, etc.' Default and keyword arguments. In Java if you want a constructor that can take up to 5 optional arguments, you must define 6 different versions of that constructor. And there's no way at all to say Student(name="Eli", age=25) Functions can only return 1 thing. In Python you have tuple assignment, so you can say spam, eggs = nee() but in Java you'd need to either resort to mutable out parameters or have a custom class with 2 fields and then have two additional lines of code to extract those fields. Built-in syntax for lists and dictionaries. Operator Overloading. Generally better designed libraries. For example, to parse an XML document in Java, you say Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("test.xml"); and in Python you say doc = parse("test.xml") Anyway, I could go on and on with further examples, but Python is just overall a much more flexible and expressive language. It's also dynamically typed, which I really like, but which comes with some disadvantages. Java has much better performance than Python and has way better tool support. Sometimes those things matter a lot and Java is the better language than Python for a task; I continue to use Java for some new projects despite liking Python a lot more. But as a language I think Python is superior for most things I find myself needing to accomplish. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/49824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4223/"
]
} |
49,870 | I have a basic cs-major understanding of multi-threading but have never had to do anything beyond simple timers in an application. Does anyone know of a good resource that will give me a tour how to work with multi-threaded applications, explaining the basics and maybe posing some of the more difficult stuff? | This is a great free resource by Joseph Albahari. Threading in C# | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/49870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
]
} |
49,883 | Say I have this given XML file: <root> <node>x</node> <node>y</node> <node>a</node></root> And I want the following to be displayed: ayx Using something similar to: <xsl:template match="/"> <xsl:apply-templates select="root/node"/></xsl:template><xsl:template match="node"> <xsl:value-of select="."/></xsl:template> | Easy! <xsl:template match="/"> <xsl:apply-templates select="root/node"> <xsl:sort select="position()" data-type="number" order="descending"/> </xsl:apply-templates></xsl:template><xsl:template match="node"> <xsl:value-of select="."/></xsl:template> | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/49883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1532/"
]
} |
49,890 | I created a few mediawiki custom tags, using the guide found here http://www.mediawiki.org/wiki/Manual:Tag_extensions I will post my code below, but the problem is after it hits the first custom tag in the page, it calls it, and prints the response, but does not get anything that comes after it in the wikitext. It seems it just stops parsing the page. Any Ideas? if ( defined( 'MW_SUPPORTS_PARSERFIRSTCALLINIT' ) ) { $wgHooks['ParserFirstCallInit'][] = 'tagregister';} else { // Otherwise do things the old fashioned way $wgExtensionFunctions[] = 'tagregister';}function tagregister(){ global $wgParser; $wgParser->setHook('tag1','tag1func'); $wgParser->setHook('tag2','tag2func'); return true;}function tag1func($input,$params){ return "It called me";}function tag2func($input,$params){ return "It called me -- 2";} Update: @George Mauer -- I have seen that as well, but this does not stop the page from rendering, just the Mediawiki engine from parsing the rest of the wikitext. Its as if hitting the custom function is signaling mediawiki that processing is done. I am in the process of diving into the rabbit hole but was hoping someone else has seen this behavior. | Easy! <xsl:template match="/"> <xsl:apply-templates select="root/node"> <xsl:sort select="position()" data-type="number" order="descending"/> </xsl:apply-templates></xsl:template><xsl:template match="node"> <xsl:value-of select="."/></xsl:template> | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/49890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/673/"
]
} |
49,900 | We have an Apache ANT script to build our application, then check in the resulting JAR file into version control (VSS in this case). However, now we have a change that requires us to build 2 JAR files for this project, then check both into VSS. The current target that checks the original JAR file into VSS discovers the name of the JAR file through some property. Is there an easy way to "generalize" this target so that I can reuse it to check in a JAR file with any name? In a normal language this would obviously call for a function parameter but, to my knowledge, there really isn't an equivalent concept in ANT. | I would suggest to work with macros over subant/antcall because the main advantage I found with macros is that you're in complete control over the properties that are passed to the macro (especially if you want to add new properties). You simply refactor your Ant script starting with your target: <target name="vss.check"> <vssadd localpath="D:\build\build.00012.zip" comment="Added by automatic build"/></target> creating a macro (notice the copy/paste and replacement with the @{file}): <macrodef name="private-vssadd"> <attribute name="file"/> <sequential> <vssadd localpath="@{file}" comment="Added by automatic build"/> </sequential></macrodef> and invoke the macros with your files: <target name="vss.check"> <private-vssadd file="D:\build\File1.zip"/> <private-vssadd file="D:\build\File2.zip"/></target> Refactoring, "the Ant way" | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/49900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1471/"
]
} |
49,912 | We are using JetBrains ' dotTrace . What other profiling tools can be recommended that are better for profiling C# Windows Forms applications? | No. I have tried pretty much every .NET profiler on the market (ANTS, vTune, OptimizeIt, DevPartner, YourKit), and in my opinion dotTrace is the best of the lot. It is one of only two profilers I have used (the other being YourKit) that has low enough overhead to handle a highly CPU-intensive application. If and only if your application is relatively light, I could recommend ANTS Profiler . Its line-by-line stats are sometimes quite useful, but they come at a price in profiling efficiency. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/49912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
]
} |
49,919 | I am looking for a Regular expression to match only if a date is in the first 28 days of the month. This is for my validator control in ASP.NET | Don't do this with Regex. Dates are formatted differently in different countries. Use the DateTime.TryParse routine instead: DateTime parsedDate;if ( DateTime.TryParse( dateString, out parsedDate) && parsedDate.Day <= 28 ){ // logic goes here.} Regex is nearly the golden hammer of input validation, but in this instance, it's the wrong choice. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/49919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
]
} |
49,925 | What is the difference between UNION and UNION ALL ? | UNION removes duplicate records (where all columns in the results are the same), UNION ALL does not. There is a performance hit when using UNION instead of UNION ALL , since the database server must do additional work to remove the duplicate rows, but usually you do not want the duplicates (especially when developing reports). To identify duplicates, records must be comparable types as well as compatible types. This will depend on the SQL system. For example the system may truncate all long text fields to make short text fields for comparison (MS Jet), or may refuse to compare binary fields (ORACLE) UNION Example: SELECT 'foo' AS bar UNION SELECT 'foo' AS bar Result: +-----+| bar |+-----+| foo |+-----+1 row in set (0.00 sec) UNION ALL example: SELECT 'foo' AS bar UNION ALL SELECT 'foo' AS bar Result: +-----+| bar |+-----+| foo || foo |+-----+2 rows in set (0.00 sec) | {
"score": 12,
"source": [
"https://Stackoverflow.com/questions/49925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
]
} |
49,926 | Is there an open-source alternative to MATLAB's fmincon function for constrained linear optimization? I'm rewriting a MATLAB program to use Python / NumPy / SciPy and this is the only function I haven't found an equivalent to. A NumPy-based solution would be ideal, but any language will do. | Is your problem convex? Linear? Non-linear? I agree that SciPy.optimize will probably do the job, but fmincon is a sort of bazooka for solving optimization problems, and you'll be better off if you can confine it to one of the categories below (in increasing level of difficulty to solve efficiently) Linear Program (LP) Quadratic Program (QP) Convex Quadratically-Constrained Quadratic Program (QCQP) Second Order Cone Program (SOCP) Semidefinite Program (SDP) Non-Linear Convex Problem Non-Convex Problem There are also combinatoric problems such as Mixed-Integer Linear Programs (MILP), but you didn't mention any sort of integrality constraints, suffice to say that they fall into a different class of problems. The CVXOpt package will be of great use to you if your problem is convex. If your problem is not convex, you need to choose between finding a local solution or the global solution. Many convex solvers 'sort of' work in a non-convex domain. Finding a good approximation to the global solution would require some form Simulated Annealing or Genetic Algorithm. Finding the global solution will require an enumeration of all local solutions or a combinatorial strategy such as Branch and Bound. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/49926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3002/"
]
} |
49,934 | On my OS X box, the kernel is a 32-bit binary and yet it can run a 64-bit binary.How does this work? cristi:~ diciu$ file ./a.out./a.out: Mach-O 64-bit executable x86_64cristi:~ diciu$ file /mach_kernel/mach_kernel: Mach-O universal binary with 2 architectures/mach_kernel (for architecture i386): Mach-O executable i386/mach_kernel (for architecture ppc): Mach-O executable ppccristi:~ diciu$ ./a.outcristi:~ diciu$ echo $?1 | The CPU can be switched from 64 bit execution mode to 32 bit when it traps into kernel context, and a 32 bit kernel can still be constructed to understand the structures passed in from 64 bit user-space apps. The MacOS X kernel does not directly dereference pointers from the user app anyway, as it resides its own separate address space. A user-space pointer in an ioctl call, for example, must first be resolved to its physical address and then a new virtual address created in the kernel address space. It doesn't really matter whether that pointer in the ioctl was 64 bits or 32 bits, the kernel does not dereference it directly in either case. So mixing a 32 bit kernel and 64 bit binaries can work, and vice-versa. The thing you cannot do is mix 32 bit libraries with a 64 bit application, as pointers passed between them would be truncated. MacOS X supplies more of its frameworks in both 32 and 64 bit versions in each release. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/49934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2811/"
]
} |
49,937 | What is Dynamic Code Analysis? How is it different from Static Code Analysis (ie, what can it catch that can't be caught in static)? I've heard of bounds checking and memory analysis - what are these? What other things are checked using dynamic analysis? -Adam | Simply put, static analysis collect information based on source code and dynamic analysis is based on the system execution , often using instrumentation. Advantages of dynamic analysis Is able to detect dependencies that are not possible to detect in static analysis. Ex.: dynamic dependencies using reflection, dependency injection, polymorphism. Can collect temporal information. Deals with real input data. During the static analysis it is difficult to impossible to know what files will be passed as input, what WEB requests will come, what user will click, etc. Disadvantages of dynamic analysis May negatively impact the performance of the application. Cannot guarantee the full coverage of the source code, as it's runs are based on user interaction or automatic tests. Resources There's many dynamic analysis tools in the market, being debuggers the most notorious one. On the other hand, it's still an academic research field. There's many researchers studying how to use dynamic analysis for better understanding of software systems. There's an annual workshop dedicated to dependency analysis. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/49937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2915/"
]
} |
49,966 | When I turn an image ( <img> ) into a hyperlink (by wrapping it in <a> ), Firefox adds a black border around the image. Safari does not display the same border. What CSS declaration would be best to eliminate the border? | img { border: 0} Or old-fashioned: <img border="0" src="..." /> ^^^^^^^^^^ | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/49966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4540/"
]
} |
49,972 | I know that the .NET framework looks for referenced DLLs in several locations Global assembly cache (GAC) Any private paths added to the AppDomain The current directory of the executing assembly What order are those locations searched? Is the search for a DLL ceased if a match is found or does it continue through all locations (and if so, how are conflicts resolved)? Also, please confirm or deny those locations and provide any other locations I have failed to mention. | Assembly loading is a rather elaborate process which depends on lots of different factors like configuration files, publisher policies, appdomain settings, CLR hosts, partial or full assembly names, etc. The simple version is that the GAC is first, then the private paths. %PATH% is never used. It is best to use Assembly Binding Log Viewer (Fuslogvw.exe) to debug any assembly loading problems. EDIT How the Runtime Locates Assemblies explains the process in more detail. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/49972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3619/"
]
} |
49,988 | Occasionally a program on a Windows machine goes crazy and just hangs. So I'll call up the task manager and hit the "End Process" button for it. However, this doesn't always work; if I try it enough times then it'll usually die eventually, but I'd really like to be able to just kill it immediately. On Linux I could just kill -9 to guarantee that a process will die. This also could be used for writing batch scripts and writing batch scripts is programming. Is there some program or command that comes with Windows that will always kill a process? A free third-party app would be fine, although I'd prefer to be able to do this on machines I sit down at for the first time. | "End Process" on the Processes-Tab calls TerminateProcess which is the most ultimate way Windows knows to kill a process. If it doesn't go away, it's currently locked waiting on some kernel resource (probably a buggy driver) and there is nothing (short of a reboot) you could do to make the process go away. Have a look at this blog-entry from wayback when: http://blogs.technet.com/markrussinovich/archive/2005/08/17/unkillable-processes.aspx Unix based systems like Linux also have that problem where processes could survive a kill -9 if they are in what's known as "Uninterruptible sleep" (shown by top and ps as state D ) at which point the processes sleep so well that they can't process incoming signals (which is what kill does - sending signals). Normally, Uninterruptible sleep should not last long, but as under Windows, broken drivers or broken userpace programs ( vfork without exec ) can end up sleeping in D forever. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/49988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1694/"
]
} |
50,064 | This is pretty simple, I come from a swing/awt background. I'm just wondering what the proper way to set the background color for a SWT widget is? I've been trying: widget.setBackground( ); Except I have no idea how to create the color Object in SWT? | To create a color, try this: Device device = Display.getCurrent ();Color red = new Color (device, 255, 0, 0); | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/50064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3415/"
]
} |
50,079 | Can anyone recommend a decent C image library? I'm after loaders for bmp, gif, jpg, png and tga. I want to use this for programming my Sony Playstation Portable , so opensource would be very handy. After some googleing I've found FreeImage and CImg, but both feel rather heavy, and CImg is C++ not C. | If you control the images you're loading, the lightest loader I know is Sean Barrett's awesome stb_image.c (direct link to single file source code!). There are also other very worthwhile libraries on Sean's site such as a tiny TrueType rasterizer and Vorbis decompressor, btw. If you need OpenGL image loading that uses stb_image, I'll humbly point you to SOILex ... | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/50079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3180/"
]
} |
50,096 | I know it is not recommended, but is it at all possible to pass the user's password to scp? I'd like to copy a file via scp as part of a batch job and the receiving server does, of course, need a password and, no, I cannot easily change that to key-based authentication. | Use sshpass : sshpass -p "password" scp -r [email protected]:/some/remote/path /some/local/path or so the password does not show in the bash history sshpass -f "/path/to/passwordfile" scp -r [email protected]:/some/remote/path /some/local/path The above copies contents of path from the remote host to your local. Install : ubuntu/debian apt install sshpass centos/fedora yum install sshpass mac w/ macports port install sshpass mac w/ brew brew install https://raw.githubusercontent.com/kadwanev/bigboybrew/master/Library/Formula/sshpass.rb | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/50096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2992/"
]
} |
50,098 | I would like to compare two collections (in C#), but I'm not sure of the best way to implement this efficiently. I've read the other thread about Enumerable.SequenceEqual , but it's not exactly what I'm looking for. In my case, two collections would be equal if they both contain the same items (no matter the order). Example: collection1 = {1, 2, 3, 4};collection2 = {2, 4, 1, 3};collection1 == collection2; // true What I usually do is to loop through each item of one collection and see if it exists in the other collection, then loop through each item of the other collection and see if it exists in the first collection. (I start by comparing the lengths). if (collection1.Count != collection2.Count) return false; // the collections are not equalforeach (Item item in collection1){ if (!collection2.Contains(item)) return false; // the collections are not equal}foreach (Item item in collection2){ if (!collection1.Contains(item)) return false; // the collections are not equal}return true; // the collections are equal However, this is not entirely correct, and it's probably not the most efficient way to do compare two collections for equality. An example I can think of that would be wrong is: collection1 = {1, 2, 3, 3, 4}collection2 = {1, 2, 2, 3, 4} Which would be equal with my implementation. Should I just count the number of times each item is found and make sure the counts are equal in both collections? The examples are in some sort of C# (let's call it pseudo-C#), but give your answer in whatever language you wish, it does not matter. Note: I used integers in the examples for simplicity, but I want to be able to use reference-type objects too (they do not behave correctly as keys because only the reference of the object is compared, not the content). | It turns out Microsoft already has this covered in its testing framework: CollectionAssert.AreEquivalent Remarks Two collections are equivalent if theyhave the same elements in the samequantity, but in any order. Elementsare equal if their values are equal,not if they refer to the same object. Using reflector, I modified the code behind AreEquivalent() to create a corresponding equality comparer. It is more complete than existing answers, since it takes nulls into account, implements IEqualityComparer and has some efficiency and edge case checks. plus, it's Microsoft :) public class MultiSetComparer<T> : IEqualityComparer<IEnumerable<T>>{ private readonly IEqualityComparer<T> m_comparer; public MultiSetComparer(IEqualityComparer<T> comparer = null) { m_comparer = comparer ?? EqualityComparer<T>.Default; } public bool Equals(IEnumerable<T> first, IEnumerable<T> second) { if (first == null) return second == null; if (second == null) return false; if (ReferenceEquals(first, second)) return true; if (first is ICollection<T> firstCollection && second is ICollection<T> secondCollection) { if (firstCollection.Count != secondCollection.Count) return false; if (firstCollection.Count == 0) return true; } return !HaveMismatchedElement(first, second); } private bool HaveMismatchedElement(IEnumerable<T> first, IEnumerable<T> second) { int firstNullCount; int secondNullCount; var firstElementCounts = GetElementCounts(first, out firstNullCount); var secondElementCounts = GetElementCounts(second, out secondNullCount); if (firstNullCount != secondNullCount || firstElementCounts.Count != secondElementCounts.Count) return true; foreach (var kvp in firstElementCounts) { var firstElementCount = kvp.Value; int secondElementCount; secondElementCounts.TryGetValue(kvp.Key, out secondElementCount); if (firstElementCount != secondElementCount) return true; } return false; } private Dictionary<T, int> GetElementCounts(IEnumerable<T> enumerable, out int nullCount) { var dictionary = new Dictionary<T, int>(m_comparer); nullCount = 0; foreach (T element in enumerable) { if (element == null) { nullCount++; } else { int num; dictionary.TryGetValue(element, out num); num++; dictionary[element] = num; } } return dictionary; } public int GetHashCode(IEnumerable<T> enumerable) { if (enumerable == null) throw new ArgumentNullException(nameof(enumerable)); int hash = 17; foreach (T val in enumerable) hash ^= (val == null ? 42 : m_comparer.GetHashCode(val)); return hash; }} Sample usage: var set = new HashSet<IEnumerable<int>>(new[] {new[]{1,2,3}}, new MultiSetComparer<int>());Console.WriteLine(set.Contains(new [] {3,2,1})); //trueConsole.WriteLine(set.Contains(new [] {1, 2, 3, 3})); //false Or if you just want to compare two collections directly: var comp = new MultiSetComparer<string>();Console.WriteLine(comp.Equals(new[] {"a","b","c"}, new[] {"a","c","b"})); //trueConsole.WriteLine(comp.Equals(new[] {"a","b","c"}, new[] {"a","b"})); //false Finally, you can use your an equality comparer of your choice: var strcomp = new MultiSetComparer<string>(StringComparer.OrdinalIgnoreCase);Console.WriteLine(strcomp.Equals(new[] {"a", "b"}, new []{"B", "A"})); //true | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/50098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/810/"
]
} |
50,106 | If any of you have worked with a cool tool for viewing/querying the SQL Transaction logs, please let me know. This should show all the transactional sql statements which are committed or rolled back. For Database files, if it has some additional graphical capabilities like showing the internal Binary Tree structure of the indexes, that will be awesome but I guess I am asking for too much huh.. | This is only relevant if you're talking SQL Server 2000 but RedGate produced a free tool called SQL Log Rescue .Otherwise, for SQL Server 2005 ApexSQLLog from ApexSQL is the only other product I'm aware of | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/50106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4337/"
]
} |
50,114 | I understand the value of the three-part service/host/client model offered by WCF. But is it just me or does it seem like WCF took something pretty direct and straightforward (the ASMX model) and made a mess out of it? Is there an alternative to using SvcUtil's command line step back in time to generate the proxy? With ASMX services a test harness was automatically provided; is there a good alternative today with WCF? I appreciate that the WS* stuff is more tightly integrated with WCF and hope to find some payoff for WCF there, but geeze, otherwise I'm perplexed. Also, the state of books available for WCF is abysmal at best. Juval Lowy, a superb author, has written a good O'Reilly reference book "Programming WCF Services" but it doesn't do that much (for me anyway) for learning now to use WCF. That book's precursor (and a little better organized, but not much, as a tutorial) is Michele Leroux Bustamante's Learning WCF. It has good spots but is outdated in place and its corresponding Web site is gone. Do you have good WCF learning references besides just continuing to Google the bejebus out of things? | Okay, here we go. First, Michele Leroux Bustamante's book has been updated for VS2008. The website for the book is not gone. It's up right now, and it has tons of great WCF info. On that website she provides updated code compatible with VS2008 for all the examples in her book. If you order from Amazon, you will get the reprint which is updated. WCF is not only a replacement for ASMX. Sure it can (and does quite well) replace ASMX, but the real benefit is that it allows your services to be self-hosted. Most of the functionality from WSE has been baked in from the start. The framework is highly configurable, and the ability to serve multiple endpoints over multiple protocols is amazing, IMO. While you can still generate proxy classes from the "Add Service Reference" option, it's not necessary. All you really have to do is copy your ServiceContract interface and tell your code where to find the endpoint for the service, and that's it. You can call methods from the service with very little code. Using this method, you have complete control over the implementation. Regardless of the method you choose to generate a proxy class, Michele shows both and uses both in her excellent series of webcasts on the subject. Michele has tons of great material out there, and I recommend you check out her website(s). Here's some links that were incredibly helpful for me as I was learning WCF. I hope that you'll come to realize how strong WCF really is, and how easy it is to implement. The learning curve is a little bit steep, but the rewards for your time investment are well worth it: Michele's webcasts: http://www.dasblonde.net/2007/06/24/WCFWebcastSeries.aspx Michele's book website (alive and updated for VS2008): http://www.thatindigogirl.com/ I recommend you watch at least 1 of Michele's webcasts. She is a very effective presenter, and she's obviously incredibly knowledgeable when it comes to WCF. She does a great job of demystifying the inner workings of WCF from the ground up. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/50114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2536/"
]
} |
50,153 | I've never had to do IPC on Windows before. I'm developing a pair of programs, a standard GUI/CLI app, and a windows service. The app has to tell the service what to do. So, assuming the communication is local only, what would be the best communication method for these two processes? By best I mean more robust and less error prone, not the best performance nor the easiest to code. Note I'm asking about what to use, a standard TCP socket, named pipes, or some other means of communication only. | IPC in .Net can be achieved using: WCF using named pipes requires .Net 3.0 and above. Code example The WCF class NetNamedPipeBinding can be used for interprocess communication on the same machine. The MSDN documentaion for this class includes a code sample covering this scenario http://msdn.microsoft.com/en-us/library/system.servicemodel.netnamedpipebinding.aspx Remoting The original IPC framework released with .Net 1.0. I believe remoting is no longer being actively developed, and you are encouraged to use WCF instead Code example Inter-process communication via Remoting - uses a tcp channel Resources GenuineChannels, sell a remoting toolkit that includes a Shared Memory Channel. http://www.genuinechannels.com/Index.aspx Ingo Rammer , wrote the definitive .Net remoting book, Advanced .NET Remoting, Second Edition Win32 RPC using csharptest-net RpcLibrary I came across a project recently that has wrapped the Win32 RPC library and created a .net class library that can be used for local and remote RPC Project home page : http://csharptest.net/projects/rpclibrary/ MSDN references: How rpc works: http://technet.microsoft.com/en-us/library/cc738291(v=ws.10).aspx RPC functions: http://msdn.microsoft.com/en-us/library/aa378623(v=VS.85).aspx Also has a google protocol buffers rpc client that runs on top of the library: https://code.google.com/p/protobuf-csharp-rpc/ WM_COPYDATA For completeness it's also possible to use the WIN32 method with the WM_COPYDATA message. I've used this method before in .Net 1.1 to create a single instance application opening multiple files from windows explorer. Resources MSDN - WM_COPYDATA Code example PInvoke.net declaration Sockets Using a custom protocol (harder) | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/50153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5190/"
]
} |
50,159 | I'd like to know which libraries are used by executables on my system. More specifically, I'd like to rank which libraries are used the most, along with the binaries that use them. How can I do this? | Use ldd to list shared libraries for each executable. Cleanup the output Sort, compute counts, sort by count To find the answer for all executables in the "/bin" directory: find /bin -type f -perm /a+x -exec ldd {} \; \| grep so \| sed -e '/^[^\t]/ d' \| sed -e 's/\t//' \| sed -e 's/.*=..//' \| sed -e 's/ (0.*)//' \| sort \| uniq -c \| sort -n Change "/bin" above to "/" to search all directories. Output (for just the /bin directory) will look something like this: 1 /lib64/libexpat.so.0 1 /lib64/libgcc_s.so.1 1 /lib64/libnsl.so.1 1 /lib64/libpcre.so.0 1 /lib64/libproc-3.2.7.so 1 /usr/lib64/libbeecrypt.so.6 1 /usr/lib64/libbz2.so.1 1 /usr/lib64/libelf.so.1 1 /usr/lib64/libpopt.so.0 1 /usr/lib64/librpm-4.4.so 1 /usr/lib64/librpmdb-4.4.so 1 /usr/lib64/librpmio-4.4.so 1 /usr/lib64/libsqlite3.so.0 1 /usr/lib64/libstdc++.so.6 1 /usr/lib64/libz.so.1 2 /lib64/libasound.so.2 2 /lib64/libblkid.so.1 2 /lib64/libdevmapper.so.1.02 2 /lib64/libpam_misc.so.0 2 /lib64/libpam.so.0 2 /lib64/libuuid.so.1 3 /lib64/libaudit.so.0 3 /lib64/libcrypt.so.1 3 /lib64/libdbus-1.so.3 4 /lib64/libresolv.so.2 4 /lib64/libtermcap.so.2 5 /lib64/libacl.so.1 5 /lib64/libattr.so.1 5 /lib64/libcap.so.1 6 /lib64/librt.so.1 7 /lib64/libm.so.6 9 /lib64/libpthread.so.0 13 /lib64/libselinux.so.1 13 /lib64/libsepol.so.1 22 /lib64/libdl.so.2 83 /lib64/ld-linux-x86-64.so.2 83 /lib64/libc.so.6 Edit - Removed "grep -P" | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/50159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3756/"
]
} |
50,194 | I've got a number of non-technical users that all share a set of project files. It would be ideal to have them using version control, but I think that both subversion and git are too technical for non-technical office staff. Is there any distributed source control software that would work well for normal people? | If source control is too technical they can use Subversion with WebDav . The less technical people will just save files normally from whatever application they use, without worrying/thinking about source control. They get the benefit of auto-versioning without doing anything. When ever they need more functionality they can learn to use TortoiseSVN to view diffs, revert to old version that were made automatically for them etc... From the subversion book : Because so many operating systems already have integrated WebDAV clients, the use case for this feature borders on fantastical: imagine an office of ordinary users running Microsoft Windows or Mac OS. Each user “mounts” the Subversion repository, which appears to be an ordinary network folder. They use the shared folder as they always do: open files, edit them, save them. Meanwhile, the server is automatically versioning everything. Any administrator (or knowledgeable user) can still use a Subversion client to search history and retrieve older versions of data. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/50194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4767/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.