Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I need to match a image url like this: ``` http://site.com/site.com/files/images/img (5).jpg ``` Something like this works fine: ``` .replace(/(http:\/\/([ \S]+\.(jpg|png|gif)))/ig, "<div style=\"background: url($1)\"></div>") ``` Except if I have something like this: ``` http://site.com/site.com/files/audio/audiofile.mp3 http://site.com/site.com/files/images/img (5).jpg ``` How do I match only the image? Thanks! Edit: And I'm using javascript.
Proper URLs should not have spaces in them, they should have `%20` or a plus `'+'` instead. If you had them written with those alternatives then your matching would be much easier.
Assuming images will always be in the 'images' directory, try: ``` http://.*/images/(.*?).(jpe?g|gif|png) ``` If you can't assume an images directory: ``` http://.*/(.*?).(jpe?g|gif|png) ``` Group 1 and 2 should have what you want (file name and extension). I tested the regular expression [here](http://www.regexplanet.com/simple/index.jsp) and [here](http://www.regular-expressions.info/javascriptexample.html) and it appears to do what you want.
regex matching image url with spaces
[ "", "javascript", "regex", "url", "" ]
I'm trying to bind KeyValuePair Elements from a Dictionary to a ItemsControl. My Dictionary has 15 Elements and the following code shows me 15 TextBoxes: ``` <WrapPanel Name="PersonsWrapPanel" Grid.Row="0"> <ItemsControl ItemsSource="{Binding Persons}" > <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <WrapPanel Orientation="Horizontal" Width="auto"> </WrapPanel> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate> <TextBox Text="{Binding Value.Text}"></TextBox> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </WrapPanel> ``` Unfortunately without any TextBox content (which would be Key or Value). Any ideas?
I solved it by using this line: ``` <TextBox Text="{Binding Value, Mode=OneWay}"></TextBox> ``` The code on <http://www.dev102.com/2008/03/07/binding-a-wpf-control-to-a-dictionary/> doesn't seem to work.
Perhaps try binding directly to the values of the dictionary: ``` ItemsSource="{Binding Persons.Values}" ``` If I am understanding your XAML properly, each object in the dictionary has a field called "Text" to which you are trying to bind. If so and you make the above changes, you will need to change your DataTemplate as well: ``` <TextBox Text="{Binding Text}" /> ``` See [this article](http://www.dev102.com/2008/03/07/binding-a-wpf-control-to-a-dictionary/) for more info. HTH.
Bind Dictionary to ItemsControl in C#/WPF
[ "", "c#", "wpf", "dictionary", "itemscontrol", "" ]
I'm seeing some strange behavior in IE trying to call functions in another page via function.apply(). Here's a simple test case: test1.html: ``` <HTML> <HEAD> <script language="javascript" type="text/javascript"> var opened = null; function applyNone() { opened.testFunc.apply(opened); } function applyArgs() { opened.testFunc.apply(opened, ["applied array"]); } function call() { opened.testFunc("called directly"); } function remoteApply() { opened.testApply(["used remote apply"]); } function remoteApplyCopy() { opened.testApplyCopy(["used remote apply copy"]); } function openPopup() { opened = window.open("test2.html", "_blank"); } </script> </HEAD> <BODY> <a href="#" onclick="openPopup()">OPEN</a> <hr> <a href="#" onclick="applyNone()">applyNone</a> <a href="#" onclick="applyArgs()">applyArgs</a> <a href="#" onclick="call()">call</a> <a href="#" onclick="remoteApply()">remoteApply</a> <a href="#" onclick="remoteApplyCopy()">remoteApplyCopy</a> </BODY> </HTML> ``` test2.html: ``` <HTML> <HEAD> <script language="javascript" type="text/javascript"> function testApply(args) { testFunc.apply(this, args); } function testApplyCopy(args) { var a = []; for(var i = 0; i < args.length; i++) { a.push(args[i]); } testFunc.apply(this, a); } function testFunc() { var s = "Got: "; for(var i = 0; i < arguments.length; i++) { s += arguments[i] + " "; } document.getElementById("output").innerHTML += s + "<BR>"; } </script> </HEAD> <BODY> Hi there <div id="output"/> </BODY> </HTML> ``` In firefox and chrome all methods work properly. In IE (tested in 6, 7, and 8) all but the applyArgs() and remoteApply() methods work as expected. applyArgs() gives a "JScript object expected" error when it tries calling apply (test1.html line 11). remoteApply() gives the same "JScript object expected" error when it tries calling apply (test2.html line 5). Problem is, I need to be able to use apply(). I can get around the issue by doing something like the remoteApplyCopy() mechanism, but I'm trying to avoid that. Why doesn't apply() just work?
You need to have the arrays created in the other window, because each window has its own Array constructor. I think this will work. Add this function to test2.html: ``` function getEmptyArray() { return new Array(); } ``` And this function to test1.html: ``` Array.prototype.cloneToRemote = function (win) { var newArray = win.getEmptyArray(); for (var i = 0; i < this.length; i++) { newArray.push(this[i]); } return newArray; } ``` Then do this: ``` function applyArgs() { opened.testFunc.apply(opened, ["applied array"].cloneToRemote(opened)); } ``` Note, it seems like you should be able to do ``` var newArray = new win.Array(); ``` within the test1.html cloneToRemote() function, but I couldn't make that work. If you could do that, you could get rid of the new getEmptyArray() function in test2.html.
If you change test2.html testApply() function as follows: ``` function testApply() { testFunc.apply(this, arguments); } ``` remoteApply() works. But, applyArgs() still failed.
Why doesn't function.apply() work across document boundaries in IE?
[ "", "javascript", "internet-explorer", "apply", "" ]
Is there any C# function which could be used to escape and un-escape a string, which could be used to fill in the content of an XML element? I am using VSTS 2008 + C# + .Net 3.0. EDIT 1: I am concatenating simple and short XML file and I do not use serialization, so I need to explicitly escape XML character by hand, for example, I need to put `a<b` into `<foo></foo>`, so I need escape string `a<b` and put it into element foo.
``` public static string XmlEscape(string unescaped) { XmlDocument doc = new XmlDocument(); XmlNode node = doc.CreateElement("root"); node.InnerText = unescaped; return node.InnerXml; } public static string XmlUnescape(string escaped) { XmlDocument doc = new XmlDocument(); XmlNode node = doc.CreateElement("root"); node.InnerXml = escaped; return node.InnerText; } ```
[SecurityElement.Escape(string s)](http://msdn.microsoft.com/en-us/library/system.security.securityelement.escape(VS.80).aspx)
String escape into XML
[ "", "c#", ".net", "xml", "visual-studio-2008", "escaping", "" ]
How to easy encode and "compress" URL/e-mail adress to string in PHP? String should be: 1. difficult to decode by user 2. as short as possible (compressed) 3. similar URLs should be different after encoding 4. not in database 5. easy to decode/uncompress by PHP script --- ex. input -> output, stackoverflow.com/1/ -> "n3uu399", stackoverflow.com/2/ -> "ojfiejfe8"
Not very short but you could [zip](http://php.net/manual/en/book.zip.php) it with a password and encode it using [base64](http://php.net/manual/en/function.base64-encode.php). Note that [zip is not too safe when it comes to passwords](http://en.wikipedia.org/wiki/ZIP_(file_format)#Encryption), but should be ok if your encrypted value is intended to have a short lifetime. Note that whatever you do, you won't be able to generate a somewhat safe encoding unless you agree to store some unaccessible information locally. This means, whatever you do, take it as given that *anyone* can access the pseudo-encrypted data with enough time, be it by reverse engineering your algorithm, brute-forcing your passwords or whatever else is necessary.
You could make your own text compression system based on common strings: if URL starts '<http://www>.', then the first character of the shortened URL is 'a', if it starts '<https://www>.', then the first character is 'b'...(repeat for popular variants), if not then first letter is 'z' and the url follows in a coded pattern. The if next three letters are 'abc', the second letter is 'a' etc. You'll need a list of which letter pairs/triplets are most common in URLs and work out the most popular 26/50 etc (depending on which characters you want to use) and you should be able to conduct some compression on the URL entirely in PHP (without using a database). People will only be able to reverse it by either knowing your letter pair/triplet list (your mapping list) or by manually reverse-engineering it.
Encoding&compression of URL in PHP
[ "", "php", "url", "string", "compression", "" ]
Could anyone recommend me a good open source .Net based wiki project? Better with successful deployment and user experience, and have a good community to support. :-) Thanks! regards, George
Screwturn wiki- <http://www.screwturn.eu/> is what I currently use successfully.
[DekiWiki](http://www.mindtouch.com/) Runs even on Mono. The [MonoDevelop site](http://monodevelop.com/) runs on it.
open source .Net wiki?
[ "", "c#", ".net", "open-source", "wiki", "" ]
As part of some WSGI middleware I want to write a python class that wraps an iterator to implement a close method on the iterator. This works fine when I try it with an old-style class, but throws a TypeError when I try it with a new-style class. What do I need to do to get this working with a new-style class? Example: ``` class IteratorWrapper1: def __init__(self, otheriter): self._iterator = otheriter self.next = otheriter.next def __iter__(self): return self def close(self): if getattr(self._iterator, 'close', None) is not None: self._iterator.close() # other arbitrary resource cleanup code here class IteratorWrapper2(object): def __init__(self, otheriter): self._iterator = otheriter self.next = otheriter.next def __iter__(self): return self def close(self): if getattr(self._iterator, 'close', None) is not None: self._iterator.close() # other arbitrary resource cleanup code here if __name__ == "__main__": for i in IteratorWrapper1(iter([1, 2, 3])): print i for j in IteratorWrapper2(iter([1, 2, 3])): print j ``` Gives the following output: ``` 1 2 3 Traceback (most recent call last): ... TypeError: iter() returned non-iterator of type 'IteratorWrapper2' ```
What you're trying to do makes sense, but there's something evil going on inside Python here. ``` class foo(object): c = 0 def __init__(self): self.next = self.next2 def __iter__(self): return self def next(self): if self.c == 5: raise StopIteration self.c += 1 return 1 def next2(self): if self.c == 5: raise StopIteration self.c += 1 return 2 it = iter(foo()) # Outputs: <bound method foo.next2 of <__main__.foo object at 0xb7d5030c>> print it.next # 2 print it.next() # 1?! for x in it: print x ``` foo() is an iterator which modifies its next method on the fly--perfectly legal anywhere else in Python. The iterator we create, it, has the method we expect: it.next is next2. When we use the iterator directly, by calling next(), we get 2. Yet, when we use it in a for loop, we get the original next, which we've clearly overwritten. I'm not familiar with Python internals, but it seems like an object's "next" method is being cached in `tp_iternext` (<http://docs.python.org/c-api/typeobj.html#tp_iternext>), and then it's not updated when the class is changed. This is definitely a Python bug. Maybe this is described in the generator PEPs, but it's not in the core Python documentation, and it's completely inconsistent with normal Python behavior. You could work around this by keeping the original next function, and wrapping it explicitly: ``` class IteratorWrapper2(object): def __init__(self, otheriter): self.wrapped_iter_next = otheriter.next def __iter__(self): return self def next(self): return self.wrapped_iter_next() for j in IteratorWrapper2(iter([1, 2, 3])): print j ``` ... but that's obviously less efficient, and you should *not* have to do that.
There are a bunch of places where CPython take surprising shortcuts based on *class* properties instead of *instance* properties. This is one of those places. Here is a simple example that demonstrates the issue: ``` def DynamicNext(object): def __init__(self): self.next = lambda: 42 ``` And here's what happens: ``` >>> instance = DynamicNext() >>> next(instance) … TypeError: DynamicNext object is not an iterator >>> ``` Now, digging into the CPython source code (from 2.7.2), here's the implementation of the `next()` builtin: ``` static PyObject * builtin_next(PyObject *self, PyObject *args) { … if (!PyIter_Check(it)) { PyErr_Format(PyExc_TypeError, "%.200s object is not an iterator", it->ob_type->tp_name); return NULL; } … } ``` And here's the implementation of PyIter\_Check: ``` #define PyIter_Check(obj) \ (PyType_HasFeature((obj)->ob_type, Py_TPFLAGS_HAVE_ITER) && \ (obj)->ob_type->tp_iternext != NULL && \ (obj)->ob_type->tp_iternext != &_PyObject_NextNotImplemented) ``` The first line, `PyType_HasFeature(…)`, is, after expanding all the constants and macros and stuff, equivalent to `DynamicNext.__class__.__flags__ & 1L<<17 != 0`: ``` >>> instance.__class__.__flags__ & 1L<<17 != 0 True ``` So that check obviously isn't failing… Which must mean that the next check — `(obj)->ob_type->tp_iternext != NULL` — *is* failing. In Python, this line is roughly (roughly!) equivalent to `hasattr(type(instance), "next")`: ``` >>> type(instance) __main__.DynamicNext >>> hasattr(type(instance), "next") False ``` Which obviously fails because the `DynamicNext` type doesn't have a `next` method — only instances of that type do. Now, my CPython foo is weak, so I'm going to have to start making some educated guesses here… But I believe they are accurate. When a CPython type is created (that is, when the interpreter first evaluates the `class` block and the class' metaclass' `__new__` method is called), the values on the type's `PyTypeObject` struct are initialized… So if, when the `DynamicNext` type is created, no `next` method exists, the `tp_iternext`, field will be set to `NULL`, causing `PyIter_Check` to return false. Now, as the Glenn points out, this is almost certainly a bug in CPython… Especially given that correcting it would only impact performance when either the object being tested isn't iterable or dynamically assigns a `next` method (*very* approximately): ``` #define PyIter_Check(obj) \ (((PyType_HasFeature((obj)->ob_type, Py_TPFLAGS_HAVE_ITER) && \ (obj)->ob_type->tp_iternext != NULL && \ (obj)->ob_type->tp_iternext != &_PyObject_NextNotImplemented)) || \ (PyObject_HasAttrString((obj), "next") && \ PyCallable_Check(PyObject_GetAttrString((obj), "next")))) ``` **Edit**: after a little bit of digging, the fix would not be this simple, because at least some portions of the code assume that, if `PyIter_Check(it)` returns `true`, then `*it->ob_type->tp_iternext` will exist… Which isn't necessarily the case (ie, because the `next` function exists on the instance, not the type). SO! That's why surprising things happen when you try to iterate over a new-style instance with a dynamically assigned `next` method.
Python iterators – how to dynamically assign self.next within a new style class?
[ "", "python", "iterator", "" ]
How to check table is there or not? Using VB 6.0 ``` cmd.CommandText = "drop table t1" cmd.Execute ``` Above code is working fine, but if table is not exist then it showing “table does not exit” How to check table exist or table not exist? Need VB CODE help?
For a Jet MDB (and perhaps generically for many OLEDB Providers) you can use an approach like: ``` Private Sub Main() Dim cnDB As ADODB.Connection Set cnDB = New ADODB.Connection cnDB.Open "Provider=Microsoft.Jet.OLEDB.4.0;" _ & "Jet OLEDB:Engine Type=5;Data Source='sample.mdb'" 'Check presence of table -------------- Dim rsSchema As ADODB.Recordset Set rsSchema = _ cnDB.OpenSchema(adSchemaColumns, _ Array(Empty, Empty, "t1", Empty)) If rsSchema.BOF And rsSchema.EOF Then MsgBox "Table does not exist" Else MsgBox "Table exists" End If rsSchema.Close Set rsSchema = Nothing '-------------------------------------- cnDB.Close End Sub ```
If you just want to drop the table without throwing an error message, you can use the following SQL if you're using MySQL. ``` DROP TABLE t1 IF EXISTS ``` Other databases have a similar feature, but the syntax is different. To do the same in MSSQL: ``` IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 't1') DROP TABLE t1; ``` Although that looks very ugly.. there must be a better syntax to get the same result.
How to check table exist or not exist
[ "", "sql", "database", "vb6", "" ]
i have one database, and it contains some columns. My requirement is that how to display each of the data that i stored in the databse on a text box? my code is shown below (after the connection string) ``` conn.Open(); mycommnd.ExecuteScalar(); SqlDataAdapter da = new SqlDataAdapter(mycommnd); DataTable dt = new DataTable(); da.Fill(dt); ``` What changes that i make after da.Fill(dt) for displaying data on the text box.
Something like: ``` textBox1.Text = dt.Rows[0].ItemArray[0].ToString(); ``` Depends on the name of your textbox and which value you want to put into that text box.
You need to loop inside each columns in the DataTable to get the values and then concatenate them into a string and assign it to a textbox.Text property ``` DataTable dt = new DataTable(); TextBox ResultTextBox; StringBuilder result = new StringBuilder(); foreach(DataRow dr in dt.Rows) { foreach(DataColumn dc in dt.Columns) { result.Append(dr[dc].ToString()); } } ResultTextBox.Text = result.ToString(); ```
Display data on a text box
[ "", "c#", "sql-server", "" ]
Is there a way using SQL to list all foreign keys for a given table? I know the table name / schema and I can plug that in.
You can do this via the information\_schema tables. For example: ``` SELECT tc.table_schema, tc.constraint_name, tc.table_name, kcu.column_name, ccu.table_schema AS foreign_table_schema, ccu.table_name AS foreign_table_name, ccu.column_name AS foreign_column_name FROM information_schema.table_constraints AS tc JOIN information_schema.key_column_usage AS kcu ON tc.constraint_name = kcu.constraint_name AND tc.table_schema = kcu.table_schema JOIN information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema='myschema' AND tc.table_name='mytable'; ``` If you need to go the other way, i.e., find all places a table is used as a foreign table, you can replace the last two conditions with: ``` AND ccu.table_schema='myschema' AND ccu.table_name='mytable'; ```
psql does this, and if you start psql with: ``` psql -E ``` it will show you exactly what query is executed. In the case of finding foreign keys, it's: ``` SELECT conname, pg_catalog.pg_get_constraintdef(r.oid, true) as condef FROM pg_catalog.pg_constraint r WHERE r.conrelid = '16485' AND r.contype = 'f' ORDER BY 1 ``` In this case, 16485 is the oid of the table I'm looking at - you can get that one by just casting your tablename to regclass like: ``` WHERE r.conrelid = 'mytable'::regclass ``` Schema-qualify the table name if it's not unique (or the first in your `search_path`): ``` WHERE r.conrelid = 'myschema.mytable'::regclass ```
How to list table foreign keys
[ "", "sql", "postgresql", "foreign-keys", "database-schema", "" ]
I'm trying to send an iCal to an outlook, using Java Mail Library, I've read already the [Question](https://stackoverflow.com/questions/461889/sending-outlook-meeting-requests-without-outlook), and I already have some sample code ``` public class SendMeetingRequest { String host = "" ; String port = "" ; String sender = "" ; public static SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyyMMdd'T'HHmm'00'" ) ; public static SimpleDateFormat dateParser = new SimpleDateFormat( "dd-MM-yyyy HH:mm" ) ; public static void main(String[] args) throws Exception { SendMeetingRequest sender = new SendMeetingRequest() ; sender.sendInvitation( “LogicaCMG Inschrijf Site” , new String[] { “robert<dot>willems<dot>of<dot>brilman<at>logicacmg<dot>com” } , “Outlook Meeting Request Using JavaMail” , dateParser.parse( “28-08-2006 18:00″ ) , dateParser.parse( “28-08-2006 21:00″ ) , “LIS-42″ , “Bar op scheveningen” , “<font color=\”Red\”>Aanwezigheid verplicht!</font><br>We gaan lekker een biertje drinken met z’n allen.” ) ; } void sendInvitation( String organizer , String[] to , String subject , Date start , Date end , String invitationId , String location , String description ) throws Exception { try { Properties prop = new Properties(); prop.put(”mail.smtp.port”, port ); prop.put(”mail.smtp.host”, host ); Session session = Session.getDefaultInstance(prop); session.setDebug(true); // Define message MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(sender)); // Set TO if( to != null && ( to.length > 0 ) ) { InternetAddress[] address = new InternetAddress[ to.length ] ; for( int i = 0; i < to.length; i++ ) { address[ i ] = new InternetAddress( to[ i ] ) ; } message.setRecipients( Message.RecipientType.TO, address ) ; } // Set subject message.setSubject(subject); // Create iCalendar message StringBuffer messageText = new StringBuffer(); messageText.append("BEGIN:VCALENDAR\n" + "PRODID:-//Microsoft Corporation//Outlook 9.0 MIMEDIR//EN\n" + "VERSION:2.0\n" + "METHOD:REQUEST\n" + "BEGIN:VEVENT\n" + "ORGANIZER:MAILTO:" ) ; messageText.append( organizer ) ; messageText.append( "\n" + "DTSTART:"); messageText.append( dateFormat.format( start ) ) ; messageText.append( "\n" + "DTEND:" ) ; messageText.append( dateFormat.format( end ) ) ; messageText.append( "\n" + "LOCATION:" ) ; messageText.append( location ) ; messageText.append( "\n" + "UID:" ) ; messageText.append( invitationId ) ; messageText.append( "\n" + "DTSTAMP:" ) ; messageText.append( dateFormat.format( new java.util.Date() ) ) ; messageText.append( "\n" + "DESCRIPTION;ALTREP=\"CID:<eventDescriptionHTML>\”" ) ; messageText.append( “\n” + ”BEGIN:VALARM\n” + ”TRIGGER:-PT15M\n” + ”ACTION:DISPLAY\n” + ”DESCRIPTION:Reminder\n” + ”END:VALARM\n” + ”END:VEVENT\n” + ”END:VCALENDAR” ) ; Multipart mp = new MimeMultipart(); MimeBodyPart meetingPart = new MimeBodyPart() ; meetingPart.setDataHandler( new DataHandler( new StringDataSource( messageText.toString(), “text/calendar”, “meetingRequest” ) ) ) ; mp.addBodyPart( meetingPart ) ; MimeBodyPart descriptionPart = new MimeBodyPart() ; descriptionPart.setDataHandler( new DataHandler( new StringDataSource( description, “text/html”, “eventDescription” ) ) ) ; descriptionPart.setContentID( “<eventDescriptionHTML>” ) ; mp.addBodyPart( descriptionPart ) ; message.setContent( mp ) ; // send message Transport.send(message); } catch (MessagingException me) { me.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } } private static class StringDataSource implements DataSource { private String contents ; private String mimetype ; private String name ; public StringDataSource( String contents , String mimetype , String name ) { this.contents = contents ; this.mimetype = mimetype ; this.name = name ; } public String getContentType() { return( mimetype ) ; } public String getName() { return( name ) ; } public InputStream getInputStream() { return( new StringBufferInputStream( contents ) ) ; } public OutputStream getOutputStream() { throw new IllegalAccessError( “This datasource cannot be written to” ) ; } } } ``` But its being sent as an attachment to the outlook 2007 and outlook 2003, and even If I click the attachment to view and accept, I don't receive the Answer, which is the purpose of the application to have a similar functionality like outlook. Is there any procedure I need to know of, or is it the Invitation ID that makes the thing rough?
So I solved the problem, and here is what I found: 1 - You have to update to Java Mail API 1.4.2 to make everything works fine 2 - Write the text/calendar part of your message like the following: ``` package com.xx.xx; import java.util.Properties; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.util.ByteArrayDataSource; public class Email { public Email() { } /* * @param args */ public static void main(String[] args) { try { Email email = new Email(); email.send(); } catch (Exception e) { e.printStackTrace(); } } public void send() throws Exception { try { String from = "xx@xx.com"; String to = "xx@xx.com"; Properties prop = new Properties(); prop.put("mail.smtp.host", "mailhost"); Session session = Session.getDefaultInstance(prop, null); // Define message MimeMessage message = new MimeMessage(session); message.addHeaderLine("method=REQUEST"); message.addHeaderLine("charset=UTF-8"); message.addHeaderLine("component=VEVENT"); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("Outlook Meeting Request Using JavaMail"); StringBuffer sb = new StringBuffer(); StringBuffer buffer = sb.append("BEGIN:VCALENDAR\n" + "PRODID:-//Microsoft Corporation//Outlook 9.0 MIMEDIR//EN\n" + "VERSION:2.0\n" + "METHOD:REQUEST\n" + "BEGIN:VEVENT\n" + "ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE:MAILTO:xx@xx.com\n" + "ORGANIZER:MAILTO:xx@xx.com\n" + "DTSTART:20051208T053000Z\n" + "DTEND:20051208T060000Z\n" + "LOCATION:Conference room\n" + "TRANSP:OPAQUE\n" + "SEQUENCE:0\n" + "UID:040000008200E00074C5B7101A82E00800000000002FF466CE3AC5010000000000000000100\n" + " 000004377FE5C37984842BF9440448399EB02\n" + "DTSTAMP:20051206T120102Z\n" + "CATEGORIES:Meeting\n" + "DESCRIPTION:This the description of the meeting.\n\n" + "SUMMARY:Test meeting request\n" + "PRIORITY:5\n" + "CLASS:PUBLIC\n" + "BEGIN:VALARM\n" + "TRIGGER:PT1440M\n" + "ACTION:DISPLAY\n" + "DESCRIPTION:Reminder\n" + "END:VALARM\n" + "END:VEVENT\n" + "END:VCALENDAR"); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); // Fill the message messageBodyPart.setHeader("Content-Class", "urn:content- classes:calendarmessage"); messageBodyPart.setHeader("Content-ID", "calendar_message"); messageBodyPart.setDataHandler(new DataHandler( new ByteArrayDataSource(buffer.toString(), "text/calendar")));// very important // Create a Multipart Multipart multipart = new MimeMultipart(); // Add part one multipart.addBodyPart(messageBodyPart); // Put parts in message message.setContent(multipart); // send message Transport.send(message); } catch (MessagingException me) { me.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } } } ``` 3 - Replace your variable, and you are good to go!
You can use [ical4j library](https://github.com/ical4j/ical4j) in addition of javamail to build the message body (instead of using a `StringBuffer`). Example: ``` Calendar calendar = new Calendar(); PropertyList calendarProperties = calendar.getProperties(); calendarProperties.add(Version.VERSION_2_0); calendarProperties.add(Method.REQUEST); // other properties ... VEvent vEvent = new VEvent(/*startDate, endDate*/); PropertyList vEventProperties = vEvent.getProperties(); vEventProperties.add(Priority.MEDIUM); vEventProperties.add(Clazz.PUBLIC); // other properties ... calendar.getComponents().add(vEvent); messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(calendar.toString(), "text/calendar"))); ```
How to send an iCal meeting request using Java Mail, and receive the response
[ "", "java", "email", "outlook", "" ]
I have two text boxes. one for login id and another is for password. and there is one button (submit). I need an event that takes the values of login id and password. I.e, without clicking the mouse I need to invoke this event(just by hitting 'enter' on keyboard). can anybody help me! thanx in advance. srini.
Simon P Stevens gave you the most adequate answer. I would just add that you also have the possibility to set a form's **CancelButton** on which a click event would be triggered when you press the escape **ESC** key. Quick summary **Enter** --> **AcceptButton** **Esc** --> **CancelButton**
Set the button to be the accept button on the form. You can do this by setting the forms "AcceptButton" property to be the button you want to trigger. This will make an enter key press trigger the button.
How can I trigger the default button on a form without clicking it (winforms)?
[ "", "c#", "winforms", "" ]
Are there any concurrency problems with one thread reading from one index of an array, while another thread writes to another index of the array, as long as the indices are different? e.g. (this example not necessarily recommended for real use, only to illustrate my point) ``` class Test1 { static final private int N = 4096; final private int[] x = new int[N]; final private AtomicInteger nwritten = new AtomicInteger(0); // invariant: // all values x[i] where 0 <= i < nwritten.get() are immutable // read() is not synchronized since we want it to be fast int read(int index) { if (index >= nwritten.get()) throw new IllegalArgumentException(); return x[index]; } // write() is synchronized to handle multiple writers // (using compare-and-set techniques to avoid blocking algorithms // is nontrivial) synchronized void write(int x_i) { int index = nwriting.get(); if (index >= N) throw SomeExceptionThatIndicatesArrayIsFull(); x[index] = x_i; // from this point forward, x[index] is fixed in stone nwriting.set(index+1); } } ``` **edit:** critiquing this example is not my question, I literally just want to know if array access to one index, concurrently to access of another index, poses concurrency problems, couldn't think of a simple example.
While you will not get an invalid state by changing arrays as you mention, you will have the same problem that happens when two threads are viewing a non volatile integer without synchronization (see the section in the Java Tutorial on [Memory Consistency Errors](http://java.sun.com/docs/books/tutorial/essential/concurrency/memconsist.html)). Basically, the problem is that Thread 1 may write a value in space i, but there is no guarantee when (or if) Thread 2 will see the change. The class [`java.util.concurrent.atomic.AtomicIntegerArray`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicIntegerArray.html) does what you want to do.
The example has a lot of stuff that differs from the prose question. The answer to that question is that distinct elements of an array are accessed independently, so you don't need synchronization if two threads change different elements. However, the Java memory model makes no guarantees (that I'm aware of) that a value written by one thread will be visible to another thread, unless you synchronize access. Depending on what you're really trying to accomplish, it's likely that `java.util.concurrent` already has a class that will do it for you. And if it doesn't, I still recommend taking a look at the source code for `ConcurrentHashMap`, since your code appears to be doing the same thing that it does to manage the hash table.
Are arrays thread-safe in Java?
[ "", "java", "arrays", "concurrency", "thread-safety", "" ]
Is it possible to ask for elevated permissions from within a Java Application? Suggestions I've seen seem to all be centered around running an external executable or setting up a manifest to request privileges on launch. These aren't available to, for instance, applets. Is there any way to request elevation from a running application?
UAC is not something that a running process can request (doesn't matter what language you are running in). You have to request elevation at launch time. The way that most windows apps handle this (and make it *look* like they are requesting elevation) is to spawn an extra copy of themselves, requesting elevation, and passing sufficient command line arguments to the new process so that the appropriate dialog can be displayed. This is why UAC elevation in a dialog is always initiated by a button click that opens a new dialog. So, in the Java world, you just have to do exactly what everyone else has to do: launch your app again, requesting elevation. There are several ways to launch elevated, the 'run as' verb probably being the easiest.
Looks like Sun will have to handle that kind of situation in the JRE since there's no other way of doing elevated actions than by running an external process. If JRE supported it, JVM would probably have to run a separate, elevated process for the java code requesting the elevation. For now however, only the manifest or running an external application are the only solutions available as far as I know. The question is, what do you need elevation for?
UAC and Java
[ "", "java", "windows-vista", "uac", "" ]
After migrating my whole setup from Java 1.5 to 1.6 (J2EE, Tomcat) a couple of months ago, I just realized that Maven is still configured to generate class files targeted for 1.5 via Sun's javac parameter "-target 1.5". Can I expect any performance boosts when changing "-target 1.5" to "-target 1.6"?
It shouldn't make much difference. 1.6 files can have stack map/table structures that improve bytecode verification speed (Apache Harmony just uses a smarter algorithm). If you were to go to 1.4 the initial loading of a class constant would be slightly slower, but that's irrelevant given how long a class takes to load (a new form of the `ldc` bytecode replaces `Class.forName`, but the result was stored in a static field.) In general it doesn't matter. The runtime compiler is the important bit and that can pretty much generate the same machine code. In the past there have been made to javac to reduce the optimisation it does so as not to mangle the code for the runtime compiler, but that is independent of the `-target` flag.
Java 1.6 uses a [different class-file-format](https://jdk.dev.java.net/verifier.html), that simplifies the process of the bytecode-verification. So startup-times should improve a little, if you use the new class-file-format.
Performance impact of Java class files generated with "-target 1.5" running on a 1.6 VM?
[ "", "java", "performance", "cross-compiling", "" ]
Here in stackoverflow, if you started to make changes then you attempt to navigate away from the page, a javascript confirm button shows up and asks: "Are you sure you want to navigate away from this page?" blee blah bloo... Has anyone implemented this before, how do I track that changes were committed? I believe I could do this myself, I am trying to learn the good practices from you the experts. I tried the following but still doesn't work: ``` <html> <body> <p>Close the page to trigger the onunload event.</p> <script type="text/javascript"> var changes = false; window.onbeforeunload = function() { if (changes) { var message = "Are you sure you want to navigate away from this page?\n\nYou have started writing or editing a post.\n\nPress OK to continue or Cancel to stay on the current page."; if (confirm(message)) return true; else return false; } } </script> <input type='text' onchange='changes=true;'> </input> </body> </html> ``` Can anyone post an example?
## Update (2017) Modern browsers now consider displaying a custom message to be a security hazard and it has therefore been [removed](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload#browser_compatibility) from all of them. Browsers now only display generic messages. Since we no longer have to worry about setting the message, it is as simple as: ``` // Enable navigation prompt window.onbeforeunload = function() { return true; }; // Remove navigation prompt window.onbeforeunload = null; ``` Read below for legacy browser support. ## Update (2013) The orginal answer is suitable for IE6-8 and FX1-3.5 (which is what we were targeting back in 2009 when it was written), but is rather out of date now and won't work in most current browsers - I've left it below for reference. The `window.onbeforeunload` is not treated consistently by all browsers. It should be a function reference and not a string (as the original answer stated) but that will work in older browsers because the check for most of them appears to be whether anything is assigned to `onbeforeunload` (including a function that returns `null`). You set `window.onbeforeunload` to a function reference, but in older browsers you have to set the `returnValue` of the event instead of just returning a string: ``` var confirmOnPageExit = function (e) { // If we haven't been passed the event get the window.event e = e || window.event; var message = 'Any text will block the navigation and display a prompt'; // For IE6-8 and Firefox prior to version 4 if (e) { e.returnValue = message; } // For Chrome, Safari, IE8+ and Opera 12+ return message; }; ``` You can't have that `confirmOnPageExit` do the check and return null if you want the user to continue without the message. You still need to remove the event to reliably turn it on and off: ``` // Turn it on - assign the function that returns the string window.onbeforeunload = confirmOnPageExit; // Turn it off - remove the function entirely window.onbeforeunload = null; ``` ## Original answer (worked in 2009) To turn it on: ``` window.onbeforeunload = "Are you sure you want to leave?"; ``` To turn it off: ``` window.onbeforeunload = null; ``` Bear in mind that this isn't a normal event - you can't bind to it in the standard way. To check for values? That depends on your validation framework. In jQuery this could be something like (very basic example): ``` $('input').change(function() { if( $(this).val() != "" ) window.onbeforeunload = "Are you sure you want to leave?"; }); ```
The `onbeforeunload` Microsoft-ism is the closest thing we have to a standard solution, but be aware that browser support is uneven; e.g. for Opera it only works in version 12 and later (still in beta as of this writing). Also, for **maximum compatibility**, you need to do more than simply return a string, as explained on the [Mozilla Developer Network](https://developer.mozilla.org/en/DOM/window.onbeforeunload). **Example:** Define the following two functions for enabling/disabling the navigation prompt (cf. the MDN example): ``` function enableBeforeUnload() { window.onbeforeunload = function (e) { return "Discard changes?"; }; } function disableBeforeUnload() { window.onbeforeunload = null; } ``` Then define a form like this: ``` <form method="POST" action="" onsubmit="disableBeforeUnload();"> <textarea name="text" onchange="enableBeforeUnload();" onkeyup="enableBeforeUnload();"> </textarea> <button type="submit">Save</button> </form> ``` This way, the user will only be warned about navigating away if he has changed the text area, and will not be prompted when he's actually submitting the form.
How to show the "Are you sure you want to navigate away from this page?" when changes committed?
[ "", "javascript", "html", "message", "onbeforeunload", "confirm", "" ]
I'd like to check if an object is a number so that `.ToString()` would result in a string containing digits and `+`, `-`, `.` Is it possible by simple type checking in .NET? Like: ``` if (p is Number) ``` Or should I convert to `string`, then try parsing to `double`? **Update:** To clarify my object is `int`, `uint`, `float`, `double`, and so on, it isn't a `string`. I'm trying to make a function that would serialize any object to XML like this: ``` <string>content</string> ``` or ``` <numeric>123.3</numeric> ``` or raise an exception.
You will simply need to do a type check for each of the basic numeric types. Here's an extension method that should do the job: ``` public static bool IsNumber(this object value) { return value is sbyte || value is byte || value is short || value is ushort || value is int || value is uint || value is long || value is ulong || value is float || value is double || value is decimal; } ``` This should cover all numeric types. ## Update It seems you do actually want to parse the number from a string during deserialisation. In this case, it would probably just be best to use `double.TryParse`. ``` string value = "123.3"; double num; if (!double.TryParse(value, out num)) throw new InvalidOperationException("Value is not a number."); ``` Of course, this wouldn't handle very large integers/long decimals, but if that is the case you just need to add additional calls to `long.TryParse` / `decimal.TryParse` / whatever else.
Taken from [Scott Hanselman's Blog](http://www.hanselman.com/blog/ExploringIsNumericForC.aspx): ``` public static bool IsNumeric(object expression) { if (expression == null) return false; double number; return Double.TryParse( Convert.ToString( expression , CultureInfo.InvariantCulture) , System.Globalization.NumberStyles.Any , NumberFormatInfo.InvariantInfo , out number); } ```
Checking if an object is a number
[ "", "c#", ".net", "serialization", "types", "xml-serialization", "" ]
I have this HTML dropdown: ``` <form> <input type="text" id="realtxt" onkeyup="searchSel()"> <select id="select" name="basic-combo" size="1"> <option value="2821">Something </option> <option value="2825">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Something </option> <option value="2842">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Something </option> <option value="2843">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;_Something </option> <option value="15999">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;_Something </option> </select> </form> ``` I need to search trough it using javascript. This is what I have now: ``` function searchSel() { var input=document.getElementById('realtxt').value.toLowerCase(); var output=document.getElementById('basic-combo').options; for(var i=0;i<output.length;i++) { var outputvalue = output[i].value; var output = outputvalue.replace(/^(\s|&nbsp;)+|(\s|&nbsp;)+$/g,""); if(output.indexOf(input)==0){ output[i].selected=true; } if(document.forms[0].realtxt.value==''){ output[0].selected=true; } } } ``` The code doesn't work, and it's probably not the best. Can anyone show me how I can search trough the dropdown items and when i hit enter find the one i want, and if i hit enter again give me the next result, using plain javascript?
Here's the fixed code. It searches for the first occurrence only: ``` function searchSel() { var input = document.getElementById('realtxt').value; var list = document.getElementById('select'); var listItems = list.options; if(input === '') { listItems[0].selected = true; return; } for(var i=0;i<list.length;i++) { var val = list[i].value.toLowerCase(); if(val.indexOf(input) == 0) { list.selectedIndex = i; return; } } } ``` You should not check for empty text outside the for loop. Also, this code will do partial match i.e. if you type 'A', it will select the option 'Artikkelarkiv' option.
Right of the bat, your code won't work as you're selecting the dropdown wrong: ``` document.getElementById("basic-combo") ``` is wrong, as the id is `select`, while "basic-combo" is the name attribute. And another thing to note, is that you have two variable named `output`. Even though they're in different scopes, it might become confusing.
Search a dropdown
[ "", "javascript", "drop-down-menu", "" ]
In c# , when sending a parameter to a method, when should we use "ref" and when "out" and when without any of them?
In general, you should avoid using ref and out, if possible. That being said, use ref when the method *might need* to modify the value. Use out when the method *always should* assign something to the value. The difference between ref and out, is that when using out, the compiler enforces the rule, that you need to assign something to the out paramter before returning. When using ref, you must assign a value to the variable *before* using it as a ref parameter. Obviously, the above applies, when you are writing your own methods. If you need to call methods that was declared with the ref or out modifiers on their parameters, you should use the same modifier before your parameter, when calling the method. Also remember, that C# passes reference types (classes) by reference (as in, the reference is passed by value). So if you provide some method with a reference type as a parameter, the method can modify the data of the object; even without ref or out. But it cannot modify the reference itself (as in, it cannot modify which object is being referenced).
They are used mainly to obtain multiple return values from a method call. Personally, I tend to not use them. If I want multiple return values from a method then I'll create a small class to hold them. ref and out are used when you want something back from the method in that parameter. As I recall, they both actually compile down to the same IL, but C# puts in place some extra stuff so you have to be specific. Here are some examples: ``` static void Main(string[] args) { string myString; MyMethod0(myString); Console.WriteLine(myString); Console.ReadLine(); } public static void MyMethod0(string param1) { param1 = "Hello"; } ``` The above won't compile because myString is never initialised. If myString is initialised to string.Empty then the output of the program will be a empty line because all MyMethod0 does is assign a new string to a local reference to param1. ``` static void Main(string[] args) { string myString; MyMethod1(out myString); Console.WriteLine(myString); Console.ReadLine(); } public static void MyMethod1(out string param1) { param1 = "Hello"; } ``` myString is not initialised in the Main method, yet, the program outputs "Hello". This is because the myString reference in the Main method is being updated from MyMethod1. MyMethod1 does not expect param1 to already contain anything, so it can be left uninitialised. However, the method should be assigning something. ``` static void Main(string[] args) { string myString; MyMethod2(ref myString); Console.WriteLine(myString); Console.ReadLine(); } public static void MyMethod2(ref string param1) { param1 = "Hello"; } ``` This, again, will not compile. This is because ref demands that myString in the Main method is initialised to something first. But, if the Main method is changed so that myString is initialised to string.Empty then the code will compile and the output will be Hello. So, the difference is out can be used with an uninitialised object, ref must be passed an initialised object. And if you pass an object without either the reference to it cannot be replaced. Just to be clear: If the object being passed is a reference type already then the method can update the object and the updates are reflected in the calling code, however the reference to the object cannot be changed. So if I write code like this: ``` static void Main(string[] args) { string myString = "Hello"; MyMethod0(myString); Console.WriteLine(myString); Console.ReadLine(); } public static void MyMethod0(string param1) { param1 = "World"; } ``` The output from the program will be Hello, and not World because the method only changed its local copy of the reference, not the reference that was passed in. I hope this makes sense. My general rule of thumb is simply not to use them. I feel it is a throw back to pre-OO days. (But, that's just my opinion)
In c# , when sending a parameter to a method, when should we use "ref" and when "out" and when without any of them?
[ "", "c#", "methods", "parameters", "" ]
When does Java's `Thread.sleep` throw `InterruptedException`? Is it safe to ignore it? I am not doing any multi-threading. I just want to wait for a few seconds before retrying some operation.
You should generally NOT ignore the exception. Take a look at the following paper: > **Don't swallow interrupts** > > Sometimes throwing InterruptedException is > not an option, such as when a task defined by Runnable calls an > interruptible method. In this case, you can't rethrow > InterruptedException, but you also do not want to do nothing. When a > blocking method detects interruption and throws InterruptedException, > it clears the interrupted status. If you catch InterruptedException > but cannot rethrow it, you should preserve evidence that the > interruption occurred so that code higher up on the call stack can > learn of the interruption and respond to it if it wants to. This task > is accomplished by calling interrupt() to "reinterrupt" the current > thread, as shown in Listing 3. At the very least, whenever you catch > InterruptedException and don't rethrow it, reinterrupt the current > thread before returning. > > ``` > public class TaskRunner implements Runnable { > private BlockingQueue<Task> queue; > > public TaskRunner(BlockingQueue<Task> queue) { > this.queue = queue; > } > > public void run() { > try { > while (true) { > Task task = queue.take(10, TimeUnit.SECONDS); > task.execute(); > } > } > catch (InterruptedException e) { > // Restore the interrupted status > Thread.currentThread().interrupt(); > } > } > } > ``` > > * From [Don't swallow interrupts](https://web.archive.org/web/20210301203607/http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html?ca=drs-) --- See the entire paper here: [http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html?ca=drs-](https://web.archive.org/web/20210301203607/http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html?ca=drs-)
If an `InterruptedException` is thrown it means that something wants to interrupt (usually terminate) that thread. This is triggered by a call to the threads `interrupt()` method. The wait method detects that and throws an `InterruptedException` so the catch code can handle the request for termination immediately and does not have to wait till the specified time is up. If you use it in a single-threaded app (and also in some multi-threaded apps), that exception will never be triggered. Ignoring it by having an empty catch clause I would not recommend. The throwing of the `InterruptedException` clears the interrupted state of the thread, so if not handled properly that info gets lost. Therefore I would propose to run: ``` } catch (InterruptedException e) { Thread.currentThread().interrupt(); // code for stopping current task so thread stops } ``` Which sets that state again. After that, finish execution. This would be correct behaviour, even tough never used. What might be better is to add this: ``` } catch (InterruptedException e) { throw new RuntimeException("Unexpected interrupt", e); } ``` ...statement to the catch block. That basically means that it must never happen. So if the code is re-used in an environment where it might happen it will complain about it.
When does Java's Thread.sleep throw InterruptedException?
[ "", "java", "multithreading", "sleep", "interrupted-exception", "interruption", "" ]
In many programming languages something like this is possible for prepared statements: ``` PreparedStatement statement = connection.prepareStatement( "SELECT id FROM Company WHERE name LIKE ${name}"); statement.setString("name", "IBM"); ``` But not with java.sql.PreparedStatement. In Java one has to use parameter indices: ``` PreparedStatement statement = connection.prepareStatement( "SELECT id FROM Company WHERE name LIKE ?"); statement.setString(1, "IBM"); ``` Is there a solution to work with string variables like in the first example? Is "${.\*}" not used somewhere else in the SQL language, or are there any conflicts? Cause then I would implement it by myself (parsing the SQL string and replacing every variable by "?" and then doing it the Java way). Regards, Kai
As kd304 mentioned in the comment to my posting, this is a very nice solution if you don't want to incorporate another 3rd party library (like Spring) into your project: [Javaworld Article: Named Parameters for PreparedStatement](http://www.javaworld.com/javaworld/jw-04-2007/jw-04-jdbc.html)
Standard JDBC PreparedStatements don't have this ability. Spring JDBC provides this functionality through [`NamedParameterJdbcTemplate`](http://static.springsource.org/spring/docs/2.5.x/reference/jdbc.html#jdbc-NamedParameterJdbcTemplate "NamedParameterJdbcTemplate").
Using a variable instead of a parameter index with a JDBC prepared statement
[ "", "java", "jdbc", "" ]
I need to manipulate large strings in Java (deleting and adding the deleted chars again, moving chars around), but still want to remember the original position offsets. E.g. the word "computer" starts at offset 133 in the original text and is then moved to position 244, I still want the info that it was originally at position 133. The most ugly (and resource hungry) solution would be to store for every character its original position plus it's position change. There are surely better solutions, but also more complex ones. Are there any good text manipulation libraries that have a solution to my problem? I don't want to reinvent the wheel. Regards, Kai
How large are these strings ? Given the quantities of memory available today, brute force may be the way to go. You talk about moving words, but storing character positions. Why not store word positions, and a history per instance of word. Note that you could be clever and make use of the [flyweight pattern](http://en.wikipedia.org/wiki/Flyweight_pattern) to save having multiple instances of these objects until you require. i.e. your 'string' object holds one 'computer' word object, but records that that word occurs at position 133, 245, 667 etc. (plus history as and when you need it)
The problem you are referring to is officially called the "[String-to-string correction problem](http://en.wikipedia.org/wiki/String-to-string_correction_problem)" which is related to [Delta Encoding](http://en.wikipedia.org/wiki/Delta_encoding) and the [Levenshtein Distance](http://en.wikipedia.org/wiki/Levenshtein_distance). [Here](http://www.merriampark.com/ld.htm) is code to compute the distance (it's in Java). All the differencing code is there, you simply have to add code that keeps track of the steps so you can reverse them or track them. Note: "moving" a word or character would be a delete/insert pair of the same word that occurs together. This should work for both character, word, and substring moves.
Text manipulation while keeping original position offsets
[ "", "java", "text-processing", "" ]
I have a List with numbers, and I'd like to find the position of the minimum (not value) using LINQ Example: ``` var lst = new List<int>() { 3, 1, 0, 5 }; ``` Now I am looking for a function returning me > output = 2 because the minimum is at position 2 in the list.
``` var list = new List<int> { 3, 1, 0, 5 }; int pos = list.IndexOf(list.Min()); // returns 2 ```
As you specifically asked for a LINQ solution, and all you got was non-LINQ solutions, here's a LINQ solution: ``` List<int> values = new List<int> { 3, 1, 0, 5 }; int index = values .Select((n, i) => new { Value = n, Index = i }) .OrderBy(n=>n.Value) .First() .Index; ``` That however doesn't mean that LINQ is the best solution for this problem... ### Edit: With a bit more complex code this performs a little better: ``` int index = values .Select((n, i) => new { Value = n, Index = i }) .Aggregate((a,b) => a.Value < b.Value ? a : b) .Index; ``` To get the best performance, you would use a plain loop go get through the items, while you keep track of the lowest: ``` int index = 0, value = values[0]; for (int i = 1; i < values.Length; i++) { if (values[i] < value) { value = values[i]; index = i; } } ```
Get List<> element position in c# using LINQ
[ "", "c#", ".net", "linq", ".net-core", "position", "" ]
In my web page i used a gridview. In this gridview it shows a group of users information. I just added one button from smart tag menu. And my requirement is that when i am hitting the button corresponding to each users, it will redirect to another page and shows the corresponding user's information. What i do for getting this type of output?
U have to add the button and add an attribute CommandName: ``` <asp:Button ID="EditBtn" runat="server" CommandName="Edit" /> ``` then in the event of itemcommand of the grid do the following ``` protected void GridView1_ItemCommand(object source, GridViewCommandEventArgs e) { if (e.CommandName == "Edit") { //Redirect to user page information Response.Redirect(PageURL); } } ```
Ahmy's answer is the way to go if you want to use a button and have your page redirect to another page with the user's information. One thing that was left out however was that you can pass a command argument through the button (like the user's unique ID) which you could then put in the querystring of the page you are redirecting to, to identify which user it is. That would look like this: ``` <asp:TemplateField HeaderText="Edit User"> <ItemTemplate> <asp:Button ID="EditBtn" Text="Edit User" CommandName="Edit" CommandArgument='<%# Eval("UserID") %>' runat="server" /> </ItemTemplate> </asp:TemplateField> ``` Then in the code behind ``` protected void GridView1_ItemCommand(object source, GridViewCommandEventArgs e) { if (e.CommandName == "Edit") { //Redirect to user page information Response.Redirect("UserProfilePage.aspx?userID=" + e.CommandArgument); } } ``` Another alternative to using a button, which I think is the best option is to use a HyperLinkField. When using a button, the page will have to post back to the server, then send a redirect to the user's browser. With a hyperlink, the user goes straight to the correct page. It saves a step and doesn't rely on javascript. ``` <asp:HyperLinkField DataTextField="UserName" DataNavigateUrlFields="UserID" DataNavigateUrlFormatString="UserProfilePage.aspx?userID={0}" HeaderText="Edit User" /> ```
gridview editing
[ "", "c#", "asp.net", "sql-server", "" ]
I have two Datetime fields that I wish to add together. They are in the following format: '01/01/1900 00:00:00'. The main issue with this is that I want the calculation to only include working hours. The working day is between 08:30 and 17:30 and does not include weekends: Also if the first field starts out of the working day or is on a weekend then the second field should be added from the start of the next working day. For example: `'26/06/2009 15:45:00' + '01/01/1900 09:00:00' = '29/06/1900 15:45:00' '12/07/2009 14:22:36' + '01/01/1900 18:00:00' = '13/07/1900 08:30:00' '15/07/2009 08:50:00' + '01/01/1900 04:00:00' = '15/07/2009 12:50:00'` Im pretty sure that this is going to involve creating a user defined function to work this out but I have no idea how to even start this(I am quite out of my depth here) Could anyone offer me some advice on how to achieve this?
try this, you might have to put it in a function ``` DECLARE @Date DATETIME, @StartOfDay FLOAT, @EndOfDay FLOAT, @DateAdd DATETIME SELECT @Date ='2009-06-26 15:45:00.000', @StartOfDay = 8.5, @EndOfDay = 17.5, @DateAdd = '1900-01-01 09:00:00.000' --fix up start date --before start of day, move to start of day IF ((CAST(@Date - DATEADD(dd,0, DATEDIFF(dd,0,@Date)) AS FLOAT) * 24) < @StartOfDay) BEGIN SET @Date = DATEADD(mi, @StartOfDay * 60, DATEDIFF(dd,0,@Date)) END --after close of day, move to start of next day IF ((CAST(@Date - DATEADD(dd,0, DATEDIFF(dd,0,@Date)) AS FLOAT) * 24) > @EndOfDay) BEGIN SET @Date = DATEADD(mi, @StartOfDay * 60, DATEDIFF(dd,0,@Date)) + 1 END --move to monday if on weekend WHILE DATENAME(dw, @Date) IN ('Saturday','Sunday') BEGIN SET @Date = @Date + 1 END --get the number of hours to add and the total hours per day DECLARE @HoursPerDay FLOAT DECLARE @HoursAdd FLOAT SET @HoursAdd = DATEDIFF(hh, '1900-01-01 00:00:00.000', @DateAdd) SET @HoursPerDay = @EndOfDay - @StartOfDay --date the time of geiven day DECLARE @CurrentHours FLOAT SET @CurrentHours = CAST(@Date - DATEADD(dd,0, DATEDIFF(dd,0,@Date)) AS FLOAT) * 24 --if we stay in the same day, all is fine IF (@CurrentHours + @HoursAdd <= @EndOfDay) BEGIN SET @Date = @Date + @DateAdd END ELSE BEGIN --remove part of day SET @HoursAdd = @HoursAdd - (@EndOfDay - @CurrentHours) --,ove to next day SET @Date = DATEADD(dd,0, DATEDIFF(dd,0,@Date)) + 1 --loop day WHILE @HoursAdd > 0 BEGIN --add day but keep hours to add same IF (DATENAME(dw,@Date) IN ('Saturday','Sunday')) BEGIN SET @Date = @Date + 1 END ELSE BEGIN --add a day, and reduce hours to add IF (@HoursAdd > @HoursPerDay) BEGIN SET @Date = @Date + 1 SET @HoursAdd = @HoursAdd - @HoursPerDay END ELSE BEGIN --add the remainder of the day SET @Date = DATEADD(mi, (@HoursAdd + @StartOfDay) * 60, DATEDIFF(dd,0,@Date)) SET @HoursAdd = 0 END END END END SELECT @Date ``` Hope that helps
you could use the dayofweek function and some in-line case statements; <http://www.smallsql.de/doc/sql-functions/date-time/dayofweek.html> <http://www.tizag.com/sqlTutorial/sqlcase.php> so, you'd perform the calculation if the dayofweek function didn't return sat. or sun.; else return a null. I think you could get away without writing a user-defined function, but the sql statement would look a bit messy. but then again most non-basic sql statements all look a bit messy!
T-Sql 2005 Adding hours to a datetime field with the result within working hours
[ "", "sql", "t-sql", "dateadd", "" ]
I have the typical HTML "contact me" page, i.e. name, e-mail address and message. Since I want to do input validation on the page itself using JavaScript, I can't use a `submit` button, otherwise, the attached JavaScript function would be ignored. At least that's how I understand it, CMIIW. I tried to load the next page writing `location = mail.php` but it appears that the form parameters don't get passed to my PHP page this way. How do I validate input in JavaScript and pass parameters to my PHP page when ok? TIA Steven
Use the onSubmit event. Attach it to your form and if it returns true then your form will be sent to the PHP page. Read more [here](http://www.htmlcodetutorial.com/forms/_FORM_onSubmit.html).
You can use a form with an onsubmit handler on it, that returns false if the validation failed. If the check is ok, return true and the form will submit normally. You'd have a javascript function something like this: ``` function check_it_all() { if (all_ok) { return true; } else { return false; } } ``` And the form ``` <form action=..... onsubmit="return check_it_all();"> .... </form> ```
Passing parameters from JavaScript
[ "", "javascript", "" ]
My situation is that I screwed up essentially. I inherited my code base about 1.5 years ago when I took this position and rather than reinventing the wheel, even though I know now that I should have, I kept the DAL in pretty much the same structure as the previous developer. Essentially there is one file (now at 15k lines of code) that serves as a go between to a bunch of DAO's that use DataSets and TableAdapters to retrieve data. My xsd files have grown to such size that they cause R# to crash visual studio every time it opens and the intermediary class that is now 15k lines also takes forever for R# to analyze. Not to mention it is ugly, it works but not well, and is an absolute nightmare to debug. What I have tried thus far is switching to NHibernate. NHibernate is a great library, but unfortunately it was not adaptable enough to work with my application, from what the lead developer says (Fabio Maulo) it is pretty much a combination of my application requirements and the restrictions upon NHibernate when using identity as a database PK strategy. So now I am back to essentially designing my own DAL. I am looking at a few different patterns for this, but would like to get your DAL design strategies. There are so many ways and reasons to implement a DAL in a particular manner so if you could please explain your strategy and why it was best fit for you I would greatly appreciate it. Thanks in advance! Edit: Let me explain why NHibernate did not work since that seems to be the immediate response. My users create a "job" that is actually just a transient representation of my Job class. Within this job they will give it one or a list of weight factors that are also transient at the time of creation. Finally they provide a list of job details that have a particular weight factor associated to them. Because, in the DB, weight factors are unique when I go to persist the job and it cascades down to weight factor it dies when it finds a duplicate weight factor. I tried running a check before assigning the weight factor to the detail (which I didn't want to do because I don't want the extra calls to the db) but calling CreateCriteria in NH also causes a flush in the session, according to Fabio, which destroys my cache and thus kills the entire in memory representation of the job. Folks over at the NH mailing list said I should switch over to GUID, but that is not a feasible option as the conversion process would be a nightmare.
My experience with NHibernate is that, while it is packed with features and very high-performance, you will eventually need to become an NHibernate expert in order to fix some unexpected behavior. Reading through the pro-NHibernate answers and seeing > Hmm , perhaps he uses long running > Sessions (Session per Business > Transaction model), and in such an > approach, using identity is > discouraged, since it breaks your > unitofwork (it needs to flush directly > after inserting a new entity). A > solution could be to drop the > identity, and use the HiLo identity > generator. illustrates exactly what I mean. What I've done is create a base class modeled somewhat off of the ActiveRecord pattern, that I inherit from and mark up the inherited class with attributes that attach it to a stored procedure each for Select, Insert, Update and Delete. The base class uses Reflection to read the attributes and assign the class's property values to SP parameters, and in the case of Select(), assign the result SQLDataReader's column values to the properties of a list of generics. This is what DataObjectBase looks like: ``` interface IDataObjectBase<T> { void Delete(); void Insert(); System.Collections.Generic.List<T> Select(); void Update(); } ``` This is an example of a data class deriving from it: ``` [StoredProcedure("usp_refund_CustRefundDetailInsert", OperationType.Insert)] [StoredProcedure("usp_refund_CustRefundDetailSelect", OperationType.Select)] [StoredProcedure("usp_refund_CustRefundDetailUpdate", OperationType.Update)] public class RefundDetail : DataObjectBase<RefundDetail> { [StoredProcedureParameter(null, OperationType.Update, ParameterDirection.Input)] [StoredProcedureParameter(null, OperationType.Insert, ParameterDirection.Output)] [StoredProcedureParameter(null, OperationType.Select, ParameterDirection.Input)] [ResultColumn(null)] public int? RefundDetailId { get; set; } [StoredProcedureParameter(null, OperationType.Update, ParameterDirection.Input)] [StoredProcedureParameter(null, OperationType.Insert, ParameterDirection.Input)] [StoredProcedureParameter(null, OperationType.Select, ParameterDirection.Input)] [ResultColumn(null)] public int? RefundId { get; set; } [StoredProcedureParameter(null, OperationType.Update, ParameterDirection.Input)] [StoredProcedureParameter(null, OperationType.Insert, ParameterDirection.Input)] [ResultColumn(null)] public int RefundTypeId { get; set; } [StoredProcedureParameter(null, OperationType.Update, ParameterDirection.Input)] [StoredProcedureParameter(null, OperationType.Insert, ParameterDirection.Input)] [ResultColumn(null)] public decimal? RefundAmount { get; set; } [StoredProcedureParameter(null, OperationType.Update, ParameterDirection.Input)] [StoredProcedureParameter(null, OperationType.Insert, ParameterDirection.Input)] [ResultColumn(null)] public string ARTranId { get; set; } } ``` I know it seems like I'm reinventing the wheel, but all of the libraries I found either had too much dependence on other libraries (ActiveRecord + NHibernate, for instance, which was a close second) or were too complicated to use and administer. The library I made is very lightweight (maybe a couple of hundred lines of C#) and doesn't do anything more than assign values to parameters and execute the SP. It also lends itself very well to code generation, so eventually I expect to write no data access code. I also like that it uses a class instance instead of a static class, so that I can pass data to queries without some awkward criteria collection or HQL. Select() means "get more like me".
For me the best fit was a pretty simple concept - use DAO class definitions and with reflection create all SQL necessary to populate and save them. This way there is no mapping file, only simple classes. My DAO's require an Entity base class so it is not a POCO but that doesn't bother me. It does support any type of primary key, be it single identity column or multi column.
What DAL strategy do you use or suggest?
[ "", "c#", ".net", "database", "design-patterns", "" ]
I just started exploring Scala in my free time. I have to say that so far I'm very impressed. Scala sits on top of the JVM, seamlessly integrates with existing Java code and has many features that Java doesn't. Beyond learning a new language, what's the downside to switching over to Scala?
Well, the downside is that you have to be prepared for Scala to be a bit rough around the edges: * you'll get the odd cryptic Scala compiler internal error * the IDE support isn't quite as good as Java (neither is the debugging support) * there will be breaks to backwards compatibility in future releases (although these will be limited) You also have to take some risk that Scala as a language will fizzle out. That said, **I don't think you'll look back**! My experiences are positive overall; the IDE's are useable, you get used to what the cryptic compiler errors mean and, whilst your Scala codebase is small, a backwards-compatibility break is not a major hassle. It's worth it for `Option`, the *monad* functionality of the collections, *closures*, the *actors* model, extractors, covariant types etc. It's an awesome language. It's also of great *personal* benefit to be able to approach problems from a different angle, something that the above constructs allow and encourage.
Some of the downsides of Scala are not related at all to the relative youth of the language. After all, Scala, has about 5 years of age, and Java was very different 5 years into its own lifespan. In particular, because Scala does not have the backing of an enterprise which considers it a strategic priority, the support resources for it are rather lacking. For example: * Lack of extensive tutorials * Inferior quality of the documentation * Non-existing localization of documentation * Native libraries (Scala uses Java or .NET libraries as base for their own) Another important difference is due to how Sun saw Java and [EPFL](http://en.wikipedia.org/wiki/%C3%89cole_Polytechnique_F%C3%A9d%C3%A9rale_de_Lausanne) sees Scala. Sun saw Java as a product to get enterprise customers. EPFL sees Scala as a language intended to be a better language than existing ones, in some particular respects (OOxFunctional integration, and type system design, mostly). As a consequence, where Sun made JVM glacially-stable, and Java fully backward compatible, with very slow deprecation and removal of features (actually, removal?), JAR files generated with one version of Scala won't work at all with other versions (a serious problem for third party libraries), and the language is constantly getting new features as well as actually removing deprecated ones, and so is Scala's library. The revision history for Scala 2.x, which I think is barely 3 years old, is impressive. Finally, because of all of the above, third party support for Scala is [incipient](http://en.wiktionary.org/wiki/incipient). But it's important to note, though, that [JetBrains](http://en.wikipedia.org/wiki/JetBrains), which makes *money* out of selling the [IntelliJ IDEA](http://en.wikipedia.org/wiki/IntelliJ_IDEA) IDE, has supported Scala for quite some time, and keeps improving its support. That means, to me, that there is demand for third party support, and support is bound to increase. I point to the book situation. One year ago there was no Scala book on the market. Right now there are two or three introductory Scala books *on the market*, about the same number of books should be out before the end of the year, and there is a book about a very important web framework based on Scala, [Lift](http://en.wikipedia.org/wiki/Lift_%28web_framework%29). I bet we'll see a book about [ESME](http://incubator.apache.org/esme/) not too far in the future, as well as books about Scala and concurrency. The publishing market has apparently reached the tipping point. Once that happens, enterprises will follow.
Scala as the new Java?
[ "", "java", "scala", "" ]
Doesn't object initialization outside of a constructor break encapsulation ? Given: ``` class MyClass { public string _aString; } ``` Shouldn't the \_aString member be private and instantiated via a call to the constructor (constructor omitted here): ``` MyClass test = new MyClass("test"); ``` Instead of the alternate method of object initialization: ``` MyClass test = new MyClass { _aString = "Test" }; ```
*"Doesn't object initialization outside of a constructor break encapsulation ?"* Well, no. As you rightly pointed out you can only initialize properties that are already accessible in your current scope. (public, internal etc) This kind of Intialization is really just some syntactic sugar around construction of a class and assigning values to properties, It is very useful for Anonymous classes and Linq select clauses.
It is usually considered bad practice to expose public fields... it may be acceptable in some cases, for instance if the field is marked as `readonly` (which means it must be set in the constructor). Instead, you should make this field private and expose it through a property, which may or may not be readonly, depending on its purpose : ``` class MyClass { private string _aString; public string AString { get { return _aString; } // uncomment to make the property writable //set { _aString = value; } } } ```
C# object initialization options
[ "", "c#", "object", "constructor", "initialization", "" ]
How do people normally manage copying a list of large objects around? Here's my situation: Currently I have this: ``` typedef std::vector<float> Image; ``` and I'm storing it in a ``` std::list<Image> lst; ``` The Image.size() is quite large (each is ~3-5 MB). I'm passing (copying) the list around. Is it a correct understanding on my part that std::vector will copy each element by value? If so, the performance might be a bit awful due to excessive copying? What can I do to minimize copying? Should I instead store ``` std::list<ImageRef> lst; ``` where ``` typedef boost::shared_ptr<Image> ImageRef; ``` ? What's the elegant way of handling this kind of issue?
Objects larger than built-in types are most often way cheaper to pass around by reference then by value. So if your object is about 3 Meg big, and you need to pass it around, please don't copy it! All STL types use value semantics: they copy their content. Note that content may exist of pointers. In that case the pointers are copied, not what they refer to. It may even be a good idea to pass your image-list around by reference. Saves a lot of smart-pointer copying, so it saves a lot of reference-count management, and may save a lot of locks/unlocks.
I think the `boost::shared_ptr` route is a good approach, as long as it doesn't matter that the `Image`s don't get copied when the list is copied. You'll minimize copying but the reference counting will also clean things up for you when the last list is destroyed.
C++ Storing large data in std::list<> ..should I use reference counting?
[ "", "c++", "reference-counting", "stdlist", "" ]
I would like to be able to spawn a process in python and have two way communication. Of course, Pexpect does this and is indeed a way I might go. However, it is not quite ideal. My ideal situation would be to have a cross platform generic technique that involved only the standard python libraries. Subprocess gets pretty close, but the fact that I have to wait for the process to terminate before safely interacting with it is not desirable. Looking at the documentation, it does say there is a stdin,stdout and stderr file descriptors that I can directly manipulate, but there is a big fat warning that says "Don't Do This". Unfortunately its not entirely clear why this warning exists, but from what I gather from google is that it is related to os buffering, and it is possible to write code that unexpectedly deadlocks when those internal buffers fail (as a side note, any examples that show the wrong way and right way would be appreciated). So, risking my code to potential deadlocks, I thought it might be interesting to use poll or select to interactively read from the running process without killing it. Although I lose (i think) the cross platform ability, I like the fact that it requires no additional libraries. But more importantly, I would like to know if this is this a good idea. I have yet to try this approach, but I am concerned about gotchas that could potentially devastate my program. Can it work? What should I test for? In my specific case I am not really concerned about being able to write to the process, just repeatedly reading from it. Also, I don't expect my processes to dump huge amounts of text, so I hope to avoid the deadlocking issue, however I would like to know exactly what those limits are and be able to write some tests to see where it breaks down.
Forgive my ignorance on this topic, but couldn't you just launch python with the -u flag for "unbuffered"? This might also be of interest... <http://www.gossamer-threads.com/lists/python/python/658167>
Use the [multiprocessing](http://docs.python.org/library/multiprocessing.html) module in the Python 2.6 standard library. It has a [Queue class](http://docs.python.org/library/multiprocessing.html#multiprocessing.Queue) that can be used for both reading and writing.
Python subprocess question
[ "", "python", "subprocess", "" ]
I have an image data in a buffer(type - long) from a scanner which is 32 bit. For example, buffer[0]'s corresponding pixel value is 952 which is [184, 3, 0, 0] <-[R,G,B,A]; I want to display/Paint/draw on to the screen; I am confused when i tried to read about displying bitmaps. I looked at win32 functions, CBitmap class, windows forms (picture box) etc I am hard to understand the general idea/appraoch for displaying this buffer data on to a application window. I have constructed the BITMAPFILEHEADER AND BITMAPINFOHEADER; Has the pixel data in a buffer, (unsigned char \*)vInBuff whose size is vImageSz; ``` //construct the BMP file Header vBmfh.bfType = 19778; vBmfh.bfSize = 54+vImageSz;//size of the whole image vBmfh.bfReserved2 = 0; vBmfh.bfReserved1 = 0; vBmfh.bfOffBits = 54;//offset from where the pixel data can be found //Construct the BMP info header vBmih.biSize = 40;//size of header from this point vBmih.biWidth = 1004; vBmih.biHeight = 1002; vBmih.biPlanes = 1; vBmih.biCompression = BI_RGB; vBmih.biSizeImage = vBmih.biWidth*vBmih.biHeight*4; vBmih.biBitCount = 32; vBmih.biClrUsed = 0; vBmih.biClrUsed = 0; ``` 1.What is that i should be doing next to display this? 2 What should i be using to display the 32bit bitmap? I see people using createwindows functions, windows forms, MFC etc; 3.I also understand that BitBlt,createDIBSection, OnPaint etc are being used? I am confused by these various functions and coding platforms? Please suggest me a simple approach. 4.How can i create a palette to display a 32 bit image? Thanks Raj **EDITED** TRYING TO IMPLEMENT DAVE'S APPROACH, CAN SOMEBODY COMMENT ON MY IMPLEMTATION. I couldn't continue to the bitblt as i donot have two HDC, i donot know how to get this one? Any help please ``` DisplayDataToImageOnScreen(unsigned char* vInBuff, int vImageSz) // buffer with pixel data, Size of pixel data { unsigned char* vImageBuff = NULL; HDC hdcMem=CreateCompatibleDC(NULL); HBITMAP hBitmap = CreateDIBSection(hdcMem, (BITMAPINFO*)&vBmih, DIB_RGB_COLORS, (void **)&vImageBuff, NULL, 0); GetDIBits(hdcMem, hBitmap, 0, 1, (void**)&vImageBuff, (BITMAPINFO*)&vBmih, DIB_RGB_COLORS); memcpy(vImageBuff,vInBuff,vImageSz); } ```
Here's a simplified approach you can try, broken down into steps: ``` BITMAPINFO bitmapinfo = { 0 }; bitmapinfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bitmapinfo.bmiHeader.biWidth = 1004; bitmapinfo.bmiHeader.biHeight = -1002; bitmapinfo.bmiHeader.biPlanes = 1; bitmapinfo.bmiHeader.biCompression = BI_RGB; HBITMAP hBitmap = CreateDIBSection(NULL, &bitmapinfo, DIB_RGB_COLORS, (void **)&vImageBuff, NULL, 0); ``` Now party on vImageBuff and then cache hBitmap somewhere so that within your wndproc you can then in the WM\_PAINT handler: 1. select hBitmap into temp compatible HDC 2. call BitBlt(..., SRCCOPY) from the compatible HDC to the window's HDC. the other parameters should be obvious. don't try to stretch or do anything fancy at first. 3. remember to select the original dummy bitmap into the temp HDC before destroying it. If you aren't seeing results try looping through vImageBuff and just set every pixel to RGB(255, 0, 0), or something like that, just to sanity check the rest of the logic. If nothing is drawing make sure that the alpha component for each pixel is 255. If you're getting a garbled image then you need to double-check pixelformat, stride, etc.
An alternative if you just want to plot it on screen is to use TinyPTC ( <http://sourceforge.net/projects/tinyptc/files/> ). It's just 3 functions and very simple if you just want to plot some pixels. EDIT: Seems like <http://www.pixeltoaster.com> is a continuation of TinyPTC, probably preffered.
Display 32bit bitmap - Palette
[ "", "c++", "windows", "image", "bitmap", "" ]
I've written a PHP extension in C, and I want to create [PHPdoc](http://www.phpdoc.org/) documentation so that my users will get inline docs in their PHP IDE (in this case, Netbeans) when calling my extension. Ideally I'd like to do this by embedding the PHPdocs in the C code, to keep implementation and documentation together. Assuming it's possible to embed PHPdocs into the C, what extra steps are needed to make the documentation appear in Netbeans (as it would for PHPdocs of PHP code)? edit: [O'Reilly Programming PHP](http://docstore.mik.ua/orelly/webprog/php/ch14_03.htm) refers to the `/* {{{ proto` comment format being used in doc generation, though I'm not sure if the referred scripts generate PHPdocs: > The {{{ proto line is not only used > for folding in the editor, but is also > parsed by the genfunclist and > genfuncsummary scripts that are part > of the PHP documentation project. If > you are never going to distribute your > extension and have no ambitions to > have it bundled with PHP, you can > remove these comments.
One approach that works is to have a PHP file with stub functions with the appropriate PHPdocs, then DON'T include it in the PHP application, but DO add it to Netbean's PHP include path (in `File->Project Properties->PHP Include Path`). This way type completion and inline docs work, but PHP isn't confused by multiple declarations of the function. This seems a bit hacky, since it would be good keep the docs in the same file as the implementation, but it does actually seem to the correct approach, since that's how the built in functions and extensions are documented - see `~/netbeans-6.7/php1/phpstubs/phpruntime/*.php` eg: In the C file: ``` PHP_FUNCTION(myFunctionStringFunction) { // extension implementation } ``` And then in a PHP file, the stub declaration: ``` /** * My docs here * @param string $myString */ function myFunctionStringFunction($myString) { die("Empty stub function for documenation purposes only. This file shouldn't be included in an app."); } ```
you only need to use the right TAGS inside your Comments. ``` /** * Returns the OS Languages for an Subversion ID * * @access public * @param int $subVersionId Subversion ID * @return array $results Languages for Subversion ID */ ``` You can find all available tags on the documenation [PHPDoc](http://manual.phpdoc.org/HTMLSmartyConverter/HandS/phpDocumentor/tutorial_phpDocumentor.pkg.html)
Documenting a PHP extension with PHPdoc
[ "", "php", "netbeans", "phpdoc", "php-extension", "" ]
I have some problem with CompletionService. My task: to parse parallely for about 300 html pages, **i need to wait for all the results only for 5 seconds,** then - return the result to main code. I`ve decided to use CompletionService + Callable for this. **The question is how to stop all threads, that were caused by CompletionService and return the result from that pages, that were successfully parsed?** In this code removed printlines, but i can say that 5 seconds is enough(there are good results, but program wait when all threads will be completed). My code performed about 2 minutes. **My calling code:** ``` Collection<Callable<HCard>> solvers = new ArrayList<Callable<HCard>>(); for (final String currentUrl : allUrls) { solvers.add(new Callable<HCard>() { public HCard call() throws ParserException { HCard hCard = HCardParser.parseOne(currentUrl); if (hCard != null) { return hCard; } else { return null; } } }); } ExecutorService execService = Executors.newCachedThreadPool(); Helper helper = new Helper(); List<HCard> result = helper.solve(execService, solvers); //then i do smth with result list ``` **My called code:** ``` public class Helper { List<HCard> solve(Executor e, Collection<Callable<HCard>> solvers) throws InterruptedException { CompletionService<HCard> cs = new ExecutorCompletionService<HCard>(e); int n = solvers.size(); Future<HCard> future = null; HCard hCard = null; ArrayList<HCard> result = new ArrayList<HCard>(); for (Callable<HCard> s : solvers) { cs.submit(s); } for (int i = 0; i < n; ++i) { try { future = cs.take(); hCard = future.get(); if (hCard != null) { result.add(hCard); } } catch (ExecutionException e1) { future.cancel(true); } } return result; } ``` I attempted to use: * awaitTermination(5000, TimeUnit.MILLISECONDS) * future.cancel(true) * execService.shutdownNow() * future.get(5000, TimeUnit.MILLISECONDS); * TimeOutException: i can`t get TimeOutException. Please, help me on context of my code. Thanks in advance!
You need to ensure that the tasks that you submit respond properly to interruption, i.e., they check Thread.isInterrupted() or are otherwise deemed "interruptible". I'm not sure that you need a completion service for this. ``` ExecutorService service = ... // Submit all your tasks for (Task t : tasks) { service.submit(t); } service.shutdown(); // Wait for termination boolean success = service.awaitTermination(5, TimeUnit.SECONDS); if (!success) { // awaitTermination timed out, interrupt everyone service.shutdownNow(); } ``` At this point, there is not much you can do if your Task objects don't respond to interruption
The problem is you always get every single result, so the code will always run to completion. I'd do it with a CountDownLatch as per the code below. Also, don't use Executors.newCachedThreadPool - chances are this will spawn a lot of threads (up to 300 if your tasks take any amount of time, as the executor won't let the number of idle threads drop to zero). Classes are all inline to make it easier - paste the whole code block into a class called LotsOfTasks and run it. ``` import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class LotsOfTasks { private static final int SIZE = 300; public static void main(String[] args) throws InterruptedException { String[] allUrls = generateUrls(SIZE); Collection<Callable<HCard>> solvers = new ArrayList<Callable<HCard>>(); for (final String currentUrl : allUrls) { solvers.add(new Callable<HCard>() { public HCard call() { HCard hCard = HCardParser.parseOne(currentUrl); if (hCard != null) { return hCard; } else { return null; } } }); } ExecutorService execService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); // One thread per cpu, ideal for compute-bound Helper helper = new Helper(); System.out.println("Starting.."); long start = System.nanoTime(); List<HCard> result = helper.solve(execService, solvers, 5); long stop = System.nanoTime(); for (HCard hCard : result) { System.out.println("hCard = " + hCard); } System.out.println("Took: " + TimeUnit.SECONDS.convert((stop - start), TimeUnit.NANOSECONDS) + " seconds"); } private static String[] generateUrls(final int size) { String[] urls = new String[size]; for (int i = 0; i < size; i++) { urls[i] = "" + i; } return urls; } private static class HCardParser { private static final Random random = new Random(); public static HCard parseOne(String currentUrl) { try { Thread.sleep(random.nextInt(1000)); // Wait for a random time up to 1 seconds per task (simulate some activity) } catch (InterruptedException e) { // ignore } return new HCard(currentUrl); } } private static class HCard { private final String currentUrl; public HCard(String currentUrl) { this.currentUrl = currentUrl; } @Override public String toString() { return "HCard[" + currentUrl + "]"; } } private static class Helper { List<HCard> solve(ExecutorService e, Collection<Callable<HCard>> solvers, int timeoutSeconds) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(solvers.size()); final ConcurrentLinkedQueue<HCard> executionResults = new ConcurrentLinkedQueue<HCard>(); for (final Callable<HCard> s : solvers) { e.submit(new Callable<HCard>() { public HCard call() throws Exception { try { executionResults.add(s.call()); } finally { latch.countDown(); } return null; } }); } latch.await(timeoutSeconds, TimeUnit.SECONDS); final List<Runnable> unfinishedTasks = e.shutdownNow(); System.out.println("There were " + unfinishedTasks.size() + " urls not processed"); return Arrays.asList(executionResults.toArray(new HCard[executionResults.size()])); } } } ``` Typical output on my system looks something like this: ``` Starting.. There were 279 urls not processed hCard = HCard[0] hCard = HCard[1] hCard = HCard[2] hCard = HCard[3] hCard = HCard[5] hCard = HCard[4] hCard = HCard[6] hCard = HCard[8] hCard = HCard[7] hCard = HCard[10] hCard = HCard[11] hCard = HCard[9] hCard = HCard[12] hCard = HCard[14] hCard = HCard[15] hCard = HCard[13] hCard = HCard[16] hCard = HCard[18] hCard = HCard[17] hCard = HCard[20] hCard = HCard[19] Took: 5 seconds ```
completionservice: how to kill all threads and return result through 5 seconds?
[ "", "java", "multithreading", "concurrency", "" ]
I want to return a set of values from function till the point they exist.... for example.... ``` function abc($i="3"){ for($a=1;$a<=$i;$a++) { $name='t'.$i; $$name = "ae".$a; } //now i am returning values return array($t1,$t2,$t3,$t4,$t5,$t6,$t7,$t8,$t9,$t10); //but i only want to return $t1,$t2,$t3 depending on $i } ``` Thanks.... @therefromhere I am also creating an array in the loop , I'll paste the original code so that you can understand it in a better way ``` function extracting_comments($table, $fields,$condition,$order,$limit){ $query="SELECT ".$fields." FROM ".$table." WHERE ".$condition." ORDER BY ".$order." LIMIT ".$limit." "; if($stmt = $this->conn->prepare($query)) { $stmt->execute(); $row = array_pad(array(), $stmt->field_count, ''); $params = array(); foreach($row as $k=>$v) { $params[] = &$row[$k]; echo $params[0]; } call_user_func_array(array($stmt,'bind_result'),$params); $i=0; while($stmt->fetch()) { $i++; $name='t'.$i; $$name = array(); foreach ($row as $b=>$elem) { $atul[$b]=$row[$b]; } $$name=$atul; } return array($t1,$t2,$t3,$t4,$t5,$t6,$t7,$t8,$t9,$t10); $stmt->close(); } } ``` now their are only 5 rows of data so their is no point returning $t6,$t7,$t8,$t9,$t10 and i want to fix it ,and i am calling the function using ``` $extract=extracting_comments($table, $fields,$condition,$order,$limit); ``` please help...thanks
I believe this will help you. You have very complicated code with a lot of side effects and bug, you'd better to consider to redisgn it. Also putting statements after return will no have any effect, since it wouldn't be invoked. ``` function extracting_comments($table, $fields,$condition,$order,$limit){ $query="SELECT ".$fields." FROM ".$table." WHERE ".$condition." ORDER BY ".$order." LIMIT ".$limit." "; if($stmt = $this->conn->prepare($query)) { $stmt->execute(); $row = array_pad(array(), $stmt->field_count, ''); $params = array(); foreach($row as $k=>$v) { $params[] = &$row[$k]; echo $params[0]; } call_user_func_array(array($stmt,'bind_result'),$params); $i=0; $result = array(); while($stmt->fetch()) { $i++; foreach ($row as $b=>$elem) { $atul[$b]=$row[$b]; } $result[]=$atul; } $stmt->close(); return $result; } } ```
Just build the array in your `for` loop: ``` function abc($i=3) { $array = array(); for ($a=1; $a<=$i; $a++) { $array[] = "ae".$a; } return $array; } ``` --- After you edited your question an revealed us your actual problem, see here my proposal: ``` function extracting_comments($table, $fields, $condition, $order, $limit) { $retVal = array(); $query = "SELECT ".$fields." FROM ".$table." WHERE ".$condition." ORDER BY ".$order." LIMIT ".$limit." "; if ($stmt = $this->conn->prepare($query)) { $stmt->execute(); $row = array_pad(array(), $stmt->field_count, ''); call_user_func_array(array($stmt, 'bind_result'), $row); while ($stmt->fetch()) { $retVal[] = $row; } $stmt->close(); return $retVal; } } ```
php - function return values dynamically
[ "", "php", "function", "return", "" ]
What is the benefit of using **`SET XACT_ABORT ON`** in a stored procedure?
`SET XACT_ABORT ON` instructs SQL Server to rollback the entire transaction and abort the batch when a run-time error occurs. It covers you in cases like a command timeout occurring on the client application rather than within SQL Server itself (which isn't covered by the default `XACT_ABORT OFF` setting.) Since a query timeout will leave the transaction open, `SET XACT_ABORT ON` is recommended in all stored procedures with explicit transactions (unless you have a specific reason to do otherwise) as the consequences of an application performing work on a connection with an open transaction are disastrous. There's a really great overview on [Dan Guzman's Blog](https://www.dbdelta.com/use-caution-with-explicit-transactions-in-stored-procedures/) ([original link](http://weblogs.sqlteam.com/dang/archive/2007/10/20/Use-Caution-with-Explicit-Transactions-in-Stored-Procedures.aspx))
In my opinion SET XACT\_ABORT ON was made obsolete by the addition of BEGIN TRY/BEGIN CATCH in SQL 2k5. Before exception blocks in Transact-SQL it was really difficult to handle errors and unbalanced procedures were all too common (procedures that had a different @@TRANCOUNT at exit compared to entry). With the addition of Transact-SQL exception handling is much easier to write correct procedures that are guaranteed to properly balance the transactions. For instance I use this [template for exception handling and nested transactions](http://rusanu.com/2009/06/11/exception-handling-and-nested-transactions/): ``` create procedure [usp_my_procedure_name] as begin set nocount on; declare @trancount int; set @trancount = @@trancount; begin try if @trancount = 0 begin transaction else save transaction usp_my_procedure_name; -- Do the actual work here lbexit: if @trancount = 0 commit; end try begin catch declare @error int, @message varchar(4000), @xstate int; select @error = ERROR_NUMBER(), @message = ERROR_MESSAGE(), @xstate = XACT_STATE(); if @xstate = -1 rollback; if @xstate = 1 and @trancount = 0 rollback if @xstate = 1 and @trancount > 0 rollback transaction usp_my_procedure_name; raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ; end catch end go ``` It allows me to write atomic procedures that rollback only their own work in case of recoverable errors. One of the main issues Transact-SQL procedures face is **data purity**: sometimes the parameters received or the data in the tables are just plain wrong, resulting in duplicate key errors, referential constrain errors, check constrain errors and so on and so forth. After all, that's exactly the role of these constrains, if these data purity errors would be impossible and all caught by the business logic, the constrains would be all obsolete (dramatic exaggeration added for effect). If XACT\_ABORT is ON then all these errors result in the entire transaction being lost, as opposed to being able to code exception blocks that handle the exception gracefully. A typical example is trying to do an INSERT and reverting to an UPDATE on PK violation.
What is the benefit of using "SET XACT_ABORT ON" in a stored procedure?
[ "", "sql", "sql-server", "" ]
Hey guys, I'm writing a word wrap function to format console text in C++. My problem is either A) I don't understand exactly what std::string::iterators do, or B) one of my iterators is not being set properly. Can anyone shed some light on the reason this code fails? by the way: sorry if this goes into too much detail. I'm not sure if most programmers (I'm a "newbie") have a C++ compiler installed on their machine. ``` std::string wordWrap(std::string sentence, int width) { //this iterator is used to optimize code; could use array indice //iterates through sentence till end std::string::iterator it = sentence.begin(); //this iterator = it when you reach a space; will place a newline here //if you reach width; std::string::iterator lastSpace = sentence.begin(); int distanceToWidth = 0; while (it != sentence.end()) { while (it != sentence.end() && distanceToWidth < width) { if (*it == ' ') { lastSpace = it; } distanceToWidth++; it++; } distanceToLength = 0; *lastSpace = '\n'; //skip the space if (it != sentence.end()) { it++; } } return sentence; } ``` I'm not getting correct output. Assuming I called it like this: ``` std::cout << wordWrap("a b c abcde abcdef longword shtwd", 5) << std::endl << std::endl; std::cout << wordWrap("this is a sentence of massive proportions", 4) << std::endl; ``` I get unsatisfying output of this: ``` a b c abcde abcdef longword shtwd //yes I get his, instead of this his is a sentence of massive proportions Press any key to continue . . . ``` My problem is that I'm am getting newlines when inappropiate. I am getting newlines too often, and I don't see any obvious error as to why that is. I was hoping someone independent (I've spent a few hours on this algorithm, and to not have the right results is quite frusturating) of the problem could look at it. Also, any obvious optimization tips?
The problem is that the word this is 4 characters, and you are wrapping at four characters. So it is trying to wrap before it has set lastSpace to something reasonable. Look at it from the point of stepping through the code: ``` lastSpace points to the "t" from the beginning of "this" distanceToWidth=0 iterator=this is ^ check if we should loop (distanceToWidth<4) is the current character a space? no distanceToWidth=1 iterator=this is ^ check if we should loop (distanceToWidth<4) is the current character a space? no distanceToWidth=2 iterator=this is ^ check if we should loop (distanceToWidth<4) is the current character a space? no distanceToWidth=3; iterator=this is ^ check if we should loop (distanceToWidth<4) is the current character a space? no distanceToWidth=4; iterator=this is ^ check if we should loop (distanceToWidth<4) NO! Because distanceToWidth equals four! We break out of the loop. Recall that lastSpace was never modified it still points to the first character in the string! now we set the "t" character from "this" to be a newline!! ``` ETC Thus we output an extra newline instead of the "t" in "this" about fixing it... well... you can figure it out
The `lastSpace` iterator starts on the first character of `sentence`: ``` //this iterator = it when you reach a space; will place a newline here //if you reach width; std::string::iterator lastSpace = sentence.begin(); ``` When you reach the fifth character of "this is a..." (the space), the inner while loop exits (because `distanceToWidth == width`), before it is recognized that the current character is a space. Then a newline is inserted in position `lastSpace`, which still points to the first character of the string. This way the "t" of "this" is lost. Next `distanceToWidth` is reset to zero and another `width` characters are appended, although the line was not split at the current position, but some characters before (at `lastSpace`). So this line can end up containing more characters than expected. In the example, "is" is still on the same line as "this" while it should be wrapped to the next line. You probably need to: * change the condition of the inner while to `<=` so that the correct width is checked * not initialize `lastSpace` to the first character of the string. Probably better: ``` std::string::iterator lastSpace; ... if (lastSpace) { *lastSpace = '\n'; } ``` * count how many characters were found since the last space, and uses this to reset `distanceToWidth` after inserting a line break
wordwrap function
[ "", "c++", "algorithm", "word-wrap", "" ]
Suppose I have following code ``` package memoryleak; public class MemoryLeak { public static int size; static { size = (int) (Runtime.getRuntime().maxMemory()*0.6); } public static void main(String[] args) throws InterruptedException { { byte[] data1 = new byte[size]; } byte[] data2 = new byte[size]; } } ``` This code generates OutOfMemoryError. You can make this code work with one variable allocation (which rewrite stack frame used by first array and make array available for garbage collecting). This puzzle explained [here](http://www.javaspecialists.eu/archive/Issue173.html). ``` { byte[] data1 = new byte[size]; } int i = 0; byte[] data2 = new byte[size]; ``` The question is: why following code still doesn't work? ``` Object o = new Object(); synchronized (o) { byte[] data1 = new byte[size]; } int i = 0; byte[] data2 = new byte[size]; ``` And following works: ``` Object o = new Object(); synchronized (o) { byte[] data1 = new byte[size]; } int i = 0; synchronized (o) { byte[] data2 = new byte[size]; } ```
My bet is that `synchronized` adds an element to the frame, causing `data1` to move up a slot and not get clobbered by `i`. `synchronized` needs to unlock the same object that it locked, even if the local/field changes. The `synchronized` code would look something like this: ``` Object $sync = o; $sync.lock(); try { byte[] data1 = new byte[size]; } finally { $sync.unlock(); } ``` So taking the last sample of code: ``` Object o = new Object(); // Slot 0. synchronized (o) { // Slot 1. byte[] data1 = new byte[size]; // Slot 2. } int i = 0; // Slot 1. synchronized (o) { // Slot 2. (clobbers data1, was slot 1) byte[] data2 = new byte[size]; // Slot 3. } ```
Puzzles are interesting, but for the pragmatic programmer who does not want to think about (or more importantly depend on) the more arcane aspects of garbage collection, would setting `data1 = null` as soon as it is no longer needed solve the problem? If so, I'd rather do that then weird synchronized block and dummy variable magic. Of course, it is sad that the memory does not get freed as soon as the array goes out of scope, which is what people were hoping for in [this thread](https://stackoverflow.com/questions/850878/does-setting-java-objects-to-null-do-anything-anymore). This should be fixed in the JVM.
Java memory puzzle
[ "", "java", "memory-management", "" ]
Can anyone tell me how to get remote Sqlserver instances using c# and SMO or any api? I have a remote server name "RemoteMC", which has 2 instances of sql server: "RemoteMc" and "RemoteMC\sqlexpress" I try to get the instances in code like this: ``` Server srv=new Server("RemoteMC"); DataTable dt=SmoApplication.EnumAvailableSqlServer(true); ``` But it returns "Host\sqlexpress" I don't know what went wrong. How can I get the result back as: > RemoteMC > RemoteMC\sqlexpress; ?
The `SmoApplication.EnumAvailableSqlServers` method is what you're looking for. There are 3 overloads, and one of those takes a `string` parameter for the server name. It returns a `DataTable` whose rows have fields like `Version`, `name`, `IsLocal`, etc. You'll need to add a reference to the SMO libraries, and you'll probably want to have "`using Microsoft.SqlServer.Management.Smo;`" at the top of your C# file. See <http://www.sqldbatips.com/showarticle.asp?ID=34> for an intro to SQL SMO. **EDIT**: Some code to address this particular problem (I have not compiled or run this): **EDIT**:.Rows add to foreach so that it can compile. ``` DataTable dataTable = SmoApplication.EnumAvailableSqlServers(false); foreach (DataRow dataRow in dataTable.Rows) { if ((dataRow["Server"] as string) == "MyServerName") Console.WriteLine(dataRow["Instance"] as string); } ```
Use the builtin way. ``` System.Data.Sql.SqlDataSourceEnumerator ```
How to get the list of SqlInstances of a particular machine
[ "", "c#", "sql-server", ".net-2.0", "wmi", "smo", "" ]
We have an `SaveFileDialog` in our application, which offers a variety of formats the user can export media in. We determine the user's choice of format using the `FilterIndex` property of the `SaveFileDialog`. The various formats have different file extensions, so we would like the file name that the user has entered to change extension when the user changes the selected filter. Is this possible, and if so, how? EDIT: I want this to happen while the dialog is shown, *when the user changes the filter*, so the user gets feedback on what the filename will be, rather than afterwards when the user closes the dialog. I've tried using a message filter, but it doesn't receive messages for the dialog. I've tried `Application.Idle` but that never fires while the dialog is running. I've tried a background thread, but `FilterIndex` doesn't get updated until the user closes the dialog.
As SaveFileDialog can't be inherited, I guess you must build your own, using FileDialog as the base class.
SaveFileDialog changes extension of the file automatically when user changes filter. If you want to process some certain actions for different file formats you can youse something like this: ``` ... if (saveDialog.ShowDialog() == DialogResult.OK) { switch (saveDialog.FilterIndex) { case 0: ... break; case 1: ... break; default: ... break; } } ... ```
How can I change the extension of the file name in a SaveFileDialog when the user changes the filter?
[ "", "c#", ".net", "winforms", "savefiledialog", "" ]
HI , I made a ICAPServer (similar with httpserver) for which the performance is very important. The DB module is sqlalchemy. I then made a test about the performance of sqlalchemy, as a result, i found that it takes about 30ms for sqlalchemy to write <50kb data to DB (Oracle), i don`t know if the result is normal, or i did something wrong? BUT, no matter right or wrong, it seems the bottle-neck comes from the DB part. HOW can i improve the performance of sqlalchemy? OR it is up to DBA to improve Oracle? BTW, ICAPServer and Oracle are on the same pc , and i used the essential way of sqlalchemy..
I had some issues with sqlalchemy's performance as well - I think you should first figure out in which ways you are using it ... they recommend that for big data sets is better to use the sql expression language. Either ways try and optimize the sqlalchemy code and have the Oracle database optimized as well, so you can better figure out what's wrong. Also, do some tests on the database.
You should first *measure* where your bottleneck is, for example using the [profile](http://docs.python.org/library/profile.html) module. Then optimize, if you have the possibility to, the slowest part of the system.
python sqlalchemy performance?
[ "", "python", "sqlalchemy", "" ]
I need to convert a `HashMap<String, Object>` to an array; could anyone show me how it's done?
``` hashMap.keySet().toArray(); // returns an array of keys hashMap.values().toArray(); // returns an array of values ``` --- # Edit It should be noted that the ordering of both arrays may not be the same, See oxbow\_lakes answer for a better approach for iteration when the pair key/values are needed.
If you want the keys and values, you can always do this via the `entrySet`: ``` hashMap.entrySet().toArray(); // returns a Map.Entry<K,V>[] ``` From each entry you can (of course) get both the key *and* value via the `getKey` and `getValue` methods
Java: how to convert HashMap<String, Object> to array
[ "", "java", "arrays", "collections", "hashmap", "" ]
The following code snippet on SQL server 2005 fails on the ampersand '&': ``` select cast('<name>Spolsky & Atwood</name>' as xml) ``` Does anyone know a workaround? Longer explanation, I need to update some data in an XML column, and I'm using a search & replace type hack by casting the XML value to a varchar, doing the replace and updating the XML column with this cast.
``` select cast('<name>Spolsky &amp; Atwood</name>' as xml) ``` A literal ampersand inside an `XML` tag is not allowed by the `XML` standard, and such a document will fail to parse by any `XML` parser. An `XMLSerializer()` will output the ampersand `HTML`-encoded. The following code: ``` using System.Xml.Serialization; namespace xml { public class MyData { public string name = "Spolsky & Atwood"; } class Program { static void Main(string[] args) { new XmlSerializer(typeof(MyData)).Serialize(System.Console.Out, new MyData()); } } } ``` will output the following: ``` <?xml version="1.0" encoding="utf-8"?> <MyData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <name>Spolsky &amp; Atwood</name> </MyData> ``` , with an `&amp;` instead of `&`.
It's not valid XML. Use `&amp;`: ``` select cast('<name>Spolsky &amp; Atwood</name>' as xml) ```
Use ampersand in CAST in SQL
[ "", "sql", "sql-server", "xml", "casting", "ampersand", "" ]
I've a database table of timesheets with some common feilds. ``` id, client_id, project_id, task_id, description, time, date ``` There are more but thats the gist of it. I have an export running on that table to a CSV file overnight to give the user a backup of their data. It also is used as a data import for a macro Excel file with some custom reports. This all works with me looping through the timesheets with php and printing the lines to a file. The problem is with a big database it can take hours to run which isn't acceptable. So I rewrote it with the MySQL `INTO OUTFILE` command and it reduced it down to a few seconds to run which was great. The problem now is I can't seem to escape all the new line characters, etc., in the description field. Really, a user can type potentially any combination of characters in here including carriage returns/new lines. This is a snippet of the MySQL code I have: ``` SELECT id, client, project, task, REPLACE(REPLACE(ifnull(ts.description,''),'\n',' '),'\r',' ') AS description, time, date INTO OUTFILE '/path/to/file.csv' FIELDS ESCAPED BY '""' TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' FROM .... ``` But... When I try look at the source of the output file, newlines still exist in the file, therefore the CSV import for the Excel breaks all the fancy macros and pivot tables the Excel wizard has created. Any thoughts on a best course of action?
I think your statement should look like: ``` SELECT id, client, project, task, description, time, date INTO OUTFILE '/path/to/file.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n' FROM ts ``` Mainly without the `FIELDS ESCAPED BY '""'` option, `OPTIONALLY ENCLOSED BY '"'` will do the trick for description fields etc and your numbers will be treated as numbers in Excel (not strings comprising of numerics) Also try calling: ``` SET NAMES utf8; ``` before your outfile select, that might help getting the character encodings inline (all UTF8) Let us know how you get on.
Here is what worked here: Simulates Excel 2003 (Save as CSV format) ``` SELECT REPLACE( IFNULL(notes, ''), '\r\n' , '\n' ) AS notes FROM sometables INTO OUTFILE '/tmp/test.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '"' ESCAPED BY '"' LINES TERMINATED BY '\r\n'; ``` 1. Excel saves \r\n for line separators. 2. Excel saves \n for newline characters within column data 3. Have to replace \r\n inside your data first otherwise Excel will think its a start of the next line.
MySQL export into outfile : CSV escaping chars
[ "", "mysql", "sql", "excel", "into-outfile", "" ]
I'm thinking about using [SCons](http://www.scons.org/) for a new project. It looks really good, though I'm finding `VariantDir` quite confusing. I have a simple project with a handful of C source files in one directory, and I want to build in "normal" and in "profile" mode -- with two different sets of options to gcc. I want the outputs to go in the normal/ and profile/ directories, respectively. For testing, I've cut back to just a single source file, t.c, which has a `main()` in it. My `SConstruct` file is in the same directory, and looks like this: ``` normal = DefaultEnvironment(tools=['mingw'], CCFLAGS = '-O2') normal.VariantDir('release', '.', duplicate=0) normal.Program('t', ['t.c']) #profile = normal.Clone(CCFLAGS='-O2 -pg', LINKFLAGS = '-pg') #profile.VariantDir('profile', '.', duplicate=0) #profile.Program('t', ['t.c']) ``` When I run scons, I'm expecting it to put t.o and t.exe into release/, but it puts them in the current directory. And I can't run it at all with the 3 profile lines uncommented -- if I do, I get this error: **scons: \*\*\* Two environments with different actions were specified for the same target: t.o** Basically, I'm unsure why my VariantDir() calls aren't telling scons to put the output in the specified output directory, `release`. (I've read a fair bit in the docs and newsgroups, but nothing that answers this question. The closest I've come is [this page](http://scons.org/wiki/SimultaneousVariantBuilds), which describes a similar thing, but it involves a separate src/ directory and two separate scons files, and importing/exporting variables between them. That doesn't seem pleasant.)
Yes, VariantDir is confusing in scons. Although not well advertised, you can put both SConstruct and SConscript in the same directory, using the current directory as the source directory ``` # SConstruct SConscript('SConscript', build_dir='build', src='.') ``` and ``` # SConscript Program('main.c') ``` I have never found a way to avoid using two files while keeping my sanity trying to understand variant dir :)
I was able to separate binaries in a build directory using this call: ``` # SConstruct SConscript('SConscript', variant_dir='build', src_dir='..', duplicate=0) ``` If you want to put binaries into a directory two levels below, do this: ``` # SConstruct SConscript('SConscript', variant_dir='build/release', src_dir='../..', duplicate=0) ``` Basically, provide the `src_dir` parameter as a path from your build directory back to your source directory.
Why does SCons VariantDir() not put output in the given directory?
[ "", "python", "c", "makefile", "scons", "" ]
I want to format a XML document during unmarshal with JAXB. Unmarshal looks like: ``` Unmarshaller u = createAndsetUpUnmarshaller(enableValidation, evtHandler, clazz); return u.unmarshal(new ByteArrayInputStream(stringSource.getBytes())); ``` While marshaling one can format the code via: ``` marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); ``` But this isn´t possible for the unmarchal process... Any idea how I can format the XML string with JAXB during (or after) unmarshal process? BTW: I read some posts here about pretty print, but I want to do it with JAXB!
it is logically senseless to format the xml code while unmarshalling it?
If you want to log formatted XML corresponding to the XML that you just unmarshalled, you can simply remarshal the unmarshalled object back to XML, using the property you specified, ie. ``` /** * Marshall input object to a formatted XML String */ protected <T> String marshal(T input) throws JAXBException { StringWriter writer = new StringWriter(); JAXBContext jc = JAXBContext.newInstance(input.getClass()); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.marshal(input, writer); return writer.toString(); } ``` On the other hand, if all you want to do is reformat the XML, you probably should be using JAXP instead of JAXB.
Format XML with JAXB during unmarshal
[ "", "java", "xml", "jaxb", "pretty-print", "" ]
If I call a destructor explicitly ( myObject.~Object() ) does this assure me that the object will be appropriately destroyed (calling all child destructors) ? Ok some code: ``` class Object { virtual ~Object() {} }; class Widget : public Object { virtual ~Widget() {} }; ... Object* aWidget = new Widget(); //allocate and construct aWidget->~Object(); //destroy and DON'T deallocate ``` I know I could just delete the object, but I don't want to. I want to keep the allocated memory handy as an important optimization. Thanks!
The answer is... nearly always. If your object has a non-virtual destructor, and is then sub-classed to add child elements that need freeing... then calling the destructor on the object base class will not free the child elements. This is why you should always declare destructors virtual. We had an interesting case where two shared libraries referenced an object. We changed the definition to add child objects which needed freeing. We recompiled the first shared library which contained the object definition. HOWEVER, the second shared library was not recompiled. This means that it did not know of the newly added virtual object definition. Delete's invoked from the second shared library simply called free, and did not invoke the virtual destructor chain. Result was a nasty memory leak.
Yes. But holy smokes, are you sure about this? If so I would use [placement `new`](https://stackoverflow.com/questions/222557/cs-placement-new) to construct your `Widget`. Using placement `new` and then explicitly calling the destructor is an acceptable, if unusual, idiom. **Edit**: Consider allocating the memory yourself manually rather than using `new` to allocate the first object and then re-using its memory afterward. That allows you complete control over the memory; you could allocate big chunks at a time, for instance, rather than allocating a separate block of memory for each `Widget`. That'd be fair savings if memory really is such a scarce resource. Also, and perhaps more importantly, you'd then be doing placement `new` "normally", rather than this hybrid regular `new`/placement `new` solution. I'm not saying it won't work, I'm just saying it's a rather, ah, *creative* solution to your memory problem.
Does calling a destructor explicitly destroy an object completely?
[ "", "c++", "destructor", "" ]
Just a quick question about how parameters are passed in Java... ``` ... if ((index = stdout.indexOf(pattern)) != -1) { tidy(stdout, index + pattern.length()); return true; } else if ((index = stderr.indexOf(pattern)) != -1) { tidy(stderr, index + pattern.length()); return true; ... private void tidy(StringBuffer buffer, int i) { logger.info("Truncating buffer: " + buffer); buffer = new StringBuffer(buffer.substring(i)); logger.info("Buffer now: " + buffer); } ``` In this case, will stdout and stderr (used as parameters in tidy()) have their values changed to new StringBuffer(buffer.substring(i))? My assumption is that they will as object variables(object pointers) are always passed-by-value?
You misstate what is going on here -- the object references are passed by value (a copy of the reference is made), so stdout and stderr do *not* get modified when you call tidy. The *copies* that are made of them get modified when you execute line 2 of `tidy`. Parameter passing in Java is a source of confusion for a lot of people. Here's [a good explanation](http://javadude.com/articles/passbyvalue.htm).
From James Gosling in "The Java Programming Language": > "...There is exactly one parameter passing mode in Java - pass by value - and that keeps things simple. .." I think that's the final authority on this.
Are Java function parameters always passed-by-value?
[ "", "java", "parameters", "" ]
i have table structure with 3 colums (column1, column2, column3) and i want to put another column with sql statement like: ``` alter table tbl_name add column4 ``` but i need to put it between column1 and column2 may i do something like in MYSQL: ``` alter table tbl_name add column4 after column1 ```
I don't think SQL Server allows you to do anything like that. If you want to put a column in the middle, you'll need to create a new table with the desired layout, migrate the data, delete the old table, and rename the new table.
@bdukes is correct. This is essentially what SSMS does when you add a column in any place other than the last position of the table. You could, however, achieve something similar using views. That is, simply add your column to the end of the table, then create a view which has the columns in a different order. Use the view instead of the actual table. I only offer this as one alternative that can be useful in certain situations. I'm not necessarily recommending it for your situation. Generally, I use the designer in SSMS and haven't had any problems with it updating tables when inserting a column. Backups, of course, are your friend!
Add column2 before column1
[ "", "sql", "sql-server-2005", "" ]
I was just wondering how prepared queries work. I am using PHP and MySQL. I know that prepared queries compile the query and then repeated uses only have to change the parameters, so it saves time. But how long does that compiled query have an effect? At which point does it have to be reevaluated? Is it just as long as the PHP script is running? Or is it as long as the connection to the database is present? In that case, would a persistent connection have any effect on it?
ryeguy, they last for the length of the connection. Per the MySQL manual: > A prepared statement is specific to the session in which it was created. If you terminate a session without deallocating a previously prepared statement, the server deallocates it automatically. If you are not using persistent connections, then this will be deallocated when your script finishes executing (or you explicitly deallocate it, or close the connection). If using persistent connections, then it will persist across multiple PHP sessions using the same persistent connection.
As far as I know, a prepared query will only "last" for as long as the variable storing it is within scope. I suppose there could be some ways to cache prepared queries for later use, but I don't know if MySQL does this.
How long do prepared queries "last" for on the server side?
[ "", "php", "mysql", "odbc", "" ]
Does anyone know of a good library (or code snippet) for converting a TimeSpan object to a "friendly" string such as: * Two years, three months and four days * One week and two days (It's for a document expiry system, where the expiry could be anything from a few days to several decades) Just to clarify, say I had a TimeSpan with 7 days, that should print "1 week", 14 days "2 weeks", 366 days "1 year and 1 day", etc etc.
Not a fully featured implementation, but it should get you close enough. ``` DateTime dtNow = DateTime.Now; DateTime dtYesterday = DateTime.Now.AddDays(-435.0); TimeSpan ts = dtNow.Subtract(dtYesterday); int years = ts.Days / 365; //no leap year accounting int months = (ts.Days % 365) / 30; //naive guess at month size int weeks = ((ts.Days % 365) % 30) / 7; int days = (((ts.Days % 365) % 30) % 7); StringBuilder sb = new StringBuilder(); if(years > 0) { sb.Append(years.ToString() + " years, "); } if(months > 0) { sb.Append(months.ToString() + " months, "); } if(weeks > 0) { sb.Append(weeks.ToString() + " weeks, "); } if(days > 0) { sb.Append(days.ToString() + " days."); } string FormattedTimeSpan = sb.ToString(); ``` In the end, do you really need to let someone know a document is going to expire exactly 1 year, 5 months, 2 weeks, and 3 days from now? Can't you get by with telling them the document will expire over 1 year from now, or over 5 months from now? Just take the largest unit and say over n of that unit.
I just stumbled upon this question because I wanted to do a similar thing. After some googling I still didn't find what I wanted: display a timespan in a sort of "rounded" fashion. I mean: when some event took several days, it doesn't always make sense to display the milliseconds. However, when it took minutes, it probably does. And in that case, I don't want 0 days and 0 hours to be displayed. So, I want to parametrize the number of relevant timespan parts to be displayed. This resulted in this bit of code: ``` public static class TimeSpanExtensions { private enum TimeSpanElement { Millisecond, Second, Minute, Hour, Day } public static string ToFriendlyDisplay(this TimeSpan timeSpan, int maxNrOfElements) { maxNrOfElements = Math.Max(Math.Min(maxNrOfElements, 5), 1); var parts = new[] { Tuple.Create(TimeSpanElement.Day, timeSpan.Days), Tuple.Create(TimeSpanElement.Hour, timeSpan.Hours), Tuple.Create(TimeSpanElement.Minute, timeSpan.Minutes), Tuple.Create(TimeSpanElement.Second, timeSpan.Seconds), Tuple.Create(TimeSpanElement.Millisecond, timeSpan.Milliseconds) } .SkipWhile(i => i.Item2 <= 0) .Take(maxNrOfElements); return string.Join(", ", parts.Select(p => string.Format("{0} {1}{2}", p.Item2, p.Item1, p.Item2 > 1 ? "s" : string.Empty))); } } ``` Example (LinqPad): ``` new TimeSpan(1,2,3,4,5).ToFriendlyDisplay(3).Dump(); new TimeSpan(0,5,3,4,5).ToFriendlyDisplay(3).Dump(); ``` Displays: ``` 1 Day, 2 Hours, 3 Minutes 5 Hours, 3 Minutes, 4 Seconds ``` Suits me, see if it suits you.
TimeSpan to friendly string library (C#)
[ "", "timespan", "c#", "" ]
I have a vector of booleans. I need to set its elements from n-th to m-th to `true`. Is there an elegant way to do this without using a loop? Edit: Tanks to all those who pointed out the problems with using `vector<bool>`. However, I was looking for a more general solution, like the one given by jalf.
`std::fill` or `std::fill_n` in the `algorithm` header should do the trick. ``` // set m elements, starting from myvec.begin() + n to true std::fill_n(myvec.begin() + n, m, true); // set all elements between myvec.begin() + n and myvec.begin() + n + m to true std::fill(myvec.begin() + n, myvec.begin() + n + m, true); ```
Vector of bool. Sends shivers down my spine. Have you looked at: std::bitset (for fixed size flag sets) boost::dynamic\_bitset (for dynamic size flag sets) Set the bottom 8 bits in a row: ``` #include <bitset> #include <iostream> int main() { std::bitset<12> flags; flags |= 0x0FF; std::cout << flags; } ```
How to set a range of elements in an stl vector to a particular value?
[ "", "c++", "stl", "vector", "variable-assignment", "" ]
I have two user Objects and while I try to save the object using ``` session.save(userObj); ``` I am getting the following error: ``` Caused by: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.pojo.rtrequests.User#com.pojo.rtrequests.User@d079b40b] ``` I am creating the session using ``` BaseHibernateDAO dao = new BaseHibernateDAO(); rtsession = dao.getSession(userData.getRegion(), BaseHibernateDAO.RTREQUESTS_DATABASE_NAME); rttrans = rtsession.beginTransaction(); rttrans.begin(); rtsession.save(userObj1); rtsession.save(userObj2); rtsession.flush(); rttrans.commit(); rtsession.close(); // in finally block ``` I also tried doing the `session.clear()` before saving, still no luck. This is for the first I am getting the session object when a user request comes, so I am getting why is saying that object is present in session. Any suggestions?
I have had this error many times and it can be quite hard to track down... Basically, what hibernate is saying is that you have two objects which have the same identifier (same primary key) but they are not the same object. I would suggest you break down your code, i.e. comment out bits until the error goes away and then put the code back until it comes back and you should find the error. It most often happens via cascading saves where there is a cascade save between object A and B, but object B has already been associated with the session but is not on the same instance of B as the one on A. What primary key generator are you using? The reason I ask is this error is related to how you're telling hibernate to ascertain the persistent state of an object (i.e. whether an object is persistent or not). The error could be happening because hibernate is trying to persist an object that is already persistent. In fact, if you use save hibernate will try and persist that object, and maybe there is already an object with that same primary key associated with the session. **Example** Assuming you have a hibernate class object for a table with 10 rows based on a primary key combination (column 1 and column 2). Now, you have removed 5 rows from the table at some point of time. Now, if you try to add the same 10 rows again, while hibernate tries to persist the objects in database, 5 rows which were already removed will be added without errors. Now the remaining 5 rows which are already existing, will throw this exception. So the easy approach would be checking if you have updated/removed any value in a table which is part of something and later are you trying to insert the same objects again
This is only one point where hibernate makes more problems than it solves. In my case there are many objects with the same identifier 0, because they are new and don't have one. The db generates them. Somewhere I have read that 0 signals Id not set. The intuitive way to persist them is iterating over them and saying hibernate to save the objects. But You can't do that - "Of course You should know that hibernate works this and that way, therefore You have to.." So now I can try to change Ids to Long instead of long and look if it then works. In the end it's easier to do it with a simple mapper by your own, because hibernate is just an additional intransparent burden. Another example: Trying to read parameters from one database and persist them in another forces you to do nearly all work manually. But if you have to do it anyway, using hibernate is just additional work.
Hibernate Error: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session
[ "", "java", "hibernate", "orm", "" ]
I realize this is a broad topic, but I'm looking for a good primer on parsing meaning from text, ideally in Python. As an example of what I'm looking to do, if a user makes a blog post like: "Manny Ramirez makes his return for the Dodgers today against the Houston Astros", what's a light-weight/ easy way of getting the nouns out of a sentence? To start, I think I'd limit it to proper nouns, but I wouldn't want to be limited to just that (and I don't want to rely on a simple regex that assumes anything Title Capped is a proper noun). To make this question even worse, what are the things I'm not asking that I should be? Do I need a corpus of existing words to get started? What lexical analysis stuff do I need to know to make this work? I did come across [one other question](https://stackoverflow.com/questions/220187/algorithms-or-libraries-for-textual-analysis-specifically-dominant-words-phras) on the topic and I'm digging through those resources now.
Use the [NLTK](http://www.nltk.org/), in particular [chapter 7 on Information Extraction.](http://www.nltk.org/book/ch07.html) You say you want to extract meaning, and there are modules for semantic analysis, but I think IE is all you need--and honestly one of the only areas of NLP computers can handle right now. See sections 7.5 and 7.6 on the subtopics of Named Entity Recognition (to chunk and categorize Manny Ramerez as a person, Dodgers as a sports organization, and Houston Astros as another sports organization, or whatever suits your domain) and Relationship Extraction. There is a NER chunker that you can plugin once you have the NLTK installed. From their examples, extracting a geo-political entity (GPE) and a person: ``` >>> sent = nltk.corpus.treebank.tagged_sents()[22] >>> print nltk.ne_chunk(sent) (S The/DT (GPE U.S./NNP) is/VBZ one/CD ... according/VBG to/TO (PERSON Brooke/NNP T./NNP Mossman/NNP) ...) ``` Note you'll still need to know tokenization and tagging, as discussed in earlier chapters, to get your text in the right format for these IE tasks.
You need to look at the [Natural Language Toolkit](http://www.nltk.org/), which is for exactly this sort of thing. This section of the manual looks very relevant: [Categorizing and Tagging Words](http://nltk.googlecode.com/svn/trunk/doc/book/ch05.html) - here's an extract: ``` >>> text = nltk.word_tokenize("And now for something completely different") >>> nltk.pos_tag(text) [('And', 'CC'), ('now', 'RB'), ('for', 'IN'), ('something', 'NN'), ('completely', 'RB'), ('different', 'JJ')] ``` *Here we see that **and** is CC, a coordinating conjunction; **now** and **completely** are RB, or adverbs; **for** is IN, a preposition; **something** is NN, a noun; and **different** is JJ, an adjective.*
Parsing Meaning from Text
[ "", "python", "parsing", "nlp", "lexical-analysis", "" ]
I've got an Ant task (using the maven task) set up to automatically download all my Java apps dependencies and consolidate them into a lib directory, but I cant see a way to tell IntelliJ to basically treat everything in that dir as an external lib - I have to manually add them all to my project. This rather defeats the object of automatically downloading my external dependencies... SO is there any way to say to Intellij 'this dir contains my external dependencies, so automatically parse these (for Autocomplete etc), and add them to the classpath when I launch my app from the IDE'?
In version 8 you can create a library (from the File->Project Structure) and there is a button called attach jar directories that does exactly what you are looking for. I'm pretty sure it was there in 7 as well (everything was under File Settings), but it may not be there in 6.
IntelliJ 8 has Maven integration (<http://www.jetbrains.com/idea/features/ant_maven.html#Maven_Integration>). For older versions you'll have to look for a plug-in. I know they are out there but not sure of their exact functionality. I've had a similar problem in the past where dependencies where specified using Ivy. I solved that by writing an Ant task given the dependencies (obtained from the Ivy Ant tasks) updated the appropriate iml file.
Using a 'lib' directory with intellj IDEA (v6)
[ "", "java", "intellij-idea", "" ]
How i can install the CDT plug-in (that you can develop in C++ under Eclipse) in my Eclipse Ganymede, remember that I use Windows Vista. Thanks!
Use this official guide: <http://wiki.eclipse.org/Getting_started_with_CDT_development>
<http://wiki.eclipse.org/CDT/User/FAQ#Are_there_complete_HowTos_for_setting_up_the_CDT.3F>
Install CDT Plug-In On Eclipse Ganymede
[ "", "c++", "eclipse", "plugins", "eclipse-cdt", "" ]
I have a method that takes an array of queries, and I need to run them against different search engine Web API's, such as Google's or Yahoo's. In order to parallelize the process, a thread is spawned for each query, which are then [`join`](http://download.oracle.com/javase/6/docs/api/java/lang/Thread.html#join%28%29)ed at the end, since my application can only continue *after* I have the results of *every* query. I currently have something along these lines: ``` public abstract class class Query extends Thread { private String query; public abstract Result[] querySearchEngine(); @Override public void run() { Result[] results = querySearchEngine(query); Querier.addResults(results); } } public class GoogleQuery extends Query { public Result querySearchEngine(String query) { // access google rest API } } public class Querier { /* Every class that implements Query fills this array */ private static ArrayList<Result> aggregatedResults; public static void addResults(Result[]) { // add to aggregatedResults } public static Result[] queryAll(Query[] queries) { /* for each thread, start it, to aggregate results */ for (Query query : queries) { query.start(); } for (Query query : queries) { query.join(); } return aggregatedResults; } } ``` Recently, I have found that there's a *new* API in Java for doing concurrent jobs. Namely, the `Callable` interface, `FutureTask` and `ExecutorService`. I was wondering if this new API is the one that should be used, and if they are more efficient than the traditional ones, `Runnable` and `Thread`. After studying this new API, I came up with the following code (simplified version): ``` public abstract class Query implements Callable<Result[]> { private final String query; // gets set in the constructor public abstract Result[] querySearchEngine(); @Override public Result[] call() { return querySearchEngine(query); } } public class Querier { private ArrayList<Result> aggregatedResults; public Result[] queryAll(Query[] queries) { List<Future<Result[]>> futures = new ArrayList<Future<Result[]>>(queries.length); final ExecutorService service = Executors.newFixedThreadPool(queries.length); for (Query query : queries) { futures.add(service.submit(query)); } for (Future<Result[]> future : futures) { aggregatedResults.add(future.get()); // get() is somewhat similar to join? } return aggregatedResults; } } ``` I'm new to this concurrency API, and I'd like to know if there's something that can be **improved** in the above code, and if it's better than the first option (using `Thread`). There are some classes which I didn't explore, such as `FutureTask`, et cetera. I'd love to hear any advice on that as well.
Several problems with your code. 1. You should probably be using the ExecutorService.invokeAll() method. The cost of creating new threads and a new thread pool can be significant (though maybe not compared to calling external search engines). invokeAll() can manage the threads for you. 2. You probably don't want to mix arrays and generics. 3. You are calling aggregatedResults.add() instead of addAll(). 4. You don't need to use member variables when they could be local to the queryAll() function call. So, something like the following should work: ``` public abstract class Query implements Callable<List<Result>> { private final String query; // gets set in the constructor public abstract List<Result> querySearchEngine(); @Override public List<Result> call() { return querySearchEngine(query); } } public class Querier { private static final ExecutorService executor = Executors.newCachedThreadPool(); public List<Result> queryAll(List<Query> queries) { List<Future<List<Result>>> futures = executor.submitAll(queries); List<Result> aggregatedResults = new ArrayList<Result>(); for (Future<List<Result>> future : futures) { aggregatedResults.addAll(future.get()); // get() is somewhat similar to join? } return aggregatedResults; } } ```
As a futher improvement, you could look into using a [**CompletionService**](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorCompletionService.html) It decouples the order of submitting and retrieving, instead placing all the future results on a queue from which you take results in the order they are completed..
Multithreaded search operation
[ "", "java", "multithreading", "concurrency", "search-engine", "future", "" ]
As the Title says, I've got a multi-project solution. I've got a "core" project that is loaded with most of the other projects. So my question is this, I have a few utility functions such as FormatPhoneNumber(..) that I would like to be able to access in the following manner from anywhere. (in Project\_B which depends on Core) ``` string str = FormatPhoneNumber(inputString); ``` At worst, I suppose I could live with a qualifier of some sort: ``` string str = util.FormatPhoneNumber(inputString); ```
The best way of doing this is to create a dll project (maybe called something like "CommonCode"?), that you can then reference this dll from all of your other projects and access the classes and methods therein. You will have to have some sort of "qualifier" (as you call it) somewhere, but to reduce the impact use the using statement at the top of each file, e.g. ``` using util; ```
Use an extension method to make it easier to call the method without using the class name. ``` public static class Util { public static string FormatPhoneNumber(this string input) { : } } ``` The method will now appear on every string object. You do not need to know which class it comes from. However, if the extension class is declared in another namespace, you must still import the namespace. ``` string formattedString = inputString.FormatPhoneNumber(); ```
ASP.NET + C# Multi-Project Solution. Where should I put my global utility functions?
[ "", "c#", ".net", "asp.net", "variables", "scope", "" ]
I was creating a http module and while debugging I noticed something which at first (at least) seemed like weird behaviour. When I set a breakpoint in the init method of the httpmodule I can see that the *http module init method* is being called several times even though I have only started up the website for debugging and made one single request (sometimes it is hit only 1 time, other times as many as 10 times). I know that I should expect several instances of the *HttpApplication* to be running and for each the http modules will be created, but when I request a single page it should be handled by a single http application object and therefore only fire the events associated once, but still it fires the events several times for each request which makes no sense - other than it must have been added several times within that *httpApplication* - which means it is the same *httpmodule init method* which is being called every time and not a new http application being created each time it hits my break point (see my code example at the bottom etc.). What could be going wrong here? Is it because I am debugging and set a breakpoint in the http module? It have noticed that it seems that if I startup the website for debugging and quickly step over the breakpoint in the httpmodule it will only hit the *init method* once and the same goes for the *eventhandler*. If I instead let it hang at the breakpoint for a few seconds the *init method* is being called several times (seems like it depends on how long time I wait before stepping over the breakpoint). Maybe this could be some build in feature to make sure that the httpmodule is initialized and the http application can serve requests , but it also seems like something that could have catastrophic consequences. This could seem logical, as it might be trying to finish the request and since I have set the break point it thinks something have gone wrong and try to call the init method again? Soo it can handle the request? But is this what is happening and is everything fine (I am just guessing), or is it a real problem? What I am specially concerned about is that if something makes it hang on the "production/live" server for a few seconds a lot of event handlers are added through the *init* and therefore each request to the page suddenly fires the *eventhandler* several times. This behaviour could quickly bring any site down. I have looked at the "original" .net code used for the httpmodules for *formsauthentication* and the *rolemanagermodule*, etc... But my code isn't any different that those modules uses. My code looks like this. ``` public void Init(HttpApplication app) { if (CommunityAuthenticationIntegration.IsEnabled) { FormsAuthenticationModule formsAuthModule = (FormsAuthenticationModule) app.Modules["FormsAuthentication"]; formsAuthModule.Authenticate += new FormsAuthenticationEventHandler(this.OnAuthenticate); } } ``` Here is an example how it is done in the *RoleManagerModule* from the .NET framework: ``` public void Init(HttpApplication app) { if (Roles.Enabled) { app.PostAuthenticateRequest += new EventHandler(this.OnEnter); app.EndRequest += new EventHandler(this.OnLeave); } } ``` Does anyone know what is going on? (I just hope someone out there can tell me why this is happening and assure me that everything is perfectly fine) :) --- **UPDATE:** I have tried to narrow down the problem and so far I have found that the *init* method being called is always on a new object of my http module (contrary to what I thought before). I seems that for the first request (when starting up the site) all of the *HttpApplication* objects being created and their modules are all trying to serve the first request and therefore all hit the *eventhandler* that is being added. I can't really figure out why this is happening. If I request another page all the *HttpApplication*'s created (and their modules) will again try to serve the request causing it to hit the *eventhandler* multiple times. But it also seems that if I then jump back to the first page (or another one) only one *HttpApplication* will start to take care of the request and everything is as expected - as long as I don't let it hang at a break point. If I let it hang at a breakpoint it begins to create new *HttpApplication*'s objects and starts adding *HttpApplications* (more than 1) to serve/handle the request (which is already in process of being served by the *HttpApplication* which is currently stopped at the breakpoint). I guess or hope that it might be some intelligent "behind the scenes" way of helping to distribute and handle load and / or errors. But I have no clue. I hope some out there can assure me that it is perfectly fine and how it is supposed to be?
1. Inspect the HttpContext.Current.Request to see, for what request the module's init is fired. Could be browser sending multiple request. 2. If you are connected to IIS, do check IIS logs to know whether any request is received for the time you are staying at the break point.
It's normal for the `Init()` method to be called multiple times. When an application starts up, the ASP.NET Worker process will instantiate as many `HttpApplication` objects as it thinks it needs, then it'll pool them (e.g. reuse them for new requests, similar to database connection pooling). Now for each `HttpApplication` object, it will also instantiate one copy of each `IHttpModule` that is registered and call the Init method that many times. So if 5 `HttpApplication` objects are created, 5 copies of your `IHttpModule` will be created, and your Init method called 5 times. Make sense? Now why is it instantiating 5 `HttpApplication` objects say? Well maybe your ASPX page has links to other resources which your browser will try to download, css, javascript, WebResource.aspx, maybe an iframe somewhere. Or maybe the ASP.NET Worker Process 'is in the mood' for starting more than 1 `HttpApplication` object, that's really an internal detail/optimisation of the ASP.NET process running under IIS (or the VS built in webserver). If you want code that's guaranteed to run just once (and don't want to use the Application\_StartUp event in the Global.asax), you could try the following in your IHttpModule: ``` private static bool HasAppStarted = false; private readonly static object _syncObject = new object(); public void Init(HttpApplication context) { if (!HasAppStarted) { lock (_syncObject) { if (!HasAppStarted) { // Run application StartUp code here HasAppStarted = true; } } } } ``` I've done something similar and it seems to work, though I'd welcome critiques of my work in case I've missed something.
HttpModule Init method is called several times - why?
[ "", "c#", ".net", "httpmodule", "init", "" ]
Consider the following code: ``` public class MyClass { public static string MyStaticMethod() { //string className = GetClassNameHere... } } ``` Is it possible to get the name of the class in which the static method resides ? Due to the fact that im using a static method, it is not possible to use the this pointer to retrieve the type of the object that im currently working in.
Try the following ``` return typeof(MyClass).Name; ``` Or also ``` return MethodBase.GetCurrentMethod().DeclaringType.Name; ```
You can do this... ``` String className = typeof(MyClass).Name; ```
Return class name in which a static method resides
[ "", "c#", "static-methods", "" ]
I want to recursively search and replace elements in an array. The array is tree based so looks like ``` Object Children Object type A Object type B Object Children Object type A Object ``` etc. I want to be able to replace certain items with other items, so for example, I want to replace all entries in the array (at whatever depth level) of type A with an array of type B. But here's the catch: The newly replaced objects may also have children of type A that need to be replaced. So far I've got ``` foreach ($nodes as &$node) { // Replace node? if ($node['type'] == 'RefObject') { $n = $this->site->get_node_where('id', $node['node_ref']); // Replace node $node = $this->site->get_node_where('object_id', $n['object_id']); // Get children $node['children'] = $this->site->get_descendants($node['lft'], $node['rgt']); } } return $nodes; ``` Which will replace the first level of RefObjects, but will not search the subsequently added children.
Put your code into a function and call it again. Pseudocode: ``` function checkArray($array) { ... if (is_array($node)) { // or whatever other criterium checkArray($node); // same function } } ``` The basics of recursion are to call the same code again...
you need to add this code into a function and call the function on the child nodes. something like this (note the parseNodes function is called again inside the function): ``` function parseNodes($node) { foreach($nodes as &$node) { // Replace node? if($node['type'] == 'RefObject') { $n = $this->site->get_node_where('id', $node['node_ref']); // Replace node $node = $this->site->get_node_where('object_id', $n['object_id']); // Get children $node['children'] = parseNodes($this->site->get_descendants($node['lft'], $node['rgt'])); } } return $nodes; } ``` Josh
Recursively search objects
[ "", "php", "object", "recursion", "" ]
I was trying to create a python wrapper for an tk extension, so I looked at Tkinter.py to learn how to do it. While looking at that file, I found the following pattern appears a lot of times: an internal method (hinted by the leading "\_" in the method name) is defined, then a public method is defined just to be the internal method. I want to know what's the benefit of doing this. For example, in the code for class Misc: ``` def _register(self, func, subst=None, needcleanup=1): # doc string and implementations is removed since it's not relevant register = _register ``` Thank you.
Sometimes, you may want to change a method's behavior. For example, I could do this (hypothetically within the Misc class): ``` def _another_register(self, func, subst=None, needcleanup=1): ... def change_register(self): self.register = self._another_register def restore_register(self): self.register = self._register ``` This can be a pretty handy way to alter the behavior of certain pieces of code without subclassing (but it's generally not advisable to do this kind of thing except within the class itself).
[From PEP8](http://www.python.org/dev/peps/pep-0008/) In addition, the following special forms using leading or trailing underscores are recognized (these can generally be combined with any case convention): > \_single\_leading\_underscore: weak > "internal use" indicator. E.g. "from > M import \*" does not import objects > whose name starts with an underscore.
What's the point of this code pattern?
[ "", "python", "" ]
I've want to implement a scroll/pan-feature on a QGraphicsView in my (Py)Qt application. It's supposed to work like this: The user presses the middle mouse button, and the view scrolls as the user moves the mouse (this is quite a common feature). I tried using the scroll() method inherited from QWidget. However, this somehow moves the view instead - scrollbars and all. See picture. So, given that this is not the way I'm supposed to do this, how should I? Or is it the correct way, but I do something else wrong? The code I use: ``` def __init__(self): ... self.ui.imageArea.mousePressEvent=self.evImagePress self.ui.imageArea.mouseMoveEvent=self.evMouseMove self.scrollOnMove=False self.scrollOrigin=[] ... def evImagePress(self, event): if event.button() == Qt.LeftButton: self.evImageLeftClick(event) if event.button() == Qt.MidButton: self.scrollOnMove=not self.scrollOnMove if self.scrollOnMove: self.scrollOrigin=[event.x(), event.y()] ... def evMouseMove(self, event): if self.scrollOnMove: self.ui.imageArea.scroll(event.x()-self.scrollOrigin[0], event.y()-self.scrollOrigin[1]) ``` It works as I expect, except for the whole move-the-widget business. [Fails to scroll http://img55.imageshack.us/img55/3222/scrollfail.jpg](http://img55.imageshack.us/img55/3222/scrollfail.jpg)
I haven't done this myself but this is from the [`QGraphicsView`](http://doc.trolltech.com/4.5/qgraphicsview.html) documentation > ... When the scene is larger > than the scroll bars' values, you can > choose to use translate() to navigate > the scene instead. By using `scroll` you are moving the widget, [`translate`](http://doc.trolltech.com/4.5/qgraphicsview.html#translate) should achieve what you are looking for, moving the contents of the `QGraphicsScene` underneath the view
My addition to translate() method. It works great unless you scale the scene. If you do this, you'll notice, that the image is not in sync with your mouse movements. That's when mapToScene() comes to help. You should map your points from mouse events to scene coordinates. Then the mapped difference goes to translate(), voila viola- your scene follows your mouse with a great precision. For example: ``` QPointF tmp2 = mapToScene(event->pos()); QPointF tmp = tmp2.mapToScene(previous_point); translate(tmp.x(),tmp.y()); ```
Scrolling QGraphicsView programmatically
[ "", "python", "qt", "" ]
I have the following string in a variable. ``` Stack Overflow is as frictionless and painless to use as we could make it. ``` I want to fetch first 28 characters from the above line, so normally if I use [substr](http://php.net/manual/en/function.substr.php) then it will give me `Stack Overflow is as frictio` this output but I want output as: ``` Stack Overflow is as... ``` Is there any pre-made function in PHP to do so, Or please provide me code for this in PHP? **Edited:** I want total 28 characters from the string without breaking a word, if it will return me few less characters than 28 without breaking a word, that's fine.
You can use the [`wordwrap()`](http://php.net/wordwrap) function, then explode on newline and take the first part: ``` $str = wordwrap($str, 28); $str = explode("\n", $str); $str = $str[0] . '...'; ```
From [AlfaSky](http://www.alfasky.com/?p=20): ``` function addEllipsis($string, $length, $end='…') { if (strlen($string) > $length) { $length -= strlen($end); $string = substr($string, 0, $length); $string .= $end; } return $string; } ``` An alternate, more featureful implementation from [Elliott Brueggeman's blog](http://www.ebrueggeman.com/blog/tag/trim/): ``` /** * trims text to a space then adds ellipses if desired * @param string $input text to trim * @param int $length in characters to trim to * @param bool $ellipses if ellipses (...) are to be added * @param bool $strip_html if html tags are to be stripped * @return string */ function trim_text($input, $length, $ellipses = true, $strip_html = true) { //strip tags, if desired if ($strip_html) { $input = strip_tags($input); } //no need to trim, already shorter than trim length if (strlen($input) <= $length) { return $input; } //find last space within length $last_space = strrpos(substr($input, 0, $length), ' '); $trimmed_text = substr($input, 0, $last_space); //add ellipses (...) if ($ellipses) { $trimmed_text .= '...'; } return $trimmed_text; } ``` (Google search: "php trim ellipses")
How to get first x chars from a string, without cutting off the last word?
[ "", "php", "string", "substr", "" ]
I'm currently working on a web application that involves mounting a drive and extracting a tar.gz file, all in Java. Since the application runs in a linux environment, I figured I'd try using unix commands like "mount" and "tar". ``` Runtime runtime = Runtime.getRuntime(); Process proc; String mountCommand = "mount -t cifs -o username=..."; String extractCommand = "tar xzf ..." proc = runtime.exec(mountCommand); proc.waitFor(); proc = runtime.exec(extractCommand); proc.waitFor(); ``` Running the mount command and extract command in the terminal works fine, but fails when FIRST run in java. The second proc.waitFor() returns exit code 2. However, running this code after the first failed attempt works fine. I have a feeling that the problem is that waitFor() isn't waiting until the mount command is fully completed. Am I missing anything important in my code? Also, I'd rather do this all in Java, but I had a really hard time figuring out how to untar a file, so I'm taking this approach. (oh if anyone can tell me how to do this i would be very happy). Any suggestions would be muuuuuuuuuuch appreciated!
Making progress. In case anyone was wondering, here is how I am extracting a tar.gz file in Java. Put together from a few online tutorials. ``` public static void extract(String tgzFile, String outputDirectory) throws Exception { // Create the Tar input stream. FileInputStream fin = new FileInputStream(tgzFile); GZIPInputStream gin = new GZIPInputStream(fin); TarInputStream tin = new TarInputStream(gin); // Create the destination directory. File outputDir = new File(outputDirectory); outputDir.mkdir(); // Extract files. TarEntry tarEntry = tin.getNextEntry(); while (tarEntry != null) { File destPath = new File(outputDirectory + File.separator + tarEntry.getName()); if (tarEntry.isDirectory()) { destPath.mkdirs(); } else { // If the parent directory of a file doesn't exist, create it. if (!destPath.getParentFile().exists()) destPath.getParentFile().mkdirs(); FileOutputStream fout = new FileOutputStream(destPath); tin.copyEntryContents(fout); fout.close(); // Presserve the last modified date of the tar'd files. destPath.setLastModified(tarEntry.getModTime().getTime()); } tarEntry = tin.getNextEntry(); } tin.close(); } ```
**Quick Answer** Since a dependency on external commands exists, simplify it like this: ``` #!/bin/bash mount -t cifs -o username=... tar xzf ... ``` Name it `mount-extract.sh` then call it using a single `Runtime.exec()` call. **Semi-integrated Answer** Use Java APIs. * <http://java.sun.com/j2se/1.4.2/docs/api/java/util/zip/GZIPInputStream.html> * <http://www.jajakarta.org/ant/ant-1.6.1/docs/ja/manual/api/org/apache/tools/tar/TarInputStream.html> You will need `Runtime.exec` to execute the mount command. **Forward Looking** Since Java is a cross-platform software development tool, consider abstracting the mount command in your application to be derived dynamically based on the underlying operating system. See: [How can I mount a windows drive in Java?](https://stackoverflow.com/questions/208839/how-can-i-mount-a-windows-drive-in-java) See: <http://java.sun.com/j2se/1.4.2/docs/api/java/lang/System.html#getProperties()> Of course, Agile development would insist that this not be done until it is needed. So keep it in the back of your mind until then (as you might never run the application on anything but Unix-based systems).
Mounting and untar'ing a file in Java
[ "", "java", "process", "runtime", "tar", "mount", "" ]
I got a query with five joins on some rather large tables (largest table is 10 mil. records), and I want to know if rows exists. So far I've done this to check if rows exists: ``` SELECT TOP 1 tbl.Id FROM table tbl INNER JOIN ... ON ... = ... (x5) WHERE tbl.xxx = ... ``` Using this query, in a stored procedure takes 22 seconds and I would like it to be close to "instant". Is this even possible? What can I do to speed it up? I got indexes on the fields that I'm joining on and the fields in the WHERE clause. Any ideas?
4 options * Try COUNT(\*) in place of TOP 1 tbl.id * An index per column may not be good enough: you may need to use composite indexes Are you on SQL Server 2005? If som, you can find missing indexes. Or try the [database tuning advisor](http://msdn.microsoft.com/en-us/library/ms166575.aspx) * Also, it's possible that you don't need 5 joins. Assuming parent-child-grandchild etc, then grandchild rows can't exist without the parent rows (assuming you have foreign keys) So your query could become ``` SELECT TOP 1 tbl.Id --or count(*) FROM grandchildtable tbl INNER JOIN anothertable ON ... = ... WHERE tbl.xxx = ... ``` * Try EXISTS. For either for 5 tables or for assumed heirarchy ``` SELECT TOP 1 --or count(*) tbl.Id FROM grandchildtable tbl WHERE tbl.xxx = ... AND EXISTS (SELECT * FROM anothertable T2 WHERE tbl.key = T2.key /* AND T2 condition*/) -- or SELECT TOP 1 --or count(*) tbl.Id FROM mytable tbl WHERE tbl.xxx = ... AND EXISTS (SELECT * FROM anothertable T2 WHERE tbl.key = T2.key /* AND T2 condition*/) AND EXISTS (SELECT * FROM yetanothertable T3 WHERE tbl.key = T3.key /* AND T3 condition*/) ```
switch to EXISTS predicate. In general I have found it to be faster than selecting top 1 etc. So you could write like this `IF EXISTS (SELECT * FROM table tbl INNER JOIN table tbl2 .. do your stuff`
SQL: Optimization problem, has rows?
[ "", "sql", "query-optimization", "" ]
I am currently in charge of the development of the second version of program that was created in Microsoft .NET C#. I'm not doing any actual programming, but I am writing the specification for the programmer. I'd like to take it off the .NET codebase, but since Joel said on his [blog](http://www.joelonsoftware.com/articles/fog0000000069.html) never to rewrite code, and he does provide good reasoning, I'm inclined to think carefully. So my question is, (1) Are there any easy ways to transition? (Languages like .NET C#) (2) Would you take it off .NET? (3) If so, what language would you use? The reason I want to take it off of .NET is as far as my understanding of .NET, it has to be installed on the client. I'd prefer not to inconvenience my customers when there's a better way.
Unless you are moving away from C# as part of some sort of enterprise-wide shift from C# to another language, or unless there is some sort of *valid* technical requirement that C#/.NET can't satisfy, I would not move from the existing code base. You state your reason as that the client needs .NET. Is your program client/server, or is it a web application? If it's web based, then you are incorrect, the client does not need .NET, only a browser. If the program is client/server and is already written in C#, then any language you move to is also likely to require some form of runtime installation. .NET comes with every new install and service pack of Windows from XP on. Unless of course you're trying to target OSX and Linux users, in which case I would consider a serious examination into the value of those markets before you make any decisions to abandon your codebase. Java might help you better there -- but you can do a hell of a lot with the Mono platform, so you might be able to save your C# code even if you target those platforms. **Edit:** > waiwai933 wrote: > > *I'm aware that I shouldn't make the decision, but it wasn't my decision to > make about who would make the > decision. By "easy language", I meant > a language extremely similar to C#, so > that the transition would be easier.* Unfortunately, you are out of luck. The closest language to C# is Java, but the differences between the two are significant enough that you'll need to do a complete rewrite; a port simply will not work. It's highly unlikely that the C# code you have does not use delegates and events -- they're omnipresent -- and there is no similar construct in Java. The WinForms GUI framework (I'm guessing WinForms) is so different from Swing that *none* of the constructs will easily port; *and* it's littered with events and delegates. You are looking at at least as much effort to switch platforms as there was for the initial effort, possibly more. Plus going to Java violates the reason you want to switch from C#: Java requires a runtime installed on the client. As I mentioned before, look long and hard at the *real* benefits you might get from switching platforms before you make this decision.
This is going to sound rude and I risk being downvoted, but forgive me, I'm going to be honest ... you are saying, "[you are] in charge of the development of the second version of program that was created in Microsoft .NET C# ... not doing any actual programming ... [would] like to take it off the .NET codebase". Are you hearing yourself? You clearly don't have any knowledge or experience to make that decision, further evidenced by questions 1 and 3. There are no "easy languages" - what does that even mean? Is a powerful language "easy"? Is a weak language "easy"? How could there be an easy transition to anything different? Even if you have something to automatically translate the code, differences in the runtimes and platforms and libraries make porting any non-trivial application far from easy. It takes work and knowledge. Perhaps easy for someone with a **lot** of time, but not for most people with deadlines and reality to face.
Moving a C# Program to a different language
[ "", "c#", ".net", "language-comparisons", "" ]
Is there a way to get the name of the first property of a JSON object? I'd like to do something like this: ``` var firstProp = jsonObj[0]; ``` **edit:** I'm getting a JSON object which hold categories of arrays with image URLs. like so: ``` { "category1":["image/url/1.jpg","image/url/2.jpg"], "category2":["image/url/3.jpg","image/url/4.jpg"] } ``` I am then iterating through the object to insert the images, and all I really wanted was an elegant way to see which category was inserted first. At first I just did ``` for (var cat in images) { if (i==0) firstCat = cat; ... } ``` But that some how "felt" ugly... So it was basically just a question of elegance.
The order of the properties of an object are not *guaranteed* to be the same as the way you put them in. In practice, however, all major browsers do return them in order. So if you're okay with relying on this... ``` var firstProp; for(var key in jsonObj) { if(jsonObj.hasOwnProperty(key)) { firstProp = jsonObj[key]; break; } } ``` Also note that there's a [bug in Chrome](http://ejohn.org/blog/javascript-in-chrome/) regarding the ordering, in some edge cases it doesn't order it in the way they were provided. As far as it changing in the future, the chances are actually pretty small as I believe this is becoming part of the standard so if anything support for this will only become official. All things considered, though, if you really, really, absolutely, positively, want to be sure it's going to be in the right order you need to use an array. Otherwise, the above is fine. Related question: [Elements order - for (… in …) loop in javascript](https://stackoverflow.com/questions/280713/elements-order-for-in-loop-in-javascript)
``` console.log(jsonObj[Object.keys(jsonObj)[0]]); ```
Getting first JSON property
[ "", "javascript", "json", "" ]
In some of my VS 2005 projects, when I change an include file some of the cpp files are not rebuilt, even though they have a simple #include line in them. Is this a known bug, or something strange about the projects? Is there any information about how VS works out the dependencies and can I view the files for that? btw I did try some googling but couldn't find anything about this. I probably need the right search term...
I've experienced this problem from time to time, and with other IDEs too, not just VS. It seems thatv their internal dependency tree sometimes gets out of whack with reality. In these cases, I've found deleting pre-compiled headers (this is important) and doing a complete rebuild always solves the problem. Luckily, it doesn't happen often.
To be honest I never faced such a problem using Visual Studio. Your CPP should be rebuild as well if it includes the header. The only reason I can come up with: same include file is taken from 2 different sources. You can try do debug this at compile time, by enabling the preprocessor to output preprocessed files. Click on the CPP file go to properties and then to C/C++->Preprocessor and select in "Generate Preprocessed File" the item with or without line numbers. Go to you include file put the pragmas around your newly added definitions like: ``` #pragma starting_definition_X ... #pragma ending_definition_X ``` Now compile everything. There will be a newly created file with the same name as CPP but with extension .I (or .i). Make a search if your pragmas are there. If not, your include come from another place. If you use pre-compiled headers, you cpp should rebuild. There is also a pragma once statement in MS VC, which parses the include file only once, but that should still recompiler you cpp-file. Hope that helps, Ovanes
How does visual studio know which cpp files to rebuild when an include file is changed?
[ "", "c++", "visual-studio-2005", "build", "include", "" ]
How do I modify an int atomically and thread-safely in Java? Atomically increment, test & set, etc...?
Use [AtomicInteger](http://java.sun.com/javase/6/docs/api/java/util/concurrent/atomic/AtomicInteger.html).
Thread safety can be achieved via synchronized functions. Wrap your int (or such data) in a class which provides the required functionalities via synchronized methods, e.g. ``` public class X { protected int x; public synchronized void set( int value ) { x = value; } } ``` You can also use classes from the [java.util.concurrent.atomic](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/atomic/package-summary.html) package, e.g. AtomicInteger or AtomicIntegerArray ## Why this answer won't work I just wanted to be sure to point out exactly what is wrong with this answer, in case anyone thinks that `synchronized` can be used to solve thread race effects. ``` | Thread A | Thread B | |---------------|------------------| | read x (x=4) | | | | read x (x=4) | | Calculate 4+1 | | | EAX ← 5 | | | | Calculate 4+1 | | | EAX ← 5 | | Start sync | | | { | Start sync | | { x ← 5 | wait | | { | wait | | End sync | wait | | | { | | | { x ← 5 | | | { | | | End sync | ``` The end result of the operations: ``` x = 4; x += 1; x += 1; ``` is that **x = 5** rather than 6. The same issue exists with the `volatile` keyword. The `volatile` keyword doesn't save you from thread effects. The volatile keyword only ensures that * caches are flushed before a variable is read * caches are flushed after a value is written Strictly speaking, `volatile` ensures that memory operations are not reordered around a volatile variable. Which means you still suffer from the: * read from x * write to x problem.
What's Java's equivalent of .Net's Interlocked class?
[ "", "java", "multithreading", "concurrency", "interlocked", "" ]
We're using the Windows COM+ Services Type Library (located at C:\Windows\system32\COMSVCS.dll) to track COM+ processes on a remote machine using a service that is written in C# 3.0/.NET 3.5. The problem that I am encountering is that I am getting a whole slew of warnings from the compiler that look something like the following: > At least one of the arguments for > 'IGetAppData.GetApps' cannot be > marshaled by the runtime marshaler. > Such arguments will therefore be > passed as a pointer and may require > unsafe code to manipulate. The generated interop function signature for the method mentioned above is: ``` void IGetAppData.GetApps(out uint nApps, IntPtr aAppData) ``` As the output is already being marshalled manually in the calling code (i.e. using `Marshall.ReadInt32` and `Marshall.PtrToStructure`), is there a way to suppress these type of warnings?
since that warning don't have a number you cannot suppress it using #pragma but you can use [tlbimp](http://msdn.microsoft.com/en-us/library/tt0cf3sx(VS.80).aspx) to import the dll outside Visual Studio and use the generated reference instead of letting Visual Studio creating it.
Add this line in first property group of your project file: ``` <ResolveComReferenceSilent>True</ResolveComReferenceSilent> ```
How to suppress compiler warnings from the use of COM references in a .NET project
[ "", "c#", "interop", "marshalling", "" ]
I have a set of images that correspond to video thumbnails. The user clicks a thumb which loads the browser. This would be simple enough, but I need to track which of the thumbs was clicked, so that I can automatically cue up the next video in sequence. My first thought was to do something like this (highly simplified example): ``` <div class="thumbs"> <img id="vt_0" src="thumbxxx00.jpg" /> <img id="vt_1" src="thumbxxx01.jpg" /> <img id="vt_2" src="thumbxxx02.jpg" /> <img id="vt_3" src="thumbxxx03.jpg" /> <img id="vt_4" src="thumbxxx04.jpg" /> <img id="vt_5" src="thumbxxx05.jpg" /> <img id="vt_6" src="thumbxxx06.jpg" /> </div> <script type="text/javascript"> var videos = [ "xxx00", "xxx01", "xxx02", "xxx03", "xxx04", "xxx05", "xxx06" ]; var video_index = null; function playVideo(id) { // play video then call "onVideoFinish()" when video ends. } function onVideoFinish() { video_index = (video_index = 6) ? video_index : video_index+1; playVideo(videos[video_index]); } $j("div.thumbnail img").live("click", function (e) { e.preventDefault(); var selected_id = $(this).attr("id").split("_")[1]; video_index = selected_id; playvideo( videos[video_index] ); }); </script> ``` At first glance this seems to be okay, but I'm not sure if this is the best/most elegant solution, especially as I'd be implementing all these methods from within an object context.
This is how I would do it. The only global that you need in this case is currentPlayOrder, which could be stored someone as part of a preferences or configuration model. First the HTML. I moved the video sources into the rel attribute of the associated thumbnail. I assume that your application is generating the thumbnails, in which case, this would be an appropriate method since whatever generates the thumbnail HTML could be made aware of the associated video sources. ``` <div class="thumbs"> <img id="vt_0" src="http://stackoverflow.com/content/img/so/logo.png" rel="videoA"/> <img id="vt_1" src="http://serverfault.com/content/img/sf/logo.png" rel="videoB"/> <img id="vt_2" src="http://stackoverflow.com/content/img/so/logo.png" rel="videoC"/> <img id="vt_3" src="http://serverfault.com/content/img/sf/logo.png" rel="videoD"/> <img id="vt_4" src="http://stackoverflow.com/content/img/so/logo.png" rel="videoE"/> <img id="vt_5" src="http://serverfault.com/content/img/sf/logo.png" rel="videoF"/> <img id="vt_6" src="http://stackoverflow.com/content/img/so/logo.png" rel="videoG"/> </div> ``` Now the JS. Notice the use of `previousSibling` and `nextSibling` to determine play order: ``` <script type="text/javascript"> var PLAY_ORDER_BACKWARD = "previousSibling"; var PLAY_ORDER_FORWARD = "nextSibling"; var currentPlayOrder = PLAY_ORDER_FORWARD; $(document).ready(function() { $(".thumbs img").each(function(i, node) { $(node).click(function() { playVideo(this.getAttribute("rel"), this); }); }); }); var playVideo = function(source, thumbNode) { console.log("Play video %s", source); onVideoFinish(thumbNode); // If your video play accepts a callback, you may need to pass it as // function() { onVideoFinish(thumbNode); } } var onVideoFinish = function(thumbNode) { // Get the next img node (if any) in the appropriate direction while ( thumbNode = thumbNode[currentPlayOrder] ) { if ( thumbNode.tagName == "IMG" ) { break; } } // If an img node exists and it has the rel (video source) attribute if ( thumbNode && thumbNode.getAttribute("rel") ) { playVideo(thumbNode.getAttribute("rel"), thumbNode); } // Otherwise, assume that there are no more thumbs/videos in this direction else { console.log("No more videos to play"); } } </script> ``` Hope that helps.
Here's how I would do it. Instead of storing the video names inside an array, why not store the video name along with the thumbnail? You can use the class attribute to store the name of the video. Once you take this approach, things become simple. ``` <div class="thumbs"> <img id="vt_0" src="thumbxxx00.jpg" class="xxx00"/> <img id="vt_1" src="thumbxxx01.jpg" class="xxx01"/> <img id="vt_2" src="thumbxxx02.jpg" class="xxx02"/> <img id="vt_3" src="thumbxxx03.jpg" class="xxx03"/> <img id="vt_4" src="thumbxxx04.jpg" class="xxx04"/> <img id="vt_5" src="thumbxxx05.jpg" class="xxx05"/> <img id="vt_6" src="thumbxxx06.jpg" class="xxx06"/> </div> <script type="text/javascript"> function setupVideoPlayer(order) { //lastThumb won't be accessible from outside of setupVideoPlayer //function. var lastThumb = null; var imageSelector = 'div.thumbs img'; function playVideo(video) { //Play the video. onVideoFinish(); } function onVideoFinish() { //If order is 'ascending', we will go to the 'next' //image, otherwise we will go to 'previous' image. var method = order == 'asc' ? 'next' : 'prev'; //When user is at the end, we need to reset it either at the //first image (for ascending) or the last (for descending). var resetIndex = order == 'asc' ? 0 : $(imageSelector).length - 1; //When video has finished playing, we will try to //find the next/prev (depending upon order) sibling of 'lastThumb', //If we can not find any sibling, it means we are at the //last/first thumbnail and we will go back and fetch the first/last //image. //Also, instead of calling the playVideo method, we will //fire the click event of thumbnail. This way, if you decide to //do something in future (say playing an ad before the video) //you only need to do it in your click handler. if($(lastThumb)[method]().length == 0) $(imageSelector).get(resetIndex).click(); else $(lastThumb)[method]().click(); } $j(imageSelector) .click( function() { //on click, we store the reference to the thumbnail which was //clicked. lastThumb = this; //We get the name of the video from the class attribute //and play the video. playVideo($(this).attr('class')); } ); } $(document).ready( function() { setupVideoPlayer('asc'); } ); </script> ``` Above code has the advantage that you can modify your HTML and it will automatically play those videos.
Tracking which image in a list of images is clicked?
[ "", "javascript", "jquery", "sequence", "" ]
How do I write the YearFrac function that comes with Excel in Sql 2005?
Find out the distance between two dates using [DateDiff](http://msdn.microsoft.com/en-us/library/ms189794.aspx), and then divide that value by 365 **EDIT** You could, of course, create your own function to do the job: ``` create function yearfrac (@d1 datetime, @d2 datetime) returns float as begin return abs(datediff(d, @d1, @d2)) / 365.00 end ```
For the default usage (two data parameters): ``` datediff(day, date1, date2) / 360.0 ``` For the special case where the third parameter has the value 3: ``` datediff(day, date1, date2) / 365.0 ``` Edit: Added a decimal to make it a floating point operation.
YearFrac in Sql 2005
[ "", "sql", "excel", "" ]
I'd like a generic method for retrieving the data from a vector. I have a the following class and vector: ``` class myClass { public: myClass(int myX, float myZ, std::string myFoo) : x ( myX ) , z ( myZ ) , foo ( myFoo ) { } myClass() { } int x; float z; std::string foo; } ; std::vector < myClass > myVector; ``` (The complete code can be seen here: <http://codepad.org/iDD1Wme5> ) In this example I would like to be able to retrieve objects in the vector based on the "z" or "foo" members without having to write another 2 functions similar to "FindDataById". Is that possible?
You can use a template and pointer to member. ``` typedef vector<myClass> myVector; template<typename T> bool FindDataById(const T &id, T myClass::* idMember, myClass &theClass, const myVector &theVector) { for(myVector::const_iterator itr = theVector.begin(); itr != myVector.end(); ++itr){ if((*itr).*idMember == id){ theClass = *itr; return true; } return false; } ``` Then call using, e.g., ``` FindDataById(string("name"), &myClass::foo, theClass, theVector) FindDataById(5, &myClass::x, theClass, theVector) FindDataById(5.25f, &myClass::z, theClass, theVector) ``` Or, go with the `find_if` idea: ``` template<typename T> struct Finder { T val_; T myClass::* idMember_; Finder(T val, T myClass::* idMember) : val_(val), idMember_(idMember) {} bool operator()(const myClass &obj) { return obj.*idMember_ == val_; } }; ``` And use: ``` find_if(theVector.begin(), theVector.end(), Finder<string>("name", &myClass::foo)) find_if(theVector.begin(), theVector.end(), Finder<int>(5, &myClass::x)) find_if(theVector.begin(), theVector.end(), Finder<float>(3.25f, &myClass::z)) ``` See the answer of MSalters for a way to deduce the template argument automatically.
`std::find_if` has already been suggested, but without a code sample, so here's a more detailed version: Define two functors to identify the object you're interested in: ``` struct z_equals { z_equals(float z) : z(z) {} bool operator()(const myClass& obj) return z == obj.z; } float z; }; struct foo_equals { foo_equals(const std::string& foo) : foo(foo) {} bool operator()(const myClass& obj) return foo == obj.foo; } const std::string& foo; }; ``` And now, to search for elements where z == 42.0f, or foo == "hello world": ``` std::find_if(myVector.begin(), myVector.end(), z_equals(42.0f)); std::find_if(myVector.begin(), myVector.end(), foo_equals("hello world")); ```
generic lookup method?
[ "", "c++", "templates", "vector", "" ]
If I include both *gtest/gtest.h* and *boost/math/distributions/poisson.hpp* I get ``` /opt/local/include/boost/tr1/tuple.hpp:63: error: ‘tuple’ is already declared in this scope /opt/local/include/boost/tr1/tuple.hpp:67: error: ‘make_tuple’ is already declared in this scope /opt/local/include/boost/tr1/tuple.hpp:68: error: ‘tie’ is already declared in this scope /opt/local/include/boost/tr1/tuple.hpp:68: error: ‘tie’ is already declared in this scope /opt/local/include/boost/tr1/tuple.hpp:68: error: ‘tie’ is already declared in this scope /opt/local/include/boost/tr1/tuple.hpp:68: error: ‘tie’ is already declared in this scope /opt/local/include/boost/tr1/tuple.hpp:68: error: ‘tie’ is already declared in this scope /opt/local/include/boost/tr1/tuple.hpp:68: error: ‘tie’ is already declared in this scope /opt/local/include/boost/tr1/tuple.hpp:68: error: ‘tie’ is already declared in this scope /opt/local/include/boost/tr1/tuple.hpp:68: error: ‘tie’ is already declared in this scope /opt/local/include/boost/tr1/tuple.hpp:68: error: ‘tie’ is already declared in this scope /opt/local/include/boost/tr1/tuple.hpp:68: error: ‘tie’ is already declared in this scope /opt/local/include/boost/tr1/tuple.hpp:72: error: ‘tuple_size’ is already declared in this scope /opt/local/include/boost/tr1/tuple.hpp:73: error: ‘tuple_element’ is already declared in this scope ``` How do I prevent these two library namespaces from colliding?
Try building with `BOOST_HAS_TR1_TUPLE` defined. It looks like both boost and your `std` libraries are defining `std::tr1::tuple` and I can't see how to disable the `std` version. Looking at the boost header though it appears that `BOOST_HAS_TR1_TUPLE` needs to be defined to tell boost that `std::tr1::tuple` is already defined. I got similar errors to yours when I tried to compile a file including both those headers and then they disappeared when I defined `BOOST_HAS_TR1_TUPLE`.
Have you tried switching the order of the includes? It is possible the other header file handles things a little more gracefully.
c++ namespace collision with gtest and boost
[ "", "c++", "boost", "googletest", "" ]
I wrote this PHP code to implement the Flesch-Kincaid Readability Score as a function: ``` function readability($text) { $total_sentences = 1; // one full stop = two sentences => start with 1 $punctuation_marks = array('.', '?', '!', ':'); foreach ($punctuation_marks as $punctuation_mark) { $total_sentences += substr_count($text, $punctuation_mark); } $total_words = str_word_count($text); $total_syllable = 3; // assuming this value since I don't know how to count them $score = 206.835-(1.015*$total_words/$total_sentences)-(84.6*$total_syllables/$total_words); return $score; } ``` Do you have suggestions how to improve the code? Is it correct? Will it work? I hope you can help me. Thanks in advance!
The code looks fine as far as a heuristic goes. Here are some points to consider that make the items you need to calculate considerably difficult for a machine: 1. What is a sentence? Seriously, what is a sentence? We have periods, but they can also be used for Ph.D., e.g., i.e., Y.M.C.A., and other non-sentence-final purposes. When you consider exclamation points, question marks, and ellipses, you're really doing yourself a disservice by assuming a period will do the trick. I've looked at this problem before, and if you really want a more reliable count of sentences in real text, you'll need to parse the text. This can be computationally intensive, time-consuming, and hard to find free resources for. In the end, you still have to worry about the error rate of the particular parser implementation. However, only full parsing will tell you what's a sentence and what's just a period's other many uses. Furthermore, if you're using text 'in the wild' -- such as, say, HTML -- you're going to also have to worry about sentences ending not with punctuation but with tag endings. For instance, many sites don't add punctuation to h1 and h2 tags, but they're clearly different sentences or phrases. 2. Syllables aren't something we should be approximating This is a major hallmark of this readability heuristic, and it's one that makes it the most difficult to implement. Computational analysis of syllable count in a work requires the assumption that the assumed reader speaks in the same dialect as whatever your syllable count generator is being trained on. How sounds fall around a syllable is actual a major part of what makes accents accents. If you don't believe me, try visiting Jamaica sometime. What this means it that even if a human were to do the calculations for this by hand, it would still be a dialect-specific score. 3. What is a word? Not to wax psycholingusitic in the slightest, but you will find that space-separated words and what are conceptualized as words to a speaker are quite different. This will make the concept of a computable readability score somewhat questionable. So in the end, I can answer your question of 'will it work'. If you're looking to take a piece of text and display this readability score among other metrics to offer some kind of conceivable added value, the discerning user will not bring up all of these questions. If you are trying to do something scientific, or even something pedagogical (as this score and those like it were ultimately intended), I wouldn't really bother. In fact, if you're going to use this to make any kind of suggestions to a user about content that they have generated, I would be extremely hesitant. A better way to measure reading difficulty of a text would more likely be something having to do with the ratio of low-frequency words to high-frequency words along with the number of [hapax legomena](http://en.wikipedia.org/wiki/Hapax_legomenon) in the text. But I wouldn't pursue actually coming up with a heuristic like this, because it would be very difficult to empirically test anything like it.
Take a look at the [PHP Text Statistics](https://github.com/DaveChild/Text-Statistics/blob/master/src/DaveChild/TextStatistics/TextStatistics.php) class on GitHub.
Flesch-Kincaid Readability: Improve PHP function
[ "", "php", "formula", "readability", "flesch-kincaid", "" ]
In a pylab program (which could probably be a matlab program as well) I have a numpy array of numbers representing distances: `d[t]` is the *distance* at time `t` (and the timespan of my data is `len(d)` time units). The events I'm interested in are when the distance is below a certain threshold, and I want to compute the duration of these events. It's easy to get an array of booleans with `b = d<threshold`, and the problem comes down to computing the sequence of the lengths of the True-only words in `b`. But I do not know how to do that efficiently (i.e. using numpy primitives), and I resorted to walk the array and to do manual change detection (i.e. initialize counter when value goes from False to True, increase counter as long as value is True, and output the counter to the sequence when value goes back to False). But this is tremendously slow. **How to efficienly detect that sort of sequences in numpy arrays ?** Below is some python code that illustrates my problem : the fourth dot takes a very long time to appear (if not, increase the size of the array) ``` from pylab import * threshold = 7 print '.' d = 10*rand(10000000) print '.' b = d<threshold print '.' durations=[] for i in xrange(len(b)): if b[i] and (i==0 or not b[i-1]): counter=1 if i>0 and b[i-1] and b[i]: counter+=1 if (b[i-1] and not b[i]) or i==len(b)-1: durations.append(counter) print '.' ```
While not `numpy` primitives, `itertools` functions are often very fast, so do give this one a try (and measure times for various solutions including this one, of course): ``` def runs_of_ones(bits): for bit, group in itertools.groupby(bits): if bit: yield sum(group) ``` If you do need the values in a list, just can use list(runs\_of\_ones(bits)), of course; but maybe a list comprehension might be marginally faster still: ``` def runs_of_ones_list(bits): return [sum(g) for b, g in itertools.groupby(bits) if b] ``` Moving to "numpy-native" possibilities, what about: ``` def runs_of_ones_array(bits): # make sure all runs of ones are well-bounded bounded = numpy.hstack(([0], bits, [0])) # get 1 at run starts and -1 at run ends difs = numpy.diff(bounded) run_starts, = numpy.where(difs > 0) run_ends, = numpy.where(difs < 0) return run_ends - run_starts ``` Again: be sure to benchmark solutions against each others in realistic-for-you examples!
Fully numpy vectorized and generic RLE for any array (works with strings, booleans etc too). Outputs tuple of run lengths, start positions, and values. ``` import numpy as np def rle(inarray): """ run length encoding. Partial credit to R rle function. Multi datatype arrays catered for including non Numpy returns: tuple (runlengths, startpositions, values) """ ia = np.asarray(inarray) # force numpy n = len(ia) if n == 0: return (None, None, None) else: y = ia[1:] != ia[:-1] # pairwise unequal (string safe) i = np.append(np.where(y), n - 1) # must include last element posi z = np.diff(np.append(-1, i)) # run lengths p = np.cumsum(np.append(0, z))[:-1] # positions return(z, p, ia[i]) ``` Pretty fast (i7): ``` xx = np.random.randint(0, 5, 1000000) %timeit yy = rle(xx) 100 loops, best of 3: 18.6 ms per loop ``` Multiple data types: ``` rle([True, True, True, False, True, False, False]) Out[8]: (array([3, 1, 1, 2]), array([0, 3, 4, 5]), array([ True, False, True, False], dtype=bool)) rle(np.array([5, 4, 4, 4, 4, 0, 0])) Out[9]: (array([1, 4, 2]), array([0, 1, 5]), array([5, 4, 0])) rle(["hello", "hello", "my", "friend", "okay", "okay", "bye"]) Out[10]: (array([2, 1, 1, 2, 1]), array([0, 2, 3, 4, 6]), array(['hello', 'my', 'friend', 'okay', 'bye'], dtype='|S6')) ``` Same results as Alex Martelli above: ``` xx = np.random.randint(0, 2, 20) xx Out[60]: array([1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1]) am = runs_of_ones_array(xx) tb = rle(xx) am Out[63]: array([4, 5, 2, 5]) tb[0][tb[2] == 1] Out[64]: array([4, 5, 2, 5]) %timeit runs_of_ones_array(xx) 10000 loops, best of 3: 28.5 µs per loop %timeit rle(xx) 10000 loops, best of 3: 38.2 µs per loop ``` Slightly slower than Alex (but still very fast), and much more flexible.
find length of sequences of identical values in a numpy array (run length encoding)
[ "", "python", "matlab", "numpy", "matplotlib", "" ]
I'm generating an unordered list through javascript (using jQuery). Each listitem must receive its own event listener for the 'click'-event. However, I'm having trouble getting the right callback attached to the right item. A (stripped) code sample might clear things up a bit: ``` for(class_id in classes) { callback = function() { this.selectClass(class_id) }; li_item = jQuery('<li></li>') .click(callback); } ``` Actually, more is going on in this iteration, but I didn't think it was very relevant to the question. In any case, what's happening is that the callback function seems to be *referenced* rather than *stored* (& copied). End result? When a user clicks *any* of the list items, it will always execute the action for the *last* `class_id` in the `classes` array, as it uses the function stored in `callback` at that specific point. I found dirty workarounds (such as parsing the `href` attribute in an enclosed `a` element), but I was wondering whether there is a way to achieve my goals in a 'clean' way. If my approach is horrifying, please say so, as long as you tell me why :-) Thanks!
This is a better cleaner way of doing what you want. Add the class\_id info onto the element using .data(). Then use .live() to add a click handler to all the new elements, this avoids having x \* click functions. ``` for(class_id in classes) { li_item = jQuery('<li></li>').data('class_id', class_id).addClass('someClass'); } //setup click handler on new li's $('li.someClass').live('click', myFunction ) function myFunction(){ //get class_id var classId = $(this).data('class_id'); //do something } ```
This is a classic "you need a closure" problem. Here's how it usually plays out. 1. Iterate over some values 2. Define/assign a function in that iteration that uses iterated variables 3. You learn that every function uses only values from the last iteration. 4. WTF? Again, when you see this pattern, it should immediately make you think "closure" Extending your example, here's how you'd put in a closure ``` for ( class_id in classes ) { callback = function( cid ) { return function() { $(this).selectClass( cid ); } }( class_id ); li_item = jQuery('<li></li>').click(callback); } ``` However, in this specific instance of jQuery, you shouldn't need a closure - but I have to ask about the nature of your variable `classes` - is that an object? Because you iterate over with a for-in loop, which suggest object. And for me it begs the question, why aren't you storing this in an array? Because if you were, your code could just be this. ``` jQuery('<li></li>').click(function() { $(this).addClass( classes.join( ' ' ) ); }); ```
How to assign event callbacks iterating an array in javascript (jQuery)
[ "", "javascript", "jquery", "events", "iteration", "" ]
I was reading some old game programming books and as some of you might know, back in that day it was usually faster to do bit hacks than do things the standard way. (Converting `float` to `int`, mask sign bit, convert back for absolute value, instead of just calling `fabs()`, for example) Nowadays is almost always better to just use the standard library math functions, since these tiny things are hardly the cause of most bottlenecks anyway. But I still want to do a comparison, just for curiosity's sake. So I want to make sure when I profile, I'm not getting skewed results. As such, I'd like to make sure the compiler does not optimize out statements that have no side effect, such as: ``` void float_to_int(float f) { int i = static_cast<int>(f); // has no side-effects } ``` Is there a way to do this? As far as I can tell, doing something like `i += 10` will still have no side-effect and as such won't solve the problem. The only thing I can think of is having a global variable, `int dummy;`, and after the cast doing something like `dummy += i`, so the value of `i` is used. But I feel like this dummy operation will get in the way of the results I want. I'm using Visual Studio 2008 / G++ (3.4.4). ### Edit To clarify, I would like to have all optimizations maxed out, to get good profile results. The problem is that with this the statements with no side-effect will be optimized out, hence the situation. ### Edit Again To clarify once more, read this: ***I'm not trying to micro-optimize this in some sort of production code.*** We all know that the old tricks aren't very useful anymore, I'm merely curious *how* not useful they are. Just plain curiosity. Sure, life could go on without me knowing just how these old hacks perform against modern day CPU's, but it never hurts to know. So telling me "these tricks aren't useful anymore, stop trying to micro-optimize blah blah" is an answer completely missing the point. I **know** they aren't useful, I don't use them. Premature quoting of Knuth is the root of all annoyance.
Compilers are unfortunately allowed to optimise as much as they like, even without any explicit switches, if the code behaves as if no optimisation takes place. However, you can often trick them into not doing so if you indicate that value might be used later, so I would change your code to: ``` int float_to_int(float f) { return static_cast<int>(f); // has no side-effects } ``` As others have suggested, you will need to examine the assemnler output to check that this approach actually works.
Assignment to a `volatile` variable shold never be optimized away, so this might give you the result you want: ``` static volatile int i = 0; void float_to_int(float f) { i = static_cast<int>(f); // has no side-effects } ```
Force compiler to not optimize side-effect-less statements
[ "", "c++", "optimization", "" ]
``` var items = from c in contacts select new ListItem { Value = c.ContactId, //Cannot implicitly convert type 'int' (ContactId) to 'string' (Value). Text = c.Name }; var items = from c in contacts select new ListItem { Value = c.ContactId.ToString(), //Throws exception: ToString is not supported in linq to entities. Text = c.Name }; ``` Is there anyway I can achieve this? Note, that in VB.NET there is no problem use the first snippet it works just great, VB is flexible, im unable to get used to C#'s strictness!!!
With EF v4 you can use [`SqlFunctions.StringConvert`](http://msdn.microsoft.com/en-us/library/dd466166.aspx). There is no overload for int so you need to cast to a double or a decimal. Your code ends up looking like this: ``` var items = from c in contacts select new ListItem { Value = SqlFunctions.StringConvert((double)c.ContactId).Trim(), Text = c.Name }; ```
I solved a similar problem by placing the conversion of the integer to string out of the query. This can be achieved by putting the query into an object. ``` var items = from c in contacts select new { Value = c.ContactId, Text = c.Name }; var itemList = new SelectList(); foreach (var item in items) { itemList.Add(new SelectListItem{ Value = item.ContactId, Text = item.Name }); } ```
Problem with converting int to string in Linq to entities
[ "", "c#", "asp.net", "linq-to-entities", "tostring", "" ]
My current situation is: I have to read a file and put the contents into `InputStream`. Afterwards I need to place the contents of the `InputStream` into a byte array which requires (as far as I know) the size of the `InputStream`. Any ideas? As requested, I will show the input stream that I am creating from an uploaded file ``` InputStream uploadedStream = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); java.util.List items = upload.parseRequest(request); java.util.Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { uploadedStream = item.getInputStream(); //CHANGE uploadedStreambyte = item.get() } } ``` The request is a `HttpServletRequest` object, which is like the `FileItemFactory` and `ServletFileUpload` is from the Apache Commons FileUpload package.
I just wanted to add, Apache Commons IO has stream support utilities to perform the copy. (Btw, what do you mean by placing the file into an inputstream? Can you show us your code?) **Edit:** Okay, what do you want to do with the contents of the item? There is an `item.get()` [which returns](http://commons.apache.org/fileupload/apidocs/org/apache/commons/fileupload/FileItem.html#get()) the entire thing in a byte array. **Edit2** `item.getSize()` will return the uploaded [file size](http://commons.apache.org/fileupload/apidocs/org/apache/commons/fileupload/FileItem.html#getSize()).
This is a REALLY old thread, but it was still the first thing to pop up when I googled the issue. So I just wanted to add this: ``` InputStream inputStream = conn.getInputStream(); int length = inputStream.available(); ``` Worked for me. And MUCH simpler than the other answers here. **Warning** This solution does not provide reliable results regarding the total size of a stream. Except from the JavaDoc: > Note that while some implementations of {@code InputStream} will return > \* the total number of bytes in the stream, many will not.
Determine the size of an InputStream
[ "", "java", "arrays", "size", "inputstream", "" ]
The question may be a little vague but here's an example of what I want to know (pseudocode): ``` //start test-case for CreateObject function { // initialization of parameters MyObject *obj = CreateObject(); // test results } //end test-case for CreateObject function ``` Is it necessary in this case to also deallocate the memory by calling "DestroyObject" function? [this is the particular case that gave birth to this question] My personal opinion would be no, that I shouldn't undo what the function did, but if many tests would be carried out I could remain without memory/resources for that test-suite (not likely to happen but ...). What do you think? In this case and also in a general case. Thanks, Iulian
In this case, you should deallocate the memory your test case has allocated. That way, you can use a tool that lets you run your tests and confirms that no memory was leaked. Letting your test code leak memory means that this would fail, and you wouldn't be able to tell for certain that the leak was in the test and not in your production code. As to the more general situation, tests should clean up what they've done. Most unit testing frameworks let you implement a tearDown() method to do this. That way, if one test fails you'll know it's an issue with that test and not an interaction with another test.
You should really try to create all the mock objects on the stack (or use smart pointers). That way they get automatically destructed when test function goes out of scope.
Must every test-case undo their operation at the end?
[ "", "c++", "unit-testing", "" ]
In Python, how can I print the current call stack from within a method (for debugging purposes).
Here's an example of getting the stack via the [traceback](http://docs.python.org/library/traceback.html) module, and printing it: ``` import traceback def f(): g() def g(): for line in traceback.format_stack(): print(line.strip()) f() # Prints: # File "so-stack.py", line 10, in <module> # f() # File "so-stack.py", line 4, in f # g() # File "so-stack.py", line 7, in g # for line in traceback.format_stack(): ``` If you really only want to print the stack to stderr, you can use: ``` traceback.print_stack() ``` Or to print to stdout (useful if want to keep redirected output together), use: ``` traceback.print_stack(file=sys.stdout) ``` But getting it via `traceback.format_stack()` lets you do whatever you like with it.
``` import traceback traceback.print_stack() ```
Print current call stack from a method in code
[ "", "python", "debugging", "stack-trace", "" ]
By which I mean a structure with: * O(log n) complexity for `x.push()` operations * O(log n) complexity to find an element * O(n) complexity to compute `list(x)` which will be sorted I also had a related question about performance of `list(...).insert(...)` which is now [here](https://stackoverflow.com/questions/1110332/performance-of-list-insert).
The standard Python list is not sorted in any form. The standard [heapq](https://docs.python.org/3/library/heapq.html) module can be used to append in O(log n) to an existing list and remove the smallest one in O(log n), but isn't a sorted list in your definition. There are various implementations of balanced trees for Python that meet your requirements, e.g. [rbtree](http://pypi.python.org/pypi/rbtree/), [RBTree](http://newcenturycomputers.net/projects/rbtree.html), or [pyavl](http://sourceforge.net/projects/pyavl/).
Is there a particular reason for your big-O requirements? Or do you just want it to be fast? The [sortedcontainers](http://www.grantjenks.com/docs/sortedcontainers/) module is pure-Python and fast (as in fast-as-C implementations like blist and rbtree). The [performance comparison](http://www.grantjenks.com/docs/sortedcontainers/performance.html) shows it benchmarks faster or on par with blist's sorted list type. Note also that rbtree, RBTree, and PyAVL provide sorted dict and set types but don't have a sorted list type. If performance is a requirement, always remember to benchmark. A module that substantiates the claim of being fast with Big-O notation should be suspect until it also shows benchmark comparisons. **Disclaimer:** I am the author of the Python sortedcontainers module. --- Installation: ``` pip install sortedcontainers ``` Usage: ``` >>> from sortedcontainers import SortedList >>> l = SortedList() >>> l.update([0, 4, 1, 3, 2]) >>> l.index(3) 3 >>> l.add(5) >>> l[-1] 5 ```
Does python have a sorted list?
[ "", "python", "list", "sorting", "" ]
I have several constants that I use, and my plan was to put them in a const array of doubles, however the compiler won't let me. I have tried declaring it this way: ``` const double[] arr = {1, 2, 3, 4, 5, 6, 73, 8, 9 }; ``` Then I settled on declaring it as static readonly: ``` static readonly double[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9}; ``` However the question remains. Why won't compiler let me declare an array of const values? Or will it, and I just don't know how?
From MSDN (<http://msdn.microsoft.com/en-us/library/ms228606.aspx>) > A constant-expression is an expression > that can be fully evaluated at > compile-time. Because the only way to > create a non-null value of a > reference-type [an array] is to apply the new > operator, and because the new operator > is not permitted in a > constant-expression, the only possible > value for constants of reference-types > other than string is null.
This is probably because ``` static const double[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9}; ``` is in fact the same as saying ``` static const double[] arr = new double[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9}; ``` A value assigned to a const has to be... const. Every reference type is not constant, and an array is a reference type. The solution, my research showed, was using a static readonly. Or, in your case, with a fixed number of doubles, give everything an individual identifier. --- **Edit(2):** A little sidenode, every type can be used const, but the value assigned to it must be const. For reference types, the only thing you can assign is null: ``` static const double[] arr = null; ``` But this is completely useless. Strings are the exception, these are also the only reference type which can be used for attribute arguments.
Declaring a const double[] in C#?
[ "", "c#", "static", "constants", "readonly", "" ]
I have always used the `mouseover` event, but while reading the jQuery documentation I found `mouseenter`. They seem to function exactly the same. Is there a difference between the two, and if so when should I use them? (Also applies for `mouseout` vs `mouseleave`).
You can try out the following example from [the jQuery doc](http://api.jquery.com/mouseover/) page. It's a nice little, interactive demo that makes it very clear and you can actually see for yourself. ``` var i = 0; $("div.overout") .mouseover(function() { i += 1; $(this).find("span").text("mouse over x " + i); }) .mouseout(function() { $(this).find("span").text("mouse out "); }); var n = 0; $("div.enterleave") .mouseenter(function() { n += 1; $(this).find("span").text("mouse enter x " + n); }) .mouseleave(function() { $(this).find("span").text("mouse leave"); }); ``` ``` div.out { width: 40%; height: 120px; margin: 0 15px; background-color: #d6edfc; float: left; } div.in { width: 60%; height: 60%; background-color: #fc0; margin: 10px auto; } p { line-height: 1em; margin: 0; padding: 0; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="out overout"> <span>move your mouse</span> <div class="in"> </div> </div> <div class="out enterleave"> <span>move your mouse</span> <div class="in"> </div> </div> ``` In short, you'll notice that a mouse over event occurs on an element when you are over it - coming from either its child OR parent element, but a mouse enter event only occurs when the mouse moves from outside this element to this element. Or [as the `mouseover()` docs](http://api.jquery.com/mouseover/) put it: > [`.mouseover()`] can cause many headaches due to event bubbling. For instance, when the mouse pointer moves over the Inner element in this example, a mouseover event will be sent to that, then trickle up to Outer. This can trigger our bound mouseover handler at inopportune times. See the discussion for `.mouseenter()` for a useful alternative.
Mouseenter and mouseleave **do not** react to event bubbling, while mouseover and mouseout **do**. Here's an [article](http://www.quirksmode.org/js/events_mouse.html) that describes the behavior.
What is the difference between the mouseover and mouseenter events?
[ "", "javascript", "jquery", "events", "jquery-events", "" ]
I've noticed that when I start Netbeans it shows up in the task manager as `netbeans.exe` as all my own Java applications show up as `java.exe` or `javaw.exe`. How can I change that so my process names shows up as `myapp.exe`?
The process name is the name of the JVM. So if you rename the jvm you have an other process name. There are some tools which can do that for you. For example [Launch4J](http://launch4j.sourceforge.net/index.html)
IMO the best option is to choose one of the many open source launchers. They all provide a nicer deployment container than java.exe and a batch file. I've compiled a list of them after a brief search on google (in no particular order and may not be exhaustive): * [NSIS](http://nsis.sourceforge.net/A_slightly_better_Java_Launcher "NSIS") * [Janel](http://www.redskaper.com/ "Janel") (dead link) * [JSmooth](http://jsmooth.sourceforge.net/ "JSmooth") * [Launch4J](http://launch4j.sourceforge.net/ "Launch4J") * [WinRun4J](http://winrun4j.sourceforge.net/ "WinRun4J") (full disclosure: i work on winrun4j)
How can I give my Java application a unique process name?
[ "", "java", "windows", "" ]
I would like to know, in a practical sense, on a large scale (Java - my case)project is it better to just code defensive logic to protect against invalid data in the DB or just take the time to go through and make sure that you don't accept any invalid data? Remember, the issue here is that there are many cases where a null is ok, and there are many cases where a null isn't, so the case to ensure that there is no invalid data is a non trivial one. The reason I ask is because I am working on a large project and find myself chasing some nasty null pointer exceptions only to realize that the reason its being thrown is because some obscure property of a large object isnt set. So, I go speak with a Systems Engineer only to realize that in the design, that is supposed to have been set by a user, etc. Note: please don't attribute these issues to just "poor systems design". Whether or not the design could have been better is not the issue at hand (as obviously any design can be improved). **I would like to take this form a point of a view of a developer that has already joined a very advanced project (in terms of time spent and lines of code) and what he should do from this point forward?** Thanks! \*\*It just occurred to me that many might consider this an opinionated issue? If this is the case then anyone can feel free to make this a community wiki. I'm not sure though. There might be some convention or "good-practice" that many follow that I am unaware of, and subsequently wouldn't be an opinionated question at all, simply a matter of informing me, a new developer, of that practice.
I tend to write my objects to validate upon construction (mostly my objects are immutable). Setters will validate as well. Validations include null checks (most common - I try *very* hard to prevent nulls, and comment code when a null is permissible), some sanity checks on values. These will result in `IllegalArgumentExceptions` upon failure (usually) When do I perform these validations ? Not on every object/helper object etc. Usually on some sort of transition between appropriate layers or component sets in my application. A good rule of thumb is that any component that is likely to be reused by a new client will perform validation. So (in your example) the database layer would provide validation, usually independently of other layers (this isn't unreasonable if you think that the different layers of the application represent the data in different forms) The level of validation depends on the source of that data. e.g. validations are performed most rigorously on user input (e.g. entries in text fields etc.). I'm less rigorous for checking input that would come from (say) a Spring XML configuration. Validation is enormously important. You're checking your data *immediately*, not when it's going to cause a problem. That makes life a lot easier (imagine if you accept bad input, serialise the object, deserialise it after a year, and find you can't use it!)
Use **database constraints** (NOT NULL, for instance) to disallow invalid data in the database by any means and **input validation** in your Java application code to disallow the user to enter invalid data. Database constraints alone are not enough because the user should see meaningful validation error messages. And input validation alone is not enough because the data in the database must be in a valid state even if there are errors in the input validation code. Also the data in the database doesn't necessarily have to come from your application.
Ensure valid data or protect against invalid data? Both?
[ "", "java", "" ]
I have a variable containing a string. The string can come in several ways: ``` // some examples of possible string $var = 'Tom Greenleaf (as John Dunn Hill)' // or $var = '(screenplay) (as The Wibberleys) &' // or $var = '(novella "Four Past Midnight: Secret Window, Secret Garden")' ``` I need to clean up the string to get only the first element. like this: ``` $var = 'Tom Greenleaf' $var = 'screenplay' $var = 'novella' ``` I know this is a bit complicated to do but there is a pattern we can use. Looking at the first variable, we can first check if the string contains the text ' (as'. If it does then we need to delete ' (as' and everything that comes after that. In the second variable the rule we made in the first one also applies. We just need also to delete the parenthesis . In the third variable if ' (as' was not found we need to get the first word only and then delete the parenthesis. Well, thas all. I just need someone to help me do it because I'm new to PHP and I don't know regular expressions.... or another way to do it. Thanks!!!!
Try this regular expression: ``` (?:^[^(]+|(?<=^\()[^\s)]+) ``` This will get you either anything up to the first parenthesis or the first word inside the first parenthesis. Together with `preg_match`: ``` preg_match('/(?:^[^(]+|(?<=^\\()[^\\s)]+)/', $var, $match); ```
actually, there's no need for complex regex ``` $var = 'Tom Greenleaf (as John Dunn Hill)'; $var = '(novella "Four Past Midnight: Secret Window, Secret Garden")'; $var = '(screenplay) (as The Wibberleys) &'; if ( strpos($var,"(as") !== FALSE ){ # get position of where (as is $ind = strpos($var,"(as"); $result = substr($var,0,$ind); }else { # if no (as, split on spaces and get first element $s = preg_split("/\s+/",$var); $result = $s[0]; } print preg_replace( "/\(|\)/","",$result); ```
PHP: Regular Expression to delete text from a string if condition is true
[ "", "php", "regex", "" ]
I have a Customer class that contains a property, MyProperty, which is of a custom type MyCustomType. I want to persist the property value in the database as text. In the designer I've set the Type to 'MyType' and the Server Data Type to 'varchar(10)'. When I build the project I get the following error: ``` DBML1005: Mapping between DbType 'varchar(10)' and Type 'MyType' in Column 'MyProperty' of Type 'Customer' is not supported. ``` Now that make sense, as Linq to Sql has no way of knowing how to convert my custom type. So I'm assuming I have to implement some kind of Parse(string) and ToString() methods on MyCustomType however I can't find any documentation on this. So, how do I map custom types in Linq to Sql?
A class to a varchar? I'm not aware of any functionality that supports this in LINQ-to-SQL. Your best bet may be a simple property (it can be private if you need): ``` [Column(Name="ColumnName", DbType="varchar(10) NULL", CanBeNull=true)] private string MyPropertyString { get { /* serialize MyProperty yourself */ } set { /* deserialize MyProperty yourself */ } } public MyCustomType MyProperty {get;set;} ``` (i.e. read from or update your actual `MyProperty` property) I also expect that you'd have to leave this **off** the designer, and add it yourself (and the `MyProperty` property) in a partial class.
Expanding on the private/public data access pattern above I did the following. 1) Select the DB data type to which the custom type will be mapped. In my case the custom object implemented the type-safe enumeration pattern so there is a natural mapping from the custom type (an enumeration of constants) and the DB types integral type (tinyint in my case). I can see the underlying DB type as string and then using JavaScriptSerializer Class for step 2. 2) Implement in your class the ability to convert between the custom type and the DB data type. The conversion have to be bi-directional: CustomObject --> DB type and DBType --> CustomObject For me it was implementing: 2a) The ordinal value of the enumerated type as a member of my type-safe enumeration class. This handles the casting from my custom type to int. 2b) A static member, findByOrdinal(), which handles the cast from int to my custom type. 3) Use Linq To SQL to create the link between the data column, this custom data type, and a public name. This is done by pasting in the name of the custom object into the Type combo box of the data member property. 4) Clean, and rebuild the project to insure the compile is clean. If the build process complains that the custom type does not exist within the context of <ProjectName>.designer.cs file found beneath the <ProjectName>.dbml file. Th regeneration issues are discussed below. If you execute the code in the DB context you will get the casting error above. Linq to SQL has created a number of partial class files when it created the .designer.cs file. We will need to add to this partial class code which will not be destroyed when Linq to SQL regenerates the code in <ProjectName>.designer.cs. 5) Create a new class file which contains source code to the partial classes created by Linq to SQL. To do this, right click on <ProjectName>.dbml in Solution Explore and select the View Code from the context menu. This will create a new file, <ProjectName>.cs, within the project which continues the definition of the partial classes found in <ProjectName>.designer.cs 6) Cut selected code from <ProjectName>.designer.cs and paste the code to <ProjectName>.cs Link to SQL has created within <ProjectName>.designer.cs a partial class that maps a table to a class. We need to remove the data access code found <ProjectName>.designer.cs and create our own version of this data access within <ProjectName>.cs. I did it by doing a straight cut and paste of the Linq-generated code and mutating the code to my puposes once the code was in <ProjectName>.cs. The cut, paste, mutate operations were: 6a) Change the data storage type from MyCustomType to something that maps easily to the DB data type for that column in the database. In my case I selected int as the internal data store for tinyint coming in from the the DB column. 6b) Alter the getter and setter methods of the publicly named data member created by Linq to SQL. See code below for details on the original Linq code and the final, mutated version. 7) Remove from <ProjectName>.designer.cs the using statment added in step 4 in order to get the compiler to temporarily accept the presence of the custom type within the Ling-Generated code. 8) Clean, and rebuild the project to insure the compile is clean. Nothing in .designer.cs should depend on a reference to the assembly which defines your custom class. this way Linq to SQL is free to generate <ProjectName>.designer.cs at will and this will not affect the code found in .cs. Note: The C# class which maps to the DB table is normally under the complete control of Linq to SQL code generator. By spliting the definition of the this class between the two source files, and , the source code in the two files must now be manually coordinated. This means the technical debt of long term maintenance between these source files has been accepted. 9) Test the interface. The Getter/Setter code maps my custom type to (and from) the underlying C# data store (and thence to the DB column on a DB table). Because of this the code consuming the data can rely on the strong typing from the C# class. The steps above are more more involved and not immediately obvvious. I did the above because rule number one with visual studio wizards (al code generating wizards for that matter): Don't Fight the Wizard. The Linq to SQL code generator is generating a lot of code on my behalf. This approach let me claim ownership of only those small pieces within the C#/Linq/SQL/DBColum code chain which deal with the C# class that is my custom type. If the Linq code is regenerated, then the compiler will throw compilation errors, but at this point the code maintainence is to delete the Linq to SQL generated code which is now a duplicate of my code in <ProjectName>.cs. Not ideal, but it should work over the longer term. The resulting code was: ``` namespace TestRepository { using System; using Framework; // Contains definition of the TestPropertyDataType class /* ******************************************************************************************************* * See: http://stackoverflow.com/questions/1097090/how-do-i-map-custom-types-in-linq-to-sql * * Expanding on the private/public interface mentioned here and using the fact that Linq auto generates a * public/private pairing with the getter/setter code, I mutated the Linq gneerated code to * quietly convert from type System.Byte to the custom type, TestPropertyDataType. * * Original code as generated by Linq to SQL which I lifted from the file: TestRepository.designer.cs * ***************************************************************************************************** * [global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.TEST_ACTION_PROPERTIES")] * public partial class TestActionPropertyMetadata : INotifyPropertyChanging, INotifyPropertyChanged * { * // <Lots of Linq-generated code> * * private TestPropertyDataType _DataType; * * // more Linq-generated code> * * #region Extensibility Method Definitions * partial void OnDataTypeChanging(TestPropertyDataType value); * #endregion * * // <Lots more Linq-generated code> * * [global::System.Data.Linq.Mapping.ColumnAttribute(Name="DATA_TYPE", Storage="_DataType", DbType="TinyInt NOT NULL", CanBeNull=false)] * public TestPropertyDataType DataType * { * get * { * return this._DataType; * } * set * { * if ((this._DataType != value)) * { * this.OnDataTypeChanging(value); * this.SendPropertyChanging(); * this._DataType = value; * this.SendPropertyChanged("DataType"); * this.OnDataTypeChanged(); * } * } * } * } * ***************************************************************************************************** */ public partial class TestActionPropertyMetadata { private byte _DataType; partial void OnDataTypeChanging(TestPropertyDataType value); [global::System.Data.Linq.Mapping.ColumnAttribute(Name = "DATA_TYPE", Storage = "_DataType", DbType = "TinyInt NOT NULL", CanBeNull = false)] public TestPropertyDataType DataType { get { return TestPropertyDataType.findByOrdinal(this._DataType); } set { if ((this.DataType != value)) { this.OnDataTypeChanging(value); this.SendPropertyChanging(); this._DataType = (byte)value.Ordinal; this.SendPropertyChanged("DataType"); this.OnDataTypeChanged(); } } } } } ```
How do I map custom types in Linq to Sql?
[ "", "c#", "linq-to-sql", "" ]
Basically this is a question how to access local scope handler. I trying to achieve something similar for global variable definition like: ``` window['newObject'] = "some string"; alert(newObject); ``` but for local scope. Right now only solution I have is using evals: ``` eval("var newObject='some string'"); ``` But this is really ugly solution... The best one would be like using some reference to local scope like in a window[] solution, but I never heard of any reference to local scope... Any ideas ? Example goes here: ``` function x(arg) { localScope[arg.name]=arg.value; alert(sex); } x({name:"sex", value:"Male"}); ```
Okey I found related question that is talking about what I need... [How can I access local scope dynamically in javascript?](https://stackoverflow.com/questions/598878/how-can-i-access-local-scope-dynamically-in-javascript) I just remember that in ECMA 262 is only one way to add dynamically local variables to scope using "with" statement (and eval of course), here are solution: ``` var x=function(obj) { with(obj) { alert(someObj); } } alert(typeof someObj); x ( {someObj:"yea"}) ; alert(typeof someObj); ```
What you're looking for is called the **call object**. But according to [this](http://books.google.com/books?id=2weL0iAfrEMC&pg=PA144&lpg=PA144&dq=javascript+%22call+object%22&source=bl&ots=_8ZDqEY5bL&sig=PoVXNKNZyxOXiMDT1v-w5gsDLEE&hl=en&ei=PUtbSr7EAZLEsQPSqOiDCw&sa=X&oi=book_result&ct=result&resnum=5), you can't access it directly, so you're out of luck.
Javascript local variable declare
[ "", "javascript", "variables", "definition", "local", "" ]
Does Javascript or jQuery have sometime like the "in" statement in Python? "a" in "dea" -> True Googling for the word *in* is hopeless :(
It does have an [`in` operator](https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Operators/Special_Operators#in) but is restricted to object keys only: ``` var object = { a: "foo", b: "bar" }; // print ab for (var key in object) { print(key); } ``` And you may also use it for checks like this one: ``` if ("a" in object) { print("Object has a property named a"); } ``` For string checking though you need to use the [indexOf()](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/String/indexOf) method: ``` if ("abc".indexOf("a") > -1) { print("Exists"); } ```
you would need to use indexOf e.g `"dea".indexOf("a");` will return 2 If its not in the item then it will return -1 I think thats what you are after.
"in" statement in Javascript/jQuery
[ "", "javascript", "jquery", "" ]
I have a javascript function that checks for a date range. Is there any way to check if a user has input a valid date in a textbox, regardless of format? ``` function checkEnteredDate() { var inputDate = document.getElementById('txtDate'); //if statement to check for valid date var formatDate = new Date(inputDate.value); if (formatDate > TodayDate) { alert("You cannot select a date later than today."); inputDate.value = TodayDate.format("MM/dd/yyyy"); } } ```
take a look at this library date.js <http://code.google.com/p/jqueryjs/source/browse/trunk/plugins/methods/date.js> it has a useful function called **fromString** which will try and convert a string (based on Date.format) to a valid date object. the function returns false if it doesn't create a valid date object - you can then try a different format before giving up if all return false. here are some example formats you could test for: ``` Date.format = 'dd mmm yyyy'; alert(Date.fromString("26 Jun 2009")); Date.format = 'mmm dd yyyy'; alert(Date.fromString("Jun 26 2009")); Date.format = 'dd/mm/yy'; alert(Date.fromString("26/06/09")); Date.format = 'mm/dd/yy'; alert(Date.fromString("06/26/09")); Date.format = 'yyyy-mm-dd'; alert(Date.fromString("2009-06-26")); ``` Josh
It is an awfully tricky problem to parse dates in an arbitrary format (as @Natrium points out). It's even more confusing when you consider that europe writes their dates as dd/mm/yyyy, so you can't tell if 2/7/09 is February 7th or July 2nd. Most people tackle this problem by either using a [datepicker](http://docs.jquery.com/UI/Datepicker) type of control from a javascript library, or by using dropdown boxes with set values for month, day, and year. ``` <select name="month"> <option value="1">January</option> <option value="2">February</option> ... <option value="12">December</option> </select> <select name="day"> <option value="1">1</option> <option value="2">2</option> ... <option value="31">31</option> </select> <select name="year"> <option value="2000">2000</option> <option value="2001">2001</option> ... <option value="2009">2009</option> </select> ```
How can I check if user passes a valid date in javascript?
[ "", ".net", "asp.net", "javascript", "html", "" ]
I have a problem trying the following with nHibernate: * Eager loading. * **Use selects** (here is my problem, I can only do this using joins) * Filtering children. Let's use an example where we have the `RichPerson` class that can have multiple: cars, houses, motorbikes and companies. All mapped to different entities with different tables. If I try the following: ``` session.CreateCriteria(typeof (RichPerson)) .Add(Expression.Eq("Id", someId)) .CreateCriteria("Cars") .Add(Expression.Eq("Brand","Ferrari") ``` nHibernate will make an inner join in order to retrieve the Cars. If RichPerson *some* Ferrari cars, the join will send duplicated data. Even with a `.SetFetchMode("Cars",FetchMode.Select)` nHibernate does a join. I guess the join is because I ask: the rich person with id X and with Ferrari cars. Thus, the join is needed. But I just want to preload (somehow) the Ferrari cars. And use them as `guy.Cars`. Uf! I don't know if I've expressed myself correctly. Anyway, thanks for your time reading this.
> I just want to preload (some how) the > Ferrari cars. And use them as > `guy.Cars`. It sounds like you have a lazy initialization problem here. Here's an interesting post about it: <http://nhforge.org/wikis/howtonh/lazy-loading-eager-loading.aspx> In short, it looks like your query is fine. But immediately after your query (while the session is still open), try adding: ``` NHibernateUtil.Initialize(guy.Cars); ``` That will force the initialization of your Cars entity, so you can immediately use it.
You have to do a join to test the criteria in a related table. There's no way around that. What you want to do is also pre-load the data in the related table, instantiating those objects immediately. ``` session.CreateCriteria(typeof (RichPerson)) .Add(Expression.Eq("Id", someId)) .SetFetchMode("Cars", FetchMode.Join) .CreateCriteria("Cars") .Add(Expression.Eq("Brand","Ferrari"); ``` This can also be done with HQL like: ``` "SELECT p FROM RichPerson p inner join fetch p.cars c where p.id=:id and c.brand=:brand" ```
Filter children without joins in nHibernate
[ "", "c#", "nhibernate", "" ]
I have a list of string values that I want add to a hashtable or other array that can be accessed by key/index but cannot implement it. I have this working how I want but its ugly ``` List<string> valueList = new List<string>(); valueList.Add("1"); valueList.Add("2"); valueList.Add("3"); Hashtable p = new Hashtable(); valueList.ForEach(delegate(string f) { p.Add(valueList.FindIndex(v => v == f), f); }); ``` EDIT: After James reminded me that a List will return values by index I went with a List and this is what I have ended up with ``` valueList.ForEach(f => sequenceList.Add(int.Parse(f))); ```
Try this: ``` valueList.ForEach(x => htable.Add(valueList.FindIndex(y => y == x), x)); ``` Although, there's really no reason *not* to use a `for` here ``` for (var index = 0; index < valueList.Count; index++) { htable.Add(index, valueList[index]); } ``` It's more lines of code, but it's more straightforward and will perform much better (findIndex is far less efficient than using the `index` from the for statement).
Even if it compiled, it wouldn't work - calling `GetEnumerator().Current` will always fail because it'll give you a *new* iterator positioned before the first item. What do you want the key for each item to be? If it's just its position within the list, I don't see the benefit that gives you over a list (which is already indexed by `int`). However, you can do it like this (assuming that `valueList` is a `List<string>`: ``` var dictionary = valueList.Select((item, index) => new { item, index }) .ToDictionary(x => x.index, x => x.item); ``` Adding it to an existing dictionary, I'd just do: ``` for (int i=0; i < valueList.Count; i++) { dictionary[i] = valueList[i]; } ``` Not *everything* has to be done with lambdas :) Note that this won't have quite the same effect as using `FindIndex` if you have repeated values.
Use List<T>ForEach to add element to HashTable
[ "", "c#", ".net", "hashtable", "ienumerable", "enumeration", "" ]
First thing i want to say that it's not an easy question to explain, so please be patient if it seems confusing. I have a set of classes like this ``` class Product { public static $static_type = 'product'; public static $static_table = 'product_table'; public function __construct($params) { //do some } } ``` and then there are the classes News, Events etc From another class i need to access to those static variables inside these classes in an iterative way. Something like: ``` //... if (Product::$static_type) { //do some } else if (News::$static_type) { //do other } //... ``` I want to trasform it in a cycle, like foreach in a way like this (it's not correct but makes sense to my question) ``` foreach ($classes as $class) { echo $class::$static_type; //brrrr, just to render the idea :) } ``` So i think about a singleton/static class that has a static method returning an array of my classes (not instantiated). Like this: ``` class Conf { public function __construct() { //nothing } public static function get_class_array () { //how to do this??? } } ``` and then ``` foreach (Conf::get_class_array() as $class) { echo $class::$static_type; //brrrr, just to render the idea :) } ``` How i can reach this? I don't want to instantiate Product, News or others in this case. Edit: eval is evil, i don't want to use it. No tricks with `get_declared_class`, if there's no way to solve I will use reflection, that i think it's the more elegant way among the mentioned :(. Edit: in the meantime i'll do the Conf::get\_class\_array() in this way ``` public static function get_class_array () { return array(new ReflectionClass('Prodotto'), new ReflectionClass('News')); } ``` and then call it here: ``` foreach (Conf::get_class_array() as $class) { echo $class->getStaticPropertyValue('static_type'); } ```
I don't think you can do this. You could however do one of these: ``` $properties = get_class_vars('Product'); echo $properties['static_type']; ``` or ``` $class = new ReflectionClass('product'); echo $class->getStaticPropertyValue('static_type'); ``` Note that in PHP 5.3 `echo $class::$static_type;` will work (<http://php.net/manual/en/language.oop5.static.php>)
Until 5.3.0, you can try this method. Create a container class as you suggested (we'll call it Conf to stick with what you had), and provide two methods for setting and getting applicable classes that you want to iterate over: ``` <?php class Conf { private static $instance; private $classes = array(); public static function getInstance() { if ( is_null(self::$instance) ) { self::$instance = new self(); } return self::$instance; } public function registerClass($className) { // Use associative index to maintain uniqueness $this->classes[$className] = $className; } public function getRegisteredClasses() { return $this->classes; } } ``` Some example classes and how to register them: ``` class X { public static $a = "catus"; public static $b = "pants"; } class Y { public static $a = "apples"; public static $b = "bananers"; } $conf = Conf::getInstance(); $conf->registerClass("X"); $conf->registerClass("Y"); ``` Now, to access and/or alter the static members, you can do something like the following (using RefelectionClass as tom Haigh pointed out): ``` $conf = Conf::getInstance(); echo "<pre>"; foreach ( $conf->getRegisteredClasses() as $class ) { $reflection = new ReflectionClass($class); echo "<hr/>Class: $class\n"; // Access example print_r( $reflection->getStaticProperties() ); // Alter example $reflection->setStaticPropertyValue("a", $reflection->getStaticPropertyValue("a") . "-modified" ); print_r( $reflection->getStaticProperties() ); } ``` If you have a class naming convention like `Com_Example_Static_X` and `Com_Example_Static_Y`, you can simplify `Conf->getRegisteredClasses()` (and even make it a static method if you so desire) by doing as n3rd suggested: ``` class Conf { // .... static public function getMatchingClasses($pattern="/^Com_Example_Static_.+$/") { $response = array(); foreach ( get_declared_classes() as $className ) { if ( preg_match($pattern, $className, $m) ) { $response[] = $className; } } return $response; } } ``` And, of course, update your `foreach` to: ``` foreach ( Conf::getMatchingClasses() as $class ) { // ... } ``` Hope that was helpful.
I need to collect an array of classes to call their static variables in php
[ "", "php", "oop", "static", "class", "" ]
First I would like to say that I am new to this site, never worked with Google Maps API and have an intermediate knowledge of JavaScript. **What I have done:** I put together a custom 'store locator' by adding locations to a Google 'my maps'. I then created a web page with a drop down menu and depending on the location you select from the drop down, it changes the the SRC for the iFrame holding the map. So when the page loads you see a larger scale map and by selecting specific locations, it will change the map to that specific location (zoom and crop). **What I need to do:** What I need to do now to complete this map is to add a 'search by zip code' which will allow the user to put in their zip code and have the web page return a list of the closest locations and hopefully their distances. Does anyone have an idea if I will be able to add the 'search by zip' functionality to my custom Google map? There really isn't much to my code to post, but if it will help, I'll gladly do so. The current functionality of my map works great, the problem is that I don't know where to begin adding the zip code search. Here is a link to the page that I am referring to: <http://74.53.82.155/store-locator.htm> Any help is appreciated. Thanks in advance, gnrlchaos
One option is to use the geonames web service that [returns locations from zip codes](http://www.geonames.org/export/web-services.html#postalCodeLookupJSON). Here's a quick example of how to use that web service with dojo. ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title></title> <link rel="stylesheet" type="text/css" href="layout.css"> <script type="text/javascript">var djConfig = { parseOnLoad: true }</script> <script type="text/javascript" src="../dojo-release-1.3.0/dojo/dojo.js"></script> </script> <script type="text/javascript"> dojo.require("dojo.io.script"); function getPlace() { var zip = dojo.byId('zipcode').value; console.log('zip is ', zip); //use country code to get results for a specific country //var gn_url = 'http://ws.geonames.org/postalCodeLookupJSON?postalcode=' + zip + '&country=US'; var gn_url = 'http://ws.geonames.org/postalCodeLookupJSON?postalcode=' + zip; console.log(gn_url); dojo.io.script.get({ url: gn_url, callbackParamName: "callback", load:function(response, io) { console.log('got json.'); console.dir(response); places = response.postalcodes; var infos = [] dojo.forEach(places, function(p, i) { infos[i] = p.placeName + ', ' + p.adminName1 + ', Lat: ' + p.lat + '; Long: ' + p.lng + '<br />'; }); dojo.byId('postalCode').innerHTML = infos.join(''); }, error:errorCb }); } function errorCb(type, data, evt){ debug(data); } </script> </head> <body class="tundra"> Enter a zip code: <input id="zipcode" type="text" /> <button onclick="getPlace(); return false;" value="Find Place.">Find Place.</button> <div>Places:</div><div id="postalCode"></div> </body> </html> ```
I don't know of any way to interact with an embedded Google Map in the way that you want. The best option would be to create your own map with the [Google Maps API](http://code.google.com/apis/maps/). Google has some great [documentation](http://code.google.com/apis/maps/documentation/introduction.html) and [examples](http://code.google.com/apis/maps/documentation/examples/index.html) to get you started.
Adding a search by zip code in a custom Google map
[ "", "javascript", "google-maps", "zipcode", "" ]
I have some code in a python string that contains extraneous empty lines. I would like to remove all empty lines from the string. What's the most pythonic way to do this? Note: I'm not looking for a general code re-formatter, just a quick one or two-liner. Thanks!
How about: ``` text = os.linesep.join([s for s in text.splitlines() if s]) ``` where `text` is the string with the possible extraneous lines?
``` "\n".join([s for s in code.split("\n") if s]) ``` Edit2: ``` text = "".join([s for s in code.splitlines(True) if s.strip("\r\n")]) ``` I think that's my final version. It should work well even with code mixing line endings. I don't think that line with spaces should be considered empty, but if so then simple s.strip() will do instead.
What's a quick one-liner to remove empty lines from a python string?
[ "", "python", "string", "line-endings", "" ]
I need a solution to a problem that has the table structure as listed below. Input 1 1/1/2009 Product1 2 2/2/2009 Product2 3 3/3/2009 Product3 4 4/4/2009 Product4 5 5/5/2009 Product5 Output 1 1/1/2009 2/2009 Product1 2 3/3/2009 4/4/2009 Product3 3 5/5/2009            Product5 I tried using CTE. But was not very sucessful in extracting the second row value. Appreciate any help. Thanks.
I don't know whether Russ' answer helps you at all. [Here is a link](http://support.microsoft.com/default.aspx?scid=KB;EN-US;q186133) to an article that explains how to add row numbers to the results of a query. (Search for "row\_number" to find the most likely example.) Once you have a query numbering the rows properly, you should be able to throw that into a CTE, then select from it twice -- once for odd numbers, then again for even numbers. Have each result return the even numbered value for joining (odd - 1 = even). At that point, you can join the results of the queries and get two products on one row.
You are looking for PIVOT: <http://msdn.microsoft.com/en-us/library/ms177410.aspx> Here is a best shot with the info you gave, I do something similar in one of my apps. You may need to use a dynamic SQL query if the pivot values change. ``` SELECT * FROM (SELECT [Date] ,[Product] FROM [Values] PIVOT (Max([Date]) FOR [Product] IN ('put date ranges here')) pvt ``` here is what mine looks like, this will allow for a set of different values. This is used in a form builder to retrive the values of user input ``` --//Get a comma delimited list of field names from the field table for this form DECLARE @FieldNames varchar(max) SELECT @FieldNames = COALESCE(@FieldNames + ', ', '') + '[' + CAST([FieldName] AS varchar(max)) + ']' FROM [Fields] WHERE [FormID] = @FormID --//create a dynamic sql pivot table that will bring our --//fields and values together to look like a real sql table DECLARE @SQL varchar(max) SET @SQL = 'SELECT * FROM (SELECT [Values].[RowID] ,[Fields].[FieldName] ,[Values].[Value] FROM [Values] INNER JOIN [Fields] ON [Fields].[FieldID] = [Values].[FieldID] WHERE [Fields].[FormID] = ''' + @FormID + ''') p PIVOT (Max([Value]) FOR [FieldName] IN (' + @FieldNames + ')) pvt' --//execute our sql to return the data EXEC(@SQL) ```
Need help with a SQL query that combines adjacent rows into a single row
[ "", "sql", "sql-server", "t-sql", "" ]
Update: Edited code example to use AutoA for the workaround (which was the original intention). Realized this after seeing rlbond's answer. I am trying to incorporate the usage of `auto_ptr` in my code based on recommendations from this thread: [Express the usage of C++ arguments through method interfaces](https://stackoverflow.com/questions/478482/express-the-usage-of-c-arguments-through-method-interfaces/478678) However, I am receiving some unexpected compile errors when compiling with Visual Studio 6.0. It has a problem when dealing with assignments/copies of a `std::auto_ptr` of a derived type to a `std::auto_ptr` of the base type. Is this an issue specific to my compiler? I know there's a strong recommendation to use Boost, but on my project it is not an option. If I still want to use `auto_ptr`, am I forced to use the workaround of calling `std::auto_ptr::release()`? From what I have encountered so far, this issue results in a compiler error, so it's easy enough to catch. However, could adopting the convention of calling release to assign to a 'auto\_ptr' of base type throughout expose me to any maintenance issues? Especially if built with a different compiler (assuming other compilers don't have this issue). If the `release()` workaround is not good due to my circumstances, should I fall back on using a different convention for describing transfer of ownership? The following is an example illustrating the problem. ``` #include "stdafx.h" #include <memory> struct A { int x; }; struct B : public A { int y; }; typedef std::auto_ptr<A> AutoA; typedef std::auto_ptr<B> AutoB; void sink(AutoA a) { //Some Code.... } int main(int argc, char* argv[]) { //Raws to auto ptr AutoA a_raw_to_a_auto(new A()); AutoB b_raw_to_b_auto(new B()); AutoA b_raw_to_a_auto(new B()); //autos to same type autos AutoA a_auto_to_a_auto(a_raw_to_a_auto); AutoB b_auto_to_b_auto(b_raw_to_b_auto); //raw derive to auto base AutoB b_auto(new B()); //auto derive to auto base AutoA b_auto_to_a_auto(b_auto); //fails to compile //workaround to avoid compile error. AutoB b_workaround(new B()); AutoA b_auto_to_a_auto_workaround(b_workaround.release()); sink(a_raw_to_a_auto); sink(b_raw_to_b_auto); //fails to compile return 0; } ``` Compile Error: ``` Compiling... Sandbox.cpp C:\Program Files\Microsoft Visual Studio\MyProjects\Sandbox\Sandbox.cpp(40) : error C2664: '__thiscall std::auto_ptr<struct A>::std::auto_ptr<struct A>(struct A *)' : cannot convert parameter 1 from 'class std::auto_ptr<struct B>' to 'struct A *' No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called C:\Program Files\Microsoft Visual Studio\MyProjects\Sandbox\Sandbox.cpp(47) : error C2664: 'sink' : cannot convert parameter 1 from 'class std::auto_ptr<struct B>' to 'class std::auto_ptr<struct A>' No constructor could take the source type, or constructor overload resolution was ambiguous Error executing cl.exe. Sandbox.exe - 2 error(s), 0 warning(s) ```
The first one is easy: ``` AutoA b_auto_to_a_auto(b_auto); //fails to compile ``` This fails on VC6 since it requires *member function templates*, something VC6's standard library doesn't support. It compiles on standard-compliant compilers, though. Workaround: ``` AutoA b_auto_to_a_auto( b_auto.release() ); ``` The second one is much more subtle :) ``` sink(b_raw_to_b_auto); //fails to compile ``` This one shouldn't compile on a standards-compliant compiler, because there's an implicit conversion going on. The compiler turns the above into ``` sink( std::auto_ptr<A>( b_raw_to_b_auto ) ); ``` however, `sink` takes `std::auto_ptr<A>` *by* *value*, so the temporary `std::auto_ptr<A>` created implicitly by the compiler needs to be *copy-constructed* into the argument to `sink`. Now, temporaries like that are *rvalues*. Rvalues don't bind to non-const references, but `std::auto_ptr`'s "copy constructor" takes it's argument by *non-const* reference. There you go - compile error. AFAICS this is standards-conforming behaviour. C++-0x "move semantics" will fix that by adding a "copy constructor" that takes an rvalue reference, though I'm not sure how much love `std::auto_ptr` will still receive in the future, what with `std::shared_ptr` and all. Workaround for the second one: ``` AutoA tmp( b_raw_to_b_auto/*.release() for VC6*/ ); sink( tmp ); ```
``` AutoA b_auto_to_a_auto(b_auto); //fails to compile sink(b_raw_to_b_auto); //fails to compile ``` Pavel Minaev points out something I actually didn't know: The first call should compile, because there is an implicit conversion from a B\* to an A\*. However, the second will not compile. The following will: ``` sink(static_cast<AutoA>(b_raw_to_b_auto)); ``` VC6 is notorious for not being very good with templates. I highly suggest you upgrade your code base to one that actually works and begin using RAII techniques, especially `boost::shared_ptr`. I know you say you can't, and I know it's difficult, but you will have virtually no memory leaks and many, many fewer bugs. Then again, maybe even without full functionality you can use `auto_ptr`?
std::auto_ptr Compile Issue in Visual Studio 6.0
[ "", "c++", "visual-studio-6", "" ]