Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I would like to delete an event from the Windows event log using C#. Can anyone point me in the right direction of how to achieve this?
I don't believe you can delete one specific event from the eventlog. It's all or nothing. If you want to get rid of one, you have to clear the whole log. Edit: The only thing you can do is [Clear the log](http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.clear.aspx). Well, okay, you can delete the entire log from the computer, if it's not Security, Application, or System, but you definitely can't remove one entry.
Easy :). But the removing is look like **removing item from array**, you need to make a copy of all array, except of item that you need to remove. There is example, how to "remove each of item from log where item have non even index". ``` using System; using System.Collections; using System.Diagnostics; using System.Threading; class EventLogEntryCollection_Item { /// <summary> /// Prints all. /// </summary> /// <param name="myEventLogEntryCollection">My event log entry collection.</param> private static void PrintAll(EventLogEntryCollection myEventLogEntryCollection) { for (int i = 0; i < myEventLogEntryCollection.Count; i++) { Console.WriteLine("The Message of the EventLog is :" + myEventLogEntryCollection[i].Message); } } /// <summary> /// Creates the new log message. /// </summary> /// <param name="LogName">Name of the log.</param> /// <param name="message">The message.</param> private static void CreateNewLogMessage(string LogName, string message) { EventLog myEventLog = new EventLog(); myEventLog.Source = LogName; myEventLog.WriteEntry(message); myEventLog.Close(); } /// <summary> /// Mains this instance. /// </summary> public static void Main() { try { // Check if the source exists. if (!EventLog.SourceExists("MySource")) { // Create the source. // An event log source should not be created and immediately used. // There is a latency time to enable the source, it should be created // prior to executing the application that uses the source. EventLog.CreateEventSource("MySource", "MySource"); Console.WriteLine("Creating EventSource"); Console.WriteLine("Exiting, execute the application a second time to use the source."); Thread.Sleep(2000); // The source is created. sleep to allow it to be registered. } string myLogName = EventLog.LogNameFromSourceName("MySource", "."); // Create a new EventLog object. EventLog myEventLog1 = new EventLog(); myEventLog1.Log = myLogName; //Create test messages. myEventLog1.Clear(); for (int i = 0; i < 20; i++) { CreateNewLogMessage("MySource", "The entry number is " + i); } // Obtain the Log Entries of "MyNewLog". EventLogEntryCollection myEventLogEntryCollection = myEventLog1.Entries; //myEventLog1.Close(); Console.WriteLine("The number of entries in 'MyNewLog' = " + myEventLogEntryCollection.Count); // Copy the EventLog entries to Array of type EventLogEntry. EventLogEntry[] myEventLogEntryArray = new EventLogEntry[myEventLogEntryCollection.Count]; myEventLogEntryCollection.CopyTo(myEventLogEntryArray, 0); Console.WriteLine("before deleting"); // Display the 'Message' property of EventLogEntry. PrintAll(myEventLogEntryCollection); myEventLog1.Clear(); Console.WriteLine("process deleting"); foreach (EventLogEntry myEventLogEntry in myEventLogEntryArray) { //Console.WriteLine("The LocalTime the Event is generated is " // + myEventLogEntry.TimeGenerated + " ; " + myEventLogEntry.Message); if (myEventLogEntry.Index % 2 == 0) { CreateNewLogMessage("MySource", myEventLogEntry.Message); } } Console.WriteLine("after deleting"); PrintAll(myEventLogEntryCollection); myEventLog1.Close(); } catch (Exception e) { Console.WriteLine("Exception:{0}", e.Message); } Console.ReadKey(); } } ```
C# Manage windows events
[ "", "c#", "windows", "" ]
The default databinding on `TextBox` is `TwoWay` and it commits the text to the property only when `TextBox` lost its focus. Is there any easy XAML way to make the databinding happen when I press the `Enter` key on the `TextBox`?. I know it is pretty easy to do in the code behind, but imagine if this `TextBox` is inside some complex `DataTemplate`.
You can make yourself a pure XAML approach by creating an [attached behaviour](http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx). Something like this: ``` public static class InputBindingsManager { public static readonly DependencyProperty UpdatePropertySourceWhenEnterPressedProperty = DependencyProperty.RegisterAttached( "UpdatePropertySourceWhenEnterPressed", typeof(DependencyProperty), typeof(InputBindingsManager), new PropertyMetadata(null, OnUpdatePropertySourceWhenEnterPressedPropertyChanged)); static InputBindingsManager() { } public static void SetUpdatePropertySourceWhenEnterPressed(DependencyObject dp, DependencyProperty value) { dp.SetValue(UpdatePropertySourceWhenEnterPressedProperty, value); } public static DependencyProperty GetUpdatePropertySourceWhenEnterPressed(DependencyObject dp) { return (DependencyProperty)dp.GetValue(UpdatePropertySourceWhenEnterPressedProperty); } private static void OnUpdatePropertySourceWhenEnterPressedPropertyChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e) { UIElement element = dp as UIElement; if (element == null) { return; } if (e.OldValue != null) { element.PreviewKeyDown -= HandlePreviewKeyDown; } if (e.NewValue != null) { element.PreviewKeyDown += new KeyEventHandler(HandlePreviewKeyDown); } } static void HandlePreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { DoUpdateSource(e.Source); } } static void DoUpdateSource(object source) { DependencyProperty property = GetUpdatePropertySourceWhenEnterPressed(source as DependencyObject); if (property == null) { return; } UIElement elt = source as UIElement; if (elt == null) { return; } BindingExpression binding = BindingOperations.GetBindingExpression(elt, property); if (binding != null) { binding.UpdateSource(); } } } ``` Then in your XAML you set the `InputBindingsManager.UpdatePropertySourceWhenEnterPressedProperty` property to the one you want updating when the `Enter` key is pressed. Like this ``` <TextBox Name="itemNameTextBox" Text="{Binding Path=ItemName, UpdateSourceTrigger=PropertyChanged}" b:InputBindingsManager.UpdatePropertySourceWhenEnterPressed="TextBox.Text"/> ``` (You just need to make sure to include an xmlns clr-namespace reference for "b" in the root element of your XAML file pointing to which ever namespace you put the InputBindingsManager in).
This is how I solved this problem. I created a special event handler that went into the code behind: ``` private void TextBox_KeyEnterUpdate(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { TextBox tBox = (TextBox)sender; DependencyProperty prop = TextBox.TextProperty; BindingExpression binding = BindingOperations.GetBindingExpression(tBox, prop); if (binding != null) { binding.UpdateSource(); } } } ``` Then I just added this as a KeyUp event handler in the XAML: ``` <TextBox Text="{Binding TextValue1}" KeyUp="TextBox_KeyEnterUpdate" /> <TextBox Text="{Binding TextValue2}" KeyUp="TextBox_KeyEnterUpdate" /> ``` The event handler uses its `sender` reference to cause it's own binding to get updated. Since the event handler is self-contained then it should work in a complex DataTemplate. This one event handler can now be added to all the textboxes that need this feature.
Bind TextBox on Enter-key press
[ "", "c#", ".net", "wpf", "xaml", "textbox", "" ]
Here is what I need to be able to do: I need to match the following tag: ``` <SPAN style="TEXT-DECORATION: underline">text sample</SPAN> ``` I need to replace the span with an html3 compliant tag, but keep the text in between. The final tag should look like this after replacement: ``` <u>text sample</u> ``` I'm just not good with regular expressions and can't seem to come up with the answer. Thank you in advance.
**Regular expressions are not designed for tag manipulation.** If you have any form of nesting going on, it gets messy. However, given the very simple example provided you could perhaps do this: ``` $MyString = preg_replace ( '/(?si)<SPAN\s+style\s*=\s*"TEXT-DECORATION:\s*underline;?"\s*>(.*?)<\/SPAN>/' , '<u>$1</u>' , $MyString ); ``` But this is flawed in many ways, and you are much better off using a tool designed for manipulating tags instead. **Have a look at [DOMDocument->loadHTML()](http://www.phpbuilder.com/manual/en/function.dom-domdocument-loadhtml.php) and [related functions](http://phpbuilder.com/manual/en/class.domdocument.php).**
DO NOT USE REGULAR EXPRESSIONS TO PARSE HTML [**do not use regular expressions to parse HTML**](http://wiki.tcl.tk/4164) *do not use regular expressions to parse HTML* [***do not use regular expressions to parse HTML***](http://www.codinghorror.com/blog/archives/001016.html) [do not use regular expressions to parse HTML](http://blog.mikeseth.com/index.php?/archives/1-For-the-2,295,485th-time-DO-NOT-PARSE-HTML-WITH-REGULAR-EXPRESSIONS.html) [do not use regular expressions to parse HTML](http://kore-nordmann.de/blog/do_NOT_parse_using_regexp.html) do you need more clarification? Use DomDocument::LoadFromHTML ;)
I need a php regular expression that replaces one tag with another
[ "", "php", "html", "regex", "html-manipulation", "" ]
I'm playing around, trying to write some code to use the [tr.im](http://www.programmableweb.com/api/tr.im) APIs to shorten a URL. After reading <http://docs.python.org/library/urllib2.html>, I tried: ``` TRIM_API_URL = 'http://api.tr.im/api' auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password(realm='tr.im', uri=TRIM_API_URL, user=USERNAME, passwd=PASSWORD) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) response = urllib2.urlopen('%s/trim_simple?url=%s' % (TRIM_API_URL, url_to_trim)) url = response.read().strip() ``` response.code is 200 (I think it should be 202). url is valid, but the basic HTTP authentication doesn't seem to have worked, because the shortened URL isn't in my list of URLs (at [http://tr.im/?page=1](http://ttp://tr.im/?page=1)). After reading <http://www.voidspace.org.uk/python/articles/authentication.shtml#doing-it-properly> I also tried: ``` TRIM_API_URL = 'api.tr.im/api' password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() password_mgr.add_password(None, TRIM_API_URL, USERNAME, PASSWORD) auth_handler = urllib2.HTTPBasicAuthHandler(password_mgr) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) response = urllib2.urlopen('http://%s/trim_simple?url=%s' % (TRIM_API_URL, url_to_trim)) url = response.read().strip() ``` But I get the same results. (response.code is 200 and url is valid, but not recorded in my account at <http://tr.im/>.) If I use query string parameters instead of basic HTTP authentication, like this: ``` TRIM_API_URL = 'http://api.tr.im/api' response = urllib2.urlopen('%s/trim_simple?url=%s&username=%s&password=%s' % (TRIM_API_URL, url_to_trim, USERNAME, PASSWORD)) url = response.read().strip() ``` ...then not only is url valid but it's recorded in my tr.im account. (Though response.code is still 200.) There must be something wrong with my code though (and not tr.im's API), because ``` $ curl -u yacitus:xxxx http://api.tr.im/api/trim_url.json?url=http://www.google.co.uk ``` ...returns: ``` {"trimpath":"hfhb","reference":"nH45bftZDWOX0QpVojeDbOvPDnaRaJ","trimmed":"11\/03\/2009","destination":"http:\/\/www.google.co.uk\/","trim_path":"hfhb","domain":"google.co.uk","url":"http:\/\/tr.im\/hfhb","visits":0,"status":{"result":"OK","code":"200","message":"tr.im URL Added."},"date_time":"2009-03-11T10:15:35-04:00"} ``` ...and the URL does appear in my list of URLs on [http://tr.im/?page=1](http://ttp://tr.im/?page=1). And if I run: ``` $ curl -u yacitus:xxxx http://api.tr.im/api/trim_url.json?url=http://www.google.co.uk ``` ...again, I get: ``` {"trimpath":"hfhb","reference":"nH45bftZDWOX0QpVojeDbOvPDnaRaJ","trimmed":"11\/03\/2009","destination":"http:\/\/www.google.co.uk\/","trim_path":"hfhb","domain":"google.co.uk","url":"http:\/\/tr.im\/hfhb","visits":0,"status":{"result":"OK","code":"201","message":"tr.im URL Already Created [yacitus]."},"date_time":"2009-03-11T10:15:35-04:00"} ``` Note code is 201, and message is "tr.im URL Already Created [yacitus]." I must not be doing the basic HTTP authentication correctly (in either attempt). Can you spot my problem? Perhaps I should look and see what's being sent over the wire? I've never done that before. Are there Python APIs I can use (perhaps in pdb)? Or is there another tool (preferably for Mac OS X) I can use?
This seems to work really well (taken from another thread) ``` import urllib2, base64 request = urllib2.Request("http://api.foursquare.com/v1/user") base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '') request.add_header("Authorization", "Basic %s" % base64string) result = urllib2.urlopen(request) ```
Really cheap solution: ``` urllib.urlopen('http://user:xxxx@api.tr.im/api') ``` (which you may decide is not suitable for a number of reasons, like security of the url) [Github API example](https://developer.github.com/v3/auth/#via-oauth-tokens): ``` >>> import urllib, json >>> result = urllib.urlopen('https://personal-access-token:x-oauth-basic@api.github.com/repos/:owner/:repo') >>> r = json.load(result.fp) >>> result.close() ```
Python urllib2, basic HTTP authentication, and tr.im
[ "", "python", "http", "authentication", "" ]
I'm working on an inter-site single-sign-on project and have had a pretty little problem dropped in my lap. When a user logs out of the "parent" site, a particular page needs to be loaded in the popup window containing the "child" site. However, I can't store a reference to the return value of `window.open(…)`, because the user must be allowed to navigate wherever they like on each site before logging out. This would be easy if I could assume that the child site is always open, as another `window.open(…)` to the same named window would change its URL. However, the popup **cannot** be caused to appear if it isn't already open (not all users have access to the child site). I think this gives me two conflicting scenarios. When the user visits the child site: 1. User logs in to parent site. 2. User clicks link for child site 3. Child site appears in a window named "child\_popup". 4. User browses far and wide in the parent site, forgetting that the child window exists. 5. User logs out of parent site. 6. Child popup is redirected to the child site's logout page. And when the user does not or cannot visit the child site: 1. User logs in to parent site. 2. User browses far and wide in the parent site. 3. User logs out of the parent site. 4. No popup should appear! So my limitations are: * I cannot store a reference to the window in JS, as the user may navigate to any number of pages between visiting the child site and logging out. * I have **zero** control over the contents of the child site (my employer runs the parent site). * The parent site cannot be converted to frames to provide a "global" JS scope. :-) I was not able to find any relevant resources on Google or SO. Is there a way to accomplish this?
We weren't able to find a way to detect whether the child-site window is *still* open, but we came up with a workaround which satisfied our business requirements folks: 1. Set cookie A from parent site when launching child popup. 2. Set cookie B from child site on every page load. 3. Clear cookie B from child site on every page *un*load. 4. When logging out of parent site: 1. If cookie A is set, clear it and close local connection to child site. 2. If cookie B is set, clear it and open child logout page in popup.
Yes, you can, subject to one important restriction. It hinges on the following behaviour: 1. the first 2 parameters of window.open are a URL and a window name 2. window.open returns a reference to a window 3. if a window is already open with the specified name, then a reference to that window is returned rather than a reference to a new window 4. ***If the URL is NULL, an existing window won't navigate to a new page*** This means that you can get a reference to an existing window, without losing the page that window has open. However, if a window *doesn't* exist with that name it *will* be opened. We used this approach at <http://carbonlogic.co.uk/> but because of a Flash Player issue the contents of the popup aren't working properly at the moment
Is it possible to determine if a named window is open in JavaScript?
[ "", "javascript", "" ]
I have a string in the format: ``` t='@abc @def Hello this part is text' ``` I want to get this: ``` l=["abc", "def"] s='Hello this part is text' ``` I did this: ``` a=t[t.find(' ',t.rfind('@')):].strip() s=t[:t.find(' ',t.rfind('@'))].strip() b=a.split('@') l=[i.strip() for i in b][1:] ``` It works for the most part, but it fails when the text part has the '@'. Eg, when: ``` t='@abc @def My email is red@hjk.com' ``` it fails. The @names are there in the beginning and there can be text after @names, which may possibly contain @. Clearly I can append initally with a space and find out first word without '@'. But that doesn't seem an elegant solution. What is a pythonic way of solving this?
Building unashamedly on MrTopf's effort: ``` import re rx = re.compile("((?:@\w+ +)+)(.*)") t='@abc @def @xyz Hello this part is text and my email is foo@ba.r' a,s = rx.match(t).groups() l = re.split('[@ ]+',a)[1:-1] print l print s ``` prints: > ['abc', 'def', 'xyz'] > Hello this part is text and my email is foo@ba.r --- Justly called to account by [hasen j](https://stackoverflow.com/users/35364/hasen-j), let me clarify how this works: ``` /@\w+ +/ ``` matches a single tag - @ followed by at least one alphanumeric or \_ followed by at least one space character. + is greedy, so if there is more than one space, it will grab them all. To match any number of these tags, we need to add a plus (one or more things) to the pattern for tag; so we need to group it with parentheses: ``` /(@\w+ +)+/ ``` which matches one-or-more tags, and, being greedy, matches all of them. However, those parentheses now fiddle around with our capture groups, so we undo that by making them into an anonymous group: ``` /(?:@\w+ +)+/ ``` Finally, we make that into a capture group and add another to sweep up the rest: ``` /((?:@\w+ +)+)(.*)/ ``` A last breakdown to sum up: ``` ((?:@\w+ +)+)(.*) (?:@\w+ +)+ ( @\w+ +) @\w+ + ``` --- Note that in reviewing this, I've improved it - \w didn't need to be in a set, and it now allows for multiple spaces between tags. Thanks, hasen-j!
``` t='@abc @def Hello this part is text' words = t.split(' ') names = [] while words: w = words.pop(0) if w.startswith('@'): names.append(w[1:]) else: break text = ' '.join(words) print names print text ```
String separation in required format, Pythonic way? (with or w/o Regex)
[ "", "regex", "string", "format", "python", "" ]
I'm trying to implement optional parameters in a stored procedure that I have but I am running into a problem. Here's a simplified query to illustrate the issue: ``` SET ANSI_NULLS OFF DECLARE @MiddleName VARCHAR(20); SET @MiddleName = NULL; SELECT * FROM [Customer] WHERE [LastName] = 'Torres' AND [MiddleName] = COALESCE(@MiddleName, [MiddleName]) ``` When I run this query I need to get one row back because one Torres has NULL in the [MiddleName] column. But the query returns zero rows. Using IFNULL() produces the same result. From researching COALESCE, I was under the impression that NULL would be returned if all expressions are NULL. As I am not a SQL expert I assume that I am missing something, but what is it..... Thanks in advance for any help.
The problem is that in sql, "WHERE Null = Null" will never return any rows since Null does not equal itself. You have to do ``` SELECT * FROM [Customer] WHERE [LastName] = 'Torres' AND ( @MiddleName IS NULL OR [MiddleName] = @MiddleName ) ```
You state you are looking for the query to return the row where the field MiddleName is NULL. Unfortunately (NULL = NULL) does not return true, it returns NULL. You need something like... ``` SELECT * FROM [Customer] WHERE [LastName] = 'Torres' AND ([MiddleName] = @MiddleName OR @MiddleName IS NULL) ```
SQL Coalesce in WHERE clause
[ "", "sql", "sql-server", "" ]
I'm behind a router, I need a simple command to discover my public ip (instead of googling what's my ip and clicking one the results) Are there any standard protocols for this? I've heard about STUN but I don't know how can I use it? P.S. I'm planning on writing a short python script to do it
**EDIT**: curlmyip.com is no longer available. (thanks maxywb) **Original Post**: As of writing this post, curlmyip.com works. From the command line: ``` curl curlmyip.com ``` It's a third-party website, which may or may not be available a couple years down the road. But for the time being, it seems pretty simple and to the point.
This may be the easiest way. Parse the output of the following commands: 1. run a traceroute to find a router that is less than 3 hops out from your machine. 2. run ping with the option to record the source route and parse the output. The first IP address in the recorded route is your public one. For example, I am on a Windows machine, but the same idea should work from unix too. ``` > tracert -d www.yahoo.com Tracing route to www-real.wa1.b.yahoo.com [69.147.76.15] over a maximum of 30 hops: 1 <1 ms <1 ms <1 ms 192.168.14.203 2 * * * Request timed out. 3 8 ms 8 ms 9 ms 68.85.228.121 4 8 ms 8 ms 9 ms 68.86.165.234 5 10 ms 9 ms 9 ms 68.86.165.237 6 11 ms 10 ms 10 ms 68.86.165.242 ``` The 68.85.228.121 is a Comcast (my provider) router. We can ping that: ``` > ping -r 9 68.85.228.121 -n 1 Pinging 68.85.228.121 with 32 bytes of data: Reply from 68.85.228.121: bytes=32 time=10ms TTL=253 Route: 66.176.38.51 -> 68.85.228.121 -> 68.85.228.121 -> 192.168.14.203 ``` Voila! The 66.176.38.51 is my public IP. **Python code to do this** (hopefully works for py2 or py3): ``` #!/usr/bin/env python def natIpAddr(): # Find next visible host out from us to the internet hostList = [] resp, rc = execute("tracert -w 100 -h 3 -d 8.8.8.8") # Remove '-w 100 -h d' if this fails for ln in resp.split('\n'): if len(ln)>0 and ln[-1]=='\r': ln = ln[:-1] # Remove trailing CR if len(ln)==0: continue tok = ln.strip().split(' ')[-1].split('.') # Does last token look like a dotted IP address? if len(tok)!=4: continue hostList.append('.'.join(tok)) if len(hostList)>1: break # If we found a second host, bail if len(hostList)<2: print("!!tracert didn't work, try removing '-w 100 -h 3' options") # Those options were to speed up tracert results else: resp, rc = execute("ping -r 9 "+hostList[1]+" -n 1") ii = resp.find("Route: ") if ii>0: return resp[ii+7:].split(' ')[0] return none def execute(cmd, showErr=True, returnStr=True): import subprocess if type(cmd)==str: cmd = cmd.split(' ') # Remove ' ' tokens caused by multiple spaces in str cmd = [xx for xx in cmd if xx!=''] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = proc.communicate() if type(out)==bytes: # Needed for python 3 (stupid python) out = out.decode() try: err = err.decode() except Exception as ex: err = "!!--"+str(type(ex))+"--!!" if showErr and len(err)>0: out += err if returnStr and str(type(out))=="<type 'unicode'>": # Trying to make 'out' be an ASCII string whether in py2 or py3, sigh. out = out.encode() # Convert UNICODE (u'xxx') to string return out, proc.returncode if __name__ == "__main__": print("(This could take 30 sec)") print(natIpAddr()) ``` Use it from the command line (on Windows) or from a python program: ``` import natIpAddr myip = natIpAddr.natIpAddr() print(myip) ```
Discovering public IP programmatically
[ "", "python", "ip-address", "tcp", "" ]
In the book I'm reading at the moment ([C++ Without Fear](https://rads.stackoverflow.com/amzn/click/com/0321246950)) it says that if you don't declare a default constructor for a class, the compiler supplies one for you, which "zeroes out each data member". I've experimented with this, and I'm not seeing any zeroing -out behaviour. I also can't find anything that mentions this on Google. Is this just an error or a quirk of a specific compiler?
If you do not define a constructor, the compiler will define a default constructor for you. ## Construction The implementation of this ### default constructor is: * default construct the base class (if the base class does not have a default constructor, this is a compilation failure) * default construct each member variable in the order of declaration. (If a member does not have a default constructor, this is a compilation failure). Note: The POD data (int,float,pointer, etc.) do not have an explicit constructor but the default action is to do nothing (in the vane of C++ philosophy; we do not want to pay for something unless we explicitly ask for it). ## Copy If no destructor/copy Constructor/Copy Assignment operator is defined the compiler builds one of those for you (so a class always has a destructor/Copy Constructor/Assignment Operator (unless you cheat and explicitly declare one but don't define it)). The default implementation is: ### Destructor: * If user-defined destructor is defined, execute the code provided. * Call the destructor of each member in reverse order of declaration * Call the destructor of the base class. ### Copy Constructor: * Call the Base class Copy Constructor. * Call the copy constructor for each member variable in the order of declaration. ### Copy Assignment Operator: * Call the base class assignment operator * Call the copy assignment operator of each member variable in the order of declaration. * Return a reference to this. Note Copy Construction/Assignment operator of POD Data is just copying the data (Hence the shallow copy problem associated with RAW pointers). ## Move If no destructor/copy Constructor/Copy Assignment/Move Constructor/Move Assignment operator is defined the compiler builds the move operators for you one of those for you. The default implementation is: Implicitly-declared move constructor If no user-defined move constructors are provided for a class type (struct, class, or union), and all of the following is true: ### Move Constructor: * Call the Base class Copy Constructor. * Call the move constructor for each member variable in the order of declaration. ### Move Assignment Operator: * Call the base class assignment operator * Call the move assignment operator of each member variable in the order of declaration. * Return a reference to this.
I think it's worth pointing out that the default constructor will only be created by the compiler if you provide **no constructor whatsoever**. That means if you only provide one constructor that takes an argument, the compiler will **not** create the default no-arg constructor for you. The zeroing-out behavior that your book talks about is probably specific to a particular compiler. I've always assumed that it can vary and that you should explicitly initialize any data members.
Is there an implicit default constructor in C++?
[ "", "c++", "constructor", "" ]
I want to backup a table saving the copy in the same database with another name. I want to do it programatically using .NET 2.0 (preferably C#). Someone can point me what should I do?
Just send this query to the server: ``` SELECT * INTO [BackupTable] FROM [OriginalTable] ``` This will create the backup table from scratch (an error will be thrown if it already exists). For large tables be prepared for it to take a while. This should mimic datatypes, collation, and NULLness (NULL or NOT NULL), but will not copy indexes, keys, or similar constraints. If you need help sending sql queries to the database, that's a different issue.
One way to do this would be to simply execute a normal query this way using INTO in SQL: ``` SELECT * INTO NewTableName FROM ExistingTableName ``` This automatically creates a new table and inserts the rows of the old one. Another way would be to use **SqlBulkCopy** from the `System.Data.SqlClient` namespace. There is a nice CodeProject article explaining how to do this: [SQL Bulk Copy with C#.Net](http://www.codeproject.com/KB/database/SqlBulkCopy.aspx) > Programmers usually need to transfer > production data for testing or > analyzing. The simplest way to copy > lots of data from any resources to SQL > Server is BulkCopying. .NET Framework > 2.0 contains a class in ADO.NET "System.Data.SqlClient" namespace: > SqlBulkCopy. The bulk copy operation > usually has two separated phases. > > In the first phase you get the source > data. The source could be various data > platforms such as Access, Excel, SQL.. > You must get the source data in your > code wrapping it in a DataTable, or > any DataReader class which implements > IDataReader. After that, in the second > phase, you must connect the target SQL > Database and perform the bulk copy > operation. > > The bulk copy operation in .Net is a > very fast way to copy large amount of > data somewhere to SQL Server. The > reason for that is the Bulkcopy Sql > Server mechanism. Inserting all data > row by row, one after the other is a > very time and system resources > consuming. But the bulkcopy mechanism > process all data at once. So the data > inserting becomes very fast. The code is pretty straightforward: ``` // Establishing connection SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder(); cb.DataSource = "SQLProduction"; cb.InitialCatalog = "Sales"; cb.IntegratedSecurity = true; SqlConnection cnn = new SqlConnection(cb.ConnectionString); // Getting source data SqlCommand cmd = new SqlCommand("SELECT * FROM PendingOrders",cnn); cnn.Open(); SqlDataReader rdr = cmd.ExecuteReader(); // Initializing an SqlBulkCopy object SqlBulkCopy sbc = new SqlBulkCopy("server=.;database=ProductionTest;" + "Integrated Security=SSPI"); // Copying data to destination sbc.DestinationTableName = "Temp"; sbc.WriteToServer(rdr); // Closing connection and the others sbc.Close(); rdr.Close(); cnn.Close(); ```
How to duplicate a SQL Server 2000 table programatically using .NET 2.0?
[ "", "c#", ".net", "sql-server", "sql-server-2000", "" ]
if i want to test the result of an expression and the function would return NaN how would i check that? examples: `$('amount').value.toInt()!='NaN'` ^ does not work and i assume that the returned value is not a string, `$('amount').value.toInt()!=NaN` ^ doesnt seem to work either and this one seems obvious so how do i check wether the returned value is not a number?
The NaN value is defined to be unequal to everything, including itself. Test if a value is NaN with the [`isNaN()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN) function, appropriately enough. (ECMAScript 6 adds a [`Number.isNan()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN) function with different semantics for non-number arguments, but it's not supported in all browsers yet as of 2015). There are two built-in properties available with a NaN value: the global [`NaN`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN) property (i.e. `window.NaN` in browsers), and [`Number.NaN`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN). It is *not* a language keyword. In older browsers, the `NaN` property could be overwritten, with potentially confusing results, but with the [ECMAScript 5 standard it was made non-writable](http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.1.1). * As @some pointed out in the comments, there is also the global function [isFinite()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite) which may be useful.
the best way to check the result of numeric operation against NaN is to aproach this way , example: ``` var x = 0; var y = 0; var result = x/y; // we know that result will be NaN value // to test if result holds a NaN value we should use the following code : if(result !=result){ console.log('this is an NaN value'); } ``` and it's done. the trick is that NaN can't be compared to any other value even with it self(NaN !=NaN is always true so we can take advantage of this and compare result against itself) **this is JavaScript(a good and bizarre language)**
what is the reserved keyword for NaN in javascript?
[ "", "javascript", "nan", "" ]
I'm trying to work on a kind of code generator to help unit-testing an legacy C/C++ blended project. I don't find any kind of independent tool can generate stub code from declaration. So I decide to build one, it shouldn't be that hard. Please, anybody can point me a standard grammar link, better described by yacc language. Hope I'm not reinventing wheel, please help me out in that case. Best Regards, Kevin
From the [C++ FAQ Lite](http://www.parashift.com/c++-faq-lite/): [38.11 Is there a yacc-able C++ grammar?](http://www.parashift.com/c++-faq-lite/compiler-dependencies.html#faq-38.11) > The primary yacc grammar you'll want > is from Ed Willink. Ed believes his > grammar is fully compliant with [the > ISO/ANSI C++ standard](http://www.parashift.com/c++-faq-lite/big-picture.html#faq-6.13), however he > doesn't warrant it: "the grammar has > not," he says, "been used in anger." > You can get [the grammar without > action routines](http://www.computing.surrey.ac.uk/research/dsrg/fog/CxxGrammar.y) or [the grammar > with dummy action routines](http://www.computing.surrey.ac.uk/research/dsrg/fog/CxxTester.y). You > can also get [the corresponding > lexer](http://www.computing.surrey.ac.uk/research/dsrg/fog/CxxLexer.l). For those who are > interested in how he achieves a > context-free parser (by pushing all > the ambiguities plus a small number of > repairs to be done later after parsing > is complete), you might want to read > chapter 4 of [his thesis](http://www.computing.surrey.ac.uk/research/dsrg/fog/FogThesis.pdf). > > There is also a very old yacc grammar > that doesn't support templates, > exceptions, nor namespaces; plus it > deviates from the core language in > some subtle ways. You can get that > grammar [here](http://www.empathy.com/pccts/roskind.zip) or [here](http://srawgw.sra.co.jp/.a/pub/cmd/c++grammar2.0.tar.gz).
I've recently found some grammar files for C++ (C++ 1998: **ISO/IEC 14882:1998** and C++ 2008: **ISO/IEC SC22/WG21 N2723=08-0233**) at the [grammarware website](http://grammarware.github.com/zoo/#cpp). The grammars are represented in **Enahnced BNF, DMS BNF, BGF, SDF and Rascal** notation. It's a pity, though, that the C++ grammars don't seem to get updated (no C++2003 or C++11).
Where can I find standard BNF or YACC grammar for C++ language?
[ "", "c++", "yacc", "bnf", "" ]
I'm a beginner with PHP, I was exposed to processed HTML forms and I'm learning how to use it to do more and more... I'm using this function (and based on Google so are a lot of people) but I really want to understand what it's doing.... ``` function pt_register() { $num_args = func_num_args(); $vars = array(); if ($num_args >= 2) { $method = strtoupper(func_get_arg(0)); if (($method != 'SESSION') && ($method != 'GET') && ($method != 'POST') && ($method != 'SERVER') && ($method != 'COOKIE') && ($method != 'ENV')) { die('The first argument of pt_register must be one of the following: GET, POST, SESSION, SERVER, COOKIE, or ENV'); } $varname = "HTTP_{$method}_VARS"; global ${$varname}; for ($i = 1; $i < $num_args; $i++) { $parameter = func_get_arg($i); if (isset(${$varname}[$parameter])) { global $$parameter; $$parameter = ${$varname}[$parameter]; } } } else { die('You must specify at least two arguments'); } } ``` Can anyone walk through this in English for me?
It looks like it's trying to be a replacement for register\_globals ``` function pt_register() { // Look at the arguments passed in... $num_args = func_num_args(); $vars = array(); // .. we need at least 2 arguments if ($num_args >= 2) { // $method is the middle part of name of one of PHPs old-style variables $method = strtoupper(func_get_arg(0)); if (($method != 'SESSION') && ($method != 'GET') && ($method != 'POST') && ($method != 'SERVER') && ($method != 'COOKIE') && ($method != 'ENV')) { die('The first argument of pt_register must be one of the following: GET, POST, SESSION, SERVER, COOKIE, or ENV'); } // $varname is the whole name of the variable $varname = "HTTP_{$method}_VARS"; // Make the global variable (for example HTTP_SESSION_VARS) accessible from this function // ${$varname} is using a technique called "variable variables" // If $varname == "HTTP_SESSION_VARS" then $$varname (or ${$varname}) is the same as $HTTP_SESSION_VARS global ${$varname}; // For each argument after the method for ($i = 1; $i < $num_args; $i++) { $parameter = func_get_arg($i); // If the parameter exists in the global variable... if (isset(${$varname}[$parameter])) { // .. make it global... global $$parameter; // ... and set its value $$parameter = ${$varname}[$parameter]; } } } else { die('You must specify at least two arguments'); } } ``` So, a for example: `pt_register('SESSION', 'foo');` does, in effect ``` function example() { global $HTTP_SESSION_VARS; global $foo; $foo = $HTTP_SESSION_VARS['foo']; } ``` IMHO, this script is outdated and evil! The superglobals $\_SESSION etc mean you shouldn't be doing this
Ow my, That looks like a code snipped that replaces the deprecated [register\_globals](http://www.php.net/register_globals) setting. Back in PHP4, all kind over user generated arguments where directly created as variables in your normal variable scope. In plain English this means that a call to `index.php?test=helloWorld` would result in ``` <?php echo "$test<br/>"; ?> ``` outputting: ``` helloWorld<br/> ``` This is considered to be a mayor chance for programmers to shoot themselves in the foot. it has since been abolished. And for good reason. Consider the following code: ``` <?php if ( isAuthorised($userId, $sessionId) ) { $hasAccess = true; } // some lines // of code... if ( $hasAccess ) { echo 'sensitive information'; } ?> ``` and what whould happen if you would call this with `index.php?hasAccess=1` That's right, the evil person calling your script has just gained access to the part that is for authorised users only. **In summary** It is a function that mimics the behaviour of functionality that is no longer used (since PHP5) because it was considered a *major* security risk. Instead of using the code above, you should access the user supplied arguments like ``` <?php echo $_GET['test'].'<br />'; ?> ``` Hope this helps :)
PHP Function pt_register
[ "", "php", "" ]
I need to find a select statement that will return either a record that matches my input exactly, or the closest match if an exact match is not found. Here is my select statement so far. ``` SELECT * FROM [myTable] WHERE Name = 'Test' AND Size = 2 AND PType = 'p' ORDER BY Area DESC ``` What I need to do is find the closest match to the 'Area' field, so if my input is 1.125 and the database contains 2, 1.5, 1 and .5 the query will return the record containing 1. My SQL skills are very limited so any help would be appreciated.
get the difference between the area and your input, take absolute value so always positive, then order ascending and take the first one ``` SELECT TOP 1 * FROM [myTable] WHERE Name = 'Test' and Size = 2 and PType = 'p' ORDER BY ABS( Area - @input ) ```
something horrible, along the lines of: ``` ORDER BY ABS( Area - 1.125 ) ASC LIMIT 1 ``` Maybe?
Find closest numeric value in database
[ "", "sql", "" ]
I have created some PHP-based intranet resources that require users to log in. The users create their own logins, and I verify that they are logged in using a cookie. I've been asked if I can tie that login to their Windows login instead. My initial response was "a web page cannot access your Windows login - that would be a security risk." But one of our departments uses Sharepoint, and it does in fact tie itself to the Windows login. How is that done? Can I do it in PHP? If so, why is it not a horrible security hole?
What you are looking for is NTLM authentication against the PHP website, which is perfectly doable but seems there is no single way in PHP to do it. Have a look at <http://siphon9.net/loune/2007/10/simple-lightweight-ntlm-in-php/> You also need to add the sites to your trusted sites in IE (or the equivalent in whichever browser you are using) and in the settings for trusted sites, turn on 'send current username and password'. Its not a horrible security hole because the credentials are not sent en clair over the wire, and the end user has specifically told the browser to send credentials to the website in question.
PHP has LDAP support, so you can access Windows' Active Directory There is this project on SourceForge: [adLDAP](http://adldap.sourceforge.net/) - "LDAP Authentication with PHP for Active Directory"
Can a PHP intranet share Windows logins?
[ "", "php", "windows", "sharepoint", "authentication", "" ]
This question is complicated so examples would work best...I have the following table on ODBC, not SQL server Management ``` NAME SEQNUM JOHN 2 JOHN 4 JOHN 7 MARY 12 MIKE 4 MIKE 9 PETER 7 PETER 12 ``` So, i want to pull back one name with the lowest seqNum... ``` NAME SEQNUM JOHN 2 MARY 12 MIKE 4 PETER 7 ``` This data will not work with `SELECT (MIN(SEQNUM))`. That returns a number. I want the actual data to put in my dataset. Does ANYONE know how to do that?
``` SELECT t1.* FROM yourtable t1 LEFT OUTER JOIN yourtable t2 ON (t1.name = t2.name AND t1.seqnum > t2.seqnum) WHERE t2.seqnum IS NULL; ``` --- Re. Dems' comment: If you simply use `GROUP BY name` then your select-list can only include `name` and the aggregate function `MIN()`. It's often the case that you really want the whole row where the minimum value occurs per group. If you use the `TOP` solution (or `LIMIT` if you use MySQL, PostgreSQL, SQLite), then you can't get the minimum for multiple groups based on `name`, you can only get the minimum for one `name`. I read between the lines of the OP's question and guessed that they want the whole row, that there are more columns than those shown in the question (there always are), and that the desired query should return results for multiple names, not just one. --- Re. SquareCog's comment: The solution you suggest is also a join: ``` SELECT t1.* FROM yourtable t1 JOIN (SELECT name, MIN(seqnum) AS seqnum FROM yourtable GROUP BY name) t2 USING (name, seqnum); ``` However, this solution probably can't use indexes to evaluate the join, whereas the solution I gave can.
``` select Name, MIN(SEQNUM) from TABLE Group By Name ```
How do I Display one Row for the lowest number of a column?
[ "", "sql", "odbc", "" ]
I am writing an API in C# and I want to provide both synchronous and asynchronous versions of the publicly available methods. For example, if I have the following function: ``` public int MyFunction(int x, int y) { // do something here System.Threading.Thread.Sleep(2000); return x * y; } ``` how can I create an asynchronous version of the above method (perhaps BeginMyFunction and EndMyFunction)? Are there different ways to achieve the same result, and what are the benefits of the various approaches?
The generic approach is to use a `delegate`: ``` IAsyncResult BeginMyFunction(AsyncCallback callback) { return BeginMyFunction(callback, null); } IAsyncResult BeginMyFunction(AsyncCallback callback, object context) { // Func<int> is just a delegate that matches the method signature, // It could be any matching delegate and not necessarily be *generic* // This generic solution does not rely on generics ;) return new Func<int>(MyFunction).BeginInvoke(callback, context); } int EndMyFunction(IAsyncResult result) { return new Func<int>(MyFunction).EndInvoke(result); } ```
Mehrdad Afshari answers your question as best as I could suggest. I would, however, advise against this if at all possible. Unless your business object's sole responsibility is to run things synchronously or asynchronously, you're violating the [single responsibility principle](http://en.wikipedia.org/wiki/Single_responsibility_principle) by even trying to make it aware of the fact that it could run asynchronously. It's easy enough to do this type of operation in the consuming class using anonymous delegates: ``` public void Foo(int x, int y) { ThreadPool.QueueUserWorkItem(delegate { // code to execute before running myObject.MyFunction(x, y); // code to execute after running }); } ``` If you have no code to run before or after, you can use a lambda to make it more concise ``` ThreadPool.QueueUserWOrkItem(() => myObject.MyFunction(x, y)); ``` **EDIT** In response to @kshahar's comment below, externalizing asynchronicity is still a good idea. This is a common problem that has been solved using callbacks for decades. Lambdas simply shorten the route, and .Net 4.0 makes it even simpler. ``` public void Foo(int x, int y) { int result = 0; // creates the result to be used later var task = Task.Factory.StartNew(() => // creates a new asynchronous task { // code to execute before running result = myObject.MyFunction(x, y); // code to execute after running }); // other code task.Wait(); // waits for the task to complete before continuing // do something with the result. } ``` .Net 5 makes it even easier than that, but I'm not familiar enough with it to make a statement beyond that at this point.
Providing Synchronous and Asynchronous Versions of Method in C#
[ "", "c#", ".net", "asynchronous", "" ]
I am a .net c# programmer but I want to learn .NET C++ also. I am a beginner for c++. Is there any site, book, or Video Tutorials from beginner to expert?
There's no such thing as ".Net c++". Maybe you mean **C++/CLI**, which is Microsoft's language specification intended to supersede Managed Extensions for C++ (See [Wikipedia](http://en.wikipedia.org/w/index.php?title=C%2B%2B/CLI)). **Managed extensions to C++** are its inferior and now defunct ancestor [thanks @dp for your comment]. Bear in mind when you choose your learning material that C++/CLI is not equal to the (standard) **C++** programming language; so if you want to learn the former, you should edit the question title and tags. (Note: This is not to be nitpicky, but to help. I think getting the right idea for each name, and the right name for each concept, is an important factor for consistent learning. And of course it's especially important if you search for information on the web.)
I'd suggest starting with Bruce Eckel's [Thinking in C++](http://www.mindview.net/Books/TICPP/ThinkingInCPP2e.html) for a start. It's already around for some time (latest version 2003) but it provides a good path from beginner to the more advanced techniques and interiors of C++. It has also some OO foundations in case you like to want to know more about that basics. ([Master download site](http://www.mindviewinc.com/Books/) for the book)
Learning C++ Language
[ "", "c++", "" ]
Is it safe to use Python UUID module generated values in URL's of a webpage? Wnat to use those ID's as part of URL's. Are there any non-safe characters ever generated by Python UUID that shouldn't be in URL's?
They are safe. See [here](http://docs.python.org/library/uuid.html) for all possible output formats. All of them are readable strings or ints.
It is good practice to **always** urlencode data that will be placed into URLs. Then you need not be concerned with the specifics of UUID or if it will change in the future.
Is it safe to use Python UUID module generated values in URL's of a webpage?
[ "", "python", "url", "uuid", "" ]
I have some data that must be presented in tabular form with multiple sections. In particular, Each section of data is broken up (with it's own headers) by day. This is basically a one-off single page deal, and won't really be maintained, so I don't want to put a lot of effort into architecture. I have two tables. HEADERS and ITEMS. HEADERS have a format of: ``` date(datetime), type(tinyint), firstline(varchar), secondline(varchar) ``` ITEMS has a format of ``` id(int), date(datetime), type(tinyint), name(varchar), value1(int), value2(int), value3(int) ``` I need the data to look similar to this (first and secondline are data populated, third line is static text, item lines are data populated): ``` 1/1/2009 -------------------------------------------------------------------------- | [First line] | -------------------------------------------------------------------------- | [Second line] | -------------------------------------------------------------------------- | Date | Name | Value 1 | Value 2 | Value 3 | ========================================================================== | [Date]| [Name] | [Value 1] | [Value 2] | [Value 3] | -------------------------------------------------------------------------- | [Date]| [Name] | [Value 1] | [Value 2] | [Value 3] | -------------------------------------------------------------------------- 1/2/2009 -------------------------------------------------------------------------- | [First line] | -------------------------------------------------------------------------- | [Second line] | -------------------------------------------------------------------------- | Date | Name | Value 1 | Value 2 | Value 3 | ========================================================================== | [Date]| [Name] | [Value 1] | [Value 2] | [Value 3] | -------------------------------------------------------------------------- | [Date]| [Name] | [Value 1] | [Value 2] | [Value 3] | -------------------------------------------------------------------------- ``` This will repeat for all days currently in the database, each day having it's own table with it's own headers. They will also be filtered by type. the page will only show headers and items of the type specified. Type is an tinyint. **So the question is, What is the best ASP.NET elements to use? DataList? GridView? And how do I include the data from two tables in a header/item format?** EDIT: Sorry, forgot to mention that this has to work on Windows 2000/IIS5, so i'm stuck with ASP.NET 2.0 and can't use 3.0 or 3.5 features.
Ok, heres the eventual solution I came up with. I'm sure this is not the most efficient, or the fastest, but I just needed to get it done and move on with something else. My first step was to create a base class, which I called RowBase, this was an abstract class which implemented an abstract method called GetRow(); Then I derived two other classes, BannerRow and ItemRow from RowBase. These classes contain fields with all the data used in my tables. I then created two DataTables, and filled them with the results of my two queries via a DataAdapter. Next, I created a List<RowBase> and interated over the datatables, creating either a BannerRow or ItemRow depending on the type of row. Next, I ran a List<RowBase>.Sort, sorting on date and type of row to make sure that BannerRows hand priority over ItemRows. Finally, I created placed a table on my webform, set it to runat="server" with an id="maintable" and then I iterated over my List<RowBase> and called GetRow on each RowBase. BannerRow and ItemRow each had an override of GetRow() that returned an HtmlTableRow formatted to include the data in the correct format. Then, I used some conditional logic to insert header rows for the ItemRow data all worked out. This is a variation of Rob and Ben's idea, but included a lot more massaging of the data, so I gave both of them upvotes, but am crediting myself with the answer.
Have a look at asp:table. You can programmaticaly add the rows and columns in some nested conditional iterations in code.
How do I create tables with sections and headers in ASP.NET?
[ "", "c#", "asp.net", "sql-server", "grouping", "" ]
I need to calculate the DateDiff (hours) between two dates, but only during business-hours (8:30 - 16:00, no weekends). This result will then be put into the Reaction\_Time column as per the example below. ``` ID Date Reaction_Time Overdue 1 29.04.2003 15:00:00 1 30.04.2003 11:00:00 3:30 2 30.04.2003 14:00:00 2 01.05.2003 14:00:00 7:30 YES ``` \*Note: I didn't check to see if the dates in example were holidays. I'm using SQL Server 2005 This will be combined with a bigger query, but for now all I need is this to get started, I'll try to figure out how to put it all together on my own. Thanks for the help! **Edit:** Hey, thanks everyone for the replies. But due to the obvious complexity of a solution on SQL side, it was decided we would do this in Excel instead as that's where the report will be moved anyway. Sorry for the trouble, but I really figured it would be simpler than this. As it is, we just don't have the time.
``` DECLARE @BusHourStart DATETIME, @BusHourEnd DATETIME SELECT @BusHourStart = '08:30:00', @BusHourEnd = '16:00:00' DECLARE @BusMinutesStart INT, @BusMinutesEnd INT SELECT @BusMinutesStart = DATEPART(minute,@BusHourStart)+DATEPART(hour,@BusHourStart)*60, @BusMinutesEnd = DATEPART(minute,@BusHourEnd)+DATEPART(hour,@BusHourEnd)*60 DECLARE @Dates2 TABLE (ID INT, DateStart DATETIME, DateEnd DATETIME) INSERT INTO @Dates2 SELECT 1, '15:00:00 04/29/2003', '11:00:00 04/30/2003' UNION SELECT 2, '14:00:00 04/30/2003', '14:00:00 05/01/2003' UNION SELECT 3, '14:00:00 05/02/2003', '14:00:00 05/06/2003' UNION SELECT 4, '14:00:00 05/02/2003', '14:00:00 05/04/2003' UNION SELECT 5, '07:00:00 05/02/2003', '14:00:00 05/02/2003' UNION SELECT 6, '14:00:00 05/02/2003', '23:00:00 05/02/2003' UNION SELECT 7, '07:00:00 05/02/2003', '08:00:00 05/02/2003' UNION SELECT 8, '22:00:00 05/02/2003', '23:00:00 05/03/2003' UNION SELECT 9, '08:00:00 05/03/2003', '23:00:00 05/04/2003' UNION SELECT 10, '07:00:00 05/02/2003', '23:00:00 05/02/2003' -- SET DATEFIRST to U.S. English default value of 7. SET DATEFIRST 7 SELECT ID, DateStart, DateEnd, CONVERT(VARCHAR, Minutes/60) +':'+ CONVERT(VARCHAR, Minutes % 60) AS ReactionTime FROM ( SELECT ID, DateStart, DateEnd, Overtime, CASE WHEN DayDiff = 0 THEN CASE WHEN (MinutesEnd - MinutesStart - Overtime) > 0 THEN (MinutesEnd - MinutesStart - Overtime) ELSE 0 END WHEN DayDiff > 0 THEN CASE WHEN (StartPart + EndPart - Overtime) > 0 THEN (StartPart + EndPart - Overtime) ELSE 0 END + DayPart ELSE 0 END AS Minutes FROM( SELECT ID, DateStart, DateEnd, DayDiff, MinutesStart, MinutesEnd, CASE WHEN(@BusMinutesStart - MinutesStart) > 0 THEN (@BusMinutesStart - MinutesStart) ELSE 0 END + CASE WHEN(MinutesEnd - @BusMinutesEnd) > 0 THEN (MinutesEnd - @BusMinutesEnd) ELSE 0 END AS Overtime, CASE WHEN(@BusMinutesEnd - MinutesStart) > 0 THEN (@BusMinutesEnd - MinutesStart) ELSE 0 END AS StartPart, CASE WHEN(MinutesEnd - @BusMinutesStart) > 0 THEN (MinutesEnd - @BusMinutesStart) ELSE 0 END AS EndPart, CASE WHEN DayDiff > 1 THEN (@BusMinutesEnd - @BusMinutesStart)*(DayDiff - 1) ELSE 0 END AS DayPart FROM ( SELECT DATEDIFF(d,DateStart, DateEnd) AS DayDiff, ID, DateStart, DateEnd, DATEPART(minute,DateStart)+DATEPART(hour,DateStart)*60 AS MinutesStart, DATEPART(minute,DateEnd)+DATEPART(hour,DateEnd)*60 AS MinutesEnd FROM ( SELECT ID, CASE WHEN DATEPART(dw, DateStart) = 7 THEN DATEADD(SECOND, 1, DATEADD(DAY, DATEDIFF(DAY, 0, DateStart), 2)) WHEN DATEPART(dw, DateStart) = 1 THEN DATEADD(SECOND, 1, DATEADD(DAY, DATEDIFF(DAY, 0, DateStart), 1)) ELSE DateStart END AS DateStart, CASE WHEN DATEPART(dw, DateEnd) = 7 THEN DATEADD(SECOND, -1, DATEADD(DAY, DATEDIFF(DAY, 0, DateEnd), 0)) WHEN DATEPART(dw, DateEnd) = 1 THEN DATEADD(SECOND, -1, DATEADD(DAY, DATEDIFF(DAY, 0, DateEnd), -1)) ELSE DateEnd END AS DateEnd FROM @Dates2 )Weekends )InMinutes )Overtime )Calculation ```
I would recommend building a user defined function that calculates the date difference in business hours according to your rules. ``` SELECT Id, MIN(Date) DateStarted, MAX(Date) DateCompleted, dbo.udfDateDiffBusinessHours(MIN(Date), MAX(Date)) ReactionTime FROM Incident GROUP BY Id ``` I'm not sure where your `Overdue` value comes from, so I left it off in my example. In a function you can write way more expressive SQL than in a query, and you don't clog your query with business rules, making it hard to maintain. Also a function can easily be reused. Extending it to include support for holidays (I'm thinking of a `Holidays` table here) would not be too hard. Further refinements are possible without the need to change hard to read nested SELECT/CASE WHEN constructs, which would be the alternative. If I have time today, I'll look into writing an example function. --- EDIT: Here is something with bells and whistles, calculating around weekends transparently: ``` ALTER FUNCTION dbo.udfDateDiffBusinessHours ( @date1 DATETIME, @date2 DATETIME ) RETURNS DATETIME AS BEGIN DECLARE @sat INT DECLARE @sun INT DECLARE @workday_s INT DECLARE @workday_e INT DECLARE @basedate1 DATETIME DECLARE @basedate2 DATETIME DECLARE @calcdate1 DATETIME DECLARE @calcdate2 DATETIME DECLARE @cworkdays INT DECLARE @cweekends INT DECLARE @returnval INT SET @workday_s = 510 -- work day start: 8.5 hours SET @workday_e = 960 -- work day end: 16.0 hours -- calculate Saturday and Sunday dependent on SET DATEFIRST option SET @sat = CASE @@DATEFIRST WHEN 7 THEN 7 ELSE 7 - @@DATEFIRST END SET @sun = CASE @@DATEFIRST WHEN 7 THEN 1 ELSE @sat + 1 END SET @calcdate1 = @date1 SET @calcdate2 = @date2 -- @date1: assume next day if start was after end of workday SET @basedate1 = DATEADD(dd, 0, DATEDIFF(dd, 0, @calcdate1)) SET @calcdate1 = CASE WHEN DATEDIFF(mi, @basedate1, @calcdate1) > @workday_e THEN @basedate1 + 1 ELSE @calcdate1 END -- @date1: if Saturday or Sunday, make it next Monday SET @basedate1 = DATEADD(dd, 0, DATEDIFF(dd, 0, @calcdate1)) SET @calcdate1 = CASE DATEPART(dw, @basedate1) WHEN @sat THEN @basedate1 + 2 WHEN @sun THEN @basedate1 + 1 ELSE @calcdate1 END -- @date1: assume @workday_s as the minimum start time SET @basedate1 = DATEADD(dd, 0, DATEDIFF(dd, 0, @calcdate1)) SET @calcdate1 = CASE WHEN DATEDIFF(mi, @basedate1, @calcdate1) < @workday_s THEN DATEADD(mi, @workday_s, @basedate1) ELSE @calcdate1 END -- @date2: assume previous day if end was before start of workday SET @basedate2 = DATEADD(dd, 0, DATEDIFF(dd, 0, @calcdate2)) SET @calcdate2 = CASE WHEN DATEDIFF(mi, @basedate2, @calcdate2) < @workday_s THEN @basedate2 - 1 ELSE @calcdate2 END -- @date2: if Saturday or Sunday, make it previous Friday SET @basedate2 = DATEADD(dd, 0, DATEDIFF(dd, 0, @calcdate2)) SET @calcdate2 = CASE DATEPART(dw, @calcdate2) WHEN @sat THEN @basedate2 - 0.00001 WHEN @sun THEN @basedate2 - 1.00001 ELSE @date2 END -- @date2: assume @workday_e as the maximum end time SET @basedate2 = DATEADD(dd, 0, DATEDIFF(dd, 0, @calcdate2)) SET @calcdate2 = CASE WHEN DATEDIFF(mi, @basedate2, @calcdate2) > @workday_e THEN DATEADD(mi, @workday_e, @basedate2) ELSE @calcdate2 END -- count full work days (subtract Saturdays and Sundays) SET @cworkdays = DATEDIFF(dd, @basedate1, @basedate2) SET @cweekends = @cworkdays / 7 SET @cworkdays = @cworkdays - @cweekends * 2 -- calculate effective duration in minutes SET @returnval = @cworkdays * (@workday_e - @workday_s) + @workday_e - DATEDIFF(mi, @basedate1, @calcdate1) + DATEDIFF(mi, @basedate2, @calcdate2) - @workday_e -- return duration as an offset in minutes from date 0 RETURN DATEADD(mi, @returnval, 0) END ``` The function returns a `DATETIME` value meant as an offset from date 0 (which is `"1900-01-01 00:00:00"`). So for example a timespan of 8:00 hours would be `"1900-01-01 08:00:00"` and 25 hours would be `"1900-01-02 01:00:00"`. The function result is the time *difference in business* hours between two dates. No special handling/support for overtime. ``` SELECT dbo.udfDateDiffBusinessHours('2003-04-29 15:00:00', '2003-04-30 11:00:00') --> 1900-01-01 03:30:00.000 SELECT dbo.udfDateDiffBusinessHours('2003-04-30 14:00:00', '2003-05-01 14:00:00') --> 1900-01-01 07:30:00.000 ``` The function assumes the start of the next available work day (08:30 h) when the `@date1` is off-hours, and the end of the previous available work day (16:00 h) when `@date2` is off-hours. "next/previous available" means: * if `@date1` is `'2009-02-06 07:00:00'` (Fri), it will become `'2009-02-06 08:30:00'` (Fri) * if `@date1` is `'2009-02-06 19:00:00'` (Fri), it will become `'2009-02-09 08:30:00'` (Mon) * if `@date2` is `'2009-02-09 07:00:00'` (Mon), it will become `'2009-02-06 16:00:00'` (Fri) * if `@date2` is `'2009-02-09 19:00:00'` (Mon), it will become `'2009-02-09 16:00:00'` (Mon)
SQL DateDiff advanced usage?
[ "", "sql", "datediff", "" ]
I'm currently working on a tree structure of nodes where each node should be able to tell if it is equivalent to another one. Each node class is a subclass of QueryNode. To check for equivalency, nodes compare if they are of the same subclass and have equal member values (of course there's more things involved, but this is the part that bugs me): ``` class VersionNode : QueryNode { VersionModifier m_versionModifier; internal VersionModifier VersionModifier { get { return this.m_versionModifier; } } // ... protected override bool AreMembersEquivalent(QueryNode other) { VersionNode otherNodeAsVersionNode = other as VersionNode; if (otherNodeAsVersionNode == null) return false; else return (this.m_versionModifier == otherNodeAsVersionNode.VersionModifier); } } ``` I feel this may not be an optimal solution because it involves casting. Is there a more elegant way to do this?
The short answer is no. Casting (and even unboxing to a degree) is not expensive.
You could do: ``` protected override bool AreMembersEquivalent(QueryNode other) { if (!(other is VersionNode)) return false; ... } ```
Is there an alternative to type checking in this C# code?
[ "", "c#", "" ]
So lets say I have these classes: ``` public class Person { public string Name { get; set; } } public class PersonCollection : ObservableCollection<Person> { } ``` And lets say I have a ListView whose ItemsSource is bound to a PersonCollection. Now lets say I have this code: ``` public void AddPeople() { Person p = new Person() { Name = "Someone" }; MyPersonCollection.Add(p); MyPersonCollection.Add(p); MyPersonCollection.Add(p); } ``` So now I have a ListView with three items in which all three items are references to the SAME object. So now I select lets say items with index 0 and 2 in the ListView. The ListView.SelectedItems property will say I have ONE item selected since both visually selected items are the SAME object. So how can I get the visually selected items so I can remove the items at indices 0 and 2, without removing the item at index 1?
In WinForms there is the `ListBox.SelectedIndices` property that would be useful here, but we don't have that in WPF, unfortunately... You could iterate through the `ListViewItem`s using [`ItemContainerGenerator.ContainerFromIndex`](http://msdn.microsoft.com/en-us/library/system.windows.controls.itemcontainergenerator.containerfromindex.aspx), check [`ListViewItem.IsSelected`](http://msdn.microsoft.com/en-us/library/system.windows.controls.listboxitem.isselected.aspx) and then remove them by index. However, this doesn't play well with virtualization because `ContainerFromIndex` could return null if you scroll away from the item and it gets virtualized. The code would look something like this: ``` for(int ixPerson = myListView.Items.Count - 1; ixPerson >= 0; ixPerson--) { ListViewItem personItem = myListView.ItemContainerGenerator.ContainerFromIndex(ixPerson); if (personItem.IsSelected) { mySourcePersonCollection.RemoveAt(ixPerson); } } ```
There are cases where this makes sense, adding people to a queue where appearing more than once is desirable for instance. For this case it seems like WPF is designed poorly. Is it possible to manually iterate between all items in the collection and check their selection state?
WPF: SelectedItems with duplicate object references
[ "", "c#", "wpf", "listview", "" ]
[Java Web Start does not come with 64-bit builds of the JDK](http://java.com/en/download/help/webstart_64bits.xml). Why is this? What is lacking that keeps it from building and working?
Thought you'd might want to know the new update is out: <http://java.sun.com/javase/6/webnotes/6u12.html> > 64-Bit Browser Support for Java Plugin > and Java Webstart This release > supports the New Java Plugin and Java > Webstart on AMD64 architecture, on > Windows platforms. A Java offline > installer (JRE and JDK) is provided. > Note, if you use 32-bit and 64-bit > browsers interchangeably, you will > need to install both 32-bit and 64-bit > JREs in order to have Java Plug-In for > both browsers.
Apparently, there *is* no reason, since its in JRE6u12. <https://bugs.java.com/bugdatabase/view_bug?bug_id=4626735>
Why does Java Web Start not work with 64-bit Java environments?
[ "", "java", "64-bit", "java-web-start", "" ]
I have a Tree. ``` class TreeNode { public TreeNode(string name, string description) { Name = name; Description = description; } string Name { get; set; } string Description { get; set; } public List<TreeNode> Children = new List<TreeNode>(); } ``` I would like to populate a large one for unit testing purposes. I would really like to keep stuff DRY. Say for illustration purposes my tree has the following structure ``` Parent,desc Child 1, desc1 Grandchild 1, desc1 Child 2, desc2 ``` How would you go about populating the tree in an elegant an maintainable way? I find this code quite repetitious and error prone: ``` var parent = new TreeNode("Parent", "desc"); var child1 = new TreeNode("Child 1", "desc1"); var child2 = new TreeNode("Child 2", "desc2"); var grandchild1 = new TreeNode("Grandchild 1", "desc1"); parent.Children.Add(child1); parent.Children.Add(child2); child1.Children.Add(grandchild1); ``` **EDIT** I ended up doing the DSL approach: A demo [test lives here](http://github.com/SamSaffron/media-library/blob/8e7d4582ddb2ae25bc9fc8fcdb82d38da54ed4a6/MediaLibraryTests/TestMockLocations.cs). The [implementation is here](http://github.com/SamSaffron/media-library/blob/8e7d4582ddb2ae25bc9fc8fcdb82d38da54ed4a6/MediaLibraryTests/MockFolderMediaLocation.cs). It uses a builder and a simple DSL.
* Ideally you want a way to extend the language to **literals of custom types**. C# doesn't have this, so you have to find another approach. * You can fabricate an **internal DSL**, typically with a **fluent interface**. * Follow the [`XElement` example of **functional construction**](http://msdn.microsoft.com/en-us/library/bb387019.aspx). * Create an **external DSL** with a custom parser. If you design the language carefully, the parser can be easy. * Use **XML**. Basically this is a way to create an external DSL and get the parser for free. The external DSL options are nice because when you read them, you know there's *only data*, and don't have to worry about making sense of code constructs. Also, the data is the file, and the file is the data. That makes it easy to swap data around by changing files, and easier to ready file change histories. Finally, and external DSL is good when a non-programmer will be supplying the data. The tradeoff here is time vs. value. **How much data you will have / how often it will change / who will change it** are the questions you have to answer.
You can write a "TreeBuilder" with a state to save some connections mess: ``` TreeBuilder builder = new TreeBuilder(); builder.AddNode("Parent", "desc"); // Adds a node, and sets the cursor to it builder.AddLeaf("Child 1", "desc1"); // Adds a node and leaves the cursor at the Parent builder.AddNode("Child 2", "desc2"); builder.AddLeaf("Grandchild 1", "desc1"); builder.Up(); // Moves the cursor to the parent builder.AddNode("Child 3", "desc3"); root = builder.GetRoot() ``` Another way is to invent a simple configuration file/string with some simple format.
Elegant and maintainable way of populating Tree structures in c#
[ "", "c#", "design-guidelines", "" ]
On my submit button, what I'd like to do is OnClick show a "Please wait" panel and hide the button, UNLESS the validators say something's invalid - then I need the buttons still showing obviously. Otherwise I have a validation summary showing erros and no way to submit again. Most articles I find about doing this want to use Page\_ClientValidate() function to tell the page to validate itself, but this comes back undefined for me, as does Page\_IsValid variable. Here is the function I'm trying to use - what am I missing?: ``` function PleaseWaitShow() { try { alert("PleaseWaitShow()"); var isPageValid = true; // Do nothing if client validation is not active if (typeof(Page_Validators) == "undefined") { if (typeof(Page_ClientValidate) == 'function') { isPageValid = Page_ClientValidate(); alert("Page_ClientValidate returned: " + isPageValid); alert("Page_IsValid=" + Page_IsValid); } else { alert("Page_ClientValidate function undefined"); } } else { alert("Page_Validators undefined"); } if(isPageValid) { // Hide submit buttons document.getElementById('pnlSubmitButton').style.visibility = 'hidden'; document.getElementById('pnlSubmitButton').style.display = 'none'; // Show please wait panel document.getElementById('pnlPleaseWait').style.visibility = 'visible'; document.getElementById('pnlPleaseWait').style.display = 'block'; } else { alert("page not valid - don't show please wait"); } } catch(er) { alert("ERROR in PleaseWaitShow(): " + er); } } ```
I believe I've found a "kind of" answer. I still cannot identify why my page will not identify "Page\_ClientValidate()" or "Page\_IsValid" - this part is still unanswered. However, I am using a number of PeterBlum validators on the page, and those do provide a "VAM\_ValOnSubmit()" that returns true/false. So this may be the solution. I might just have to be sure all the validators are PeterBlum to catch them all. Not the greatest solution, but better than I've gotten so far. I'm still open to answers on the "Page\_IsValid" portion.
change this line "if (typeof(Page\_Validators) == "undefined") " to if (typeof(Page\_Validators) != "undefined")
Javascript checking if page is valid
[ "", "asp.net", "javascript", "validation", "" ]
The question is how long have these customers been jerks on any given date. I'm working against Sybase For this simplified table structure of table history\_data ``` table: history_of_jerkiness processing_date name is_jerk --------------- ----- ------- 20090101 Matt true 20090101 Bob false 20090101 Alex true 20090101 Carol true 20090102 Matt true 20090102 Bob true 20090102 Alex false 20090102 Carol true 20090103 Matt true 20090103 Bob true 20090103 Alex true 20090103 Carol false ``` The report for the 3rd should show that Matt has always been a jerk, Alex has just become a jerk, and Bob has been a jerk for 2 days. ``` name days jerky ----- ---------- Matt 3 Bob 2 Alex 1 ``` I'd like to find these spans of time dynamically, so if I run the report for the 2nd, I should get different results: ``` name days_jerky ----- ---------- Matt 2 Bob 1 Carol 2 ``` The key here is trying to find only continuous spans older than a certain date. I've found a few leads, but it seems like a problem where there would be very smart tricky solutions.
My solution from SQL Server - same as Dems but I put in a min baseline myself. It assumes there are no gaps - that is there is an entry for each day for each person. If that isn't true then I'd have to loop. ``` DECLARE @run_date datetime DECLARE @min_date datetime SET @run_date = {d '2009-01-03'} -- get day before any entries in the table to use as a false baseline date SELECT @min_date = DATEADD(day, -1, MIN(processing_date)) FROM history_of_jerkiness -- get last not a jerk date for each name that is before or on the run date -- the difference in days between the run date and the last not a jerk date is the number of days as a jerk SELECT [name], DATEDIFF(day, MAX(processing_date), @run_date) FROM ( SELECT processing_date, [name], is_jerk FROM history_of_jerkiness UNION ALL SELECT DISTINCT @min_date, [name], 0 FROM history_of_jerkiness ) as data WHERE is_jerk = 0 AND processing_date <= @run_date GROUP BY [name] HAVING DATEDIFF(day, MAX(processing_date), @run_date) > 0 ``` I created the test table with the following: ``` CREATE TABLE history_of_jerkiness (processing_date datetime, [name] varchar(20), is_jerk bit) INSERT INTO history_of_jerkiness (processing_date, [name], is_jerk) VALUES ({d '2009-01-01'}, 'Matt', 1) INSERT INTO history_of_jerkiness (processing_date, [name], is_jerk) VALUES ({d '2009-01-01'}, 'Bob', 0) INSERT INTO history_of_jerkiness (processing_date, [name], is_jerk) VALUES ({d '2009-01-01'}, 'Alex', 1) INSERT INTO history_of_jerkiness (processing_date, [name], is_jerk) VALUES ({d '2009-01-01'}, 'Carol', 1) INSERT INTO history_of_jerkiness (processing_date, [name], is_jerk) VALUES ({d '2009-01-02'}, 'Matt', 1) INSERT INTO history_of_jerkiness (processing_date, [name], is_jerk) VALUES ({d '2009-01-02'}, 'Bob', 1) INSERT INTO history_of_jerkiness (processing_date, [name], is_jerk) VALUES ({d '2009-01-02'}, 'Alex', 0) INSERT INTO history_of_jerkiness (processing_date, [name], is_jerk) VALUES ({d '2009-01-02'}, 'Carol', 1) INSERT INTO history_of_jerkiness (processing_date, [name], is_jerk) VALUES ({d '2009-01-03'}, 'Matt', 1) INSERT INTO history_of_jerkiness (processing_date, [name], is_jerk) VALUES ({d '2009-01-03'}, 'Bob', 1) INSERT INTO history_of_jerkiness (processing_date, [name], is_jerk) VALUES ({d '2009-01-03'}, 'Alex', 1) INSERT INTO history_of_jerkiness (processing_date, [name], is_jerk) VALUES ({d '2009-01-03'}, 'Carol', 0) ```
This can be made simple if you structure the data so as to meet the following criteria... > All people must have an initial record where they are not a jerk You can do something like... ``` SELECT name, MAX(date) last_day_jerk_free FROM jerkiness AS [data] WHERE jerk = 'false' AND date <= 'a date' GROUP BY name ``` You already know what the base date is ('a date'), and now you know the last day they were not a jerk. I don't know sybase but I'm sure there are commands you can use to get the number of days between 'a data' and 'last\_day\_jerk\_free' EDIT: There are multiple ways of artificially creating an initialising "not jerky" record. The one suggested by Will Rickards uses a sub query containing a union. Doing so, however, has two down sides... 1. The sub-query masks any indexes which may otherwise have been used 2. It assumes all people have data starting from the same point Alternatively, take Will Rickard's suggestion and move the aggregation from the outer query into the inner query (so maximising use of indexes), and union with a generalised 2nd sub query to create the starting jerky = false record... ``` SELECT name, DATEDIFF(day, MAX(processing_date), @run_date) AS days_jerky FROM ( SELECT name, MAX(processing_date) as processing_date FROM history_of_jerkiness WHERE is_jerk = 0 AND processing_date <= @run_date GROUP BY name UNION SELECT name, DATEADD(DAY, -1, MIN(processing_date)) FROM history_of_jerkiness WHERE processing_date <= @run_date GROUP BY name ) as data GROUP BY name ``` The outer query still has to do a max without indexes, but over a reduced number of records (2 per name, rather than n per name). The number of records is also reduced by not requiring every name to have a value for every date in use. There are many other ways of doing this, some can be seen in my edit history.
SQL Dates Query - how long has this condition been true
[ "", "sql", "database", "datetime", "sybase", "" ]
What is causing this error? ``` Fatal error: Call to undefined function imagefilter() in /var/www/polaroid.php on line 5 ``` ``` 1 <?PHP 2 $img_addr = $_GET['image_address']; 3 $img = imagecreatefromjpeg($img_addr); 4 /* everything works as expected without this line */ 5 imagefilter($img, IMG_FILTER_GRAYSCALE); 6 7 if ($img) 8 { /* I moved the header function here so I can see errors in the browser. If I leave it at the top of the file, the browser expects an image and doesn't print the error messages. */ 9 header('Content-type: image/jpeg'); 10 imagejpeg($img); 11 } 12 ?> 13 ``` This is the URL I use: ``` http://localhost/polaroid.php?image_address=http://mattnelsoninfo.files.wordpress.com/2008/04/ceiling_cat1.jpg ``` NOTE: gd is listed in the output from phpinfo(). ## EDIT: I'm using PHP Version 5.2.6-2ubuntu4.1 ## Another EDIT: phpinfo() yields this in the gd section ``` gd GD Support enabled GD Version 2.0 or higher FreeType Support enabled FreeType Linkage with freetype FreeType Version 2.3.7 T1Lib Support enabled GIF Read Support enabled GIF Create Support enabled JPG Support enabled PNG Support enabled WBMP Support enabled ``` Thanks!
What version of PHP are you using? It looks like imagefilter is a PHP5 function ... <https://www.php.net/manual/en/function.imagefilter.php> EDIT: Your code works on my version of PHP. For reference, here's my phpinfo: ``` gd GD Support enabled **GD Version bundled (2.0.34 compatible)** FreeType Support enabled FreeType Linkage with freetype FreeType Version 2.1.9 T1Lib Support enabled GIF Read Support enabled GIF Create Support enabled JPG Support enabled PNG Support enabled WBMP Support enabled XBM Support enabled ``` You might want to make sure that the GD Version is bundled. I've seen installations that say GD Support is enabled but not bundled. Not sure if that makes a difference though.
imagefilter seems to be available only if PHP is compiled agains the bundled GD library which in your case it's not (that's the difference between the bundled and enabled). Since you're using Ubuntu the version of php that you find in the repository does not have GD bundled.
Fatal error: Call to undefined function imagefilter()
[ "", "php", "image-processing", "gd", "imagefilter", "" ]
I am new to Python and it seems to have a lot of nice functions that I don't know about. What function can I use to get the root site name? For example, how would I get *faqs.org* if I gave the function the URL "[http://www.faqs.org/docs/diveintopython/kgp\_commandline.html](http://ttp://www.faqs.org/docs/diveintopython/kgp_commandline.html)"?
``` >>> from urllib.parse import urlparse >>> urlparse('http://www.cwi.nl:80/%7Eguido/Python.html').hostname 'www.cwi.nl' ```
The much overlooked [urlparse](http://www.python.org/doc/2.5.4/lib/module-urlparse.html) module: ``` from urlparse import urlparse scheme, netloc, path, params, query, fragment = urlparse("http://www.faqs.org/docs/diveintopython/kgp_commandline.html") print netloc ```
get site name from a URL in python
[ "", "python", "" ]
I have created an ActiveX control using C++. I use Visual Basic code to instance the control in an Excel worksheet. I can only run the VB script once, subsequent runs cause the following runtime error when attempting to access the 'ActiveSheet' variable: ``` Microsoft Visual Basic Run-time error '-2147319765 (8002802b)': Automation error Element not found ``` I am trying to work out what causes this error and how I can fix it? As an experiment I tried creating a simple ActiveX control generated by Visual Studio wizards (in both VS 2005 & 2008). I didn't add or modify any code in this test case. The simple test case still causes this error. Other ActiveX controls in the system don't cause this error (eg I tried instancing 'Bitmap Image') from VB code. This is the VB code (a macro that I recorded, but hand-coded VB has the same issue): ``` Sub Macro1() ActiveSheet.OLEObjects.Add(ClassType:="test.test_control.1" _ , Link:=False, DisplayAsIcon:=False).Select End Sub ``` Can anyone give me an answer on this? Alternatively any pointers to resources that may help will be appreciated. Thanks
After talking to Microsoft I found out the cause of the problem I was having. When creating an ActiveX control using the VS 2005/2008 wizard you need to check the 'Connection points' check box in the 'Options' page. This adds, among other things, IConnectionPointContainerImpl as a base class for your ATL class, which in turn implements IConnectionPointContainer. Failure to do this means that you can't insert your ActiveX control into an Excel document via Visual Basic more than once. The second time you execute the script you start getting the 'automation errors'. The answer to the problem was simple enough and it worked, although I am still not sure how it actually relates to the 'automation error' and leaves me wondering why the error messages are not more informative.
You have created an "unqualified" reference to an Excel application that you cannot release by utilizing a Global variable intended for VBA that should not be used in VB 6.0. This is an unfortunate side-effect of using VB 6.0, but it is the only problem I know of using VB6, and it is easily fixed. The problem in your case stems from using the 'ActiveSheet' global variable. When using VBA, this is fine, but when using VB 6.0, you must avoid this or else you create an Excel application that you cannot release. This approach will run fine the first time, but will cause all kinds of undefined behavior the **second** time your routine runs. In your example, the code should do something like this: ``` Sub Macro1() Dim xlApp As Excel.Application Set xlApp = New Excel.Application xlApp.ActiveSheet.OLEObjects.Add(ClassType:="test.test_control.1" _ , Link:=False, DisplayAsIcon:=False).Select ' Then when done: xlApp.Quit() xlApp = Nothing End Sub ``` For a detailed discussion about how to handle this in general, see: VB 6.0 Tutorial - Finding and Repairing Unqualified References (<http://www.xtremevbtalk.com/showthread.php?p=900556#post900556>) For Microsoft documentation on this issue see: Excel Automation Fails Second Time Code Runs (MSKB 178510) (<http://support.microsoft.com/default.aspx?scid=http://support.microsoft.com:80/support/kb/articles/q178/5/10.asp>) Error or Unexpected Behavior with Office Automation When You Use Early Binding in Visual Basic (MSKB 319832) (<http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q319832&>) **Edit**: *Note that using html 'a' tags were not working with these links for some reason. Someone might need to look into the parser?*
What causes Visual Basic Run-time error -2147319765 (8002802b) in Excel when an ActiveX control has been instanced?
[ "", "c++", "vba", "activex", "excel", "" ]
My project requires me to validate a large number of web URLs. These URLs have been captured by a very unreliable process which I do not control. All of the URLs have already been regexp validated and are known to be well-formed. I also know that they all have valid TLDs I want to be able to filter these URLs quickly in order to determine which of these are incorrect. At this point I do not care what content is on the pages - I'd just like to know as quickly as possible which of the pages are inaccessible (e.g. produce a 404 error). Given that there are a lot of these I do not want to download the entire page, just the HTTP header and then take a good guess from the content of the header whether the page is likely to exist. Can it be done?
To really make this fast you might also use [eventlet](http://pypi.python.org/pypi/eventlet) which uses non-blocking IO to speed things up. You can use a head request like this: ``` from eventlet import httpc try: res = httpc.head(url) except httpc.NotFound: # handle 404 ``` You can then put this into some simple script like [that example script here](http://wiki.secondlife.com/wiki/Eventlet/Examples). With that you should get pretty much concurrency by using a coroutines pool.
I'm assuming you want to do it in Python based on your tags. In that case, I'd use httplib. Optionally, somehow group the URLs by host so you can make multiple requests in one connection for those URLs that have the same host. Use the HEAD request. ``` conn = httplib.HTTPConnection("example.com") conn.request("HEAD", "/index.html") resp = conn.getresponse() print resp.status ```
What's the fastest way to test the validity of a large number of well-formed URLs
[ "", "python", "http", "" ]
I need a simple "one at a time" lock on a section of code. Consider the function `func` which can be run from multiple threads: ``` void func() { // locking/mutex statement goes here operation1(); operation2(); // corresponding unlock goes here operation3(); } ``` I need to make sure that `operation1` and `operation2` always run "together". With C# I would use a simple `lock` block around these two calls. What is the C++/Win32/MFC equivalent? Presumably some sort of `Mutex`?
Critical sections will work (they're lighter-weight that mutexes.) InitializeCriticalSection, EnterCriticalSection, LeaveCriticalSection, and DeleteCriticalSection are the functions to look for on [MSDN](https://msdn.microsoft.com/en-us/library/windows/desktop/ms686908(v=vs.85).aspx "MSDN"). ``` void func() { // cs previously initialized via InitializeCriticalSection EnterCriticalSection(&cs); operation1(); operation2(); LeaveCriticalSection(&cs); operation3();} } ``` EDIT: Critical sections are faster than mutexes since critical sections are primarily user mode primitives - in the case of an uncontended acquire (usually the common case) there is no system call into the kernel, and acquiring takes on the order of dozens of cycles. A kernel switch is more more expensive (on the order of hundreds of cycles). The only time critical sections call into the kernel is in order to block, which involves waiting on a kernel primitive, (either mutex or event). Acquiring a mutex always involves a call into the kernel, and is thus orders of magnitude slower. However, critical sections can only be used to synchronize resources in one process. In order to synchronize across multiple processes, a mutex is needed.
Improving [Michael solution](https://stackoverflow.com/questions/635276/simple-thread-synchronization/635295#635295) above for C++. Michael solution is perfect for C applications. But when used in C++ this style is discouraged because of the possibility of exceptions. If an exception happens in operation1 or operation2 then the critical section will not be correctly left and all other threads will block waiting. ``` // Perfect solution for C applications void func() { // cs previously initialized via InitializeCriticalSection EnterCriticalSection(&cs); operation1(); operation2(); LeaveCriticalSection(&cs); operation3();} } // A better solution for C++ class Locker { public: Locker(CSType& cs): m_cs(cs) { EnterCriticalSection(&m_cs); } ~Locker() { LeaveCriticalSection(&m_cs); } private: CSType& m_cs; } void func() { // cs previously initialized via InitializeCriticalSection { Locker lock(cs); operation1(); operation2(); } operation3(); } ```
Simple Thread Synchronization
[ "", "c++", "winapi", "mfc", "" ]
I have a COM+ component developed with VB6. After registering it with the component services manager COM+ application, I can use it from ASP like this ``` Set Comando = Server.CreateObject("JuiciosComando.clsComando") ComandoExecute = Comando.execute(Xml) Set Comando = Nothing ``` That's all I need, the component just receives a (maybe a huge) string and returns another (also possibly huge) string... Is there some way to access this very same component from Java? What I've found so far is [J-Integra](http://j-integra.intrinsyc.com/support/com/doc/servlet_com/ServletToComPlusExample.html) but it's a commercial product. I've also found [this thread on codeguru.com](http://www.codeguru.com/forum/archive/index.php/t-383429.html) but my C++.NET knowledge is rather poor, besides I would rather just find a free, pure Java solution.
As Eddie mentioned, you have two main methods of using COM via java: using C++ and writing a JNI wrapper or using a third party JAR to wrap the COM object. I've attempted to use C++ to wrap a COM object in the past - it's not for the faint hearted - it is not easy to do and its very easy to leak resources. I've also used two third party JAR's: ComfyJ and JACOB. ComfyJ was really easy to use and also included a codegen utility to generate java wrapper classes for your COM classes. It can be downloaded and trialed via <http://www.teamdev.com/comfyj/index.jsf> (I am not affiliated with TeamDev in any way!) If you are desperate for a totally free solution, you could also try JACOB (<http://sourceforge.net/projects/jacob-project/>). I had issues with documentation, but it was relatively stable.
I can confirm that [JACOB](http://danadler.com/jacob/) works pretty well. I've used it for numerous COM automation projects without any issues. And it's free...
How to execute COM+ libraries from Java using a free method
[ "", "java", "com+", "" ]
I wanted to set up remote debugging from Eclipse. Tomcat is running as a service on windows. That bit is fine, a quick google pointed me towards the correct settings to add to wrapper.conf to enable this. There were entries already in wrapper.conf, so I copy/pasted the last entry and modified it: ``` wrapper.java.additional.8="-Djava.endorsed.dirs=C:/Program Files/OurApp/tomcat/common/endorsed" wrapper.java.additional.8.stripquotes=TRUE wrapper.java.additional.9="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=9135,suspend=n" wrapper.java.additional.9.stripquotes=TRUE ``` It didn't work, because the quotes are around everything, and the stripquotes only applies to linux systems. Theoretically the correct entries should be: ``` wrapper.java.additional.8=-Djava.endorsed.dirs="C:/Program Files/OurApp/tomcat/common/endorsed" wrapper.java.additional.8.stripquotes=TRUE wrapper.java.additional.9=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=9135,suspend=n ``` The second example doesn't need quotes - no spaces to break it up. The first example does - because of "Program Files" Am I correct in this assessment? If so, how/why is the application working as is? There are several parameters ostensibly being set like this (nested in qutoes), which I believe actually have no effect. For instance min/max memory settings. I found an example [here](http://cocoondev.org/books/daisy_docs_book--20070924-080121/publications/html-chunked/output/dsy331-cd.html) that has the same thing, ostensibly being a config for windows and linux. My questions: Will these quotes stop the config commands going through? Why is the app working if that is the case?
AFter a bit more playing around and trolling through debug logs, I think I have isolated the issue. The problem was the mix of 1 - Being lazy and putting two configuration items on the same line. (In my defense I copied it as one line from [the Tomcat FAQ](http://wiki.apache.org/tomcat/FAQ/Developing) 2 - Using quotes The combination of these two was causing the issue. ``` wrapper.java.additional.9="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=9135,suspend=n" wrapper.java.additional.9.stripquotes=TRUE ``` Like this it generates a command line: ``` java "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=9135,suspend=n" ... ``` It treats that entire string as one argument - rather than the two as I intended. Without the quotes wrapper.java.additional.9=-Xdebug -Xrunjdwp:transport=dt\_socket,server=y,address=9135,suspend=n wrapper.java.additional.9.stripquotes=TRUE It generates: ``` java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=9135,suspend=n ... ``` Seeing as there are no quotes to screw things up, it processes the two -X parameters as I would want it to. Even better (and probably the intended use) as two seperate entries ``` wrapper.java.additional.9="-Xdebug" wrapper.java.additional.9.stripquotes=TRUE wrapper.java.additional.10="-Xrunjdwp:transport=dt_socket,server=y,address=9135,suspend=n" wrapper.java.additional.10.stripquotes=TRUE java "-Xdebug" "-Xrunjdwp:transport=dt_socket,server=y,address=9135,suspend=n" ... ``` There are quotes around each one, and it treats them individually. The existing entries are all fine, because they only set one item per line. So I'll just put this down to a learning experience (sigh) and realise that I now know a whole lot more about wrapper.conf that I didn't know before. Cheers, evnafets
I'm using remote debugging in Eclipse via \*.bat files. Possible it will be more easy way for you. Steps to accomplish: 1. Download tomcat installation in zip file and copy all files to bin folder 2. Create debug.bat file with such content as set JPDA\_ADDRESS=8000 set JPDA\_TRANSPORT=dt\_socket call catalina.bat jpda start If you'll got an error that the port already in use, change 8000 to any other (8001, 8002 etc.). From Eclipse side: 1. Open Debug Dialog 2. New Remote Java Application (Connect tab: Host - localhost or any other ip address, Port - 8000; Source tab:Add all source files (e.g. remove all, add Java project, select all projects) 3. Push Debug 4. Set breakpoints in Eclipse and try to reach them from Tomcat
Tomcat service: quotes in wrapper.conf
[ "", "java", "tomcat", "windows-services", "" ]
I have a swing client that renders HTML through the use of the `JEditorPane` and `HTMLDocument` classes. The problem I have is that I want to be able to define an area of the document as a container for some text that will be retrieved at a later date, and then use `document.setInnerHTML(element, data);` to swap out the place-holder content with the "real" content. So, I decided that I would define a tag similar to this: ``` <html> <body> some text <mytag id="1>placeholder</mytag> some more text </body> </html> ``` The problem occurs when I use `document.getElement(String id)` - it finds mytag as an element, but it thinks it's a leaf element that has no content and so I cannot call .setInner() on it. Looking at it's parents list of elements, it thinks there are 3 - my tag has just been interpreted as individual components: mytag (start) content mytag (end) So, I'm guessing that I need to tell the document (or it's parser) about my tag, but that's where I'm falling flat as I'm fairly new to this area. So, has anyone had any experience with this at all? I could cheat and use a span tag, but that doesn't feel right as (excluded for brevity) I also need to store an additional attribute against the tag. Thanks in advance for your time...
It looks like you need to override the HTMLDocument to return a reader that recognises the custom tags. See [HTMLDocument#getReader](http://java.sun.com/javase/6/docs/api/javax/swing/text/html/HTMLDocument.html#getReader(int)) for more information. You'll need to return a subclass of [HTMLReader](http://java.sun.com/javase/6/docs/api/javax/swing/text/html/HTMLDocument.HTMLReader.html) which understands the custom tag (via the registerTag method).
perhaps set your detail as an attribute of your tag?
How can I handle custom tags in a Java HTMLDocument?
[ "", "java", "html", "jeditorpane", "" ]
What are the main benefits of using Mono over Java (or any other "free" or Linux-friendly language/runtime)? Mono will always trail behind the latest developments in the .NET framework, why would you want to use Mono over another traditional open-source language/framework (Java)? EDIT: Like someone mentioned below, I guess the root question is, why would you want to use .NET on the Linux platform?
The answer is pretty obvious: because you want to use .Net on Linux. This of course begs the question (which I think is really what you're getting at): why would you want to use .Net on Linux (over Java)? Lots of reasons: * Common code between your server and, say, a WPF or Winforms app; * Use of a particular .Net language, like F#; * Language features that aren't in Java (closures, operator overloading, partial classes, runtime generics, indexers, delegates, LINQ, var types, etc etc etc); * Your skills or those of your team are already in C#; * etc.
Personally, i have more trust in Linux platform as server, but want to use C# as program language.
What are the main benefits of using Mono over Java?
[ "", "java", ".net", "linux", "mono", "" ]
I'm experiencing this problem today on many different servers. **System.UnauthorizedAccessException: Access to the temp directory is denied.** The servers were not touched recently. The only thing that comes in my mind is a windows update breaking something.. Any idea? This happens when trying to access a webservice from an asp.net page ``` System.UnauthorizedAccessException: Access to the temp directory is denied. Identity 'NT AUTHORITY\NETWORK SERVICE' under which XmlSerializer is running does not have sufficient permission to access the temp directory. CodeDom will use the user account the process is using to do the compilation, so if the user doesnt have access to system temp directory, you will not be able to compile. Use Path.GetTempPath() API to find out the temp directory location. at System.Xml.Serialization.Compiler.Compile(Assembly parent, String ns, XmlSerializerCompilerParameters xmlParameters, Evidence evidence) at System.Xml.Serialization.TempAssembly.GenerateAssembly(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, Evidence evidence, XmlSerializerCompilerParameters parameters, Assembly assembly, Hashtable assemblies) at System.Xml.Serialization.TempAssembly..ctor(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, String location, Evidence evidence) at System.Xml.Serialization.XmlSerializer.FromMappings(XmlMapping[] mappings, Evidence evidence) at System.Web.Services.Protocols.XmlReturn.GetInitializers(LogicalMethodInfo[] methodInfos) at System.Web.Services.Protocols.HttpServerType..ctor(Type type) at System.Web.Services.Protocols.HttpServerProtocol.Initialize() at System.Web.Services.Protocols.ServerProtocol.SetContext(Type type, HttpContext context, HttpRequest request, HttpResponse response) at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing) ```
Have you checked the permissions on the temp folder? In these cases, the easiest and quickest solution is usually to re-run the *aspnet\_regiis -i* command to re-install the asp.net framework which also resets the permissions on the required folders. Failing that, try using [Process Monitor](http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx) to check what's going on and modify the permissions accordingly.
I had the same issue and none of the above solved our issue -- we restored service temporally by changing the setting that each app pool site was running under - you can do this by going into app pools--> idenity tab and and changing user from Network Service to local user- while we figured out what the problem was(this is not recommended- so if you choose to do this make sure you understand the repercussions) We then found a [link](http://support.microsoft.com/default.aspx?scid=kb;en-us;825791) about the Temp\TMP mappings and how to fix them -Which was not our issue On another [site](http://social.msdn.microsoft.com/Forums/en-US/tfswebaccess/thread/c43238f8-a2ef-4503-aec6-fbf46870d8a4) (and as described in other answers) we used `Path.GetTempPath()` to see what the CLR was actually looking for it turned out to be > C:\WINDOWS\system32\config\systemprofile\Local > Settings\Temp folder We then used [Process Monitor](http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx) to verify this was in fact correct, when we changed the permission on this folder it worked correctly. We are still unsure as to why the CLR choose to stop using the default temp directory but we did find a link as to how it makes that decision. [How GetTempPath is picked](https://stackoverflow.com/questions/2365307/what-determines-the-return-value-of-path-gettemppath). Update: We Finally figured out HOW our Temp folder PATH was changed when Someone decided to repeat the error! The Issue was the [**CLR Profiler**](http://msdn.microsoft.com/en-us/library/ff650691.aspx) *someone* decided to run on live which changes all permissions of the temp directory so If you didn't already know this already I would not recommend running it on a Prod server.
ASP.NET Access to the temp directory is denied
[ "", "c#", "asp.net", "exception", "" ]
I've seen many javascript objects that have a 'init' method that you pass in values to in order to setup the object. How do they internally handle the initializations of their private variables when passed in a array of name/value pairs like: myObject.init( {prop1: "blah", prop2: "asdf", ..., propn: "n"} ); Specifically, some of these values can be optional, so how would you setup defaults and then override them if the name/value pair was passed in during the init.
``` var myObject = { init: function(options) { this.foo = options.foo || 'some default'; this.bar = options.requiredArg; if (!this.bar) raiseSomeError(); } } ```
This tests ok on FF5, IE8, Chrome 12, Opera v11.5. It doesn't matter what the default values are, they will be overwritten if their key is in the calling list, if not they will be left alone. ``` var myObject = { prop1: 'default1', prop2: 'default2', prop3: 'default3', prop4: 'default4', prop5: 'default5', prop6: 'default6', init: function(options) { for(key in options) { if(this.hasOwnProperty(key)) { this[key] = options[key] } } } } myObject.init( {prop1: "blah", prop2: "asdf", prop5: "n"} ) ```
creating a object in javascript that has a 'init' method with optional name/value pairs
[ "", "javascript", "arrays", "initialization", "" ]
I have got a project that can copy files to another client's desktops in my domain.There is 300+ client machine.But there is a problem.When i run this project in a non admin user account in my domain.It cant copy files getting error about Access Denied , user restrictions.I wanna do this program like this , in non admin user account when user start to copy files ; first my program will get admin access by loggin in my admin user accoun to domain than will copy files.Than logout.How can i do this ? I wanna do this with C#.
I had a similar problem: Production needed to run one of my programs that processes files on a location on the network where they don't have any access. I ended up using Impersonation, which allowed me to run the file processing thread under a set of credentials set at runtime by my program. In AD I created a special user account with all required permissions for exclusive use by this program. I know it’s not at all secure, but it works and the odds that it would even occur to someone to hack my program to get these credentials is remote. Anyway, look into [Impersonation](http://msdn.microsoft.com/en-us/library/system.security.principal.windowsimpersonationcontext(VS.80).aspx) I found these resources helpful: [Safely Impersonating Another User](http://blogs.msdn.com/shawnfa/archive/2005/03/22/400749.aspx) [Brian Low's ImpersonationHelper class](http://www.brianlow.com/index.php/2007/04/20/impersonate-user/) -Jay
You can switch privileges when starting the program from itself or from another program. You can do this with two programs, one that runs as the user account and then launches your privileged application. (or launch itself with a different command line to indicate the different run-mode.) To launch a program in C# as a different user, do this, ``` // Create a secure version of the password SecureString pass = new SecureString(); foreach ( char c in _pass.Text ) { pass.AppendChar( c ); } Process process = Process.Start( "PrivilegedProgram.exe", _arguments, _user.Text, pass, _domain.Text ); ```
Login with Admin user to some domain and copy files client machines with C#
[ "", "c#", "file-io", "permissions", "copy", "dns", "" ]
I'm talking about things like page/stylesheet caching, minifying javascript, etc. Half of me thinks it's better to do these things as early as possible while still in development so I can be consciously aware of more realistic speed and response issues as well as interacting with something that more closely resembles what will be deployed into production, but the other half of my brain thinks it makes more sense to not do anything until just before launch so that I'm constantly working with the raw data that has not been optimized while in development. Is there common or conventional wisdom on this subject?
I do all optimizations at the end. That way I know when something doesn't work it is because the code is wrong. I've tried to optimize things too early at times, and realized that I wasted an hour because I was caching something etc.
Realize that a user spents most of his time waiting on frontend objects to (down)load. Your application may generate html in 0.1 second but the user spends at least 2 seconds waiting on all the images etc to load. Getting these download times to a small number will positively increase the user experience. A lot can be done already by enabling GZIP and using minified javascript libraries. You should download and install YSlow and configure your webserver with appropriate caching headers. This alone can save hundreds of miliseconds loading time. The last step is to optimize the amount of images using CSS sprites. Other steps can include minimizing css and javascript, but this will gain the least of all methods I mentioned already. To summarize, most of this can be done by properly configuring your webserver, the sprites however should be done during development.
At what point do you perform front-end optimization?
[ "", "javascript", "css", "performance", "optimization", "caching", "" ]
**I need to be able to trigger a event whenever an object is added to a `Queue<Delegate>`.** I created a new class that extends `Queue`: ``` public delegate void ChangedEventHandler(object sender, EventArgs e); public class QueueWithChange<Delegate> : Queue<Delegate> { public event ChangedEventHandler Changed; protected virtual void OnChanged(EventArgs e) { if (Changed != null) { Changed(this, e); } } } ``` And then attached the event from another class, like such: ``` QueueWithChange<TimerDelegate> eventQueue = new QueueWithChange<TimerDelegate>(); // eventQueue.Changed += new ChangedEventHandler(delegate(object s, EventArgs ex) { //This event is not being triggered, so this code is unreachable atm...and that is my problem if (eventQueue.Count > 0) { eventQueue.Dequeue().Invoke(new DispatcherTimer() { Interval = TimeSpan.FromMilliseconds(5) }); actionTimer.Stop(); } }); ``` But whenever I enqueue an object (`eventQueue.Enqueue(something)`), the attached event is not being fired. What am I missing here?
If you mean the non-generic `Queue` class, then you can just override `Enqueue`: ``` public override void Enqueue(object obj) { base.Enqueue(obj); OnChanged(EventArgs.Empty); } ``` However, if you mean the generic `Queue<T>` class, then note that there is no suitable virtual method to override. You might do better to **encapsulate** the queue with your own class: (\*\* important edit: removed base-class!!! \*\*) ``` class Foo<T> { private readonly Queue<T> queue = new Queue<T>(); public event EventHandler Changed; protected virtual void OnChanged() { if (Changed != null) Changed(this, EventArgs.Empty); } public virtual void Enqueue(T item) { queue.Enqueue(item); OnChanged(); } public int Count { get { return queue.Count; } } public virtual T Dequeue() { T item = queue.Dequeue(); OnChanged(); return item; } } ``` However, looking at your code, it seems possible that you are using multiple threads here. If that is the case, consider a [threaded queue](https://stackoverflow.com/questions/530211/creating-a-blocking-queuet-in-net) instead.
I just did write up on what I call a TriggeredQueue. It's inspired the answer by Marc Gravell. You can find my post here: [https://joesauve.com/triggeredqueuelttgt](https://www.joesauve.com/triggeredqueuelttgt/) And the Gist here: [http://gist.github.com/jsauve/b2e8496172fdabd370c4](https://gist.github.com/jsauve/b2e8496172fdabd370c4) It has four events: * WillEnqueue * WillDequeue * DidEnqueue * DidDequeue You can hook into any of these like so: ``` YourQueue.WillEnqueue += (sender, e) => { // kick off some process }; YourQueue.DidEnqueue += (sender, e) => { // kick off some process // e.Item provides access to the enqueued item, if you like }; YourQueue.WillDequeue += (sender, e) => { // kick off some process }; YourQueue.DidDequeue += (sender, e) => { // kick off some process // e.Item provides access to the dequeued item, if you like }; ``` One neat trick is that you can use the DidDequeue method to kick off some process to ensure that the queue is full by making a web request or loading some data from a filesystem, etc. I use this class in Xamarin mobile apps to ensure that data and images are pre-cached in order to provide a smooth user experience, instead of loading images AFTER they scroll onto the screen (like you might see in Facebook and countless other apps).
C#: Triggering an Event when an object is added to a Queue
[ "", "c#", "events", "delegates", "queue", "" ]
How would I return the column names of a table using SQL Server 2008? i.e. a table contains these columns- id, name, address, country and I want to return these as data.
Not sure if there is an easier way in 2008 version. ``` USE [Database Name] SELECT COLUMN_NAME,* FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'YourTableName' AND TABLE_SCHEMA='YourSchemaName' ```
This is the easiest way ``` exec sp_columns [tablename] ```
How do you return the column names of a table?
[ "", "sql", "sql-server", "t-sql", "" ]
I am in the process of converting an internal application to use more Ajax via jQuery. I am moving away from the standard code behind of the current ASP.NET application and incorporating JavaScript methods that are going to run client side. My concern is what is the best method for allowing this application to stay maintainable for those who come behind me.
I've found that build scripts are the key to success in maintainable Javascript. Essentially in order to have something fast and concise on the final page you need a script to make that maintainable in development. If you use a build process you can break your JS into files based on the functionality. You can use the debug versions of libraries during development, and leave glorious code comments smattered around your code with impunity. A build script should: * [Lint](http://www.jslint.com) all your code * Strip comments * Concatenate the files together * [Minify](http://javascript.crockford.com/jsmin.html)/Obfuscate/Compress the code * Version files for deployment * Push the version files to the server ready to be "turned on" in production This leaves you to work on files that make logical sense and it to tidy up after you for production.
I would say that applying the same sort of OOP principles to your javascript that you apply to server-side code is one of the best ways to enhance maintainability. Instead of global functions, think about creating classes that encapsulate your javascript methods and data. Use javascript unit testing frameworks to test this code to make sure that it is robust.
Making your javascript maintainable
[ "", "javascript", "jquery", "" ]
I want to be able to have LinkedList.contains() return true for a custom comparator. Suppose that I have 1 LinkedList and 2 objects ``` LinkedList<MyObject> myList = new LinkedList<MyObject>(); MyObject a = new MyObject("HELLO"); MyObject b = new MyObject("HELLO"); ``` Technicaly, both objects are identical in terms of comparison (MyObject implements Comparable) ( a == b ) == true however, when I do the following, myList does not return true for myList.contains(b) ``` myList.add(a) myList.contains(b) // == false ``` I think its because contains will check object reference and see that a and b are 2 distinct objects. Is there any way I can make it so I don't have to extend LinkedList to compare those objects?
LinkedList uses the equals method, not Comparable.compareTo. You should [override equals (and hashCode)](http://www.ibm.com/developerworks/java/library/j-jtp05273.html) in MyObject to solve the problem.
The `contains()` method uses `equals()` to determine whether an object is in the list. I suspect your class `MyObject` does not override the `equals()` method, and this will be why `myList.contains(b)` is returning `false`.
Compare objects in LinkedList.contains()
[ "", "java", "linked-list", "contains", "equality", "" ]
What is the best way to model the following... Assume I have two objects: `Agency` and `Publisher`, and both have a 1-to-n relationship to `Employee`. This is a true 1-to-n relationship, as each `Employee` can only work for one `Agency` or one `Publisher`. Let's assume further that I cannot introduce a supertype (e.g. `Employer`) which holds the 1-to-n relationship. My preferred solution is to have a foreign key in `Employee` that can either link to a primary key of `Agency` or `Publisher` (all my primary keys are 64-bit IDs that are unique across the database). However, now I won't be able to map a bi-directional association, without indicating in `Employee` whether this is an `Agency` or `Publisher` relationship. My other option is to use two tables, `AgencyEmployee` and `PublisherEmployee`, which can then be linked as traditional 1-to-n bidirectional associations. What do you consider best practice in this situation? UPDATE: Thanks for the great responses in such short amount of time! What do you think of the following solution: Foreign keys in `Employee` for both `Agency` and `Publisher`, such as `agency_id` and `publisher_id`?
The best practice would probably be introducing an Employer class. Dividing Employee into AgencyEmployee and PublisherEmployee, on the other hand, would be a Bad Thing™ to do. If introducing Employer was out of the question, I would indicate the employer type (Agency or Publisher) in Employee. **Response to the updated question:** That is an option, but employer\_type is better because: 1. You might want to add other employer types in the future 2. There will be an empty field in each row of the Employees table.
Sounds like this could be modeled as a [ternary relationship](http://msdn.microsoft.com/en-us/library/bb399189.aspx). See if you like the approach taken in this MSDN article.
"One-to-many" modeling question
[ "", "sql", "database-design", "orm", "data-modeling", "" ]
I have a \_Click event that is firing when a chart is clicked on. In this event I immediately cast the sender to type Chart. I often follow this paradigm but feel icky each time that I do. In this particular instance I am also immediately running out to find a corresponding UpdatePanel so I can add a dynamically rendered GridView to it. The Chart and UpdatePanel are cobbled together by having similar IDs. Both the chart and updatepanel are dynamically created at runtime. I am wondering if there is a better/preferred way to implement this sort of behavior. ``` protected void Chart_Click(object sender, ImageMapEventArgs e) { Chart chart = (Chart)sender; UpdatePanel up = (UpdatePanel)chart.Parent.FindControl(chart.ID + "UP"); GridView gv = new GridView(); Dictionary<string, string> displayFields = new Dictionary<string, string>(); // add data to displayFields by using the ImageMapEventArgs.PostBackValue // to create data for dictionary ... gv.DataSource = displayFields; gv.DataBind(); up.ContentTemplateContainer.Controls.Add(gv); } ```
I'm not sure what else can be done about casting sender to a chart (other than using `as`), but there are many ways to deal with the associated controls problem. * Add a property to the Chart called "LinkedPanel" and assign your update panel to it You'll see a similar pattern used in a notification icon, where you [associate it with a context menu](http://msdn.microsoft.com/en-us/library/system.windows.forms.notifyicon.contextmenu.aspx)) I think this is particularly nice, because when it's done right you can just assign the linked control in the form designer. (Of course it won't help with your dynamically generated controls) * Combine both controls into a single UserControl (if the controls always show right next to each other, this might be the right thing to do) * Create an object that knows about both controls, and have it handle the events that they raise I agree that depending on the name just feels wrong; I'd be too embarassed/nervous to use it in production code :-/ (If you're the only developer, then I guess it's up to you...) Using these other approaches makes it less likely that an "innocent change" made by another developer is going to start causing unexpected exceptions.
I think it's safe to cast sender to `Chart` because you know it's always a `Chart`. Note the method name is even `Chart_Click`. You could, however, save a reference to the `UpdatePanel` in the `Chart`'s `Tag` property. That saves the ugliness and risk of a name-search in the parent. Could get hard to maintain if you're constantly switching parents or moving panels around. If you know *100%* the `UpdatePanel`'s going to be there *and* named properly, however, there's nothing necessarily "wrong" with your approach IMHO. You might want to throw a "don't change this name" comment next to the `UpdatePanel.Name =` line where you initialize it though for security. (BTW, if you're not the only one with access to your code, the 100% instantly drops to at most a 99.9%.)
C# _Click Event Casting Sender and Using FindControl
[ "", "c#", ".net", "asp.net", "events", "" ]
Let's say I've got the following ActiveRecord class: ``` [ActiveRecord] public class Account { ... [BelongsTo("CustomerId")] public Customer Customer { get; set; } } ``` Currently, to set the value of the CustomerId field I have to get the entire Customer object from the database and assign it to the Account: ``` Customer customer = Customer.FindById(1); account.Customer = customer; ``` This isn't very efficient. I'd rather set the value of CustomerId field directly without round-tripping the database, e.g. ``` account.CustomerId = 1; ``` What's the correct way to do this?
You can implement MK8k's solution in ActiveRecord. It would look like this: ``` using (new SessionScope()) { var ghostCustomer = Customer.Find(customerId); var account = Account.TryFind(accountId); account.Customer = ghostCustomer; } ``` Two important points: The Customer.Find must be in a SessionScope. The Find method checks and will fully load your object if a SessionScope is not defined. The Customer class must be defined as lazy. NHibernate will not use a proxy for a non-lazy class.
I don't know how Castle ActiveRecord uses NHibernate to load objects from the database (using `ISession.Get` or `ISession.Load`?), but I know that the following can be done with NHibernate: ``` var ghostCustomer = session.Load<Customer>(customerId); var account = session.Get<Account>(accountId); account.Customer = ghostCustomer; ``` Here, `ghostCustomer` will be an unitialized proxy object, whose fields will be lazy loaded the first time they are accessed. But since we only use it to assign the customer relation on the account, it will never actually be loaded. Thus, the only database access in this example will happen when loading the account and afterwards when the session is flushed and the account must be updated.
NHibernate / ActiveRecord: How to set foreign key without getting entire object?
[ "", "c#", "nhibernate", "activerecord", "castle-activerecord", "" ]
I'm working with a library that uses Environment.NewLine as it's newline char when writing a file. I need it to write Unix formatted files, and as such would like to change the newline char. Can I change the value of Environment.NewLine? Any other ideas (aside from converting the file post creation)?
> Can I change the value of Environment.NewLine? No. If you know which platform to write for, create classes for each of these platforms and let them have their own implementation. In the simplest case, this would look as follows: ``` public abstract class Platform { public abstract string Newline { get; } } public sealed class Unix : Platform { public override string Newline { get { return "\n"; } } } ``` etc., and then just use an instance of the appropriate class.
Environment.Newline is returning the newline character of the runtime environment hosting the .Net runtime. You should not use this for conversion of newline to another platform's newline character. I would recommend to implement your own class for conversions.
Can I change the value of Environment.NewLine?
[ "", "c#", ".net", "newline", "" ]
Are there some good resources for fixed point math in C#? I've seen things like this (<http://2ddev.72dpiarmy.com/viewtopic.php?id=156>) and this (*[What's the best way to do fixed-point math?](https://stackoverflow.com/questions/79677/whats-the-best-way-to-do-fixed-point-math)*), and a number of discussions about whether decimal is really fixed point or actually floating point (update: responders have confirmed that it's definitely floating point), but I haven't seen a solid C# library for things like calculating cosine and sine. My needs are simple -- I need the basic operators, plus cosine, sine, arctan2, [π](https://en.wikipedia.org/wiki/Pi), etc. I think that's about it. Maybe sqrt. I'm programming a two-dimensional [RTS](https://en.wikipedia.org/wiki/Real-time_strategy) game, which I have largely working, but the unit movement when using floating-point math (doubles) has very small inaccuracies over time (10-30 minutes) across multiple machines, leading to desyncs. This is presently only between a 32-bit OS and a 64-bit OS. All the 32-bit machines seem to stay in sync without issue, which is what makes me think this is a floating point issue. I was aware from this as a possible issue from the outset, and so have limited my use of non-integer position math as much as possible, but for smooth diagonal movement at varying speeds I'm calculating the angle between points in radians, then getting the x and y components of movement with sin and cos. That's the main issue. I'm also doing some calculations for line segment intersections, line-circle intersections, circle-rect intersections, etc, that also probably need to move from floating-point to fixed-point to avoid cross-machine issues. If there's something open source in Java or [Visual Basic](https://en.wikipedia.org/wiki/Visual_Basic) or another comparable language, I could probably convert the code for my uses. The main priority for me is accuracy, although I'd like as little speed loss over present performance as possible. This whole fixed point math thing is very new to me, and I'm surprised by how little practical information on it there is on Google -- most stuff seems to be either theory or dense C++ header files. Anything you could do to point me in the right direction is much appreciated; if I can get this working, I plan to open-source the math functions I put together so that there will be a resource for other C# programmers out there. I could definitely make a cosine/sine lookup table work for my purposes, but I don't think that would work for arctan2, since I'd need to generate a table with about 64,000x64,000 entries (yikes). If you know any programmatic explanations of efficient ways to calculate things like arctan2, that would be awesome. My math background is all right, but the advanced formulas and traditional math notation are very difficult for me to translate into code.
Ok, here's what I've come up with for a fixed-point struct, based on the link in my original question but also including some fixes to how it was handling division and multiplication, and added logic for modules, comparisons, shifts, etc: ``` public struct FInt { public long RawValue; public const int SHIFT_AMOUNT = 12; //12 is 4096 public const long One = 1 << SHIFT_AMOUNT; public const int OneI = 1 << SHIFT_AMOUNT; public static FInt OneF = FInt.Create( 1, true ); #region Constructors public static FInt Create( long StartingRawValue, bool UseMultiple ) { FInt fInt; fInt.RawValue = StartingRawValue; if ( UseMultiple ) fInt.RawValue = fInt.RawValue << SHIFT_AMOUNT; return fInt; } public static FInt Create( double DoubleValue ) { FInt fInt; DoubleValue *= (double)One; fInt.RawValue = (int)Math.Round( DoubleValue ); return fInt; } #endregion public int IntValue { get { return (int)( this.RawValue >> SHIFT_AMOUNT ); } } public int ToInt() { return (int)( this.RawValue >> SHIFT_AMOUNT ); } public double ToDouble() { return (double)this.RawValue / (double)One; } public FInt Inverse { get { return FInt.Create( -this.RawValue, false ); } } #region FromParts /// <summary> /// Create a fixed-int number from parts. For example, to create 1.5 pass in 1 and 500. /// </summary> /// <param name="PreDecimal">The number above the decimal. For 1.5, this would be 1.</param> /// <param name="PostDecimal">The number below the decimal, to three digits. /// For 1.5, this would be 500. For 1.005, this would be 5.</param> /// <returns>A fixed-int representation of the number parts</returns> public static FInt FromParts( int PreDecimal, int PostDecimal ) { FInt f = FInt.Create( PreDecimal, true ); if ( PostDecimal != 0 ) f.RawValue += ( FInt.Create( PostDecimal ) / 1000 ).RawValue; return f; } #endregion #region * public static FInt operator *( FInt one, FInt other ) { FInt fInt; fInt.RawValue = ( one.RawValue * other.RawValue ) >> SHIFT_AMOUNT; return fInt; } public static FInt operator *( FInt one, int multi ) { return one * (FInt)multi; } public static FInt operator *( int multi, FInt one ) { return one * (FInt)multi; } #endregion #region / public static FInt operator /( FInt one, FInt other ) { FInt fInt; fInt.RawValue = ( one.RawValue << SHIFT_AMOUNT ) / ( other.RawValue ); return fInt; } public static FInt operator /( FInt one, int divisor ) { return one / (FInt)divisor; } public static FInt operator /( int divisor, FInt one ) { return (FInt)divisor / one; } #endregion #region % public static FInt operator %( FInt one, FInt other ) { FInt fInt; fInt.RawValue = ( one.RawValue ) % ( other.RawValue ); return fInt; } public static FInt operator %( FInt one, int divisor ) { return one % (FInt)divisor; } public static FInt operator %( int divisor, FInt one ) { return (FInt)divisor % one; } #endregion #region + public static FInt operator +( FInt one, FInt other ) { FInt fInt; fInt.RawValue = one.RawValue + other.RawValue; return fInt; } public static FInt operator +( FInt one, int other ) { return one + (FInt)other; } public static FInt operator +( int other, FInt one ) { return one + (FInt)other; } #endregion #region - public static FInt operator -( FInt one, FInt other ) { FInt fInt; fInt.RawValue = one.RawValue - other.RawValue; return fInt; } public static FInt operator -( FInt one, int other ) { return one - (FInt)other; } public static FInt operator -( int other, FInt one ) { return (FInt)other - one; } #endregion #region == public static bool operator ==( FInt one, FInt other ) { return one.RawValue == other.RawValue; } public static bool operator ==( FInt one, int other ) { return one == (FInt)other; } public static bool operator ==( int other, FInt one ) { return (FInt)other == one; } #endregion #region != public static bool operator !=( FInt one, FInt other ) { return one.RawValue != other.RawValue; } public static bool operator !=( FInt one, int other ) { return one != (FInt)other; } public static bool operator !=( int other, FInt one ) { return (FInt)other != one; } #endregion #region >= public static bool operator >=( FInt one, FInt other ) { return one.RawValue >= other.RawValue; } public static bool operator >=( FInt one, int other ) { return one >= (FInt)other; } public static bool operator >=( int other, FInt one ) { return (FInt)other >= one; } #endregion #region <= public static bool operator <=( FInt one, FInt other ) { return one.RawValue <= other.RawValue; } public static bool operator <=( FInt one, int other ) { return one <= (FInt)other; } public static bool operator <=( int other, FInt one ) { return (FInt)other <= one; } #endregion #region > public static bool operator >( FInt one, FInt other ) { return one.RawValue > other.RawValue; } public static bool operator >( FInt one, int other ) { return one > (FInt)other; } public static bool operator >( int other, FInt one ) { return (FInt)other > one; } #endregion #region < public static bool operator <( FInt one, FInt other ) { return one.RawValue < other.RawValue; } public static bool operator <( FInt one, int other ) { return one < (FInt)other; } public static bool operator <( int other, FInt one ) { return (FInt)other < one; } #endregion public static explicit operator int( FInt src ) { return (int)( src.RawValue >> SHIFT_AMOUNT ); } public static explicit operator FInt( int src ) { return FInt.Create( src, true ); } public static explicit operator FInt( long src ) { return FInt.Create( src, true ); } public static explicit operator FInt( ulong src ) { return FInt.Create( (long)src, true ); } public static FInt operator <<( FInt one, int Amount ) { return FInt.Create( one.RawValue << Amount, false ); } public static FInt operator >>( FInt one, int Amount ) { return FInt.Create( one.RawValue >> Amount, false ); } public override bool Equals( object obj ) { if ( obj is FInt ) return ( (FInt)obj ).RawValue == this.RawValue; else return false; } public override int GetHashCode() { return RawValue.GetHashCode(); } public override string ToString() { return this.RawValue.ToString(); } } public struct FPoint { public FInt X; public FInt Y; public static FPoint Create( FInt X, FInt Y ) { FPoint fp; fp.X = X; fp.Y = Y; return fp; } public static FPoint FromPoint( Point p ) { FPoint f; f.X = (FInt)p.X; f.Y = (FInt)p.Y; return f; } public static Point ToPoint( FPoint f ) { return new Point( f.X.IntValue, f.Y.IntValue ); } #region Vector Operations public static FPoint VectorAdd( FPoint F1, FPoint F2 ) { FPoint result; result.X = F1.X + F2.X; result.Y = F1.Y + F2.Y; return result; } public static FPoint VectorSubtract( FPoint F1, FPoint F2 ) { FPoint result; result.X = F1.X - F2.X; result.Y = F1.Y - F2.Y; return result; } public static FPoint VectorDivide( FPoint F1, int Divisor ) { FPoint result; result.X = F1.X / Divisor; result.Y = F1.Y / Divisor; return result; } #endregion } ``` Based on the comments from ShuggyCoUk, I see that this is in [Q12](https://en.wikipedia.org/wiki/Q_%28number_format%29#Texas_Instruments_version) format. That's reasonably precise for my purposes. Of course, aside from the bugfixes, I already had this basic format before I asked my question. What I was looking for were ways to calculate Sqrt, Atan2, Sin, and Cos in C# using a structure like this. There aren't any other things that I know of in C# that will handle this, but in Java I managed to find the [MathFP](http://home.comcast.net/%7Eohommes/MathFP/) library by Onno Hommes. It's a liberal source software license, so I've converted some of his functions to my purposes in C# (with a fix to atan2, I think). Enjoy: ``` #region PI, DoublePI public static FInt PI = FInt.Create( 12868, false ); //PI x 2^12 public static FInt TwoPIF = PI * 2; //radian equivalent of 260 degrees public static FInt PIOver180F = PI / (FInt)180; //PI / 180 #endregion #region Sqrt public static FInt Sqrt( FInt f, int NumberOfIterations ) { if ( f.RawValue < 0 ) //NaN in Math.Sqrt throw new ArithmeticException( "Input Error" ); if ( f.RawValue == 0 ) return (FInt)0; FInt k = f + FInt.OneF >> 1; for ( int i = 0; i < NumberOfIterations; i++ ) k = ( k + ( f / k ) ) >> 1; if ( k.RawValue < 0 ) throw new ArithmeticException( "Overflow" ); else return k; } public static FInt Sqrt( FInt f ) { byte numberOfIterations = 8; if ( f.RawValue > 0x64000 ) numberOfIterations = 12; if ( f.RawValue > 0x3e8000 ) numberOfIterations = 16; return Sqrt( f, numberOfIterations ); } #endregion #region Sin public static FInt Sin( FInt i ) { FInt j = (FInt)0; for ( ; i < 0; i += FInt.Create( 25736, false ) ) ; if ( i > FInt.Create( 25736, false ) ) i %= FInt.Create( 25736, false ); FInt k = ( i * FInt.Create( 10, false ) ) / FInt.Create( 714, false ); if ( i != 0 && i != FInt.Create( 6434, false ) && i != FInt.Create( 12868, false ) && i != FInt.Create( 19302, false ) && i != FInt.Create( 25736, false ) ) j = ( i * FInt.Create( 100, false ) ) / FInt.Create( 714, false ) - k * FInt.Create( 10, false ); if ( k <= FInt.Create( 90, false ) ) return sin_lookup( k, j ); if ( k <= FInt.Create( 180, false ) ) return sin_lookup( FInt.Create( 180, false ) - k, j ); if ( k <= FInt.Create( 270, false ) ) return sin_lookup( k - FInt.Create( 180, false ), j ).Inverse; else return sin_lookup( FInt.Create( 360, false ) - k, j ).Inverse; } private static FInt sin_lookup( FInt i, FInt j ) { if ( j > 0 && j < FInt.Create( 10, false ) && i < FInt.Create( 90, false ) ) return FInt.Create( SIN_TABLE[i.RawValue], false ) + ( ( FInt.Create( SIN_TABLE[i.RawValue + 1], false ) - FInt.Create( SIN_TABLE[i.RawValue], false ) ) / FInt.Create( 10, false ) ) * j; else return FInt.Create( SIN_TABLE[i.RawValue], false ); } private static int[] SIN_TABLE = { 0, 71, 142, 214, 285, 357, 428, 499, 570, 641, 711, 781, 851, 921, 990, 1060, 1128, 1197, 1265, 1333, 1400, 1468, 1534, 1600, 1665, 1730, 1795, 1859, 1922, 1985, 2048, 2109, 2170, 2230, 2290, 2349, 2407, 2464, 2521, 2577, 2632, 2686, 2740, 2793, 2845, 2896, 2946, 2995, 3043, 3091, 3137, 3183, 3227, 3271, 3313, 3355, 3395, 3434, 3473, 3510, 3547, 3582, 3616, 3649, 3681, 3712, 3741, 3770, 3797, 3823, 3849, 3872, 3895, 3917, 3937, 3956, 3974, 3991, 4006, 4020, 4033, 4045, 4056, 4065, 4073, 4080, 4086, 4090, 4093, 4095, 4096 }; #endregion private static FInt mul( FInt F1, FInt F2 ) { return F1 * F2; } #region Cos, Tan, Asin public static FInt Cos( FInt i ) { return Sin( i + FInt.Create( 6435, false ) ); } public static FInt Tan( FInt i ) { return Sin( i ) / Cos( i ); } public static FInt Asin( FInt F ) { bool isNegative = F < 0; F = Abs( F ); if ( F > FInt.OneF ) throw new ArithmeticException( "Bad Asin Input:" + F.ToDouble() ); FInt f1 = mul( mul( mul( mul( FInt.Create( 145103 >> FInt.SHIFT_AMOUNT, false ), F ) - FInt.Create( 599880 >> FInt.SHIFT_AMOUNT, false ), F ) + FInt.Create( 1420468 >> FInt.SHIFT_AMOUNT, false ), F ) - FInt.Create( 3592413 >> FInt.SHIFT_AMOUNT, false ), F ) + FInt.Create( 26353447 >> FInt.SHIFT_AMOUNT, false ); FInt f2 = PI / FInt.Create( 2, true ) - ( Sqrt( FInt.OneF - F ) * f1 ); return isNegative ? f2.Inverse : f2; } #endregion #region ATan, ATan2 public static FInt Atan( FInt F ) { return Asin( F / Sqrt( FInt.OneF + ( F * F ) ) ); } public static FInt Atan2( FInt F1, FInt F2 ) { if ( F2.RawValue == 0 && F1.RawValue == 0 ) return (FInt)0; FInt result = (FInt)0; if ( F2 > 0 ) result = Atan( F1 / F2 ); else if ( F2 < 0 ) { if ( F1 >= 0 ) result = ( PI - Atan( Abs( F1 / F2 ) ) ); else result = ( PI - Atan( Abs( F1 / F2 ) ) ).Inverse; } else result = ( F1 >= 0 ? PI : PI.Inverse ) / FInt.Create( 2, true ); return result; } #endregion #region Abs public static FInt Abs( FInt F ) { if ( F < 0 ) return F.Inverse; else return F; } #endregion ``` There are a number of other functions in Dr. Hommes' MathFP library, but they were beyond what I needed, and so I have not taken the time to translate them to C# (that process was made extra difficult by the fact that he was using a long, and I am using the FInt struct, which makes the conversion rules are a bit challenging to see immediately). The accuracy of these functions as they are coded here is more than enough for my purposes, but if you need more you can increase the SHIFT AMOUNT on FInt. Just be aware that if you do so, the constants on Dr. Hommes' functions will then need to be divided by 4096 and then multiplied by whatever your new SHIFT AMOUNT requires. You're likely to run into some bugs if you do that and aren't careful, so be sure to run checks against the built-in Math functions to make sure that your results aren't being put off by incorrectly adjusting a constant. So far, this FInt logic seems as fast, if not perhaps a bit faster, than the equivalent built in .NET functions. That would obviously vary by machine, since the floating point coprocessor would determine that, so I have not run specific benchmarks. But they are integrated into my game now, and I've seen a slight decrease in processor utilization compared to before (this is on a [Q6600](https://en.wikipedia.org/wiki/Kentsfield_%28microprocessor%29) quad core -- about a 1% drop in usage on average).
I've implemented a fixed-point Q31.32 type in C#. It performs all basic arithmetic, sqrt, sin, cos, tan, and is well covered by unit tests. You can find it [here](https://github.com/asik/FixedMath.Net), and the interesting type is Fix64. Note that the library also includes Fix32, Fix16 and Fix8 types, but those were mainly for experimenting and are not as complete and bug-free.
Fixed point math in C#
[ "", "c#", "math", "fixed-point", "" ]
I'm looking for alternatives to client side Javascript in web programming, because for me this language just plain sucks. I mean I am indeed impressed of the capabilities jquery or other javascript-frameworks accomplish, but for myself programming in javascript is a pain in the rump. I would like to replace it without sacrifice functionality. But I think there is no real alternative, at least I'm not aware of. What is your recommendation?
Javascript can be rough because it is running in browser environments that you have little control over. [Firebug](http://getfirebug.com/) on firefox is an immense help. The [Google Web Toolkit](http://code.google.com/webtoolkit/) allows you to write in java and "compiles" to javascript. More info on it here: <http://code.google.com/webtoolkit/> Back to javascript, it is best to start small and understand what is going on. If you always start with frameworks, it is very hard to know the "how" behind it. But really, once you deal with a few cross-browser bugs, it's not too bad! Like any language, you can write "clear" code, or "unclear" code. If you choose the former, you can turn it from a Pain-in-the-rump, to a pleasure.
Javascript is an awesome beast when tamed. Learn it and love it. :) I'm also not quite sure what your experiences are with jQuery, but I am a big fan of it because it lets you do what you want to do very, very, easily. Just hang in there.
Web programming: Get rid of Javascript or convince me to dive into this mess
[ "", "javascript", "client", "" ]
I don’t have any experience in F# but have a few lines of test code in C# for a framework I've made that I need to rewrite in F#. Any help would be appreciated. ``` bar.Ready += new Agent.ReadyHandler(bar_Ready); static void bar_Ready(string msg) { Console.WriteLine(msg.body); } ```
I have played a lot with this and this is the code that work. ``` bar.add_Ready(fun msg -> Console.WriteLine(msg)) ``` I don't know how theoreticly correct it is but it works fine. Can any one confirm it is correct?
Just to clarify - the shorter version should correctly be: ``` bar.Ready.Add(fun msg -> System.Console.WriteLine(msg)) ``` Because F# doesn't automatically convert lambda functions to delegates - but there is an Add method that takes a function. This can then be written even simpler like this: ``` bar.Ready.Add(System.Console.WriteLine) ``` Because F# allows you to use .NET members as first-class functions.
Events and Delegates in F#
[ "", "c#", ".net", "f#", "" ]
on my company we are developing a ERP-like app using java and jsf, so far the design team has identified about 20 entities,each with diferent properties, usually we'll be building 20 pages of CRUD , is there any better way to do this?, we are using hibernate as db access, so we came up with the idea of a single DAO for this part of the system, have you faced a similiar situation? what are your thoughts on it?
You might consider codegenerating those 20 screens, much like scaffolding in Ruby does. As far as DAO is concerned, you might pull CUD operations to some generic IBusinessObjectDao, leaving specific R operations (querying by various parameters) to concrete DAO implementations.
You really should look into Seam. It has a feature called [Seam-Gen](http://docs.jboss.com/seam/2.1.1.GA/reference/en-US/html/gettingstarted.html) that will reverse engineer your entire application CRUD pages from the database. You can edit the Seam-Gen templates (which are based on Freemarker) to customise the pages that will be generated to your liking. I use the Eclipse plugin [Azzurri Clay](http://www.azzurri.jp/en/clay/index.html) to model my database and generate the DDL. I then run Seam-Gen and in a few seconds you have a running application. It's a very handy combination.
Best strategy to multiple CRUD with jsf
[ "", "java", "hibernate", "jsf", "crud", "" ]
How can I get a list of assemblies in a given location? I'm trying to reflect over the appdomain, and that's giving me everything that's loaded. I just want what's in the executing assembly's directory.
The solution provided by [BtBh](https://stackoverflow.com/users/6088/btbh) works to find all files with extension .dll. [Ricards](https://stackoverflow.com/users/67392/richard) remarks that only .Net runtime can tell you what is valid assembly. This means that you would have to explicitly load every .dll file found to check whether it is a valid .Net assembly (it could just be a plain old Windows dll). As mentioned by [Josh](https://stackoverflow.com/users/26160/josh) there is a static method [Assembly.ReflectionOnlyLoadFrom](http://msdn.microsoft.com/en-us/library/system.reflection.assembly.reflectiononlyloadfrom.aspx) that allows you to load assemblies for inspection via reflection.
To get the executing assembly path: ``` using System.IO; String path= Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().Location); ``` To get all assemblies: ``` DirectoryInfo di= new DirectoryInfo(path); FileInfo[] fis = di.GetFiles("*.dll"); foreach(FileInfo fis in fls ) //do something ```
Find assemblies in a directory
[ "", "c#", "reflection", "" ]
Ok, here's my situation: I have an Array of States, which may contain duplicates. To get rid of the duplicates, I can add them all to a Set. However when I create the Set, it wants the initial capacity and load factor to be defined, but what should they be set to? From googling, I have come up with: ``` String[] allStates = getAllStates(); Set<String> uniqueStates = new HashSet<String>(allStates.length, 0.75); ``` The problem with this, is that allStates can contain anwhere between 1 and 5000 states. So the Set will have capacity of over 5000, but only containing at most 50. So alternatively set the max size of the Set could be set to be the max number of states, and the load factor to be 1. I guess my questions really are: * What should you set the initial capacity to be when you don't know how many items are to be in the Set? * Does it really matter what it gets set to when the most it could contain is 50? * Should I even be worrying about it?
Assuming that you know there won't be more than 50 states (do you mean US States?), the ``` Set<String> uniqueStates = new HashSet<String>(allStates.length, 0.75); ``` quoted is definitely wrong. I'd suggest you go for an initial capacity of 50 / 0.75 = 67, or perhaps 68 to be on the safe side. I also feel the need to point out that you're probably overthinking this intensely. Resizing the arraylist twice from 16 up to 64 isn't going to give you a noticeable performance hit unless this is right in the most performance-critical part of the program. So the best answer is probably to use: ``` new HashSet<String>(); ``` That way, you won't come back a year later and puzzle over why you chose such strange constructor arguments.
Use the [constructor](http://java.sun.com/j2se/1.5.0/docs/api/java/util/HashSet.html#HashSet()) where you don't need to specify these values, then reasonable defaults are chosen.
Choosing the initial capacity of a HashSet with an expected number of unique values and insertions
[ "", "java", "set", "" ]
What is out there on conventions and tools for documenting python source code?
[Epydoc](http://epydoc.sourceforge.net/) is also a good tool for documenting source code, and handles cross-referencing classes, modules, variables, etc, into HTML, PDF, LaTeX. Draws some nice class inheritance diagrams too. It's used by a number of open-source projects, so it's fairly actively developed.
Conventions: [PEP 257](http://www.python.org/dev/peps/pep-0257/) and [PEP 8](http://www.python.org/dev/peps/pep-0008/). Note, that docstrings can be written in [reStructuredText](http://docutils.sourceforge.net/rst.html) Tools for generating documentation: for example [Sphinx](http://sphinx.pocoo.org/)
code documentation for python
[ "", "python", "documentation", "documentation-generation", "" ]
My thread runs forever and calls ConcurrentLinkedQueue#poll() after a ConcurrentLinkedQueue#peek(). But under some conditions, the thread seems to hang. I know this is a bit vague but can people confirm for me that the methods poll() or peek() will **NEVER** block. Thanks.
For what I can tell, the [ConcurrentLinkedQueue](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html) is a "wait-free" implementation. So I must assume that each independent call to `poll()` or `peek()` will **NEVER block**. Atomic operations on this collection are synchronized and each individual call to the queue is guaranteed thread-safe. There must be a problem with your code. For instance, if you do: ``` Object obj; if (queue.peek() != null) obj = queue.poll() ``` Does not garentee that `obj` will not be `null`.
According to the Javadoc, it seems that peek() and poll() should never block. I whipped up a quick producer/consumer test and I've gotten no blocking.
Will ConcurrentLinkedQueue#poll() ever block?
[ "", "java", "concurrency", "" ]
How can I append an XML document to an xml node in c#?
An `XmlDocument` *is* basically an `XmlNode`, so you can append it just like you would do for any other `XmlNode`. However, the difference arises from the fact that *this* `XmlNode` does not belong to the target document, therefore you will need to use the ImportNode method *and then* perform the append. ``` // xImportDoc is the XmlDocument to be imported. // xTargetNode is the XmlNode into which the import is to be done. XmlNode xChildNode = xSrcNode.ImportNode(xImportDoc, true); xTargetNode.AppendChild(xChildNode); ```
Yes: ``` XmlNode imported = targetNode.OwnerDocument.ImportNode(otherDocument.DocumentElement, true); targetNode.AppendChild(imported); ``` I think this creates a clone of your document though.
Append an xml document to an xml node in C#?
[ "", "c#", "xml", "" ]
I'm calling http\_get\_request\_headers() in a PHP file on a server running PHP 5. However, I'm getting Fatal error: Call to undefined function http\_get\_request\_headers(). Does anyone know what the problem might be? Does this function not come with plain PHP?
No it does not. You need a [PECL module](http://pecl.php.net/package/pecl_http) for that function to work. But you can use the contents of the $\_SERVER variable as stated in [this comment](http://us.php.net/reserved.variables.server#87195) on the php site. Alternatively you can use the [apache function](http://de.php.net/manual/en/function.apache-request-headers.php) if this is your web server.
If you're using version >= 2 of `pecl_http` you'll need to use the namespace syntax for calling the functions. Check out the [version 2 documentation here](http://devel-m6w6.rhcloud.com/mdref/http/Env/getRequestHeader) and [example here](http://techblog.willshouse.com/?p=5340) Basically `\http\Env::getRequestHeader()`
PHP Not Recognizing http_get_request_headers()?
[ "", "php", "http", "" ]
Using the new Rhino Mocks 3.5 Arrange/Act/Assert (AAA) Testing style, I'm having problems writing a test. I have a method that calls a method on a repository class. ActivateFoo, where my Foo object has an IsActive property. The result of the ActivateFoo object should change the property. Here is sample code: ``` [TestMethod] public void Should_update_foo_to_active_inside_of_repository() { // arrange var repo = MockRepository.GenerateMock<IRepository>(); var foo = new Foo() { ID = 1, IsActive = false }; var target = new Presenter(repo); repo.Expect(x => x.ActivateFoo(foo)).Return(true); // act target.Activate(foo); // assert Assert.IsTrue(foo.IsActive); repo.VerifyAllExpectations(); } ``` I'm guessing that the key piece of code would be inbetween "ActivateFoo(foo))." and "Return(true);". One point to clarify how the method chaining stuff works behind the scenes, If there is code written on the line I expect, does it matter if it is after Return() or before? (unless of course the solution is using the MethodOptions overload of Expect, or something else). Thanks in advance for any help.
You might want to try something out like this using the Do handler. I honestly feel ActivateFoo should be void return type. But here's the code for ActivateFoo with bool return type. ``` [TestMethod] public void Should_update_foo_to_active_inside_of_repository() { // arrange var repo = MockRepository.GenerateMock<IRepository>(); var foo = new Foo() { ID = 1, IsActive = false }; var target = new Presenter(repo); repo.Expect(x => x.ActivateFoo(foo)). Do(new ActivateFooDelegate(ActivateFooDelegateInstance)); // act target.Activate(foo); // assert Assert.IsTrue(foo.IsActive); repo.VerifyAllExpectations(); } private delegate bool ActivateFooDelegate(Foo f); public bool ActivateFooDelegateInstance(Foo f) { f.IsActive = true; return f.IsActive; } ```
Thanks to AB Kolan this is the resulting code I used and works. ``` [TestMethod] public void Should_update_foo_to_active_inside_of_repository() { // arrange var repo = MockRepository.GenerateMock<IRepository>(); var foo = new Foo() { ID = 1, IsActive = false }; var target = new Presenter(repo); repo.Expect(x => x.ActivateFoo(foo)). Do(new Func<Foo, bool>( delegate(Foo f) { f.IsActive = true; return true; } )); // act target.Activate(foo); // assert Assert.IsTrue(foo.IsActive); repo.VerifyAllExpectations(); } ``` I tend to not like to have to have extra methods of functions for single use of a test, preferring an inline delegate if possible. To address the issue of is this something I should be doing or not as far as the design. As the names are there, this isn't the exact code and inside of the target.Activate() method. The code in Activate() does some checking and if needed, will do the repository ActivateFoo(), and then check the result of that operation and do other things. So, it might be possible that at a later time I will have to refactor this out and separate the steps, but for now, I've got it to work. Thanks
Using Rhino Mocks how can I set a property of a parameter for a Mocked method
[ "", "c#", "unit-testing", "syntax", "mocking", "rhino-mocks", "" ]
I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this: ``` {'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}}, 'new york': {'queens county': {'plumbers': 9, 'salesmen': 36}}} ``` Now, maintaining and creating this is pretty painful; every time I have a new state/county/profession I have to create the lower layer dictionaries via obnoxious try/catch blocks. Moreover, I have to create annoying nested iterators if I want to go over all the values. I could also use tuples as keys, like such: ``` {('new jersey', 'mercer county', 'plumbers'): 3, ('new jersey', 'mercer county', 'programmers'): 81, ('new jersey', 'middlesex county', 'programmers'): 81, ('new jersey', 'middlesex county', 'salesmen'): 62, ('new york', 'queens county', 'plumbers'): 9, ('new york', 'queens county', 'salesmen'): 36} ``` This makes iterating over the values very simple and natural, but it is more syntactically painful to do things like aggregations and looking at subsets of the dictionary (e.g. if I just want to go state-by-state). Basically, sometimes I want to think of a nested dictionary as a flat dictionary, and sometimes I want to think of it indeed as a complex hierarchy. I could wrap this all in a class, but it seems like someone might have done this already. Alternatively, it seems like there might be some really elegant syntactical constructions to do this. How could I do this better? Addendum: I'm aware of `setdefault()` but it doesn't really make for clean syntax. Also, each sub-dictionary you create still needs to have `setdefault()` manually set.
> ## What is the best way to implement nested dictionaries in Python? This is a bad idea, don't do it. Instead, use a regular dictionary and use `dict.setdefault` where apropos, so when keys are missing under normal usage you get the expected `KeyError`. If you insist on getting this behavior, here's how to shoot yourself in the foot: Implement `__missing__` on a `dict` subclass to set and return a new instance. This approach has been available [(and documented)](http://docs.python.org/2/library/stdtypes.html#dict) since Python 2.5, and (particularly valuable to me) **it pretty prints just like a normal dict**, instead of the ugly printing of an autovivified defaultdict: ``` class Vividict(dict): def __missing__(self, key): value = self[key] = type(self)() # retain local pointer to value return value # faster to return than dict lookup ``` (Note `self[key]` is on the left-hand side of assignment, so there's no recursion here.) and say you have some data: ``` data = {('new jersey', 'mercer county', 'plumbers'): 3, ('new jersey', 'mercer county', 'programmers'): 81, ('new jersey', 'middlesex county', 'programmers'): 81, ('new jersey', 'middlesex county', 'salesmen'): 62, ('new york', 'queens county', 'plumbers'): 9, ('new york', 'queens county', 'salesmen'): 36} ``` Here's our usage code: ``` vividict = Vividict() for (state, county, occupation), number in data.items(): vividict[state][county][occupation] = number ``` And now: ``` >>> import pprint >>> pprint.pprint(vividict, width=40) {'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}}, 'new york': {'queens county': {'plumbers': 9, 'salesmen': 36}}} ``` ## Criticism A criticism of this type of container is that if the user misspells a key, our code could fail silently: ``` >>> vividict['new york']['queens counyt'] {} ``` And additionally now we'd have a misspelled county in our data: ``` >>> pprint.pprint(vividict, width=40) {'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}}, 'new york': {'queens county': {'plumbers': 9, 'salesmen': 36}, 'queens counyt': {}}} ``` # Explanation: We're just providing another nested instance of our class `Vividict` whenever a key is accessed but missing. (Returning the value assignment is useful because it avoids us additionally calling the getter on the dict, and unfortunately, we can't return it as it is being set.) Note, these are the same semantics as the most upvoted answer but in half the lines of code - nosklo's implementation: > ``` > class AutoVivification(dict): > """Implementation of perl's autovivification feature.""" > def __getitem__(self, item): > try: > return dict.__getitem__(self, item) > except KeyError: > value = self[item] = type(self)() > return value > ``` ## Demonstration of Usage Below is just an example of how this dict could be easily used to create a nested dict structure on the fly. This can quickly create a hierarchical tree structure as deeply as you might want to go. ``` import pprint class Vividict(dict): def __missing__(self, key): value = self[key] = type(self)() return value d = Vividict() d['foo']['bar'] d['foo']['baz'] d['fizz']['buzz'] d['primary']['secondary']['tertiary']['quaternary'] pprint.pprint(d) ``` Which outputs: ``` {'fizz': {'buzz': {}}, 'foo': {'bar': {}, 'baz': {}}, 'primary': {'secondary': {'tertiary': {'quaternary': {}}}}} ``` And as the last line shows, it pretty prints beautifully and in order for manual inspection. But if you want to visually inspect your data, implementing `__missing__` to set a new instance of its class to the key and return it is a far better solution. # Other alternatives, for contrast: ## `dict.setdefault` Although the asker thinks this isn't clean, I find it preferable to the `Vividict` myself. ``` d = {} # or dict() for (state, county, occupation), number in data.items(): d.setdefault(state, {}).setdefault(county, {})[occupation] = number ``` and now: ``` >>> pprint.pprint(d, width=40) {'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}}, 'new york': {'queens county': {'plumbers': 9, 'salesmen': 36}}} ``` A misspelling would fail noisily, and not clutter our data with bad information: ``` >>> d['new york']['queens counyt'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'queens counyt' ``` Additionally, I think setdefault works great when used in loops and you don't know what you're going to get for keys, but repetitive usage becomes quite burdensome, and I don't think anyone would want to keep up the following: ``` d = dict() d.setdefault('foo', {}).setdefault('bar', {}) d.setdefault('foo', {}).setdefault('baz', {}) d.setdefault('fizz', {}).setdefault('buzz', {}) d.setdefault('primary', {}).setdefault('secondary', {}).setdefault('tertiary', {}).setdefault('quaternary', {}) ``` Another criticism is that setdefault requires a new instance whether it is used or not. However, Python (or at least CPython) is rather smart about handling unused and unreferenced new instances, for example, it reuses the location in memory: ``` >>> id({}), id({}), id({}) (523575344, 523575344, 523575344) ``` ## An auto-vivified defaultdict This is a neat looking implementation, and usage in a script that you're not inspecting the data on would be as useful as implementing `__missing__`: ``` from collections import defaultdict def vivdict(): return defaultdict(vivdict) ``` But if you need to inspect your data, the results of an auto-vivified defaultdict populated with data in the same way looks like this: ``` >>> d = vivdict(); d['foo']['bar']; d['foo']['baz']; d['fizz']['buzz']; d['primary']['secondary']['tertiary']['quaternary']; import pprint; >>> pprint.pprint(d) defaultdict(<function vivdict at 0x17B01870>, {'foo': defaultdict(<function vivdict at 0x17B01870>, {'baz': defaultdict(<function vivdict at 0x17B01870>, {}), 'bar': defaultdict(<function vivdict at 0x17B01870>, {})}), 'primary': defaultdict(<function vivdict at 0x17B01870>, {'secondary': defaultdict(<function vivdict at 0x17B01870>, {'tertiary': defaultdict(<function vivdict at 0x17B01870>, {'quaternary': defaultdict( <function vivdict at 0x17B01870>, {})})})}), 'fizz': defaultdict(<function vivdict at 0x17B01870>, {'buzz': defaultdict(<function vivdict at 0x17B01870>, {})})}) ``` This output is quite inelegant, and the results are quite unreadable. The solution typically given is to recursively convert back to a dict for manual inspection. This non-trivial solution is left as an exercise for the reader. # Performance Finally, let's look at performance. I'm subtracting the costs of instantiation. ``` >>> import timeit >>> min(timeit.repeat(lambda: {}.setdefault('foo', {}))) - min(timeit.repeat(lambda: {})) 0.13612580299377441 >>> min(timeit.repeat(lambda: vivdict()['foo'])) - min(timeit.repeat(lambda: vivdict())) 0.2936999797821045 >>> min(timeit.repeat(lambda: Vividict()['foo'])) - min(timeit.repeat(lambda: Vividict())) 0.5354437828063965 >>> min(timeit.repeat(lambda: AutoVivification()['foo'])) - min(timeit.repeat(lambda: AutoVivification())) 2.138362169265747 ``` Based on performance, `dict.setdefault` works the best. I'd highly recommend it for production code, in cases where you care about execution speed. If you need this for interactive use (in an IPython notebook, perhaps) then performance doesn't really matter - in which case, I'd go with Vividict for readability of the output. Compared to the AutoVivification object (which uses `__getitem__` instead of `__missing__`, which was made for this purpose) it is far superior. # Conclusion Implementing `__missing__` on a subclassed `dict` to set and return a new instance is slightly more difficult than alternatives but has the benefits of * easy instantiation * easy data population * easy data viewing and because it is less complicated and more performant than modifying `__getitem__`, it should be preferred to that method. Nevertheless, it has drawbacks: * Bad lookups will fail silently. * The bad lookup will remain in the dictionary. Thus I personally prefer `setdefault` to the other solutions, and have in every situation where I have needed this sort of behavior.
``` class AutoVivification(dict): """Implementation of perl's autovivification feature.""" def __getitem__(self, item): try: return dict.__getitem__(self, item) except KeyError: value = self[item] = type(self)() return value ``` Testing: ``` a = AutoVivification() a[1][2][3] = 4 a[1][3][3] = 5 a[1][2]['test'] = 6 print a ``` Output: ``` {1: {2: {'test': 6, 3: 4}, 3: {3: 5}}} ```
What is the best way to implement nested dictionaries?
[ "", "python", "data-structures", "dictionary", "mapping", "autovivification", "" ]
I want to list the recent activities of a user on my site without doing too many queries. I have a table where I list all the things the user did with the date. ``` page_id - reference_id - reference_table - created_at - updated_at ``` The `reference_id` is the ID I need to search for in the reference\_table (example: comments). If I would do a `SELECT` on my activity table I would then have to query: ``` SELECT * FROM reference_table where id = reference_id LIMIT 1 ``` An activity can be a comment, a page update or a subscription. Depending which one it is, I need to fetch different data from other tables in my database For example if it is a comment, I need to fetch the author's name, the comment, if it is a reply I need to fetch the orignal comment username, etc. I've looked into UNION keyword to union all my tables but I'm getting the error > 1222 - The used SELECT statements have a different number of columns and it seems rather complicated to make it work because the amount of columns has to match and none of my table has the same amount of tables and I'm not to fond of create column for the fun of it. I've also looked into the CASE statement which also requires the amount of columns to match if I remember correctly (I could be wrong for this one though). Does anyone has an idea of how I could list the recent activities of a user without doing too many queries? I am using PHP and MySQL.
You probably want to split out the different activities into different tables. This will give you more flexiblity on how you query the data. If you choose to use UNION, make sure that the you use the same number of columns in each select query that the UNION is comprised of. **EDIT:** I was down-voted for my response, so perhaps I can give a better explanation. **Split Table into Separate Tables and UNION** I recommended this technique, because it will allow you to be more explicit about the resources for which you are querying. Having a single table for inserting is convenient, but you will always have to do separate queries to join with other tables to get meaningful information. Also, you database schema will be obfuscated by a single column being a foreign key for different tables depending on the data stored in that row. You could have tables for comment, update and subscription. These would have their own data which could be queried on individually. If, say, you wanted to look at ALL user activity, you could somewhat easily use a UNION as follows: ``` (SELECT 'comment', title, comment_id AS id, created FROM comment) UNION (SELECT 'update', title, update_id as id, created FROM update) UNION (SELECT 'subscription', title, subscription_id as id, created FROM subscription) ORDER BY created desc ``` This will provide you with a listing view. You could then link to the details of each type or load it on an ajax call. You could accomplish this with the method that you are currently using, but this will actually eliminate the need for the 'reference\_table' and will accomplish the same thing in a cleaner way (IMO).
The problem is that UNION should be used just to get **similar** recordsets together. If you try to unify two different queries (for example, with different columns being fetched) it's an error. If the nature of the queries is different (having different column count, or data types) you'll need to make several different queries and treat them all separately. Another approach (less elegant, I guess) would be LEFT JOINing your activities table with all the others, so you'll end up with a recordset with a lot of columns, and you'll need to check for each row which columns should be used depending on the activity nature. Again, I'd rather stick with the first one, since the second procudes a rather sparse recorset.
What is the best approach to list a user's recent activities in PHP/MySQL?
[ "", "php", "mysql", "" ]
Consider the following code: ``` partial class OurBusinessObject { partial void OnOurPropertyChanged() { if(ValidateOurProperty(this.OurProperty) == false) { this.OurProperty = OurBusinessObject.Default.OurProperty; } } } ``` That is, when the value of `OurProperty` in `OurBusinessObject` is changed, if the value is not valid, set it to be the default value. This pattern strikes me as code smell but others here (at my employer) do not agree. What are your thoughts? **Edited to add**: I've been asked to add an explanation for why this is thought to be okay. The idea was that rather than having the producers of the business object validate the data, the business object could validate its own properties, and set clean default values in cases when the validation failed. Further, it was thought, if the validation rules change, the business object producers won't have to change their logic as the business object will take care of validating and cleaning the data.
It absolutely horrible. Good luck trying to debug issues in Production. The only thing it can lead to is to cover bugs, which will just pop up somewhere else, where it will be not obvious at all where they are coming from.
I think I have to agree with you. This could definitely lead to issues where the logic unexpectedly returns to the defaults, which could be very difficult to debug. At the very least, this behavior should be logged, but this seems more like a case for throwing an exception.
Business Validation Logic Code Smell
[ "", "c#", ".net", "entity-framework", "business-logic", "" ]
I have an application that uses disabled JTextFields in several places which are intended to be transparent - allowing the background to show through instead of the text field's normal background. When running the new Nimbus LAF these fields are opaque (despite setting setOpaque(false)), and my UI is broken. It's as if the LAF is ignoring the opaque property. Setting a background color explicitly is both difficult in several places, and less than optimal due to background images actually doesn't work - it still paints it's LAF default background over the top, leaving a border-like appearance (the splash screen below has the background explicitly set to match the image). Any ideas on how I can get Nimbus to not paint the background for a JTextField? Note: I need a JTextField, rather than a JLabel, because I need the thread-safe setText(), and wrapping capability. Note: My fallback position is to continue using the system LAF, but Nimbus does look substantially better. See example images below. --- ## Conclusions The *surprise* at this behavior is due to a misinterpretation of what setOpaque() is meant to do - from the Nimbus bug report: > This is a problem the the orginal design of Swing and how it has been confusing for years. The issue is setOpaque(false) has had a side effect in exiting LAFs which is that of hiding the background which is not really what it is ment for. It is ment to say that the component my have transparent parts and swing should paint the parent component behind it. It's unfortunate that the Nimbus components also appear not to honor setBackground(null) which would otherwise be the recommended way to stop the background painting. Setting a fully transparent background seems unintuitive to me. In my opinion, setOpaque()/isOpaque() is a faulty public API choice which should have been only: ``` public boolean isFullyOpaque(); ``` I say this, because isOpaque()==true is a contract with Swing that the component subclass will take responsibility for painting it's entire background - which means the parent can skip painting that region if it wants (which is an important performance enhancement). Something external cannot *directly* change this contract (legitimately), whose fulfillment may be coded into the component. So the opacity of the component should not have been settable using setOpaque(). Instead something like setBackground(null) should cause many components to "not have a background" and therefore become not fully opaque. By way of example, in an ideal world most components should have an isOpaque() that looks like this: ``` public boolean isOpaque() { return (background!=null); } ``` --- [![Example](https://i.stack.imgur.com/Abu15.png)](https://i.stack.imgur.com/Abu15.png) [![alt text](https://i.stack.imgur.com/pFI5p.png)](https://i.stack.imgur.com/pFI5p.png)
I ran into this same issue last week using JTextPane. The setOpaque() method works as expected when using any look and feel other than nimbus. Apparently, the nimbus look and feel changes the behaviour we have come to expect with setOpaque() for many Components. Depending on how you look at it, it can be considered a bug. Check the comments on this sun bugid: [nimbus opaque bug](https://bugs.java.com/bugdatabase/view_bug?bug_id=6687960) The workaround that worked for me was: ``` myPane.setOpaque(false); // added by OP myPane.setBorder(BorderFactory.createEmptyBorder()); myPane.setBackground(new Color(0,0,0,0)); ``` --- Note from OP: I also had to ensure setOpaque(false) for JTextField so that the parent background was painted - just wanted to mention this for others who follow in case they had experimented with setOpaque(true), as I had.
Hey there Software Monkey. mmhh what about installing UI's subclasses replacement that actually respect the setOpaque behavior. I think it is something like setUI or something like that. You could grab the source code of the nimbus and see what's broken there ( if it is there ) , subclass it and install the "fixed" one. Yours sound quite intersting, do you have any screenshot we can see?
Java Nimbus LAF with transparent text fields
[ "", "java", "swing", "nimbus", "" ]
[Maven Archetypes](http://maven.apache.org/plugins/maven-archetype-plugin/) are the "templates" by which you can quickly generate a running example of a given framework or project type. I am trying to compile a list of all the Maven archetype catalogs currently active on the net. [From the Maven documentation about catalog files](http://maven.apache.org/plugins/maven-archetype-plugin/specification/archetype-catalog.html): > Knowledge about archetypes are stored > in catalogs. > > The catalogs are xml files. > > The Archetype Plugin comes bundled > with an internal catalog. This one is > used by default. > > The Archetype Plugin can use catalogs > from local filesystem and from HTTP > connections. So far, I've gathered this list of repositories that do publish catalogs, but would love to see if anyone knows of more: ``` mvn archetype:generate -DarchetypeCatalog=local -DarchetypeCatalog=remote -DarchetypeCatalog=http://repo.fusesource.com/maven2 -DarchetypeCatalog=http://cocoon.apache.org -DarchetypeCatalog=http://download.java.net/maven/2 -DarchetypeCatalog=http://myfaces.apache.org -DarchetypeCatalog=http://tapestry.formos.com/maven-repository -DarchetypeCatalog=http://scala-tools.org -DarchetypeCatalog=http://www.terracotta.org/download/reflector/maven2/ ``` Links to same: 1) [FuseSource](http://repo.fusesource.com/maven2/archetype-catalog.xml) 2) [Cocoon](http://cocoon.apache.org/archetype-catalog.xml) 3) [Java.net](http://download.java.net/maven/2/archetype-catalog.xml) 4) [MyFaces](http://myfaces.apache.org/archetype-catalog.xml) 5) [Tapestry](http://tapestry.formos.com/maven-repository/archetype-catalog.xml) 6) [Scala Catalog](http://scala-tools.org/archetype-catalog.xml) 7) [Terracotta Catalog](http://www.terracotta.org/download/reflector/maven2/archetype-catalog.xml) You'll notice that if the repository actually publishes an archetype catalog (all of the above do), you'll get a UI prompt of all the choices found in that `archetype-catalog.xml`. For example: ``` mvn archetype:generate -DarchetypeCatalog=http://scala-tools.org [INFO] No archetype defined. Using maven-archetype-quickstart (org.apache.maven.archetypes:maven-archetype-quickstart:1.0) Choose archetype: 1: http://scala-tools.org -> scala-archetype-simple (A simple scala project) 2: http://scala-tools.org -> lift-archetype-blank (A blank/empty liftweb project) 3: http://scala-tools.org -> lift-archetype-basic (A basic liftweb project (with DB, css, ...)) Choose a number: (1/2/3): ``` If you want to view the Scala catalog file directly for example, you can [browse to http://scala-tools.org/archetype-catalog.xml](http://scala-tools.org/archetype-catalog.xml) But if the repository doesn't provide an archetype-catalog.xml, then just as PascalT says, you'll need to know the name in advance (much less convenient) and pass it in command line arguments.
To be honest, I don't really see the point of building a list of all catalogs. It looks more "natural" to me to pick a project first and then add the catalog if required. This is why there is IMO more value in a list of archetypes. You'll need their name anyway, even if you have all catalogs in a list. Anyway, here are some candidates; * Grails has archetypes in <http://snapshots.repository.codehaus.org/>. * Atlassian has archetypes in <https://maven.atlassian.com/repository/public/> Edit: after Matthew clarification on archetype's catalogs. I misunderstood some concepts and my answer isn't clear and correct. The point of catalogs is exactly to **not have to know the names of archetypes in advance**. They are made to publish archetypes and allow `mvn archetype:generate` to list archetypes. So it makes sense to add "external" catalogs (understand not in the internal) to get a wider list of known archetypes when using `mvn archetype:generate`. For archetypes without a catalog, users have to type an horrible command that must be documented somewhere (because it requires knowledge of the artifact). Regarding my propositions: * Atlassian's archetypes are in the internal catalog. **Not a good proposition.** * Grails archetypes aren't in the internal catalog or in a published `archetype-catalog.xml`. **Not a good proposition.** * [ServiceMix](http://servicemix.apache.org/) has catalogs here <http://servicemix.apache.org/tooling/> (based on a `http://servicemix.apache.org/tooling/<version>/archetype-catalog.xml` pattern). **Valid proposition.** --- One fun thing I learned while digging this. The maven guys provides a nice tool that helps people developing archetypes to create a catalog XML: the `archetype:crawl` goal basically crawls a local Maven repository searching for Archetypes and generates/updates a `archetype-catalog.xml` file in `~/.m2/repository` by default. Projects, people just have to run periodically something like: ``` mvn archetype:crawl -Dcatalog=/var/www/html/archetype-catalog.xml ``` Grails doesn't provide a catalog. To create a project, [we have to run](http://www.grails.org/Maven+Integration): ``` mvn org.apache.maven.plugins:maven-archetype-plugin:2.0-alpha-4:generate -DarchetypeGroupId=org.grails \ -DarchetypeArtifactId=grails-maven-archetype \ -DarchetypeVersion=1.0 \ -DarchetypeRepository=http://snapshots.repository.codehaus.org \ -DgroupId=example -DartifactId=my-app ``` But once we did this, we have the archetype in our local repository. So if we type: ``` mvn archetype:crawl -Dcatalog=/home/<me>/.m2/archetype-catalog.xml ``` The archetype get listed in `~/.m2/archetype-catalog.xml` and we can now use the `mvn archetype:generate` for Grails too (see option 5): ``` mvn archetype:generate ... [INFO] No archetype defined. Using maven-archetype-quickstart (org.apache.maven.archetypes:maven-archetype-quickstart:1.0) Choose archetype: 1: local -> maven-archetype-archetype (archetype) 2: local -> maven-archetype-j2ee-simple (j2ee) 3: local -> maven-archetype-quickstart (quickstart) 4: local -> maven-archetype-webapp (webapp) 5: local -> grails-maven-archetype (maven-project) 6: internal -> appfuse-basic-jsf (AppFuse archetype for creating a web application with Hibernate, Spring and JSF) ... ``` This is of course a (hugly) workaround and it might have side effects (you won't see new versions of archetypes). Actually, I don't think the archetype:crawl goal is intended for this use. I would like all projects them to publish their archetypes.
Terracotta has one but I don't know the url off-hand...will post back. Also, I have used archetypes in the past from [AppFuse](http://appfuse.org/) (<http://static.appfuse.org/releases/>) and [Webtide](http://www.webtide.com/) although I don't know where to find their archetype catalogs. The Terracotta repository and catalog are here: <http://www.terracotta.org/download/reflector/maven2/> Perhaps this is useful: <http://docs.codehaus.org/display/MAVENUSER/Archetypes+List>
What are the URLs of all the Maven Archetype catalogs that you know about?
[ "", "java", "maven-2", "maven-plugin", "maven-archetype", "" ]
While I can't get my desktop, running Win7 64, to connect to our network printer, I'd like to be able to paste files, using [Input Director](http://www.inputdirector.com/), into a share on my laptop. There I'd like a FileSystemWatcher to pick them up and print, then delete them. How can I do thi? I assume I need to hook into the shell somehow, meaning my app can't be a service, but I'm really clueless here. I've installed Input Director, so I can move my cursor off my desktop desktop screen onto my laptop desktop, and just right click the file to print. However, I am still interested in learning ways to do the printing.
I suppose it would depend on what you are trying to print, since the app is responsible for rendering a document to the print device, not the shell itself. Isn't this just the long way round to finding correct drivers for your printer?
[System.Drawing.Printing](http://msdn.microsoft.com/en-us/library/system.drawing.printing.aspx) will help you do what you want. No need to hook into the shell, so you could do this as a service. Whenever you detect a new file, just ship it off to the printer. For more involved types (Word documents and such), you can use the Interop libraries to use Word itself to print the document. For example, [here](http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.documentclass.printout(VS.80).aspx) is the Interop.Word PrintOut method.
Programmatically Print Documents
[ "", "c#", ".net", "windows", "" ]
I have been looking for a while now to find a solution to accomplish the following system. I would like to build a PHP system on, let's say, domainA. On this domainA I will allow an administrator to 'create' a new website. This website contains only of pieces of text, which are all stored in a database. This, I know how to do. However, now I would like to make it possible that visitors that surf to domainB will be invisibly redirected to for example domainA.com/gateway.php?refdomain=domainB&page=xxx or something similar. I have a vague idea this should be done by .htaccess, but I don't really know how I can do this in the most easy way. If for example there are some POST or GET requests on domainB, this should keep working. Also images linked to <http://www.domainB.com/test.gif> should be invisibly loaded form www.domainA.com. I also know there are some CMS systems (eg drupal) which allow this feature, so it is possible, I just don't know how. Thank you for any advice that might point me in the right direction, kind regards, Digits
Basically, you'll want to point all your domains to the same directory (maybe using a wildcard in your [vhosts](http://httpd.apache.org/docs/2.0/vhosts/)) and then setup [urlrewrite](http://httpd.apache.org/docs/2.0/misc/rewriteguide.html); look at [this question](https://stackoverflow.com/questions/522452/how-do-i-do-url-rewriting-in-php) for an example, and it can be in a .htaccess file or Apache configuration. All requests that come in will go to the same gateway.php and you can extract the current domain and requests using `$_SERVER['REDIRECT_QUERY_STRING']`, `$_SERVER['REQUEST_URI']` and $`_SERVER['SERVER_NAME']` for example. See [`$_SERVER`](http://www.php.net/manual/en/reserved.variables.server.php). You'll then be able in your gateway.php to send the correct files.
Are you hosting both of these on the same machine? If so, something like [VirtualHosts](http://httpd.apache.org/docs/2.2/vhosts/) in Apache could solve this for you. [mod\_alias](http://httpd.apache.org/docs/2.2/mod/mod_alias.html) and [mod\_rewrite](http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html) might also be of some use to you.
Manage multiple websites from one domain
[ "", "php", ".htaccess", "" ]
I'd like to be able to detect when a USB key is inserted. Furthermore, if I can distinguish between USB key A and USB key B then I am in even better shape. Lastly, if I can uniquely identify the key using some sort of hardware serial number, MAC address or whatever, then I'm in the best shape of all. Basically I am looking at using a USB key as a hardware dongle to "unlock" my C# application.
All hard-drives have a Serial Number, USB flash drives are no different. Here is an article, with a sample project, that shows [how to get the non-volatile serial number](http://www.cfdan.com/posts/Retrieving_Non-Volatile_USB_Serial_Number_Using_C_Sharp.cfm). Basically you just need to enumerate the system drives and grab the PNPDeviceID property.
You need to retrieve the key's [Hardware ID](http://ezinearticles.com/?Unique-Hardware-ID-in-C&id=1057498). I don't see how to subscribe to the plugged-in event, but you could always have the user click a button too.
How can I uniquely identify a USB key from C#?
[ "", "c#", "windows", "" ]
I would like my form to output something like this: ``` Name: ___________ Company: ___________ Interested in ------------- Foo: [ ] Bar: [ ] Baz: [ ] ``` That is to say, I would like to have the 'Interested In' title inserted in the middle of my form output. One way of doing this would be to write out the template code for each field, and insert the heading as appropriate. However, I'd prefer not to do this. I suspect that there is something to do with formsets that will do what I want. *Is* there a way to do what I want, or do I just need to suck it up and accept that I need to write my template out longhand for this?
With [`FieldsetMixin`](http://github.com/muhuk/django-formfieldset/tree/master) you get Admin-like fieldsets. You create your form like this: ``` from django.forms import Form from formfieldset.forms import FieldsetMixin class MyForm(Form, FieldsetMixin): fieldsets = ( (u'', {'fields': ['name', 'company']}), (u'Interested in', {'fields': ['foo', 'bar', 'baz']}), ) # rest of the form ```
Django formsets are not the way to go: They are used if you need to edit multiple objects at the same time. HTML fieldsets are more like the correct way. I imagine you could group the name and company fields into one fieldset, and then the interest fields into another. On DjangoSnippets you can find a [template tag that aids the grouping](http://www.djangosnippets.org/snippets/663/). Using this snippet, you would define the grouping in your view as ``` fieldsets = ( ('', {'fields': ('name','company')}), ('Interested in', {'fields': ('foo','bar','baz')}) ) ``` Pass it to the template along with the form, and render the form with ``` {% draw_form form fieldsets %} ``` I would prefer not to define the grouping in the view, as it's mainly presentational issue and should belong to the view, but what the heck, this seems to do the job! *muhuk*'s solution though looks more elegant than this...
Inserting A Heading Into A Django Form
[ "", "python", "django", "forms", "" ]
I have the following snippet: ``` string base= tag1[j]; ``` That gives the invalid conversion error. What's wrong with my code below? How can I overcome it. Full code is here: ``` #include <iostream> #include <vector> #include <fstream> #include <sstream> #include <time.h> using namespace std; int main ( int arg_count, char *arg_vec[] ) { if (arg_count < 3 ) { cerr << "expected one argument" << endl; return EXIT_FAILURE; } // Initialize Random Seed srand (time(NULL)); string line; string tag1 = arg_vec[1]; string tag2 = arg_vec[2]; double SubsRate = 0.003; double nofTag = static_cast<double>(atoi(arg_vec[3])); vector <string> DNA; DNA.push_back("A"); DNA.push_back("C"); DNA.push_back("G"); DNA.push_back("T"); for (unsigned i=0; i < nofTag ; i++) { int toSub = rand() % 1000 + 1; if (toSub <= (SubsRate * 1000)) { // Mutate cout << toSub << " Sub" << endl; int mutateNo = 0; for (int j=0; j < tag1.size(); j++) { mutateNo++; string base = tag1[j]; // This fail int dnaNo = rand() % 4; if (mutateNo <= 3) { // Mutation happen at most at 3 position base = DNA[dnaNo]; } cout << tag1[j] << " " << dnaNo << " " << base << endl; //cout << base; } cout << endl; } else { // Don't mutate //cout << tag1 << endl; } } return 0; } ``` Why do I get an Invalid conversion from `char` to `const char*` when looping over a string?
The `std::string operator []` returns a single char. string cannot be instantiated with a single char. Use: `string base = string( 1, tag1[j] )` instead
Change it to ``` char base = tag1[j]; ```
Invalid Conversion Problem in C++
[ "", "c++", "string", "char", "" ]
I have a class for interacting with a memcache server. I have different functions for inserting, deleting and retrieving data. Originally each function made a call to `memcache_connect()`, however that was unnecessary, e.g.: ``` mc->insert() mc->get() mc->delete() ``` would make three memcache connections. I worked around this by creating a construct for the class: ``` function __construct() { $this->mem = memcache_connect( ... ); } ``` and then using `$this->mem` wherever the resource was needed, so each of the three functions use the same `memcache_connect` resource. This is alright, however if I call the class inside other classes, e.g.: ``` class abc { function __construct() { $this->mc = new cache_class; } } class def { function __construct() { $this->mc = new cache_class; } } ``` then it is still making two `memcache_connect` calls, when it only *needs* one. I can do this with globals but I would prefer not to use them if I don't have to. Example globals implementation: ``` $resource = memcache_connect( ... ); class cache_class { function insert() { global $resource; memcache_set( $resource , ... ); } function get() { global $resource; return memcache_get( $resource , ... ); } } ``` Then no matter how many times the class is called there will only be one call to `memcache_connect`. Is there a way to do this or should I just use globals?
I would code another class using singleton pattern for getting the only instance of memcache. Like this - ``` class MemCache { private static $instance = false; private function __construct() {} public static function getInstance() { if(self::$instance === false) { self::$instance = memcache_connect(); } return self::$instance; } } ``` and usage - ``` $mc = MemCache::getInstance(); memcache_get($mc, ...) ... ```
Pass in the MC instance: ``` class abc { function __construct($mc) { $this->mc = $mc; } } class def { function __construct($mc) { $this->mc = $mc; } } $mc = new cache_class; $abc = new abc($mc); ``` etc.
Share variables between functions in PHP without using globals
[ "", "php", "oop", "global", "" ]
I have a 32 bit in-proc STA VB6 dll. I sadly cannot do anything about this. My C# component greatly benefits from being 64 bit. Is there anyway to call/interface with this 32-bit dll from my 64 bit process? Any sort of wrapper or anything?
There's no direct way you can do this. Since you can't port the VB6 inproc dll I'd suggest you write a 32bit out of process server that implements the same interfaces and have it delegate down to the VB6 code. Then, your 64bit app can call the out of process server as COM will take care of marshaling the types between the processes. It ain't pretty, bit it will work!
This article [Dealing with Legacy 32-bit Components in 64-bit Windows](https://stackoverflow.com/questions/359331/access-x86-com-from-x64-net/448039#448039) help you : I have found this solution, see in [article](https://web.archive.org/web/20150428181827/http://blogs.msdn.com/b/volkerw/archive/2006/03/23/559087.aspx) : • Converting a project type from in-process to out-of-process • Using COM+ as a host (this work for me) • Using dllhost as a surrogate host
64 bit C# with a 32 bit VB6 COM object
[ "", "c#", "com", "vb6", "interop", "" ]
I'd like to implement a method that takes an `Object` as argument, casts it to an arbitrary type, and if that fails returns `null`. Here's what I have so far: ``` public static void main(String[] args) { MyClass a, b; a = Main.<MyClass>staticCast(new String("B")); } public static class MyClass { } public static <T> T staticCast(Object arg) { try { if (arg == null) return null; T result = (T) arg; return result; } catch (Throwable e) { return null; } } ``` Unfortunately the class cast exception is never thrown/caught in the body of the `staticCast()` function. It seems Java compiler generates the function `String staticCast(Object arg)` in which you have a line `String result = (String) arg;` even though I explicitly say that the template type should be `MyClass`. Any help? Thanks.
Because generic type information is erased at runtime, the standard way to cast to a generic type is with a `Class` object: ``` public static <T> T staticCast(Object arg, Class<T> clazz) { if (arg == null) return null; if (!clazz.isInstance(arg)) return null; T result = clazz.cast(arg); return result; } ``` Then call it like this: ``` a = Main.staticCast("B", MyClass.class); ```
You cannot do what you want... at least not this way. The compiler removed all of the information so you wind up with (T) being Object in the cast - and that works. The problem is that later on you are doing MyClass = (String)object; and that isn't allowed. You have bypassed the compilers checking and made it fail at runtime. So what is it exactly that you are trying to do? If you tell us why you want to do this we can probably tell you the Java way of doing it. Given your comment you might try something like: ``` public class Main { public static void main(String[] args) { String a; MyClass b; a = staticCast(new String("B"), String.class); b = staticCast(new String("B"), MyClass.class); System.out.println(a); } public static class MyClass { } public static <T> T staticCast(Object arg, final Class clazz) { // edit - oops forgot to deal with null... if(arg == null) { return (null); } // the call to Class.cast, as mmeyer did, might be better... probably is better... if(arg.getClass() != clazz) { // Given your answer to Ben S... return (null); // throw new ClassCastException("cannot cast a " + arg.getClass() + " to a " + clazz); } return ((T)arg); } } ```
Java generics
[ "", "java", "generics", "casting", "" ]
In his [article about preventing multiple instances](http://www.ai.uga.edu/~mc/SingleInstance.html) of an application, Michael Covington presents this code: ``` static void Main() // args are OK here, of course { bool ok; m = new System.Threading.Mutex(true, "YourNameHere", out ok); if (! ok) { MessageBox.Show("Another instance is already running."); return; } Application.Run(new Form1()); // or whatever was there GC.KeepAlive(m); // important! } ``` He explains that the GC.KeepAlive(m) is required to prevent the garbage collector from collecting the mutex early, since there are no additional references to it. My question: will wrapping the mutex in a using do the same thing? That is, will the following also prevent the GC from pulling the rug out from under me? ``` static void Main() // args are OK here, of course { bool ok; using (var m = new System.Threading.Mutex(true, "YourNameHere", out ok)) { if (! ok) { MessageBox.Show("Another instance is already running."); return; } Application.Run(new Form1()); // or whatever was there } } ``` My gut reaction is that the using will work, since using is (supposed to be) equivalent to: ``` Mutex m = new System.Threading.Mutex(true, "YourNameHere", out ok); try { // do stuff here } finally { m.Close(); } ``` And I would think that the m.Close() there would be enough to signal to the JIT compiler that there's another reference, thus preventing premature garbage collection.
Wrapping the mutex in a `using` statement will indeed prevent it from being garbage collected, but will *also* dispose of it (it calls `Dispose`, not `Close`) at the end (whereas `GC.KeepAlive` won't, obviously). If the end of the method is genuinely going to be the end of the process, I don't believe it's likely to make any practical difference which you use - I prefer the `using` statement on the general principle of disposing of anything which implements `IDisposable`. If the mutex hasn't been disposed when the process exits, I suspect its finalizer will take care of it - so long as other finalizers don't hog the finalization thread beyond its timeout. If the finalizer doesn't take care of it, I don't know whether Windows itself will notice that the process can't possibly own the mutex any more, given that it (the process) doesn't exist any more. I suspect it will, but you'd have to check detailed Win32 documentation to know for sure.
Using `using` seems to be a better fit in this case than using `GC.KeepAlive`. You not only want to keep the `Mutex` alive as long as the application is running, you also want it to go away as soon as you exit the main loop. If you just leave the `Mutex` hanging without disposing it, there may be some time before it's finalized, depending on how much cleanup work there is to do when the application is shutting down.
GC.KeepAlive versus using
[ "", "c#", "garbage-collection", "keep-alive", "" ]
Should you use pointers in your C# code? What are the benefits? Is it recommend by The Man (Microsoft)?
From "The Man" himself: The use of pointers is rarely required in C#, but there are some situations that require them. As examples, using an unsafe context to allow pointers is warranted by the following cases: * Dealing with existing structures on disk * Advanced COM or Platform Invoke scenarios that involve structures with pointers in them * Performance-critical code The use of unsafe context in other situations is discouraged. **Specifically, an unsafe context should not be used to attempt to write C code in C#.** Caution: Code written using an unsafe context cannot be verified to be safe, so it will be executed only when the code is fully trusted. In other words, unsafe code cannot be executed in an untrusted environment. For example, you cannot run unsafe code directly from the Internet. [Reference](http://msdn.microsoft.com/en-us/library/aa288474(VS.71).aspx)
If you have to. Say that you need to false color a large grayscale image, say 2000x2000 pixels. First write the 'safe' version using `GetPixel()` and `SetPixel()`. If that works, great, move on. if that proves to be too slow, you may need to get at the actual bits that make up the image (forget about Color matrices for the sake of the example). There is nothing 'bad' about using unsafe code, but it adds complexity to the project and should thus be used only when necessary.
Should you use pointers (unsafe code) in C#?
[ "", "c#", ".net", "pointers", "coding-style", "unsafe", "" ]
Does `Using Namespace;` consume more memory? I'm currently working on a mobile application and I was just curious if those unneeded using statements that visual studio places when creating a class make my application require some extra memory to run.
To put it simply: no. Those statements aren't translated into any form of IL. They're just shortcuts to avoid using (ugly!) fully qualified type names. But, if you're using VS2008 and/or R# you can remove unused ones automagically.
Namespaces are a compile-time only feature of C# that allow you to save time during development. The `using` directives are utilized by the compiler to look up shorthand Type names in your code. Basically each time the compiler encounters a type name in your code that it does not know it takes each `using` directive and prepends it to the type's name and sees if that fully qualified name resolves. Once you application is compiled the namespaces and the `using` directives are gone as the IL does not need them.
Does `Using Namespace;` consume more memory?
[ "", "c#", "mobile-application", "" ]
I just tried to do a correlated subquery in the `FROM` clause of a `SELECT` statement in Oracle, but I was given an error indicating that I couldn't do the correlation (something to the effect that `Obs.pID` was not recognized). Should this work? ``` FROM ml.Person Person JOIN ml.Obs ON Person.pID = Obs.pId JOIN (SELECT ObsMax2.pId, ObsMax2.hdId , MAX(ObsMax2.obsDate) as maxDate FROM ml.Obs ObsMax2 WHERE ObsMax2.pId = Obs.pId AND ObsMax2.obsDate < {?EndDate} GROUP BY ObsMax2.pId, ObsMax2.hdId) ObsMax ON Obs.pId = ObsMax.pId AND Obs.hdId = ObsMax.hdId AND Obs.obsDate = ObsMax.maxDate ``` My workaround would appear to be to make it a non-correlated subquery, and add criteria to the subquery that keeps it from running completely amuck, amuck, amu--*oof* Sorry. I'd rather figure out how to properly correlate it, though, if possible - the view that works like that subquery takes forever to build.
You can achieve the intent of this part of the query by using an analytic function to identify the maximum obsDate for each pid and hdid. It would be something like: ``` select ... from ( SELECT pId, hdId, obsDate MAX(obsDate) over (partition by pId, hdId) maxDate FROM ml.Obs WHERE obsDate < {?EndDate} ) where obsDate = maxDate / ```
Sub-queries within a FROM clause cannot refer to other tables from the same FROM clause. Removing the ObsMax2.pId = Obs.pId clause should resolve the problem and from I can tell will give you exactly the same result since the same clause is in the join condition. However, as you mention, you may run into performance issues with having the GROUP BY in the sub-query. From what I can tell, you're trying to get the individual pID/hdId records from ml.Obs with the largest obsDate that's less than {EndDate}. In that case, what about moving the sub-query into the WHERE clause where you can correlate it? E.g.: ``` select ... from ml.Person Person join ml.Obs on Person.PID = Obs.pId where Obs.obsDate = ( select max(obsDate) from ml.Obs Obs2 where Obs2.pId = Obs.pId and obs2.hdId = Obs.hdId and Obs2.obsDate < {EndDate}) ```
Oracle correlated subquery in FROM list
[ "", "oracle", "oracle10g", "subquery", "sql", "" ]
In C++, say you want to declare a global variable to be used by many. How do you do it? I commonly use declare and define in cpp file, and then use extern in other cpp file (and not headers). I don't like this approach, and I am considering something along these lines: In a header file: some\_file.h ``` Class MYGlobalClass { }; MyGlobalClass& MyGlobalClassInstance() { static MYGlobalClass instance; return instance; } ``` **Edit** ***Consider in the following contexts:*** * can be used in multi-threaded applications * namespace pollution * may NOT necessery be a singleton, as many instances of this might be created What are your thoughts, suggestions, new ideas?
Declare it in one header file (using `extern`), and define it in *one* `.cpp` (or whatever other extension) file. You may use a function and return a reference to a static variable like you showed to circumvent problems with construction order relative to other such namespace scope variables in other `.cpp` files. But remember that won't protect you from destruction order problems - which is in the exact reverse order from construction (these things are called "static initialization order fiasco". If you use a function like yours and put it into headers, make it inline to make the redefinition of the function valid when it is included into multiple `.cpp` files (logically, the function is still only apparent once, because the static in it will only exist once, not separately for each file it is included into). Alternatively just declare it in a header but define it in *one* `.cpp` file (but then, remove the inline from it!). ``` inline A& getA() { static A a; return a; } ``` The potential problems with destruction order can be circumvented by using `new`: ``` inline A& getA() { static A *a = new A; return *a; } ``` The destructor of it, however, will never be called then. If you need thread safety, you should add a mutex that protects against multiple accesses. `boost.thread` probably has something for that.
The best advice is probably "try to avoid globals". People don't need global variables as often as they think. Usually it turns out that "passing everything as arguments to constructors" isn't quite as much work as people think when they hear the suggestion. It also tends to lead to cleaner code with fewer, and more explicit, dependencies. I'm not aware of any "correct" way to declare globals in C++. The way you do it now works fine, but the order of initialization is unspecified, so if there are any dependencies between your globals, you're in trouble. A function returning a static instance more or less solves that problem, but isn't thread safe. And a singleton is just a terrible idea. It doesn't solve your problem, but adds additional constraints to your code, which weren't actually necessary, and will most likely come back and bite you later.
What is the best way to declare a global variable?
[ "", "c++", "design-patterns", "" ]
From a memory leak log I have the following info: TestApp.exe! + 2238ch Let us say this means that method at offset '2238c' (hex value) is leaking. How can I locate the corresponding method in my source code? I have the linker map (testapp.map) but not sure how to use it. This is a C++ application compiled in VS2008.
Your map file will have a bunch of entries like these: ``` 0001:00000070 ??0logic_error@std@@QAE@ABV01@@Z 00401070 f i scratch.obj 0001:000000e0 _main 004010e0 f scratch.obj 0001:00000310 ??1?$list@V?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@V?$allocator@V?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@@std@@@std@@QAE@XZ 00401310 f i scratch.obj 0001:00000330 ??1?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@QAE@XZ 00401330 f i scratch.obj 0001:00000360 ?_Buynode@?$list@V?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@V?$allocator@V?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@@std@@@std@@IAEPAU_Node@?$_List_nod@V?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@V?$allocator@V?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@@std@@@2@XZ 00401360 f i scratch.obj 0001:00000380 ?clear@?$list@V?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@V?$allocator@V?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@@std@@@std@@QAEXXZ 00401380 f i scratch.obj 0001:000003f0 ?_Buynode@?$list@V?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@V?$allocator@V?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@@std@@@std@@IAEPAU_Node@?$_List_nod@V?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@V?$allocator@V?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@@std@@@2@PAU342@0ABV?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@@Z 004013f0 f i scratch.obj 0001:00000480 ?_Incsize@?$list@V?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@V?$allocator@V?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@@std@@@std@@IAEXI@Z 00401480 f i scratch.obj ``` This shows you exactly how your code is laid out in memory. e.g. main() starts at E0 and ends at 30F in segment 1. You just need to go through the address list to see where the address you were given lands. One thing to look out for is there are usually multiple segments, but you can usually deduce which one has the code you're interested in.
Use [`objdump`](http://en.wikipedia.org/wiki/Objdump) -- that should tell you the function-address mapping. From Ferruccio: The Windows version of that is dumpbin, it comes with Visual Studio
How to find a method in assembly code
[ "", "c++", "assembly", "" ]
I want to inherit a model class from some 3rd party code. I won't be using some of the fields but want my client to be able to edit the model in Admin. Is the best bet to hide them from Admin or can I actually prevent them being created in the first place? Additionally - what can I do if one of the unwanted fields is required? My first thought is to override the save method and just put in a default value.
If you are inheriting the model then it is probably not wise to attempt to hide or disable any existing fields. The best thing you could probably do is exactly what you suggested: override `save()` and handle your logic in there.
Rather than inherit, consider using customized Forms. 1. You can eliminate fields from display that are still in the model. 2. You can validate and provide default values in the form's `clean()` method. See <http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin>
Django Model Inheritance. Hiding or removing fields
[ "", "python", "python-3.x", "django", "django-models", "django-admin", "" ]
We have a web application where we are using global.asax for url rewriting. We use a compiled version of the site on the live server. As a part of modification request, we had to add some custom native AJAX code where javascript would call a webservice to update the content of the page. For being able to call the webservice with extension .asmx, we modified the url rewriting code to handle asmx requests seperately. this arrangement works fine on the local machine, but when we publish the site and deploy it on the live server, the new code doesnt seem to get included. It still skips the condition to check the ".asmx" extension, and throws a page not found exception considering the webservice name as a page name. We have tried looking all over and googled for such things as well.. but no avail.. any pointers on what might be going wrong.. ?
Assuming your URL rewriting is good (isn't that normally implemented as a HttpModule?) I'd check to make sure that there's an ISAPI mapping in IIS on production that sends .asmx requests to ASP.NET. If you think your changes to the global.asax haven't been rejitted then you can always stop the application pool, go find your web applications compiled bits in c:\windows\microsoft.net\framework[version]\temporary asp.net files... and delete the jitted version. I've seen ASP.NET miss when it comes to Jitting changes before. I'd also consider running http fiddler (IE) or tamper data (FireFox extension) on one of the pages that makes calls to the web service. It will tell you exactly how the page is calling the web service and you can validate that the called URL is correct.
There is machine.config file where you can add HttpModules. I also think that you can do that through web.config.
global.asax not being updated
[ "", "c#", "asp.net", "global-asax", "" ]
I am going to be building a Pylons-based web application. For this purpose, I'd like to build a minimal Linux platform, upon which I would then install the necessary packages such as Python and Pylons, and other necessary dependencies. The other reason to keep it minimal is because this machine will be virtual, probably over KVM, and will eventually be replicated in some cloud environment. What would you use to do this? I am thinking of using Fedora 10's AOS iso, but would love to understand all my options.
I really like [JeOS](http://www.ubuntu.com/products/whatisubuntu/serveredition/jeos) "Just enough OS" which is a minimal distribution of the Ubuntu Server Edition.
If you want to be able to remove all the cruft but still be using a ‘mainstream’ distro rather than one cut down to aim at tiny devices, look at Slackware. You can happily remove stuff as low-level as sysvinit, cron and so on, without collapsing into dependency hell. And nothing in it relies on Perl or Python, so you can easily remove them (and install whichever version of Python your app prefers to use).
Miminal Linux For a Pylons Web App?
[ "", "python", "linux", "pylons", "" ]
Using these tables, as a sample: **CodeVariations**: ``` CODE ----------- ABC_012 DEF_024 JKLX048 ``` **RegisteredCodes**: ``` CODE AMOUNT -------- ------ ABCM012 5 ABCK012 25 JKLM048 16 ``` Is it possible to write a query to retrieve all rows in *RegisteredCodes* when CODE matches a pattern in **any** row of the *CodeVariations* table? That is, any row that matches a LIKE pattern of either `'ABC_012'`, `'DEF_024'` or `'JKLX048'` Result should be: ``` CODE AMOUNT -------- ------ ABCM012 5 ABCK012 25 ``` I'm using PostgreSQL, but it would be interesting to know if it's possible to do this in a simple query for either PostgreSQL or any other DB.
Does this do what you need? ``` select distinct RC.* from RegisteredCodes RC, CodeVariations CV where RC.CODE LIKE CV.CODE; ```
Is this you are looking for: ``` SELCET * FROM RegisteredCodes RC WHERE RC.Code IN (SELECT CODE FROM CodeVariations WHERE CODE LIKE ('ABC%') AND CODE LIKE ('%012') ``` This will fetch all the record that start with 'ABC' and Ends with '012' and similar for 'DEF" and 'JKL'. OR Are you looking for something like [this](http://msdn.microsoft.com/en-us/magazine/cc163473.aspx)?
Is it possible in SQL to match a LIKE from a list of records in a subquery?
[ "", "sql", "postgresql", "sql-like", "" ]
I'm having an issue trying to NOT select a tablerow with the function: ``` $("tr").click(function(e) { var row = jQuery(this) //rest of code left off }); ``` Basically it finds all tablerows and adds click functionality that will open a edit modal that has a row with textboxes that are populated with info from the tablecells. The problem is that the tablerow in the modal is also getting the functionality so when a user goes to edit a value in a text box the all the values disappears... So what I have been trying and failing is to filter the tr by id several way by using: ``` $("tr").not('trEdit').click(function(e) { var row = jQuery(this) ``` and ``` $("tr not:'trEdit').click(function(e) { var row = jQuery(this) ``` I've also played around with trying the second table and then not selecting it's table rows, but the tables aren't besides each other & the example I had was...no I haven't tried table[1] tr yet(now that I think about it)... Please help...I'm going nuts trying to figure this out.. Thanks!!!!!
Could you implement it this way? It would make your intentions much clearer. ``` $("#theClickableTable tr").click(function() { ... }) ```
The syntax is either `$("tr:not(.trEdit)")` or `$("tr :not(.trEdit)")` - depending on if the trEdit class applies to the tr or a sub-element. However, I think your problem may have to do with **event bubbling** - you'll have to search for details on that, or wait for someone else to extend the answer, as I have to go now.
Problem with jquery :not selector
[ "", "javascript", "jquery", "" ]
I am fascinated by the way the CLR and GC works (I'm working on expanding my knowledge on this by reading CLR via C#, Jon Skeet's books/posts, and more). Anyway, what is the difference between saying: ``` MyClass myclass = new MyClass(); myclass = null; ``` Or, by making MyClass implement IDisposable and a destructor and calling Dispose()? Also, if I have a code block with a using statement (eg below), if I step through the code and exit the using block, is the object disposed of then or when a garbage collection occurs? What would happen if I call Dispose() in the using block anyay? ``` using (MyDisposableObj mydispobj = new MyDisposableObj()) { } ``` Stream classes (eg BinaryWriter) have a Finalize method? Why would I want to use that?
It's important to separate disposal from garbage collection. They are completely separate things, with one point in common which I'll come to in a minute. **`Dispose`, garbage collection and finalization** When you write a `using` statement, it's simply syntactic sugar for a try/finally block so that `Dispose` is called even if the code in the body of the `using` statement throws an exception. It *doesn't* mean that the object is garbage collected at the end of the block. Disposal is about *unmanaged resources* (non-memory resources). These could be UI handles, network connections, file handles etc. These are limited resources, so you generally want to release them as soon as you can. You should implement `IDisposable` whenever your type "owns" an unmanaged resource, either directly (usually via an `IntPtr`) or indirectly (e.g. via a `Stream`, a `SqlConnection` etc). Garbage collection itself is only about memory - with one little twist. The garbage collector is able to find objects which can no longer be referenced, and free them. It doesn't look for garbage all the time though - only when it detects that it needs to (e.g. if one "generation" of the heap runs out of memory). The twist is *finalization*. The garbage collector keeps a list of objects which are no longer reachable, but which have a finalizer (written as `~Foo()` in C#, somewhat confusingly - they're nothing like C++ destructors). It runs the finalizers on these objects, just in case they need to do extra cleanup before their memory is freed. Finalizers are almost always used to clean up resources in the case where the user of the type has forgotten to dispose of it in an orderly manner. So if you open a `FileStream` but forget to call `Dispose` or `Close`, the finalizer will *eventually* release the underlying file handle for you. In a well-written program, finalizers should almost never fire in my opinion. **Setting a variable to `null`** One small point on setting a variable to `null` - this is almost never required for the sake of garbage collection. You might sometimes want to do it if it's a member variable, although in my experience it's rare for "part" of an object to no longer be needed. When it's a local variable, the JIT is usually smart enough (in release mode) to know when you're not going to use a reference again. For example: ``` StringBuilder sb = new StringBuilder(); sb.Append("Foo"); string x = sb.ToString(); // The string and StringBuilder are already eligible // for garbage collection here! int y = 10; DoSomething(y); // These aren't helping at all! x = null; sb = null; // Assume that x and sb aren't used here ``` The one time where it *may* be worth setting a local variable to `null` is when you're in a loop, and some branches of the loop need to use the variable but you know you've reached a point at which you don't. For example: ``` SomeObject foo = new SomeObject(); for (int i=0; i < 100000; i++) { if (i == 5) { foo.DoSomething(); // We're not going to need it again, but the JIT // wouldn't spot that foo = null; } else { // Some other code } } ``` **Implementing IDisposable/finalizers** So, should your own types implement finalizers? Almost certainly not. If you only *indirectly* hold unmanaged resources (e.g. you've got a `FileStream` as a member variable) then adding your own finalizer won't help: the stream will almost certainly be eligible for garbage collection when your object is, so you can just rely on `FileStream` having a finalizer (if necessary - it may refer to something else, etc). If you want to hold an unmanaged resource "nearly" directly, [`SafeHandle`](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.safehandle.aspx) is your friend - it takes a bit of time to get going with, but it means you'll [almost](http://joeduffyblog.com/2008/02/17/idisposable-finalization-and-concurrency/) [never need to write a finalizer again](http://joeduffyblog.com/2005/12/27/never-write-a-finalizer-again-well-almost-never/). You should usually only need a finalizer if you have a really direct handle on a resource (an `IntPtr`) and you should look to move to `SafeHandle` as soon as you can. (There are two links there - read both, ideally.) Joe Duffy has a [very long set of guidelines around finalizers and IDisposable](http://joeduffyblog.com/2005/04/08/dg-update-dispose-finalization-and-resource-management/) (co-written with lots of smart folk) which are worth reading. It's worth being aware that if you seal your classes, it makes life a lot easier: the pattern of overriding `Dispose` to call a new virtual `Dispose(bool)` method etc is only relevant when your class is designed for inheritance. This has been a bit of a ramble, but please ask for clarification where you'd like some :)
When you dispose an object, the resources are freed. When you assign null to a variable, you're just changing a reference. ``` myclass = null; ``` After you execute this, the object myclass was referring to still exists, and will continue to until the GC gets around to cleaning it up. If Dispose is explicitly called, or it's in a using block, any resources will be freed as soon as possible.
Setting an object to null vs Dispose()
[ "", "c#", ".net", "disposable", "" ]
I'm running a memory intensive app on a machine with 16Gb of RAM, and an 8-core processor, and Java 1.6 all running on CentOS release 5.2 (Final). Exact JVM details are: ``` java version "1.6.0_10" Java(TM) SE Runtime Environment (build 1.6.0_10-b33) Java HotSpot(TM) 64-Bit Server VM (build 11.0-b15, mixed mode) ``` I'm launching the app with the following command line options: ``` java -XX:+UseConcMarkSweepGC -verbose:gc -server -Xmx10g -Xms10g ... ``` My application exposes a JSON-RPC API, and my goal is to respond to requests within 25ms. Unfortunately, I'm seeing delays up to and exceeding 1 second and it appears to be caused by garbage collection. Here are some of the longer examples: ``` [GC 4592788K->4462162K(10468736K), 1.3606660 secs] [GC 5881547K->5768559K(10468736K), 1.2559860 secs] [GC 6045823K->5914115K(10468736K), 1.3250050 secs] ``` Each of these garbage collection events was accompanied by a delayed API response of very similar duration to the length of the garbage collection shown (to within a few ms). Here are some typical examples (these were all produced within a few seconds): ``` [GC 3373764K->3336654K(10468736K), 0.6677560 secs] [GC 3472974K->3427592K(10468736K), 0.5059650 secs] [GC 3563912K->3517273K(10468736K), 0.6844440 secs] [GC 3622292K->3589011K(10468736K), 0.4528480 secs] ``` The thing is that I thought the UseConcMarkSweepGC would avoid this, or at least make it extremely rare. On the contrary, delays exceeding 100ms are occurring almost once a minute or more (although delays of over 1 second are considerably rarer, perhaps once every 10 or 15 minutes). The other thing is that I thought only a FULL GC would cause threads to be paused, yet these don't appear to be full GCs. It may be relevant to note that most of the memory is occupied by a LRU memory cache that makes use of soft references. Any assistance or advice would be greatly appreciated.
Turns out that part of the heap was getting swapped out to disk, so that garbage collection had to pull a bunch of data off the disk back into memory. I resolved this by setting Linux's "swappiness" parameter to 0 (so that it wouldn't swap data out to disk).
First, check out the [Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning](http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html) documentation, if you haven't already done so. This documentation says: > the concurrent collector does most of its tracing and sweeping work with the > application threads still running, so only brief pauses are seen by the > application threads. However, if the concurrent collector is unable to finish > reclaiming the unreachable objects before the tenured generation fills up, or if > an allocation cannot be satisfied with the available free space blocks in the > tenured generation, then the application is paused and the collection is completed > with all the application threads stopped. The inability to complete a collection > concurrently is referred to as concurrent mode failure and indicates the need to > adjust the concurrent collector parameters. and a little bit later on... > The concurrent collector pauses an application twice during a > concurrent collection cycle. I notice that those GCs don't seem to be freeing very much memory. Perhaps many of your objects are long lived? You may wish to tune the generation sizes and other GC parameters. 10 Gig is a *huge* heap by many standards, and I would naively expect GC to take longer with such a huge heap. Still, 1 second is a very long pause time and indicates either something is wrong (your program is generating a large number of unneeded objects or is generating difficult-to-reclaim objects, or something else) or you just need to tune the GC. Usually, I would tell someone that if they have to tune GC then they have other problems they need to fix first. But with an application of this size, I think you fall into the territory of "needing to understand GC much more than the average programmer." As others have said, you need to profile your application to see where the bottleneck is. Is your PermGen too large for the space allocated to it? Are you creating unnecessary objects? jconsole works to at least show a minimum of information about the VM. It's a starting point. As others have indicated however, you very likely need more advanced tools than this. Good luck.
Reducing JVM pause time > 1 second using UseConcMarkSweepGC
[ "", "java", "performance", "garbage-collection", "jvm", "jvm-arguments", "" ]
I have code like this, and I find it a bit hard to read: ``` // code1 if( (expensiveOperation1() && otherOperation() && foo()) || (expensiveOperation2() && bar() && baz()) { // do something } ``` I just changed it to the following, to make it more readable: ``` // code2 const bool expr1 = expensiveOperation1() && otherOperation() && foo(); const bool expr2 = expensiveOperation2() && bar() && baz(); if(expr1 || expr2){ // one of the conditions met } ``` But should I now be concerned about efficiency? I mean, in `code1`, if the first conjunctive clause is fulfilled then it won't even bother to look at the second one because it's already clear that the statement will be true. But in my more readable example, both `cond1` and `cond2` have to be computed. Or will the compiler be smart enough to change my `code2` into `code1` if expr2 is not used anywhere else?
I would say it shouldn't, since they're not logically equivalent if any of the functions have side-effects. The following would be equivalent however, and it'd have the advantage allowing you to give descriptive names to the test functions, making the code more self-documenting: ``` // code3 inline bool combinedOp1() { return expensiveOperation1() && otherOperation() && foo(); } inline bool combinedOp2() { return expensiveOperation2() && bar() && baz(); } ``` And then call it as follows: ``` if (combinedOp1() || combinedOp2()) { // do something } ```
Maybe, but why not just make your second check incorporate the first? ``` // code3 bool expr = expensiveOperation1() && otherOperation() && foo(); expr = expr || (expensiveOperation2() && bar() && baz()); if(expr){ // one of the conditions met } ``` Better yet, turn things around so the least expensive check occurs first in each list, taking advantage of the lazy evaluation to skip the expensive operations entirely.
Will the C/C++ compiler optimize this if statement?
[ "", "c++", "c", "optimization", "compiler-construction", "performance", "" ]
I have a class with a (non smart) pointer to an interface object (lets call it pInterface) and I am building a nested class which also needs access to that interface. I am going to get around this by passing the pointer to the interface into the constructor of the nested class like so: ``` CNestedClass someClass( pInterface, ... ); ``` However I am unsure of the best way of storing this pointer in the nested class. I could use: ``` 1) A scoped (or other smart) pointer (to the original object) 2) A pointer to a pointer ``` What would you guys suggest and why? EDIT: I should clarify - the nested class will need to call methods on the interface object, however it does not create it (or modify the object 'pointed' to ), the parent class is responsible for that.
The use a pointer to a pointer is if either class may alter the value of the pointer - e.g. by deleting the existing object and replacing it with a new one. This allows both classes to still use the same object by dereferencing the pointer-to-pointer. If not your concern is ensuring the object remains valid throughout the lifetime of both classes. * If the nested class lives shorter you don't really have to worry. * If it's the same, provided you clean-up in the correct order (e.g. nested class first, object later) then again, you don't have to worry * If the nested class could persist after the owner is destroyed then you must implement a way to ensure the object also persists. If you need to ensure the lifetime of the object it could be done via reference counting-semantics, either manually or through a smart-pointer interface. For a smart pointer then boost::shared\_ptr would be a good choice. shared\_ptr allows the ownership of an object to be shared amount multiple pointers. When the last shared\_ptr goes out of scope, the object is deleted. (note this is not the case with auto\_ptr, where an object are exclusively owned). Things to be aware of; 1. When using boost::shared\_ptr be sure the nested class has a **copy** of the shared\_ptr and not a reference/pointer. 2. std::auto\_ptr behaves quite differently, objects are exclusively owned and not shared 3. boost::shared\_ptr can only work with heap objects, e.g pointers returned from a call to 'new' Example: ``` typedef boost::shared_ptr<Interface> shared_interface; class NestedClass { shared_interface mInterface; // empty pointer } void NestedClass::setInterface(shared_interface& foo) { mInterface= foo; // take a copy of foo. } void ParentClass::init( void ) { // mInterface is also declared as shared_interface mInterface = new Interface(); mNestedClass->setInterface(mInterface); } ```
The other reason you may want to use a pointer to a pointer would be if the *outer* code might change the original pointer value (e.g. make it point to a new object, or set it to NULL after releasing the object it points to). However, IMO it is quite bad practice to change a pointer after giving it to someone else. So, if neither the outer code nor the nested class changes the pointer, just store it in the nested class as a copy of the original pointer as a member variable (field).
Pointer to a Pointer question
[ "", "c++", "pointers", "smart-pointers", "" ]
I'm near ending the repetitive alarms at my [little learning project](http://www.my-clock.net). It's still full of bugs, but as it is a weekend project I'm correcting them slowly. My problem is inconsistency of layout across browsers. At the moment, I'm trying to improve the "`My Alarms`" box after login (Just don't try to hack my website, it's still very unstable). ### Question What kind of tricks, hacks, tips, etc. can you give me to ensure cross-browser layout compatibility?
I find the best policy to avoid pain is to follow these rules: 1. Build in a more-compliant and developer-friendly browser like firefox first, test thoroughly in IE (and safari/chrome(webkit) and opera) periodically. 2. Use a strict doctype- you don't necessarily need *perfect* markup, but it should be very good — good enough to avoid browser quirks modes, since quirks are by definition not standard 3. Use a [reset style sheet](https://stackoverflow.com/questions/167531/is-it-ok-to-use-a-css-reset-stylesheet). Note that depending on the sheet's contents this item may be incompatible with the goal of #2. 4. Use a javascript framework like jQuery or Prototype - they can hide some javascript and DOM incompatibilities. 5. Use good semantic layout- it's more likely to degrade nicely for a mis-behaving browser 6. Accept that it won't be perfect and don't sweat the really small variances Follow those rules and there aren't as many problems in the first place. For a TODO reference, see this question: <https://stackoverflow.com/questions/72394/what-should-a-developer-know-before-building-a-public-web-site>
You need a proper doctype so that the page renders in standards compliant mode. [W3C: Recommended list of DTDs](http://www.w3.org/QA/2002/04/valid-dtd-list.html) Keep to the standards as far as possible. That's what the browsers are built to follow, so that is the best common ground that you can find. Also, that is what browsers will follow in the future, so you get the best possible prediction for how the code should look to work with future browser versions. When building, first test the page in a browser that is not Internet Explorer. If you first build for IE, you will be relying on it's rendering errors, and then you will have great problems to make it look the same in browsers that doesn't have those errors. Firefox is the most common non-IE browsers, and also one of the most neutral when it comes to following the standards. The Firebug add-on for Firefox lets you see exactly what styles are applied to each element, and you can also tweak the styles in real time, so that is a very handy tool. Try to make the layout as simple and robust as possible, and keep to the original semantics of html if possible. Search engines look for content in elements that was intended for it, like a header in a `h1` tag, and text in a `p` tag, so by following the original intention for the markup you make your page more visible on the web. You may have to add some extra styles to suppress quirks in IE, like specifying a height for elements that should manage to figure out their height by themselves, adding display:inline; to floating elements (which still will be block elements) to fiddle the internal rendering flags of IE, or using overflow:hidden to suppress the urge of IE to make all elements at least one character high. Use padding rather than margin where either works, as IE has problems to collapse margins correctly. Use conditional tags only as a last resort. By using version specific code you get code that you may have to maintain for every new browser version that is released.
How can I achieve a consistent layout in all browsers?
[ "", "javascript", "jquery", "html", "css", "" ]
[The code](http://www.djangobook.com/en/2.0/chapter01/) ``` #!/usr/bin/env python import MySQLdb print "Content-Type: text/html" print print "<html><head><title>Books</title></head>" print "<body>" print "<h1>Books</h1>" print "<ul>" connection = MySQLdb.connect(user='me', passwd='letmein', db='my_db') cursor = connection.cursor() cursor.execute(“SELECT name FROM books ORDER BY pub_date DESC LIMIT 10”) for row in cursor.fetchall(): print "<li>%s</li>" % row[0] print "</ul>" print "</body></html>" connection.close() ``` I saved it as test.cgi to my web server. I run it by www.mysite.com/test.cgi unsuccessfully ``` Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. ``` How can you solve the problem? **[edit]** after the first answer 1. test.cgi is executable (I run $ chmod +x test.cgi) 2. I use Apache. 3. I have this in .bashrc export PATH=${PATH}:~/bin 4. Python module MySQLdb is installed. 5. The code does not have smart quotes. **[edit]** after the second answer > you're getting that error because you > haven't installed the MySQLdb module > that Python needs to talk to a MySQL > database I installed MySQLdb to my system. The module works, since I can import them. However, I still get the same error whet I go to the www.[mysite].com/test.cgi. **[edit]** I am not sure about the questions > Are the connect() parameters correct? Is MySQL running on localhost > at the default port? I run MySQL on my server. Is the question about the connect() parameters relevant here? > Is the SELECT statement correct? You mean whether I have my SQL statements such as SELECT statement correct? I have not used any SQL queries yet. Do I need them here?
Any number of issues can cause the error you are seeing: 1. Is `test.cgi` executable (chmod 755) on the server? 2. Is the directory in which you placed `test.cgi` designated as a [ScriptAlias](http://httpd.apache.org/docs/2.2/mod/mod_alias.html#scriptalias) location or have the [ExecCGI](http://httpd.apache.org/docs/2.2/howto/cgi.html) option enabled (or equivalent if you're not using Apache)? 3. Is `python` in the system `PATH` or in the `PATH` in the Web server's startup environment? 4. Is the [MySQLdb](http://mysql-python.sourceforge.net/) Python library installed? 5. Are the `connect()` parameters correct? Is MySQL running on localhost at the default port? 6. Is the `SELECT` statement correct? If you're sure that `python` is found (test using the simplest possible script or by logging into the Web server if you can and typing `which python`) then you can get much better debug output by adding the following to the top of your script just below the shebang: ``` import cgitb cgitb.enable() ``` More details: <http://docs.python.org/library/cgitb.html> Additionally, if you have shell access to the Web server, try running python and just typing: ``` >>> import MySQLdb ``` If the command returns with no error, you have your answer for #4 above. If an error is printed, you will need to get MySQLdb installed into the Web server's Python installation. **EDIT:** Looking more closely at the top of your question, I see that the code was scraped from an illustrative example at the very beginning of the Django Book. As such, I might expand #5 above to include the caveat that, of course, the requisite database, tables, user, and permissions need to be set up on the MySQL installation available to the Web server.
I've tidied up the code a bit by inserting linebreaks where necessary and replacing smart quotes with `"` and `'`. Do you have any more luck with the following? Can you run it from a terminal just by typing `python test.cgi`? ``` #!/usr/bin/env python import MySQLdb print "Content-Type: text/html" print print "<html><head><title>Books</title></head>" print "<body>" print "<h1>Books</h1>" print "<ul>" connection = MySQLdb.connect(user='me', passwd='letmein', db='my_db') cursor = connection.cursor() cursor.execute("SELECT name FROM books ORDER BY pub_date DESC LIMIT 10") for row in cursor.fetchall(): print "<li>%s</li>" % row[0] print "</ul>" print "</body></html>" connection.close() ```
.cgi problem with web server
[ "", "python", "cgi", "" ]
I am looking to use a natural language parsing library for a simple chat bot. I can get the Parts of Speech tags, but I always wonder. What do you do with the POS. If I know the parts of the speech, what then? I guess it would help with the responses. But what data structures and architecture could I use.
A part-of-speech tagger assigns labels to the words in the input text. For example, the popular Penn Treebank tagset has some 40 labels, such as "plural noun", "comparative adjective", "past tense verb", etc. The tagger also resolves some ambiguity. For example, many English word forms can be either nouns or verbs, but in the context of other words, their part of speech is unambiguous. So, having annotated your text with POS tags you can answer questions like: how many nouns do I have?, how many sentences do not contain a verb?, etc. For a chatbot, you obviously need much more than that. You need to figure out the subjects and objects in the text, and which verb (predicate) they attach to; you need to resolve anaphors (which individual does a *he* or *she* point to), what is the scope of negation and quantifiers (e.g. *every*, *more than 3*), etc. Ideally, you need to map you input text into some logical representation (such as first-order logic), which would let you bring in reasoning to determine if two sentences are equivalent in meaning, or in an entailment relationship, etc. While a POS-tagger would map the sentence ``` Mary likes no man who owns a cat. ``` to such a structure ``` Mary/NNP likes/VBZ no/DT man/NN who/WP owns/VBZ a/DT cat/NN ./. ``` you would rather need something like this: ``` SubClassOf( ObjectIntersectionOf( Class(:man) ObjectSomeValuesFrom( ObjectProperty(:own) Class(:cat) ) ) ObjectComplementOf( ObjectSomeValuesFrom( ObjectInverseOf(ObjectProperty(:like)) ObjectOneOf( NamedIndividual(:Mary) ) ) ) ) ``` Of course, while POS-taggers get precision and recall values close to 100%, more complex automatic processing will perform much worse. A good Java library for NLP is [LingPipe](http://alias-i.com/lingpipe/). It doesn't, however, go much beyond POS-tagging, chunking, and named entity recognition.
Natural language processing is wide and deep, with roots going back at least to the 60s. You could start reading up on [computational linguistics](http://en.wikipedia.org/wiki/Computational_linguistics) in general, [natural language generation](http://en.wikipedia.org/wiki/Natural_language_generation), [generative grammars](http://en.wikipedia.org/wiki/Generative_grammar), [Markov chains](http://en.wikipedia.org/wiki/Markov_chains), [chatterbots](http://en.wikipedia.org/wiki/Chatterbot) and so forth. Wikipedia has a [short list of libraries](http://en.wikipedia.org/wiki/Natural_language_processing_toolkits) which I assume you might have seen. Java doesn't have a long tradition in NLP, though I haven't looked at the Stanford libraries. I doubt you'll get very impressive results without diving fairly deeply into linguistics and grammar. Not everybody's favourite school subject (or so I've heard reported -- loved'em meself!).
Natural language parsing, practical example
[ "", "java", "nlp", "" ]
With forms I've always used ``` <form method="post" action="<?php echo strip_tags($_SERVER['REQUEST_URI']); ?>"> ``` To get my forms to submit to themselves. I use `striptags()` in case someone links to: ``` http://www.mysite.com/page-with-form.php?bla="><script src="http://www.nasty.com/super-nasty.js"></script><a href="# ``` Have I covered all bases, to secure from XSS attacks, or should I use a more whitelist approach, say a regex that only allows alphanumerical characters, the forward slash, question mark, equals sign, parenthesis etc? Thank you!
Use [`htmlspecialchars`](http://docs.php.net/htmlspecialchars) instead of `strip_tags`.
If you want to reference the same schema/host/path a simple action="?" schould suffice. According to <https://www.rfc-editor.org/rfc/rfc3986#section-4.2> ``` relative-ref = relative-part [ "?" query ] [ "#" fragment ] relative-part = "//" authority path-abempty / path-absolute / path-noscheme / path-empty ``` it's a valid relative uri.
Have I covered all bases with security when echo'ing a server variable to the page?
[ "", "php", "security", "xss", "" ]
Case: you're developing a site with Zend Framework and need relative links to the folder the webapp is deployed in. I.e. `mysite.com/folder` online and `localhost:8080` under development. The following works nice in controllers regardless of deployed location: ``` $this->_helper->redirector->gotoSimple($action, $controller, $module, $params); ``` And the following inside a viewscript, ie. index.phtml: ``` <a href="<?php echo $this->url(array('controller'=>'index', 'action' => 'index'), null, true); ?>"> ``` But how do I get the correct basepath when linking to images or stylesheets? (in a layout.phtml file, for example): ``` <img src='<?php echo WHAT_TO_TYPE_HERE; ?>images/logo.png' /> ``` and ``` $this->headLink()->appendStylesheet( WHAT_TO_TYPE_HERE . 'css/default.css'); ``` `WHAT_TO_TYPE_HERE` should be replaced with something that gives ``` <img src="/folder/images/logo.png />` on mysite.com and `<img src="/images/logo.png /> ``` on localhost
You can get the base url from the Front Controller `Zend_Controller_Front::getInstance()->getBaseUrl();`. I wrap that in a view helper ``` class My_View_Helper_BaseUrl { /** * Get base url * * @return string */ public function baseUrl() { return rtrim(Zend_Controller_Front::getInstance()->getBaseUrl(),'/'); } } ``` So in the html markup you have something like `<img src="<?php echo $this->baseUrl();?>/images/logo.png"/>` The trailing slash is stripped out in the helper so that when the application isn't run in a sub folder (baseUrl is blank in that case) the path will still work.
In case anyone wants to know the best way and doesn't want to waste 2 hours searching Zend/Google. There is a view helper to do that. ``` $this->view->serverUrl(); ```
Getting basepath from view in zend framework
[ "", "php", "zend-framework", "zend-view", "zend-layout", "" ]
I am trying to find out how many regex matches are in a string. I'm using an iterator to iterate the matches, and and integer to record how many there were. ``` long int before = GetTickCount(); string text; boost::regex re("^(\\d{5})\\s(\\d{8})\\s(.*)\\s(.*)\\s(.*)\\s(\\d{8})\\s(.{1})$"); char * buffer; long length; long count; ifstream f; f.open("c:\\temp\\test.txt", ios::in | ios::ate); length = f.tellg(); f.seekg(0, ios::beg); buffer = new char[length]; f.read(buffer, length); f.close(); text = buffer; boost::sregex_token_iterator itr(text.begin(), text.end(), re, 0); boost::sregex_token_iterator end; count = 0; for(; itr != end; ++itr) { count++; } long int after = GetTickCount(); cout << "Found " << count << " matches in " << (after-before) << " ms." << endl; ``` In my example, count always returns 1, even if I put code in the for loop to show the matches (and there are plenty). Why is that? What am I doing wrong? ## Edit TEST INPUT: ``` 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N ``` OUTPUT (without matches): > Found 1 matches in 16 ms. If I change the for loop to this: ``` count = 0; for(; itr != end; ++itr) { string match(itr->first, itr->second); cout << match << endl; count++; } ``` I get this as output: ``` 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N Found 1 matches in 47 ms. ```
Heh. Your problem is your regex. Change your `(.\*)`s to `(.\*?)`s (assuming that's supported). You think you're seeing each line being matched, but in fact you're seeing the *entire text* being matched because your pattern is greedy. To see the issue illustrated, change the debug output in your loop to: ``` cout << "[" << match << "]" << endl; ```
Can you paste the input and also the output. If count returns 1, that means there is only *one* match in your string `text`.
Why does my Boost.Regex search report only one match iteration?
[ "", "c++", "regex", "iterator", "greedy", "boost-regex", "" ]
What security issues can arise from not closing the database connection after using it? Doesn't PHP automatically close it once a new page loads?
As the [`mysql_close()`](http://uk.php.net/mysql_close) documentation says: > Using mysql\_close() isn't usually > necessary, as non-persistent open > links are automatically closed at the > end of the script's execution. See > also freeing resources. Since the connections are managed by PHP there shouldn't be a security risk.
PHP is *supposed* to be a "shared nothing" architecture. That is, all resources are allocated for every request, and then cleaned up after the request is finished. So resources like memory, file handles, sockets, database connections, etc. should be deallocated or closed. However, you can use [persistent database connections](http://php.net/mysql_pconnect) which are not closed, but are re-used for the next request. If you do this, there is some security implication. Any connection state is inherited by the next PHP request. So if your application uses database user-defined variables, or temporary tables, or even `LAST_INSERT_ID()`, the next PHP request may be able to see privileged data that it shouldn't see. If you close the database connection to avoid this, you're basically defeating the value of the persistent connection. So you might as well use plain database connections.
What are the security implications of not closing connection to the database after you are done with it?
[ "", "php", "database", "security", "" ]
We are using the WebBrowser control in c# winforms and need to be able to get information about the Url the cursor is positioned on. So we have a web page in design mode, which has multiple urls, when the cursor is over one I would like to call a method which would return the id of the link. Thanks
You can use the `IHTMLCaret` to get the cursor position from there using `IMarkupPointer` you can get the element in the current scope.
The webBrowser control has a Document property which has a Links collection. Each Link is an HTMLElement which has events you can tap into. Again, I'm not sure what you mean "cursor" because in the web world, unless if you're in a textbox, there really isn't a "cursor" (which is what I meant to ask in my comment) but you can tap into the MouseOver event and other stuff like that. Example: ``` foreach (HtmlElement element in this.webBrowser1.Document.Links) { element.MouseOver += (o, ex) => { Console.WriteLine(ex.ToElement.GetAttribute("HREF")); }; } ``` This will print out the actual URL that the mouse is over.
Get the links id for the current cursor position in the webrowser control
[ "", "c#", "hyperlink", "browser", "" ]
I have a scrolled `div` and I want to have an event when I click on it, it will force this `div` to scroll to view an element inside. I wrote its JavasSript like this: ``` document.getElementById(chr).scrollIntoView(true); ``` but this scrolls all the page while scrolling the `div` itself. How to fix that? I want to say it like this: `MyContainerDiv.getElementById(chr).scrollIntoView(true);`
You need to get the top offset of the element you'd like to scroll into view, relative to its parent (the scrolling div container): ``` var myElement = document.getElementById('element_within_div'); var topPos = myElement.offsetTop; ``` The variable topPos is now set to the distance between the top of the scrolling div and the element you wish to have visible (in pixels). Now we tell the div to scroll to that position using `scrollTop`: ``` document.getElementById('scrolling_div').scrollTop = topPos; ``` If you're using the prototype JS framework, you'd do the same thing like this: ``` var posArray = $('element_within_div').positionedOffset(); $('scrolling_div').scrollTop = posArray[1]; ``` Again, this will scroll the div so that the element you wish to see is exactly at the top (or if that's not possible, scrolled as far down as it can so it's visible).
# Method 1 - Smooth scrolling to an element inside an element ``` var box = document.querySelector('.box'), targetElm = document.querySelector('.boxChild'); // <-- Scroll to here within ".box" document.querySelector('button').addEventListener('click', function(){ scrollToElm( box, targetElm , 600 ); }); ///////////// function scrollToElm(container, elm, duration){ var pos = getRelativePos(elm); scrollTo(container, pos.top , duration/1000); // duration in seconds } function getRelativePos(elm){ var pPos = elm.parentNode.getBoundingClientRect(), // parent pos cPos = elm.getBoundingClientRect(), // target pos pos = {}; pos.top = cPos.top - pPos.top + elm.parentNode.scrollTop, pos.right = cPos.right - pPos.right, pos.bottom = cPos.bottom - pPos.bottom, pos.left = cPos.left - pPos.left; return pos; } function scrollTo(element, to, duration, onDone) { var start = element.scrollTop, change = to - start, startTime = performance.now(), val, now, elapsed, t; function animateScroll(){ now = performance.now(); elapsed = (now - startTime)/1000; t = (elapsed/duration); element.scrollTop = start + change * easeInOutQuad(t); if( t < 1 ) window.requestAnimationFrame(animateScroll); else onDone && onDone(); }; animateScroll(); } function easeInOutQuad(t){ return t<.5 ? 2*t*t : -1+(4-2*t)*t }; ``` ``` .box{ width:80%; border:2px dashed; height:180px; overflow:auto; } .boxChild{ margin:600px 0 300px; width: 40px; height:40px; background:green; } ``` ``` <button>Scroll to element</button> <div class='box'> <div class='boxChild'></div> </div> ``` # Method 2 - Using [Element.scrollIntoView](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView): ``` var targetElm = document.querySelector('.boxChild'), // reference to scroll target button = document.querySelector('button'); // button that triggers the scroll // bind "click" event to a button button.addEventListener('click', function(){ targetElm.scrollIntoView() }) ``` ``` .box { width: 80%; border: 2px dashed; height: 180px; overflow: auto; scroll-behavior: smooth; /* <-- for smooth scroll */ } .boxChild { margin: 600px 0 300px; width: 40px; height: 40px; background: green; } ``` ``` <button>Scroll to element</button> <div class='box'> <div class='boxChild'></div> </div> ``` # Method 3 - Using CSS [scroll-behavior](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior): ``` .box { width: 80%; border: 2px dashed; height: 180px; overflow-y: scroll; scroll-behavior: smooth; /* <--- */ } #boxChild { margin: 600px 0 300px; width: 40px; height: 40px; background: green; } ``` ``` <a href='#boxChild'>Scroll to element</a> <div class='box'> <div id='boxChild'></div> </div> ```
How to scroll to an element inside a div?
[ "", "javascript", "html", "scroll", "" ]
Does anyone have an explanation of how javascript could do this. Somehow this function is both true and false at the exact same time. This is just one pass, no looping or anything. ``` console.log(key); if (this.watches.get(key)) { console.log("found it"); } else { console.log("whhhat?"); } console.log(this.watches); ``` Firebug Console logs as is. ``` search-key found it Object search-key=Object $family=Object whhhat? Object search-key=Object $family=Object ``` **[EDIT]** Here it is. The full script and the block of output above is copy and paste from firebug. This is the strangest thing I have ever seen. <http://snipt.org/Hkl> I use mootools framework so the this.watches = $H({}); is a hashtable. I was using an Array and was experiencing the exact same issue, then switched it to $H({}) because I thought i was doing something wrong.
If this ``` Object search-key=Object $family=Object ``` is produced by: ``` console.log(this.watches); ``` Then this is *obviously* not just one pass. This is not to say that it's in a loop or anything, just that this code is being called more than once. One might say > why is search-key showing up only once then? The answer is: we don't really know because we don't see all the code. The most likely scenario is that `key` in the second time is the empty string try `console.log("")` it prints nothing also try this: ``` >>> console.log(""); console.log(1); console.log(""); console.log(2) ``` copy the output and paste it in any text editor (i.e. paste it as plain text) ``` 1 2 ``` it *looks like* there was nothing between 1 and 2, even though the console *does* show a cue of an empty line, but this cue disappears when you copy-paste the output as plain text. **UPDATE** well, if this process is initiated by the call to `WCHistory.implement(..)`, and this method is being called twice, then obviously, the second time, for some reason, the key is empty. **Try this** Change `console.log(key)` to `console.log("key: " + key)` and you should see something like this: ``` key: search-key found it Object search-key=Object $family=Object key: whhhat? Object search-key=Object $family=Object ```
I think the answer is that this isn't just one pass. This looks like the code is getting called twice, then second time with an empty key. Probably need to see more of the code to be sure. I guess you could stick a integer count incremented before the if statement to confirm this hypothesis.
Javascript: This evaluates to true and false at the same time! What is going on?
[ "", "javascript", "" ]
I'm learning PHP and MySQL and I'm creating a movies website for learning purposes. I want to insert variables and arrays containing movie info into a database but in different tables. This is what I have right now: ``` include('inc/connection.php'); $conn = dbConnect(); // create SQL $sql = 'INSERT INTO movies (movieid, title, year, runtime, plot) VALUES(?, ?, ?, ?, ?)'; // initialize prepared statement $stmt = $conn->stmt_init(); if ($stmt->prepare($sql)) { // bind parameters and execute statment $stmt->bind_param('isiis', $movieid, $title, $year, $runtime, $plot); $stmt->execute(); } ``` This insert the variables into the movies table. But I also need to insert (at the same time) the genres of the movie, the actors, languages, etc... they are in arrays and go into different tables (and maybe also in different rows). For example the array containing the genres (Action, Crime, Drama) genres in the genres table, and the actors in the actors table and so on... I then will use many-to-many and one-to-many tables to display the info. Can someone explain to me how to do this?? I need to connect to the database multiple times?? I need loops? I'm really new to PHP and MySQLi so please try to explain as much as you can. Thanks.
`INSERT` supports only one table at a time, so you'll certainly have to execute multiple `INSERT` statements if you have complex data that goes into multiple tables. If you've inserted a specific `$movieid` value to `movies` then you know what value you need to insert to the rows of the other tables, to satisfy referential integrity (pseudocode follows, not fully functional example): ``` $movies_sql = 'INSERT INTO movies (movieid, title, year, runtime, plot) VALUES(?, ?, ?, ?, ?)'; // execute ($movieid, ...) $actors_sql = 'INSERT INTO movie_actors (movieid, actorid) VALUES (?, ?)'; foreach ($actorlist as $actorid) { // execute ($movieid, $actorid) } $lang_sql = 'INSERT INTO movie_languages (movieid, language) VALUES (?, ?)'; foreach ($languagelist as $language) { // execute ($movieid, $language) } ``` If your `movies` table uses an `AUTO_INCREMENT` primary key, then you can get the value generated during the first `INSERT` either by calling [$mysqli->insert\_id()](http://php.net/mysqli_insert_id), or by using the builtin function [`LAST_INSERT_ID()`](http://dev.mysql.com/doc/refman/5.1/en/information-functions.html#function_last-insert-id). ``` $actors_sql = 'INSERT INTO movie_actors (movieid, actorid) VALUES (LAST_INSERT_ID(), ?)'; foreach ($actorlist as $actorid) { // execute ($actorid) -- only one param in this INSERT } ``` Note that `LAST_INSERT_ID()` reports the most recent auto-generated value during your current session, so if you insert to another table that uses an auto primary key, the value changes. But the value reported is stable during your sessions; it does *not* change if another client session is doing inserts concurrently.
1. You only need one database connection 2. Yes you do need loops 3. Use an `auto_increment` primary key field in each table, and then use `$stmt->insert_id()` to extract the value after each `insert` 4. If you can, use `InnoDB` on the MySQL server to get transaction support, and then `commit` relevant updates together, to ensure that your database is consistent if your script drops out mid-way through an update. The more common `MyISAM` database table format doesn't support transactions.
Insert variables and arrays in different database tables using PHP and MySQLi
[ "", "php", "mysql", "database", "database-design", "mysqli", "" ]
I'm making asynchronous web service calls from a C# app: ``` { //Put UI in 'loading' state ... //Now call web service webServiceProxy.BeginMyMethod(param, new AsyncCallback(MyCallback), null); } private void MyCallback(IAsyncResult res) { ... //process result // Put UI back in normal state (yes I'm marshalling back to the UI thread) } ``` The main thread puts the app in a "waiting" mode, and then the end of the Callback function re-enables the controls. I'm seeing a bug that occasionally, the UI is stuck forever in the loading mode. Now there may just be a bug in the callback code (there's quite a bit there), but my question to the community here is this: Is "MyCallback" GUARANTEED to be called? Presuming that "BeginMyMethod" didn't throw an exception, can I be sure that MyCallback will be executed? I'm seeing a "CompletedSynchronously" and "IsCompleted" on the IAsyncResult returned by the BeginXXX functions, but I'm not sure if that's important or not.
Yes, the callback is guaranteed to be called. The callback is what permits asynchronous code using the `Begin*` / `End*` pattern to be written in a continuation-passing style. You must call the corresponding `End*` method in your callback (normally, the first thing in the callback), however. It is how the asynchronous method signals an exception that may have occurred during the call, for one thing, as well as the way to get a result out (if any). Coding the asynchronous pattern using anonymous delegates when using C# 2.0 is sometimes more elegant, and permits writing of the post-call continuation close to the initiation of the call, as well as permitting much easier data sharing through captured variables, providing that appropriate synchronization measures are used. Ref: [<http://msdn.microsoft.com/en-us/library/ms228972.aspx>](http://msdn.microsoft.com/en-us/library/ms228972.aspx): > Applications that can do other work while waiting for the results of an asynchronous operation should not block waiting until the operation completes. Use one of the following options to continue executing instructions while waiting for an asynchronous operation to complete: > > * Use an AsyncCallback delegate to process the results of the asynchronous operation in a separate thread. This approach is demonstrated in this topic. > > [...]
The AsyncCallback will be called regardless of whether the operation was completed synchronously or asynchronously.
Do asynchronous web service calls always call the AsyncCallback?
[ "", "c#", ".net", "web-services", "" ]
I would like to put the date the application was built somewhere in the application. Say the about box. Any ideas how this can be done? I need to do this for C# but I am also looking for a general idea, so you can answer this for any specific language other than C#.
Typically we just go with the executable's last modify date. This will be set when the exe is built and usually never changes (short of someone actually editing the file). When the file is installed, copied, moved, etc, Windows doesn't change that value. ``` DateTime buildDate = new FileInfo(Assembly.GetExecutingAssembly().Location).LastWriteTime; ``` We use this technique for the about dialogs in our C# and C++ apps.
The third number of the assembly version is a julian date with 0=1 Jan 2000 if you're using [assembly: AssemblyVersion("1.0.\*")] e.g. ``` DateTime buildDate = new DateTime(2000,1,1).AddDays( System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.Build ); ```
How to put the build date of application somewhere in the application?
[ "", "c#", "" ]