source_id
int64
1
74.7M
question
stringlengths
0
40.2k
response
stringlengths
0
111k
metadata
dict
90,580
Without getting a degree in information retrieval, I'd like to know if there exists any algorithms for counting the frequency that words occur in a given body of text. The goal is to get a "general feel" of what people are saying over a set of textual comments. Along the lines of Wordle . What I'd like: ignore articles, pronouns, etc ('a', 'an', 'the', 'him', 'them' etc) preserve proper nouns ignore hyphenation, except for soft kind Reaching for the stars, these would be peachy: handling stemming & plurals (e.g. like, likes, liked, liking match the same result) grouping of adjectives (adverbs, etc) with their subjects ("great service" as opposed to "great", "service") I've attempted some basic stuff using Wordnet but I'm just tweaking things blindly and hoping it works for my specific data. Something more generic would be great.
You'll need not one, but several nice algorithms, along the lines of the following. ignoring pronouns is done via a stoplist . preserving proper nouns? You mean, detecting named entities, like Hoover Dam and saying "it's one word" or compound nouns, like programming language ? I'll give you a hint: that's tough one, but there exist libraries for both. Look for NER (Named entitiy recognition) and lexical chunking. OpenNLP is a Java-Toolkit that does both. ignoring hyphenation? You mean, like at line breaks? Use regular expressions and verify the resulting word via dictionary lookup. handling plurals/stemming: you can look into the Snowball stemmer . It does the trick nicely. "grouping" adjectives with their nouns is generally a task of shallow parsing . But if you are looking specifically for qualitative adjectives (good, bad, shitty, amazing...) you may be interested in sentiment analysis . LingPipe does this, and a lot more. I'm sorry, I know you said you wanted to KISS, but unfortunately, your demands aren't that easy to meet. Nevertheless, there exist tools for all of this, and you should be able to just tie them together and not have to perform any task yourself, if you don't want to. If you want to perform a task yourself, I suggest you look at stemming, it's the easiest of all. If you go with Java, combine Lucene with the OpenNLP toolkit. You will get very good results, as Lucene already has a stemmer built in and a lot of tutorial. The OpenNLP toolkit on the other hand is poorly documented, but you won't need too much out of it. You might also be interested in NLTK , written in Python. I would say you drop your last requirement, as it involves shallow parsing and will definetly not impove your results. Ah, btw. the exact term of that document-term-frequency-thing you were looking for is called tf-idf . It's pretty much the best way to look for document frequency for terms. In order to do it properly, you won't get around using multidimenional vector matrices. ... Yes, I know. After taking a seminar on IR, my respect for Google was even greater. After doing some stuff in IR, my respect for them fell just as quick, though.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/90580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17328/" ] }
90,595
How to implement a web page that scales when the browser window is resized? I can lay out the elements of the page using either a table or CSS float sections, but i want the display to rescale when the browser window is resized i have a working solution using AJAX PRO and DIVs with overflow:auto and an onwindowresize hook, but it is cumbersome. Is there a better way? thanks everyone for the answers so far, i intend to try them all (or at least most of them) and then choose the best solution as the answer to this thread using CSS and percentages seems to work best, which is what I did in the original solution; using a visibility:hidden div set to 100% by 100% gives a way to measure the client area of the window [difficult in IE otherwise], and an onwindowresize javascript function lets the AJAXPRO methods kick in when the window is resized to redraw the layout-cell contents at the new resolution EDIT: my apologies for not being completely clear; i needed a 'liquid layout' where the major elements ('panes') would scale as the browser window was resized. I found that i had to use an AJAX call to re-display the 'pane' contents after resizing, and keep overflow:auto turned on to avoid scrolling
instead of using in css say "width: 200px", use stuff like "width: 50%" This makes it use 50% of whatever it's in, so in the case of: <body> <div style="width:50%"> <!--some stuff--> </div></body> The div will now always take up half the window horizontaly.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/90595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9345/" ] }
90,697
How do I create a resource that I can reference and use in various parts of my program easily? My specific problem is that I have a NotifyIcon that I want to change the icon of depending on the state of the program. A common problem, but one I've been struggling with for a long time.
Well, after searching around and cobbling together various points from around StackOverflow (gee, I love this place already), most of the problems were already past this stage. I did manage to work out an answer to my problem though. How to create a resource: In my case, I want to create an icon. It's a similar process, no matter what type of data you want to add as a resource though. Right click the project you want to add a resource to. Do this in the Solution Explorer. Select the "Properties" option from the list. Click the "Resources" tab. The first button along the top of the bar will let you select the type of resource you want to add. It should start on string. We want to add an icon, so click on it and select "Icons" from the list of options. Next, move to the second button, "Add Resource". You can either add a new resource, or if you already have an icon already made, you can add that too. Follow the prompts for whichever option you choose. At this point, you can double click the newly added resource to edit it. Note, resources also show up in the Solution Explorer, and double clicking there is just as effective. How to use a resource: Great, so we have our new resource and we're itching to have those lovely changing icons... How do we do that? Well, lucky us, C# makes this exceedingly easy. There is a static class called Properties.Resources that gives you access to all your resources, so my code ended up being as simple as: paused = !paused;if (paused) notifyIcon.Icon = Properties.Resources.RedIcon;else notifyIcon.Icon = Properties.Resources.GreenIcon; Done! Finished! Everything is simple when you know how, isn't it?
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/90697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15537/" ] }
90,751
Do C#/.NET floating point operations differ in precision between debug mode and release mode?
They can indeed be different. According to the CLR ECMA specification: Storage locations for floating-point numbers (statics, array elements, and fields of classes) are of fixed size. The supported storage sizes are float32 and float64. Everywhere else (on the evaluation stack, as arguments, as return types, and as local variables) floating-point numbers are represented using an internal floating-point type. In each such instance, the nominal type of the variable or expression is either R4 or R8, but its value can be represented internally with additional range and/or precision. The size of the internal floating-point representation is implementation-dependent, can vary, and shall have precision at least as great as that of the variable or expression being represented. An implicit widening conversion to the internal representation from float32 or float64 is performed when those types are loaded from storage. The internal representation is typically the native size for the hardware, or as required for efficient implementation of an operation. What this basically means is that the following comparison may or may not be equal: class Foo{ double _v = ...; void Bar() { double v = _v; if( v == _v ) { // Code may or may not execute here. // _v is 64-bit. // v could be either 64-bit (debug) or 80-bit (release) or something else (future?). } }} Take-home message: never check floating values for equality.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/90751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/288629/" ] }
90,802
I am looking for a PHP blog engine which needs to be easy to redesign (CSS, HTML). It also needs to be free and have simple user interface so that the client doesn't struggle to add posts. Any suggestions?
Wordpress - I keep trying other blogs and I keep going back to wordpress. It's definitely the easiest I've used for customizing templates, and the admin UI is very nice.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/90802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17366/" ] }
90,813
What is your best practical user-friendly user-interface design or principle? Please submit those practices that you find actually makes things really useful - no matter what - if it works for your users, share it! Summary/Collation Principles KISS. Be clear and specific in what an option will achieve: for example, use verbs that indicate the action that will follow on a choice (see: Impl. 1). Use obvious default actions appropriate to what the user needs/wants to achieve. Fit the appearance and behavior of the UI to the environment/process/audience: stand-alone application, web-page, portable, scientific analysis, flash-game, professionals/children, ... Reduce the learning curve of a new user. Rather than disabling or hiding options, consider giving a helpful message where the user can have alternatives, but only where those alternatives exist. If no alternatives are available, its better to disable the option - which visually then states that the option is not available - do not hide the unavailable options, rather explain in a mouse-over popup why it is disabled. Stay consistent and conform to practices, and placement of controls, as is implemented in widely-used successful applications. Lead the expectations of the user and let your program behave according to those expectations. Stick to the vocabulary and knowledge of the user and do not use programmer/implementation terminology. Follow basic design principles: contrast (obviousness), repetition (consistency), alignment (appearance), and proximity (grouping). Implementation (See answer by paiNie) "Try to use verbs in your dialog boxes." Allow/implement undo and redo. References Windows Vista User Experience Guidelines [ http://msdn.microsoft.com/en-us/library/aa511258.aspx] Dutch websites - "Drempelvrij" guidelines [ http://www.drempelvrij.nl/richtlijnen] Web Content Accessibility Guidelines (WCAG 1.0) [ http://www.w3.org/TR/WCAG10/] Consistence [ http://www.amazon.com/Design-Everyday-Things-Donald-Norman/dp/0385267746] Don't make me Think [ http://www.amazon.com/Dont-Make-Me-Think-Usability/dp/0321344758/ref=pdbbssr_1?ie=UTF8&s=books&qid=1221726383&sr=8-1] Be powerful and simple [ http://msdn.microsoft.com/en-us/library/aa511332.aspx] Gestalt design laws [ http://www.squidoo.com/gestaltlaws]
Try to use verbs in your dialog boxes. It means use instead of
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/90813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15161/" ] }
90,838
In our application, we receive text files ( .txt , .csv , etc.) from diverse sources. When reading, these files sometimes contain garbage, because the files where created in a different/unknown codepage. Is there a way to (automatically) detect the codepage of a text file? The detectEncodingFromByteOrderMarks , on the StreamReader constructor, works for UTF8 and other unicode marked files, but I'm looking for a way to detect code pages, like ibm850 , windows1252 . Thanks for your answers, this is what I've done. The files we receive are from end-users, they do not have a clue about codepages. The receivers are also end-users, by now this is what they know about codepages: Codepages exist, and are annoying. Solution: Open the received file in Notepad, look at a garbled piece of text. If somebody is called François or something, with your human intelligence you can guess this. I've created a small app that the user can use to open the file with, and enter a text that user knows it will appear in the file, when the correct codepage is used. Loop through all codepages, and display the ones that give a solution with the user provided text. If more as one codepage pops up, ask the user to specify more text.
You can't detect the codepage, you need to be told it. You can analyse the bytes and guess it, but that can give some bizarre (sometimes amusing) results. I can't find it now, but I'm sure Notepad can be tricked into displaying English text in Chinese. Anyway, this is what you need to read: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) . Specifically Joel says: The Single Most Important Fact About Encodings If you completely forget everything I just explained, please remember one extremely important fact. It does not make sense to have a string without knowing what encoding it uses. You can no longer stick your head in the sand and pretend that "plain" text is ASCII. There Ain't No Such Thing As Plain Text. If you have a string, in memory, in a file, or in an email message, you have to know what encoding it is in or you cannot interpret it or display it to users correctly.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/90838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11492/" ] }
90,871
Continuing from my previous question , is there a comprehensive document that lists all available differences between debug and release modes in a C# application, and particularly in a web application? What differences are there?
"Debug" and "Release" are just names for predefined project configurations defined by Visual Studio. To see the differences, look at the Build Tab in Project Properties in Visual Studio. The differences in VS2005 include: DEBUG constant defined in Debug configuration Optimize code enabled in Release configuration as well as other differences you can see by clicking on the "Advanced" button But you can: Change the build settings for Debug and Release configurations in Project Propeties / Build Create your own custom configurations by right-clicking on the solution in Solution Explorer and selecting Configuration Manager I think the behaviour of the DEBUG constant is fairly clear (can be referenced in the #if preprocessor directive or in the ConditionalAttribute). But I'm not aware of any comprehensive documentation on exactly what optimizations are enabled - in fact I suspect Microsoft would want to be free to enhance their optimizer without notice
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/90871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/288629/" ] }
90,885
I want to make an entity that has an autogenerated primary key, but also a unique compound key made up of two other fields. How do I do this in JPA? I want to do this because the primary key should be used as foreign key in another table and making it compound would not be good. In the following snippet, I need the command and model to be unique. pk is of course the primary key. @Entity@Table(name = "dm_action_plan")public class ActionPlan { @Id private int pk; @Column(name = "command", nullable = false) private String command; @Column(name = "model", nullable = false) String model;}
You can use @UniqueConstraint something like this : @Entity@Table(name = "dm_action_plan", uniqueConstraints={ @UniqueConstraint(columnNames= "command","model") } )public class ActionPlan { @Id private int pk; @Column(name = "command", nullable = false) private String command; @Column(name = "model", nullable = false) String model;} This will allow your JPA implementation to generate the DDL for the unique constraint.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/90885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16152/" ] }
90,899
How can I get all items from a specific calendar (for a specific date). Lets say for instance that I have a calendar with a recurring item every Monday evening. When I request all items like this: CalendarItems = CalendarFolder.Items;CalendarItems.IncludeRecurrences = true; I only get 1 item... Is there an easy way to get all items (main item + derived items) from a calendar?In my specific situation it can be possible to set a date limit but it would be cool just to get all items (my recurring items are time limited themselves). I'm using the Microsoft Outlook 12 Object library (Microsoft.Office.Interop.Outlook) .
I believe that you must Restrict or Find in order to get recurring appointments, otherwise Outlook won't expand them. Also, you must Sort by Start before setting IncludeRecurrences.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/90899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
90,907
I would like to know what would be the best way to do unit testing of a servlet. Testing internal methods is not a problem as long as they don't refer to the servlet context, but what about testing the doGet/doPost methods as well as the internal method that refer to the context or make use of session parameters? Is there a way to do this simply using classical tools such as JUnit, or preferrably TestNG? Did I need to embed a tomcat server or something like that?
Most of the time I test Servlets and JSP's via 'Integration Tests' rather than pure Unit Tests. There are a large number of add-ons for JUnit/TestNG available including: HttpUnit (the oldest and best known, very low level which can be good or bad depending on your needs) HtmlUnit (higher level than HttpUnit, which is better for many projects) JWebUnit (sits on top of other testing tools and tries to simplify them - the one I prefer) WatiJ and Selenium (use your browser to do the testing, which is more heavyweight but realistic) This is a JWebUnit test for a simple Order Processing Servlet which processes input from the form 'orderEntry.html'. It expects a customer id, a customer name and one or more order items: public class OrdersPageTest { private static final String WEBSITE_URL = "http://localhost:8080/demo1"; @Before public void start() { webTester = new WebTester(); webTester.setTestingEngineKey(TestingEngineRegistry.TESTING_ENGINE_HTMLUNIT); webTester.getTestContext().setBaseUrl(WEBSITE_URL); } @Test public void sanity() throws Exception { webTester.beginAt("/orderEntry.html"); webTester.assertTitleEquals("Order Entry Form"); } @Test public void idIsRequired() throws Exception { webTester.beginAt("/orderEntry.html"); webTester.submit(); webTester.assertTextPresent("ID Missing!"); } @Test public void nameIsRequired() throws Exception { webTester.beginAt("/orderEntry.html"); webTester.setTextField("id","AB12"); webTester.submit(); webTester.assertTextPresent("Name Missing!"); } @Test public void validOrderSucceeds() throws Exception { webTester.beginAt("/orderEntry.html"); webTester.setTextField("id","AB12"); webTester.setTextField("name","Joe Bloggs"); //fill in order line one webTester.setTextField("lineOneItemNumber", "AA"); webTester.setTextField("lineOneQuantity", "12"); webTester.setTextField("lineOneUnitPrice", "3.4"); //fill in order line two webTester.setTextField("lineTwoItemNumber", "BB"); webTester.setTextField("lineTwoQuantity", "14"); webTester.setTextField("lineTwoUnitPrice", "5.6"); webTester.submit(); webTester.assertTextPresent("Total: 119.20"); } private WebTester webTester;}
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/90907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9396/" ] }
90,949
There is no documentation on cakephp.org and I am unable to find one on google. Please link me some documentation or supply one!
The translate behavior is another of CakePHP's very useful but poorly documented features. I've implemented it a couple of times with reasonable success in multi-lingual websites along the following lines. Firstly, the translate behavior will only internationalize the database content of your site. If you've any more static content, you'll want to look at Cake's __('string') wrapper function and gettext (there's some useful information about this here ) Assuming there's Contents that we want to translate with the following db table: CREATE TABLE `contents` ( `id` int(11) unsigned NOT NULL auto_increment, `title` varchar(255) default NULL, `body` text, PRIMARY KEY (`id`),) ENGINE=InnoDB DEFAULT CHARSET=utf8; The content.php model then has: var $actsAs = array('Translate' => array('title' => 'titleTranslation', 'body' => 'bodyTranslation' )); in its definition. You then need to add the i18n table to the database thusly: CREATE TABLE `i18n` ( `id` int(10) NOT NULL auto_increment, `locale` varchar(6) NOT NULL, `model` varchar(255) NOT NULL, `foreign_key` int(10) NOT NULL, `field` varchar(255) NOT NULL, `content` mediumtext, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8; Then when you're saving the data to the database in your controller, set the locale to the language you want (this example would be for Polish): $this->Content->locale = 'pol';$result = $this->Content->save($this->data); This will create entries in the i18n table for the title and body fields for the pol locale. Finds will find based on the current locale set in the user's browser, returning an array like: [Content] [id] [titleTranslation] [bodyTranslation] We use the excellent p28n component to implement a language switching solution that works pretty well with the gettext and translate behaviours. It's not a perfect system - as it creates HABTM relationships on the fly, it can cause some issues with other relationships you may have created manually, but if you're careful, it can work well.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/90949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4013/" ] }
90,971
Let's say I have a class: class Foo{ public string Bar { get { ... } } public string this[int index] { get { ... } }} I can bind to these two properties using "{Binding Path=Bar}" and "{Binding Path=[x]}". Fine. Now let's say I want to implement INotifyPropertyChanged: class Foo : INotifyPropertyChanged{ public string Bar { get { ... } set { ... if( PropertyChanged != null ) { PropertyChanged( this, new PropertyChangedEventArgs( "Bar" ) ); } } } public string this[int index] { get { ... } set { ... if( PropertyChanged != null ) { PropertyChanged( this, new PropertyChangedEventArgs( "????" ) ); } } } public event PropertyChangedEventHandler PropertyChanged;} What goes in the part marked ????? (I've tried string.Format("[{0}]", index) and it doesn't work). Is this a bug in WPF, is there an alternative syntax, or is it simply that INotifyPropertyChanged isn't as powerful as normal binding?
Thanks to Cameron's suggestion, I've found the correct syntax, which is: Item[] Which updates everything (all index values) bound to that indexed property.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/90971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6604/" ] }
90,982
I'm looking for a good, clean way to go around the fact that PHP5 still doesn't support multiple inheritance. Here's the class hierarchy: Message -- TextMessage -------- InvitationTextMessage -- EmailMessage -------- InvitationEmailMessage The two types of Invitation* classes have a lot in common; i'd love to have a common parent class, Invitation, that they both would inherit from. Unfortunately, they also have a lot in common with their current ancestors... TextMessage and EmailMessage. Classical desire for multiple inheritance here. What's the most light-weight approach to solve the issue? Thanks!
Alex, most of the times you need multiple inheritance is a signal your object structure is somewhat incorrect. In situation you outlined I see you have class responsibility simply too broad. If Message is part of application business model, it should not take care about rendering output. Instead, you could split responsibility and use MessageDispatcher that sends the Message passed using text or html backend. I don't know your code, but let me simulate it this way: $m = new Message();$m->type = 'text/html';$m->from = 'John Doe <[email protected]>';$m->to = 'Random Hacker <[email protected]>';$m->subject = 'Invitation email';$m->importBody('invitation.html');$d = new MessageDispatcher();$d->dispatch($m); This way you can add some specialisation to Message class: $htmlIM = new InvitationHTMLMessage(); // html type, subject and body configuration in constructor$textIM = new InvitationTextMessage(); // text type, subject and body configuration in constructor$d = new MessageDispatcher();$d->dispatch($htmlIM);$d->dispatch($textIM); Note that MessageDispatcher would make a decision whether to send as HTML or plain text depending on type property in Message object passed. // in MessageDispatcher classpublic function dispatch(Message $m) { if ($m->type == 'text/plain') { $this->sendAsText($m); } elseif ($m->type == 'text/html') { $this->sendAsHTML($m); } else { throw new Exception("MIME type {$m->type} not supported"); }} To sum it up, responsibility is split between two classes. Message configuration is done in InvitationHTMLMessage/InvitationTextMessage class, and sending algorithm is delegated to dispatcher. This is called Strategy Pattern, you can read more on it here .
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/90982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16668/" ] }
91,071
In Emacs, C-x o takes me to the next window. What keyboard macro takes me to the previous window in Emacs?
That'd be C-- C-x o In other words, C-x o with an argument of -1. You can specify how many windows to move by inserting a numeric argument between C-u and the command, as in C-u 2 C-x o . ( C-- is a shortcut for C-u - 1 )
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/91071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17239/" ] }
91,108
How do I get my C# program to sleep (pause execution) for 50 milliseconds?
System.Threading.Thread.Sleep(50); Remember though, that doing this in the main GUI thread will block your GUI from updating (it will feel "sluggish") Just remove the ; to make it work for VB.net as well.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/91108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1816/" ] }
91,110
How to match a single quote in sed if the expression is enclosed in single quotes: sed -e '...' For example need to match this text: 'foo'
You can either use: "texta'textb" (APOSTROPHE inside QUOTATION MARKs) or 'texta'\''textb' (APOSTROPHE text APOSTROPHE, then REVERSE SOLIDUS, APOSTROPHE, then APOSTROPHE more text APOSTROPHE) I used unicode character names. REVERSE SOLIDUS is more commonly known as backslash. In the latter case, you close your apostrophe, then shell-quote your apostrophe with a backslash, then open another apostrophe for the rest of the text.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/91110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1692070/" ] }
91,169
So I log into a Solaris box, try to start Apache, and find that there is already a process listening on port 80, and it's not Apache. Our boxes don't have lsof installed, so I can't query with that. I guess I could do: pfiles `ls /proc` | less and look for "port: 80", but if anyone has a better solution, I'm all ears! Even better if I can look for the listening process without being root. I'm open to both shell and C solutions; I wouldn't mind having a little custom executable to carry with me for the next time this comes up. Updated: I'm talking about generic installs of solaris for which I am not the administrator (although I do have superuser access), so installing things from the freeware disk isn't an option. Obviously neither are using Linux-specific extensions to fuser, netstat, or other tools. So far running pfiles on all processes seems to be the best solution, unfortunately. If that remains the case, I'll probably post an answer with some slightly more efficient code that the clip above.
I found this script somewhere. I don't remember where, but it works for me: #!/bin/kshline='---------------------------------------------'pids=$(/usr/bin/ps -ef | sed 1d | awk '{print $2}')if [ $# -eq 0 ]; then read ans?"Enter port you would like to know pid for: "else ans=$1fifor f in $pidsdo /usr/proc/bin/pfiles $f 2>/dev/null | /usr/xpg4/bin/grep -q "port: $ans" if [ $? -eq 0 ]; then echo $line echo "Port: $ans is being used by PID:\c" /usr/bin/ps -ef -o pid -o args | egrep -v "grep|pfiles" | grep $f fidoneexit 0 Edit: Here is the original source: [Solaris] Which process is bound to a given port ?
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/91169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
91,179
What options are there for building automated tests for GUIs written in Java Swing? I'd like to test some GUIs which have been written using the NetBeans Swing GUI Builder , so something that works without requiring special tampering of the code under test would be ideal.
Recently I came across FEST which seemed promising, except that the developer announced in 2012 that development would not continue . AssertJ is a fork of FEST that is working very well for me. It is actively maintained (at time of writing), supports Java 8, has assertions for a few popular libraries such as Guava and Joda Time, and is very well documented. It is also free and open.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/91179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/755/" ] }
91,205
I'm a little confused about how the standard library will behave now that Python (from 3.0) is unicode-based. Will modules such as CGI and urllib use unicode strings or will they use the new 'bytes' type and just provide encoded data?
Logically a lot of things like MIME-encoded mail messages, URLs, XML documents, and so on should be returned as bytes not strings. This could cause some consternation as the libraries start to be nailed down for Python 3 and people discover that they have to be more aware of the bytes / string conversions than they were for str / unicode ...
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/91205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17457/" ] }
91,216
mysql_real_escape_string and addslashes are both used to escape data before the database query, so what's the difference? (This question is not about parametrized queries/PDO/mysqli)
string mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier ] ) mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a. string addslashes ( string $str ) Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte). They affect different characters. mysql_real_escape_string is specific to MySQL. Addslashes is just a general function which may apply to other things as well as MySQL.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/91216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7506/" ] }
91,234
I have a system where I have multiple keyboards and really need to know which keyboard the key stroke is coming from. To explain the set up: I have a normal PC and USB keyboard I have an external VGA screen with some hard-keys The hard keys are mapped as a standard USB keyboard, sending a limited number of key-codes (F1, F2, Return, + and -) I have a low-level hook (in C# but actually calling upon Win32 functionality) which is able to deal with the input even when my application is not focused. The problem is that when using the normal keyboard, some of the mapped key-codes at picked up by the application being driven on the external screen. One of the key-presses sent by the external screen and used for confirmation is VK_RETURN. Unless I can identify the "device" and filter upon it, the user could be performing actions and confirming them on a screen their not even looking at. How do I know which keyboard was responsible for the key-press?
Yes I stand corrected, my bad, learning something new every day. Here's my attempt at making up for it :) : Register the devices you want to use for raw input (the two keyboards) with ::RegisterRawInputDevices(). You can get these devices from GetRawInputDeviceList() After you've registered your devices, you will start getting WM_INPUT messages. The lParam of the WM_INPUT message contains a RAWKEYBOARD structure that you can use to determine the keyboard where the input came from, plus the virtual keycode and the type of message (WM_KEYDOWN, WM_KEYUP, ...) So you can set a flag of where the last message came from and then dispatch it to the regular keyboard input handlers.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/91234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7093/" ] }
91,257
We have been using Scrum for around 9 months and it has largely been successful. However our burndown charts rarely look like the 'model' charts, instead resembling more of a terrifying rollercoaster ride with some vomit inducing climbs and drops. To try and combat this we are spending more time before the sprint prototyping and designing but we still seem to discover much more work during the sprint than initially thought. Note: By this I mean the work required to meet the backlog is more involved than first thought rather than we have identified new items for the backlog. Is this a common problem with Scrum and does anyone have any tips to help smooth the ride? I should point out that most of our development work is not greenfield, so we are maintaining functionality in an existing large and complex application. Is scrum less suited to this type of development simply because you don't know what problems the existing code is going to throw up? Just how much time should we be spending before the sprint starts working out the detail of the development? UPDATE: We are having more success and a smoother ride now. This is largely because we have taken a more pessimistic view when estimating which is giving us more breathing space to deal with things when they dont go to plan. You could say its allowing us to be more 'agile'. We are also trying to change the perception that the burn down chart is some kind of schedule rather than an indication of scope v resources.
Some tips on smoothing things out. 1) As others have said - try and break down the tasks into smaller chunks. The more obvious way of doing this is to try and break down the technical tasks in greater detail. Where possible I'd encourage you to talk to the product owner and see if you can reduce scope or "thin" the story instead. I find the latter more effective. Juggling priorities and estimates is easier if both team and product owner understand what's being discussed. My general rule of thumb is any estimate bigger than half an ideal day is probably wrong :-) 2) Try doing shorter sprints. If you're doing one month sprints - try two weeks. If you're doing two weeks - try one. It acts a limiter on story size - encouraging the product owner and the team to work on smaller stories that are easier to estimate accurately You get feedback more often about your estimates - and it's easier to see the connections between the decisions you made at the start of the sprint and what actually happened Everything gets better with practice :-) 3) Use the stand ups and retrospectives to look a bit more at the reasons for the ups and downs. Is it when you spend time with particular areas of the code base? Is it caused by folk misunderstanding the product owner? Random emergencies that take development time away from the team? Once you have more of an understanding where ups and downs are coming from you can often address those problems specifically. Again - shorter sprints can help make this more obvious. 4) Believe your history. You probably know this one... but I'll say it anyway :-) If fiddling with that ghastly legacy Foo package took 3 x longer than you thought it would last sprint - then it will also take 3 x as long as you think the next sprint. No matter how much more effective you think you'll be this time ;-) Trust the history and use things like Yesterday's Weather to guide your estimates in the next spring. Hope this helps!
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/91257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1127460/" ] }
91,275
I'm writing a small tool in C# which will need to send and receive data to/from a website using POST and json formatting. I've never done anything like this before in C# (or any language really) so I'm struggling to find some useful information to get me started. I've found some information on the WebRequest class in C# (specifically from here ) but before I start diving into it, I wondered if this was the right tool for the job. I've found plenty of tools to convert data into the json format but not much else, so any information would be really helpful here in case I end up down a dead end.
WebRequest and more specifically the HttpWebRequest class is a good starting point for what you want to achieve. To create the request you will use the WebRequest.Create and cast the created request to an HttpWebRequest to actually use it. You will then create your post data and send it to the stream like: HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://mysite.com/index.php");req.Method = "POST";req.ContentType = "application/x-www-form-urlencoded";string postData = "var=value1&var2=value2";req.ContentLength = postData.Length;StreamWriter stOut = newStreamWriter(req.GetRequestStream(),System.Text.Encoding.ASCII);stOut.Write(postData);stOut.Close(); Similarly you can read the response back by using the GetResponse method which will allow you to read the resultant response stream and do whatever else you need to do. You can find more info on the class at: http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/91275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
91,305
Is there a easy way to do this? Or do I have to parse the file and do some search/replacing on my own? The ideal would be something like: var myXML: XML = ???; // ... load xml data into the XML objectmyXML.someAttribute = newValue;
Attributes are accessible in AS3 using the @ prefix. For example: var myXML:XML = <test name="something"></test>;trace(myXML.@name);myXML.@name = "new";trace(myXML.@name); Output: somethingnew
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/91305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
91,307
When I use quick documentaion lookup (Ctrl+Q) on j2ee classes or annotations in IDEA I only get an empty javadoc. It only contains the basics like class name. How do I add the javadoc to the libs IDEA provides itself?
You can attach javadoc to any library you have configure in your module or project. Just access the project structure windows (File -> Project Structure) , then select "modules" and select the module that has the dependency you want to configure. Then select the "Dependencies" tab, select the dependency that's missing the javadoc and click "Edit". In the window that just showed up you see two buttons "Add" and "Specify Javadoc URL". If you have the javadoc in a jar file select the first one, if you want to point to a web site that contains the javadoc select the latest.That's it.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/91307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16152/" ] }
91,355
Environment: HP laptop with Windows XP SP2 I had created some encrypted files using GnuPG (gpg) for Windows. Yesterday, my hard disk failed so I had reimage the hard disk. I have now reinstalled gpg and regenerated my keys using the same passphrase as earlier. But, I am now unable to decrypt the files. I get the following error: C:\sureshr>gpg -a c:\sureshr\work\passwords.gpggpg: encrypted with 1024-bit ELG-E key, ID 279AB302, created 2008-07-21 "Suresh Ramaswamy (AAA) BBB"gpg: decryption failed: secret key not availableC:\sureshr>gpg --list-keysC:/Documents and Settings/sureshr/Application Data/gnupg\pubring.gpg--------------------------------------------------------------------pub 1024D/80059241 2008-07-21uid Suresh Ramaswamy (AAA) BBBsub 1024g/279AB302 2008-07-21 AAA = gpg comment BBB = my email address I am sure that I am using the correct passphrase. What exactly does this error mean? How do I tell gpg where to find my secret key? Thanks, Suresh
when reimporting your keys from the old keyring, you need to specify the command: gpg --allow-secret-key-import --import <keyring> otherwise it will only import the public keys, not the private keys.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/91355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
91,357
I want to log in to Stack Overflow with Techorati OpenID hosted at my site. https://stackoverflow.com/users/login has some basic information. I understood that I should change <link rel="openid.delegate" href="http://yourname.x.com" /> to <link rel="openid.delegate" href="http://technorati.com/people/technorati/USERNAME/" /> but if I change <link rel="openid.server" href="http://x.com/server" /> to <link rel="openid.server" href="http://technorati.com/server" /> or <link rel="openid.server" href="http://technorati.com/" /> it does not work.
when reimporting your keys from the old keyring, you need to specify the command: gpg --allow-secret-key-import --import <keyring> otherwise it will only import the public keys, not the private keys.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/91357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17469/" ] }
91,362
How can brackets be escaped in using string.Format ? For example: String val = "1,2,3"String.Format(" foo {{0}}", val); This example doesn't throw an exception, but it outputs the string foo {0} . Is there a way to escape the brackets?
For you to output foo {1, 2, 3} you have to do something like: string t = "1, 2, 3";string v = String.Format(" foo {{{0}}}", t); To output a { you use {{ and to output a } you use }} . Or now, you can also use C# string interpolation like this (a feature available in C# 6.0) Escaping brackets: String interpolation $("") . It is new feature in C# 6.0. var inVal = "1, 2, 3";var outVal = $" foo {{{inVal}}}";// The output will be: foo {1, 2, 3}
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/91362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4685/" ] }
91,368
From a shell script, how do I check if a directory contains files? Something similar to this if [ -e /some/dir/* ]; then echo "huzzah"; fi; but which works if the directory contains one or several files (the above one only works with exactly 0 or 1 files).
The solutions so far use ls . Here's an all bash solution: #!/bin/bashshopt -s nullglob dotglob # To include hidden filesfiles=(/some/dir/*)if [ ${#files[@]} -gt 0 ]; then echo "huzzah"; fi
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/91368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17491/" ] }
91,384
I'm working on a large c++ system that is has been in development for a few years now. As part of an effort to improve the quality of the existing code we engaged on a large long-term refactoring project. Do you know a good tool that can help me write unit tests in C++? Maybe something similar to Junit or Nunit? Can anyone give some good advice on the methodology of writing unit tests for modules that were written without unit testing in mind?
Applying unit tests to legacy code was the very reason Working Effectively with Legacy Code was written. Michael Feathers is the author - as mentioned in other answers, he was involved in the creation of both CppUnit and CppUnitLite .
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/91384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12818/" ] }
91,518
Suppose I have a simple XHTML document that uses a custom namespace for attributes: <html xmlns="..." xmlns:custom="http://www.example.com/ns"> ... <div class="foo" custom:attr="bla"/> ...</html> How do I match each element that has a certain custom attribute using jQuery? Using $("div[custom:attr]") does not work. (Tried with Firefox only, so far.)
jQuery does not support custom namespaces directly, but you can find the divs you are looking for by using filter function. // find all divs that have custom:attr$('div').filter(function() { return $(this).attr('custom:attr'); }).each(function() { // matched a div with custom::attr $(this).html('I was found.');});
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/91518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7779/" ] }
91,563
How can I make this work? switch(property.PropertyType){ case typeof(Boolean): //doStuff break; case typeof(String): //doOtherStuff break; default: break;} I don't want to use the name since string comparing for types is just awfull and can be subject to change.
System.Type propertyType = typeof(Boolean); System.TypeCode typeCode = Type.GetTypeCode(propertyType); switch (typeCode) { case TypeCode.Boolean: //doStuff break; case TypeCode.String: //doOtherStuff break; default: break; } You can use an hybrid approach for TypeCode.Object where you dynamic if with typeof. This is very fast because for the first part - the switch - the compiler can decide based on a lookup table.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/91563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ] }
91,576
I'm building a project using a GNU tool chain and everything works fine until I get to linking it, where the linker complains that it is missing/can't find crti.o . This is not one of my object files, it seems to be related to libc but I can't understand why it would need this crti.o , wouldn't it use a library file, e.g. libc.a ? I'm cross compiling for the arm platform. I have the file in the toolchain, but how do I get the linker to include it? crti.o is on one of the 'libraries' search path, but should it look for .o file on the library path? Is the search path the same for gcc and ld ?
crti.o is the bootstrap library, generally quite small. It's usually statically linked into your binary. It should be found in /usr/lib . If you're running a binary distribution they tend to put all the developer stuff into -dev packages (e.g. libc6-dev) as it's not needed to run compiled programs, just to build them. You're not cross-compiling are you? If you're cross-compiling it's usually a problem with gcc's search path not matching where your crti.o is. It should have been built when the toolchain was. The first thing to check is gcc -print-search-dirs and see if crti.o is in any of those paths. The linking is actually done by ld but it has its paths passed down to it by gcc. Probably the quickest way to find out what's going on is compile a helloworld.c program and strace it to see what is getting passed to ld and see what's going on. strace -v -o log -f -e trace=open,fork,execve gcc hello.c -o test Open the log file and search for crti.o, as you can see my non-cross compiler: 10616 execve("/usr/bin/ld", ["/usr/bin/ld", "--eh-frame-hdr", "-m", "elf_x86_64", "--hash-style=both", "-dynamic-linker", "/lib64/ld-linux-x86-64.so.2", "-o", "test", "/usr/lib/gcc/x86_64-linux-gnu/4."..., "/usr/lib/gcc/x86_64-linux-gnu/4."..., "/usr/lib/gcc/x86_64-linux-gnu/4."..., "-L/usr/lib/gcc/x86_64-linux-gnu/"..., "-L/usr/lib/gcc/x86_64-linux-gnu/"..., "-L/usr/lib/gcc/x86_64-linux-gnu/"..., "-L/lib/../lib", "-L/usr/lib/../lib", "-L/usr/lib/gcc/x86_64-linux-gnu/"..., "/tmp/cc4rFJWD.o", "-lgcc", "--as-needed", "-lgcc_s", "--no-as-needed", "-lc", "-lgcc", "--as-needed", "-lgcc_s", "--no-as-needed", "/usr/lib/gcc/x86_64-linux-gnu/4."..., "/usr/lib/gcc/x86_64-linux-gnu/4."...], "COLLECT_GCC=gcc", "COLLECT_GCC_OPTIONS=\'-o\' \'test\' "..., "COMPILER_PATH=/usr/lib/gcc/x86_6"..., "LIBRARY_PATH=/usr/lib/gcc/x86_64"..., "COLLECT_NO_DEMANGLE="]) = 010616 open("/etc/ld.so.cache", O_RDONLY) = 310616 open("/usr/lib/libbfd-2.18.0.20080103.so", O_RDONLY) = 310616 open("/lib/libc.so.6", O_RDONLY) = 310616 open("test", O_RDWR|O_CREAT|O_TRUNC, 0666) = 310616 open("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/../../../../lib/crt1.o", O_RDONLY) = 410616 open("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/../../../../lib/crti.o", O_RDONLY) = 510616 open("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/crtbegin.o", O_RDONLY) = 610616 open("/tmp/cc4rFJWD.o", O_RDONLY) = 7 If you see a bunch of attempts to open(...crti.o) = -1 ENOENT , ld is getting confused and you want to see where the path it's opening came from...
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/91576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/76121/" ] }
91,616
What is the easiest cross platform widget toolkit? I'm looking for one that minimally covers Windows, OSX, and Linux with a C or C++ interface.
I don't know of any I've personally used with a C API, but wxWidgets is C++. It runs on Windows, Linux, and Mac OS X. And if you're looking for easy, wxPython is a Python wrapper around wxWidgets and it is pretty easy to use.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/91616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17398/" ] }
91,683
I believe strongly in using unit-tests as part of building large multi-platform applications. We currently are planning on having our unit-tests within a separate project. This has the benefit of keeping our code base clean. I think, however, that this would separate the test code from the implementation of the unit. What do you think of this approach and are there any tools like JUnit for c++ applications?
There are many Test Unit frameforks for C++.CppUnit is certainly not the one I would choose (at least in its stable version 1.x, as it lacks many tests, and requires a lot of redundant lines of codes).So far, my preferred framework is CxxTest , and I plan on evaluating Fructose some day. Any way, there are a few "papers" that evaluate C++ TU frameworks : Exploring the C++ Unit Testing Framework Jungle , By Noel Llopis an article in Overload Journal #78
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/91683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/97554/" ] }
91,688
What are the differences between a clustered and a non-clustered index ?
Clustered Index Only one per table Faster to read than non clustered as data is physically stored in index order Non Clustered Index Can be used many times per table Quicker for insert and update operations than a clustered index Both types of index will improve performance when select data with fields that use the index but will slow down update and insert operations. Because of the slower insert and update clustered indexes should be set on a field that is normally incremental ie Id or Timestamp. SQL Server will normally only use an index if its selectivity is above 95%.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/91688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6522/" ] }
91,692
Can anyone recommend a framework for templating/formatting messages in a standalone application along the lines of the JSP EL (Expression Language)? I would expect to be able to instantiate a an object of some sort, give it a template along the lines of Dear ${customer.firstName}. You order will be dispatched on ${order.estimatedDispatchDate} provide it with a context which would include a value dictionary of parameter objects (in this case an object of type Customer with a name 'customer', say, and an object of type Order with a name 'order'). I know there are many template frameworks out there - many of which work outside the web application context, but I do not see this as a big heavyweight templating framework. Just a better version of the basic Message Format functionality Java already provides For example, I can accomplish the above with java.text.MessageFormat by using a template (or a 'pattern' as they call it) such as Dear {0}. You order will be dispatched on {1,date,EEE dd MMM yyyy} and I can pass it an Object array, in my calling Java program new Object[] { customer.getFirstName(), order.getEstimatedDispatchDate() }; However, in this usage, the code and the pattern are intimately linked. While I could put the pattern in a resource properties file, the code and the pattern need to know intimate details about each other. With an EL-like system, the contract between the code and the pattern would be at a much higher level (e.g. customer and order, rather then customer.firstName and order.estimatedDispatchDate), making it easier to change the structure, order and contents of the message without changing any code.
You can just use the Universal Expression Language itself. You need an implementation (but there are a few to choose from). After that, you need to implement three classes: ELResolver, FunctionMapper and VariableMapper. This blog post describes how to do it: Java: using EL outside J2EE .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/91692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15452/" ] }
91,745
I am building a table using the DataGridView where a user can select items from a dropdown in each cell. To simplify the problem, lets say i have 1 column. I am using the DataGridViewComboBoxColumn in the designer. I am trying to support having each row in that column have a different list of items to choose from. Is this possible?
Yes. This can be done using the DataGridViewComboBoxCell. Here is an example method to add the items to just one cell, rather than the whole column. private void setCellComboBoxItems(DataGridView dataGrid, int rowIndex, int colIndex, object[] itemsToAdd){ DataGridViewComboBoxCell dgvcbc = (DataGridViewComboBoxCell) dataGrid.Rows[rowIndex].Cells[colIndex]; // You might pass a boolean to determine whether to clear or not. dgvcbc.Items.Clear(); foreach (object itemToAdd in itemsToAdd) { dgvcbc.Items.Add(itemToAdd); }}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/91745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ] }
91,747
How can I set the background color of a specific item in a System.Windows.Forms.ListBox ? I would like to be able to set multiple ones if possible.
Probably the only way to accomplish that is to draw the items yourself. Set the DrawMode to OwnerDrawFixed and code something like this on the DrawItem event: private void listBox_DrawItem(object sender, DrawItemEventArgs e){ e.DrawBackground(); Graphics g = e.Graphics; g.FillRectangle(new SolidBrush(Color.Silver), e.Bounds); // Print text e.DrawFocusRectangle();} The second option would be using a ListView, although they have an other way of implementations (not really data bound, but more flexible in way of columns).
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/91747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11137/" ] }
91,778
To create a new event handler on a control you can do this c.Click += new EventHandler(mainFormButton_Click); or this c.Click += mainFormButton_Click; and to remove an event handler you can do this c.Click -= mainFormButton_Click; But how do you remove all event handlers from an event?
I found a solution on the MSDN forums . The sample code below will remove all Click events from button1 . public partial class Form1 : Form{ public Form1() { InitializeComponent(); button1.Click += button1_Click; button1.Click += button1_Click2; button2.Click += button2_Click; } private void button1_Click(object sender, EventArgs e) => MessageBox.Show("Hello"); private void button1_Click2(object sender, EventArgs e) => MessageBox.Show("World"); private void button2_Click(object sender, EventArgs e) => RemoveClickEvent(button1); private void RemoveClickEvent(Button b) { FieldInfo f1 = typeof(Control).GetField("EventClick", BindingFlags.Static | BindingFlags.NonPublic); object obj = f1.GetValue(b); PropertyInfo pi = b.GetType().GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance); EventHandlerList list = (EventHandlerList)pi.GetValue(b, null); list.RemoveHandler(obj, list[obj]); }}
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/91778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7297/" ] }
91,784
I have a table with say 3 columns. There's no primary key so there can be duplicate rows. I need to just keep one and delete the others. Any idea how to do this is Sql Server?
I'd SELECT DISTINCT the rows and throw them into a temporary table, then drop the source table and copy back the data from the temp. EDIT: now with code snippet! INSERT INTO TABLE_2 SELECT DISTINCT * FROM TABLE_1GODELETE FROM TABLE_1GOINSERT INTO TABLE_1SELECT * FROM TABLE_2GO
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/91784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1688440/" ] }
91,791
When doing shell scripting, typically data will be in files of single line records like csv. It's really simple to handle this data with grep and sed . But I have to deal with XML often, so I'd really like a way to script access to that XML data via the command line. What are the best tools?
I've found xmlstarlet to be pretty good at this sort of thing. http://xmlstar.sourceforge.net/ Should be available in most distro repositories, too. An introductory tutorial is here: http://www.ibm.com/developerworks/library/x-starlet.html
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/91791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16981/" ] }
91,810
Working with python interactively, it's sometimes necessary to display a result which is some arbitrarily complex data structure (like lists with embedded lists, etc.)The default way to display them is just one massive linear dump which just wraps over and over and you have to parse carefully to read it. Is there something that will take any python object and display it in a more rational manner. e.g. [0, 1, [a, b, c], 2, 3, 4] instead of: [0, 1, [a, b, c], 2, 3, 4] I know that's not a very good example, but I think you get the idea.
from pprint import pprinta = [0, 1, ['a', 'b', 'c'], 2, 3, 4]pprint(a) Note that for a short list like my example, pprint will in fact print it all on one line. However, for more complex structures it does a pretty good job of pretty printing data.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/91810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4086/" ] }
91,817
I discovered that you can start your variable name with a '@' character in C#. In my C# project I was using a web service (I added a web reference to my project) that was written in Java. One of the interface objects defined in the WSDL had a member variable with the name "params". Obviously this is a reserved word in C# so you can't have a class with a member variable with the name "params". The proxy object that was generated contained a property that looked like this: public ArrayList @params { get { return this.paramsField; } set { this.paramsField = value; }} I searched through the VS 2008 c# documentation but couldn't find anything about it. Also searching Google didn't give me any useful answers. So what is the exact meaning or use of the '@' character in a variable/property name?
Straight from the C# Language Specification , Identifiers (C#) : The prefix "@" enables the use of keywords as identifiers, which is useful when interfacing with other programming languages. The character @ is not actually part of the identifier, so the identifier might be seen in other languages as a normal identifier, without the prefix. An identifier with an @ prefix is called a verbatim identifier.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/91817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13287/" ] }
91,831
Say I have the following web.config: <?xml version="1.0" encoding="utf-8"?><configuration> <system.web> <authentication mode="Windows"></authentication> </system.web></configuration> Using ASP.NET C#, how can I detect the Mode value of the Authentication tag?
The mode property from the authenticationsection: AuthenticationSection.Mode Property (System.Web.Configuration) . And you can even modify it. // Get the current Mode property.AuthenticationMode currentMode = authenticationSection.Mode;// Set the Mode property to Windows.authenticationSection.Mode = AuthenticationMode.Windows; This article describes how to get a reference to the AuthenticationSection .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/91831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ] }
91,856
Would the following SQL remove also the index - or does it have to be removed separately? CREATE TABLE #Tbl (field int)CREATE NONCLUSTERED INDEX idx ON #Tbl (field)DROP TABLE #Tbl
Yes they are. You can search in MSSQL help for CREATE INDEX article it is said there: "Indexes can be created on a temporary table. When the table is dropped or the session ends, all indexes and triggers are dropped."
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/91856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2133/" ] }
91,899
I'm using grep to generate a list of files I need to move: grep -L -r 'Subject: \[SPAM\]' . How can I pass this list to the mv command and move the files somewhere else?
If you want to find and move files that do not match your pattern (move files that don't contain 'Subject \[SPAM\]' in this example) use: grep -L -Z -r 'Subject: \[SPAM\]' . | xargs -0 -I{} mv {} DIR The -Z means output with zeros (\0) after the filenames (so spaces are not used as delimeters). xargs -0 means interpret \0 to be delimiters. The -L means find files that do not match the pattern. Replace -L with -l if you want to move files that match your pattern. Then -I{} mv {} DIR means replace {} with the filenames, so you get mv filenames DIR .
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/91899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17582/" ] }
91,932
How does it work, what is it used for and when should one use it?
Let's explain the strategy pattern the easy way: You have a class Car() with a method run() , so you use it this way in a pseudo language: mycar = new Car()mycar.run() Now, you may want to change the run() behavior on the fly, while the program is executing. For example, you might want to simulate a motor failure or the use of a "boost" button in a video game. There are several ways to do this simulation: using conditional statements and a flag variable is one way. The strategy pattern is another: it delegates the behavior of the run() method to another class: Class Car(){ this.motor = new Motor(this) // passing "this" is important for the motor so it knows what it is running method run() { this.motor.run() } method changeMotor(motor) { this.motor = motor }} If you want to change the car's behavior, you can just change the motor. (Easier in a program than in real life, right? ;-) ) It's very useful if you have a lot of complex states: you can change and maintain them much more easily.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/91932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2695/" ] }
91,984
When I use CTRL + H I end up on the Java Search tab. I would very much like a shortcut to go directly to File Search instead. Is that possible? See image here for what I'm talking about:
You can just define a key binding that opens the file search: Go to Preferences > General > Keys Type "file search" in the search box. (If there are no results, and you have a really old Eclipse version, select the Include Unbound Commands check box.) Put the caret into the Binding text box and press the key combination you want to use: You can either re-use the CTRL + H binding (delete the other binding in that case) or define another one (e.g. CTRL + SHIFT + H ). To delete the other binding search for "Open Search Dialog" and click on Unbind Command . Other solution: You could press CTRL + 3 in your editor, type in "file s", press Enter . The next time you press CTRL + 3 "File Search" is at the top.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/91984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/86/" ] }
91,986
I've got the following SQL: select * from transaction_log where stoptime like '%2008%' How do I write this in LINQ to SQL syntax?
If you want to use the literal method, it's like this: var query = from l in transaction_log where SqlMethods.Like(l.stoptime, "%2008%") select l; Another option is: var query = from l in transaction_log where l.stoptime.Contains("2008") select l; If it's a DateTime: var query = from l in transaction_log where l.stoptime.Year = 2008 select l; That method is in the System.Data.Linq.SqlClient namespace
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/91986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1683/" ] }
92,001
AKA - What's this obsession with pointers? Having only really used modern, object oriented languages like ActionScript, Java and C#, I don't really understand the importance of pointers and what you use them for. What am I missing out on here?
It's all just indirection: The ability to not deal with data, but say "I'll direct you to some data, over there". You have the same concept in Java and C#, but only in reference format. The key differences are that references are effectively immutable signposts - they always point to something. This is useful, and easy to understand, but less flexible than the C pointer model. C pointers are signposts that you can happily rewrite. You know that the string you're looking for is next door to the string being pointed at? Well, just slightly alter the signpost. This couples well with C's "close to the bone, low level knowledge required" approach. We know that a char* foo consists of a set of characters beginning at the location pointed to by the foo signpost. If we also know that the string is at least 10 characters long, we can change the signpost to (foo + 5) to point at then same string, but start half the length in. This flexibility is useful when you know what you're doing, and death if you don't (where "know" is more than just "know the language", it's "know the exact state of the program"). Get it wrong, and your signpost is directing you off the edge of a cliff. References don't let you fiddle, so you're much more confident that you can follow them without risk (especially when coupled with rules like "A referenced object will never disappear", as in most Garbage collected languages).
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/92001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11911/" ] }
92,006
I have an algorithm that generates strings based on a list of input words. How do I separate only the strings that sounds like English words? ie. discard RDLO while keeping LORD . EDIT: To clarify, they do not need to be actual words in the dictionary. They just need to sound like English. For example KEAL would be accepted.
You can build a markov-chain of a huge english text. Afterwards you can feed words into the markov chain and check how high the probability is that the word is english. See here: http://en.wikipedia.org/wiki/Markov_chain At the bottom of the page you can see the markov text generator. What you want is exactly the reverse of it. In a nutshell: The markov-chain stores for each character the probabilities of which next character will follow. You can extend this idea to two or three characters if you have enough memory.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/92006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/976/" ] }
92,043
I've tried the tools listed here , some with more success than others, but none gave me valid postgres syntax I could use (tinyint errors etc.)
There's a mysqldump option which makes it output PostgreSQL code: mysqldump --compatible=postgresql ... But that doesn't work too well. Instead, please see the mysql-to-postgres tool as described in Linus Oleander's answer .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/92043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4196/" ] }
92,082
How can I add a column with a default value to an existing table in SQL Server 2000 / SQL Server 2005 ?
Syntax: ALTER TABLE {TABLENAME} ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL} CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}WITH VALUES Example: ALTER TABLE SomeTable ADD SomeCol Bit NULL --Or NOT NULL. CONSTRAINT D_SomeTable_SomeCol --When Omitted a Default-Constraint Name is autogenerated. DEFAULT (0)--Optional Default-Constraint.WITH VALUES --Add if Column is Nullable and you want the Default Value for Existing Records. Notes: Optional Constraint Name: If you leave out CONSTRAINT D_SomeTable_SomeCol then SQL Server will autogenerate a Default-Contraint with a funny Name like: DF__SomeTa__SomeC__4FB7FEF6 Optional With-Values Statement: The WITH VALUES is only needed when your Column is Nullable and you want the Default Value used for Existing Records. If your Column is NOT NULL , then it will automatically use the Default Value for all Existing Records, whether you specify WITH VALUES or not. How Inserts work with a Default-Constraint: If you insert a Record into SomeTable and do not Specify SomeCol 's value, then it will Default to 0 . If you insert a Record and Specify SomeCol 's value as NULL (and your column allows nulls), then the Default-Constraint will not be used and NULL will be inserted as the Value. Notes were based on everyone's great feedback below. Special Thanks to: @Yatrix, @WalterStabosz, @YahooSerious, and @StackMan for their Comments.
{ "score": 13, "source": [ "https://Stackoverflow.com/questions/92082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7241/" ] }
92,093
I am working on a SQL query that reads from a SQLServer database to produce an extract file. One of the requirements to remove the leading zeroes from a particular field, which is a simple VARCHAR(10) field. So, for example, if the field contains '00001A', the SELECT statement needs to return the data as '1A'. Is there a way in SQL to easily remove the leading zeroes in this way? I know there is an RTRIM function, but this seems only to remove spaces.
select substring(ColumnName, patindex('%[^0]%',ColumnName), 10)
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/92093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7585/" ] }
92,100
Is it possible to set code behind a resource dictionary in WPF. For example in a usercontrol for a button you declare it in XAML. The event handling code for the button click is done in the code file behind the control. If I was to create a data template with a button how can I write the event handler code for it's button click within the resource dictionary.
I think what you're asking is you want a code-behind file for a ResourceDictionary. You can totally do this! In fact, you do it the same way as for a Window: Say you have a ResourceDictionary called MyResourceDictionary. In your MyResourceDictionary.xaml file, put the x:Class attribute in the root element, like so: <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="MyCompany.MyProject.MyResourceDictionary" x:ClassModifier="public"> Then, create a code behind file called MyResourceDictionary.xaml.cs with the following declaration: namespace MyCompany.MyProject{ partial class MyResourceDictionary : ResourceDictionary { public MyResourceDictionary() { InitializeComponent(); } ... // event handlers ahead.. }} And you're done. You can put whatever you wish in the code behind: methods, properties and event handlers. == Update for Windows 10 apps == And just in case you are playing with UWP there is one more thing to be aware of: <Application x:Class="SampleProject.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:rd="using:MyCompany.MyProject"><!-- no need in x:ClassModifier="public" in the header above --> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <!-- This will NOT work --> <!-- <ResourceDictionary Source="/MyResourceDictionary.xaml" />--> <!-- Create instance of your custom dictionary instead of the above source reference --> <rd:MyResourceDictionary /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources></Application>
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/92100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6204/" ] }
92,103
What do you find is the optimal setting for mysql slow query log parameter, and why?
I recommend these three lines log_slow_queriesset-variable = long_query_time=1log-queries-not-using-indexes The first and second will log any query over a second. As others have pointed out a one second query is pretty far gone if you are a shooting for a high transaction rate on your website, but I find that it turns up some real WTFs; queries that should be fast, but for whatever combination of data it was run against was not. The last will log any query that does not use an index. Unless your doing data warehousing any common query should have the best index you can find so pay attention to its output. Although its certainly not for production, this last option log = /var/log/mysql/mysql.log will log all queries, which can be useful if you are trying to tune a specific page or action.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/92103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10596/" ] }
92,114
There is a limitation on Windows Server 2003 that prevents you from copying extremely large files, in proportion to the amount of RAM you have. The limitation is in the CopyFile and CopyFileEx functions, which are used by xcopy, Explorer, Robocopy, and the .NET FileInfo class. Here is the error that you get: Cannot copy [filename]: Insufficient system resources exist to complete the requested service. The is a knowledge base article on the subject, but it pertains to NT4 and 2000. There is also a suggestion to use ESEUTIL from an Exchange installation, but I haven't had any luck getting that to work. Does anybody know of a quick, easy way to handle this? I'm talking about >50Gb on a machine with 2Gb of RAM. I plan to fire up Visual Studio and just write something to do it for me, but it would be nice to have something that was already out there, stable and well-tested. [Edit] I provided working C# code to accompany the accepted answer.
The best option is to just open the original file for reading, the destination file for writing and then loop copying it block by block. In pseudocode : f1 = open(filename1);f2 = open(filename2, "w");while( !f1.eof() ) { buffer = f1.read(buffersize); err = f2.write(buffer, buffersize); if err != NO_ERROR_CODE break;}f1.close(); f2.close(); [Edit by Asker] Ok, this is how it looks in C# (it's slow but it seems to work Ok, and it gives progress): using System;using System.Collections.Generic;using System.IO;using System.Text;namespace LoopCopy{ class Program { static void Main(string[] args) { if (args.Length != 2) { Console.WriteLine( "Usage: LoopCopy.exe SourceFile DestFile"); return; } string srcName = args[0]; string destName = args[1]; FileInfo sourceFile = new FileInfo(srcName); if (!sourceFile.Exists) { Console.WriteLine("Source file {0} does not exist", srcName); return; } long fileLen = sourceFile.Length; FileInfo destFile = new FileInfo(destName); if (destFile.Exists) { Console.WriteLine("Destination file {0} already exists", destName); return; } int buflen = 1024; byte[] buf = new byte[buflen]; long totalBytesRead = 0; double pctDone = 0; string msg = ""; int numReads = 0; Console.Write("Progress: "); using (FileStream sourceStream = new FileStream(srcName, FileMode.Open)) { using (FileStream destStream = new FileStream(destName, FileMode.CreateNew)) { while (true) { numReads++; int bytesRead = sourceStream.Read(buf, 0, buflen); if (bytesRead == 0) break; destStream.Write(buf, 0, bytesRead); totalBytesRead += bytesRead; if (numReads % 10 == 0) { for (int i = 0; i < msg.Length; i++) { Console.Write("\b \b"); } pctDone = (double) ((double)totalBytesRead / (double)fileLen); msg = string.Format("{0}%", (int)(pctDone * 100)); Console.Write(msg); } if (bytesRead < buflen) break; } } } for (int i = 0; i < msg.Length; i++) { Console.Write("\b \b"); } Console.WriteLine("100%"); Console.WriteLine("Done"); } }}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/92114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219/" ] }
92,230
I've gotten to grips with the basics of Python and I've got a small holiday which I want to use some of to learn a little more Python. The problem is that I have no idea what to learn or where to start. I'm primarily web development but in this case I don't know how much difference it will make.
Well, there are great ressources for advanced Python programming : Dive Into Python ( read it for free ) Online python cookbooks (e.g. here and there ) O'Reilly's Python Cookbook (see amazon) A funny riddle game : Python Challenge Here is a list of subjects you must master if you want to write "Python" on your resume : list comprehensions iterators and generators decorators They are what make Python such a cool language (with the standard library of course, that I keep discovering everyday).
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/92230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ] }
92,239
If you have several div s on a page, you can use CSS to size, float them and move them round a little... but I can't see a way to get past the fact that the first div will show near the top of the page and the last div will be near the bottom! I cannot completely override the order of the elements as they come from the source HTML, can you? I must be missing something because people say "we can change the look of the whole website by just editing one CSS file.", but that would depend on you still wanting the div s in the same order! (P.S. I am sure no one uses position:absolute on every element on a page.)
CSS can take elements out of the normal flow and position them anywhere, in any manner you want. But it cannot create a new flow . By this I mean that you can position the last item from the html document at the beginning/top of the page/window, and you can position the first item from the html document at the end/bottom of the page/window. But when you do this you can't position these items relative to each other; you have to know for yourself how far down the end of the page will be for the first item from the html document to be positioned correctly. If that content is dynamic (ie: from a database or CMS), this can be far from trivial.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/92239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11461/" ] }
92,328
Within an event, I'd like to put the focus on a specific TextBox within the ListViewItem's template. The XAML looks like this: <ListView x:Name="myList" ItemsSource="{Binding SomeList}"> <ListView.View> <GridView> <GridViewColumn> <GridViewColumn.CellTemplate> <DataTemplate> <!-- Focus this! --> <TextBox x:Name="myBox"/> I've tried the following in the code behind: (myList.FindName("myBox") as TextBox).Focus(); but I seem to have misunderstood the FindName() docs, because it returns null . Also the ListView.Items doesn't help, because that (of course) contains my bound business objects and no ListViewItems. Neither does myList.ItemContainerGenerator.ContainerFromItem(item) , which also returns null.
To understand why ContainerFromItem didn't work for me, here some background. The event handler where I needed this functionality looks like this: var item = new SomeListItem();SomeList.Add(item);ListViewItem = SomeList.ItemContainerGenerator.ContainerFromItem(item); // returns null After the Add() the ItemContainerGenerator doesn't immediately create the container, because the CollectionChanged event could be handled on a non-UI-thread. Instead it starts an asynchronous call and waits for the UI thread to callback and execute the actual ListViewItem control generation. To be notified when this happens, the ItemContainerGenerator exposes a StatusChanged event which is fired after all Containers are generated. Now I have to listen to this event and decide whether the control currently want's to set focus or not.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/92328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4918/" ] }
92,376
Is there any way that I can programmatically create (and I guess access) hidden folders on a storage device from within c#?
using System.IO; string path = @"c:\folders\newfolder"; // or whatever if (!Directory.Exists(path)) { DirectoryInfo di = Directory.CreateDirectory(path); di.Attributes = FileAttributes.Directory | FileAttributes.Hidden; }
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/92376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1816/" ] }
92,396
I've always wondered this - why can't you declare variables after a case label in a switch statement? In C++ you can declare variables pretty much anywhere (and declaring them close to first use is obviously a good thing) but the following still won't work: switch (val) { case VAL: // This won't work int newVal = 42; break;case ANOTHER_VAL: ... break;} The above gives me the following error (MSC): initialization of 'newVal' is skipped by 'case' label This seems to be a limitation in other languages too. Why is this such a problem?
Case statements are only labels . This means the compiler will interpret this as a jump directly to the label. In C++, the problem here is one of scope. Your curly brackets define the scope as everything inside the switch statement. This means that you are left with a scope where a jump will be performed further into the code skipping the initialization. The correct way to handle this is to define a scope specific to that case statement and define your variable within it: switch (val){ case VAL: { // This will work int newVal = 42; break;}case ANOTHER_VAL: ...break;}
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/92396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ] }
92,427
Based on a simple test I ran, I don't think it's possible to put an inline <style> tag into an ASP.NET server control. The style did not end up rendering to the output HTML. Even if it was possible, I'm sure it is bad practice to do this. Is it possible to do this? I can see it being useful for quick prototypes that just have 1 or 2 CSS classes to apply.
Intellisense won't give you hints but you can do this: <asp:Label ID="Label1" runat="server" Text="Label" style="color:Red;"></asp:Label>
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/92427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2470/" ] }
92,438
I use to run $s =~ s/[^[:print:]]//g; on Perl to get rid of non printable characters. In Python there's no POSIX regex classes, and I can't write [:print:] having it mean what I want. I know of no way in Python to detect if a character is printable or not. What would you do? EDIT: It has to support Unicode characters as well. The string.printable way will happily strip them out of the output. curses.ascii.isprint will return false for any unicode character.
Iterating over strings is unfortunately rather slow in Python. Regular expressions are over an order of magnitude faster for this kind of thing. You just have to build the character class yourself. The unicodedata module is quite helpful for this, especially the unicodedata.category() function. See Unicode Character Database for descriptions of the categories. import unicodedata, re, itertools, sysall_chars = (chr(i) for i in range(sys.maxunicode))categories = {'Cc'}control_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories)# or equivalently and much more efficientlycontrol_chars = ''.join(map(chr, itertools.chain(range(0x00,0x20), range(0x7f,0xa0))))control_char_re = re.compile('[%s]' % re.escape(control_chars))def remove_control_chars(s): return control_char_re.sub('', s) For Python2 import unicodedata, re, sysall_chars = (unichr(i) for i in xrange(sys.maxunicode))categories = {'Cc'}control_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories)# or equivalently and much more efficientlycontrol_chars = ''.join(map(unichr, range(0x00,0x20) + range(0x7f,0xa0)))control_char_re = re.compile('[%s]' % re.escape(control_chars))def remove_control_chars(s): return control_char_re.sub('', s) For some use-cases, additional categories (e.g. all from the control group might be preferable, although this might slow down the processing time and increase memory usage significantly. Number of characters per category: Cc (control): 65 Cf (format): 161 Cs (surrogate): 2048 Co (private-use): 137468 Cn (unassigned): 836601 Edit Adding suggestions from the comments.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/92438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5190/" ] }
92,452
I've been working on this for a few days now, and I've found several solutions but none of them incredibly simple or lightweight. The problem is basically this: We have a cluster of 10 machines, each of which is running the same software on a multithreaded ESB platform. I can deal with concurrency issues between threads on the same machine fairly easily, but what about concurrency on the same data on different machines? Essentially the software receives requests to feed a customer's data from one business to another via web services. However, the customer may or may not exist yet on the other system. If it does not, we create it via a web service method. So it requires a sort of test-and-set, but I need a semaphore of some sort to lock out the other machines from causing race conditions. I've had situations before where a remote customer was created twice for a single local customer, which isn't really desirable. Solutions I've toyed with conceptually are: Using our fault-tolerant shared file system to create "lock" files which will be checked for by each machine depending on the customer Using a special table in our database, and locking the whole table in order to do a "test-and-set" for a lock record. Using Terracotta, an open source server software which assists in scaling, but uses a hub-and-spoke model. Using EHCache for synchronous replication of my in-memory "locks." I can't imagine that I'm the only person who's ever had this kind of problem. How did you solve it? Did you cook something up in-house or do you have a favorite 3rd-party product?
you might want to consider using Hazelcast distributed locks. Super lite and easy. java.util.concurrent.locks.Lock lock = Hazelcast.getLock ("mymonitor");lock.lock ();try {// do your stuff}finally { lock.unlock();} Hazelcast - Distributed Queue, Map, Set, List, Lock
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/92452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7567/" ] }
92,455
In my multithreaded application and I see heavy lock contention in it, preventing good scalability across multiple cores. I have decided to use lock free programming to solve this. How can I write a lock free structure?
Short answer is: You cannot. Long answer is: If you are asking this question, you do not probably know enough to be able to create a lock free structure. Creating lock free structures is extremely hard, and only experts in this field can do it. Instead of writing your own, search for an existing implementation. When you find it, check how widely it is used, how well is it documented, if it is well proven, what are the limitations - even some lock free structure other people published are broken. If you do not find a lock free structure corresponding to the structure you are currently using, rather adapt the algorithm so that you can use some existing one. If you still insist on creating your own lock free structure, be sure to: start with something very simple understand memory model of your target platform (including read/write reordering constraints, what operations are atomic) study a lot about problems other people encountered when implementing lock free structures do not just guess if it will work, prove it heavily test the result More reading: Lock free and wait free algorithms at Wikipedia Herb Sutter: Lock-Free Code: A False Sense of Security
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/92455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16673/" ] }
92,504
I'm trying to create a self signed certificate for use with Apache Tomcat 6. Every certificate I can make always results in the browser connecting with AES-128. The customer would like me to demonstrate that I can create a connection at AES-256. I've tried java's keytool and openssl. I've tried with a variety of parameters, but can't seem to specify anything about the keysize, just the signature size. How can I get the browser-tomcat connection to use AES-256 with a self signed certificate?
Okie doke, I think I just figured this out. As I said above, the key bit of knowledge is that the cert doesn't matter, so long as it's generated with an algorithm that supports AES 256-bit encryption (e.g., RSA). Just to make sure that we're on the same page, for my testing, I generated my self-signed cert using the following: keytool -genkey -alias tomcat -keyalg RSA Now, you have to make sure that your Java implementation on your server supports AES-256, and this is the tricky bit. I did my testing on an OS X (OS 10.5) box, and when I checked to see the list of ciphers that it supported by default, AES-256 was NOT on the list, which is why using that cert I generated above only was creating an AES-128 connection between my browser and Tomcat. (Well, technically, TLS_RSA_WITH_AES_256_CBC_SHA was not on the list -- that's the cipher that you want, according to this JDK 5 list .) For completeness, here's the short Java app I created to check my box's supported ciphers: import java.util.Arrays;import javax.net.ssl.SSLSocketFactory;public class CipherSuites { public static void main(String[] args) { SSLSocketFactory sslsf = (SSLSocketFactory) SSLSocketFactory.getDefault(); String[] ciphers = sslsf.getDefaultCipherSuites(); Arrays.sort(ciphers); for (String cipher : ciphers) { System.out.println(cipher); } }} It turns out that JDK 5, which is what this OS X box has installed by default, needs the "Unlimited Strength Jurisdiction Policy Files" installed in order to tell Java that it's OK to use the higher-bit encryption levels; you can find those files here (scroll down and look at the top of the "Other Downloads" section). I'm not sure offhand if JDK 6 needs the same thing done, but the same policy files for JDK 6 are available here , so I assume it does. Unzip that file, read the README to see how to install the files where they belong, and then check your supported ciphers again... I bet AES-256 is now on the list. If it is, you should be golden; just restart Tomcat, connect to your SSL instance, and I bet you'll now see an AES-256 connection.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/92504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17583/" ] }
92,522
What is the best way to issue a http get in VB.net? I want to get the result of a request like http://api.hostip.info/?ip=68.180.206.184
In VB.NET: Dim webClient As New System.Net.WebClientDim result As String = webClient.DownloadString("http://api.hostip.info/?ip=68.180.206.184") In C#: System.Net.WebClient webClient = new System.Net.WebClient();string result = webClient.DownloadString("http://api.hostip.info/?ip=68.180.206.184");
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/92522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4221/" ] }
92,537
I have an AST derived from the ANTLR Parser Generator for Java. What I want to do is somehow construct a control flow graph of the source code, where each statement or expression is a unique Node. I understand there must be some recursiveness to this identification, I was wondering what you would suggest as the best option and if ANTLR has a toolset I can use for this job.Cheers,Chris EDIT - My main concern is to get a control flow graph(CFG) from the AST. This way I can get a tree representation of the source. To clarify, both the source code and the implementation language is Java.
Usually CFGs are computed on a lower-level representation (e.g. JVM bytecode). Someone did a thesis on such things a few years ago. There might be a helpful way described in there for how to get at that representation. Since your source and target languages are the same, there's no code generation step -- you're already done! However, now you get to walk the AST. At each node of the AST, you have to ask yourself: is this a "jumping" instruction or not? Method calls and if statements are examples of jumping instructions. So are loop constructs (such as for and while ). Instructions such as addition and multiplication are non-jumping. First associate with each java statement a node in the CFG, along with an entry and exit node. As a first approximation, walk the tree and: if the current statement is a method call, figure out where the entry node is for the corresponding body of that method call, and make an edge pointing from the current statement to that entry node. if the statement is a method return, enumerate the places that could have called it and add an edge to those. for each non-jumping statement, make an edge between it and the next statement. This will give you some kind of CFG. The procedure is slightly hairy in step 2 because the method called may be declared in a library, and not elsewhere in the AST -- if so, either don't make an edge or make an edge to a special node representing the entry to that library method. Does this make sense?
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/92537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5915/" ] }
92,546
When refactoring away some #defines I came across declarations similar to the following in a C++ header file: static const unsigned int VAL = 42;const unsigned int ANOTHER_VAL = 37; The question is, what difference, if any, will the static make? Note that multiple inclusion of the headers isn't possible due to the classic #ifndef HEADER #define HEADER #endif trick (if that matters). Does the static mean only one copy of VAL is created, in case the header is included by more than one source file?
The static means that there will be one copy of VAL created for each source file it is included in. But it also means that multiple inclusions will not result in multiple definitions of VAL that will collide at link time. In C, without the static you would need to ensure that only one source file defined VAL while the other source files declared it extern . Usually one would do this by defining it (possibly with an initializer) in a source file and put the extern declaration in a header file. static variables at global level are only visible in their own source file whether they got there via an include or were in the main file. Editor's note: In C++, const objects with neither the static nor extern keywords in their declaration are implicitly static .
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/92546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ] }
92,592
How solid is Mono for C# development on Linux and OS X? I've been thinking about learning C# on the side, and was wondering if learning using Mono would suffice.
I have been using mono for upwards of 2 years now. Work is windows and .Net, home is mono on GNU/Linux. I have been able to run both GUI and ASP.NET apps with no problems from the same SVN repository. The only changes I had to make were in connection strings. ASP.NET works well under mod_mono for apache and xsp2. Some of the .NET 3.5 pieces are not there but definitely works for .NET 2.0 and earlier. Monodevelop is coming along nicely and I believe the debugger is working well too.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/92592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15846/" ] }
92,601
Intermittently in our app, we encounter LockTimeoutExceptions being throw from SQL CE. We've recently upgraded to 3.5 SP 1, and a number of them seem to have gone away, but we still do see them occasionally. I'm certain it's a bug in our code (which is multi-threaded) but I haven't been able to pin it down precisely. Does anyone have any good techniques for debugging this problem? The exceptions log like this (there's never a stack trace for these exceptions): SQL Server Compact timed out waiting for a lock. The default lock time is 2000ms for devices and 5000ms for desktops. The default lock timeout can be increased in the connection string using the ssce: default lock timeout property. [ Session id = 6,Thread id = 7856,Process id = 10116,Table name = Product,Conflict type = s lock (x blocks),Resource = DDL ] Our database is read-heavy, but does seldom writes, and I think I've got everything protected where it needs to be. EDIT: SQL CE already automatically uses NOLOCK http://msdn.microsoft.com/en-us/library/ms172398(sql.90).aspx
I have been using mono for upwards of 2 years now. Work is windows and .Net, home is mono on GNU/Linux. I have been able to run both GUI and ASP.NET apps with no problems from the same SVN repository. The only changes I had to make were in connection strings. ASP.NET works well under mod_mono for apache and xsp2. Some of the .NET 3.5 pieces are not there but definitely works for .NET 2.0 and earlier. Monodevelop is coming along nicely and I believe the debugger is working well too.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/92601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6897/" ] }
92,698
I'm looking for an Access 2007 equivalent to SQL Server's COALESCE function. In SQL Server you could do something like: Person JohnSteveRichard SQL DECLARE @PersonList nvarchar(1024)SELECT @PersonList = COALESCE(@PersonList + ',','') + PersonFROM PersonTablePRINT @PersonList Which produces: John, Steve, Richard I want to do the same but in Access 2007. Does anyone know how to combine rows like this in Access 2007?
Here is a sample User Defined Function (UDF) and possible usage. Function: Function Coalsce(strSQL As String, strDelim, ParamArray NameList() As Variant)Dim db As DatabaseDim rs As DAO.RecordsetDim strList As String Set db = CurrentDb If strSQL <> "" Then Set rs = db.OpenRecordset(strSQL) Do While Not rs.EOF strList = strList & strDelim & rs.Fields(0) rs.MoveNext Loop strList = Mid(strList, Len(strDelim)) Else strList = Join(NameList, strDelim) End If Coalsce = strListEnd Function Usage: SELECT documents.MembersOnly, Coalsce("SELECT FName From Persons WHERE Member=True",":") AS Who, Coalsce("",":","Mary","Joe","Pat?") AS OthersFROM documents; An ADO version, inspired by a comment by onedaywhen Function ConcatADO(strSQL As String, strColDelim, strRowDelim, ParamArray NameList() As Variant) Dim rs As New ADODB.Recordset Dim strList As String On Error GoTo Proc_Err If strSQL <> "" Then rs.Open strSQL, CurrentProject.Connection strList = rs.GetString(, , strColDelim, strRowDelim) strList = Mid(strList, 1, Len(strList) - Len(strRowDelim)) Else strList = Join(NameList, strColDelim) End If ConcatADO = strList Exit Function Proc_Err: ConcatADO = "***" & UCase(Err.Description) End Function From: http://wiki.lessthandot.com/index.php/Concatenate_a_List_into_a_Single_Field_%28Column%29
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/92698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3742/" ] }
92,720
I have a web page that includes a bunch of images. Sometimes the image isn't available, so a broken image is displayed in the client's browser. How do I use jQuery to get the set of images, filter it to broken images then replace the src? --I thought it would be easier to do this with jQuery, but it turned out much easier to just use a pure JavaScript solution, that is, the one provided by Prestaul.
Handle the onError event for the image to reassign its source using JavaScript: function imgError(image) { image.onerror = ""; image.src = "/images/noimage.gif"; return true;} <img src="image.png" onerror="imgError(this);"/> Or without a JavaScript function: <img src="image.png" onError="this.onerror=null;this.src='/images/noimage.gif';" /> The following compatibility table lists the browsers that support the error facility: http://www.quirksmode.org/dom/events/error.html
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/92720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17702/" ] }
92,802
I have a Bash shell script in which I would like to pause execution until the user presses a key. In DOS, this is easily accomplished with the pause command. Is there a Linux equivalent I can use in my script?
read does this: user@host:~$ read -n1 -r -p "Press any key to continue..." key[...]user@host:~$ The -n1 specifies that it only waits for a single character. The -r puts it into raw mode, which is necessary because otherwise, if you press something like backslash, it doesn't register until you hit the next key. The -p specifies the prompt, which must be quoted if it contains spaces. The key argument is only necessary if you want to know which key they pressed, in which case you can access it through $key . If you are using Bash, you can also specify a timeout with -t , which causes read to return a failure when a key isn't pressed. So for example: read -t5 -n1 -r -p 'Press any key in the next five seconds...' keyif [ "$?" -eq "0" ]; then echo 'A key was pressed.'else echo 'No key was pressed.'fi
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/92802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4362/" ] }
92,811
I need to reverse engineer a Microsoft SQL Server 2008 in order to create a Microsoft Visio 2007 Database Model Diagram. So I choose "Reverse Engineer" from the Database menu to connect to the DB. I configured the Microsoft SQL Server Visio driver so that is uses SQL Server Native Client 10.0 as the ODBC driver. Afterwards I created a User DSN which connects to my DB. This DSN works (at least the provided test is successful). After clicking next in the Reverse Engineer Wizard, Visio kindly asks for my credentials which I properly provide, but after clicking OK I receive the following message: The currently selected Visio driver is not compatible with the data source. I tried using the old SQL Server ODBC driver, by also reconfiguring the Visio driver of course. It does not work too.
From Microsoft support via the Microsoft forums: Further investigation reveals that this is expected behavior for Visio 2007. When Visio opens a connection using the Visio SQL Server Driver it checks the server version and since SQL Server 2008 shipped after Visio 2007 it doesn't recognise SQL Server 2008 as a supported version and closes the connection. You can wait for a future version of Visio to ship which does recognise SQL Server 2008 or use the Visio Generic ODBC driver which can successfully open connections to SQL Server 2008. A third option is to use a copy of SQL Server 2005 for initial reverse engineering. The Visio team is aware of this issue.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/92811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17713/" ] }
92,826
Simply setting the SVN_EDITOR variable to "mate" does not get the job done. It opens TextMate when appropriate, but then when I save the message and exit, I'm prompted to continue, abort or try again. It seems like the buffer isn't returned to the svn command for use.
You need to include a command line option in your SVN_EDITOR (or EDITOR) variable export SVN_EDITOR='mate -w' This makes the svn command wait for the editor to close/release the file before continuing, which is where the process is getting mucked up now. See here .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/92826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5586/" ] }
92,841
I am using CodeDom to generate dynamic code based on user values. One of those values controls what the name of the class I'm generating is. I know I could sterilize the name based on language rules about valid class names using regular expressions, but I'd like to know if there is a specific method built into the framework to validate and/or sterilize a class name.
An easy way to determine if a string is a valid identifier for a class or variable is to call the static method System.CodeDom.Compiler.CodeGenerator.IsValidLanguageIndependentIdentifier(string value)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/92841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8720/" ] }
92,847
How do I make an array shorter in Perl? I read some webpages indicating that I can assign: $#ARRAY = 42; I read that the use of $# is deprecated. I need a solution that will work for an array of arrays, too. This didn't work: $#$ARRAY[$i] = 42;
I'm not aware of assigning $#ARRAY being deprecated; perldoc perldata from 5.10.0 certainly says nothing about it. It is the fastest way to truncate an array. If you want something a little more readable, use splice : splice @ARRAY, 43; (Note 43 instead of 42 - $#ARRAY gets you the last index of the array, whereas splice taks the length of the array instead). As for working on arrays of arrays, I assume you mean being able to truncate a nested array via a reference? In that case, you want: $#{$ARRAY->[7]} = 42; or splice @{$ARRAY->[7]}, 43;
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/92847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4454/" ] }
92,859
This question was already asked in the context of C#/.Net . Now I'd like to learn the differences between a struct and a class in C++. Please discuss the technical differences as well as reasons for choosing one or the other in OO design. I'll start with an obvious difference: If you don't specify public: or private: , members of a struct are public by default; members of a class are private by default. I'm sure there are other differences to be found in the obscure corners of the C++ specification.
You forget the tricky 2nd difference between classes and structs. Quoth the standard (§11.2.2 in C++98 through C++11): In absence of an access-specifier for a base class, public is assumed when the derived class is declared struct and private is assumed when the class is declared class . And just for completeness' sake, the more widely known difference between class and struct is defined in (11.2): Member of a class defined with the keyword class are private by default. Members of a class defined with the keywords struct or union are public by default. Additional difference: the keyword class can be used to declare template parameters, while the struct keyword cannot be so used.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/92859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2686/" ] }
92,862
In Ruby, like in many other OO programming languages, operators are overloadable. However, only certain character operators can be overloaded. This list may be incomplete but, here are some of the operators that cannot be overloaded: !, not, &&, and, ||, or
Methods are overloadable, those are part of the language syntax.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/92862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1167846/" ] }
92,869
I am going to be starting up a new project at work and want to get into unit testing. We will be using Visual Studio 2008, C#, and the ASP.NET MVC stuff. I am looking at using either NUnit or the built-in test projects that Visual Studio 2008 has, but I am open to researching other suggestions. Is one system better than the other or perhaps easier to use/understand than the other? I am looking to get this project set up as kind of the "best practice" for our development efforts going forward.
Daok named all the pro's of Visual Studio 2008 test projects. Here are the pro's of NUnit. NUnit has a mocking framework. NUnit can be run outside of theIDE. This can be useful if you wantto run tests on a non-Microsoft build server,like CruiseControl.NET . NUnit has more versions coming outthan visual studio. You don't haveto wait years for a new version.And you don't have to install a new version of the IDE toget new features. There are extensions being developedfor NUnit, like row-tests, etc. Visual Studio tests take a long timeto start up for some reason. This isbetter in Visual Studio 2008,but it is still too slowfor my taste. Quickly running a testto see if you didn't break somethingcan take too long. NUnit withsomething like Testdriven.Net to runtests from the IDE is actually muchfaster. Especially when runningsingle tests.According to Kjetil Klaussen, this is caused by the Visual Studio testrunner. Running MSTest tests in TestDriven.Net makes MSTest performance comparable to NUnit.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/92869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13593/" ] }
92,928
In Python for *nix, does time.sleep() block the thread or the process?
It blocks the thread. If you look in Modules/timemodule.c in the Python source, you'll see that in the call to floatsleep() , the substantive part of the sleep operation is wrapped in a Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS block, allowing other threads to continue to execute while the current one sleeps. You can also test this with a simple python program: import timefrom threading import Threadclass worker(Thread): def run(self): for x in xrange(0,11): print x time.sleep(1)class waiter(Thread): def run(self): for x in xrange(100,103): print x time.sleep(5)def run(): worker().start() waiter().start() Which will print: >>> thread_test.run()0100>>> 12345101678910102
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/92928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17732/" ] }
92,971
I'm trying to detect the size of the screen I'm starting emacs on, and adjust the size and position the window it is starting in (I guess that's the frame in emacs-speak) accordingly. I'm trying to set up my .emacs so that I always get a "reasonably-big" window with it's top-left corner near the top-left of my screen. I guess this is a big ask for the general case, so to narrow things down a bit I'm most interested in GNU Emacs 22 on Windows and (Debian) Linux.
If you want to change the size according to resolution you can do something like this (adjusting the preferred width and resolutions according to your specific needs): (defun set-frame-size-according-to-resolution () (interactive) (if window-system (progn ;; use 120 char wide window for largeish displays ;; and smaller 80 column windows for smaller displays ;; pick whatever numbers make sense for you (if (> (x-display-pixel-width) 1280) (add-to-list 'default-frame-alist (cons 'width 120)) (add-to-list 'default-frame-alist (cons 'width 80))) ;; for the height, subtract a couple hundred pixels ;; from the screen height (for panels, menubars and ;; whatnot), then divide by the height of a char to ;; get the height we want (add-to-list 'default-frame-alist (cons 'height (/ (- (x-display-pixel-height) 200) (frame-char-height)))))))(set-frame-size-according-to-resolution) Note that window-system is deprecated in newer versions of emacs. A suitable replacement is (display-graphic-p) . See this answer to the question How to detect that emacs is in terminal-mode? for a little more background.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/92971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6402/" ] }
93,022
Does anyone know of an IDE for F# development that does not involve me shelling out $300? I will gladly move to F# VS Express if they ever release one, but spending money to just get started with a new language is not in my budget.
http://msdn.microsoft.com/en-us/vsx2008/products/bb933751.aspx Visual Studio Shell - Free, and F# supports it out of the box. (edited) http://blogs.msdn.com/dsyme/archive/2008/04/04/tackling-the-f-productization.aspx Theres a link talking about using the Shell and such too
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/93022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1358/" ] }
93,039
In what segment (.BSS, .DATA, other) of an executable file are static variables stored so that they don't have name collision?For example: foo.c: bar.c:static int foo = 1; static int foo = 10;void fooTest() { void barTest() { static int bar = 2; static int bar = 20; foo++; foo++; bar++; bar++; printf("%d,%d", foo, bar); printf("%d, %d", foo, bar);} } If I compile both files and link it to a main that calls fooTest() and barTest repeatedly, the printf statements increment independently. Makes sense since the foo and bar variables are local to the translation unit. But where is the storage allocated? To be clear, the assumption is that you have a toolchain that would output a file in ELF format. Thus, I believe that there has to be some space reserved in the executable file for those static variables. For discussion purposes, lets assume we use the GCC toolchain.
Where your statics go depends on whether they are zero-initialized . zero-initialized static data goes in .BSS (Block Started by Symbol) , non-zero-initialized data goes in .DATA
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/93039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10703/" ] }
93,058
I can switch between windows with "C-x o", but if I have opened multiple frames, can I move between them without the mouse as well? I just realized that the question probably sounds braindead without this detail: I'm on Mac OS X (Finnish keyboard) and switching between windows of the same application is difficult.
If you want an Emacs-centric method, try C-x 5 o.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/93058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4110/" ] }
93,073
How do you implement an efficient and thread safe reference counting system on X86 CPUs in the C++ programming language? I always run into the problem that the critical operations not atomic , and the available X86 Interlock operations are not sufficient for implementing the ref counting system. The following article covers this topic, but requires special CPU instructions: http://www.ddj.com/architect/184401888
Nowadays, you can use the Boost/TR1 shared_ptr<> smart pointer to keep your reference counted references. Works great; no fuss, no muss. The shared_ptr<> class takes care of all the locking needed on the refcount.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/93073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15288/" ] }
93,091
Why is it that they decided to make String immutable in Java and .NET (and some other languages)? Why didn't they make it mutable?
According to Effective Java , chapter 4, page 73, 2nd edition: "There are many good reasons for this: Immutable classes are easier to design, implement, and use than mutable classes. They are less prone to error and are more secure. [...] " Immutable objects are simple. An immutable object can be in exactly one state, the state in which it was created. If you make sure that all constructors establish class invariants, then it is guaranteed that these invariants will remain true for all time, with no effort on your part. [...] Immutable objects are inherently thread-safe; they require no synchronization. They cannot be corrupted by multiple threads accessing them concurrently. This is far and away the easiest approach to achieving thread safety. In fact, no thread can ever observe any effect of another thread on an immutable object. Therefore, immutable objects can be shared freely [...] Other small points from the same chapter: Not only can you share immutable objects, but you can share their internals. [...] Immutable objects make great building blocks for other objects, whether mutable or immutable. [...] The only real disadvantage of immutable classes is that they require a separate object for each distinct value.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/93091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2936/" ] }
93,128
I'm importing a MySQL dump and getting the following error. $ mysql foo < foo.sql ERROR 1153 (08S01) at line 96: Got a packet bigger than 'max_allowed_packet' bytes Apparently there are attachments in the database, which makes for very large inserts. This is on my local machine, a Mac with MySQL 5 installed from the MySQL package. Where do I change max_allowed_packet to be able to import the dump? Is there anything else I should set? Just running mysql --max_allowed_packet=32M … resulted in the same error.
You probably have to change it for both the client (you are running to do the import) AND the daemon mysqld that is running and accepting the import. For the client, you can specify it on the command line: mysql --max_allowed_packet=100M -u root -p database < dump.sql Also, change the my.cnf or my.ini file (usually found in /etc/mysql/) under the mysqld section and set: max_allowed_packet=100M or you could run these commands in a MySQL console connected to that same server: set global net_buffer_length=1000000; set global max_allowed_packet=1000000000; (Use a very large value for the packet size.)
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/93128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13989/" ] }
93,147
I'm supposed to create a simple rule engine in C#. Any leads on how I can proceed?. It's a minimalistic rule engine, and would use SQL server as the back end. Do we have any general blueprint or design patterns that generally apply to rule engines? What kind of .Net technologies can I use to design one? Any directions would be helpful.Thanks.
If you're using .NET 3.0 or later, you can use the Rules Engine of Windows Workflow Foundation without having to acutally use Workflow. I've done this on a project, and you can use SQL or XML as the backend, and it works great. You can use the IDE that comes with the Workflow examples and put it in your own apps. It's excellent.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/93147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
93,153
In a .net 2 winforms application, what's a good way to set the culture for the entire application? Setting CurrentThread.CurrentCulture for every new thread is repetitive and error-prone. Ideally I'd like to set it when the app starts and forget about it.
The culture for a thread in .NET is the culture for the system (as viewed by a single application/process). There is no way to override that in .NET, you'll have to continue setting the CurrentCulture for each new thread.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/93153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/626/" ] }
93,162
Apparently you can easily obtain a client IP address in WCF 3.5 but not in WCF 3.0. Anyone know how?
This doesn't help you in 3.0, but I can just see people finding this question and being frustrated because they are trying to get the client IP address in 3.5. So, here's some code which should work: using System.ServiceModel;using System.ServiceModel.Channels;OperationContext context = OperationContext.Current;MessageProperties prop = context.IncomingMessageProperties;RemoteEndpointMessageProperty endpoint = prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;string ip = endpoint.Address;
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/93162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3856/" ] }
93,171
I have a bowling web application that allows pretty detailed frame-by-frame information entry. One thing it allows is tracking which pins were knocked down on each ball. To display this information, I make it look like a rack of pins: o o o o o o o o o o Images are used to represent the pins. So, for the back row, I have four img tags, then a br tag. It works great... mostly. The problem is in small browsers, such as IEMobile. In this case, where there are may 10 or 11 columns in a table, and there may be a rack of pins in each column, Internet Explorer will try to shrink the column size to fit on the screen, and I end up with something like this: o o o oo o o o o o or o oo oo o oo o o The structure is: <tr> <td> <!-- some whitespace --> <div class="..."><img .../><img .../><img .../><img .../><br/>...</div> <!-- some whitespace --> </td></tr> There is no whitespace inside the inner div. If you look at this page in a regular browser, it should display fine. If you look at it in IEMobile, it does not. Any hints or suggestions? Maybe some sort of &nbsp; that doesn't actually add a space? Follow-up/Summary I have received and tried several good suggestions, including: Dynamically generate the whole image on the server. It is a good solution, but doesn't really fit my need (hosted on GAE ), and a bit more code than I'd like to write. These images could also be cached after the first generation. Use CSS white-space declaration. It is a good standards-based solution, but it fails miserably in the IEMobile view. What I ended up doing *hangs head and mumbles something* Yes, that's right, a transparent GIF at the top of the div, sized to the width I need. End code (simplified) looks like: <table class="game"> <tr class="analysis leave"> <!-- ... --> <td> <div class="smallpins"><img class="spacer" src="http://seasrc.th.net/gif/cleardot.gif" /><br/><img src="/img/pinsmall.gif"/><img src="/img/nopinsmall.gif"/><img src="/img/nopinsmall.gif"/><img src="/img/nopinsmall.gif"/><br/><img src="/img/pinsmall.gif"/><img src="/img/pinsmall.gif"/><img src="/img/nopinsmall.gif"/><br/><img src="/img/nopinsmall.gif"/><img src="/img/nopinsmall.gif"/><br/><img src="/img/nopinsmall.gif"/></div> </td> <!-- ... --> </tr></table> And CSS: div.smallpins { background: url(/img/lane.gif) repeat; text-align: center; padding: 0; white-space: nowrap;}div.smallpins img { width: 1em; height: 1em;}div.smallpins img.spacer { width: 4.5em; height: 0px;}table.game tr.leave td{ padding: 0; margin: 0;}table.game tr.leave .smallpins { min-width: 4em; white-space: nowrap; background: none;} P.S.: No, I will not be hotlinking someone else's clear dot in my final solution :)
You could try the css "nowrap" option in the containing div. {white-space: nowrap;} Not sure how widely that is supported.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/93171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96/" ] }
93,260
It looks quite easy to find such a tool for Java ( Checkstyle , JCSC ), but I can't seem to find one for C/C++. I am not looking for a lint-like static code analyzer, I only would like to check against coding standards like variable naming, capitalization, spacing, identation, bracket placement, and so on.
The only tool I know is Vera . Haven't used it, though, so can't comment how viable it is. Demo looks promising.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/93260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12291/" ] }
93,264
I have created a foreign key (in SQL Server) by: alter table company add CountryID varchar(3);alter table company add constraint Company_CountryID_FK foreign key(CountryID) references Country; I then run this query: alter table company drop column CountryID; and I get this error: Msg 5074, Level 16, State 4, Line 2 The object 'Company_CountryID_FK' is dependent on column 'CountryID'. Msg 4922, Level 16, State 9, Line 2 ALTER TABLE DROP COLUMN CountryID failed because one or more objects access this column I have tried this, yet it does not seem to work: alter table company drop foreign key Company_CountryID_FK; alter table company drop column CountryID; What do I need to do to drop the CountryID column? Thanks.
Try alter table company drop constraint Company_CountryID_FKalter table company drop column CountryID
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/93264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ] }
93,277
I have a rails form with a datetime_select field. When I try to submit the form, I get the following exception: ActiveRecord::MultiparameterAssignmentErrors in WidgetsController#update 1 error(s) on assignment of multiparameter attributes If it's a validation error, why don't I see an error on the page? This is in Rails 2.0.2
It turns out that rails uses something called Multi-parameter assignment to transmit dates and times in small parts that are reassembled when you assign params to the model instance. My problem was that I was using a datetime_select form field for a date model field. It apparently chokes when the multi-parameter magic tries to set the time on a Date object. The solution was to use a date_select form field rather than a datetime_select .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/93277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11078/" ] }
93,297
I want to make a small app that displays a PDF, presenting zoom-able single pages with a previous-next page function.
The Core Graphics API is pretty much the same in Cocoa and Cocoa touch. Read up on CGPDFDocument , it should provide you with everything you will need to render PDF pages. You won't need to read the PDF spec or use a library to parse PDF files directly. You will probably to learn more about Core Graphics / Quartz 2D / etc. to understand how to use those functions inside of a Cocoa app.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/93297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15420/" ] }