Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
The following code says that passing the map as `const` into the `operator[]` method discards qualifiers: ``` #include <iostream> #include <map> #include <string> using namespace std; class MapWrapper { public: const int &get_value(const int &key) const { return _map[key]; } private: map<int, int> _map; }; int main() { MapWrapper mw; cout << mw.get_value(42) << endl; return 0; } ``` Is this because of the possible allocation that occurs on the map access? Can no functions with map accesses be declared const? ``` MapWrapper.cpp:10: error: passing const std::map<int, int, std::less<int>, std::allocator<std::pair<const int, int> > > as this argument of _Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = int, _Tp = int, _Compare = std::less<int>, _Alloc = std::allocator<std::pair<const int, int> >] discards qualifiers ```
[`std::map`'s `operator []` is not declared as `const`, and cannot be due to its behavior:](http://en.cppreference.com/w/cpp/container/map/operator_at) > T& operator[] (const Key& key) > > Returns a reference to the value that is mapped to a key equivalent to key, performing insertion if such key does not already exist. As a result, your function cannot be declared `const`, and use the map's `operator[]`. [`std::map`'s `find()`](http://en.cppreference.com/w/cpp/container/map/find) function allows you to look up a key without modifying the map. [`find()`](http://en.cppreference.com/w/cpp/container/map/find) returns an `iterator`, or `const_iterator` to an [`std::pair`](http://en.cppreference.com/w/cpp/utility/pair) containing both the key (`.first`) and the value (`.second`). In C++11, you could also use [`at()`](http://en.cppreference.com/w/cpp/container/map/at) for `std::map`. If element doesn't exist the function throws a `std::out_of_range` exception, in contrast to `operator []`.
Since [`operator[]`](http://www.cplusplus.com/reference/map/map/operator%5b%5d/) does not have a const-qualified overload, it cannot be safely used in a const-qualified function. This is probably because the current overload was built with the goal of both returning and setting key values. Instead, you can use: ``` VALUE = map.find(KEY)->second; ``` or, in C++11, you can use the [`at()`](http://www.cplusplus.com/reference/map/map/at/) operator: ``` VALUE = map.at(KEY); ```
C++ map access discards qualifiers (const)
[ "", "c++", "constants", "" ]
Ok so I have an abstract base class called Product, a KitItem class that inherits Product and a PackageKitItem class that inherits KitItem. ie. ``` Product KitItem : Product PackageKitItem : KitItem ``` I have my KitItems loaded and I need to load up a collection of PackageKitItems which are, effectively, shallow copies of KitItems. Currently we are doing what feels to me a hacky shallow copy in the Product constructor like so: ``` public Product(Product product) { FieldInfo[] fields = product.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); // copy each value over to 'this' foreach (FieldInfo fi in fields) fi.SetValue(this, fi.GetValue(product)); } ``` I've tried setting up a copy on KitItem like so: ``` public KitItem ShallowCopy() { return (KitItem)this.MemberwiseClone(); } ``` and calling it thus: ``` PackageKitItem tempPackKitItem = (PackageKitItem)packKitItem.ShallowCopy(); ``` but I get an invalid cast. I'm looking for ideas for the best way to accomplish this.
The problem you have is that since ShallowCopy() is a member of KitItem, MemberwiseClone() is just copying the KitItem fields and returning a KitItem even if the original object is a PackageKitItem. I think what you have to do in this circumstance add to KitItem: ``` public virtual KitItem ShallowCopy() { return (KitItem) this.MemberwiseClone(); } ``` and in PackageKitItem: ``` public override KitItem ShallowCopy() { return (PackageKitItem) this.MemberwiseClone(); } ``` Thus you will get the proper MemberwiseClone() call done depending on the object you are trying to ShallowCopy(). If you wanted to go further, you could define a ShallowCopy() in Product (returning a Product) and then have overridden versions in KitItem and PackageKitItem each returning their respective shallow copy.
Strangely I didn't get an error doing this on Visual Studio 2008. I am posting the code so you can see what I am missing or what I am assuming wrong. My guess is that the problem is in one of the class members that you didn't post. ``` using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Reflection; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { PackageKitItem PKI = new PackageKitItem(); PKI.ID = 1; PKI.KitName = "2"; PKI.Name = "3"; PKI.Package = 4; PackageKitItem tempPackKitItem = (PackageKitItem)PKI.ShallowCopy(); } } } public class Product { public int ID; public string Name; public Product() { } public Product(Product product) { FieldInfo[] fields = product.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); // copy each value over to 'this' foreach (FieldInfo fi in fields) fi.SetValue(this, fi.GetValue(product)); } } public class KitItem:Product { public string KitName; public KitItem ShallowCopy() { return (KitItem)this.MemberwiseClone(); } } public class PackageKitItem : KitItem { public int Package; } ```
Shallow Copy From Inherited Classes
[ "", "c#", "inheritance", "shallow-copy", "" ]
I've a form and I'm doing databinding of my datagridview in the event "form load", the problem is, that the form takes a little (or a lot depends on the size of information) to load, because my data has a lot of binary information (photos) to binding there. In some sites, we can see a picture saying "loading", which is cool and is good to the user, because I knows that is loading and not stoped. So, I wanted to simulate something like that to desktop application when I'm doing databinding to the table, can you help me?
You can't do much about the actual binding itself, since forms have thread affinity. However, you can load the data (from the database or where-ever) on a separate thread - look at [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx), for example. If the db-load is fast, but the binding is slow, you can look at things like "[virtual mode](http://msdn.microsoft.com/en-us/library/ms171622.aspx)" that exists for many standard list-based controls. This can reduce the time taken to bind by only looking at the immediately visible data. Other than that, you can do things like changing the cursor, showing a splash on another thread, etc. It really depends where the time is being spent (have you profiled?).
You could show the 'loading' form in a different thread. Also consider hard whether you need *all* of the data loaded with the form - could any of this data be loaded after the form load? Try and give your application a feeling of *perceived* speed.
How can I play with databinding to a desktop application like in web-based application
[ "", "c#", ".net", "" ]
The problem is simple: Using bash, I want to add a directory to my PYTHONPATH for ease of script execution. Unfortunately, the directory I want to use has a : in it. So I try each of the following ``` export PYTHONPATH=${PYTHONPATH}:/home/shane/mywebsite.com:3344/ export PYTHONPATH=${PYTHONPATH}:/home/shane/mywebsite.com\:3344/ export PYTHONPATH=${PYTHONPATH}:"/home/shane/mywebsite.com:3344/" ``` None of these work. Every time, the path is created as two separate directories on the path in python. My question is, is it possible to do this for bash? If so, what's the syntax required?
The problem is not with bash. It should be setting your environment variable correctly, complete with the `:` character. The problem, instead, is with Python's parsing of the `PYTHONPATH` variable. Following the example set by the [`PATH` variable](http://sourceware.org/cgi-bin/cvsweb.cgi/libc/posix/execvp.c?rev=1.27&content-type=text/x-cvsweb-markup&cvsroot=glibc), it seems there is no escape character at all, so there is no way to make it interpret the `:` as something other than a separator. You can see it for yourself in the [Python interpreter source code](http://svn.python.org/view/python/trunk/Modules/getpath.c?rev=54257&view=auto). The only solution is, as several people already mentioned, to use a symlink or something else to allow you to give a colon-less name for your directories.
The OP was trying to add a URL with a port number to a list of file paths. This type of URL is not a file path so python would never find a python file at that location. It doesn't make sense to put a URL with a port number into PYTHONPATH. Regardless, some people may end up at this question because of the following: On Windows paths have drive designators followed by a colon, like `C:/Python27/lib`. In bash on Windows you can add multiple paths to PYTHONPATH with a semicolon like this: ``` $ export PYTHONPATH="C:\MYPATH1;C:\MYPATH2" $ python -i Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.path ['', 'C:\\MYPATH1', 'C:\\MYPATH2', 'C:\\Windows\\system32\\python27.zip', 'C:\\Python27\\DLLs', 'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages', 'C:\\Python27\\lib\\site-packages\\win32', 'C:\\Python27\\lib\\site-packages\\win32\\lib', 'C:\\Python27\\lib\\site-packages\\Pythonwin'] ```
How do I add a directory with a colon to PYTHONPATH?
[ "", "python", "bash", "shell", "" ]
My friend produced a small proof-of-concept assembler that worked on x86. I decided to port it for x86\_64 as well, but I immediately hit a problem. I wrote a small piece of program in C, then compiled and objdumped the code. After that I inserted it to my python script, therefore the x86\_64 code is correct: ``` from ctypes import cast, CFUNCTYPE, c_char_p, c_long buffer = ''.join(map(chr, [ #0000000000000000 <add>: 0x55, # push %rbp 0x48, 0x89, 0xe5, # mov %rsp,%rbp 0x48, 0x89, 0x7d, 0xf8, # mov %rdi,-0x8(%rbp) 0x48, 0x8b, 0x45, 0xf8, # mov -0x8(%rbp),%rax 0x48, 0x83, 0xc0, 0x0a, # add $0xa,%rax 0xc9, # leaveq 0xc3, # retq ])) fptr = cast(c_char_p(buffer), CFUNCTYPE(c_long, c_long)) print fptr(1234) ``` Now, why does this script keeps doing segmentation fault whenever I run it? I have yet a question about mprotect and no execution flag. It is said to protect against most basic security exploits like buffer overruns. But what is the real reason it's in use? You could just keep on writing until you hit the .text, then inject your instructions into a nice, PROT\_EXEC -area. Unless, of course, you use a write protection in .text But then, why have that PROT\_EXEC everywhere anyway? Wouldn't it just help tremendously that your .text section is write protected?
As [vincent](https://stackoverflow.com/questions/275207/python-ctypes-and-function-calls#275333) mentioned, this is due to the allocated page being marked as non executable. Newer processors support this [functionality](http://en.wikipedia.org/wiki/NX_bit), and its used as an added layer of security by OS's which support it. The idea is to protect against certain buffer overflow attacks. Eg. A common attack is to overflow a stack variable, rewriting the return address to point to code you have inserted. With a non-executable stack this now only produces a segfault, rather than control of the process. Similar attacks also exist for heap memory. To get around it, you need to alter the protection. This can only be performed on page aligned memory, so you'll probably need to change your code to something like the below: ``` libc = CDLL('libc.so') # Some constants PROT_READ = 1 PROT_WRITE = 2 PROT_EXEC = 4 def executable_code(buffer): """Return a pointer to a page-aligned executable buffer filled in with the data of the string provided. The pointer should be freed with libc.free() when finished""" buf = c_char_p(buffer) size = len(buffer) # Need to align to a page boundary, so use valloc addr = libc.valloc(size) addr = c_void_p(addr) if 0 == addr: raise Exception("Failed to allocate memory") memmove(addr, buf, size) if 0 != libc.mprotect(addr, len(buffer), PROT_READ | PROT_WRITE | PROT_EXEC): raise Exception("Failed to set protection on buffer") return addr code_ptr = executable_code(buffer) fptr = cast(code_ptr, CFUNCTYPE(c_long, c_long)) print fptr(1234) libc.free(code_ptr) ``` Note: It may be a good idea to unset the executable flag before freeing the page. Most C libraries don't actually return the memory to the OS when done, but keep it in their own pool. This could mean they will reuse the page elsewhere without clearing the EXEC bit, bypassing the security benefit. Also note that this is fairly non-portable. I've tested it on linux, but not on any other OS. It won't work on windows, buy may do on other unixes (BSD, OsX?).
Done some research with my friend and found out this is a platform-specific issue. We suspect that on some platforms malloc mmaps memory without PROT\_EXEC and on others it does. Therefore it is necessary to change the protection level with mprotect afterwards. Lame thing, took a while to find out what to do. ``` from ctypes import ( cast, CFUNCTYPE, c_long, sizeof, addressof, create_string_buffer, pythonapi ) PROT_NONE, PROT_READ, PROT_WRITE, PROT_EXEC = 0, 1, 2, 4 mprotect = pythonapi.mprotect buffer = ''.join(map(chr, [ #0000000000000000 <add>: 0x55, # push %rbp 0x48, 0x89, 0xe5, # mov %rsp,%rbp 0x48, 0x89, 0x7d, 0xf8, # mov %rdi,-0x8(%rbp) 0x48, 0x8b, 0x45, 0xf8, # mov -0x8(%rbp),%rax 0x48, 0x83, 0xc0, 0x0a, # add $0xa,%rax 0xc9, # leaveq 0xc3, # retq ])) pagesize = pythonapi.getpagesize() cbuffer = create_string_buffer(buffer)#c_char_p(buffer) addr = addressof(cbuffer) size = sizeof(cbuffer) mask = pagesize - 1 if mprotect(~mask&addr, mask&addr + size, PROT_READ|PROT_WRITE|PROT_EXEC) < 0: print "mprotect failed?" else: fptr = cast(cbuffer, CFUNCTYPE(c_long, c_long)) print repr(fptr(1234)) ```
Python ctypes and function calls
[ "", "python", "c", "assembly", "ctypes", "x86-64", "" ]
Previously, I had a class that wrapped an internal `System.Collections.Generic.List<Item>` (where Item is a class I created). The wrapper class provided several collection-level properties that provided totals, averages, and other computations on items in the list. I was creating a `BindingSource` around this wrapped `List<>` and another `BindingSource` around my class and was able to get at the Items in the wrapped list through the first `BindingSource` and the collection-level properties of the wrapper class using the second. A simplified example looks like: ``` public class OldClass() { private List<Item> _Items; public OldClass() { _Items = new List<Item>(); } public List<Item> Items { get { return _Items; } } // collection-level properties public float AverageValue { get { return Average() } } public float TotalValue { get { return Total() } } // ... other properties like this } ``` With the binding sources created in this way: ``` _itemsBindingSource = new BindingSource(oldClass.Items); _summaryBindingSource = new BindingSource(oldClass); ``` Recently, I tried to change this class to be derived from `System.Collections.Generic.List<Item>` instead of keeping a wrapped `List<>` member. My hope was to get rid of the extra wrapper layer and use only one `BindingSource` instead of two. However, now I find that I cannot get at the properties that apply to all items in the list (such as `AverageValue`) when I do data binding. Only the properties of list items are available. Am I forced to go back to using a wrapped `List<>` of `Item`s? Or is there a way that I can get at both the properties of `Item`s stored my new class as well as the properties that apply to the collection itself?
The system treats anything that implements `IList` (or `IListSource`) as a container, rather than an item. As such, you cannot bind to properties of anything that implements `IList`. As such, *encapsulation* (i.e. what you already have) is the best approach if you want to be able to bind to properties of the container. However, you should note that many bindings support dot-notation in the source - i.e. either binding to "Items.SomeProperty", or setting the auxiliary property (typically `DataMember`) to specify sub-lists. This allows you to have a single `BindingSource`, and have different controls bound to different levels in the hierarchy - i.e. you might have a `TextBox` bound to `AverageValue`, and a `DataGridView` (with the same `DataSource`) that has `DataMember="Items"`.
The problem here is that you want to use your one class for two completely different purposes (in terms of bindings). Example: The "AverageValue" property doesn't make sense to be on each item, because it's a global property that spans all items. Either way, I'm guessing that your \_itemsBindingSource is for a ComboBox or something, and that your \_summaryBindingSource is for a PropertyGrid (or something like that). What you *could* do, that *might* work in your situation (I can't be certain because I don't know what you are actually doing) is this: 1) Make your "OldClass" implement IEnumerable... and in that, simply return the enumeration from the list. That will give you the ability to bind to "oldClass" instead of "oldClass.Items". 2) Make the "public List Items" a field, instead of a property... or add the "Browsable(false)" attribute so it won't get bound to the PropertyGrid (this is a guess as it's unclear what you're using these bindings for).
How can I databind to properties not associated with a list item in classes deriving List<T>
[ "", "c#", "generics", "data-binding", "" ]
I have a rather complex decorator written by someone else. What I want to do is call a decorated version of the function one time based on a descision or call the original function (not decorated) another time. Is this possible?
With: ``` decorator(original_function)() ``` Without: ``` original_function() ``` A decorator is just a function which takes a function as an argument and returns another one. The @ syntax is totally optional. Perhaps a sift through some [documentation](https://wiki.python.org/moin/PythonDecorators) might help clarify things.
``` def original_function(): pass decorated_function= decorator(original_function) if use_decorated: decorated_function() else: original_function() ``` Decorate only once, and afterwards choose which version to call.
Python decorating functions before call
[ "", "python", "decorator", "" ]
We are using jQuery [thickbox](http://jquery.com/demo/thickbox/) to dynamically display an iframe when someone clicks on a picture. In this iframe, we are using [galleria](http://devkick.com/lab/galleria/demo_01.htm) a javascript library to display multiple pictures. The problem seems to be that `$(document).ready` in the iframe seems to be fired too soon and the iframe content isn't even loaded yet, so galleria code is not applied properly on the DOM elements. `$(document).ready` seems to use the iframe parent ready state to decide if the iframe is ready. If we extract the function called by document ready in a separate function and call it after a timeout of 100 ms. It works, but we can't take the chance in production with a slow computer. ``` $(document).ready(function() { setTimeout(ApplyGalleria, 100); }); ``` My question: which jQuery event should we bind to to be able to execute our code when the dynamic iframe is ready and not just it's a parent?
I answered a similar question (see [Javascript callback when IFRAME is finished loading?](https://stackoverflow.com/questions/164085/javascript-callback-when-iframe-is-finished-loading)). You can obtain control over the iframe load event with the following code: ``` function callIframe(url, callback) { $(document.body).append('<IFRAME id="myId" ...>'); $('iframe#myId').attr('src', url); $('iframe#myId').load(function() { callback(this); }); } ``` In dealing with iframes I found good enough to use load event instead of document ready event.
Using jQuery 1.3.2 the following worked for me: ``` $('iframe').ready(function() { $('body', $('iframe').contents()).html('Hello World!'); }); ``` REVISION:! Actually the above code sometimes looks like it works in Firefox, never looks like it works in Opera. Instead I implemented a polling solution for my purposes. Simplified down it looks like this: ``` $(function() { function manipIframe() { el = $('body', $('iframe').contents()); if (el.length != 1) { setTimeout(manipIframe, 100); return; } el.html('Hello World!'); } manipIframe(); }); ``` This doesn't require code in the called iframe pages. All code resides and executes from the parent frame/window.
jQuery .ready in a dynamically inserted iframe
[ "", "javascript", "jquery", "iframe", "thickbox", "galleria", "" ]
[Spring Workflow](http://www.springsource.org/extensions/se-workflow) has now been published. * Have you tried it yet? For what kind of scenario? * What is your impression? How do you find it stacks up against other workflow libs? * Found any good docs or tutorials?
OK, ignoring my beliefs shown in my previous post I did try spring workflow, only to find out that I was right. Getting the sources and building is not that hard, they use svn, ant and ivy as repository manager. Making it work is another story. I took the sample sources, an placed them in a new project. At this poit I had to rename all imports since they were built for test eviron ment i guess. This is easy with help from the IDE in classes, but you also have to rename them in spring's XML context files. Further on, it starts to look bad once you try to run the project. First you get a NullPointerException, because of the following lines : ``` public final void afterPropertiesSet() throws Exception { if (this.flowInstanceDescriptorPersisters == null) { this.flowInstanceDescriptorPersisters.put(DEFAULT_PERSISTER, new DefaultFlowInstanceDescriptorPersister()); } } ``` I simply created a new HashMap, rebuit the project and gave it another try. Now it will fail at an Assert if you did not include spring security. There is a hidded dependency (because reflection is used). Added the lib. and ran it again. I got another Assert fail, and when I looked that up I realised the samples are not even supposed to work. A method intentionally returns null and it shouldn't. I went to the interface, of cource, no javadoc, but i suspected what it should return from it's name, so i placed a hardcode value. At this point it biulds and it runs but it does not work, it's supposed to (at least i think it is, there are no docs.) do a transition, but the flow remains unchanged after the performTransition call. So there you have it. Dont try it just yet.
I don't think it's a good idea to try it yet, it's just a release to proove the concept. First of all you have to manually build your library, after that, leran how to use it with no example or documentation, just using the scarcely documented code and test code. And when you have an idea about it you realise it can't do very mutch right now.
Have you tried Spring Workflow already?
[ "", "java", "spring", "workflow", "" ]
I'm attempting to get my first ASP.NET web page working on windows using [Mono](http://www.mono-project.com/Main_Page) and the XSP web server. I'm following this chaps [example](http://www.codeproject.com/KB/cross-platform/introtomono2.aspx). The [first part](http://www.codeproject.com/KB/cross-platform/introtomono1.aspx) of his example works very well with the latest version of mono. however the web part seems to fall over with the following error > '{Path Name}\Index.aspx.cs' is not a > valid virtual path. Here's the full Stack Trace: ``` System.Web.HttpException: 'C:\Projects\Mono\ASPExample\simpleapp\index.aspx.cs' is not a valid virtual path. at System.Web.HttpRequest.MapPath (System.String virtualPath, System.String baseVirtualDir, Boolean allowCrossAppMapping) [0x00000] at System.Web.HttpRequest.MapPath (System.String virtualPath) [0x00000] at System.Web.Compilation.BuildManager.AddToCache (System.String virtualPath, System.Web.Compilation.BuildProvider bp) [0x00000] at System.Web.Compilation.BuildManager.BuildAssembly (System.Web.VirtualPath virtualPath) [0x00000] at System.Web.Compilation.BuildManager.GetCompiledType (System.String virtualPath) [0x00000] at System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath (System.String virtualPath, System.Type requiredBaseType) [0x00000] at System.Web.UI.PageParser.GetCompiledPageInstance (System.String virtualPath, System.String inputFile, System.Web.HttpContext context) [0x00000] at System.Web.UI.PageHandlerFactory.GetHandler (System.Web.HttpContext context, System.String requestType, System.String url, System.String path) [0x00000] at System.Web.HttpApplication.GetHandler (System.Web.HttpContext context, System.String url, Boolean ignoreContextHandler) [0x00000] at System.Web.HttpApplication.GetHandler (System.Web.HttpContext context, System.String url) [0x00000] at System.Web.HttpApplication+<Pipeline>c__Iterator5.MoveNext () [0x00000] ``` I was wondering if anyone knew what this error meant. I guess i'm looking for a mono expert, who's tried out the windows version.
Hey i don't know how to get the "code behind" stuff working but i've found a workaround that i'm happy with. I thought i'd post it up here for the benefit of others. Basically you move the code behind into the main page and it works great just by using the XSD command and no parameters. ``` <%@ Page Language="C#" %> <%@ Import Namespace="System.Data" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Code behind Arrrrrrrrrrgh</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script runat="server"> private void Page_Load(Object sender, EventArgs e) { DisplayServerDetails(); DisplayRequestDetails(); } private void DisplayServerDetails() { serverName.Text = Environment.MachineName; operatingSystem.Text = Environment.OSVersion.Platform.ToString(); operatingSystemVersion.Text = Environment.OSVersion.Version.ToString(); } private void DisplayRequestDetails() { requestedPage.Text = Request.Url.AbsolutePath; requestIP.Text = Request.UserHostAddress; requestUA.Text = Request.UserAgent; } </script> </head> <body> <form method="post" runat="server"> <table width="450px" border="1px"> <tr> <td colspan="2"><strong>Server Details</strong></td> </tr> <tr> <td>Server Name:</td> <td> <asp:Label id="serverName" runat="server"></asp:Label></td> </tr> <tr> <td>Operating System:</td> <td> <asp:Label id="operatingSystem" runat="server"></asp:Label> </td> </tr> <tr> <td>Operating System Version:</td> <td> <asp:Label id="operatingSystemVersion" runat="server"> </asp:Label> </td> </tr> </table> <br> <table width="450px" border="1px"> <tr> <td colspan="2"><strong>Request Details</strong></td> </tr> <tr> <td>Page Requested:</td> <td> <asp:Label id="requestedPage" runat="server"></asp:Label> </td> </tr> <tr> <td>Request From:</td> <td> <asp:Label id="requestIP" runat="server"></asp:Label> </td> </tr> <tr> <td>User Agent:</td> <td> <asp:Label id="requestUA" runat="server"></asp:Label> </td> </tr> </table> </form> </body> ```
Can you paste the command line you are using to start xsp? If you are just running a single webapp something like this isn't really needed, and could be the source of the problem: xsp --applications /SimpleWebApp:C:\Projects\Mono\ASPExample\ just cd to the ASPExample directory and run xsp with no parameters.
Sample web Page using Mono and XSP on windows box
[ "", "c#", "asp.net", "windows", "mono", "xsp", "" ]
How do I serialize a 'Type'? I want to serialize to XML an object that has a property that is a type of an object. The idea is that when it is deserialized I can create an object of that type. ``` public class NewObject { } [XmlRoot] public class XmlData { private Type t; public Type T { get { return t; } set { t = value; } } } static void Main(string[] args) { XmlData data = new XmlData(); data.T = typeof(NewObject); try { XmlSerializer serializer = new XmlSerializer(typeof(XmlData)); try { using (FileStream fs = new FileStream("test.xml", FileMode.Create)) { serializer.Serialize(fs, data); } } catch (Exception ex) { } } catch (Exception ex) { } } ``` I get this exception: "The type ConsoleApplication1.NewObject was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically." Where do I put the [XmlInclude]? Is this even possible?
XML serialization serializes only the public fields and property values of an object into an XML stream. **XML serialization does not include type information.** For example, if you have a Book object that exists in the Library namespace, there is no guarantee that it will be deserialized into an object of the same type. Source: [Details of XML serialization | Microsoft Docs](https://learn.microsoft.com/en-us/dotnet/standard/serialization/introducing-xml-serialization)
`Type` class cannot be serialized because `System.RuntimeType` is not accessible to our code, it is an internal CLR type. You may work around this by using the type's name instead, like this: ``` public class c { [XmlIgnore] private Type t; [XmlIgnore] public Type T { get { return t; } set { t = value; tName = value.AssemblyQualifiedName; } } public string tName{ get { return t.AssemblyQualifiedName; } set { t = Type.GetType(value);} } } ```
How to XML Serialize a 'Type'
[ "", "c#", "xml", "serialization", "" ]
There is div named "dvUsers". there is an anchor tag "lnkUsers". When one clicks on anchortag, the div must open like a popup div just below it. Also the divs relative position should be maintained at window resize and all. How to do that using javascript/jquery?
Perhaps you should look for a premade script like **overLIB**: <http://www.bosrup.com/web/overlib/> !-)
My preference is to place both of these inside of a parent div as follows: ``` <div id="container"> <a id="lnkUsers" href="#">Users</a> <div id="dvUsers" style="display: none;"> <!-- user content... --> </div> </div> ``` The CSS for these elements would be: ``` #container{ /* ensure that #dvUsers is positioned relatively to this element */ position: relative; } #dvUsers{ position: absolute; /* this value should be based on the font-size of #lnkUsers */ top: 30px; left: -10px; } ``` This ensures that the div is positioned correctly relative to the link. (For the sake of this question I am assuming the parent div is either "text-align: left" or floated) The javascript would look something like this: ``` $(function(){ $('#lnkUsers').click(function(){ $('#dvUsers').slideToggle(); }); }); ```
Relative Positioning of DIV
[ "", "javascript", "jquery", "" ]
The very common beginner mistake is when you try to use a class property "statically" without making an instance of that class. It leaves you with the mentioned error message: > You can either make the non static method static or make an instance of that class to use its properties. **What the reason behind this? Am not concern with the solution, rather the reason.** ``` private java.util.List<String> someMethod(){ /* Some Code */ return someList; } public static void main(String[] strArgs){ // The following statement causes the error. java.util.List<String> someList = someMethod(); } ```
You can't call something that doesn't exist. Since you haven't created an object, the non-static method doesn't exist yet. A static method (by definition) always exists.
The method you are trying to call is an instance-level method; you do not have an instance. `static` methods belong to the class, non-`static` methods belong to instances of the class.
What is the reason behind "non-static method cannot be referenced from a static context"?
[ "", "java", "static", "" ]
I'm currently refactoring code to replace Convert.To's to TryParse. I've come across the following bit of code which is creating and assigning a property to an object. ``` List<Person> list = new List<Person>(); foreach (DataRow row in dt.Rows) { var p = new Person{ RecordID = Convert.ToInt32(row["ContactID"]) }; list.Add(p); } ``` What I've come up with as a replacement is: ``` var p = new Person { RecordID = Int32.TryParse(row["ContactID"].ToString(), out RecordID) ? RecordID : RecordID }; ``` Any thoughts, opinions, alternatives to what I've done?
Write an extension method. ``` public static Int32? ParseInt32(this string str) { Int32 k; if(Int32.TryParse(str, out k)) return k; return null; } ```
I'd use an alternative implementation `TryParse` which returns an `int?`: ``` public static int? TryParseInt32(string x) { int value; return int.TryParse(x, out value) ? value : (int?) null; } ``` Then you can write: ``` var p = new Person { RecordID = Helpers.TryParseInt32(row["ContactID"].ToString()) ?? 0 }; ``` (Or use a different default value, if you want - either way it'll be visible in your code.)
Using TryParse for Setting Object Property Values
[ "", "c#", "exception", "refactoring", "tryparse", "" ]
Say I have this simple form: ``` class ContactForm(forms.Form): first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) ``` And I have a default value for one field but not the other. So I set it up like this: ``` default_data = {'first_name','greg'} form1=ContactForm(default_data) ``` However now when I go to display it, Django shows a validation error saying last\_name is required: ``` print form1.as_table() ``` What is the correct way to do this? Since this isn't data the user has submitted, just data I want to prefill. **Note:** required=False will not work because I do want it required when the user submits the data. Just when I'm first showing the form on the page, I won't have a default value.
Form constructor has `initial` param that allows to provide default values for fields.
From the django docs is this: ``` from django import forms class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField() sender = forms.EmailField() cc_myself = forms.BooleanField(required=False) ``` The "required=False" should produce the effect you're after.
Django Forms - How to Not Validate?
[ "", "python", "django", "forms", "" ]
In C++, is it possible to have a base plus derived class implement a single interface? For example: ``` class Interface { public: virtual void BaseFunction() = 0; virtual void DerivedFunction() = 0; }; class Base { public: virtual void BaseFunction(){} }; class Derived : public Base, public Interface { public: void DerivedFunction(){} }; void main() { Derived derived; } ``` This fails because Derived can not be instantiated. As far as the compiler is concerned Interface::BaseFunction is never defined. So far the only solution I've found would be to declare a pass through function in Derived ``` class Derived : public Base, public Interface { public: void DerivedFunction(){} void BaseFunction(){ Base::BaseFunction(); } }; ``` Is there any better solution? --- **EDIT:** If it matters, here is a real world problem I had using MFC dialogs. I have a dialog class (MyDialog lets say) that derives from CDialog. Due to dependency issues, I need to create an abstract interface (MyDialogInterface). The class that uses MyDialogInterface needs to use the methods specific to MyDialog, but also needs to call CDialog::SetParent. I just solved it by creating MyDialog::SetParent and having it pass through to CDialog::SetParent, but was wondering if there was a better way.
C++ doesn't notice the function inherited from Base already implements `BaseFunction`: The function has to be implemented explicitly in a class derived from `Interface`. Change it this way: ``` class Interface { public: virtual void BaseFunction() = 0; virtual void DerivedFunction() = 0; }; class Base : public Interface { public: virtual void BaseFunction(){} }; class Derived : public Base { public: virtual void DerivedFunction(){} }; int main() { Derived derived; } ``` If you want to be able to get away with only implementing one of them, split `Interface` up into two interfaces: ``` class DerivedInterface { public: virtual void DerivedFunction() = 0; }; class BaseInterface { public: virtual void BaseFunction() = 0; }; class Base : public BaseInterface { public: virtual void BaseFunction(){} }; class Derived : public DerivedInterface { public: virtual void DerivedFunction(){} }; class Both : public DerivedInterface, public Base { public: virtual void DerivedFunction(){} }; int main() { Derived derived; Base base; Both both; } ``` Note: main must return int Note: it's good practise to keep `virtual` in front of member functions in the derived that were virtual in the base, even if it's not strictly required.
It looks like it's not quite the case that Derived "is-a" Base, which suggests that containment may be a better implementation than inheritance. Also, your Derived member functions should be decalred as virtual as well. ``` class Contained { public: void containedFunction() {} }; class Derived { public: virtual void derivedFunction() {} virtual void containedFunction() {return contained.containedFunction();} private: Containted contained; }; ``` You can make the contained member a reference or smart pointer if you want to hide the implementation details.
C++: Derived + Base class implement a single interface?
[ "", "c++", "class", "inheritance", "interface", "" ]
It doesn't look like basic javascript but nor can I use JQuery commands like `$('myId')`. Is this or similar functions documented anywhere? For reason I don't want to go into, I am not able to use 3rd party libraries like JQuery but if some powerful javascript extensions come with asp then I would like to know about them.
$get is a function from the (now depreciated) ms ajax core javascript library. In the future they will be using jquery therefore $get will just be $('#myid') so I dont understand your feelings about not using jQuery, MS have decided to embrace OpenSource and bundle it with visual studio, check out Scott Gu and Hanslemans announcements on their blogs. The ms ajax $get('foo') and jQuery $('#someID') are both just shortened wrappers around native javascript document.getElementById('bla') ms ajax docs <http://www.asp.net/ajax/documentation/>
Something to keep in mind is that MS AJAX's $get() function returns the same things as document.getElementById() where as JQuery's $() function returns a special object with different properties and methods. While they are used to select elements in the DOM, the $() is a lot more powerful thanks to jQuery's framework and the vast array of Plug-Ins available for it. As far as adoption and such, both Visual Studio 2008 and Adobe's Dreamweaver CS4 (I think CS3 as well) have the ability to have jQuery integrated. While you're forbidden to use 3rd party libraries, I'd hope that you'd be able to make a case that reinventing the wheel or the plumbing code that someone else has already done can be very costly...especially if the 3rd party libraries are free.
ASP.Net AJAX uses syntax like $get('myId'), is this standard Javascript or JQuery?
[ "", "asp.net", "javascript", "jquery", "asp.net-ajax", "" ]
I have a `JPanel` extension that I've written and would like to be able to use it in the NetBeans designer. The component is simply adds some custom painting and continues to function as a container to be customised on each use. I have properties to expose in addition to the standard `JPanel` ones and have a custom `paintComponent()` method that I'd like to be able to see in use when building up GUIs. Ideally I'd like to associate an icon with the component as well so that its easily recognisable for my colleagues to work with. What's the best way of achieving this?
I made JPanel component in NetBeans with overridden paint method: ``` @Override public void paint(Graphics g) { super.paint(g); Graphics2D g2 = (Graphics2D) g; ... //draw elements ... } ``` It has some custom properties accessible through NetBeans properties window. ``` public int getResolutionX() { return resolutionX; } public void setResolutionX(int resolutionX) { this.resolutionX = resolutionX; } public int getResolutionY() { return resolutionY; } public void setResolutionY(int resolutionY) { this.resolutionY = resolutionY; } ``` I put it in my palette using: Tools->Palette->Swing/AWT Components. It even has the same look I painted in my overridden paint method while I am doing drag/drop in another container. I didn't associate icon to it though. Hope this helps.
<http://www.netbeans.org> search for Matisse.
How do I create a custom JPanel extension and use it from the NetBeans palette?
[ "", "java", "swing", "netbeans", "" ]
My class contains a `Dictionary<T, S> dict`, and I want to expose a `ReadOnlyCollection<T>` of the keys. How can I do this without copying the `Dictionary<T, S>.KeyCollection dict.Keys` to an array and then exposing the array as a `ReadOnlyCollection`? I want the `ReadOnlyCollection` to be a proper wrapper, ie. to reflect changes in the underlying Dictionary, and as I understand it copying the collection to an array will not do this (as well as seeming inefficient - I don't actually want a new collection, just to expose the underlying collection of keys...). Any ideas would be much appreciated! Edit: I'm using C# 2.0, so don't have extension methods such as .ToList (easily) available.
If you really want to use ReadOnlyCollection<T>, the issue is that the constructor of ReadOnlyCollection<T> takes an IList<T>, while the KeyCollection of the Dictionary is only a ICollection<T>. So if you want to wrap the KeyCollection in a ReadOnlyCollection, you'll have to create an adapter (or wrapper) type, implementing IList<T>, wrapping the KeyCollection. So it would look like: ``` var dictionary = ...; var readonly_keys = new ReadOnlyCollection<T> (new CollectionListWrapper<T> (dictionary.Keys) ); ``` Not very elegant though, especially as the KeyCollection is already a readonly collection, and that you could simply pass it around as an ICollection<T> :)
DrJokepu said that it might be difficult to implement a wrapper for Keys Collection. But, in this particular case, I think the implementation is not so difficult because, as we know, this is a read-only wrapper. This allows us to ignore some methods that, in other case, would be hard to implement. Here's a quick implementation of the wrapper for Dictionary.KeyCollection : ``` class MyListWrapper<T, TValue> : IList<T> { private Dictionary<T, TValue>.KeyCollection keys; public MyListWrapper(Dictionary<T, TValue>.KeyCollection keys) { this.keys = keys; } #region IList<T> Members public int IndexOf(T item) { if (item == null) throw new ArgumentNullException(); IEnumerator<T> e = keys.GetEnumerator(); int i = 0; while (e.MoveNext()) { if (e.Current.Equals(item)) return i; i++; } throw new Exception("Item not found!"); } public void Insert(int index, T item) { throw new NotImplementedException(); } public void RemoveAt(int index) { throw new NotImplementedException(); } public T this[int index] { get { IEnumerator<T> e = keys.GetEnumerator(); if (index < 0 || index > keys.Count) throw new IndexOutOfRangeException(); int i = 0; while (e.MoveNext() && i != index) { i++; } return e.Current; } set { throw new NotImplementedException(); } } #endregion #region ICollection<T> Members public void Add(T item) { throw new NotImplementedException(); } public void Clear() { throw new NotImplementedException(); } public bool Contains(T item) { return keys.Contains(item); } public void CopyTo(T[] array, int arrayIndex) { keys.CopyTo(array, arrayIndex); } public int Count { get { return keys.Count; } } public bool IsReadOnly { get { return true; } } public bool Remove(T item) { throw new NotImplementedException(); } #endregion #region IEnumerable<T> Members public IEnumerator<T> GetEnumerator() { return keys.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return keys.GetEnumerator(); } #endregion } ``` This might not be the best implementation for these methods :) but it was just for proving that this might be done.
How to get a ReadOnlyCollection<T> of the Keys in a Dictionary<T, S>
[ "", "c#", "generics", "dictionary", "collections", "c#-2.0", "" ]
How do I build an escape sequence string in hexadecimal notation. Example: ``` string s = "\x1A"; // this will create the hex-value 1A or dec-value 26 ``` I want to be able to build strings with hex-values between 00 to FF like this (in this example 1B) ``` string s = "\x" + "1B"; // Unrecognized escape sequence ``` Maybe there's another way of making hexadecimal strings...
You don't store hexadecimal values in strings. You can, but it would just be that, a string, and would have to be cast to an integer or a byte to actually read its value. You can assign a hexadecimal value as a literal to an int or a byte though: ``` Byte value = 0x0FF; int value = 0x1B; ``` So, its easily possible to pass an hexadecimal literal into your string: ``` string foo = String.Format("{0} hex test", 0x0BB); ``` Which would create this string "126 hex test". But I don't think that's what you wanted?
Please try to avoid the `\x` escape sequence. It's difficult to read because where it stops depends on the data. For instance, how much difference is there at a glance between these two strings? ``` "\x9Good compiler" "\x9Bad compiler" ``` In the former, the "\x9" is tab - the escape sequence stops there because 'G' is not a valid hex character. In the second string, "\x9Bad" is all an escape sequence, leaving you with some random Unicode character and " compiler". I suggest you use the \u escape sequence instead: ``` "\u0009Good compiler" "\u0009Bad compiler" ``` (Of course for tab you'd use `\t` but I hope you see what I mean...) This is somewhat aside from the original question of course, but that's been answered already :)
C# Build hexadecimal notation string
[ "", "c#", "string", "hex", "" ]
Suppose I have #define foo in various header files. It may expand to some different things. I would like to know (when compiling a .cc file) when a #define is encountered, to what it will expand, it which file it is and where it got included from. Is it possible? If not, are there any partial solutions that may help? Feel free to add comments with clarification requests. **Edit: current answers seem to concentrate on the case when there is one #define and I just want to jump to definition or know what the definition is. That's the simple case and yes, your solutions work. But when I have the same #define in different files, and want to know which one kicks in first, none of these techniques is useful. Okay, I actually used #warning carefully to find the right place. But this requires much work.**
Use -E : ``` # shows preprocessed source with cpp internals removed g++ -E -P file.cc # shows preprocessed source kept with macros and include directives g++ -E -dD -dI -P file.cc ``` The internals above are line-markers for gcc which are kinda confusing when you read the output. `-P` strips them ``` -E Stop after the preprocessing stage; do not run the compiler proper. The output is in the form of preprocessed source code, which is sent to the standard output. Input files which don't require preprocessing are ignored. ``` Note: comments correctly complain this is only a partial solution. It won't tell you when a macro will be replaced. It shows you the preprocessed source, which can be helpful anyway.
> I would like to know (when compiling a .cc file) when a #define is encountered, [I know a solution to that](http://blogs.msdn.com/oldnewthing/archive/2008/04/10/8373617.aspx). Compile the file with the symbol already defined as illegal C++ code (the article linked to uses '@'). So, for GCC you would write ``` gcc my_file.c -Dfoo=@ ``` When that expands it's guaranteed to cause a syntax error, and the compiler should tell you which file that syntax error is in, which will be very helpful. If you use the trick Raymond Chen suggests, the compiler *may* tell you where the "conflicting" definition came from, and *may* give you a list of how it got included. But there's no guarantee. Since I don't use macros (I prefer const and enum) I can't say if GCC is one of the smarter compilers in this regard. I don't believe the C or C++ standards say anything about this, other than once the preprocessor runs you lose all sorts of useful information.
How to know (in GCC) when given macro/preprocessor symbol gets declared?
[ "", "c++", "gcc", "c-preprocessor", "" ]
What is the best way to do cross-platform handling of hidden files? (preferably in Python, but other solutions still appreciated) Simply checking for a leading '.' works for \*nix/Mac, and file attributes work on Windows. However, this seems a little simplistic, and also doesn't account for alternative methods of hiding things (.hidden files, etc.). Is there a standard way to deal with this?
We actually address this in a project we write. What we do is have a number of different "hidden file checkers" that are registered with a main checker. We pass each file through these to see if it should be hidden or not. These checkers are not only for different OS's etc, but we plug into version control "ignored" files, and optional user overrides by glob or regular expression. It mostly amounts to what you have done, but in a pluggable, flexible and extensible way. See source code here: <https://bitbucket.org/aafshar/pida-main/src/tip/pida/services/filemanager/filemanager.py>
Here's a script that runs on Python 2.5+ and should do what you're looking for: ``` import ctypes import os def is_hidden(filepath): name = os.path.basename(os.path.abspath(filepath)) return name.startswith('.') or has_hidden_attribute(filepath) def has_hidden_attribute(filepath): try: attrs = ctypes.windll.kernel32.GetFileAttributesW(unicode(filepath)) assert attrs != -1 result = bool(attrs & 2) except (AttributeError, AssertionError): result = False return result ``` I added something similar to has\_hidden\_attribute to [jaraco.windows](https://bitbucket.org/jaraco/jaraco.windows). If you have jaraco.windows >= 2.3: ``` from jaraco.windows import filesystem def has_hidden_attribute(filepath): return filesystem.GetFileAttributes(filepath).hidden ``` As Ben has pointed out, on Python 3.5, you can use the stdlib: ``` import os, stat def has_hidden_attribute(filepath): return bool(os.stat(filepath).st_file_attributes & stat.FILE_ATTRIBUTE_HIDDEN) ``` Though you may still want to use jaraco.windows for the more Pythonic API.
Cross platform hidden file detection
[ "", "python", "cross-platform", "filesystems", "" ]
Is something like the following possible in PHP? ``` $blah = 'foo1'; class foo2 extends $blah { //... } class foo1 { //... } ``` This gives an error. I want to dynamically set $blah so I can extend whatever class I want. **Edit:** The reason for wanting to do this because I wanted to use a function out of another class in a related class. In the end it would have been something like: ``` Final extends foo1 extends foo2 extends foo3 extends foo4 extends parent { ... } ``` In the end I decided to instantiate the other class within the class and use it. Not the best options because they both you 2 of the same classes, but this won't be used that often, so it will work for now.
You're assuming here php executes top to bottom, but it doesn't quite work like that: ``` <?php foo(); # works function foo(){ print "bar"; } ``` --- ``` <?php foo(); #dies if( $i == 1 ) { function foo(){ print "bar"; } } ``` --- ``` <?php $i = 1; if( $i == 1 ) { function foo(){ print "bar"; } } foo(); #works ``` --- Now, although you can conditionally create classes: ``` <?php class A { } class B { } if( false ){ class C extends B { public static function bar(){ print "baz"; } } } C::bar(); # dies ``` You cant instantiate one at runtime from a variable: ``` <?php class A { } class B { } $x = 'B'; if( false ){ class C extends $x { public static function bar(){ print "baz"; } } } C::bar(); ---> Parse error: syntax error, unexpected T_VARIABLE, expecting T_STRING in /tmp/eg.php on line 7 ``` There is a way to do it with Eval, but you *really* don't want to go there: ``` <?php class A { } class B { } $x = 'B'; if( true ){ $code =<<<EOF class C extends $x { public static function bar(){ print "baz"; } } EOF; eval( $code ); } C::bar(); $o = new C; if ( $o instanceof $x ) { print "WIN!\n"; } --->barWIN! ``` However, there is a more important question here: **Why the hell would you *want* to extend a different class at runtime** Anybody using your code will want to hold you down and *whip* you for that. ( Alternatively, if you're into whipping, do that eval trick )
I know this question was asked a long time ago, but the answer is relatively simple. Assuming you want to extend class foo if class foo exists, or class bar if it doesn't, you'd use: ``` if(!class_exists('foo')) { class foo extends bar { function __construct() { parent::__construct(); } } } class myclass extends foo{ //YOUR CLASS HERE } ```
Variable variable class extensions in PHP--is it possible?
[ "", "php", "class", "object", "variable-variables", "" ]
I need to read an Excel 2007 XLSX file in a Java application. Does anyone know of a good API to accomplish this task?
AFAIK there are no xlsx-libraries available yet. But there are some for old xls: One library is [jxls](http://jxls.sourceforge.net/) which internally uses the already mentioned [POI](http://poi.apache.org/). 2 other links: [Handle Excel files](http://www.rgagnon.com/javadetails/java-0516.html), [Java libraries to read and write Excel XLS document files](http://roide-textcube.blogspot.fr/2009/02/java-libraries-to-read-and-write-excel.html).
[Apache POI](http://poi.apache.org/) 3.5 have added support to all the OOXML (docx, xlsx, etc.) See the [XSSF sub project](http://poi.apache.org/spreadsheet/index.html)
Read XLSX file in Java
[ "", "java", "excel", "parsing", "" ]
This very simple code gives me tons of errors: ``` #include <iostream> #include <string> int main() { std::string test = " "; std::cout << test; } ``` I tried to compile it on linux by typing **gcc -o simpletest simpletest.cpp** on the console. I can't see why it isn't working. What is happening?
Try using 'g++' instead of 'gcc'.
To add to what others have said: `g++` is the GNU C++ compiler. `gcc` is the GNU compiler collection (**not** the GNU C compiler, as many people assume). `gcc` serves as a frontend for `g++` when compiling C++ sources. `gcc` can compile C, C++, Objective-C, Fortran, Ada, assembly, and others. The reason why it fails trying to compile with `gcc` is that you need to link in the C++ standard library. By default, `g++` does this, but `gcc` does not. To link in the C++ standard library using `gcc`, use the following: ``` gcc -o simpletest simpletest.cpp -lstdc++ ```
Simple C++ code not working
[ "", "c++", "gcc", "g++", "" ]
Say I have a list of all `Projects`, and that I group them by `Category` like this: ``` var projectsByCat = from p in Projects group p by p.Category into g orderby g.Count() descending select new { Category = g.Key, Projects = g }; ``` Now I want to display this as a list in a web page, where first I create the left side div, secondly the right side div. I am ordering by number of `Projects` in each `Category` to show the `Categories` with the most `Projects` on top - thus I would like to split `projectsByCat` in two - if I put all the "odd numbered" `Categories` on the left and the "even numbered" categories on the right, I think I will get a reasonably sane view. So I thought I could do this to get the odd and even members of `projectsByCat`: ``` var oddCategories = projectsByCat.Where((cat, index) => index % 2 != 0); var evenCategories = projectsByCat.Where((cat, index) => index % 2 == 0); ``` And it compiles - however, when I run it, I get an exception such as this: > Unsupported overload used for query operator 'Where'. And I thought I was safe since it compiled in the first place.. ;) Is there an elegant way to do this? And also, is there an elegant explanation for why my creative use of `Where()` won't work?
If you're using LINQ to SQL or LINQ to Entities you should first fully materialize the results into memory: ``` var oddCategories = projectsByCat.ToList().Where((c,i) => i % 2 != 0); var evenCategories = projectsByCat.ToList().Where((c,i) => i % 2 == 0); ``` It isn't possible to iterate through results on the database with an indexer without the use of a cursor, which either ORM framework does **not** do.
Note that calling `.ToList()` twice for the same query is going query the database twice. It would be much better to cache the result in an intermediate list, *then* apply your predicate filtering: ``` var projectsByCat = (from p in Projects group p by p.Category into g orderby g.Count() descending select new { Category = g.Key, Projects = g }).ToList(); var oddCategories = projectsByCat.Where((cat, index) => index % 2 != 0); var evenCategories = projectsByCat.Where((cat, index) => index % 2 == 0); ```
Getting odd/even part of a sequence with LINQ
[ "", "c#", "linq", "" ]
I have a Windows forms project (VS 2005, .net 2.0). The solution has references to 9 projects. Everything works and compiles fine on one of my computers. When I move it to a second computer, 8 out of the 9 project compile with no problem. When I try to compile the 9th project (the main project for the application - produces the .exe file to execute the application), I get the following error: ``` 'Error 3: A strongly-named assembly is required. (Exception from HRESULT: 0x80131044)' ``` The file location for the error is is listed as "C:\PATH-TO-APP\LC". I have checked in the project properties and all of the projects are set to build in Debug mode, none of them are supposed to be signed. In the project that is failing, the only assembly that it references that is not in any of the other projects is Microsoft.VisualBasic (a .net 2.0 assembly). So I am at a loss to find what ids causing this error (the file referenced above in the error message - "LC" - does not exist. Anyone know how I can force the project to accept all unsigned assemblies, or to determine which assembly is the culprit? The only meaningful difference between the dev environments between the dev environment where this worked and the current one is that the first was XP and this is Vista64. However, a colleague of mine who is using XP is getting the same error. **Third-party assemblies being used:** * ComponentFactory.Krypton.Toolkit * ComponentFactory.Krypton.Navigator * VistaDB.NET20 All of these are referenced in other projects in the solution which build with no problems, so it doesn't look like these are the problem. So far I have tried deleting the suo file, Rebuild All, unloading and reloading projects from the solution, removing and readding referenced assemblies. Nothing has worked.
I just got it to build by doing the following: There had been a licenses file in the Properties of the project in question. After deleting the file (it was no longer needed) the project was able to build successfully. So it looks like that was the culprit.
## What the error means *"Strong Name : Indicates that the reference has been signed with a key pair."* If your current project's assembly is signed, then all your reference assemblies **must** also be signed. **Failure to do so will result in this error.** --- ## How to check Solution Explorer > References > [Click on the reference in question] > Properties [![Strong Name = TRUE](https://i.stack.imgur.com/30ZCG.png)](https://i.stack.imgur.com/30ZCG.png) If `Strong Name` is `true` means *signed*, else the *reference* is not signed and is causing the error. --- ## How to fix ***Method 1*** : Unsign your current project's assembly. Project Properties > Signing > Sign the assembly (checkbox) [![enter image description here](https://i.stack.imgur.com/jH7bO.png)](https://i.stack.imgur.com/jH7bO.png) ***Method 2*** : Sign the assembly of the reference project. (**Only possible if you're building it yourself**) [![Located in Project properties](https://i.stack.imgur.com/UsJIU.png)](https://i.stack.imgur.com/UsJIU.png)
Error: A strongly-named assembly is required
[ "", "c#", ".net", "" ]
I have a block of code that works and I wanted to ask what exactly is happening here? ``` Class<?> normalFormClass = null; ``` ---added--- The wildcard "`<?>`" is the part that is confusing for me. Why would this be used rather than not using it (generics)?
That means it can be a Class of any type. ? is a wildcard denoting the set of all types, or 'any'. So you can later do ``` Integer normalForm = new Integer(); normalFormClass = normalForm.getClass(); ``` or ``` String normalForm = new String(); normalFormClass = normalForm.getClass(); ``` If you are not aware of generics on Java, read <http://java.sun.com/developer/technicalArticles/J2SE/generics/> As for the why, I think it might be to strictly express that you *are* using generics everywhere and your code is not compatible with older Java versions, or maybe to shut up some trigger happy IDEs. And yes, ``` Class foo ``` and ``` Class<?> foo ``` are equivalent.
Also, the generic version ``` Class<?> normalClass = null; ``` is pretty much equivalent to the raw type version, ``` Class normalClass = null; ``` the main difference is that the latter will be compatible with versions of Java that do not support generics, like Java 1.4.
Java Class Type
[ "", "java", "generics", "" ]
Is there any way to reboot the JVM? As in don't actually exit, but close and reload all classes, and run main from the top?
Your best bet is probably to run the java interpreter within a loop, and just exit. For example: ``` #!/bin/sh while true do java MainClass done ``` If you want the ability to reboot or shutdown entirely, you could test the exit status: ``` #!/bin/sh STATUS=0 while [ $STATUS -eq 0 ] do java MainClass STATUS=$? done ``` Within the java program, you can use System.exit(0) to indicate that you want to "reboot," and System.exit(1) to indicate that you want to stop and stay stopped.
IBM's JVM has a feature called "resettable" which allows you to effectively do what you are asking. <http://publib.boulder.ibm.com/infocenter/cicsts/v3r1/index.jsp?topic=/com.ibm.cics.ts31.doc/dfhpj/topics/dfhpje9.htm> Other than the IBM JVM, I don't think it is possible.
Any way to "reboot" the JVM?
[ "", "java", "jvm", "" ]
I am building a WPF application. Inside that application I am using the XmlReader class to parse several local XML files. The code I have written **works perfectly** during debugging, but fails once I publish the application and install it. I have the XML documents as CONTENT in build action, and I have them set to COPY ALWAYS.I can confirm that the XML documents are being deployed in my build and are in tact in the application folder once installed. What further confuses me is that I am using the same XmlReader code to parse RSS feeds from external websites in this application without problem. It only fails on the local XML documents. Does anyone know why my XmlReader would fail to parse local XML documents once the application is published? Here is a small snippet of my XmlReader code for referance: ``` XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreComments = true; settings.IgnoreProcessingInstructions = true; settings.IgnoreWhitespace = true; try { settingsReader = XmlReader.Create("Resources/data/TriviaQuestions.xml", settings); nodeNum = 0; while (settingsReader.Read()) { switch (settingsReader.NodeType) { case XmlNodeType.Element: if (settingsReader.HasAttributes) { for (int i = 0; i < settingsReader.AttributeCount; i++) { settingsReader.MoveToAttribute(i); _feeds[nodeNum] = settingsReader.Value.ToString(); } settingsReader.MoveToContent(); // Moves the reader back to the element node. } break; case XmlNodeType.Text: _questions[nodeNum] = settingsReader.Value; nodeNum++; break; } } settingsReader.Close(); } catch { } ``` Here is my XML ``` <?xml version="1.0" encoding="utf-8" ?> <Questions> <Question feed="http://entertainment.msn.com/rss/topboxoffice/">What movie has the top box office sales in the US right now?</Question> <Question feed="http://entertainment.msn.com/rss/topdvdrentals/">What is the top DVD rental in the US this week?</Question> <Question feed="http://entertainment.msn.com/rss/topalbums/">Which of the following albums is currently topping the charts?</Question> </Questions> ```
By your publish description I assume you are using clickonce to install the application. Clickonce has different default behavior for xml files - it assumes they are data files and places them in a different install location from your other files. Please double check that your xml files really are being installed where you think they are. In the publish settings you can change the setting for each xml file from data file to include. Your other files will already be set to include. Note that the publish settings are independent of the build settings for the file.
Can you describe "but fails once I publish the application and install it" ? It would be helpful if you could describe what doesn't work, what the error is and provide exception information. --- Unrelated to your question, I cringe in horror every time I see empty catch blocks in production code!!
Parsing a local XML Document in WPF (works in debug, fails once published)
[ "", "c#", "wpf", "xml", "" ]
I'm working on a program that searches entire drives for a given file. At the moment, I calculate an MD5 hash for the known file and then scan all files recursively, looking for a match. The only problem is that MD5 is painfully slow on large files. Is there a faster alternative that I can use while retaining a very small probablity of false positives? All code is in C#. Thank you. **Update** I've read that even MD5 can be pretty quick and that disk I/O should be the limiting factor. That leads me to believe that my code might not be optimal. Are there any problems with this approach? ``` MD5 md5 = MD5.Create(); StringBuilder sb = new StringBuilder(); try { using (FileStream fs = File.Open(fileName, FileMode.Open, FileAccess.Read)) { foreach (byte b in md5.ComputeHash(fs)) sb.Append(b.ToString("X2")); } return sb.ToString(); } catch (Exception) { return ""; } ```
I hope you're checking for an MD5 match only if the file size already matches. Another optimization is to do a quick checksum of the first 1K (or some other arbitrary, but reasonably small number) and make sure those match before working the whole file. Of course, all this assumes that you're just looking for a match/nomatch decision for a particular file.
Regardless of cryptographic requirements, the possibility of a hash collision exists, so no hashing function can be used to *guarantee* that two files are identical. I wrote similar code a while back which I got to run pretty fast by indexing all the files first, and discarding any with a different size. A fast hash comparison (on part of each file) was then performed on the remaining entries (comparing bytes for this step was proved to be less useful - many file types have common headers which have identical bytes at the start of the file). Any files that were left after this stage were then checked using MD5, and finally a byte comparison of the whole file if the MD5 matched, just to ensure that the contents were the same.
Faster MD5 alternative?
[ "", "c#", "md5", "hash", "" ]
The JUnit framework contains 2 `Assert` classes (in different packages, obviously) and the methods on each appear to be very similar. Can anybody explain why this is? The classes I'm referring to are: [`junit.framework.Assert`](http://junit.org/junit/javadoc/4.5/junit/framework/Assert.html) and [`org.junit.Assert`](http://junit.org/junit/javadoc/4.5/org/junit/Assert.html).
The old method (of JUnit 3) was to mark the test-classes by extending `junit.framework.TestCase`. That inherited `junit.framework.Assert` itself and your test class gained the ability to call the assert methods this way. Since version 4 of JUnit, the framework uses `Annotations` for marking tests. So you no longer need to extend `TestCase`. But that means, the assert methods aren't available. But you can make a static import of the new `Assert` class. That's why all the assert methods in the new class are static methods. So you can import it this way: ``` import static org.junit.Assert.*; ``` After this static import, you can use this methods without prefix. At the redesign they also moved to the new package `org.junit` that follows better the normal conventions for package naming.
JUnit 3.X: `junit.framework.Assert` JUnit 4.X: `org.junit.Assert` Prefer the newest one, especially when running JDK5 and higher with annotation support.
differences between 2 JUnit Assert classes
[ "", "java", "unit-testing", "junit", "junit4", "assert", "" ]
I am starting again with c++ and was thinking about the scope of variables. If I have a variable inside a function and then I return that variable will the variable not be "dead" when it's returned because the scope it was in has ended? I have tried this with a function returning a string and it did work. Can anyone explain this? Or at least point me to some place that can explain this to me please. Thanks
> When the function terminates, the > following steps happen: > > * The function’s return value is > copied into the placeholder that was > put on the stack for this purpose. > * Everything after the stack frame > pointer is popped off. This destroys > all local variables and arguments. > * The return value is popped off the > stack and is assigned as the value > of the function. If the value of the > function isn’t assigned to anything, > no assignment takes place, and the > value is lost. > * The address of the next instruction > to execute is popped off the stack, > and the CPU resumes execution at > that instruction. [The stack and the heap](http://www.learncpp.com/cpp-tutorial/79-the-stack-and-the-heap/)
It really depends on what kind of variable you are returning. If you return a primitive then it is returned by copy, not by reference so the value is copied to the top of the stack (or, more often placed into a register) where the calling function can get it. If you allocate an object or memory on the heap and return a pointer then it doesn't die because it's on the heap, not the stack. If you allocate something on the stack, however, and return it, that would be a bad thing. For instance, either of these would be very bad: ``` int *myBadAddingFunction(int a, int b) { int result; result = a + b; return &result; // this is very bad and the result is undefined } char *myOtherBadFunction() { char myString[256]; strcpy(myString, "This is my string!"); return myString; // also allocated on the stack, also bad } ```
Scope and return values in C++
[ "", "c++", "return-value", "scope", "" ]
I have an application which I have made a 256 x 256 Windows Vista icon for. I was wondering how I would be able to use a 256x256 PNG file in the ico file used as the application icon and show it in a picture box on a form. I am using VB.NET, but answers in C# are fine. I'm thinking I may have to use reflection. I am not sure if this is even possible in Windows XP and may need Windows Vista APIs
Today, I made a very nice function for **extracting the 256x256 Bitmaps from Vista icons**. Like you, Nathan W, I use it to display the large icon as a Bitmap in "About" box. For example, this code gets Vista icon as PNG image, and displays it in a 256x256 PictureBox: ``` picboxAppLogo.Image = ExtractVistaIcon(myIcon); ``` This function takes Icon object as a parameter. So, you can use it with any icons - **from resources**, from files, from streams, and so on. (Read below about extracting EXE icon). It runs on **any OS**, because it does **not** use any Win32 API, it is **100% managed code** :-) ``` // Based on: http://www.codeproject.com/KB/cs/IconExtractor.aspx // And a hint from: http://www.codeproject.com/KB/cs/IconLib.aspx Bitmap ExtractVistaIcon(Icon icoIcon) { Bitmap bmpPngExtracted = null; try { byte[] srcBuf = null; using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) { icoIcon.Save(stream); srcBuf = stream.ToArray(); } const int SizeICONDIR = 6; const int SizeICONDIRENTRY = 16; int iCount = BitConverter.ToInt16(srcBuf, 4); for (int iIndex=0; iIndex<iCount; iIndex++) { int iWidth = srcBuf[SizeICONDIR + SizeICONDIRENTRY * iIndex]; int iHeight = srcBuf[SizeICONDIR + SizeICONDIRENTRY * iIndex + 1]; int iBitCount = BitConverter.ToInt16(srcBuf, SizeICONDIR + SizeICONDIRENTRY * iIndex + 6); if (iWidth == 0 && iHeight == 0 && iBitCount == 32) { int iImageSize = BitConverter.ToInt32(srcBuf, SizeICONDIR + SizeICONDIRENTRY * iIndex + 8); int iImageOffset = BitConverter.ToInt32(srcBuf, SizeICONDIR + SizeICONDIRENTRY * iIndex + 12); System.IO.MemoryStream destStream = new System.IO.MemoryStream(); System.IO.BinaryWriter writer = new System.IO.BinaryWriter(destStream); writer.Write(srcBuf, iImageOffset, iImageSize); destStream.Seek(0, System.IO.SeekOrigin.Begin); bmpPngExtracted = new Bitmap(destStream); // This is PNG! :) break; } } } catch { return null; } return bmpPngExtracted; } ``` **IMPORTANT!** If you want to load this icon directly from EXE file, then you **CAN'T** use *Icon.ExtractAssociatedIcon(Application.ExecutablePath)* as a parameter, because .NET function ExtractAssociatedIcon() is so stupid, it extracts ONLY 32x32 icon! Instead, you better use the whole **IconExtractor** class, created by Tsuda Kageyu (<http://www.codeproject.com/KB/cs/IconExtractor.aspx>). You can slightly simplify this class, to make it smaller. Use **IconExtractor** this way: ``` // Getting FILL icon set from EXE, and extracting 256x256 version for logo... using (TKageyu.Utils.IconExtractor IconEx = new TKageyu.Utils.IconExtractor(Application.ExecutablePath)) { Icon icoAppIcon = IconEx.GetIcon(0); // Because standard System.Drawing.Icon.ExtractAssociatedIcon() returns ONLY 32x32. picboxAppLogo.Image = ExtractVistaIcon(icoAppIcon); } ``` Note: I'm still using my ExtractVistaIcon() function here, because I don't like how **IconExtractor** handles this job - first, it extracts all icon formats by using IconExtractor.SplitIcon(icoAppIcon), and then you have to know the exact 256x256 icon index to get the desired vista-icon. So, using my ExtractVistaIcon() here is much faster and simplier way :)
Found info [here](http://www.geekpedia.com/tutorial219_Extracting-Icons-from-Files.html). To get the large Vista icon, you need to use Shell32's SHGetFileInfo method. I've copied the relevant text below, of course you'll want to replace the filename variable with "Assembly.GetExecutingAssembly().Location". ``` using System.Runtime.InteropServices; ``` A bunch of constants we will use in the call to SHGetFileInfo() to specify the size of the icon we wish to retrieve: ``` // Constants that we need in the function call private const int SHGFI_ICON = 0x100; private const int SHGFI_SMALLICON = 0x1; private const int SHGFI_LARGEICON = 0x0; ``` The SHFILEINFO structure is very important as it will be our handle to various file information, among which is the graphic icon. ``` // This structure will contain information about the file public struct SHFILEINFO { // Handle to the icon representing the file public IntPtr hIcon; // Index of the icon within the image list public int iIcon; // Various attributes of the file public uint dwAttributes; // Path to the file [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string szDisplayName; // File type [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] public string szTypeName; }; ``` The final preparation for the unmanaged code is to define the signature of SHGetFileInfo, which is located inside the popular Shell32.dll: ``` // The signature of SHGetFileInfo (located in Shell32.dll) [DllImport("Shell32.dll")] public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, int cbFileInfo, uint uFlags); ``` Now that we have everything prepared, it's time to make the call to the function and display the icon that we retrieved. The object that will be retrieved is an Icon type (System.Drawing.Icon) but we want to display it in a PictureBox so we'll convert the Icon to a Bitmap using the ToBitmap() method. But first of all there are 3 controls you need to add to the form, a Button btnExtract that has "Extract Icon" for its Text property, picIconSmall which is a PictureBox and a picIconLarge which is also a PictureBox. That's because we will get two icons sizes. Now double click btnExtract in Visual Studio's Design view and you'll get to its Click event. Inside it is the rest of the code: ``` private void btnExtract_Click(object sender, EventArgs e) { // Will store a handle to the small icon IntPtr hImgSmall; // Will store a handle to the large icon IntPtr hImgLarge; SHFILEINFO shinfo = new SHFILEINFO(); // Open the file that we wish to extract the icon from if(openFile.ShowDialog() == DialogResult.OK) { // Store the file name string FileName = openFile.FileName; // Sore the icon in this myIcon object System.Drawing.Icon myIcon; // Get a handle to the small icon hImgSmall = SHGetFileInfo(FileName, 0, ref shinfo, Marshal.SizeOf(shinfo), SHGFI_ICON | SHGFI_SMALLICON); // Get the small icon from the handle myIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon); // Display the small icon picIconSmall.Image = myIcon.ToBitmap(); // Get a handle to the large icon hImgLarge = SHGetFileInfo(FileName, 0, ref shinfo, Marshal.SizeOf(shinfo), SHGFI_ICON | SHGFI_LARGEICON); // Get the large icon from the handle myIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon); // Display the large icon picIconLarge.Image = myIcon.ToBitmap(); } } ``` UPDATE: found even more info [here](http://support.microsoft.com/kb/319350).
Using a 256 x 256 Windows Vista icon in an application
[ "", "c#", "vb.net", "png", "icons", "" ]
I need to generate random numbers within a specified interval, [max;min]. Also, the random numbers should be uniformly distributed over the interval, not located to a particular point. Currenly I am generating as: ``` for(int i=0; i<6; i++) { DWORD random = rand()%(max-min+1) + min; } ``` From my tests, random numbers are generated around one point only. ``` Example min = 3604607; max = 7654607; ``` Random numbers generated: ``` 3631594 3609293 3630000 3628441 3636376 3621404 ``` From answers below: OK, RAND\_MAX is 32767. I am on C++ Windows platform. Is there any other method to generate random numbers with a uniform distribution?
## Why `rand` is a bad idea Most of the answers you got here make use of the `rand` function and the modulus operator. That method [may not generate numbers uniformly](https://learn.microsoft.com/en-us/events/goingnative-2013/rand-considered-harmful) (it depends on the range and the value of `RAND_MAX`), and is therefore discouraged. ## C++11 and generation over a range With C++11 multiple other options have risen. One of which fits your requirements, for generating a random number in a range, pretty nicely: [`std::uniform_int_distribution`](https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution). Here's an example: ``` #include <iostream> #include <random> int main() { const int range_from = 0; const int range_to = 1000; std::random_device rand_dev; std::mt19937 generator(rand_dev()); std::uniform_int_distribution<int> distr(range_from, range_to); std::cout << distr(generator) << '\n'; } ``` [Try it online on Godbolt](https://godbolt.org/z/xq77YGjqc) And [here](https://coliru.stacked-crooked.com/a/c5b94870fdcd13f2)'s the running example. Template function may help some: ``` template<typename T> T random(T range_from, T range_to) { std::random_device rand_dev; std::mt19937 generator(rand_dev()); std::uniform_int_distribution<T> distr(range_from, range_to); return distr(generator); } ``` ### Other random generators The [`<random>` header](https://en.cppreference.com/w/cpp/numeric/random) offers innumerable other random number generators with different kind of distributions including Bernoulli, Poisson and normal. ### How can I shuffle a container? The standard provides [`std::shuffle`](https://en.cppreference.com/w/cpp/algorithm/random_shuffle), which can be used as follows: ``` #include <iostream> #include <random> #include <vector> int main() { std::vector<int> vec = {4, 8, 15, 16, 23, 42}; std::random_device random_dev; std::mt19937 generator(random_dev()); std::shuffle(vec.begin(), vec.end(), generator); std::for_each(vec.begin(), vec.end(), [](auto i){std::cout << i << '\n';}); } ``` [Try it online on Godbolt](https://godbolt.org/z/rxrrrche5) The algorithm will reorder the elements randomly, with a linear complexity. ## Boost.Random Another alternative, in case you don't have access to a C++11+ compiler, is to use [Boost.Random](https://www.boost.org/doc/libs/1_55_0/doc/html/boost_random.html). Its interface is very similar to the C++11 one.
**Warning: Do not use `rand()` for statistics, simulation, cryptography or anything serious.** It's good enough to make numbers *look* random for a typical human in a hurry, no more. See [Jefffrey's reply](https://stackoverflow.com/a/20136256/4513656) for better options, or [this answer](https://stackoverflow.com/a/2572373/59087) for crypto-secure random numbers. --- Generally, the high bits show a better distribution than the low bits, so the recommended way to generate random numbers of a range for simple purposes is: ``` ((double) rand() / (RAND_MAX+1)) * (max-min+1) + min ``` **Note**: make sure RAND\_MAX+1 does not overflow (thanks Demi)! The division generates a random number in the interval [0, 1); "stretch" this to the required range. Only when max-min+1 gets close to RAND\_MAX you need a "BigRand()" function like posted by Mark Ransom. This also avoids some slicing problems due to the modulo, which can worsen your numbers even more. --- The built-in random number generator isn't guaranteed to have a the quality required for statistical simulations. It is OK for numbers to "look random" to a human, but for a serious application, you should take something better - or at least check its properties (uniform distribution is usually good, but values tend to correlate, and the sequence is deterministic). Knuth has an excellent (if hard-to-read) treatise on random number generators, and I recently found [LFSR](http://en.wikipedia.org/wiki/Linear_feedback_shift_register) to be excellent and darn simple to implement, given its properties are OK for you.
Generate random numbers uniformly over an entire range
[ "", "c++", "random", "" ]
Once a programmer decides to implement `IXmlSerializable`, what are the rules and best practices for implementing it? I've heard that `GetSchema()` should return `null` and `ReadXml` should move to the next element before returning. Is this true? And what about `WriteXml` - should it write a root element for the object or is it assumed that the root is already written? How should child objects be treated and written? Here's a sample of what I have now. I'll update it as I get good responses. ``` public class MyCalendar : IXmlSerializable { private string _name; private bool _enabled; private Color _color; private List<MyEvent> _events = new List<MyEvent>(); public XmlSchema GetSchema() { return null; } public void ReadXml(XmlReader reader) { if (reader.MoveToContent() == XmlNodeType.Element && reader.LocalName == "MyCalendar") { _name = reader["Name"]; _enabled = Boolean.Parse(reader["Enabled"]); _color = Color.FromArgb(Int32.Parse(reader["Color"])); if (reader.ReadToDescendant("MyEvent")) { while (reader.MoveToContent() == XmlNodeType.Element && reader.LocalName == "MyEvent") { MyEvent evt = new MyEvent(); evt.ReadXml(reader); _events.Add(evt); } } reader.Read(); } } public void WriteXml(XmlWriter writer) { writer.WriteAttributeString("Name", _name); writer.WriteAttributeString("Enabled", _enabled.ToString()); writer.WriteAttributeString("Color", _color.ToArgb().ToString()); foreach (MyEvent evt in _events) { writer.WriteStartElement("MyEvent"); evt.WriteXml(writer); writer.WriteEndElement(); } } } public class MyEvent : IXmlSerializable { private string _title; private DateTime _start; private DateTime _stop; public XmlSchema GetSchema() { return null; } public void ReadXml(XmlReader reader) { if (reader.MoveToContent() == XmlNodeType.Element && reader.LocalName == "MyEvent") { _title = reader["Title"]; _start = DateTime.FromBinary(Int64.Parse(reader["Start"])); _stop = DateTime.FromBinary(Int64.Parse(reader["Stop"])); reader.Read(); } } public void WriteXml(XmlWriter writer) { writer.WriteAttributeString("Title", _title); writer.WriteAttributeString("Start", _start.ToBinary().ToString()); writer.WriteAttributeString("Stop", _stop.ToBinary().ToString()); } } ``` Corresponding Sample XML ``` <MyCalendar Name="Master Plan" Enabled="True" Color="-14069085"> <MyEvent Title="Write Code" Start="-8589241828854775808" Stop="-8589241756854775808" /> <MyEvent Title="???" Start="-8589241828854775808" Stop="-8589241756854775808" /> <MyEvent Title="Profit!" Start="-8589247048854775808" Stop="-8589246976854775808" /> </MyCalendar> ```
Yes, GetSchema() [should return null](http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.getschema.aspx). > IXmlSerializable.GetSchema Method This > method is reserved and should not be > used. When implementing the > IXmlSerializable interface, you should > return a null reference (Nothing in > Visual Basic) from this method, and instead, > if specifying a custom schema is > required, apply the > XmlSchemaProviderAttribute to the > class. For both read and write, the object element has already been written, so you don't need to add an outer element in write. For example, you can just start reading/writing attributes in the two. For [write](http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.writexml.aspx): > The WriteXml implementation you > provide should write out the XML > representation of the object. The > framework writes a wrapper element and > positions the XML writer after its > start. Your implementation may write > its contents, including child > elements. The framework then closes > the wrapper element. And for [read](http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.readxml.aspx): > The ReadXml method must reconstitute > your object using the information that > was written by the WriteXml method. > > When this method is called, the reader > is positioned at the start of the > element that wraps the information for > your type. That is, just before the > start tag that indicates the beginning > of a serialized object. When this > method returns, it must have read the > entire element from beginning to end, > including all of its contents. Unlike > the WriteXml method, the framework > does not handle the wrapper element > automatically. Your implementation > must do so. Failing to observe these > positioning rules may cause code to > generate unexpected runtime exceptions > or corrupt data. I'll agree that is a little unclear, but it boils down to "it is your job to `Read()` the end-element tag of the wrapper".
I wrote one article on the subject with samples as the MSDN documentation is by now quite unclear and the examples you can find on the web are most of the time incorrectly implemented. Pitfalls are handling of locales and empty elements beside what Marc Gravell already mentioned. <http://www.codeproject.com/KB/XML/ImplementIXmlSerializable.aspx>
Proper way to implement IXmlSerializable?
[ "", "c#", "xml", "xml-serialization", "" ]
Writing a JSP page, what exactly does the `<c:out>` do? I've noticed that the following both has the same result: ``` <p>The person's name is <c:out value="${person.name}" /></p> <p>The person's name is ${person.name}</p> ```
`c:out` escapes HTML characters so that you can avoid cross-site scripting. if `person.name = <script>alert("Yo")</script>` the script will be executed in the second case, but not when using `c:out`
As said Will Wagner, in old version of jsp you should always use `c:out` to output dynamic text. Moreover, using this syntax: ``` <c:out value="${person.name}">No name</c:out> ``` you can display the text "No name" when name is null.
JSP : JSTL's <c:out> tag
[ "", "java", "jsp", "jstl", "tags", "" ]
I work on a medium sized development team that maintains a 8+ years old web application written in Java 1.4. For new development I always try to convince people to adhere to newer standards and best practices, That goes from simple things like using new naming standards like HtmlImplementation over HTMLImplementation, to things like why it's better to code against an interface versus coding against concrete classes, favor immutability or object composition a over class inheritance. I have found this rather [generic link in Stackoverflow](https://stackoverflow.com/questions/82672/best-practices-online-resources), which is not Java-oriented nor complete. I always try to explain the rationale behind my arguments, and always suggest people buy the latest edition of Effective Java, but it's not every developer that takes my word without questioning (which is a good thing). When that happens, they often ask me for pointers where they could read further about that specific good practice and sometimes I fail to quickly find pointers about that. Do you have any links to online material I could gather in a "collection" of Best Practices reference, in a way I can always look that up and suggest the "further reading" to my teammates?
Check out these links : * [Best Practice Software Engineering](http://best-practice-software-engineering.ifs.tuwien.ac.at/) (more in depth) * [Software Engineeting Best Practices](http://prof.tfh-berlin.de/edlich/lecture-results/swt-best-practices/) (lists briefly out some practices and tools by name) One book (that concentrates mostly on tools worth considering): * [Java Power Tools (O'Reilly)](http://oreilly.com/catalog/9780596527938/)
I really don't think there's anything in the same league as Effective Java. The cost of buying a book is much smaller than the developer time spent reading it (or other material anyway) - so I would strongly recommend going for EJ rather than trying to find anything similar. There may be an online version of Effective Java - I'm not sure. I know this probably isn't the advice you wanted to get, but I'm that passionate about the quality of Effective Java :)
Can you help me gather a Java Best Practices online material collection?
[ "", "java", "reference", "" ]
This works, but is it the proper way to do it??? I have a custom server control that has an [input] box on it. I want it to kinda mimic the ASP.NET TextBox, but not completely. When the textbox is rendered i have a javascript that allows users to select values that are then placed in that input box. I have a public text property on the control. In the get/set i get/set the viewstate for the control - that part is easy, but when the control is populated via the javascript, the Text get is not actually called, what is the proper way to set this exposed property using JavaScript (or even if the user just types in the box) ? Edit: In the OnInit i ensure the state is maintained by reaching into the form values. ``` protected override void OnInit(EventArgs e) { base.OnInit(e); if (HttpContext.Current.Request.Form["MyInputBoxValue"] != "") { ViewState["MyInputBoxValue"] = HttpContext.Current.Request.Form["MyInputBoxValue"]; } } ``` Then to get the value actually back in place in the HtmlTextWrite, i do this: ``` protected override void RenderContents(HtmlTextWriter output) { // There is an input control here and i set its value property // like this using the Text internal defined. output.Write("<input value=" + Text + ">..... } ``` thanks
I find using IStateManager works the best. For example: ``` partial class MyControl : System.Web.UI.UserControl, IStateManager { [Serializable()] protected struct MyControlState { public bool someValue; public string name; } protected MyControlState state; public bool someValue { get { return state.someValue; } set { state.someValue = value; } } public bool IsTrackingViewState { get { return true; } } protected override void LoadViewState(object state) { if ((state != null) && state is MyControlState) { this.state = state; } } protected override object SaveViewState() { return state; } protected override void TrackViewState() { base.TrackViewState(); } } ``` getDefaultState() would just load some sane defaults into a new state struct. state gets tracked in the viewstate of the page, and ASP will take care of bring it in/out for you. (above code ported from VB and not checked, hopefully I didn't make any errors but it should get the point across anyways)
If you need to maintain state on postback, you must provide your own methods of recording what the user has done with your control on the client side and either update the server control later on the server with the changes, or redo the changes on the client side when the page refreshes.
What is the proper way to maintain state in a custom server control?
[ "", "c#", "asp.net", "custom-server-controls", "servercontrols", "" ]
Having played around a little with both Tkinter and wxPython, I like Tkinter much better in terms of how clean my source code looks. However, it doesn't seem to have as many features; in particular it doesn't have tabs (as in, the tabs at the top of a Firefox window). A little Googling on the subject offers a few suggestions. There's [a cookbook entry](http://code.activestate.com/recipes/188537/) with a class allowing you to use tabs, but it's very primitive. There's also [Python megawidgets](http://pmw.sourceforge.net/) on SourceForge, although this seems very old and gave me errors during installation. Does anyone have experience making tabbed GUIs in Tkinter? What did you use? Or is it simply the case that anyone who needs more powerful windowing components has to use wxPython?
On recent Python (> 2.7) versions, you can use the [`ttk`](https://docs.python.org/2/library/ttk.html) module, which provides access to the *Tk themed widget* set, which has been introduced in `Tk 8.5`. Here's how you import `ttk` in Python 2: ``` import ttk help(ttk.Notebook) ``` In Python 3, the [`ttk`](https://docs.python.org/3.4/library/tkinter.ttk.html?highlight=ttk#module-tkinter.ttk) module comes with the standard distributions as a submodule of [`tkinter`](https://docs.python.org/3.4/library/tkinter.html). Here's a simple working example based on an example from the [`TkDocs`](http://www.tkdocs.com/tutorial/complex.html) website: ``` from tkinter import ttk import tkinter as tk from tkinter.scrolledtext import ScrolledText def demo(): root = tk.Tk() root.title("ttk.Notebook") nb = ttk.Notebook(root) # adding Frames as pages for the ttk.Notebook # first page, which would get widgets gridded into it page1 = ttk.Frame(nb) # second page page2 = ttk.Frame(nb) text = ScrolledText(page2) text.pack(expand=1, fill="both") nb.add(page1, text='One') nb.add(page2, text='Two') nb.pack(expand=1, fill="both") root.mainloop() if __name__ == "__main__": demo() ``` Another alternative is to use the `NoteBook` widget from the [`tkinter.tix`](https://docs.python.org/3/library/tkinter.tix.html) library. To use `tkinter.tix`, you must have the `Tix` widgets installed, usually alongside your installation of the `Tk` widgets. To test your installation, try the following: ``` from tkinter import tix root = tix.Tk() root.tk.eval('package require Tix') ``` For more info, check out this [webpage](https://docs.python.org/3/library/tkinter.tix.html) on the PSF website. Note that `tix` is pretty old and not well-supported, so your best choice might be to go for `ttk.Notebook`.
If anyone still looking, I have got this working as Tab in tkinter. Play around with the code to make it function the way you want (for example, you can add button to add a new tab): ``` from tkinter import * class Tabs(Frame): """Tabs for testgen output""" def __init__(self, parent): super(Tabs, self).__init__() self.parent = parent self.columnconfigure(10, weight=1) self.rowconfigure(3, weight=1) self.curtab = None self.tabs = {} self.addTab() self.pack(fill=BOTH, expand=1, padx=5, pady=5) def addTab(self): tabslen = len(self.tabs) if tabslen < 10: tab = {} btn = Button(self, text="Tab "+str(tabslen), command=lambda: self.raiseTab(tabslen)) btn.grid(row=0, column=tabslen, sticky=W+E) textbox = Text(self.parent) textbox.grid(row=1, column=0, columnspan=10, rowspan=2, sticky=W+E+N+S, in_=self) # Y axis scroll bar scrollby = Scrollbar(self, command=textbox.yview) scrollby.grid(row=7, column=5, rowspan=2, columnspan=1, sticky=N+S+E) textbox['yscrollcommand'] = scrollby.set tab['id']=tabslen tab['btn']=btn tab['txtbx']=textbox self.tabs[tabslen] = tab self.raiseTab(tabslen) def raiseTab(self, tabid): print(tabid) print("curtab"+str(self.curtab)) if self.curtab!= None and self.curtab != tabid and len(self.tabs)>1: self.tabs[tabid]['txtbx'].lift(self) self.tabs[self.curtab]['txtbx'].lower(self) self.curtab = tabid def main(): root = Tk() root.geometry("600x450+300+300") t = Tabs(root) t.addTab() root.mainloop() if __name__ == '__main__': main() ```
Notebook widget in Tkinter
[ "", "python", "wxpython", "tabs", "tkinter", "" ]
let me tell you a bit about where this question came from. I have been playing around with the SDK of Serious Sam 2, a first person shooter which runs on the Serious Engine 2. This engine introduces something called MetaData. MetaData is used in the engine to serialize classes and be able to edit them in the editor environment (Serious Editor 2). So for example, instead of: ``` class CSomeGameItem : CEntity { public: int iHealthToGive; } ``` Which will not show up in the editor, you would do: ``` meta ver(1) class CSomeGameItem : CEntity _("Some game item") { public: meta int iHealthToGive; _("Amount of health to give") } ``` Now when making a level, you can insert a "Some game item" entity into your level, and edit the one property it has. Now, I know Croteam (the developers of said game and engine) are using an extra compiler (Mdc, meta data compiler) to inject extra information about classes and their variables into the dll files, to make this metadata system possible. Does anyone have any clue as to how they did this? Oh, btw, the meta, ver() and \_() keywords are #define'd to nothing in their code, so the "normal" compiler ignores them.
This looks somewhat similar to Qt's moc (meta object compiler). In Qt's case, it generates extra C++ source files which are then compiled and linked together with the original source files. A possible implementation in your example would be for the generated files to implement a set of functions which can be called to get the extra information, to set the properties, and so on.
To get a definitive answer, study the [PE File Format](http://en.wikipedia.org/wiki/Portable_Executable). This is the low level file format for binaries on Win32. ie. DLLs, EXEs, COM, etc. There are many books that discribe PE File layout and features. And many tools that allow you to explore it. The short answer is that at the lowest level, PE File format allows you to embed data into the binary that can be extracted at run times. DLLs and Exe will often embed their icons and localization text. These are often called resources. A good place to start is the [Resource File](http://msdn.microsoft.com/en-us/library/7zxb70x7.aspx) section on MSDN. Also research "Resource Scripts (\*.rc files)" and the "Resource Compiler (rc.exe)".
Saving extra data in a dll, how did they do it?
[ "", "c++", "serialization", "" ]
So I've got a program that needs to be multilingual. The only difference between what I'm needing and what I've found on the web is that all the computers my program will run on are set to the localization of EN. We have spanish speaking employees that will use the program just like the english speaking employees. So I won't be able to set something up based on the localization of the computer, it'll all have to be done in code. I was thinking of trying to create an XML file (really just a dataset) for every form that I have and having each data table be a selectable language. In each table, it would have the information (control name, property, and text) to set the labels/checkboxes/etc that it needs to. I'll have to create a new form control so that I can have a generic function to go through and rename all of these controls if possible. ``` <DataSet> <English> <ControlName>labelHello</ControlName> <ControlProperty>Text</ControlProperty> <Text>Hello</Text> </English> <English> <ControlName>labelBye</ControlName> <ControlProperty>Text</ControlProperty> <Text>Bye</Text> </English> <Spanish> <ControlName>labelHello</ControlName> <ControlProperty>Text</ControlProperty> <Text>Hola</Text> </Spanish> </DataSet> ``` Also I didn't know much about the strings in the resources file for each form. Could I do it from there and use .Net functions to achieve this? So I'm up for lots of suggestions because I really don't want to go back into the program I just wrote and put this in, I hate going back and adding more functionality once I've already spent so much time with this sucker... Thanks
You can set the culture you want in code, e.g.: ``` Thread.CurrentThread.CurrentUICulture = new CultureInfo("es-ES"); ``` See [this MSDN article](http://msdn.microsoft.com/en-us/library/b28bx3bh(VS.80).aspx) for more info.
It is a pain, but its not hard. Within VS2008's WinForm designer, select the form, view its properties and set Localizable=True (if you view the partial class/code behind file you will see a new line that looks something like ``` resources.ApplyResources(this, "$this") ``` Then, for each locale you want to support, select Language, and localize any changes needed over the Default local. I believe Windows allows the user to specify a different locale for a specified application. I last tried this with Windows 2000.
Multilingual Winforms in .Net - opinions and suggestions
[ "", "c#", "winforms", "multilingual", "" ]
How can I generate valid XML in C#?
It depends on the scenario. `XmlSerializer` is certainly one way and has the advantage of mapping directly to an object model. In .NET 3.5, `XDocument`, etc. are also very friendly. If the size is very large, then `XmlWriter` is your friend. For an `XDocument` example: ``` Console.WriteLine( new XElement("Foo", new XAttribute("Bar", "some & value"), new XElement("Nested", "data"))); ``` Or the same with `XmlDocument`: ``` XmlDocument doc = new XmlDocument(); XmlElement el = (XmlElement)doc.AppendChild(doc.CreateElement("Foo")); el.SetAttribute("Bar", "some & value"); el.AppendChild(doc.CreateElement("Nested")).InnerText = "data"; Console.WriteLine(doc.OuterXml); ``` If you are writing a **large** stream of data, then any of the DOM approaches (such as `XmlDocument`/`XDocument`, etc.) will quickly take a lot of memory. So if you are writing a 100 MB XML file from [CSV](http://en.wikipedia.org/wiki/Comma-separated_values), you might consider `XmlWriter`; this is more primitive (a write-once firehose), but very efficient (imagine a big loop here): ``` XmlWriter writer = XmlWriter.Create(Console.Out); writer.WriteStartElement("Foo"); writer.WriteAttributeString("Bar", "Some & value"); writer.WriteElementString("Nested", "data"); writer.WriteEndElement(); ``` Finally, via `XmlSerializer`: ``` [Serializable] public class Foo { [XmlAttribute] public string Bar { get; set; } public string Nested { get; set; } } ... Foo foo = new Foo { Bar = "some & value", Nested = "data" }; new XmlSerializer(typeof(Foo)).Serialize(Console.Out, foo); ``` This is a nice model for mapping to classes, etc.; however, it might be overkill if you are doing something simple (or if the desired XML doesn't really have a direct correlation to the object model). Another issue with `XmlSerializer` is that it doesn't like to serialize immutable types : everything must have a public getter *and* setter (unless you do it all yourself by implementing `IXmlSerializable`, in which case you haven't gained much by using `XmlSerializer`).
The best thing hands down that I have tried is [LINQ to XSD](http://linqtoxsd.codeplex.com/) (which is unknown to most developers). You give it an XSD Schema and it generates a perfectly mapped complete strongly-typed object model (based on LINQ to XML) for you in the background, which is really easy to work with - and it updates and validates your object model and XML in real-time. While it's still "Preview", I have not encountered any bugs with it. If you have an XSD Schema that looks like this: ``` <xs:element name="RootElement"> <xs:complexType> <xs:sequence> <xs:element name="Element1" type="xs:string" /> <xs:element name="Element2" type="xs:string" /> </xs:sequence> <xs:attribute name="Attribute1" type="xs:integer" use="optional" /> <xs:attribute name="Attribute2" type="xs:boolean" use="required" /> </xs:complexType> </xs:element> ``` Then you can simply build XML like this: ``` RootElement rootElement = new RootElement; rootElement.Element1 = "Element1"; rootElement.Element2 = "Element2"; rootElement.Attribute1 = 5; rootElement.Attribute2 = true; ``` Or simply load an XML from file like this: ``` RootElement rootElement = RootElement.Load(filePath); ``` Or save it like this: ``` rootElement.Save(string); rootElement.Save(textWriter); rootElement.Save(xmlWriter); ``` `rootElement.Untyped` also yields the element in form of a XElement (from LINQ to XML).
How can I build XML in C#?
[ "", "c#", "xml", "" ]
I got a message saying `script xyz.py returned exit code 0`. What does this mean? What do the exit codes in Python mean? How many are there? Which ones are important?
You're looking for calls to `sys.exit()` (`exit()` calls `sys.exit()`) in the script. The argument to that method is returned to the environment as the exit code. It's fairly likely that the script is never calling the *exit* method, and that 0 is the default exit code.
From the documentation for [`sys.exit`](https://docs.python.org/2/library/sys.html#sys.exit): > The optional argument arg can be an > integer giving the exit status > (defaulting to zero), or another type > of object. If it is an integer, zero > is considered “successful termination” > and any nonzero value is considered > “abnormal termination” by shells and > the like. Most systems require it to > be in the range 0-127, and produce > undefined results otherwise. Some > systems have a convention for > assigning specific meanings to > specific exit codes, but these are > generally underdeveloped; Unix > programs generally use 2 for command > line syntax errors and 1 for all other > kind of errors. One example where exit codes are used are in shell scripts. In Bash you can check the special variable `$?` for the last exit status: ``` me@mini:~$ python -c ""; echo $? 0 me@mini:~$ python -c "import sys; sys.exit(0)"; echo $? 0 me@mini:~$ python -c "import sys; sys.exit(43)"; echo $? 43 ``` Personally I try to use the exit codes I find in `/usr/include/asm-generic/errno.h` (on a Linux system), but I don't know if this is the right thing to do.
Exit codes in Python
[ "", "python", "exit-code", "" ]
I have a form that contains a bunch of checkboxes. Before submitting the form, I'd like to grab the values of the checkboxes and stick them into a text field, then submit that. So I might have: Red Orange X Yellow Blue X Green And I'd like my textfield to end up with the content "Yellow, Green" . This doesn't seem too complicated, but I am totally out of my league. I already use jQuery for a few other things so I have the framework ready, if that makes it easer. Thanks for any advice --
Just use this code: ``` $(function(){ $('#YourFormID').bind('submit',function(){ var serializedCheckboxes = ''; $("input[type=checkbox]").each(function() { if($(this).attr("checked")) { serializedCheckboxes += (serializedCheckboxes != '' ? ', ' : '') + $(this).attr("value"); } }); $("input[name=allchecks]").attr("value", serializedCheckboxes); }); }); ``` It starts when page is loaded and bind to "submit" event of your form correct function
First hack at it (without testing): ``` var serializedCheckboxes = ''; $("input type='checkbox'").each(function() { if($(this).attr("checked")) { serializedCheckboxes += $(this).attr("value") + ','; } }); $("input name='allchecks').attr("value", serializedCheckboxes); ```
How to use jQuery to grab the values of checkboxes and spit them into a different form field
[ "", "javascript", "jquery", "forms", "" ]
I am trying to use the Event Log to write some debug information and I can't make it works. It complains about not being able to find the Event Source. Do I have to install something on the OS?
Here a code that I modified from one of our application. This might help you to start with the creation. ``` System.Diagnostics.EventLog eventLog1 = new System.Diagnostics.EventLog(); string eventLogName = "StackOverFlowEventName"; string eventLogSource = "StackOverFlowWebsite"; //This code HERE will create the Event for you if (!System.Diagnostics.EventLog.SourceExists(eventLogSource)) { System.Diagnostics.EventLog.CreateEventSource(eventLogSource, eventLogName); } eventLog1.Source = eventLogSource; eventLog1.Log = eventLogName; eventLog1.WriteEntry("This is a test"); ```
What code are you using currently in your project? I'm currently using this line to write to the event log. ``` System.Diagnostics.EventLog.WriteEntry(assemblyName, "Error stuff", System.Diagnostics.EventLogEntryType.Error); ``` Watch out though, this will throw an exception if the log file is full
Event log code error not being able to find the Event Source?
[ "", "c#", "events", "c#-2.0", "" ]
I'm trying to get the following SQL statement to work: ``` UPDATE myschema.tableA update_tableA SET field_id = ( SELECT src.field_id FROM myschema.srcTable src INNER JOIN myschema.tableB tableB ON update_tableA.id = tableB.id AND SDO_ANYINTERACT( tableB.shape, src.shape ) = 'TRUE' ); ``` When I run this statement, I get the following error: ``` ORA-00904: "UPDATE_TABLEA"."ID": invalid identifier ``` Can I not use a variable scoped outside of the nested select within the nested select? Any thoughts? P.S. The identifier is indeed valid in the database table. The problem appears to be scope, but I want to make sure that is indeed an issue.
I don't believe you can JOIN on a column (i.e. use it in the ON clause) that's not in one of the tables being joined. Additional predicates need to be in a WHERE clause. Try this: ``` UPDATE myschema.tableA update_tableA SET field_id = ( SELECT src.field_id FROM myschema.srcTable src INNER JOIN myschema.tableB tableB ON SDO_ANYINTERACT( tableB.shape, src.shape ) = 'TRUE' WHERE update_tableA.id = tableB.id ); ```
Looking at the SQL above, here is what I am thinking 1) myschema.tableA doesn't have ID column (it could be field\_id) 2) The SELECT doesn't seem to provide a join condition `SELECT src.field_id FROM myschema.srcTable src INNER JOIN myschema.tableB tableB ON` Where is the condition to JOIN src with tableB?
In SQL, can I use a variable scoped outside a nested select within the nested select itself?
[ "", "sql", "oracle", "ora-00904", "" ]
I have an `ICollection<T>` called `foos` in my class which I want to expose as read-only (see [this question](https://stackoverflow.com/questions/284090/how-to-get-a-readonlycollectiont-of-the-keys-in-a-dictionaryt-s)). I see that the interface defines a property `.IsReadOnly`, which seems appropriate... My question is this: how do I make it obvious to the consumer of the class that `foos` is read-only? I don't want to rely on them remembering to query `.IsReadOnly` before trying a not-implemented method such as `.Add()`. Ideally, I would like to expose `foos` as a `ReadOnlyCollection<T>`, but it does not implement `IList<T>`. Should I expose `foo` via a method called, for example, `GetReadOnlyFooCollection` rather than via a property? If so, would this not confuse someone who then expects a `ReadOnlyCollection<T>`? This is C# 2.0, so extension methods like `ToList()` are not available...
I seem to have settled on returning IEnumerable **with the objects cloned.** ``` public IEnumerable<Foose> GetFooseList() { foreach(var foos in Collection) { yield return foos.Clone(); } } ``` * requires a Clone method on Foos. This allows no changes in the collection. Remember that ReadonlyCollection is "leaky" since the objects inside it can be changed as mentioned in a link in another post.
You can make "foos" a ReadOnlyCollection like this: ``` ReadOnlyCollection<T> readOnlyCollection = foos.ToList<T>().AsReadOnly(); ``` Then you can expose it as a property of your class. EDIT: ``` class FooContainer { private ICollection<Foo> foos; public ReadOnlyCollection<Foo> ReadOnlyFoos { get { return foos.ToList<Foo>().AsReadOnly();} } } ``` Note: You should remember that once you get the ReadOnlyFoos collection is no longer "synchronized" with your foos ICollection. See the [thread you referenced](https://stackoverflow.com/questions/284090/how-to-get-a-readonlycollectiont-of-the-keys-in-a-dictionaryt-s).
Best practice: How to expose a read-only ICollection
[ "", "c#", "collections", "c#-2.0", "" ]
I wrote a small PHP application that I'd like to distribute. I'm looking for best practices so that it can be installed on most webhosts with minimal hassle. Briefly: It's simple tool that lets people download files once they login with a password. So my questions are: 1) How should I handle configuration values? I'm not using a database, so a configuration file seems appropriate. I know that other php apps (e.g. Wordpress) use defines, but they are global and there is potential that the names will conflict. (Global variables also have the same problem, obviously.) I looked at the "ini" file mechanism built into PHP. It only allows comments at the top - so you can't annotate each setting easily - and you can't validate syntax with "php -f". Other options? 2) How to handle templating? The application needs to pump out a form. Possibly with an error message. (e.g. "Sorry, wrong password.") I've have a class variable with the HTML form, but also allow an external template file to be used instead (specified in the config). I do some trivial search and replace - e.g. %SCRIPT% to the name of the script, %STATUS% to hold the error message. This feels a bit like reinventing the wheel, but including a templating system like Smarty is overkill. (Plus they may already have a templating system.) Other options? 3) i18n - There are only 3 message strings, and gettext doesn't seem to be universally installed. Is it such a bad idea just to make these three strings parameters in the config file? 4) How to best integrate with other frameworks? My app is a single class. So, I thought I could just include a php script that showed how the class was called. It would be a starting point for people who had to integrate it into another framework, but also be fine as-is for those not interested in customizing. Reasonable? 5) GET/POST parameters - Is it bad form for a class to be looking at $\_GET and $\_POST? Should all values be passed into my class during construction? Thanks.
# Configuration You can use a php file like this: ``` <?php return array( 'option1' =&gt; 'foobar', 'option2' =&gt; 123, //and so on... ); ?> ``` And in the main class just use: ``` $config = (array) include 'path/to/config/file'; ``` And if you plan to mostly distribute your class as a component in other applications, then simply put config array/object as a parameter in your class' constructor and leave the details to the user. # Templating For such simple application the method your described should be enough. Remember that one can always extend your class and overload your outputting method with his own. # I10N As mentioned before, for 3 variables anything more than storing them as config is just overkill. # Integration Comment each public method (or even better also protected and private ones) with explanations what do they do and what parameters are needed. If you combine that with an example, it should be enough for most users. # GET vs POST Your class uses passwords and you even think of sending them via GET? ;) Think of browser history, referer headers etc - your users' passwords would be visible there.
1. Can config be local to class instances? Or could you create a little class that you could create an instance of to query for config values? Also prepending any global vars with you application's name should go some way to stop clashes. 2. If your templating is really simple, just write a short templater. It'll be easier than trying to fend off problems people get with any 3rd party templater. It might also simplify licensing issues. If you start worrying about what they already have, you'll never release anything. There are too many combinations. 3. For 3 strings? Yeah do those the same way you're handling config. 4. Good comments throughout with an intro explaining how you use the class. 5. I don't think so. If it bothers you, you could use default arguments to use given arguments first, then search for GET/POST values if none are provided (though that might be a security risk) There are other things to take into consideration. Lots of people are on shared hosts and as a result, don't have control over their php.ini or their php version. You need to make sure you're only using features that are as commonplace as possible. One example is that shorttags aren't enabled on some hosts (you have to use `<?php ... ?>` and `<?php echo "..."?>` instead of `<? ... ?>` or `<?= "..." ?>`) which can be a royal PITA.
Distributing a small PHP application
[ "", "php", "distribution", "" ]
I'm learning c# , and I reached the LinkedList<T> type and I still need to know more, like when should I use it, how do I create one, how do I to use it. I just want information. If any one knows a good article about this subject, or if you can show me some examples with explanation, such as how to create, how to add and remove, and how to deal with nodes and elements. Thanks in advance. I really enjoy asking questions around here with all the pros answering and helping. [EDIT] Changed reference to LinkedList<T> instead of "array linkedlist." I think this was what was meant based on the context.
You can find more information on [LinkedList<T>](http://msdn.microsoft.com/en-us/library/he2s3bh7.aspx) at MSDN, including an example of how to create and use one. [Wikipedia](http://en.wikipedia.org/wiki/Linked_list) has a reasonable article on linked lists, including their history, usage, and some implementation details.
Linked is a collection to store sequences of values of the same type, which is a frequent task, e.g. to represent a queue of cars waiting at a stoplight. There are many different collection types like linked list, array, map, set etc. Which one to use when depends on their properties, e.g.: * do you need some type of ordering? * is the container associative, storing key-value pairs like a dictionary? * can you store the same element twice? * performance measures - how fast is e.g. inserting, removing, finding an element? This is usually given in Big-O notation, telling you how the time required scales with the number of elements in the collection. * Memory footprint and layout. This also can affect performance, due to good/bad locality.
I want to know more about LinkedList<T>
[ "", "c#", "linked-list", "" ]
I am opening a XML file using .NET XmlReader and saving the file in another filename and it seems that the DOCTYPE declaration changes between the two files. While the newly saved file is still valid XML, I was wondering why it insisted on changing original tags. ``` Dim oXmlSettings As Xml.XmlReaderSettings = New Xml.XmlReaderSettings() oXmlSettings.XmlResolver = Nothing oXmlSettings.CheckCharacters = False oXmlSettings.ProhibitDtd = False oXmlSettings.IgnoreWhitespace = True Dim oXmlDoc As XmlReader = XmlReader.Create(pathToOriginalXml, oXmlSettings) Dim oDoc As XmlDocument = New XmlDocument() oDoc.Load(oXmlDoc) oDoc.Save(pathToNewXml) ``` The following (in the original document): ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd"> ``` becomes (notice the [ ] characters at the end): ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd"[]> ```
Probably the library parses the DOCTYPE element into an internal structure and then converts the structure back to text. It doesn't store the original string form.
There is a bug in System.Xml when you set XmlDocument.XmlResolver = null. The workaround is to create a custom XmlTextWriter: ``` private class NullSubsetXmlTextWriter : XmlTextWriter { public NullSubsetXmlTextWriter(String inputFileName, Encoding encoding) : base(inputFileName, encoding) { } public override void WriteDocType(string name, string pubid, string sysid, string subset) { if (subset == String.Empty) { subset = null; } base.WriteDocType(name, pubid, sysid, subset); } } ``` In your code, create a new NullSubsetXmlTextWriter(pathToNewXml, Encoding.UTF8) and pass that object to the oDoc.Save() method. Here is the [Microsoft support case](http://www.vistax64.com/net-general/215921-xmldocument-save-null-xmlresolver-modifies-doctype-tag.html) where you can read about the workaround (it describes the workaround but doesn't provide the code).
.NET XmlDocument : Why DOCTYPE changes after Save?
[ "", "c#", "xml", "vb.net", "doctype", "xmldocument", "" ]
I have an auditing trigger that automatically places the time something was updated and the user that updated in fields in all my tables. I have another set of triggers that write event information from updates to an events table. The issue is when someone updates something, the event information is fired twice because of the first triggers. How to I suppress the duplicate entries?
Look into TRIGGER\_NESTLEVEL function. It returns the current level of trigger nesting. You can check that to prevent the duplicates.
I guess you have 2 choices: 1. Either combine both sets of triggers into one. 2. Or, there is a per database setting that allows recursive firing of triggers to be disabled.
SQL Server Triggers Firing Each other Question
[ "", "sql", "triggers", "" ]
When Xdebug is installed/enabled, standard PHP errors (when set to display in the browser) are replaced with more informative messages that include stack traces for each. Also, I've noticed that it also seems to improve output in other areas such as the var\_dump() function, formatting/color-coding the output to make it more readable. Are there any 3rd party packages that offer similar functionality? I tend to prefer using Zend Debugger for debugging and would love to find something like this that doesn't depend on Xdebug. Certainly I could write my own error handler, a custom var\_dump() function, etc., but I would love to find something that transparently integrates itself into PHP the way Xdebug's functionality does. **Edit:** I should emphasize that I'm not looking for a debugger, but for the "extras" that Xdebug offers.
As for your debugging you'll only find access through PHP extensions, regardless of what IDE you are using. Xdebug is the most popular due to it's extra features, beyond that of what you've even described. Xdebug will do profiling (tracing) into the valgrind format that you can use programs like Kcachegrind and wincachegrind to evaluate. Your only other real alternative to the debugging facilities Xdebug provides is Zend Debugger which is a part of the Zend Platform (again available as an extension). As for the replacements, you won't find any other extensions that do the var\_dump and error reporting replacements. And especially won't find (beyond Zend Debugger) a debugging protocol, and definitely won't find any other extension that does profiling.
dBug offers quite a nice replacement for print\_r: <http://dbug.ospinto.com/>
Other packages with Xdebug-like features (informative PHP errors, formatted var_dump()s, etc.)?
[ "", "php", "xdebug", "" ]
Is there a way to accept input from more than one mouse separately? I'm interested in making a multi-user application and I thought it would be great if I could have 2 or more users holding wireless mice each interacting with the app individually with a separate mouse arrow. Is this something I should try to farm out to some other application/driver/os\_magic? or is there a library I can use to accomplish this? Language isn't a *HUGE* deal, but C, C++, and Python are preferrable. Thanks :) edit: Found this multi-pointer toolkit for linux (it's actually a multi-pointer x server): <http://wearables.unisa.edu.au/mpx/>
You could try the [Microsoft Windows MultiPoint Software Development Kit 1.1](http://www.microsoft.com/downloads/details.aspx?familyid=F851122A-4925-4788-BC39-409644CE0F9B&displaylang=en) or the new [Microsoft Windows MultiPoint Software Development Kit 1.5](http://www.microsoft.com/downloads/details.aspx?FamilyID=0eb18c26-5e02-4c90-ae46-06662818f817&displaylang=en) and the main [Microsoft Multipoint](http://www.microsoft.com/multipoint/mouse-sdk/) site
Yes. I know of at least one program that does this, [KidPad](http://www.cs.umd.edu/hcil/kiddesign/introduction.shtml). I think it's written in Java and was developed by [Juan Pablo Hourcade](http://www.cs.uiowa.edu/~hourcade/), now at the University of Iowa. You'd have to ask him how it was implemented.
Multiple mouse pointers?
[ "", "python", "user-interface", "mouse", "multi-user", "" ]
I normally use the following idiom to check if a String can be converted to an integer. ``` public boolean isInteger( String input ) { try { Integer.parseInt( input ); return true; } catch( Exception e ) { return false; } } ``` Is it just me, or does this seem a bit hackish? What's a better way? --- See my answer (with benchmarks, based on the [earlier answer](https://stackoverflow.com/a/237321/1288) by [CodingWithSpike](https://stackoverflow.com/users/28278/codingwithspike)) to see why I've reversed my position and accepted [Jonas Klemming's answer](https://stackoverflow.com/a/237204/1288) to this problem. I think this original code will be used by most people because it's quicker to implement, and more maintainable, but it's orders of magnitude slower when non-integer data is provided.
If you are not concerned with potential overflow problems this function will perform about 20-30 times faster than using `Integer.parseInt()`. ``` public static boolean isInteger(String str) { if (str == null) { return false; } int length = str.length(); if (length == 0) { return false; } int i = 0; if (str.charAt(0) == '-') { if (length == 1) { return false; } i = 1; } for (; i < length; i++) { char c = str.charAt(i); if (c < '0' || c > '9') { return false; } } return true; } ```
You have it, but you should only catch `NumberFormatException`.
What's the best way to check if a String represents an integer in Java?
[ "", "java", "string", "int", "" ]
I am just getting started with IoC containers so apologies if this is a stupid question. I have code like the following in an app ``` internal static class StaticDataHandlerFactory { public static IStaticDataHandler CreateHandler(StaticDataUpdate staticDataUpdate) { if (staticDataUpdate.Item is StaticDataUpdateOffice) { return new OfficeUpdateHandler(); } if (staticDataUpdate.Item is StaticDataUpdateEmployee) { return new EmployeeUpdateHandler(); } if (staticDataUpdate.Item == null) { throw new NotImplementedException( string.Format("No static data provided")); } else { throw new NotImplementedException( string.Format("Unimplemented static data type of {0}", staticDataUpdate.Item.GetType().FullName)); } } } ``` It is basically a simple factory that returns the correct strategy for handling the input data. Would an IoC container allow me to eliminate code like this? That is to say : would it allow me to dynamically choose a concrete implementation to load based on the type of an input parameter? Or am I way off course here?
Actually, although it is possible to replace some of the code with an inversion of control system, it's not obvious to me it's a good idea. Dependency injection tends to be best for configuration of systems, not dynamic creation of objects. To put it a different way, the container itself is a huge global variable and as such should appear in much of your code. As an aside, the code appears to be violating the [Law of Demeter](http://googletesting.blogspot.com/2008/07/breaking-law-of-demeter-is-like-looking.html). It appears that the parameter should be of type "StaticDataUpdateItem" rather than "StaticDataUpdate". With that observed, there's a pretty strong argument for rewriting this code as a method call on the StaticDataUpdateItem. I used IoC quite heavily, but dynamic object creation is still better dealt with using an abstract factory pattern. In short, if you don't like the idea of adding a method to the item itself to generate the handle, the code's probably best left the way it is.
You're not far off course at all; the way I understand it, you're pretty close. The way I would most commonly structure this sort of thing is to turn your Factory class into your IoC container, simply by allowing the UpdateHandlers that are returned to be specified using Dependency Injection. So instead of having the logic in your code that specifies that StaticDataUpdateOffice means to return OfficeUpdateHandler, you can turn your code into simply saying that StaticDataUpdateOffice returns whatever a (newly specified) `m_officeUpdateHandler` variable contains; so long as your Framework makes sure that you set the value of `m_officeUpdateHandler` before you invoke your factory, you're good to go. And you can change the value of the `m_officeUpdateHandler` to anything you want at runtime as your needs change. This Dependency Injection allows you to have control over the Inversion of Control process; you can have a simple factory that returns your handlers, and you can abstract the logic that controls what handler gets returned to a different location, as appropriate. Note: my experience with this sort of thing is pretty strongly driven by my (very positive) experience with Spring, and so that may color my interpretation of your question (and the answer).
Does an IoC container replace the use of Factories
[ "", "c#", "inversion-of-control", "factory", "" ]
I have an input which at some points happens to have the focus. If the user click in the "background" of the page, the input loses its focus. I was trying to simulate the click on the background with the following code, but this doesn't work (you will notice that the input still has the focus). Any suggestion on how to write code that simulates a click on the "background" of the page? ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/yahoo/yahoo-min.js" ></script> <script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/event/event-min.js" ></script> <script type="text/javascript"> YAHOO.util.Event.onDOMReady(function() { document.getElementById("input").focus(); document.getElementById("main").focus(); }); </script> </head> <body> <div id="main"> <form action="/"> <p> <input type="text" id="input"/> </p> </form> </div> </body> </html> ```
I would imagine using `blur()` would do the trick: ``` <script type="text/javascript"> YAHOO.util.Event.onDOMReady(function() { document.getElementById("input").focus(); document.getElementById("input").blur(); }); </script> ```
Try using the `blur` event. If you're using jQuery there is a method you can call on the DOM object to raise this event. The `blur()` method should also work without jQuery. <http://docs.jquery.com/Events/blur>
How to simulate a click to make the current input lose its focus with JavaScript
[ "", "javascript", "focus", "yui", "" ]
I'm using Emacs with [C# Mode](http://mfgames.com/linux/csharp-mode) and when I turn on the speedbar, no files show up by default. I can choose "show all files" on the speedbar mode, but then every .cs file shows up with a '[?]' next to the name. How do I properly configure speedbar so it shows up with .cs files by default? How do I get the '[+]' next to each file so I can navigate inside the file?
I think ECB with CEDET is simply too bloated. I use speedbar alone with emacs and I use the original parser for C/C++. Just add this line to your .emacs and you'll be ok: ``` (speedbar-add-supported-extension ".cs") (add-to-list 'speedbar-fetch-etags-parse-list '("\\.cs" . speedbar-parse-c-or-c++tag)) ``` This handles C# perfectly without a problem. Hope this helps.
I used speedbar earlier and got really irritated. I now use [ECB](http://ecb.sourceforge.net/). [ECB](http://ecb.sourceforge.net/) uses its own buffer for the tree and can optionally show the outline of the CS file in a separate buffer. They all fit in the same frame while Speedbar has its own frame. I have some [custom stuff](http://lisp.pastebin.com/m2a590520) setup for ECB. You can see it here.
How do I configure Emacs speedbar for C# mode?
[ "", "c#", "emacs", "" ]
Has anyone here ever used C++'s "placement new"? If so, what for? It looks to me like it would only be useful on memory-mapped hardware.
## Placement new allows you to construct an object in memory that's already allocated. You may want to do this for optimization when you need to construct multiple instances of an object, and it is faster not to re-allocate memory each time you need a new instance. Instead, it might be more efficient to perform a single allocation for a chunk of memory that can hold multiple objects, even though you don't want to use all of it at once. DevX gives a [good example](http://www.devx.com/tips/Tip/12582): > Standard C++ also supports placement > new operator, which constructs an > object on a pre-allocated buffer. This > is useful when building a memory pool, > a garbage collector or simply when > performance and exception safety are > paramount (there's no danger of > allocation failure since the memory > has already been allocated, and > constructing an object on a > pre-allocated buffer takes less time): ``` char *buf = new char[sizeof(string)]; // pre-allocated buffer string *p = new (buf) string("hi"); // placement new string *q = new string("hi"); // ordinary heap allocation ``` You may also want to be sure there can be no allocation failure at a certain part of critical code (for instance, in code executed by a pacemaker). In that case you would want to allocate memory earlier, then use placement new within the critical section. ## Deallocation in placement new You should not deallocate every object that is using the memory buffer. Instead you should delete[] only the original buffer. You would have to then call the destructors of your classes manually. For a good suggestion on this, please see Stroustrup's FAQ on: [Is there a "placement delete"](http://www.stroustrup.com/bs_faq2.html#placement-delete)?
We use it with custom memory pools. Just a sketch: ``` class Pool { public: Pool() { /* implementation details irrelevant */ }; virtual ~Pool() { /* ditto */ }; virtual void *allocate(size_t); virtual void deallocate(void *); static Pool *Pool::misc_pool() { return misc_pool_p; /* global MiscPool for general use */ } }; class ClusterPool : public Pool { /* ... */ }; class FastPool : public Pool { /* ... */ }; class MapPool : public Pool { /* ... */ }; class MiscPool : public Pool { /* ... */ }; // elsewhere... void *pnew_new(size_t size) { return Pool::misc_pool()->allocate(size); } void *pnew_new(size_t size, Pool *pool_p) { if (!pool_p) { return Pool::misc_pool()->allocate(size); } else { return pool_p->allocate(size); } } void pnew_delete(void *p) { Pool *hp = Pool::find_pool(p); // note: if p == 0, then Pool::find_pool(p) will return 0. if (hp) { hp->deallocate(p); } } // elsewhere... class Obj { public: // misc ctors, dtors, etc. // just a sampling of new/del operators void *operator new(size_t s) { return pnew_new(s); } void *operator new(size_t s, Pool *hp) { return pnew_new(s, hp); } void operator delete(void *dp) { pnew_delete(dp); } void operator delete(void *dp, Pool*) { pnew_delete(dp); } void *operator new[](size_t s) { return pnew_new(s); } void *operator new[](size_t s, Pool* hp) { return pnew_new(s, hp); } void operator delete[](void *dp) { pnew_delete(dp); } void operator delete[](void *dp, Pool*) { pnew_delete(dp); } }; // elsewhere... ClusterPool *cp = new ClusterPool(arg1, arg2, ...); Obj *new_obj = new (cp) Obj(arg_a, arg_b, ...); ``` Now you can cluster objects together in a single memory arena, select an allocator which is very fast but does no deallocation, use memory mapping, and any other semantic you wish to impose by choosing the pool and passing it as an argument to an object's placement new operator.
What uses are there for "placement new"?
[ "", "c++", "memory-management", "new-operator", "placement-new", "" ]
If I have a function that returns an object, but this return value is never used by the caller, will the compiler optimize away the copy? (Possibly an always/sometimes/never answer.) Elementary example: ``` ReturnValue MyClass::FunctionThatAltersMembersAndNeverFails() { //Do stuff to members of MyClass that never fails return successfulResultObject; } void MyClass::DoWork() { // Do some stuff FunctionThatAltersMembersAndNeverFails(); // Do more stuff } ``` In this case, will the `ReturnValue` object get copied at all? Does it even get constructed? (I know it probably depends on the compiler, but let's narrow this discussion down to the popular modern ones.) EDIT: Let's simplify this a bit, since there doesn't seem to be a consensus in the general case. What if `ReturnValue` is an int, and we return 0 instead of `successfulResultObject`?
If the ReturnValue class has a non-trivial copy constructor, the compiler must not eliminate the call to the copy constructor - it is mandated by the language that it is invoked. If the copy constructor is inline, the compiler might be able to inline the call, which in turn might cause a elimination of much of its code (also depending on whether FunctionThatAltersMembersAndNeverFails is inline).
They most likely will if the optimization level causes them to inline the code. If not, they would have to generate two different translations of the same code to make it work, which could open up a lot of edge case problems.
Will the c++ compiler optimize away unused return value?
[ "", "c++", "visual-c++", "gcc", "compiler-construction", "return", "" ]
I would like to add a backcolor for specific line depending of a Property of the object binded. The solution I have (and it works) is to use the Event `DataBindingComplete` but I do not think it's the best solution. Here is the event: ``` private void myGrid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) { for (int i = 0; i < this.myGrid.Rows.Count; i++) { if((this.myGrid.Rows[i].DataBoundItem as MyObject).Special) { this.myGrid.Rows[i].DefaultCellStyle.BackColor = Color.FromArgb(240, 128, 128); } } } ``` Any other option that would be better?
You can also attach an event handler to RowPostPaint: ``` dataGridView1.RowPostPaint += OnRowPostPaint; void OnRowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) { MyObject value = (MyObject) dataGridView1.Rows[e.RowIndex].DataBoundItem; DataGridViewCellStyle style = dataGridView1.Rows[e.RowIndex].DefaultCellStyle; // Do whatever you want with style and value .... } ```
I would suggest a few things: * look at modifying your rows at \_OnRowDatabound * Do not set color in your code!!! This would be a big mistake. Use the attributes property and set the cssclass. Wag of the finger to people still doing this. Let me know if you struggle with the implementation and i'll post a snippet.
(DataGridView + Binding)How to color line depending of the object binded?
[ "", "c#", ".net", "winforms", ".net-2.0", "c#-2.0", "" ]
What is the idiomatic Python equivalent of this C/C++ code? ``` void foo() { static int counter = 0; counter++; printf("counter is %d\n", counter); } ``` specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?
A bit reversed, but this should work: ``` def foo(): foo.counter += 1 print "Counter is %d" % foo.counter foo.counter = 0 ``` If you want the counter initialization code at the top instead of the bottom, you can create a decorator: ``` def static_vars(**kwargs): def decorate(func): for k in kwargs: setattr(func, k, kwargs[k]) return func return decorate ``` Then use the code like this: ``` @static_vars(counter=0) def foo(): foo.counter += 1 print "Counter is %d" % foo.counter ``` It'll still require you to use the `foo.` prefix, unfortunately. (Credit: [@ony](https://stackoverflow.com/questions/279561/what-is-the-python-equivalent-of-static-variables-inside-a-function/279586#comment41067162_279586))
You can add attributes to a function, and use it as a static variable. ``` def myfunc(): myfunc.counter += 1 print myfunc.counter # attribute must be initialized myfunc.counter = 0 ``` Alternatively, if you don't want to setup the variable outside the function, you can use `hasattr()` to avoid an `AttributeError` exception: ``` def myfunc(): if not hasattr(myfunc, "counter"): myfunc.counter = 0 # it doesn't exist yet, so initialize it myfunc.counter += 1 ``` Anyway static variables are rather rare, and you should find a better place for this variable, most likely inside a class.
What is the Python equivalent of static variables inside a function?
[ "", "python", "static", "" ]
I'm a big fan of [simpletest](http://www.simpletest.org/) because it's what I know. It has excellent support for mocking and web-testing. But I'm always scared of stagnating so any compelling arguments to switch would be appreciated.
I don't think either is going away anytime soon. Simpletest is maintained by a small, but involved group of people. PHPUnit seems to have a bigger userbase, which may count as an argument for switching. I'm quite happy with Simpletest though.
I haven't used SimpleTest myself, so I can't say much in a way of comparison. Just by observation though, the PHPUnit syntax seems much more verbose. The [PHPUnit Manual](http://www.phpunit.de/pocket_guide/3.3/en/index.html) is a great source of documentation, and covers most areas of the framework. My only complaint about the manual is that some areas lack detail. My main reason for using PHPUnit over SimpleTest is that it has great [Phing](http://phing.info/trac/) integration.
which unit-test framework for PHP: simpletest, phpunit or?
[ "", "php", "unit-testing", "phpunit", "simpletest", "" ]
I am setting-up my DataGridView like this: ``` jobs = new List<DisplayJob>(); uxJobList.AutoGenerateColumns = false; jobListBindingSource.DataSource = jobs; uxJobList.DataSource = jobListBindingSource; int newColumn; newColumn = uxJobList.Columns.Add("Id", "Job No."); uxJobList.Columns[newColumn].DataPropertyName = "Id"; uxJobList.Columns[newColumn].DefaultCellStyle.Format = Global.JobIdFormat; uxJobList.Columns[newColumn].DefaultCellStyle.Font = new Font(uxJobList.DefaultCellStyle.Font, FontStyle.Bold); uxJobList.Columns[newColumn].AutoSizeMode = DataGridViewAutoSizeColumnMode.None; uxJobList.Columns[newColumn].Width = 62; uxJobList.Columns[newColumn].Resizable = DataGridViewTriState.False; uxJobList.Columns[newColumn].SortMode = DataGridViewColumnSortMode.Automatic; : : ``` where the DisplayJob class looks like: ``` public class DisplayJob { public DisplayJob(int id) { Id = id; } public DisplayJob(JobEntity job) { Id = job.Id; Type = job.JobTypeDescription; CreatedAt = job.CreatedAt; StartedAt = job.StartedAt; ExternalStatus = job.ExternalStatus; FriendlyExternalStatus = job.FriendlyExternalStatus; ExternalStatusFriendly = job.ExternalStatusFriendly; CustomerName = job.Customer.Name; CustomerKey = job.Customer.CustomerKey; WorkAddress = job.WorkAddress; CreatedBy = job.CreatedBy; CancelledAt = job.CancelledAt; ClosedAt = job.ClosedAt; ReasonWaiting = job.ReasonWaiting; CancelledBy = job.CancelledBy; CancelledReason = job.CancelledReason; DisplayCreator = Global.GetDisplayName(CreatedBy); ActionRedoNeeded = job.ActionRedoNeeded; if (job.Scheme != null) { SchemeCode = job.Scheme.Code; } } public int Id { get; private set; } public string Type { get; private set; } public DateTime CreatedAt { get; private set; } public DateTime? StartedAt { get; private set; } public string ExternalStatus { get; private set; } public string FriendlyExternalStatus { get; private set; } public string ExternalStatusFriendly { get; private set; } public string CustomerName { get; private set; } public string CustomerKey { get; private set; } public string WorkAddress { get; private set; } public string CreatedBy { get; private set; } public DateTime? CancelledAt { get; private set; } public DateTime? ClosedAt { get; private set; } public string CancelledBy { get; private set; } public string ReasonWaiting { get; private set; } public string DisplayCreator { get; private set; } public string CancelledReason { get; private set; } public string SchemeCode { get; private set; } public bool ActionRedoNeeded { get; private set; } } ``` However the column sorting does not work. What is the best way to get this working?
If you want to support sorting and searching on the collection, all **it takes it to derive a class from your BindingList parameterized type**, and override a few base class methods and properties. The best way is to extend the BindingList and do those following things: ``` protected override bool SupportsSearchingCore { get { return true; } } protected override bool SupportsSortingCore { get { return true; } } ``` You will also need to implement the sort code: ``` ListSortDirection sortDirectionValue; PropertyDescriptor sortPropertyValue; protected override void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction) { sortedList = new ArrayList(); // Check to see if the property type we are sorting by implements // the IComparable interface. Type interfaceType = prop.PropertyType.GetInterface("IComparable"); if (interfaceType != null) { // If so, set the SortPropertyValue and SortDirectionValue. sortPropertyValue = prop; sortDirectionValue = direction; unsortedItems = new ArrayList(this.Count); // Loop through each item, adding it the the sortedItems ArrayList. foreach (Object item in this.Items) { sortedList.Add(prop.GetValue(item)); unsortedItems.Add(item); } // Call Sort on the ArrayList. sortedList.Sort(); T temp; // Check the sort direction and then copy the sorted items // back into the list. if (direction == ListSortDirection.Descending) sortedList.Reverse(); for (int i = 0; i < this.Count; i++) { int position = Find(prop.Name, sortedList[i]); if (position != i) { temp = this[i]; this[i] = this[position]; this[position] = temp; } } isSortedValue = true; // Raise the ListChanged event so bound controls refresh their // values. OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1)); } else // If the property type does not implement IComparable, let the user // know. throw new NotSupportedException("Cannot sort by " + prop.Name + ". This" + prop.PropertyType.ToString() + " does not implement IComparable"); } ``` If you need more information you can always go there and get all explication about [how to extend the binding list](http://msdn.microsoft.com/en-us/library/aa480736.aspx).
Daok's solution is the right one. It's also very often more work than it's worth. The lazy man's way to get the functionality you want is to create and populate a DataTable off of your business objects, and bind the DataGridView to that. There are a lot of use cases that this approach won't handle (like, editing), and it obviously wastes time and space. As I said, it's lazy. But it's easy to write, and the resulting code is a damn sight less mysterious than an implementation of `IBindingList`. Also, you're already writing a lot of the code anyway, or similar code at least: the code you write to define the DataTable frees you from having to write code to create the columns of the DataGridView, since the DataGridView will construct its columns off of the DataTable when you bind it.
DataGridView Column sorting with Business Objects
[ "", "c#", ".net", "datagridview", "" ]
We have an application that generates simulated data for one of our services for testing purposes. Each data item has a unique Guid. However, when we ran a test after some minor code changes to the simulator all of the objects generated by it had the same Guid. There was a single data object created, then a for loop where the properties of the object were modified, including a new unique Guid, and it was sent to the service via remoting (serializable, not marshal-by-ref, if that's what you're thinking), loop and do it again, etc. If we put a small Thread.Sleep( ...) inside of the loop, it generated unique id's. I think that is a red-herring though. I created a test app that just created one guid after another and didn't get a single duplicate. My theory is that the IL was optimized in a way that caused this behavior. But enough about my theories. What do YOU think? I'm open to suggestions and ways to test it. UPDATE: There seems to be a lot of confusion about my question, so let me clarify. I DON'T think that NewGuid() is broken. Clearly it works. Its FINE! There is a bug somewhere though, that causes NewGuid() to either: 1) be called only once in my loop 2) be called everytime in my loop but assigned only once 3) something else I haven't thought of This bug can be in my code (MOST likely) or in optimization somewhere. So to reiterate my question, how should I debug this scenario? (and thank you for the great discussion, this is really helping me clarify the problem in my mind) UPDATE # 2: I'd love to post an example that shows the problem, but that's part of my problem. I can't duplicate it outside of the whole suite of applications (client and servers). Here's a relevant snippet though: ``` OrderTicket ticket = new OrderTicket(... ); for( int i = 0; i < _numOrders; i++ ) { ticket.CacheId = Guid.NewGuid(); Submit( ticket ); // note that this simply makes a remoting call } ```
Does Submit do an async call, or does the ticket object go into another thread at any stage. In the code example you are reusing the same object. What if Submit sends the ticket in a background thread after a short delay (and does not take a copy). When you change the CacheId you are actually updating all the pending submits. This also explains why a Thread.Sleep fixes the problem. Try this: ``` for( int i = 0; i < _numOrders; i++ ) { OrderTicket ticket = new OrderTicket(... ); ticket.CacheId = Guid.NewGuid(); Submit( ticket ); // note that this simply makes a remoting call } ``` If for some reason this is not possible, try this and see if they are still the same: ``` ticket.CacheId = new Guid("00000000-0000-0000-0000-" + string.Format("{0:000000000000}", i)); ```
Thousands of developers use Guids in .NET. If Guid.NewGuid() had any tendency at all to get "stuck" on one value, the problem would have been encountered long ago. The minor code changes are the sure culprit here. The fact that [Thread.Sleep](https://stackoverflow.com/questions/143429/whats-the-least-useful-comment-youve-ever-seen#143556) (which is less a red herring than a fish rotting in the sun) "fixes" your problem suggests that your properties are being set in some weird way that can't take effect until the loop stops blocking (either by ending or by Thread.Sleep). I'd even be willing to bet that the "minor change" was to reset all the properties from a separate thread. If you posted some sample code, that would help.
Duplicate returned by Guid.NewGuid()?
[ "", "c#", "guid", "" ]
I sign up Spring courses tomorrow morning (transferring in to the Computer Science program). Since I'm a transfer student, I get the last pick of leftover classes not already taken. Emphasis on 'last pick' and 'leftover'. It's highly probable that whatever classes I intend on picking tomorrow, I might not even get because other students will be vying for those same classes. Add on top of this, even with scheduling, an extremely sluggish server when it gets hit with a big load. So, when I register next semester (or even register for different classes for Spring if others drop 'em) I'd like to have a script or code ready to go so I could just automate my inputs without filling out web forms and hoping the server parses them correctly. (By inputs, I'm being general -- from automatically filling in form fields to SQL inputs). Obviously, this might not work. But, what I'm looking for is a kind of keylogger for a web browser, which would download all web pages visited, any javascript executed, forms filled out, anything and everything. This way, I could analyze the data later, and at my leisure, to see if I could do this in a better way. Any suggestions on what could do this? (I'm thinking maybe some testing software?). Thanks in advance.
**Selenium** can automate most browser based tasks. <http://selenium.seleniumhq.org/> **The Grinder** comes with a local proxy that can record traffic and is scriptable with Python. <http://grinder.sourceforge.net/>
I would highly suggest you check out your university's *acceptable use policy*, at mine, such a thing would be considered a serious infraction and possibly get you kicked out.
Script for College Class Registration
[ "", "javascript", "" ]
How come the following doesn't work? ``` CREATE FUNCTION Test (@top integer) RETURNS TABLE AS RETURN SELECT TOP @top * FROM SomeTable GO ``` I just want to be able to be able to specify the number of results to be returned. [SQL Server 2000.] Thanks!
For MS SQL 2000, you can use: ``` CREATE FUNCTION Test (@top integer) RETURNS TABLE AS SET ROWCOUNT @top RETURN SELECT * FROM SomeTable ```
Support for this was added to SQL Server 2005, but it's not available in 2000. You'd have to use (shudder) dynamic sql or some other number trick instead.
SQL User-Defined Functions: Fetching TOP n records in a user-defined function
[ "", "sql", "sql-server", "sql-server-2000", "user-defined-functions", "" ]
I'm trying to perform a simple LINQ query on the Columns property of a DataTable: ``` from c in myDataTable.Columns.AsQueryable() select c.ColumnName ``` However, what I get is this: > Could not find an implementation of the query pattern for source type 'System.Linq.IQueryable'. 'Select' not found. Consider explicitly specifying the type of the range variable 'c'. How can I get the DataColumnCollection to play nice with LINQ?
How about: ``` var x = from c in dt.Columns.Cast<DataColumn>() select c.ColumnName; ```
With Linq Method Syntax: ``` var x = myDataTable.Columns.Cast<DataColumn>().Select(c => c.ColumnName); ```
Querying DataColumnCollection with LINQ
[ "", "c#", "linq", "datatable", "asqueryable", "datacolumncollection", "" ]
I have a few questions related: 1) Is possible to make my program change filetype association but only when is running? Do you see anything wrong with this behavior? 2) The other option that I'm seeing is to let users decide to open with my application or restore default association ... something like: "capture all .lala files" or "restore .lala association". How can I do this? What do you think that is the best approach?
Regarding file associations, I've wrote an answer earlier that at least [covers the "How"](https://stackoverflow.com/questions/212906/script-to-associate-an-extension-to-a-program#212921). This should also point you to the right direction how to handle backup and restore. With direct registry access through c#, there will be no need to use .reg files, so you are free to back up the previous value however you like in your app, and also restore it from there. The key question here is: *Should* you change file associations randomly? At least asking the user up-front would obviously be necessary (as you also indicated). Furthermore, Vista users with UAC enabled, or non-privileged users of other Windows versions may not have the required permission to change global file associations. The (un)installation procedure of your program may be the only place where this can succeed. EDIT As [Franci Penov indicated in his answer](https://stackoverflow.com/questions/222561/filetype-association-with-application-c#222799), there *is* a way to change local file associations on a per-user basis, even for non-admins (that's why I spoke of "global associations" in the previous paragraph). He also mentioned mentioned why going there is not overly advisable.
You can implement an "on the fly" file association change by associating a small executable with that file extension that upon start will check if your main application is running and pass the file name to it or if it's not running it'll invoke the "regular" associated application. The main advantage of this approach is that you need to muck with the registry only once. The main drawbacks of this approach are: * you need a helper process * the application that "owns" these file extensions can detect the change and complain to the user, prompting "repair" thus getting you out of the picture. Alternatively, you could change the file association upon your main program start. This will work even for non-admin users. while file associations are stored in `HKEY_CLASSES_ROOT`, there's a small trick - HKCR is actually a map of both `HKEY_LOCAL_MACHINE\SOFTWARE\Classes` and `HKEY_CURRENT_USER\SOFTWARE\Classes`. Thus, you can temporarily register the file extension for the current user in HKCU and "shadow" the original association from HKLM. Of course, I would advise against this approach though, as it takes just one crash in your application to make that association permanent and since very few applications know how to deal with file associations in HKCU, chances are it'll be an unrecoverable situation for the original application.
Filetype association with application (C#)
[ "", "c#", ".net", "registry", "file-type", "" ]
I'm curious as to the best route (more looking towards simplicity, not speed or efficiency) to sort a DropDownList in C#/ASP.NET - I've looked at a few recommendations but they aren't clicking well with me. Edit: Folks, I do not have control over how the data comes into the DropDownList - I cannot modify the SQL.
If you get a DataTable with the data, you can create a DataView off of this and then bind the drop down list to that. Your code would look something like... ``` DataView dvOptions = new DataView(DataTableWithOptions); dvOptions.Sort = "Description"; ddlOptions.DataSource = dvOptions; ddlOptions.DataTextField = "Description"; ddlOptions.DataValueField = "Id"; ddlOptions.DataBind(); ``` Your text field and value field options are mapped to the appropriate columnns in the data table you are receiving.
A C# solution for .NET 3.5 (needs System.Linq and System.Web.UI): ``` public static void ReorderAlphabetized(this DropDownList ddl) { List<ListItem> listCopy = new List<ListItem>(); foreach (ListItem item in ddl.Items) listCopy.Add(item); ddl.Items.Clear(); foreach (ListItem item in listCopy.OrderBy(item => item.Text)) ddl.Items.Add(item); } ``` Call it after you've bound your dropdownlist, e.g. OnPreRender: ``` protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); ddlMyDropDown.ReorderAlphabetized(); } ``` Stick it in your utility library for easy re-use.
Sorting a DropDownList? - C#, ASP.NET
[ "", "c#", "asp.net", "drop-down-menu", "" ]
I have an assembly that may be used by more than one process at a time. If I am using a static class, would the multiple processes all use the same "instance" of that class? Since the processes are separate, would these be running under difference Application Domains, hence have the static "instances" separate? The pudding in the details here is that the assembly is being used by a custom BizTalk adapter that my be set to process the messages in parallel batches. That is what I am calling "multiple processes" above.
Multiple threads would share an instance. For this reason a static class can be convenient for passing state between threads, but you need to be very careful not to introduce race conditions (`Monitor` or `lock` your properties). However, multiple *processes* should be in separate AppDomains and therefore each have their own instance.
Static classes exist once per application domain. In your case, it would depend on whether the adapter is using multiple threads in the same application domain (thus sharing a single instance of the static class) or using multiple processes (thus having separate instances of the static class).
What is the scope of a Static Class?
[ "", "c#", "static", "biztalk", "applicationdomain", "" ]
So here's my current code: ``` List<string> rowGroups = GetFileGroups((int)row.Cells["document_security_type"].Value); bool found = false; System.Security.Principal.WindowsPrincipal p = new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent()); foreach (string group in rowGroups) { if (p.IsInRole(group)) { found = true; break; } } ``` This was done a couple of months ago by someone and I'm having difficulty grasping why its not working. The company has recently just moved from one domain name to another. So I was curious to what domain controller the p.IsInRole("String") function will use. I'm assuming its going to use the default DC by whatever the computer is using. The odd item is that the computers in the office where this is running could be on 2 seperate domains. In the `List<string>` object, i've got both domains possible. so it could contain items such as "domainA\groupA", "domainA\userB", domainB\groupC", and/or "domainB\userD". So my major problem is that the IsInRole function is never returning true. i know it should, i even tested it with domainA\Domain users and still get a false returned. Any ideas? changing the code is possible, but not wanted. i'm not 100% i can even compile it...
Well, to fix the problem I just had to specifically add each user of the group instead of the group name.
I have to point out, are you actually escaping your '\' character correctly inside your strings? As in "domainA\\groupA"?
WindowsPrincipal.IsInRole() not returning the expected result
[ "", "c#", "security", "active-directory", "security-roles", "iprincipal", "" ]
For my application there are several entity classes, User, Customer, Post, and so on I'm about to design the database and I want to store the date when the entities were created and updated. This is where it gets tricky. Sure one option is to add created\_timestamp and update\_timestamp columns for each of the entity tables but that isn't that redudant? Another possibility could be to create a log table that stores this information, and it could be made to contain keep track of updates for **any** entity. Any thoughts? I'm leaning on implementing the latter.
The single-log-table-for-all-tables approach has two main problems that I can think of: 1. The design of the log table will (probably) constrain the design of all the other tables. Most likely the log table would have one column named TableName and then another column named PKValue (which would store the primary key value for the record you're logging). If some of your tables have compound primary keys (i.e. more than one column), then the design of your log table would have to account for this (probably by having columns like PKValue1, PKValue2 etc.). 2. If this is a web application of some sort, then the user identity that would be available from a trigger would be the application's account, instead of the ID of the web app user (which is most likely what you really want to store in your CreatedBy field). This would only help you distinguish between records created by your web app code and records created otherwise. CreatedDate and ModifiedDate columns aren't redundant just because they're defined in each table. I would stick with that approach and put insert and update triggers on each table to populate those columns. If I also needed to record the end-user who made the change, I would skip the triggers and populate the timestamp and user fields from my application code.
I do the latter, with a "log" or "events" table. In my experience, the "updated" timestamp becomes frustrating pretty quick, because a lot of the time you find yourself in a fix where you want not just the very latest update time.
SQL - Table Design - DateCreated and DateUpdated columns
[ "", "sql", "timestamp", "insert-update", "" ]
The [jQuery documentation](http://docs.jquery.com/Events/bind#typedatafn) says the library has built-in support for the following events: blur, focus, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and error. I need to handle cut, copy, and paste events. How best to do that? FWIW, I only need to worry about WebKit (lucky me!). UPDATE: I'm working on a "widget" in a Dashboard-like environment. It uses WebKit, so it only really matters (for my purposes) whether these events are supported there, which it looks like they are.
You can add and remove events of any kind by using the [`.on()`](http://api.jquery.com/on/) and [`off()`](http://api.jquery.com/off) methods Try this, for instance ``` jQuery(document).on('paste', function(e){ alert('pasting!') }); ``` jQuery is actually quite indifferent to whether the event type you assign is supported by the browser, so you can assign arbitrary event types to elements (and general objects) such as: ``` jQuery('p').on('foobar2000', function(e){ alert(e.type); }); ``` In case of custom event types, you must [`.trigger()`](http://api.jquery.com/trigger) them "manually" in your code, like this: ``` jQuery('p').trigger('foobar2000'); ``` Neat eh? Furthermore, to work with proprietary/custom DOM events in a cross-browser compatible way, you may need to use/write an "jQuery event plugin" ... example of which may be seen in ~~[jquery.event.wheel.js](http://plugins.jquery.com/files/jquery.event.wheel.js.txt)~~ Brandon Aaron's [Mousewheel plugin](https://github.com/brandonaaron/jquery-mousewheel)
Various clipboard events are available in Javascript, though support is spotty. QuicksMode.org has a [compatibility grid](http://www.quirksmode.org/dom/events/cutcopypaste.html) and [test page](http://www.quirksmode.org/dom/events/tests/cutcopypaste.html). The events are not exposed through jQuery, so you'll either have to extend the library or use native Javascript events.
How do you handle oncut, oncopy, and onpaste in jQuery?
[ "", "javascript", "jquery", "event-handling", "webkit", "" ]
When I create a new `Date` object, it is initialized to the current time but in the local timezone. How can I get the current date and time in GMT?
`java.util.Date` has no specific time zone, although its value is most commonly thought of in relation to UTC. What makes you think it's in local time? To be precise: the value within a `java.util.Date` is the number of milliseconds since the Unix epoch, which occurred at midnight January 1st 1970, UTC. The same epoch could also be described in other time zones, but the traditional description is in terms of UTC. As it's a number of milliseconds since a fixed epoch, the value within `java.util.Date` is the same around the world at any particular instant, regardless of local time zone. I suspect the problem is that you're displaying it via an instance of Calendar which uses the local timezone, or possibly using `Date.toString()` which also uses the local timezone, or a `SimpleDateFormat` instance, which, by default, also uses local timezone. If this isn't the problem, please post some sample code. I would, however, recommend that you use [Joda-Time](http://www.joda.org/joda-time/) anyway, which offers a much clearer API.
# tl;dr ``` Instant.now() // Capture the current moment in UTC. ``` Generate a String to represent that value: ``` Instant.now().toString() ``` > 2016-09-13T23:30:52.123Z # Details As [the correct answer by Jon Skeet](https://stackoverflow.com/a/308689/642706) stated, a java.util.Date object has **no time zone**†. But its [`toString`](http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#toString%28%29) implementation applies the JVM’s default time zone when generating the String representation of that date-time value. Confusingly to the naïve programmer, a Date *seems* to have a time zone but does not. The `java.util.Date`, `j.u.Calendar`, and `java.text.SimpleDateFormat` classes bundled with Java are notoriously troublesome. **Avoid them.** Instead, use either of these competent date-time libraries: * [java.time.\*](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) package in Java 8 * [Joda-Time](http://www.joda.org/joda-time/) # java.time (Java 8) [Java 8](http://en.wikipedia.org/wiki/Java_version_history#Java_SE_8) brings an excellent new [java.time.\* package](http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) to supplant the old java.util.Date/Calendar classes. Getting current time in UTC/GMT is a simple one-liner… ``` Instant instant = Instant.now(); ``` That [`Instant`](http://docs.oracle.com/javase/8/docs/api/java/time/Instant.html) class is the basic building block in java.time, representing a moment on the timeline in [UTC](https://en.wikipedia.org/wiki/Coordinated_Universal_Time) with a resolution of [nanoseconds](https://en.wikipedia.org/wiki/Nanosecond). In Java 8, the current moment is captured with only up to milliseconds resolution. [Java 9 brings a fresh implementation](https://bugs.openjdk.java.net/browse/JDK-8068730) of [`Clock`](https://docs.oracle.com/javase/8/docs/api/java/time/Clock.html) captures the current moment in up to the full nanosecond capability of this class, depending on the ability of your host computer’s clock hardware. It’s `toString` method generates a String representation of its value using [one specific ISO 8601 format](http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_INSTANT). That format outputs zero, three, six or nine digits digits ([milliseconds](https://en.wikipedia.org/wiki/Millisecond), [microseconds](https://en.wikipedia.org/wiki/Microsecond), or [nanoseconds](https://en.wikipedia.org/wiki/Nanosecond)) as necessary to represent the fraction-of-second. If you want more flexible formatting, or other additional features, then apply an offset-from-UTC of zero, for UTC itself ([`ZoneOffset.UTC` constant](http://docs.oracle.com/javase/8/docs/api/java/time/ZoneOffset.html#UTC)) to get a [`OffsetDateTime`](https://docs.oracle.com/javase/10/docs/api/java/time/OffsetDateTime.html). ``` OffsetDateTime now = OffsetDateTime.now( ZoneOffset.UTC ); ``` Dump to console… ``` System.out.println( "now.toString(): " + now ); ``` When run… ``` now.toString(): 2014-01-21T23:42:03.522Z ``` ![Table of date-time types in Java, both modern and legacy.](https://i.stack.imgur.com/MZe55.png) --- # About *java.time* The [*java.time*](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/package-summary.html) framework is built into Java 8 and later. These classes supplant the troublesome old [legacy](https://en.wikipedia.org/wiki/Legacy_system) date-time classes such as [`java.util.Date`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Date.html), [`Calendar`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Calendar.html), & [`SimpleDateFormat`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/SimpleDateFormat.html). To learn more, see the [*Oracle Tutorial*](http://docs.oracle.com/javase/tutorial/datetime/TOC.html). And search Stack Overflow for many examples and explanations. Specification is [JSR 310](https://jcp.org/en/jsr/detail?id=310). The [*Joda-Time*](http://www.joda.org/joda-time/) project, now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), advises migration to the [java.time](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/package-summary.html) classes. You may exchange *java.time* objects directly with your database. Use a [JDBC driver](https://en.wikipedia.org/wiki/JDBC_driver) compliant with [JDBC 4.2](http://openjdk.java.net/jeps/170) or later. No need for strings, no need for `java.sql.*` classes. Where to obtain the java.time classes? * [**Java SE 8**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_8), [**Java SE 9**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_9), [**Java SE 10**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_10), [**Java SE 11**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_11), and later - Part of the standard Java API with a bundled implementation. + Java 9 adds some minor features and fixes. * [**Java SE 6**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_6) and [**Java SE 7**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7) + Most of the *java.time* functionality is back-ported to Java 6 & 7 in [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/). * [**Android**](https://en.wikipedia.org/wiki/Android_(operating_system)) + Later versions of Android bundle implementations of the *java.time* classes. + For earlier Android (<26), the [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP) project adapts [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) (mentioned above). See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). [![Table of which java.time library to use with which version of Java or Android](https://i.stack.imgur.com/eT2Oo.png)](https://i.stack.imgur.com/eT2Oo.png) The [**ThreeTen-Extra**](http://www.threeten.org/threeten-extra/) project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as [`Interval`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/Interval.html), [`YearWeek`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html), [`YearQuarter`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearQuarter.html), and [more](http://www.threeten.org/threeten-extra/apidocs/index.html). --- # Joda-Time UPDATE: The [Joda-Time](http://www.joda.org/joda-time/) project, now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), advises migration to the [java.time](http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. Using the [Joda-Time](http://www.joda.org/joda-time/) 3rd-party open-source free-of-cost library, you can get the current date-time in just one line of code. Joda-Time inspired the new java.time.\* classes in Java 8, but has a different architecture. You may use Joda-Time in older versions of Java. Joda-Time continues to work in Java 8 and continues to be actively maintained (as of 2014). However, the Joda-Time team does advise migration to java.time. ``` System.out.println( "UTC/GMT date-time in ISO 8601 format: " + new org.joda.time.DateTime( org.joda.time.DateTimeZone.UTC ) ); ``` More detailed example code (Joda-Time 2.3)… ``` org.joda.time.DateTime now = new org.joda.time.DateTime(); // Default time zone. org.joda.time.DateTime zulu = now.toDateTime( org.joda.time.DateTimeZone.UTC ); ``` Dump to console… ``` System.out.println( "Local time in ISO 8601 format: " + now ); System.out.println( "Same moment in UTC (Zulu): " + zulu ); ``` When run… ``` Local time in ISO 8601 format: 2014-01-21T15:34:29.933-08:00 Same moment in UTC (Zulu): 2014-01-21T23:34:29.933Z ``` For more example code doing time zone work, see [my answer](https://stackoverflow.com/a/19378311/642706) to a similar question. # Time Zone I recommend you always specify a time zone rather than relying implicitly on the JVM’s current default time zone (which can change at any moment!). Such reliance seems to be a common cause of confusion and bugs in date-time work. When calling `now()` pass the desired/expected time zone to be assigned. Use the [`DateTimeZone`](http://www.joda.org/joda-time/apidocs/org/joda/time/DateTimeZone.html) class. ``` DateTimeZone zoneMontréal = DateTimeZone.forID( "America/Montreal" ); DateTime now = DateTime.now( zoneMontréal ); ``` That class holds a [constant for UTC](http://www.joda.org/joda-time/apidocs/org/joda/time/DateTimeZone.html#UTC) time zone. ``` DateTime now = DateTime.now( DateTimeZone.UTC ); ``` If you truly want to use the JVM’s current default time zone, make an explicit call so your code is self-documenting. ``` DateTimeZone zoneDefault = DateTimeZone.getDefault(); ``` # ISO 8601 Read about [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) formats. Both java.time and Joda-Time use that standard’s sensible formats as their defaults for both parsing and generating strings. --- † Actually, java.util.Date *does* have a time zone, buried deep under layers of source code. For most practical purposes, that time zone is ignored. So, as shorthand, we say java.util.Date has no time zone. Furthermore, that buried time zone is *not* the one used by Date’s `toString` method; that method uses the JVM’s current default time zone. All the more reason to avoid this confusing class and stick with Joda-Time and java.time.
How can I get the current date and time in UTC or GMT in Java?
[ "", "java", "date", "localization", "timezone", "gmt", "" ]
I'm looking for a QR-Code library for C/C++, not Java or .Net please. Anyone knows of one? Note: There was a [similar question](https://stackoverflow.com/questions/231741/qr-code-2d-barcode-coding-and-decoding-algorithms) a while back however but it didn't get answered properly.
How is this one? <http://megaui.net/fukuchi/works/qrencode/index.en.html>
The [zxing library](http://code.google.com/p/zxing) is primarily Java, but, includes a [port of the QR Code detector and decoder to C++](http://code.google.com/p/zxing/source/browse/#svn/trunk/cpp).
Does anyone know of a C/C++ Unix QR-Code library?
[ "", "c++", "c", "qr-code", "" ]
`Html.TextBox("ParentPassword", "", new { @class = "required" })` what the gosh darned heck is the @ for the @class.
`class` is a reserved keyword, so you can't use this as a variable name. The @ operator allows you to get around this rule. The reason why its being done here is that the anonymous object is used to populate attributes on a HTML element. A valid attribute name is "class", which lets you set the CSS class on the element.
`class` is a keyword. To use `class` as the name of a variable/property, in C#, you can prepend `@` to it, as `@class`. In the IL, for all .net is concerned, the name of the variable/property is still `class` - `@` is the way you have to do it in C#.
What does the @ in this code sample mean?
[ "", "c#", ".net", "variables", "keyword", "variable-names", "" ]
I'm constructing a method to take in an ArrayList(presumably full of objects) and then list all the fields(and their values) for each object in the ArrayList. Currently my code is as follows: ``` public static void ListArrayListMembers(ArrayList list) { foreach (Object obj in list) { Type type = obj.GetType(); string field = type.GetFields().ToString(); Console.WriteLine(field); } } ``` Of course, I understand the immediate issue with this code: if it worked it'd only print one field per object in the ArrayList. I'll fix this later - right now I'm just curious how to get all of the public fields associated with an object.
``` foreach (Object obj in list) { Type type = obj.GetType(); foreach (var f in type.GetFields().Where(f => f.IsPublic)) { Console.WriteLine( String.Format("Name: {0} Value: {1}", f.Name, f.GetValue(obj)); } } ``` Note that this code requires .NET 3.5 to work ;-)
You can obtain all the object Fields declared directly in the class with the BindingFlags: ``` GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) ``` and all object Fields including inherited with: ``` GetFields(BindingFlags.Public | BindingFlags.Instance) ```
How can I find all the public fields of an object in C#?
[ "", "c#", "object", "field", "public", "" ]
At my workplace, we tend to use **iostream**, **string**, **vector**, **map**, and the odd **algorithm** or two. We haven't actually found many situations where template techniques were a best solution to a problem. What I am looking for here are ideas, and optionally sample code that shows how you used a template technique to create a new solution to a problem that you encountered in real life. As a bribe, expect an up vote for your answer.
I've used a lot of template code, mostly in Boost and the STL, but I've seldom had a need to *write* any. One of the exceptions, a few years ago, was in a program that manipulated Windows PE-format EXE files. The company wanted to add 64-bit support, but the `ExeFile` class that I'd written to handle the files only worked with 32-bit ones. The code required to manipulate the 64-bit version was essentially identical, but it needed to use a different address type (64-bit instead of 32-bit), which caused two other data structures to be different as well. Based on the STL's use of a single template to support both `std::string` and `std::wstring`, I decided to try making `ExeFile` a template, with the differing data structures and the address type as parameters. There were two places where I still had to use `#ifdef WIN64` lines (slightly different processing requirements), but it wasn't really difficult to do. We've got full 32- and 64-bit support in that program now, and using the template means that every modification we've done since automatically applies to both versions.
**General info on templates:** Templates are useful anytime you need to use the same code but operating on different data types, where the types are known at compile time. And also when you have any kind of container object. A very common usage is for just about every type of data structure. For example: Singly linked lists, doubly linked lists, trees, tries, hashtables, ... Another very common usage is for sorting algorithms. One of the main advantages of using templates is that you can remove code duplication. Code duplication is one of the biggest things you should avoid when programming. You could implement a function Max as both a macro or a template, but the template implementation would be type safe and therefore better. **And now onto the cool stuff:** Also see [template metaprogramming](http://en.wikipedia.org/wiki/Template_metaprogramming), which is a way of pre-evaluating code at compile-time rather than at run-time. Template metaprogramming has only immutable variables, and therefore its variables cannot change. Because of this template metaprogramming can be seen as a type of functional programming. Check out this example of template metaprogramming from Wikipedia. It shows how templates can be used to **execute code at compile time**. Therefore at runtime you have a pre-calculated constant. ``` template <int N> struct Factorial { enum { value = N * Factorial<N - 1>::value }; }; template <> struct Factorial<0> { enum { value = 1 }; }; // Factorial<4>::value == 24 // Factorial<0>::value == 1 void foo() { int x = Factorial<4>::value; // == 24 int y = Factorial<0>::value; // == 1 } ```
Where do you find templates useful?
[ "", "c++", "templates", "metaprogramming", "generic-programming", "" ]
I am writing a lib and a demo project. The project doesn't care which version of the lib I use (I can use sdl, directx or whatever I like as the gfx backend). To get the object I do ``` Obj *obj = libname_newDevice(); ``` Now, should I use delete or should I do `obj->deleteMe();`? I ask because I am not exactly doing new so I shouldn't be doing the delete? I have `obj->create(theType);` which returns a class with the Obj interface. My real question is do I need a `libname_deleteDevice();` or is `obj->deleteMe()` fine since I have a deleteMe in the interface?
I would take one step further. If you are using a factory function to create, it may be logical to use a factory function to destroy. In addition to this to make it all nice and exetion safe wrap in in an object. ``` class ObjWrap { public: ObjWrap() :obj(libname_newDevice()) {} ~ObjWrap() { libname_deleteDevice(obj);} private: ObjWrap(ObjWrap const&); // Dont copy void operator=(ObjWrap const&); // Dont copy Obj* obj; }; // If you want to copy then you need to extra work on ref counting // This may need some form of smart pointer. ```
Since you are abstracting the creation inside `libname_newDevice()` (which I have to say isn't a good approach), you should destroy using something like `libname_destroyDevice (obj)`. And as the comment from Martin suggests, it's best to put them in the constructor and destructor of a custom class, that you just need to create on stack, and the compiler will take care of the rest.
delete or virtual delete?
[ "", "c++", "virtual", "" ]
I have an existing Stored Procedure which I am trying to now call with LINQ to SQL, here is the stored procedure: ``` ALTER procedure [dbo].[sp_SELECT_Security_ALL] ( @UID Varchar(15) ) as DECLARE @A_ID int If ISNULL(@UID,'') = '' SELECT DISTINCT App_ID, App_Name, App_Description, DB, DBNameApp_ID, For_One_EVA_List_Ind From v_Security_ALL ELSE BEGIN Select @A_ID = (Select Assignee_ID From NEO.dbo.v_Assignees Where USER_ID = @UID and Inactive_Ind = 0) SELECT DISTINCT Security_User_ID, Security_Company, Security_MailCode, Security_Last_Name, Security_First_Name, Security_User_Name, Security_User_Info, Security_User_CO_MC, Security_Email_Addr, Security_Phone, Security_Security_Level, Security_Security_Desc, Security_Security_Comment, Security_Security_Inactive_Ind, App_ID, App_Name, App_Description, DB, DBNameApp_ID, For_One_EVA_List_Ind, @A_ID as Assignee_ID From v_Security_ALL Where Security_User_ID = @UID END ``` My problem is that the intellsense only sees the first set of return values in the IF statement and I can not access anything from the "else" part of my stored procedure. so when I try to do this: ``` var apps = dataContext.sp_SELECT_Security_ALL(userId); foreach (var app in apps) { string i = app. } ``` On the app. part the only available values I have there is the results of the the first Select distinct above. Is it possible to use LINQ with this type of stored procedure?
Scott Guthrie has covered this case [in a blog post](http://weblogs.asp.net/scottgu/archive/2007/08/16/linq-to-sql-part-6-retrieving-data-using-stored-procedures.aspx). Scroll down to "Handling Multiple Result Shapes from SPROCs."
The problem isn't with Intellisense. `dataContext.sp_SELECT_Security_ALL()` is returning a fixed data type. You may be hiding that behind a "var", but it's nevertheless a concrete type with a fixed number of properties. There is still C# remember, and a function can only return one type of object. Look in your dataContext.designer.cs file to see how it's actually defined.
Linq to SQL, Stored Procedure with different return types based on an If/Else
[ "", "c#", "linq-to-sql", "stored-procedures", "" ]
I'm creating an interface wrapper for a class. The member within the class is a reference(to avoid copying the large structure). If I create a private constructor, what is the best way to initialize that reference to appease the compiler? ``` struct InterfaceWrapper { InterfaceWrapper( SomeHugeStructure& src ):m_internal(src){}; int someElement(void) const { return m_internal.someElement; }; private: InterfaceWrapper(){} // initialize m_internal SomeHugeStructure& m_internal; }; ```
As others have mentioned, if your purpose is to prevent others from calling the default constructor, then you don't want to provide a body at all, and declaring it is unnecessary since you have another constructor and the compiler won't generate it for you. If the purpose is to limit access to friends of the class, then you would probably be best having a pointer (prefereably a smart pointer) member, and setting it to NULL. -- Also, I'm not sure why you made this a struct rather than a class. In general making something a struct makes sense when you're exposing data members as public, similar to C. In this case, it looks like you have a conventional class, in which case the C++ convention would be to make it a class.
If you really need to construct the class without having an element, a reference is not the way to go. If your only reason to use a reference is to avoid copying, I'd suggest using a pointer. You can simply take the address of the passed reference in you regular constructor, and initialize it to NULL in the private constructor. When the object's lifetime ends the pointer will be a dangling pointer, but the same is true for references... Alternatively, have the public constructor take a smart pointer and use such a smart pointer as member too, if you're concerned about lifetimes. And of course, cope with the pointer possibly being NULL in the remainder of the class' code. (but you had to cope with the member possible being a stub in the reference case too, so that's not really an issue)
How can you initialize a class with a reference member from a private constructor?
[ "", "c++", "constructor", "reference", "" ]
Steve Yegge recently posted an [interesting blog post](http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html) on what he calls the universal design pattern. In there he details using prototypes as a modelling tool, instead of classes. I like the way this introduces less coupling compared to inheritance. But that is something one can get with classes as well, by implementing classes in terms of other classes, instead of inheritance. Does anyone else have success stories of using prototypes, and can maybe help explain where using prototypes is advantageous compared to classes. I guess it comes down to static modelling versus dynamic modelling, but more examples would be very welcome.
One interesting bit is that it's easy to make a prototype-based language act OO but it's difficult to make an OO language act prototype-based. * Alex Arnell's [inheritance.js](http://code.google.com/p/inheritance/) is a short and sweet chunk of code that makes JavaScript act OO, complete with access to the parent 'Class'. * Here's one of John Resig's solutions to the same problem: <http://ejohn.org/blog/simple-javascript-inheritance/>. * [Chapter 16 of Programming in Lua](http://www.lua.org/pil/16.html) describes object orientation in Lua. Specifically, [section 16.2](http://www.lua.org/pil/16.2.html) gives a nice example of inheritance. It's not entirely clear what OO as prototype would look like, aside from composition versus inheritance as you mention. A prototype language makes complex inheritance behavior easy. You can implement [multiple inheritance](http://www.lua.org/pil/16.3.html), [mixin](http://en.wikipedia.org/wiki/Mixin)-like behavior, or just pick and choose what you want from one object to add to another. [Wikipedia's article](http://en.wikipedia.org/wiki/Prototype-based_programming) mentions: "Advocates of prototype-based programming often argue that class-based languages encourage a model of development that focuses first on the taxonomy and relationships between classes. In contrast, prototype-based programming is seen as encouraging the programmer to focus on the behavior of some set of examples and only later worry about classifying these objects into archetypal objects that are later used in a fashion similar to classes." That's not to say the prototype paradigm is all pros and no cons. If OO is more restrictive, it's because it chooses to be. I can see where all that flexibility might get you into trouble if you aren't careful.
Prototypes are a form of inheritance, it's just that objects inherit attributes and behavior directly from other objects, instead of getting their attributes and behavior from their class, which inherits from other classes. For examples, check out any object oriented code in a [prototype based language](http://en.wikipedia.org/wiki/Prototype-based_programming) like, for example, JavaScript.
prototypes versus classes
[ "", "javascript", "oop", "prototype", "" ]
In particular, would it be possible to have **code similar to this c++ code executed at compile time in c#**? ``` template <int N> struct Factorial { enum { value = N * Factorial<N - 1>::value }; }; template <> struct Factorial<0> { enum { value = 1 }; }; // Factorial<4>::value == 24 // Factorial<0>::value == 1 void foo() { int x = Factorial<4>::value; // == 24 int y = Factorial<0>::value; // == 1 } ```
No, metaprogramming of this complexity is not supported directly by the C# language. However, like [@littlegeek](https://stackoverflow.com/questions/237326/is-metaprogramming-possible-in-c#237644) said, the [Text Template Transformation Toolkit](http://www.hanselman.com/blog/T4TextTemplateTransformationToolkitCodeGenerationBestKeptVisualStudioSecret.aspx) included with Visual Studio will allow you to achieve code generation of any complexity.
Metaprogramming is possible in .NET (see compiler compilers, regular expressions, code DOM, reflection etc.) but C# is not capable of *template* metaprogramming because it does not have that language feature.
Is metaprogramming possible in C#?
[ "", "c#", "metaprogramming", "" ]
The UPSERT operation either updates or inserts a row in a table, depending if the table already has a row that matches the data: ``` if table t has a row exists that has key X: update t set mystuff... where mykey=X else insert into t mystuff... ``` Since Oracle doesn't have a specific UPSERT statement, what's the best way to do this?
An alternative to MERGE (the "old fashioned way"): ``` begin insert into t (mykey, mystuff) values ('X', 123); exception when dup_val_on_index then update t set mystuff = 123 where mykey = 'X'; end; ```
The [MERGE statement](http://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_9016.htm#SQLRF01606) merges data between two tables. Using DUAL allows us to use this command. Note that this is not protected against concurrent access. ``` create or replace procedure ups(xa number) as begin merge into mergetest m using dual on (a = xa) when not matched then insert (a,b) values (xa,1) when matched then update set b = b+1; end ups; / drop table mergetest; create table mergetest(a number, b number); call ups(10); call ups(10); call ups(20); select * from mergetest; A B ---------------------- ---------------------- 10 2 20 1 ```
How to UPSERT (update or insert into a table?)
[ "", "sql", "oracle", "merge", "upsert", "" ]
I am trying to call a setTimeout from within a setInterval callback: ``` function callback() { //assign myVar var myVar = document.getElementById("givenID"); //... //now wait 2 secs then call some code that uses myVAr setTimeout("myVar.innerHTML = 'TEST'", 2000); } setInterval("callback();", 10000); ``` setInterval works as expected but setTimeout call is failing. I guess the problem is related to the fact that I am referencing a variable (myVar) that's not in scope. What's the best way to solve this?
This is a perfect candidate for closures: ``` setInterval( function () { var myVar = document.getElementById("givenID"); setTimeout( function() { // myVar is available because the inner closure // gets the outer closures scope myVar.innerHTML = "Junk"; },2000); }, 10000); ``` Your problem is scope related, and this would work around that.
I had a similar problem. The issue was that I was trying to call a method from within itself through a setTimeout(). Something like this, WHICH DIDN'T WORK FOR ME: ``` function myObject() { this.egoist = function() { setTimeout( 'this.egoist()', 200 ); } } myObject001 = new myObject(); myObject001.egoist(); ``` The following ALSO DIDN'T WORK: ``` ... setTimeout( egoist, 200 ); ... setTimeout( egoist(), 200 ); ... setTimeout( this.egoist, 200 ); ... setTimeout( this.egoist(), 200 ); ... setTimeout( function() { this.egoist() }, 200 ); ``` The solution was to use with() statement like so: ``` function myObject() { this.egoist = function() { with (this) { setTimeout( function() { egoist() }, 200 );} } } myObject001 = new myObject(); myObject001.egoist(); ``` Of course, this is an endless cycle, but the point I'm making here is different. Hope this helps :)
How to solve Var out of scope within setTimeout call
[ "", "javascript", "scope", "" ]
I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this? ``` Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in <module> from django.core import management ImportError: No module named django.core ```
You must make sure that django is in your PYTHONPATH. To test, just do a `import django` from a python shell. There should be no output: ``` ActivePython 2.5.1.1 (ActiveState Software Inc.) based on Python 2.5.1 (r251:54863, May 1 2007, 17:47:05) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> ``` If you installed django via `setuptools` (`easy_install`, or with the `setup.py` included with django), then check in your `site-packages` if the `.pth` file (`easy-install.pth`, `django.pth`, ...) point to the correct folder. HIH.
I have the same problem on Windows and it seems I've found the problem. I have both 2.7 and 3.x installed. It seems it has something to do with the associate program of .py: In commandline type: > assoc .py and the result is: .py=Python.File which means .py is associated with Python.File then I tried this: > ftype Python.File I got: Python.File="C:\Python32\python.exe" "%1" %\* which means in commandline .py is associated with my Python 3.2 installation -- and that's why I can't just type "django-admin.py blah blah" to use django. ALL you need to do is change the association: > ftype Python.File="C:\Python27\python.exe" "%1" %\* then everythong's okay!
No Module named django.core
[ "", "python", "django", "" ]
In some code I've inherited, I see frequent use of `size_t` with the `std` namespace qualifier. For example: ``` std::size_t n = sizeof( long ); ``` It compiles and runs fine, of course. But it seems like bad practice to me (perhaps carried over from C?). Isn't it true that `size_t` is built into C++ and therefore in the global namespace? Is a header file include needed to use `size_t` in C++? Another way to ask this question is, would the following program (with *no* includes) be expected to *compile* on all C++ compilers? ``` size_t foo() { return sizeof( long ); } ```
There seems to be confusion among the stackoverflow crowd concerning this `::size_t` is defined in the backward compatibility header `stddef.h` . It's been part of `ANSI/ISO C` and `ISO C++` since their very beginning. Every C++ implementation has to ship with `stddef.h` (compatibility) and `cstddef` where only the latter defines `std::size_t` and not necessarily `::size_t`. See Annex D of the C++ Standard.
Section 17.4.1.2 of the C++ standard, paragraph 4, states that: "In the C++ Standard Library, however, the declarations and definitions (except for names which are defined as macros in C) are within namespace scope (3.3.5) of the namespace std." This includes items found in headers of the pattern *cname*, including *cstddef*, which defines size\_t. So std::size\_t is in fact correct.
Does "std::size_t" make sense in C++?
[ "", "c++", "size-t", "" ]
Is it possible to detect, on the client side, whether the user is using an encrypted page or not? Put another way -- I want to know if the URL of the current page starts with http or https.
Use `window.location.protocol` to check if it is `https:` ``` function isSecure() { return window.location.protocol == 'https:'; } ``` Alternatively you can omit specifying "window" if you don't have a locally scoped location. ``` function isSecure() { return location.protocol == 'https:'; } ```
As google analytics taught me: ``` if ("https:" == document.location.protocol) { /* secure */ } else { /* unsecure */ } ```
How can I use JavaScript on the client side to detect if the page was encrypted?
[ "", "javascript", "http", "https", "" ]
Is there a better way to do this? ``` string[] s = {"zero", "one", "two", "three", "four", "five"}; var x = s .Select((a,i) => new {Value = a, Index = i}) .Where(b => b.Value.StartsWith("t")) .Select(c => c.Index); ``` i.e. I'm looking for a more efficient or more elegant way to get the positions of the items matching the criteria.
You could easily add your own extension method: ``` public static IEnumerable<int> IndexesWhere<T>(this IEnumerable<T> source, Func<T, bool> predicate) { int index=0; foreach (T element in source) { if (predicate(element)) { yield return index; } index++; } } ``` Then use it with: ``` string[] s = {"zero", "one", "two", "three", "four", "five"}; var x = s.IndexesWhere(t => t.StartsWith("t")); ```
If you're just using the example as a way to learn LINQ, ignore this post. --- It's not clear to me that LINQ is actually the best way to do this. The code below seems like it would be more efficient since no new anonymous type needs to be created. Granted, your example may be contrived and the technique might be more useful in a different context, for example in a data structure where it could take advantage of an index on value, but the code below is reasonably straight-forward, understandable (no thought required) and arguably more efficient. ``` string[] s = {"zero", "one", "two", "three", "four", "five"}; List<int> matchingIndices = new List<int>(); for (int i = 0; i < s.Length; ++i) { if (s[i].StartWith("t")) { matchingIndices.Add(i); } } ```
Getting a collection of index values using a LINQ query
[ "", "c#", ".net", "arrays", "linq", "indexof", "" ]
Ok, so i have been trying to put everyone one of my classes in some root folder, either: UI BusinessLogic DataAccess BusinessObjects Interfaces i have a few more where i can't seem to bucket very well so i am looking for suggestions 1. A Cache class that maintains a private dictionary and allows different access to objects based on some specific keys 2. Event Arg classes? Also, under a project i now start to have sub systems that have all 3 (data access, business objects, busiensslogic). How should i break up the folders structure? A. ProjectX --Subsystem1 ----BusinessObjects ----DataAccess ----BusinessObjects --Subsystem2 ----BusinessObjects ----DataAccess ----BusinessObjects or ProjectX --BusienssLogic ----Subsystem1BL ----Subsystem2BL --DataAccess ----Subsystem1DA ----Subsystem2DA --BusinessObjects ----Subsystem1BO ----Subsystem2BO or ProjectX --BusinessLogic --DataAccess --BusinessObjects (with no subdirectories for each functional subsystem)
I try to align my assembly names with their namespaces, and use the .NET Framework itself as a guideline. I firmly believe that working with a namespace structure that drives a folder structure makes for a much more maintainable codebase. For example, I have a caching provider that is part of the global developer framework that we use. It lives in a namespace of something similar to: [Company].Core.Data.Caching I have other data related functionality that also logically falls underneath the Data feature, so caching has siblings like Adapters, Converters, and Generators. So, let's assume we have the following namespaces: [Company].Core.Data.Adapters [Company].Core.Data.Converters [Company].Core.Data.Caching [Company].Core.Data.Generators These related namespaces live in an assembly called [Company].Core.Data, which is also the project name. Finding things in the solution becomes very simple following this structure. Speaking of structure, now we get back to how they are stored on disk. The project name is the root folder name. This assumes my source control folder, which is "C:\Source Control" on my local machine: C:\Source Control\Core[Company].Core.Data\ C:\Source Control\Core[Company].Core.Data\Adapters C:\Source Control\Core[Company].Core.Data\Caching C:\Source Control\Core[Company].Core.Data\Converters C:\Source Control\Core[Company].Core.Data\Generators So, as a hierarchy, it looks something like: [Solution] --[Company].Core.Data ----[Adapters] ------(Adapters files) ----[Caching] ------(Caching files) ----[Converters] ------(Converters files) I put all projects at the same level, and vary sub-namespaces with folders. This way the namespaces and the physical structures are easy to reconcile. The hard part is finding balance. You don't want to have a large number of smaller assemblies, so I normally will group them at a higher level, and eventually refactor it when either it is trending to grow too large, or if sub-namespaces change more frequently than other parts. I have been doing this for years now, and it is very comfortable for not only myself, but for my developers to use. As for your EventArgs question, I agree with the consensus that I normally do one class per file, but will make the exception to place an EventArgs class with another class if it is singular usage. For multiuse, I put them at the highest logical point in the assembly, allowing the namespace structure to bind my scoping.
I usually like to stick to the 1 class, 1 file rule, but when it comes to EventArgs, I actually like to declare them in the same file that I define the delegate or event. Unless, the args are used by more than one class hierarchy, which doesn't tend to happen to me often. As for the cache, I would put in the folder of the classes in which it supports. As much as I like good organization, one can get too anal with it.
Class bucketing . .
[ "", "c#", "projects-and-solutions", "directory-structure", "" ]
I know that [buffer overruns](http://en.wikipedia.org/wiki/Buffer_overflow) are one potential hazard to using C-style strings (char arrays). If I know my data will fit in my buffer, is it okay to use them anyway? Are there other drawbacks inherent to C-style strings that I need to be aware of? **EDIT:** Here's an example close to what I'm working on: ``` char buffer[1024]; char * line = NULL; while ((line = fgets(fp)) != NULL) { // this won't compile, but that's not the issue // parse one line of command output here. } ``` This code is taking data from a FILE pointer that was created using a `popen("df")` command. I'm trying to run Linux commands and parse their output to get information about the operating system. Is there anything wrong (or dangerous) with setting the buffer to some arbitrary size this way?
C strings lack the following aspects of their C++ counterparts: * Automatic memory management: you have to allocate and free their memory manually. * Extra capacity for concatenation efficiency: C++ strings often have a capacity greater than their size. This allows increasing the size without many reallocations. * No embedded NULs: by definition a NUL character ends a C string; C++ string keep an internal size counter so they don't need a special value to mark their end. * Sensible comparison and assignment operators: even though comparison of C string pointers is permitted, it's almost always *not* what was intended. Similarly, assigning C string pointers (or passing them to functions) creates ownership ambiguities.
There are a few disadvantages to C strings: 1. Getting the length is a relatively expensive operation. 2. No embedded nul characters are allowed. 3. The signed-ness of chars is implementation defined. 4. The character set is implementation defined. 5. The size of the char type is implementation defined. 6. Have to keep track separately of how each string is allocated and so how it must be free'd, or even if it needs to be free'd at all. 7. No way to refer to a slice of the string as another string. 8. Strings are not immutable, meaning they must be synchronized separately. 9. Strings cannot be manipulated at compile time. 10. Switch cases cannot be strings. 11. The C preprocessor does not recognize strings in expressions. 12. Cannot pass strings as template arguments (C++).
What are some of the drawbacks to using C-style strings?
[ "", "c++", "c", "string", "" ]
I would like to know which one is the best material that I can hand out to my students about "*C# comments*".
This is quite interesting to do with the xml comments: <http://thoughtpad.net/alan-dean/cs-xml-documentation.html> These get read by [sandcastle](http://blogs.msdn.com/sandcastle/) too... :o)
Something that I read a while ago (and have lost track of where) is: * Beginners comment nothing * Apprentices comment the obvious * Journeymen comment the reason for doing it * Masters comment the reason for not doing it another way
C# comments tutorial
[ "", "c#", "comments", "" ]
Is it possible to check if a dynamically loaded assembly has been signed with a specific strong name? Is it enough / secure to compare the values returned from **AssemblyName.GetPublicKey()** method? ``` Assembly loaded = Assembly.LoadFile(path); byte[] evidenceKey = loaded.GetName().GetPublicKey(); if (evidenceKey != null) { byte[] internalKey = Assembly.GetExecutingAssembly().GetName().GetPublicKey(); if (evidenceKey.SequenceEqual(internalKey)) { return extension; } } ``` Can't this be spoofed? I am not sure if the SetPublicKey() method has any effect on a built assembly, but even the MSDN documentation shows how you can use this on a dynamically generated assembly (reflection emit) so that would mean you could extract the public key from the host application and inject it into an assembly of your own and run mallicious code if the above was the safe-guard, or am I missing something? Is there a more correct and secure approach? I know if the reversed situation was the scenario, that is, where I wanted to secure the assembly from only being called by signed hosts then I could tag the assembly with the StrongNameIdentityPermission attribute.
There is no managed way to check the signature of an assembly and checking the public key leaves you vulnerable to spoofing. You will have to use [P/Invoke](http://en.wikipedia.org/wiki/Platform_Invocation_Services) and call the **StrongNameSignatureVerificationEx** function to check the signature ``` [DllImport("mscoree.dll", CharSet=CharSet.Unicode)] static extern bool StrongNameSignatureVerificationEx(string wszFilePath, bool fForceVerification, ref bool pfWasVerified); ```
Checking strong name using StrongNameSignatureVerificationEx from mscoree.dll is deprecated under .NET 4 according to <http://msdn.microsoft.com/pl-pl/library/ms232579.aspx>. .NET 4 way of doing it is: ``` var clrStrongName = (IClrStrongName)RuntimeEnvironment.GetRuntimeInterfaceAsObject(new Guid("B79B0ACD-F5CD-409b-B5A5-A16244610B92"), new Guid("9FD93CCF-3280-4391-B3A9-96E1CDE77C8D")); bool verificationForced; int result = clrStrongName.StrongNameSignatureVerificationEx(@"PATH\TO\ASSEMBLY.DLL", true, out verificationForced); if (result == 0) { Console.WriteLine("Valid."); } [ComConversionLoss, Guid("9FD93CCF-3280-4391-B3A9-96E1CDE77C8D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), SecurityCritical] [ComImport] internal interface IClrStrongName { [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall)] int GetHashFromAssemblyFile([MarshalAs(UnmanagedType.LPStr)] [In] string pszFilePath, [MarshalAs(UnmanagedType.U4)] [In] [Out] ref int piHashAlg, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] [Out] byte[] pbHash, [MarshalAs(UnmanagedType.U4)] [In] int cchHash, [MarshalAs(UnmanagedType.U4)] out int pchHash); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall)] int GetHashFromAssemblyFileW([MarshalAs(UnmanagedType.LPWStr)] [In] string pwzFilePath, [MarshalAs(UnmanagedType.U4)] [In] [Out] ref int piHashAlg, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] [Out] byte[] pbHash, [MarshalAs(UnmanagedType.U4)] [In] int cchHash, [MarshalAs(UnmanagedType.U4)] out int pchHash); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall)] int GetHashFromBlob([In] IntPtr pbBlob, [MarshalAs(UnmanagedType.U4)] [In] int cchBlob, [MarshalAs(UnmanagedType.U4)] [In] [Out] ref int piHashAlg, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] [Out] byte[] pbHash, [MarshalAs(UnmanagedType.U4)] [In] int cchHash, [MarshalAs(UnmanagedType.U4)] out int pchHash); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall)] int GetHashFromFile([MarshalAs(UnmanagedType.LPStr)] [In] string pszFilePath, [MarshalAs(UnmanagedType.U4)] [In] [Out] ref int piHashAlg, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] [Out] byte[] pbHash, [MarshalAs(UnmanagedType.U4)] [In] int cchHash, [MarshalAs(UnmanagedType.U4)] out int pchHash); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall)] int GetHashFromFileW([MarshalAs(UnmanagedType.LPWStr)] [In] string pwzFilePath, [MarshalAs(UnmanagedType.U4)] [In] [Out] ref int piHashAlg, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] [Out] byte[] pbHash, [MarshalAs(UnmanagedType.U4)] [In] int cchHash, [MarshalAs(UnmanagedType.U4)] out int pchHash); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall)] int GetHashFromHandle([In] IntPtr hFile, [MarshalAs(UnmanagedType.U4)] [In] [Out] ref int piHashAlg, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] [Out] byte[] pbHash, [MarshalAs(UnmanagedType.U4)] [In] int cchHash, [MarshalAs(UnmanagedType.U4)] out int pchHash); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall)] [return: MarshalAs(UnmanagedType.U4)] int StrongNameCompareAssemblies([MarshalAs(UnmanagedType.LPWStr)] [In] string pwzAssembly1, [MarshalAs(UnmanagedType.LPWStr)] [In] string pwzAssembly2, [MarshalAs(UnmanagedType.U4)] out int dwResult); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall)] int StrongNameFreeBuffer([In] IntPtr pbMemory); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall)] int StrongNameGetBlob([MarshalAs(UnmanagedType.LPWStr)] [In] string pwzFilePath, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] [Out] byte[] pbBlob, [MarshalAs(UnmanagedType.U4)] [In] [Out] ref int pcbBlob); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall)] int StrongNameGetBlobFromImage([In] IntPtr pbBase, [MarshalAs(UnmanagedType.U4)] [In] int dwLength, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] [Out] byte[] pbBlob, [MarshalAs(UnmanagedType.U4)] [In] [Out] ref int pcbBlob); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall)] int StrongNameGetPublicKey([MarshalAs(UnmanagedType.LPWStr)] [In] string pwzKeyContainer, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] [In] byte[] pbKeyBlob, [MarshalAs(UnmanagedType.U4)] [In] int cbKeyBlob, out IntPtr ppbPublicKeyBlob, [MarshalAs(UnmanagedType.U4)] out int pcbPublicKeyBlob); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall)] [return: MarshalAs(UnmanagedType.U4)] int StrongNameHashSize([MarshalAs(UnmanagedType.U4)] [In] int ulHashAlg, [MarshalAs(UnmanagedType.U4)] out int cbSize); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall)] int StrongNameKeyDelete([MarshalAs(UnmanagedType.LPWStr)] [In] string pwzKeyContainer); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall)] int StrongNameKeyGen([MarshalAs(UnmanagedType.LPWStr)] [In] string pwzKeyContainer, [MarshalAs(UnmanagedType.U4)] [In] int dwFlags, out IntPtr ppbKeyBlob, [MarshalAs(UnmanagedType.U4)] out int pcbKeyBlob); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall)] int StrongNameKeyGenEx([MarshalAs(UnmanagedType.LPWStr)] [In] string pwzKeyContainer, [MarshalAs(UnmanagedType.U4)] [In] int dwFlags, [MarshalAs(UnmanagedType.U4)] [In] int dwKeySize, out IntPtr ppbKeyBlob, [MarshalAs(UnmanagedType.U4)] out int pcbKeyBlob); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall)] int StrongNameKeyInstall([MarshalAs(UnmanagedType.LPWStr)] [In] string pwzKeyContainer, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] [In] byte[] pbKeyBlob, [MarshalAs(UnmanagedType.U4)] [In] int cbKeyBlob); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall)] int StrongNameSignatureGeneration([MarshalAs(UnmanagedType.LPWStr)] [In] string pwzFilePath, [MarshalAs(UnmanagedType.LPWStr)] [In] string pwzKeyContainer, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] [In] byte[] pbKeyBlob, [MarshalAs(UnmanagedType.U4)] [In] int cbKeyBlob, [In] [Out] IntPtr ppbSignatureBlob, [MarshalAs(UnmanagedType.U4)] out int pcbSignatureBlob); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall)] int StrongNameSignatureGenerationEx([MarshalAs(UnmanagedType.LPWStr)] [In] string wszFilePath, [MarshalAs(UnmanagedType.LPWStr)] [In] string wszKeyContainer, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] [In] byte[] pbKeyBlob, [MarshalAs(UnmanagedType.U4)] [In] int cbKeyBlob, [In] [Out] IntPtr ppbSignatureBlob, [MarshalAs(UnmanagedType.U4)] out int pcbSignatureBlob, [MarshalAs(UnmanagedType.U4)] [In] int dwFlags); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall)] int StrongNameSignatureSize([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] [In] byte[] pbPublicKeyBlob, [MarshalAs(UnmanagedType.U4)] [In] int cbPublicKeyBlob, [MarshalAs(UnmanagedType.U4)] out int pcbSize); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall)] [return: MarshalAs(UnmanagedType.U4)] int StrongNameSignatureVerification([MarshalAs(UnmanagedType.LPWStr)] [In] string pwzFilePath, [MarshalAs(UnmanagedType.U4)] [In] int dwInFlags, [MarshalAs(UnmanagedType.U4)] out int dwOutFlags); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall)] [return: MarshalAs(UnmanagedType.U4)] int StrongNameSignatureVerificationEx([MarshalAs(UnmanagedType.LPWStr)] [In] string pwzFilePath, [MarshalAs(UnmanagedType.I1)] [In] bool fForceVerification, [MarshalAs(UnmanagedType.I1)] out bool fWasVerified); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall)] [return: MarshalAs(UnmanagedType.U4)] int StrongNameSignatureVerificationFromImage([In] IntPtr pbBase, [MarshalAs(UnmanagedType.U4)] [In] int dwLength, [MarshalAs(UnmanagedType.U4)] [In] int dwInFlags, [MarshalAs(UnmanagedType.U4)] out int dwOutFlags); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall)] int StrongNameTokenFromAssembly([MarshalAs(UnmanagedType.LPWStr)] [In] string pwzFilePath, out IntPtr ppbStrongNameToken, [MarshalAs(UnmanagedType.U4)] out int pcbStrongNameToken); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall)] int StrongNameTokenFromAssemblyEx([MarshalAs(UnmanagedType.LPWStr)] [In] string pwzFilePath, out IntPtr ppbStrongNameToken, [MarshalAs(UnmanagedType.U4)] out int pcbStrongNameToken, out IntPtr ppbPublicKeyBlob, [MarshalAs(UnmanagedType.U4)] out int pcbPublicKeyBlob); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall)] int StrongNameTokenFromPublicKey([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] [In] byte[] pbPublicKeyBlob, [MarshalAs(UnmanagedType.U4)] [In] int cbPublicKeyBlob, out IntPtr ppbStrongNameToken, [MarshalAs(UnmanagedType.U4)] out int pcbStrongNameToken); } ```
Checking an assembly for a strong name
[ "", "c#", "security", "strongname", "" ]
I'm starting to learn about using Memcached with PHP and I was wondering; is there a point at which you should start using it? Is it always more efficient to cache data or does it only become effective once your site gets a certain number of hits? Presumably there is an overhead associated with Memcached, so when does the speed benefit outweigh this? Thanks in advance for any advice.
You should start using memcached when not using it starts to affect your site / server. So when you just have 100 visitors a day and your site still responds quickly, don't bother using it. But when you have running times somewhere near 200ms or more per page, and the site feels slow too, you should look out for the bottlenecks using some PHP profiler (XDebug integrates one that you can use in combination with WinCacheGrind or KCacheGrind). Especially caching database requests should save you some load time.
The #1 rule when it comes to performance optimization is: Don't optimize until you need to! If you don't have performance problems, then you don't need to optimize. Other good rules include: * Don't optimize until you're done writing the application. You rarely know where real-world performance problems will crop up while developing, and it'll only make your code sloppier and more difficult to modify when you need to make a change down the road. * Use a profiler or some other way of measuring specific chunks of code to actually measure what's taking a long time, and optimize those sections. Don't just guess at what's taking a long time. Actually measure it.
When should you start using Memcached?
[ "", "php", "caching", "memcached", "" ]
HI All, I have a piece of javaScript that removes commas from a provided string (in my case currency values) It is: ``` function replaceCommaInCurrency(myField, val) { var re = /,/g; document.net1003Form.myField.value=val.replace(re, ''); } ``` 'MyField' was my attempt to dynamically have this work on any field that I pass in, but it doesn't work, I get errors saying 'MyField' is not valid. I sort of get my, but I thought this was valid. I am calling by using: onBlur="replaceCommaInCurrency(this.name, this.value);return false;" this.name and this.value are passing in the right values...field name and its value. How do I do this dynamically? -Jason
You can use eval to make your code snippet work: ``` eval("document.net1003Form." + myField + ".value=val.replace(re, '');"); ``` As mentioned below, the square brackets work (and don't suck like eval), stupid me for forgetting about those: ``` document.net1003Form[myField].value=val.replace(re, ''); ``` Alternatively, try something like this: ``` function replaceCommaInCurrency(field){ var re = /,/g; field.value = field.value.replace(re, ''); } ``` Which gets called like so: ``` onBlur="replaceCommaInCurrency(this); return false"; ``` You should consider using a javascript toolkit for things like this. You could set a class like "currency" on each input, then use this snippet of jQuery based Javascript to handle everything: ``` $(function(){ $("input.currency").bind('blur', function(){ this.value = $(this).val().replace(',', ''); }) }); ``` This code would fire on document ready, attach an event handler to each input with currency as its class, and then do the replacements. Note that you don't need a regex for replacement as well.
If you code it right into the markup like that, e.g. onblur="replaceCommaInCurrency(this)", the control originating the event gets passed as the parameter. Then you should be able to do something like: ``` myField.value = myField.value.replace(re, ''); ``` with jQuery: ``` var jqField = $(myField); jqField.val(jqField.val().replace(re, '')); ```
JavaScript: Dynamic Field Names
[ "", "javascript", "parsing", "" ]
What are the coolest examples of metaprogramming that you've seen in C++? What are some practical uses of metaprogramming that you've seen in C++?
Personally, I think [Boost.Spirit](http://www.boost.org/doc/libs/release/libs/spirit/doc/html/index.html) is a pretty amazing example of meta-programming. It's a complete parser generator that lets you express grammars using C++ syntax.
The most practical use of meta programming is turning a runtime error into a compile time error. Example: Lets call the interface IFoo. One of my programs dealt with a COM object that had multiple paths to IFoo (very complicated inheritance hierarchy). Unfortunately the underlying COM object implementation didn't realize they had multiple paths to IFoo. They assumed it was always the left most one. So inside their code, the following pattern was very common ``` void SomeMethod(IFoo* pFoo) { CFooImpl *p = (CFooImpl)pFoo; } ``` The second IFoo though caused the resulting "p" pointer to be completely invalid (multiple inheritance is dangerous). The long term solution was to have the COM object owner fix this issue. Short term though I needed to make sure that I always returned the correct IFoo. I could guarantee that I had the appropriate IFoo by using a QI and avoiding any implicit casts to IFoo. So I created a new CComPtr<> implementation and added the following override to the equal method. ``` template <typename T> CComPtr<T>& operator=(const T* pT) { // CComPTr Assign logic } template <> CComPtr<IFoo> operator=<IFoo>(const IFoo* pT) { COMPILE_ERROR(); } ``` This quickly revealed every single place I implicitly casted to IFoo.
What are the coolest examples of metaprogramming that you've seen in C++?
[ "", "c++", "templates", "metaprogramming", "template-meta-programming", "" ]
I have a base class with a property which (the get method) I want to overwrite in the subclass. My first thought was something like: ``` class Foo(object): def _get_age(self): return 11 age = property(_get_age) class Bar(Foo): def _get_age(self): return 44 ``` This does not work (subclass bar.age returns 11). I found a solution with an lambda expression which works: ``` age = property(lambda self: self._get_age()) ``` So is this the right solution for using properties and overwrite them in a subclass, or are there other preferred ways to do this?
I simply prefer to repeat the `property()` as well as you will repeat the `@classmethod` decorator when overriding a class method. While this seems very verbose, at least for Python standards, you may notice: 1) for read only properties, `property` can be used as a decorator: ``` class Foo(object): @property def age(self): return 11 class Bar(Foo): @property def age(self): return 44 ``` 2) in Python 2.6, [properties grew a pair of methods](http://docs.python.org/library/functions.html#property) `setter` and `deleter` which can be used to apply to general properties the shortcut already available for read-only ones: ``` class C(object): @property def x(self): return self._x @x.setter def x(self, value): self._x = value ```
I don't agree that the chosen answer is the ideal way to allow for overriding the property methods. If you expect the getters and setters to be overridden, then you can use lambda to provide access to self, with something like `lambda self: self.<property func>`. This works (at least) for Python versions 2.4 to 3.6. If anyone knows a way to do this with by using property as a decorator instead of as a direct property() call, I'd like to hear it! Example: ``` class Foo(object): def _get_meow(self): return self._meow + ' from a Foo' def _set_meow(self, value): self._meow = value meow = property(fget=lambda self: self._get_meow(), fset=lambda self, value: self._set_meow(value)) ``` This way, an override can be easily performed: ``` class Bar(Foo): def _get_meow(self): return super(Bar, self)._get_meow() + ', altered by a Bar' ``` so that: ``` >>> foo = Foo() >>> bar = Bar() >>> foo.meow, bar.meow = "meow", "meow" >>> foo.meow "meow from a Foo" >>> bar.meow "meow from a Foo, altered by a Bar" ``` I discovered this on [geek at play](http://www.kylev.com/2004/10/13/fun-with-python-properties/ "omg it's ancient!").
python properties and inheritance
[ "", "python", "inheritance", "properties", "polymorphism", "" ]
I am trying to get pylons to debug in Eclipse under Ubuntu. Specifically. I am not sure what to use for the 'Main Module' on the Run configurations dialog. ([this](https://stackoverflow.com/questions/147650/debug-pylons-application-through-eclipse) is a similar question on stackoverflow, but I think it applies to windows as I can't find paster-script.py on my system) Can anyone help?
I've managed to fix this now. In `Window>Preferences>Pydev>Interpreter-Python` remove the python interpreter and reload it (select `New`) after installing pylons. In the Terminal cd into the projects directory. Then type `sudo python setup.py develop` Not sure what this does, but it does the trick (if any one wants to fill me in, please do) In `Run>Open Debug Dialog` enter the location of paster in `Main Module`. For me this is `/usr/bin/paster` . Then in the `Arguments` tab in `Program arguments` enter `serve /locationOfYourProject/development.ini` All set to go. It took a lot of search for me to find out that it does not work if the arguments includes `--reload`
I got it running basically almost the same way - although you do not have to do the setup.py develop step - it works fine without that. What it does is that is sets global link to your project directory for a python package named after your project name.
Debugging pylons in Eclipse under Ubuntu
[ "", "python", "eclipse", "debugging", "ubuntu", "pylons", "" ]
A PHP array can have arrays for its elements. And those arrays can have arrays and so on and so forth. Is there a way to find out the maximum nesting that exists in a PHP array? An example would be a function that returns 1 if the initial array does not have arrays as elements, 2 if at least one element is an array, and so on.
This should do it: ``` <?php function array_depth(array $array) { $max_depth = 1; foreach ($array as $value) { if (is_array($value)) { $depth = array_depth($value) + 1; if ($depth > $max_depth) { $max_depth = $depth; } } } return $max_depth; } ?> ``` Edit: Tested it very quickly and it appears to work.
Here's another alternative that avoids the problem Kent Fredric pointed out. It gives [print\_r()](http://php.net/print_r) the task of checking for infinite recursion (which it does well) and uses the indentation in the output to find the depth of the array. ``` function array_depth($array) { $max_indentation = 1; $array_str = print_r($array, true); $lines = explode("\n", $array_str); foreach ($lines as $line) { $indentation = (strlen($line) - strlen(ltrim($line))) / 4; if ($indentation > $max_indentation) { $max_indentation = $indentation; } } return ceil(($max_indentation - 1) / 2) + 1; } ```
Is there a way to find out how "deep" a PHP array is?
[ "", "php", "arrays", "associative-array", "" ]