Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
A long time ago when I was a young lat I used to do a lot of assembler and optimization programming. Today I mainly find myself building web apps (it's alright too...). However, whenever I create fields for database tables I find myself using values like 16, 32 & 128 for text fields and I try to combine boolean values into SET data fields. Is giving a text field a length of 9 going to make my database slower in the long run and do I actually help it by specifying a field length that is more easy memory aligned?
Database optimization is quite unlike machine code optimization. With databases, most of the time you want to reduce disk I/O, and wastefully trying to align fields will only make less records fit in a disk block/page. Also, if any alignment is beneficial, the database engine will do it for you automatically. What will matter most is indexes and how well you use them. Trying tricks to pack more information in less space can easily end up making it harder to have good indexes. (Do not overdo it, however; not only do indexes slow down INSERTs and UPDATEs to indexed columns, they also mean more work for the planner, which has to consider all the possibilities.) Most databases have an EXPLAIN command; try using it on your selects (in particular, the ones with more than one table) to get a feel for how the database engine will do its work.
The size of the field itself may be important, but usually for text if you use nvarchar or varchar it is not a big deal. Since the DB will take what you use. the follwoing will have a greater impact on your SQL speed: don't have more columns then you need. bigger table in terms of columns means the database will be less likely to find the results for your queries on the same disk page. Notice that this is true even if you only ask for 2 out of 10 columns in your select... (there is one way to battle this, with clustered indexes but that can only address one limited scenario). you should give more details on the type of design issues/alternatives you are considering to get additional tips.
Is there any performance reason to use powers of two for field sizes in my database?
[ "", "sql", "database", "optimization", "" ]
The IT department of a subsidiary of ours had a consulting company write them an ASP.NET application. Now it's having intermittent problems with mixing up who the current user is and has been known to show Joe some of Bob's data by mistake. The consultants were brought back to troubleshoot and we were invited to listen in on their explanation. Two things stuck out. First, the consultant lead provided this pseudo-code: ``` void MyFunction() { Session["UserID"] = SomeProprietarySessionManagementLookup(); Response.Redirect("SomeOtherPage.aspx"); } ``` He went on to say that the assignment of the session variable is asynchronous, which seemed untrue. Granted the call into the lookup function could do something asynchronously, but this seems unwise. Given that alleged asynchronousness, his theory was that the session variable was not being assigned before the redirect's inevitable ThreadAbort exception was raised. This faulure then prevented SomeOtherPage from displaying the correct user's data. Second, he gave an example of a coding best practice he recommends. Rather than writing: ``` int MyFunction(int x, int x) { try { return x / y; } catch(Exception ex) { // log it throw; } } ``` the technique he recommended was: ``` int MyFunction(int x, int y, out bool isSuccessful) { isSuccessful = false; if (y == 0) return 0; isSuccessful = true; return x / y; } ``` This will certainly work and could be better from a performance perspective in some situations. However, from these and other discussion points it just seemed to us that this team was not well-versed technically. Opinions?
I would agree. These guys seem quite incompetent. (BTW, I'd check to see if in "SomeProprietarySessionManagementLookup," they're using static data. Saw this -- with behavior *exactly as you describe* on a project I inherited several months ago. It was a total head-slap moment when we finally saw it ... And wished we could get face to face with the guys who wrote it ... )
Rule of thumb: If you need to ask if a consultant knows what he's doing, he probably doesn't ;) And I tend to agree here. Obviously you haven't provided much, but they don't seem terribly competent.
Does This ASP.NET Consultant Know What He's Doing?
[ "", "c#", "asp.net", "exception", "session-variables", "" ]
I'm pretty sure there should be a more Pythonic way of doing this - but I can't think of one: How can I merge a two-dimensional list into a one-dimensional list? Sort of like zip/map but with more than two iterators. Example - I have the following list: ``` array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] ``` I want to have ``` result = [12, 15, 18] # [1+4+7, 2+5+8, 3+6+9] ``` So far what I've come up with is: ``` def add_list(array): number_items = len(array[0]) result = [0] * number_items for index in range(number_items): for line in array: result[index] += line[index] return result ``` But that doesn't look very elegant/Pythonic to me. Aside from not checking if all the "lines" in the 2D array are of the same length, can be added to each other, etc. What would be a better way to do it?
``` [sum(a) for a in zip(*array)] ```
[sum(value) for value in zip(\*array)] is pretty standard. This might help you understand it: ``` In [1]: array=[[1, 2, 3], [4, 5, 6], [7, 8, 9]] In [2]: array Out[2]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] In [3]: *array ------------------------------------------------------------ File "<ipython console>", line 1 *array ^ <type 'exceptions.SyntaxError'>: invalid syntax ``` *The unary star is not an operator by itself. It unwraps array elements into arguments into function calls.* ``` In [4]: zip(*array) Out[4]: [(1, 4, 7), (2, 5, 8), (3, 6, 9)] ``` *zip() is a built-in function* ``` In [5]: zip(*array)[0] Out[5]: (1, 4, 7) ``` *each element for the list returned by zip is a set of numbers you want.* ``` In [6]: sum(zip(*array)[0]) Out[6]: 12 In [7]: [sum(values) for values in zip(*array)] Out[7]: [12, 15, 18] ```
Merging/adding lists in Python
[ "", "python", "list", "" ]
I want to find out if length property for Java arrays is an int/long or something else.
It is an int. See the [Java Language Specification](http://java.sun.com/docs/books/jls/third_edition/html/arrays.html#10.7), section 10.7.
In [Java Language spec, Arrays](http://java.sun.com/docs/books/jls/third_edition/html/arrays.html) you can see in 10.4: > Arrays must be indexed by int values; > short, byte, or char values may also > be used as index values because they > are subjected to unary numeric > promotion and become int values. > An attempt to access an array > component with a long index value > results in a compile-time error. I could not find the type of the length attribute, but it is at least an int; and if it's a long then you can not access elements beyond the max integer length. So I guess it's a (final) int.
What is the data type for length property for Java arrays?
[ "", "java", "types", "limits", "" ]
I have a large collection of static 'Utility' classes that contain very generic static methods. For example, I have a CollectionUtility class that has useful methods like: public static void RemoveDuplicates(ICollection collection)... etc With C# 3.0 I've been converting these to extension methods. Now, I've heard some talk that in an 'enterprise level' application it is often considered best practice to avoid large libraries of these static classes and methods. I imagine that it could get quite hard to maintain. A question for those of you who work on large enterprise projects for large companies - do you maintain libraries of utility classes like these or not? What do you?
You're talking about code that would be shared library stuff. Static methods do have a place in shared libs. Check out System.Linq.Enumerable I'd follow these guidelines: * These aren't static methods by default. They should only be static methods because they are naturally stateless (behavior only depend on parameters). If they aren't naturally stateless, then you should be making a proper class to manage that state. * Cover these with Unit Tests. If you don't Unit Test anything else, Unit Test these. This should be very very easy to do. If this isn't easy, this isn't right. If dependency injection is something you like, you can still have it. Code that relies on a static method could instead be calling a Func(T, U) or an Action that references that static method.
> I've heard some talk that in an 'enterprise level' application it is often considered best practice to avoid large libraries of these static classes and methods. I imagine that it could get quite hard to maintain. IMHO you should apply things like generics to cut down on the size of your utility methods/libraries, and if you only use a utility method in one place, then it doesn't belong in a shared library, but at the end of the day you're still likely to have quite a lot. At any rate, this perplexes me. If you didn't put them in a shared library where would you put them? Copy/paste into each project or something daft like that?
Alternative to libraries of static classes
[ "", "c#", "class", "static", "" ]
What are some good templating engines for web designers? I definitely have my preferences as to what I'd prefer to work with as a programmer. But web designers seem to have a different way of thinking about things and thus may prefer a different system. So: * Web designers: what templating engine do you prefer to work with? * programmers: what templating engines have you worked with that made working with web designers easy?
Look at [Mako](http://www.makotemplates.org/). Here's how I cope with web designers. 1. Ask them to mock up the page. In HTML. 2. Use the HTML as the basis for the template, replacing the mocked-up content with `${...}` replacements. 3. Fold in loops to handle repeats. The use of if-statements requires negotiation, since the mock-up is one version of the page, and there are usually some explanations for conditional presentation of some material.
I had good votes when [answering this same question's duplicate](https://stackoverflow.com/questions/98245/what-is-your-single-favorite-python-templating-engine#98285). My answer was: [Jinja2](http://jinja.pocoo.org/2 "Jinja2 homepage"). Nice [syntax](http://jinja.pocoo.org/2/documentation/templates "template syntax doc"), good [customization possibilities](http://jinja.pocoo.org/2/documentation/extensions.html "Extending Jinja2"). Integrates well. Can be sandboxed, so you don't have to trust completely your template authors. (Mako can't). It is also pretty fast, with the bonus of compiling your template to bytecode and cache it, as in the demonstration below: ``` >>> import jinja2 >>> print jinja2.Environment().compile('{% for row in data %}{{ row.name | upper }}{% endfor %}', raw=True) from __future__ import division from jinja2.runtime import LoopContext, Context, TemplateReference, Macro, Markup, TemplateRuntimeError, missing, concat, escape, markup_join, unicode_join name = None def root(context, environment=environment): l_data = context.resolve('data') t_1 = environment.filters['upper'] if 0: yield None for l_row in l_data: if 0: yield None yield unicode(t_1(environment.getattr(l_row, 'name'))) blocks = {} debug_info = '1=9' ``` This code has been generated on the fly by Jinja2. Of course the compiler optmizes it further (e.g. removing `if 0: yield None`)
Python templates for web designers
[ "", "python", "templating", "" ]
What is the prefered method for creating a byte array from an input stream? Here is my current solution with .NET 3.5. ``` Stream s; byte[] b; using (BinaryReader br = new BinaryReader(s)) { b = br.ReadBytes((int)s.Length); } ``` Is it still a better idea to read and write chunks of the stream?
It really depends on whether or not you can trust `s.Length`. For many streams, you just don't know how much data there will be. In such cases - and before .NET 4 - I'd use code like this: ``` public static byte[] ReadFully(Stream input) { byte[] buffer = new byte[16*1024]; using (MemoryStream ms = new MemoryStream()) { int read; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } return ms.ToArray(); } } ``` With .NET 4 and above, I'd use [`Stream.CopyTo`](https://msdn.microsoft.com/en-us/library/system.io.stream.copyto), which is basically equivalent to the loop in my code - create the `MemoryStream`, call `stream.CopyTo(ms)` and then return `ms.ToArray()`. Job done. I should perhaps explain why my answer is longer than the others. [`Stream.Read`](http://msdn.microsoft.com/en-us/library/system.io.stream.read.aspx) doesn't guarantee that it will read everything it's asked for. If you're reading from a network stream, for example, it may read one packet's worth and then return, even if there will be more data soon. [`BinaryReader.Read`](http://msdn.microsoft.com/en-us/library/system.io.binaryreader.read.aspx) will keep going until the end of the stream or your specified size, but you still have to know the size to start with. The above method will keep reading (and copying into a `MemoryStream`) until it runs out of data. It then asks the `MemoryStream` to return a copy of the data in an array. If you know the size to start with - or *think* you know the size, without being sure - you can construct the `MemoryStream` to be that size to start with. Likewise you can put a check at the end, and if the length of the stream is the same size as the buffer (returned by [`MemoryStream.GetBuffer`](http://msdn.microsoft.com/en-us/library/system.io.memorystream.getbuffer.aspx)) then you can just return the buffer. So the above code isn't quite optimised, but will at least be correct. It doesn't assume any responsibility for closing the stream - the caller should do that. See [this article](https://jonskeet.uk/csharp/readbinary.html) for more info (and an alternative implementation).
While Jon's answer is correct, he is rewriting code that already exists in `CopyTo`. So for .Net 4 use Sandip's solution, but for previous version of .Net use Jon's answer. Sandip's code would be improved by use of "using" as exceptions in `CopyTo` are, in many situations, quite likely and would leave the `MemoryStream` not disposed. ``` public static byte[] ReadFully(Stream input) { using (MemoryStream ms = new MemoryStream()) { input.CopyTo(ms); return ms.ToArray(); } } ```
Creating a byte array from a stream
[ "", "c#", ".net-3.5", "inputstream", "" ]
I am wondering how I can break up my index.php homepage to multiple php pages (i.e. header.php, footer.php) and build a working index.php page using those separate php pages. I know WordPress uses this with different functions like: ``` GetHeader(); GetFoodter(); ``` But when I tried to use those functions, it errors. I am guessing they are not native functions to PHP. What would I need to do to get this functionality?
``` include 'header.php'; include 'footer.php'; ```
Go with an MVC framework like Zend's. That way you'll keep more maintainable code.
Breaking up PHP Websites
[ "", "php", "" ]
When you lock an object is that object locked throughout the whole application? For Example, this snippet from C# 3.0 in a Nutshell Section 19.6.1 "Thread Safety and .NET Framework Types": ``` static void AddItems( ) { for (int i = 0; i < 100; i++) lock (list) list.Add ("Item " + list.Count); string[] items; lock (list) items = list.ToArray( ); foreach (string s in items) Console.WriteLine (s); } ``` Does the first lock: ``` lock (list) list.Add ("Item " + list.Count); ``` prevent another thread from accessing: ``` lock (list) items = list.ToArray( ); ``` or can both be executed at the same time? And does the CLR automatically make your static methods thread safe? Or is that up to the developer? Thanks, John
``` class UsefulStuff { object _TheLock = new object { }; public void UsefulThingNumberOne() { lock(_TheLock) { //CodeBlockA } } public void UsefulThingNumberTwo() { lock(_TheLock) { //CodeBlockB } } } ``` `CodeBlockA` and `CodeBlockB` are prevented from executing at the same time in different threads, because they are both locked on the same object instance `_TheLock`. The methods on `_TheLock` itself are completely unaffected.
One other thing to note is that static constructors ARE executed in a threadsafe way by the runtime. If you are creating a singleton and declare it as: ``` public class Foo { private static Foo instance = new Foo(); public static Foo Instance { get { return instance; } } } ``` Then it will be threadsafe. If however, you instantiate a new Foo **inside** the Instance getter, then you would need to write your own thread safety (ie. lock an object)
Does the lock(objlocker) make that object thread safe app wide? And are static members automatically thread safe?
[ "", "c#", "multithreading", "thread-safety", "static-members", "" ]
I have a PHP script that sends critical e-mails. I know how to check whether the e-mail was sent successfully. However, is there a way to verify whether the e-mail reached its destination?
If you make the email HTML based, you can include images in it which contain URLs with information unique to the recipient. You could structure your application so that these URLs trigger some code to mark that particular email as read before returning the required image data. To be totally effective, the images would have to form a key part of the email, so that the recipient *has* to make their email client grab the images. You could also make the plain text part of the email just contain a URL to retrieve the full message, again allowing you to track receipt. How far you take these ideas depends on *why* you need to know it's been read and to what extent you want to potentially annoy the recipient with an email they can't cut'n'paste, read easily on mobile device, listen to with a screenreader, etc...
Delivery Status Notification is the usual way: [http://www.sendmail.org/~ca/email/dsn.html](http://www.sendmail.org/%7Eca/email/dsn.html) You can't tell if an email is read unless you use that microsoft email thing and the reader has not disabled read receipts. Edit: I haven't progressed to HTML email yet so I never considered that for a read notification.
Is there a way to determine whether an e-mail reaches its destination?
[ "", "php", "error-handling", "email", "error-detection", "" ]
How can I get Environnment variables and if something is missing, set the value?
Use the [System.Environment](https://learn.microsoft.com/en-us/dotnet/api/system.environment) class. The methods ``` var value = System.Environment.GetEnvironmentVariable(variable [, Target]) ``` and ``` System.Environment.SetEnvironmentVariable(variable, value [, Target]) ``` will do the job for you. The optional parameter `Target` is an enum of type `EnvironmentVariableTarget` and it can be one of: `Machine`, `Process`, or `User`. If you omit it, the default target is the **current process.**
***Get and Set*** **Get** ``` string getEnv = Environment.GetEnvironmentVariable("envVar"); ``` **Set** ``` string setEnv = Environment.SetEnvironmentVariable("envvar", varEnv); ```
How do I get and set Environment variables in C#?
[ "", "c#", ".net", ".net-2.0", "environment-variables", "" ]
I have a gridview like below: ``` <asp:GridView DataKeyNames="TransactionID" AllowSorting="True" AllowPaging="True"ID="grvBrokerage" runat="server" AutoGenerateColumns="False" CssClass="datatable" Width="100%" <Columns> <asp:BoundField DataField="BrkgAccountNameOutput" HeaderText="Account Name"/> <asp:BoundField DataField="TransactionAmount" HeaderText="Transaction Amount" SortExpression="TransactionAmount" /> <asp:BoundField DataField="TransType" HeaderText="Transaction Type" SortExpression="TransType"/> <asp:BoundField DataField="AccountBalance" HeaderText="Account Balance"/> <asp:BoundField DataField="CreateDt" HeaderText="Transaction Date" /> </Columns> </asp:GridView> ``` I have a page with a gridview and a objectdatasource control. AllowPaging and AllowSorting is enabled. Here is the method I use that gets the data and binds the objectdatasource to the grid: ``` protected void BindBrokerageDetails() { HomePage master = (HomePage)Page.Master; BrokerageAccount brokerageAccount = new BrokerageAccount(); brokerageAccount.UserID = new Guid(Membership.GetUser().ProviderUserKey.ToString()); ddlBrokerageDetails.DataSource = brokerageAccount.GetAll(); ddlBrokerageDetails.DataTextField = "Account Name"; ddlBrokerageDetails.DataValueField = "Account Name"; ddlBrokerageDetails.DataBind(); if (ddlBrokerageDetails.Items.Count > 0) { BrokerageTransactions brokerageaccountdetails = new BrokerageTransactions(); DataSet ds = BrokerageAccount.GetBrkID2( new Guid(Membership .GetUser() .ProviderUserKey .ToString()), ddlBrokerageDetails .SelectedItem .Text .ToString()); foreach (DataRow dr in ds.Tables[0].Rows) { brokerageaccountdetails.BrokerageId = new Guid(dr["BrkrgId"].ToString()); } ddlBrokerageDetails.SelectedItem.Value = brokerageaccountdetails.BrokerageId.ToString(); grvBrokerage.DataSource = ObjectDataSource1; grvBrokerage.DataBind(); } } ``` I have a sorting event, but when I check the grvBrokerage.DataSource, it is null. I am curious as to why? Here is the code for that? ``` protected void grvBrokerage_Sorting(object sender, GridViewSortEventArgs e) { DataTable dt = grvBrokerage.DataSource as DataTable; if (dt != null) { DataView dv = new DataView(dt); dv.Sort = e.SortExpression + " " + e.SortDirection; grvBrokerage.DataSource = dv; grvBrokerage.DataBind(); } } ``` Here is the ObjectDataSource declaration: ``` <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetAllWithId" TypeName="BrokerageTransactions"> <SelectParameters> <asp:ControlParameter ControlID="ddlBrokerageDetails" Name="brokid" PropertyName="SelectedValue" Type="Object" /> </SelectParameters> </asp:ObjectDataSource> ``` Thanks, X
When you are using an ObjectDataSource (or any other \*DataSource), you set the DataSourceID for your GridView, not the DataSource. The DataSourceID should be whatever the ID of your ObjectDataSource is. If you provide the declaration of your ObjectDataSource, I might be able to help more. As to why your DataSource is null in your Sorting event, it's because you set the DataSource, sent the page to the client, clicked on a column header, posted back to the server, and now have a brand new GridView instance that has never had its DataSource property set. The old GridView instance (and the data table you bound to) have been thrown away.
Your datasource no longer exists when you're posting back. Try creating your datasources in your Page\_Init function, then hooking your gridview up to it. Has always worked for me (Using SQLDataSources). EDIT: Alternatively, you could re-create your datasource for the grid on each postback. That might work. EDIT2: Or, you could save your DataSource to the ViewState (If it's not that large), then reset the grid to whatever datasource is in the viewstate on postback (again, I stress that the dataset not be magnificently large or else you'll have slow load times)
Sorting a GridView with an ObjectDataSource is not Sorting
[ "", "c#", "asp.net", "" ]
Given a class instance, is it possible to determine if it implements a particular interface? As far as I know, there isn't a built-in function to do this directly. What options do I have (if any)?
``` interface IInterface { } class TheClass implements IInterface { } $cls = new TheClass(); if ($cls instanceof IInterface) { echo "yes"; } ``` You can use the "instanceof" operator. To use it, the left operand is a class instance and the right operand is an interface. It returns true if the object implements a particular interface. Reference: <https://www.php.net/manual/en/language.operators.type.php#example-124>
As [therefromhere](https://stackoverflow.com/users/8331/therefromhere) points out, you can use `class_implements()`. Just as with Reflection, this allows you to specify the class name as a string and doesn't require an instance of the class: ``` interface IInterface { } class TheClass implements IInterface { } $interfaces = class_implements('TheClass'); if (isset($interfaces['IInterface'])) { echo "Yes!"; } ``` `class_implements()` is part of the SPL extension. See: <http://php.net/manual/en/function.class-implements.php> # Performance Tests Some simple performance tests show the costs of each approach: ## Given an instance of an object ``` Object construction outside the loop (100,000 iterations) ____________________________________________ | class_implements | Reflection | instanceOf | |------------------|------------|------------| | 140 ms | 290 ms | 35 ms | '--------------------------------------------' Object construction inside the loop (100,000 iterations) ____________________________________________ | class_implements | Reflection | instanceOf | |------------------|------------|------------| | 182 ms | 340 ms | 83 ms | Cheap Constructor | 431 ms | 607 ms | 338 ms | Expensive Constructor '--------------------------------------------' ``` ## Given only a class name ``` 100,000 iterations ____________________________________________ | class_implements | Reflection | instanceOf | |------------------|------------|------------| | 149 ms | 295 ms | N/A | '--------------------------------------------' ``` Where the expensive \_\_construct() is: ``` public function __construct() { $tmp = array( 'foo' => 'bar', 'this' => 'that' ); $in = in_array('those', $tmp); } ``` These tests are based on [this simple code](http://pastebin.com/2xftNXip).
Checking if an instance's class implements an interface?
[ "", "php", "interface", "oop", "" ]
ok so my issue is i have the string '\222\222\223\225' which is stored as latin-1 in the db. What I get from django (by printing it) is the following string, 'ââââ¢' which I assume is the UTF conversion of it. Now I need to pass the string into a function that does this operation: ``` strdecryptedPassword + chr(ord(c) - 3 - intCounter - 30) ``` I get this error: > chr() arg not in range(256) If I try to encode the string as latin-1 first I get this error: > 'latin-1' codec can't encode characters in position 0-3: ordinal not > in range(256) I have read a bunch on how character encoding works, and there is something I am missing because I just don't get it!
Your first error 'chr() arg not in range(256)' probably means you have underflowed the value, because chr cannot take negative numbers. I don't know what the encryption algorithm is supposed to do when the inputcounter + 33 is more than the actual character representation, you'll have to check what to do in that case. About the second error. you must decode() and not encode() a regular string object to get a proper representation of your data. encode() takes a unicode object (those starting with u') and generates a regular string to be output or written to a file. decode() takes a string object and generate a unicode object with the corresponding code points. This is done with the unicode() call when generated from a string object, you could also call a.decode('latin-1') instead. ``` >>> a = '\222\222\223\225' >>> u = unicode(a,'latin-1') >>> u u'\x92\x92\x93\x95' >>> print u.encode('utf-8') ÂÂÂÂ >>> print u.encode('utf-16') ÿþ >>> print u.encode('latin-1') >>> for c in u: ... print chr(ord(c) - 3 - 0 -30) ... q q r t >>> for c in u: ... print chr(ord(c) - 3 -200 -30) ... Traceback (most recent call last): File "<stdin>", line 2, in <module> ValueError: chr() arg not in range(256) ```
As Vinko notes, Latin-1 or ISO 8859-1 doesn't have printable characters for the octal string you quote. According to my notes for 8859-1, "C1 Controls (0x80 - 0x9F) are from ISO/IEC 6429:1992. It does not define names for 80, 81, or 99". The code point names are as Vinko lists them: ``` \222 = 0x92 => PRIVATE USE TWO \223 = 0x93 => SET TRANSMIT STATE \225 = 0x95 => MESSAGE WAITING ``` The correct UTF-8 encoding of those is (Unicode, binary, hex): ``` U+0092 = %11000010 %10010010 = 0xC2 0x92 U+0093 = %11000010 %10010011 = 0xC2 0x93 U+0095 = %11000010 %10010101 = 0xC2 0x95 ``` The LATIN SMALL LETTER A WITH CIRCUMFLEX is ISO 8859-1 code 0xE2 and hence Unicode U+00E2; in UTF-8, that is %11000011 %10100010 or 0xC3 0xA2. The CENT SIGN is ISO 8859-1 code 0xA2 and hence Unicode U+00A2; in UTF-8, that is %11000011 %10000010 or 0xC3 0x82. So, whatever else you are seeing, you do not seem to be seeing a UTF-8 encoding of ISO 8859-1. All else apart, you are seeing but 5 bytes where you would have to see 8. *Added*: The previous part of the answer addresses the 'UTF-8 encoding' claim, but ignores the rest of the question, which says: ``` Now I need to pass the string into a function that does this operation: strdecryptedPassword + chr(ord(c) - 3 - intCounter - 30) I get this error: chr() arg not in range(256). If I try to encode the string as Latin-1 first I get this error: 'latin-1' codec can't encode characters in position 0-3: ordinal not in range(256). ``` You don't actually show us how intCounter is defined, but if it increments gently per character, sooner or later '`ord(c) - 3 - intCounter - 30`' is going to be negative (and, by the way, why not combine the constants and use '`ord(c) - intCounter - 33`'?), at which point, `chr()` is likely to complain. You would need to add 256 if the value is negative, or use a modulus operation to ensure you have a positive value between 0 and 255 to pass to `chr()`. Since we can't see how intCounter is incremented, we can't tell if it cycles from 0 to 255 or whether it increases monotonically. If the latter, then you need an expression such as: ``` chr(mod(ord(c) - mod(intCounter, 255) + 479, 255)) ``` where 256 - 33 = 223, of course, and 479 = 256 + 223. This guarantees that the value passed to `chr()` is positive and in the range 0..255 for any input character c and any value of intCounter (and, because the `mod()` function never gets a negative argument, it also works regardless of how `mod()` behaves when its arguments are negative).
UTF-8 latin-1 conversion issues, python django
[ "", "python", "django", "utf-8", "character-encoding", "" ]
I plan to use PyInstaller to create a stand-alone python executable. PythonInstaller comes with built-in support for UPX and uses it to compress the executable but they are still really huge (about 2,7 mb). Is there any way to create even smaller Python executables? For example using a shrinked python.dll or something similiar?
If you recompile pythonxy.dll, you can omit modules that you don't need. Going by size, stripping off the unicode database and the CJK codes creates the largest code reduction. This, of course, assumes that you don't need these. Remove the modules from the pythoncore project, and also remove them from PC/config.c
Using a earlier Python version will also decrease the size considerably if your really needing a small file size. I don't recommend using a very old version, Python2.3 would be the best option. I got my Python executable size to 700KB's! Also I prefer Py2Exe over Pyinstaller.
Tiny python executable?
[ "", "python", "executable", "pyinstaller", "" ]
currently i have jdbc code with the following basic stucture: get Connection (do the next 4 lines several times, never closing statement) get statement get result set process result set close result set close connection It occurred to me after writing this code that i need to close the statement. 1 what are the effects of not closing the statement. 2 will the following work, this si will closing the statement prevent me from processing the result set as normal? get Connection (do the next 5 lines several times) get statement get result set close statement process result set close result set close connection
The answer depends on your JDBC driver unfortunately. What you wrote there might work. However, the general rule is that you close your statement only when you are done with the corresponding resultset. EDIT: I realize that you had a second question where you asked about the effects of not closing the statements/Resultsets and so on. The effects also depend on your JDBC driver but, it could lead to significant resource leaks.
The close behavior is specified in the [JDBC Specification](http://jcp.org/aboutJava/communityprocess/final/jsr221/index.html). Closing the Connection releases all JDBC resources associated with the connection and will implicitly close all Statements, ResultSets, etc. Closing the statement will close the ResultSets. Example 2 is not guaranteed to work. The statement should be closed AFTER the ResultSet has been used. The spec says that you should get an SQLException if you try to use that ResultSet (some JDBC drivers don't follow the spec strictly--and MS is not biggest offender). If you forget to close a ResultSet or Statement, the worse case that happens is you consume database and JVM resources for longer than necessary. On a resource constrained or high load system, this could cause memory/connection/resource errors or reduced performance.
jdbc: when can i close what
[ "", "java", "database", "jdbc", "" ]
I have heard that closures could be introduced in the next Java standard that is scheduled to be released somewhere around next summer. What would this syntax look like? I read somewhere that introducing closures in java is a bigger change than generic was in java 5. Is this true? pros and cons? (By now we definitely know that closures not will be included in the next Java release) OR **edit: <http://puredanger.com/tech/2009/11/18/closures-after-all/> :D** **edit2: Re-thinking JDK7: <http://blogs.oracle.com/mr/entry/rethinking_jdk7>** **edit3: There’s not a moment to lose!: <http://blogs.oracle.com/mr/entry/quartet>**
Have a look at <http://www.javac.info/> . It seems like this is how it would look: ``` boolean even = { int x => x % 2 == 0 }.invoke(15); ``` where the `{ int x => x % 2 == 0 }` bit is the closure.
It really depends on what gets introduced, and indeed *whether* it will be introduced at all. There are a number of closure proposals of varying sizes. See [Alex Miller's Java 7 page](http://tech.puredanger.com/java7#closures) for the proposals and various blog posts. Personally I'd love to see closures - they're [beautiful and incredibly helpful](http://csharpindepth.com/Articles/Chapter5/Closures.aspx) - but I fear that some of the proposals are pretty hairy.
Closures in Java 7
[ "", "java", "syntax", "closures", "java-7", "" ]
I have a page where search resuts are shown both in a grid and on a map (using KML generated on the fly, overlaid on an embedded Google map). I've wired this up to work as the user types; here's the skeleton of my code, which works: ``` $(function() { // Wire up search textbox $('input.Search').bind("keyup", update); }); update = function(e) { // Get text from search box // Pass to web method and bind to concessions grid $.ajax({ ... success: function(msg) { displayResults(msg, filterParams); }, }); } displayResults = function(msg, filterParams) { // Databind results grid using jTemplates // Show results on map: Pass parameters to KML generator and overlay on map } ``` Depending on the search, there may be hundreds of results; and so the work that happens in `displayResults` is processor-intensive both on the server (querying the database, building and simplifying the KML on the fly) and on the client (databinding the results grid, overlaying big KML files on the map). I like the immediacy of getting progressively narrower results as I type, but I'd like to minimize the number of times this refreshes. What's the simplest way to introduce an N-second delay after the user stops typing, before running the `update` function?
Instead of calling `update()` directly, call a wrapper that checks to see if there are any pending delayed updates: ``` $('input.Search').bind("keyup", delayedUpdate); function delayedUpdate() { if (updatePending) { clearTimeout(updatePending); } updatePending = setTimeout(update, 250); } function update() { updatePending = false; //$.ajax(... } ``` You should also probably add: ``` $('input.Search').bind("blur", update); ``` This will do an immediate update when the user leaves the field. But make sure you also add handling for the case where the user leaves the field while there's a pending delayed update (cancel the delayed update first).
As a first approach, what about something like : ``` $('input.Search').bind("keyup", function() { setTimeout(update, 5) } ); ``` (not sure about the exact setTimeout syntax). You can also keep a variable to track whether the timeout has already been scheduled or not.
How do I set up a timer to prevent overlapping ajax calls?
[ "", "javascript", "jquery", "" ]
I want to get a type of a "BasePage" object that I am creating. Every Page object is based off BasePage. For instance, I have a Login.aspx and in my code-behind and a class that has a method Display: ``` Display(BasePage page) { ResourceManager manager = new ResourceManager(page.GetType()); } ``` In my project structure I have a default resource file and a psuedo-translation resource file. If I set try something like this: ``` Display(BasePage page) { ResourceManager manager = new ResourceManager(typeof(Login)); } ``` it returns the translated page. After some research I found that page.GetType().ToString() returned something to the effect of "ASP\_login.aspx" How can I get the actual code behind class type, such that I get an object of type "Login" that is derived from "BasePage"? Thanks in advance!
If your code-beside looks like this: ``` public partial class _Login : BasePage { /* ... */ } ``` Then you would get the `Type` object for it with *`typeof(_Login)`*. To get the type dynamically, you can find it recursively: ``` Type GetCodeBehindType() { return getCodeBehindTypeRecursive(this.GetType()); } Type getCodeBehindTypeRecursive(Type t) { var baseType = t.BaseType; if (baseType == typeof(BasePage)) return t; else return getCodeBehindTypeRecursive(baseType); } ```
After some additional research I found that if I call Page.GetType().BaseType it returns the code-behind type of the Aspx page.
ASP.Net and GetType()
[ "", "c#", "asp.net", "reflection", "resourcemanager", "" ]
For instance in the snippet below - how do I access the h1 element knowing the ID of parent element (header-inner div)? ``` <div id='header-inner'> <div class='titlewrapper'> <h1 class='title'> Some text I want to change </h1> </div> </div> ``` Thanks!
``` function findFirstDescendant(parent, tagname) { parent = document.getElementById(parent); var descendants = parent.getElementsByTagName(tagname); if ( descendants.length ) return descendants[0]; return null; } var header = findFirstDescendant("header-inner", "h1"); ``` Finds the element with the given ID, queries for descendants with a given tag name, returns the first one. You could also loop on `descendants` to filter by other criteria; if you start heading in that direction, i recommend you check out a pre-built library such as jQuery (will save you a good deal of time writing this stuff, it gets somewhat tricky).
If you were to use [jQuery](http://jquery.com/) as mentioned by some posters, you can get access to the element very easily like so (though technically this would return a collection of matching elements if there were more than one H1 descendant): ``` var element = $('#header-inner h1'); ``` Using a library like JQuery makes things like this trivial compared to the normal ways as mentioned in other posts. Then once you have a reference to it in a jQuery object, you have even more functions available to easily manipulate its content and appearance.
How to access HTML element without ID?
[ "", "javascript", "dom", "xhtml", "" ]
I'm working through some homework and a question on a previous exam paper asks to name all of the abstract classes in a given UML diagram. Fairly straightforward, I suppose. There are one abstract class and three interfaces. Do these interfaces qualify as abstract classes, in general?
Thing is, while technically interfaces may be represented as classes in languages like Java, I wouldn't consider them classes. Abstract? Hell yes. Class? No. Interfaces cannot have constructors, neither properties, fields, function bodies, etc. Interfaces cannot be inherited, they are implemented (again, technically it might be true that implementing an interface is actually inheriting it in specific languages, but that's not my point.) Interfaces are more like 'contracts' as they do not define any behaviour whatsoever like classes. Now if this is a homework then you shouldn't really argue about these sort of stuff with the teacher. Just check your lecture notes and see if the word "class" is mentioned anywhere in the your teacher's definition of interface.
All interface are [indeed abstract](http://en.wikipedia.org/wiki/Interface_(Java)) Actually, you can declare an method as abstract within an interface... except any 'checkstyle' tool will tell you the abstract keyword is redundant. And all methods are public. If a class implements an interface and does not implement all its methods, it must be marked as abstract. If a class is abstract, one of its subclasses is expected to implement its unimplemented methods. To echo other answers, an [interface is not a class](http://java.sun.com/docs/books/tutorial/java/IandI/interfaceAsType.html). An interface is a *reference type*, similar to a class, that can contain only constants, method signatures, and nested types. There are no method bodies. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces. Interfaces are not part of the class hierarchy, although they work in combination with classes. When you define a new interface, you are defining a new reference data type. You can use interface names anywhere you can use any other data type name. If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface --- To better explain why an interface is not a class, consider the following: 1/ an interface is a **type** used by **values** 2/ a class is for Objects 3/: ``` Object a = new Date(); String s = a.toString(); ``` * The **type** of the variable 'a' is Object (which is actually a type notation in Java source code meaning a *reference* to an Object), * but the **class** of the object it points to is Date. The type (Object) only affects what code is valid according to the compiler's type-checking, but *not* what the code actually does. The class of the object affects what the code does, so that the a.toString() call in the second line returns a String that looks like a Date, not one that looks like "java.lang.Object@XXXXXXXX". Since an Interface is a type, it is used for values only, and will not represent what objects will actually do in term of runtime.
Is a Java interface an abstract class?
[ "", "java", "oop", "interface", "abstract-class", "" ]
I've previously used [`jquery-ui tabs`](https://jqueryui.com/tabs/) extension to load page fragments via `ajax`, and to conceal or reveal hidden `div`s within a page. Both of these methods are well documented, and I've had no problems there. Now, however, I want to do something different with tabs. When the user selects a tab, it should reload the page entirely - the reason for this is that the contents of each tabbed section are somewhat expensive to render, so I don't want to just send them all at once and use the normal method of toggling 'display:none' to reveal them. My plan is to intercept the tabs' `select` event, and have that function reload the page with by manipulating document.location. How, in the `select` handler, can I get the newly selected tab index and the html LI object it corresponds to? ``` $('#edit_tabs').tabs( { selected: 2, // which tab to start on when page loads select: function(e, ui) { var t = $(e.target); // alert("data is " + t.data('load.tabs')); // undef // alert("data is " + ui.data('load.tabs')); // undef // This gives a numeric index... alert( "selected is " + t.data('selected.tabs') ) // ... but it's the index of the PREVIOUSLY selected tab, not the // one the user is now choosing. return true; // eventual goal is: // ... document.location= extract-url-from(something); return false; } }); ``` Is there an attribute of the event or ui object that I can read that will give the index, id, or object of the newly selected tab or the anchor tag within it? Or is there a better way altogether to use tabs to reload the entire page?
I would take a look at the [events](http://docs.jquery.com/UI/Tabs#Events) for Tabs. The following is taken from the jQuery docs: ``` $('.ui-tabs-nav').bind('tabsselect', function(event, ui) { ui.options // options used to intialize this widget ui.tab // anchor element of the selected (clicked) tab ui.panel // element, that contains the contents of the selected (clicked) tab ui.index // zero-based index of the selected (clicked) tab }); ``` Looks like ui.tab is the way to go.
in jQuery UI - v1.9.2 ``` ui.newTab.index() ``` to get a base 0 index of active tab
jQuery tabs - getting newly selected index
[ "", "javascript", "jquery", "jquery-ui", "jquery-plugins", "jquery-ui-tabs", "" ]
I regularly want to check if an object has a member or not. An example is the creation of a singleton in a function. For that purpose, you can use `hasattr` like this: ``` class Foo(object): @classmethod def singleton(self): if not hasattr(self, 'instance'): self.instance = Foo() return self.instance ``` But you can also do this: ``` class Foo(object): @classmethod def singleton(self): try: return self.instance except AttributeError: self.instance = Foo() return self.instance ``` Is one method better of the other? **Edit:** Added the `@classmethod` ... But note that the question is *not* about how to make a singleton but how to check the presence of a member in an object. **Edit:** For that example, a typical usage would be: ``` s = Foo.singleton() ``` Then `s` is an object of type `Foo`, the same each time. And, typically, the method is called many times.
These are two different methodologies: №1 is LBYL (look before you leap) and №2 is EAFP (easier to ask forgiveness than permission). Pythonistas typically suggest that EAFP is better, with arguments in style of "what if a process creates the file between the time you test for it and the time you try to create it yourself?". This argument does not apply here, but it's the general idea. Exceptions should not be treated as *too* exceptional. Performance-wise in your case —since setting up exception managers (the `try` keyword) is very cheap in CPython while creating an exception (the `raise` keyword and internal exception creation) is what is relatively expensive— using method №2 the exception would be raised only once; afterwards, you just use the property.
I just tried to measure times: ``` class Foo(object): @classmethod def singleton(self): if not hasattr(self, 'instance'): self.instance = Foo() return self.instance class Bar(object): @classmethod def singleton(self): try: return self.instance except AttributeError: self.instance = Bar() return self.instance from time import time n = 1000000 foo = [Foo() for i in xrange(0,n)] bar = [Bar() for i in xrange(0,n)] print "Objs created." print for times in xrange(1,4): t = time() for d in foo: d.singleton() print "#%d Foo pass in %f" % (times, time()-t) t = time() for d in bar: d.singleton() print "#%d Bar pass in %f" % (times, time()-t) print ``` On my machine: ``` Objs created. #1 Foo pass in 1.719000 #1 Bar pass in 1.140000 #2 Foo pass in 1.750000 #2 Bar pass in 1.187000 #3 Foo pass in 1.797000 #3 Bar pass in 1.203000 ``` It seems that try/except is faster. It seems also more readable to me, anyway depends on the case, this test was very simple maybe you'd need a more complex one.
Checking for member existence in Python
[ "", "python", "exception", "introspection", "hasattr", "" ]
I'm writing a construct in PHP where a parser determins which function to call dynamically, kind of like this: ``` // The definition of what to call $function_call_spec = array( "prototype" => "myFunction", "parameters" => array( "first_par" => "Hello", "second_par" => "World")); // Dispatch $funcPrototype = $function_call_spec["prototype"]; $funcPrototype(); // Here we call function 'myFunction'. ``` This is all fine and dandy. But now comes the next step, passing the parameters, which I don't really know if it's possible the way I want to do it. It never stops amazing me however what script languages can do these days, so here goes: One could pass the parameters to the function like this: ``` // Here we call function 'myFunction' with the array of parameters. $funcPrototype( $function_call_spec["parameters"] ); ``` However, I want to declare 'myFunction' properly with clear arguments etc: ``` function myFunction( $first_par, $second_par ) { } ``` The question then follows - Is there any way to pass parameters to a function dynamically simply by looping through the parameter array? To clarify, I **don't** want to do it like this: ``` $funcPrototype( $function_call_spec["parameters"]["first_par"], $function_call_spec["parameters"]["second_par"] ); ``` Because this requires my code to statically know details about myFunction, which goes against the whole idea. Instead I would want to do it in some way like this maybe: ``` // Special magic PHP function which can be used for invoking functions dynamically InvokeFunction( $funcPrototype, $function_call_spec["parameters"] ); ``` Which then results in myFunction being called and all parameters in the array gets passed to each individual parameter variable in the prototype. Any comments are welcome. Regards. /R PS: None of the code in this post has been tested for typos etc.
You should use [`call_user_func_array`](http://php.net/call_user_func_array) which can call any function or method and takes parameteres from an array. Alternatively you can use [`ReflectionFunction::invokeArgs`](http://php.net/manual/en/language.oop5.reflection.php#language.oop5.reflection.reflectionfunction), but there's no benefit over `call_user_func_array` unless you already use this class for someting else (like checking whether function you call accepts appropriate number and types of arguments).
``` call_user_func_array($funcPrototype, $function_call_spec["parameters"]); ``` You might want to create a wrapper that names the function to your preference, such as: ``` function InvokeFunction($function, $args = array()) { return call_user_func_array($function, (array)$args); } ``` With this function you can call it in 3 different ways: ``` $return = InvokeFunction('doStuff'); $return = InvokeFunction('doStuff', $single_arg); $return = InvokeFunction('doStuff', $multiple_args); ```
Using function prototypes dynamically in PHP
[ "", "php", "function-calls", "" ]
I created the setup project for the application and I can see that the later modifications of the configuration file (Application.exe.config) don't affect the application execution. I am developing an application with the database file included and I want to enable users to move the database file and modify connection strings. Does anyone know what's the best practice for the deployment of the application with the database file?
It should work, provided that you use the exact same connection string setting in your DB access DLL's Settings.settings file and in your application's config file. An example that works well for me: ``` <connectionStrings> <add name="YourApp.Properties.Settings.DatabaseConnectionString" connectionString="Data Source=localhost;Initial Catalog=xxx;Integrated Security=True;" providerName="System.Data.SqlClient" /> </connectionStrings> ``` When entered appropriately in both locations (ie. the dll's Settings.settings and the exe's App.config files), this does allow me to change the database connection in YourApp.exe.config before the app runs. (I assume you already know that you need to change the application's config file, as DLL's do not support the app.config mechanism directly.)
Have you checked out using a [UDL file](http://support.microsoft.com/kb/308426)? If you save your connection string in the udl file, the user can change the connection via an interface by simply double clicking that file. You can set your connection string in the app to point to the udl file. You can also launch the udl interface programmatically if you want. The only downside to these is if the user saves their password to the file, it is saved as plain text. But this isn't an issue if you are using windows authentication.
Connection Strings modification after the deployment
[ "", "c#", ".net", "database", "deployment", "sql-server-express", "" ]
I need a tool that handle both on-screen and printed reports, via my C# application. I'm looking for simple, standard and powerful. I need to be able to give the user the ability to select which columns to display, formatting, etc... with my own GUI and dynamically build the report based upon their choices. Crystal does not fit the bill here because the columns cannot be added on the fly (and the column widths can not be adjusted on the fly). I'm thinking of using HTML with the WebBrowser control in my app, but I will have very little control over printing and print preview. Another option is go to .NET 3.5 (I'm using 2.0) and use XAML with Flow Documents. What would you use?
We use SQL reporting services. HTML reports have their place but you dont get very much controlling over formatting. SQL reporting services summary: Advantages: Basic version is free Included with SQL express Many exporting options pdf, html, csv etc Can use many different datasources Webservice which exposes various methods SQL standard editon includes a report builder component to allow users create and share their own reports Lots of features for querying formatting etc Scheduling options Extensibility import .net framework dlls for custom functionality Familiar microsoft environment Disadvantages: An extra thing to setup Seemless authentication between application and report server can be a pain depending on your setup A little bit of a learning curve although its not too hard to pick up Report model creator needs some work and doesnt automatically a-z fields I have heard good things about DevXpress so may be worth looking into. I used Crystal about 5 years ago and remember it being a pain to setup and was costly licence wise.
Check out the Report Viewer stuff in studio 2008 / .NET 3.5 This amazing site has the full scoop: [GotReportViewer](http://www.gotreportviewer.com/) It's a nice build in reporting system that will show a report and print. It's not full blown like Crystal or SQL Reporting Services. If all you need is some lightweight reporting you can't beat the price.
What is the reporting tool that you would use?
[ "", "c#", "printing", "report", "" ]
I've been reading about thread-safe singleton patterns here: <http://en.wikipedia.org/wiki/Singleton_pattern#C.2B.2B_.28using_pthreads.29> And it says at the bottom that the only safe way is to use pthread\_once - which isn't available on Windows. Is that the **only** way of guaranteeing thread safe initialisation? I've read this thread on SO: [Thread safe lazy construction of a singleton in C++](https://stackoverflow.com/questions/6915/thread-safe-lazy-contruction-of-a-singleton-in-c) And seems to hint at an atomic OS level swap and compare function, which I assume on Windows is: <http://msdn.microsoft.com/en-us/library/ms683568.aspx> Can this do what I want? **Edit:** I would like lazy initialisation and for there to only ever be one instance of the class. Someone on another site mentioned using a global inside a namespace (and he described a singleton as an anti-pattern) - how can it be an "anti-pattern"? **Accepted Answer:** I've accepted [Josh's answer](https://stackoverflow.com/questions/164496/how-can-i-create-a-thread-safe-singleton-pattern-in-windows#164640) as I'm using Visual Studio 2008 - NB: For future readers, if you aren't using this compiler (or 2005) - Don't use the accepted answer!! **Edit:** **The code works fine except the return statement - I get an error: error C2440: 'return' : cannot convert from 'volatile Singleton \*' to 'Singleton \*'. Should I modify the return value to be volatile Singleton \*?** **Edit:** Apparently const\_cast<> will remove the volatile qualifier. Thanks again to Josh.
If you are are using Visual C++ 2005/2008 you can use the double checked locking pattern, since "[volatile variables behave as fences](http://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Microsoft_Visual_C.2B.2B)". This is the most efficient way to implement a lazy-initialized singleton. From [MSDN Magazine:](http://msdn.microsoft.com/en-us/magazine/cc163405.aspx) ``` Singleton* GetSingleton() { volatile static Singleton* pSingleton = 0; if (pSingleton == NULL) { EnterCriticalSection(&cs); if (pSingleton == NULL) { try { pSingleton = new Singleton(); } catch (...) { // Something went wrong. } } LeaveCriticalSection(&cs); } return const_cast<Singleton*>(pSingleton); } ``` Whenever you need access to the singleton, just call GetSingleton(). The first time it is called, the static pointer will be initialized. After it's initialized, the NULL check will prevent locking for just reading the pointer. *DO NOT* use this on just any compiler, as it's not portable. The standard makes no guarantees on how this will work. Visual C++ 2005 explicitly adds to the semantics of volatile to make this possible. You'll have to declare and [initialize the CRITICAL SECTION](http://msdn.microsoft.com/en-us/library/ms683472(VS.85).aspx) elsewhere in code. But that initialization is cheap, so lazy initialization is usually not important.
A simple way to guarantee **cross-platform thread safe initialization of a singleton** is to perform it explicitly (via a call to a static member function on the singleton) in the main thread of your application **before** your application starts any other threads (or at least any other threads that will access the singleton). Ensuring thread safe access to the singleton is then achieved in the usual way with mutexes/critical sections. **Lazy initialization** can also be achieved using a similar mechanism. The usual problem encountered with this is that the mutex required to provide thread-safety is often initialized in the singleton itself which just pushes the thread-safety issue to initialization of the mutex/critical section. One way to overcome this issue is to create and initialize a mutex/critical section in the main thread of your application then pass it to the singleton via a call to a static member function. The heavyweight initialization of the singleton can then occur in a thread-safe manner using this pre-initialized mutex/critical section. For example: ``` // A critical section guard - create on the stack to provide // automatic locking/unlocking even in the face of uncaught exceptions class Guard { private: LPCRITICAL_SECTION CriticalSection; public: Guard(LPCRITICAL_SECTION CS) : CriticalSection(CS) { EnterCriticalSection(CriticalSection); } ~Guard() { LeaveCriticalSection(CriticalSection); } }; // A thread-safe singleton class Singleton { private: static Singleton* Instance; static CRITICAL_SECTION InitLock; CRITICIAL_SECTION InstanceLock; Singleton() { // Time consuming initialization here ... InitializeCriticalSection(&InstanceLock); } ~Singleton() { DeleteCriticalSection(&InstanceLock); } public: // Not thread-safe - to be called from the main application thread static void Create() { InitializeCriticalSection(&InitLock); Instance = NULL; } // Not thread-safe - to be called from the main application thread static void Destroy() { delete Instance; DeleteCriticalSection(&InitLock); } // Thread-safe lazy initializer static Singleton* GetInstance() { Guard(&InitLock); if (Instance == NULL) { Instance = new Singleton; } return Instance; } // Thread-safe operation void doThreadSafeOperation() { Guard(&InstanceLock); // Perform thread-safe operation } }; ``` However, there are good reasons to avoid the use of singletons altogether (and why they are sometimes referred to as an **anti-pattern**): * They are essentially glorified global variables * They can lead to high coupling between disparate parts of an application * They can make unit testing more complicated or impossible (due to the difficultly in swapping real singletons with fake implementations) An alternative is to make use of a 'logical singleton' whereby you create and initialise a single instance of a class in the main thread and pass it to the objects which require it. This approach can become unwieldy where there are many objects which you want to create as singletons. In this case the disparate objects can be bundled into a single 'Context' object which is then passed around where necessary.
How can I create a thread-safe singleton pattern in Windows?
[ "", "c++", "windows", "singleton", "" ]
I have a models `A` and `B`, that are like this: ``` class A(models.Model): title = models.CharField(max_length=20) (...) class B(models.Model): date = models.DateTimeField(auto_now_add=True) (...) a = models.ForeignKey(A) ``` Now I have some `A` and `B` objects, and I'd like to get a query that selects all `A` objects that have less then 2 `B` pointing at them. A is something like a pool thing, and users (the B) join pool. if there's only 1 or 0 joined, the pool shouldn't be displayed at all. Is it possible with such model design? Or should I modify that a bit?
Sounds like a job for [`extra`](http://docs.djangoproject.com/en/dev/ref/models/querysets/#extra-select-none-where-none-params-none-tables-none-order-by-none-select-params-none). ``` A.objects.extra( select={ 'b_count': 'SELECT COUNT(*) FROM yourapp_b WHERE yourapp_b.a_id = yourapp_a.id', }, where=['b_count < 2'] ) ``` If the B count is something you often need as a filtering or ordering criterion, or needs to be displayed on list views, you could consider denormalisation by adding a b\_count field to your A model and using signals to update it when a B is added or deleted: ``` from django.db import connection, transaction from django.db.models.signals import post_delete, post_save def update_b_count(instance, **kwargs): """ Updates the B count for the A related to the given B. """ if not kwargs.get('created', True) or kwargs.get('raw', False): return cursor = connection.cursor() cursor.execute( 'UPDATE yourapp_a SET b_count = (' 'SELECT COUNT(*) FROM yourapp_b ' 'WHERE yourapp_b.a_id = yourapp_a.id' ') ' 'WHERE id = %s', [instance.a_id]) transaction.commit_unless_managed() post_save.connect(update_b_count, sender=B) post_delete.connect(update_b_count, sender=B) ``` Another solution would be to manage a status flag on the A object when you're adding or removing a related B. ``` B.objects.create(a=some_a) if some_a.hidden and some_a.b_set.count() > 1: A.objects.filter(id=some_a.id).update(hidden=False) ... some_a = b.a some_b.delete() if not some_a.hidden and some_a.b_set.count() < 2: A.objects.filter(id=some_a.id).update(hidden=True) ```
The question and selected answer are from 2008 and since then this functionality has been integrated into the django framework. Since this is a top google hit for "django filter foreign key count" I'd like to add an easier solution with a recent django version using [Aggregation](https://docs.djangoproject.com/en/dev/topics/db/aggregation/ "Aggregation"). ``` from django.db.models import Count cats = A.objects.annotate(num_b=Count('b')).filter(num_b__lt=2) ``` In my case I had to take this concept a step further. My "B" object had a boolean field called is\_available, and I only wanted to return A objects who had more than 0 B objects with is\_available set to True. ``` A.objects.filter(B__is_available=True).annotate(num_b=Count('b')).filter(num_b__gt=0).order_by('-num_items') ```
Django models - how to filter number of ForeignKey objects
[ "", "python", "django", "database-design", "" ]
What are the correct version numbers for C#? What came out when? Why can't I find any answers about ***C# 3.5***? This question is primarily to aid those who are searching for an answer using an incorrect version number, e.g. ***C# 3.5***. The hope is that anyone failing to find an answer with the wrong version number will find *this* question and then search again with the right version number.
# C# language version history: These are the [versions of C#](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-version-history) known about at the time of this writing: * **C# 1.0** released with .NET 1.0 and VS2002 (January 2002) * **C# 1.2** (bizarrely enough); released with .NET 1.1 and VS2003 (April 2003). First version to call `Dispose` on `IEnumerator`s which implemented `IDisposable`. A few other small features. * **C# 2.0** released with .NET 2.0 and VS2005 (November 2005). Major new features: generics, anonymous methods, nullable types, and iterator blocks * **C# 3.0** released with .NET 3.5 and VS2008 (November 2007). Major new features: lambda expressions, extension methods, expression trees, anonymous types, implicit typing (`var`), and query expressions * **C# 4.0** released with .NET 4 and VS2010 (April 2010). Major new features: late binding (`dynamic`), delegate and interface generic variance, more [COM](https://en.wikipedia.org/wiki/Component_Object_Model) support, named arguments, tuple data type and optional parameters * **C# 5.0** released with .NET 4.5 and VS2012 (August 2012). [Major features](https://devblogs.microsoft.com/csharpfaq/visual-studio-11-beta-is-here/): async programming, and caller info attributes. Breaking change: [loop variable closure](https://ericlippert.com/2009/11/16/closing-over-the-loop-variable-considered-harmful-part-two/). * **C# 6.0** released with .NET 4.6 and VS2015 (July 2015). Implemented by [Roslyn](https://github.com/dotnet/roslyn). [Features](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-6): initializers for automatically implemented properties, using directives to import static members, exception filters, element initializers, `await` in `catch` and `finally`, extension `Add` methods in collection initializers. * **C# 7.0** released with .NET 4.7 and VS2017 (March 2017). Major [new features](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7): [tuples](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#tuples), [ref locals and ref return](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#ref-locals-and-returns), [pattern matching](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#pattern-matching) (including pattern-based switch statements), [inline `out` parameter declarations](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#out-variables), [local functions](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#local-functions), [binary literals, digit separators](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#numeric-literal-syntax-improvements), and [arbitrary async returns](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#generalized-async-return-types). * **C# 7.1** released with VS2017 v15.3 (August 2017). New features: [async main](https://github.com/dotnet/csharplang/issues/97), [tuple member name inference](https://github.com/dotnet/csharplang/issues/415), [default expression](https://github.com/dotnet/csharplang/issues/102), and [pattern matching with generics](https://github.com/dotnet/csharplang/issues/154). * **C# 7.2** released with VS2017 v15.5 (November 2017). New features: [private protected access modifier](https://github.com/dotnet/csharplang/issues/37), [Span<T>, aka interior pointer, aka stackonly struct](https://github.com/dotnet/csharplang/issues/666), and [everything else](https://github.com/dotnet/csharplang/milestone/6). * **C# 7.3** released with VS2017 v15.7 (May 2018). New features: [enum, delegate and `unmanaged` generic type constraints](https://devblogs.microsoft.com/premier-developer/dissecting-new-generics-constraints-in-c-7-3/). `ref` reassignment. Unsafe improvements: `stackalloc` initialization, unpinned indexed `fixed` buffers, custom `fixed` statements. Improved overloading resolution. Expression variables in initializers and queries. `==` and `!=` defined for tuples. Auto-properties' backing fields can now be targeted by attributes. * **C# 8.0** released with .NET Core 3.0 and VS2019 v16.3 (September 2019). Major [new features](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8): [nullable reference-types](https://learn.microsoft.com/en-us/dotnet/csharp/nullable-references), [asynchronous streams](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#asynchronous-streams), [indices and ranges](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#indices-and-ranges), [readonly members](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#readonly-members), [using declarations](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#using-declarations), [default interface methods](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#default-interface-methods), [static local functions](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#static-local-functions), and [enhancement of interpolated verbatim strings](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#enhancement-of-interpolated-verbatim-strings). * **C# 9** released with [.NET 5.0](https://devblogs.microsoft.com/dotnet/announcing-net-5-0/) and VS2019 v16.8 (November 2020). Major [new features](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9): [init-only properties](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9#init-only-setters), [records](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9#record-types), [with-expressions](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/with-expression), data classes, positional records, [top-level programs](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9#top-level-statements), [improved pattern matching](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9#pattern-matching-enhancements) (simple type patterns, relational patterns, logical patterns), improved target typing (target-type `new` expressions, target typed `??` and `?`), and covariant returns. Minor features: relax ordering of `ref` and `partial` modifiers, parameter null checking, lambda discard parameters, native `int`s, attributes on local functions, function pointers, static lambdas, extension `GetEnumerator`, module initializers, and extending partial. * **C# 10** released with .NET 6.0 (November 2021). Major [new features](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-10): record structs, struct parameterless constructors, interpolated string handlers, global `using` directives, file-scoped namespace declarations, extended property patterns, const interpolated strings, mixed assignment and declaration in deconstruction, async method builders (via attributes) for individual methods, the `CallerArgumentExpression` attribute for parameters, enhanced `#line` pragmas. * **C# 11** released with .NET 7.0 (November 2022). Major [new features](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11): file-scoped types, generic math support, auto-default structs, pattern match `Span<char>` on a constant string, extended nameof scope, numeric `IntPtr`, UTF-8 string literals, required members, `ref` fields and `scoped ref`, raw string literals, improved method group conversion to delegate, warning wave 7, generic attributes, newlines in string interpolation expressions, list patterns * **C# 12** released with .NET 8.0 (November 2023). Major [new features](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-12): primary constructors, collection expressions, inline arrays, optional parameters in lambda expressions, `ref readonly` parameters, alias any type, `Experimental` attribute, interceptors ## In response to the OP's question: > What are the correct version numbers for C#? What came out when? Why can't I find any answers about C# 3.5? There is no such thing as C# 3.5 - the cause of confusion here is that the C# 3.0 is present in .NET 3.5. The language and framework are versioned independently, however - as is the CLR, which is at version 2.0 for .NET 2.0 through 3.5, .NET 4 introducing CLR 4.0, service packs notwithstanding. The CLR in .NET 4.5 has various improvements, but the versioning is unclear: in some places it may be referred to as CLR 4.5 ([this MSDN page](https://msdn.microsoft.com/en-us/library/bb822049.aspx) used to refer to it that way, for example), but the [`Environment.Version`](https://learn.microsoft.com/en-us/dotnet/api/system.environment.version) property still reports 4.0.xxx. As of May 3, 2017, the C# Language Team created a history of C# versions and features on their GitHub repository: [Features Added in C# Language Versions](https://github.com/dotnet/csharplang/blob/master/Language-Version-History.md). There is also [a page that tracks upcoming and recently implemented language features](https://github.com/dotnet/roslyn/blob/master/docs/Language%20Feature%20Status.md).
This is the same as most answers here, but tabularized for ease, and it has **Visual Studio** and **.NET** versions for completeness. | C# version | VS version | .NET version | CLR version | Release date | | --- | --- | --- | --- | --- | | 1.0 | 2002 | 1.0 | 1.0 | Feb 2002 | | 1.2 | 2003 | 1.1 | 1.1 | Apr 2003 | | 2.0 | 2005 | 2.0 | 2.0 | Nov 2005 | | | | 3.0 | 2.0 | Nov 2006 | | 3.0 | 2008 | 3.5 | 2.0 | Nov 2007 | | 4.0 | 2010 | 4.0 | 4 | Apr 2010 | | 5.0 | 2012 | 4.5 | 4 | Aug 2012 | | | 2013 | 4.5.1 | 4 | Oct 2013 | | | | 4.5.2 | 4 | May 2014 | | 6.0 | 2015 | 4.6 | 4 | Jul 2015 | | | | 4.6.1 | 4 | Nov 2015 | | | | 4.6.2 | 4 | Aug 2016 | | 7.0 | 2017 | | | Mar 2017 | | | | 4.7 | 4 | May 2017 | | 7.1 | 2017 (v15.3) | | | Aug 2017 | | | | 4.7.1 | 4 | Oct 2017 | | 7.2 | 2017 (v15.5) | | | Dec 2017 | | | | 4.7.2 | 4 | Apr 2018 | | 7.3 | 2017 (v15.7) | | | May 2018 | | 8.0 | 2019 | 4.8 | 4 | Apr 2019 | | | | 4.8.1 | 4 | Aug 2022 | ### Versions since .NET Core | C# version | VS version | .NET version | Release date | End of Support | | --- | --- | --- | --- | --- | | | 2015 Update 3 | .NET Core 1.0 | Jun 2016 | Jun 2019 | | | | .NET Core 1.1 | Nov 2016 | Jun 2019 | | 7.0 | 2017 | | Mar 2017 | | | 7.1 | 2017 (v15.3) | .NET Core 2.0 | Aug 2017 | Oct 2018 | | 7.3 | 2017 (v15.7) | .NET Core 2.1 | May 2018 | Aug 2021 | | | | .NET Core 2.2 | Dec 2018 | Dec 2019 | | 8.0 | 2019 | | Apr 2019 | | | | 2019 (v16.3) | .NET Core 3.0 | Sep 2019 | Mar 2020 | | | 2019 (v16.4) | .NET Core 3.1 | Dec 2019 | Dec 2022 | | 9 (†) | 2019 (v16.8) | .NET 5 | Nov 2020 | May 2022 | | 10 | 2022 | .NET 6 | Nov 2021 | Nov 2024 | | 11 | 2022 (17.4) | .NET 7 | Nov 2022 | May 2024 | | 12 | 2022 (17.8) | .NET 8 | Nov 2023 | Nov 2026 | \* - .NET 5.0 is not a newer version of .NET framework but .NET Core 3. Starting from .NET 5.0, there are no newer versions of .NET full framework. \*\* - [There are no separate CLR (CoreCLR) versions for .NET Core.](https://docs.microsoft.com/en-us/dotnet/standard/clr?redirectedfrom=MSDN#clr-versions) Whatever is the .NET Core version is the CoreCLR version. So not mentioning it. --- **Note:** .NET is pretty much independent of VS and compiler versions, there is no correlation between versions of each. The above lists don't imply certain version of .NET are tied to certain C# or VS versions. This is just compiled in their chronological order of their releases (VS/C# and .NET). Some releases happen to be together, hence they sit in the same row. Refer to "[.NET Framework versions and dependencies](https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/versions-and-dependencies)" and "[.NET release cadence](https://dotnet.microsoft.com/platform/support/policy/dotnet-core)" for more. † The `major.minor` versioning scheme became just `major` [starting with C# 9](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-version-history)
What are the correct version numbers for C#?
[ "", "c#", ".net", "visual-studio", ".net-core", ".net-framework-version", "" ]
Given the string "ThisStringHasNoSpacesButItDoesHaveCapitals" what is the best way to add spaces before the capital letters. So the end string would be "This String Has No Spaces But It Does Have Capitals" Here is my attempt with a RegEx ``` System.Text.RegularExpressions.Regex.Replace(value, "[A-Z]", " $0") ```
The regexes will work fine (I even voted up Martin Browns answer), but they are expensive (and personally I find any pattern longer than a couple of characters prohibitively obtuse) This function ``` string AddSpacesToSentence(string text, bool preserveAcronyms) { if (string.IsNullOrWhiteSpace(text)) return string.Empty; StringBuilder newText = new StringBuilder(text.Length * 2); newText.Append(text[0]); for (int i = 1; i < text.Length; i++) { if (char.IsUpper(text[i])) if ((text[i - 1] != ' ' && !char.IsUpper(text[i - 1])) || (preserveAcronyms && char.IsUpper(text[i - 1]) && i < text.Length - 1 && !char.IsUpper(text[i + 1]))) newText.Append(' '); newText.Append(text[i]); } return newText.ToString(); } ``` Will do it 100,000 times in 2,968,750 ticks, the regex will take 25,000,000 ticks (and thats with the regex compiled). It's better, for a given value of better (i.e. faster) however it's more code to maintain. "Better" is often compromise of competing requirements. **Update** It's a good long while since I looked at this, and I just realised the timings haven't been updated since the code changed (it only changed a little). On a string with 'Abbbbbbbbb' repeated 100 times (i.e. 1,000 bytes), a run of 100,000 conversions takes the hand coded function 4,517,177 ticks, and the Regex below takes 59,435,719 making the Hand coded function run in 7.6% of the time it takes the Regex. **Update 2** Will it take Acronyms into account? It will now! The logic of the if statment is fairly obscure, as you can see expanding it to this ... ``` if (char.IsUpper(text[i])) if (char.IsUpper(text[i - 1])) if (preserveAcronyms && i < text.Length - 1 && !char.IsUpper(text[i + 1])) newText.Append(' '); else ; else if (text[i - 1] != ' ') newText.Append(' '); ``` ... doesn't help at all! Here's the original *simple* method that doesn't worry about Acronyms ``` string AddSpacesToSentence(string text) { if (string.IsNullOrWhiteSpace(text)) return ""; StringBuilder newText = new StringBuilder(text.Length * 2); newText.Append(text[0]); for (int i = 1; i < text.Length; i++) { if (char.IsUpper(text[i]) && text[i - 1] != ' ') newText.Append(' '); newText.Append(text[i]); } return newText.ToString(); } ```
Your solution has an issue in that it puts a space before the first letter T so you get ``` " This String..." instead of "This String..." ``` To get around this look for the lower case letter preceding it as well and then insert the space in the middle: ``` newValue = Regex.Replace(value, "([a-z])([A-Z])", "$1 $2"); ``` **Edit 1:** If you use `@"(\p{Ll})(\p{Lu})"` it will pick up accented characters as well. **Edit 2:** If your strings can contain acronyms you may want to use this: ``` newValue = Regex.Replace(value, @"((?<=\p{Ll})\p{Lu})|((?!\A)\p{Lu}(?>\p{Ll}))", " $0"); ``` So "DriveIsSCSICompatible" becomes "Drive Is SCSI Compatible"
Add spaces before Capital Letters
[ "", "c#", "regex", "string", "" ]
I'm doing some shennanigans with jQuery to put little plus/minus icons next to my expanders. Its similar to the windows file trees, or firebugs code expanders. It works, but its not specific enough. Hopefully this makes sense... ``` $('div.toggle').hide();//hide all divs that are part of the expand/collapse $('ul.product-info li a').toggle(function(event){ event.preventDefault(); $(this).next('div').slideToggle(200);//find the next div and sliiiide it $('img.expander').attr('src','img/content/info-close.gif');//this is the part thats not specific enough!!! },function(event) { // opposite here event.preventDefault(); $(this).next('div').slideToggle(200); $('img.expander').attr('src','img/content/info-open.gif'); }); <ul class="product-info"> <li> <a class="img-link" href="#"><img class="expander" src="img/content/info-open.gif" alt="Click to exand this section" /> <span>How it compares to the other options</span> </a> <div class="toggle"><p>Content viewable when expanded!</p></div> </li> </ul> ``` There are loads of `$('img.expander')` tags on the page, but I need to be specific. I've tried the next() functionality ( like I've used to find the next div), but it says that its undefined. How can I locate my specific img.expander tag? Thanks. EDIT, updated code as per Douglas' solution: ``` $('div.toggle').hide(); $('ul.product-info li a').toggle(function(event){ //$('#faq-copy .answer').hide(); event.preventDefault(); $(this).next('div').slideToggle(200); $(this).contents('img.expander').attr('src','img/content/info-close.gif'); //alert('on'); },function(event) { // same here event.preventDefault(); $(this).next('div').slideToggle(200); $(this).contents('img.expander').attr('src','img/content/info-open.gif'); }); ```
``` $(this).contents('img.expander') ``` This is what you want. It will select all of the nodes that are children of your list. In your case, all of your images are nested inside of the list element, so this will filter out only what you want.
How about making your click event toggle a CSS class on a parent item (in your case, perhaps the ul.product-info). Then you can use CSS background properties to change the background image for a <span> instead of using a literal <img> and trying to fiddle with the src. You would also be able to accomplish a showing and hiding on your div.toggle's. ``` ul.product-info.open span.toggler { background-image: url( "open-toggler.png" ); } ul.product-info.closed span.toggler { background-image: url( "closed-toggler.png" ); } ul.product-info.open div.toggle { display: block; } ul.product-info.closed div.toggle { display: hidden; } ``` Using jQuery navigation/spidering functions can be slow when the DOM has many items and deep nesting. With CSS, your browser will render and change things more quickly.
Open/Close Icons
[ "", "javascript", "jquery", "html", "dom", "" ]
I'm programming something that allows users to store documents and pictures on a webserver, to be stored and retrieved later. When users upload files to my server, PHP tells me what filetype it is based on the extension. However, I'm afraid that users could rename a zip file as somezipfile.png and store it, thus keeping a zip file on my server. Is there any reasonable way to open an uploaded file and "check" to see if it truly is of the said filetype?
[Magic number](http://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files). If you can read first few bytes of a binary file you can know what kind of file it is.
Check out the [FileInfo](http://php.net/manual/en/book.fileinfo.php) PECL extension for PHP, which can do the MIME magic lookups for you.
How do I tell if someone's faking a filetype? (PHP)
[ "", "php", "upload", "mime-types", "file-type", "" ]
I have an import-from-excel script as part of a CMS that previously ran without issue. My shared-hosting provider has recently upgraded their infrastructure, including PHP from 5.1 to 5.2.6, and the script now returns "Uninitialized string offset: -XXX in /path/scriptname.php on line 27" (XXX being a decreasing number from 512 and /path/scriptname.php of course being the full path to script in question). It returns this error for every line of the excel file. Line 27 is just a return from within a function that is the first point at which the imported data is being processed: ``` function GetInt4d($data, $pos) { return ord($data[$pos]) | (ord($data[$pos+1]) << 8) | (ord($data[$pos+2]) << 16) | (ord($data[$pos+3]) << 24); } ``` It finally implodes with a "Fatal error: Allowed memory size of 47185920 bytes exhausted (tried to allocate 71 bytes) in /path/scriptname.php on line 133". There's nothing useful in Apache error logs. I am stumped. Anyone have any ideas of at least where to look? Even knowing if it's likely to be something within my script or something to do with upgrade would be useful. I had another issue with a different site on same provider that (after upgrade) couldn't write sessions to tmp directory (since resolved), but am pretty sure it's not that (?). EDIT: As it turned out that the answer was to do with the version of the parser being incompatible in some way with PHP 5.2.6, I thought it might be of use to someone that the parser in question is [Spreadsheet Excel Reader](http://sourceforge.net/project/showfiles.php?group_id=99160&package_id=106368) .
> Uninitialized string offset: ... means that `$data` is not an array.
Solved here: <http://www.phpbuilder.com/board/archive/index.php/t-10328608.html>
Uninitialized string offset error from PHP import script
[ "", "php", "apache", "web-hosting", "" ]
What is a fast way to select a random row from a large mysql table? I'm working in php, but I'm interested in any solution even if it's in another language.
Grab all the id's, pick a random one from it, and retrieve the full row. If you know the id's are sequential without holes, you can just grab the max and calculate a random id. If there are holes here and there but mostly sequential values, and you don't care about a slightly skewed randomness, grab the max value, calculate an id, and select the first row with an id equal to or above the one you calculated. The reason for the skewing is that id's following such holes will have a higher chance of being picked than ones that follow another id. If you order by random, you're going to have a terrible table-scan on your hands, and the word *quick* doesn't apply to such a solution. Don't do that, nor should you order by a GUID, it has the same problem.
I knew there had to be a way to do it in a single query in a fast way. And here it is: A fast way without involvement of external code, kudos to <http://jan.kneschke.de/projects/mysql/order-by-rand/> ``` SELECT name FROM random AS r1 JOIN (SELECT (RAND() * (SELECT MAX(id) FROM random)) AS id) AS r2 WHERE r1.id >= r2.id ORDER BY r1.id ASC LIMIT 1; ```
quick selection of a random row from a large table in mysql
[ "", "mysql", "sql", "select", "random", "" ]
Am I safe in casting a C++ bool to a Windows API BOOL via this construct ``` bool mybool = true; BOOL apiboolean = mybool ? TRUE : FALSE; ``` I'd assume this is a yes because I don't see any obvious problems but I wanted to take a moment to ask only because this may be more subtle than it appears. *Thanks to Dima for (gently) pointing out my carelessness in the way I'd originally phrased the question.*
Do you mean ``` bool b; ... BOOL apiboolean = b ? TRUE : FALSE; ``` If so, then yes, this will work.
Yes, that will work, but ``` bool b; ... BOOL apiboolean = (BOOL) b; ``` should work just as well, as does the reverse: ``` bool bb = (bool) apiboolean; ```
How do I cast a bool to a BOOL?
[ "", "c++", "winapi", "casting", "boolean", "" ]
A pattern that's started to show up a lot in one of the web apps I'm working are links that used to just be a regular a-tag link now need a popup box asking "are you sure?" before the link will go. (If the user hits cancel, nothing happens.) We've got a solution that works, but somehow we're a web app shop without a Javascript expert, so I'm left with this crawling feeling like there's a better way to get the job done. So, JS experts, what's the most standards-compliant, cross-browser way to get this done? (For the record, this is already a site that requires JS, so no need to have a "non-JS" version. But, it does need to work in any and all reasonably modern browsers.) (Also, for bonus points it would be nice if people with JS turned off didn't have the links work, rather than bypassing the confirm box.)
**Unobtrusive Javascript** The best practice is to add event handler methods to the links. The *confirm()* function produces the dialog box you described, and returns true or false depending on the user's choice. Event handler methods on links have a special behavior, which is that they kill the link action if they return false. ``` var link = document.getElementById('confirmToFollow'); link.onclick = function () { return confirm("Are you sure?"); }; ``` If you want the link to **require javascript**, the HTML must be edited. Remove the href: ``` <a href="#" id="confirmToFollow"... ``` You can explicitly set the link destination in the event handler: ``` var link = document.getElementById('confirmToFollow'); link.onclick = function () { if( confirm("Are you sure?") ) { window.location = "http://www.stackoverflow.com/"; } return false; }; ``` If you want the same method called on multiple links, you can acquire a nodeList of the links you want, and apply the method to each as you loop through the nodeList: ``` var allLinks = document.getElementsByTagName('a'); for (var i=0; i < allLinks.length; i++) { allLinks[i].onclick = function () { return confirm("Are you sure?"); }; } ``` There are further permutations of the same idea here, such as using a classname to determine which links will listen for the method, and to pass a unique location into each based on some other criteria. They are six of one, half dozen of another. **Alternative Approaches (not encouraged practices):** One **discouraged practice** is to attach a method via an **onclick attribute**: ``` <a href="mypage.html" onclick="... ``` Another **discouraged practice** is to set the **href attribute** to a function call: ``` <a href="javascript: confirmLink() ... ``` Note that these discouraged practices are all working solutions.
Here's how we've been doing it: ``` <a href="#" onClick="goThere(); return false;">Go to new page</a>` function goThere() { if( confirm("Are you sure?") ) { window.location.href="newPage.aspx"; } } ``` (EDIT: Code reformatted to avoid horizontal scroll)
What's the best way to replace links with JS functions?
[ "", "javascript", "" ]
I've got a Repeater and its SqlDatasource nested inside a Gridview TemplatedField. The Repeater's datasource SelectCommand is set using the FormatString of an Eval from the Gridview. The SelectCommand has a WHERE clause which is to compare a string. Because I have already used the single and double quotes, I am having trouble delimiting the string in the SQL WHERE clause. **How do I add single quotes inside an Eval FormatString?** I have tried using '[Replace](http://forums.asp.net/p/1116668/1732706.aspx#1732706)'. I have tried using '[Special Characters](http://www.firstobject.com/dn_markspecialchar.htm)' (... WHERE StringField = '{0}' ...) No luck so far. I appreciate any help you may be able to offer. ``` <asp:GridView ID="GridView1" runat="server" DataSourceID="DataSource1" DataKeyNames="Foo" AutoGenerateColumns="False" AllowSorting="true" > <Columns> <asp:BoundField DataField="Foo" HeaderText="Foo" SortExpression="Foo" /> <asp:BoundField DataField="Bar" HeaderText="Bar" SortExpression="Bar" /> <asp:TemplateField> <ItemTemplate> <asp:Repeater ID="Repeater1" runat="server" DataSourceID="DataSourceNested"> <ItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Eval("Blah") %>'></asp:Label> </ItemTemplate> </asp:Repeater> <asp:SqlDataSource ID="DataSourceNested" runat="server" DataFile="~/App_Data/DatabaseName" SelectCommand='<%# Eval("Bar", "SELECT Blah FROM TableName WHERE (StringField = {0})") %>' > </asp:SqlDataSource> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> ```
Don't forget that a .aspx page is simply XML. You just escape the quotes as you normally would. For example: ``` <asp:Repeater ID="repeatTheLabel" runat="server"> <ItemTemplate> <asp:Label ID="Label1" Text="<%# Eval(&quot;Id&quot;, &quot;This is item '{0}'.&quot;) %>" runat="server" /> </ItemTemplate> <SeparatorTemplate> <br /> </SeparatorTemplate> </asp:Repeater> ``` When the above expression is databound the value between `<%#` and `%>` becomes: > `Eval("Id", "This is item '{0}'.")` ...which produces on the HTML page as output when databound with an array of objects with "Id" property values from 1 to 5: > This is item '1'. > This is item '2'. > This is item '3'. > This is item '4'. > This is item '5'.
Why don't you define this WHERE clause as a const in your codebehind. Define: ``` protected const string SELECTCLAUSE = "SELECT Blah FROM TableName WHERE (StringField = '{0}')"; ``` Then your SelectCommand property would be: ``` SelectCommand='<%# Eval("Bar", SELECTCLAUSE ) %>' ```
How to use Single Quotes in Eval Format String
[ "", "asp.net", "sql", "eval", "string-formatting", "" ]
In oracle, I want to create a delete sproc that returns an integer based on the outcome of the deletion. this is what i have so far. ``` create or replace PROCEDURE Testing ( iKey IN VARCHAR2 ) AS BEGIN delete from MyTable WHERE TheKey = iKey; END Testing; ``` i've tried putting a RETURNS INTEGER in but the sproc won't compile.
Use a function and the implicit SQL cursor to determine the number of rows deleted ``` create or replace FUNCTION Testing ( iKey IN VARCHAR2 ) RETURN INTEGER AS BEGIN delete from MyTable WHERE TheKey = iKey; RETURN SQL%ROWCOUNT; END Testing; ``` That should work
A procedure does not return a value. A function returns a value, but you shouldn't be doing DML in a function (otherwise you cannot do things like reference the function in a SQL statement, you confuse permission grants since normally DBAs want to be able to grant read-only users access to all the functions so that users are doing computations consistently, etc.). You can add an OUT parameter to the procedure to return the status. If "success" means that one or more rows were updated, you can use SQL%ROWCOUNT to get a count of the number of rows modified by the prior SQL statement and use that to populate the return parameter, i.e. ``` CREATE OR REPLACE PROCEDURE test_proc ( p_iKey IN VARCHAR2, p_retVal OUT INTEGER ) AS BEGIN DELETE FROM myTable WHERE theKey = p_iKey; IF( SQL%ROWCOUNT >= 1 ) THEN p_retVal := 1; ELSE p_retVal := 0; END IF; END test_proc; ``` Of course, from a general code clarity standpoint, I'm dubious about OUT parameters that appear to be trying to return a status code. You are generally much better served by assuming success and throwing exceptions in the event of an error.
oracle procedure returns integer
[ "", "sql", "oracle", "" ]
Does Eclipse have a feature that lets you search a project to find all calls to deprecated methods?
You can set the compiler to generate errors or warnings (your choice) for any usage of deprecated API. > Preferences -> Java -> Compiler -> Errors/Warnings -> *Deprecated and restricted API* section. Then, each use of a deprecated method or API will show up as an error/warning in the Problems view.
*[Updating eight years later, for current versions of Eclipse, with screenshots.]* **First, build your projects.** Once you've built your projects, the Problems view includes deprecations by default. You can group all the deprecations together. **To show the Problems view,** use *Window>Show View>Problems*. **If deprecations don't appear after the next step**, you can configure them in Preferences under *Java>Compiler>Errors/Warnings*. **Group deprecations together** using the Problem view menu. Start by clicking the control circled below. [![Menu to gruop by Java problem type](https://i.stack.imgur.com/hIu5k.png)](https://i.stack.imgur.com/hIu5k.png) Once you've done that, open the "Deprecation" subtree. For example: [![enter image description here](https://i.stack.imgur.com/avN90.png)](https://i.stack.imgur.com/avN90.png)
Can Eclipse Be Used To Find All Deprecated Method Calls?
[ "", "java", "eclipse", "ide", "" ]
Is there a way to declare a variable as Nullable in c#? ``` struct MyStruct { int _yer, _ner; public MyStruct() { _yer = Nullable<int>; //This does not work. _ner = 0; } } ```
\_yer must be declare as int? or Nullable<int>. ``` int? _yer; int _ner; public MyStruct(int? ver, int ner) { _yer = ver; _ner = ner; } } ``` Or like this: ``` Nullable<int> _yer; int _ner; public MyStruct(Nullable<int> ver, int ner) { _yer = ver; _ner = ner; } } ``` **Remember that structs cannot contain explicit parameterless constructors.** ``` error CS0568: Structs cannot contain explicit parameterless constructors ```
Try declaring your variable like this: ``` int? yer; ```
Initialising a struct variable to Nullable<int>
[ "", "c#", ".net", "nullable", "" ]
What is the purpose of the colon before a block in Python? Example: ``` if n == 0: print "The end" ```
The colon is there to declare the start of an indented block. Technically, it's not necessary; you could just indent and de-indent when the block is done. However, based on the [Python koan](http://www.python.org/dev/peps/pep-0020/) “explicit is better than implicit” (EIBTI), I believe that Guido deliberately made the colon obligatory, so *any* statement that *should* be followed by indented code ends in a colon. (It also allows one-liners if you continue after the colon, but this style is not in wide use.) It also makes the work of syntax-aware auto-indenting editors easier, which also counted in the decision. --- This question turns out to be a [Python FAQ](http://docs.python.org/faq/design.html#why-are-colons-required-for-the-if-while-def-class-statements), and I found one of its answers by Guido [here](http://markmail.org/message/ve7mwqxhci4pm6lw): > **Why are colons required for the if/while/def/class statements?** > > The colon is required primarily to enhance readability (one of the results of the experimental ABC language). Consider this: > > ``` > if a == b > print a > ``` > > versus > > ``` > if a == b: > print a > ``` > > Notice how the second one is slightly easier to read. Notice further how a colon sets off the example in this FAQ answer; it’s a standard usage in English. > > Another minor reason is that the colon makes it easier for editors with syntax highlighting; they can look for colons to decide when indentation needs to be increased instead of having to do a more elaborate parsing of the program text.
Consider the following list of things to buy from the grocery store, written in Pewprikanese. ``` pewkah lalala chunkykachoo pewpewpew skunkybacon ``` When I read that, I'm confused, Are chunkykachoo and pewpewpew a kind of lalala? Or what if chunkykachoo and pewpewpew are indented just because they are special items? Now see what happens when my Pewprikanese friend add a colon to help me parse the list better: (<-- like this) ``` pewkah lalala: (<-- see this colon) chunkykachoo pewpewpew skunkybacon ``` Now it's clear that chunkykachoo and pewpewpew are a kind of lalala. Let's say there is a person who's starting to learn Python, which happens to be her first programming language to learn. Without colons, there's a considerable probability that she's going to keep thinking "this lines are indented because this lines are like special items.", and it could take a while to realize that that's not the best way to think about indentation.
What is the purpose of the colon before a block in Python?
[ "", "python", "syntax", "" ]
Is it better to learn how to code AJAX without the use of an AJAX library? What are the advantages of coding from scratch over using a library such as jQuery? ### See also: [What are some of the pros and cons of using jQuery?](https://stackoverflow.com/questions/122902/what-are-some-of-the-pros-and-cons-of-using-jquery)
For learning, yes, avoid libraries. Especially for something as conceptually simple as AJAX, forcing yourself to learn how the browser can be used "raw" will benefit you immensely later on, even if you are using a library to take care of the drudgery and abstract away browser differences. Once you have a solid understanding of how it works though, use a library, if for no other reason than spending time working around subtle browser differences is a waste. Better yet though, spending some time reading through the source of jQuery and others will give you insight into what well-written JavaScript looks like - and that in turn will benefit the code you *do* write!
While I think it is really important to understand conceptually what is going on and be able to correctly implement calls using an AJAX library, I disagree with @Shog9 that you need to write the actual code to perform an XmlHttpRequest in order to start using AJAX. I'd say do some background reading to understand the concepts -- implement the code samples demonstrating them if you want -- but once you get the concept, find some tutorials on how to do stuff with AJAX with or without libraries. You'll soon find that others have been there before and left pretty good sign-posts on how to get around. I agree with the sentiment about looking at framework code to see how to write good code.
Should I avoid using a JavaScript library while learning how to write AJAX client code?
[ "", "javascript", "ajax", "" ]
I have a class called `Ship` and a class called `Lifeboat` Lifeboat inherits from Ship. Ship contains a method called `Validate()` which is called before save and it has an abstract method called `FurtherValidate()` which it calls from Validate. The reason this is in place is so when you call validate on the base it also validates the class that is inheriting. So we have ``` public class Ship public bool Validate() { //validate properties only found on a ship FurtherValidate(); } public abstract bool FurtherValidate(); ``` So `Lifeboat` has ``` public override bool FurtherValidate() { //validate properties only found on a lifeboat } ``` This means anyone implementing `Ship` also needs to provide their own validation for their class and it's guaranteed to be called on the save as the base ship. `Validate()` is called which in turns calls the inherited validate. How can we re work this so we still force inherited classes to implement `FurtherValidate()` but `FurtherValidate()` can never be called by the programmer. Currently you can called `Lifeboat.FurtherValidate()` and I want to somehow prevent this.
The exact scenario you describe isn't possible. You can restrict access to the `FurtherValidate` method to only derived classes by using the `protected` access modifier. You could also restrict it to only classes in the same assembly by using the `internal` modifier, but this would still allow the programmer writing the derived class to call FurtherValidate any time they wish. Using both protected and internal combines the two and really means that is restricted to derived classes or classes defined in the same assembly. Using the [EditorBrowsable] attribute is an IDE trick that will hide the method from IntelliSense (unless the other programmer has turned on the right options in VS). That will effectively prevent most people from calling it (if they can't see it, it doesn't exist). You could possibly achieve this using reflection to interrogate who your caller is, but I think the performance costs of doing this would be too high compared to the benefit.
``` protected abstract bool FurtherValidate(); ``` only Ship and Lifeboat can see it now. EDIT: Lifeboat must be able to see it. How should it be able to override `FurtherValidate` when it can't even see it. I would rename it to `ValidateCore`, the 'Core' part (to me) implies that it should not be called without a very good reason. I don't think it's easy to make it abstract but not visible. You need to have some faith in your lifeboat ;)
How do I hide a method so it's not called by programmers but still usable in code?
[ "", "c#", "inheritance", "" ]
I'm serializing an object in a C# VS2003 / .Net 1.1 application. I need it serialized without the processing instruction, however. The XmlSerializer class puts out something like this: ``` <?xml version="1.0" encoding="utf-16" ?> <MyObject> <Property1>Data</Property1> <Property2>More Data</Property2> </MyObject> ``` Is there any way to get something like the following, without processing the resulting text to remove the tag? ``` <MyObject> <Property1>Data</Property1> <Property2>More Data</Property2> </MyObject> ``` For those that are curious, my code looks like this... ``` XmlSerializer serializer = new XmlSerializer(typeof(MyObject)); StringBuilder builder = new StringBuilder(); using ( TextWriter stringWriter = new StringWriter(builder) ) { serializer.Serialize(stringWriter, comments); return builder.ToString(); } ```
The following link will take you to a post where someone has a method of supressing the processing instruction by using an XmlWriter and getting into an 'Element' state rather than a 'Start' state. This causes the processing instruction to not be written. [Suppress Processing Instruction](http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.webservices/2004-03/0315.html) > If you pass an XmlWriter to the serializer, it will only emit a processing > instruction if the XmlWriter's state is 'Start' (i.e., has not had anything > written to it yet). ``` // Assume we have a type named 'MyType' and a variable of this type named 'myObject' System.Text.StringBuilder output = new System.Text.StringBuilder(); System.IO.StringWriter internalWriter = new System.IO.StringWriter(output); System.Xml.XmlWriter writer = new System.Xml.XmlTextWriter(internalWriter); System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(MyType)); writer.WriteStartElement("MyContainingElement"); serializer.Serialize(writer, myObject); writer.WriteEndElement(); ``` > In this case, the writer will be in a state of 'Element' (inside an element) > so no processing instruction will be written. One you finish writing the > XML, you can extract the text from the underlying stream and process it to > your heart's content.
I made a small correction ``` XmlSerializer serializer = new XmlSerializer(typeof(MyObject)); StringBuilder builder = new StringBuilder(); XmlWriterSettings settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = true; using ( XmlWriter stringWriter = XmlWriter.Create(builder, settings) ) { serializer.Serialize(stringWriter, comments); return builder.ToString(); } ```
Omitting XML processing instruction when serializing an object
[ "", "c#", ".net", "xml-serialization", "visual-studio-2003", "" ]
To use [modular exponentiation](http://en.wikipedia.org/wiki/Modular_exponentiation) as you would require when using the [Fermat Primality Test](http://en.wikipedia.org/wiki/Fermat_primality_test) with large numbers (100,000+), it calls for some very large calculations. When I multiply two large numbers (eg: 62574 and 62574) PHP seems to cast the result to a float. Getting the modulus value of that returns strange values. ``` $x = 62574 * 62574; var_dump($x); // float(3915505476) ... correct var_dump($x % 104659); // int(-72945) ... wtf. ``` Is there any way to make PHP perform these calculations properly? Alternatively, is there another method for finding modulus values that would work for large numbers?
For some reason, there are two standard libraries in PHP handling the arbitrary length/precision numbers: [BC Math](http://www.php.net/manual/en/book.bc.php) and [GMP](http://www.php.net/manual/en/book.gmp.php). I personally prefer GMP, as it's fresher and has richer API. Based on GMP I've implemented [Decimal2 class](https://github.com/ikr/money-math-php) for storing and processing currency amounts (like USD 100.25). *A lot* of mod calculations there w/o any problems. Tested with *very* large numbers.
use this ``` $num1 = "123456789012345678901234567890"; $num2 = "9876543210"; $r = mysql_query("Select @sum:=$num1 + $num2"); $sumR = mysql_fetch_row($r); $sum = $sumR[0]; ```
Working with large numbers in PHP
[ "", "php", "bignum", "" ]
I'd like to write some unit tests for some code that connects to a database, runs one or more queries, and then processes the results. (Without actually using a database) Another developer here wrote our own DataSource, Connection, Statement, PreparedStatement, and ResultSet implementation that will return the corresponding objects based on an xml configuration file. (we could use the bogus datasource and just run tests against the result sets it returns). Are we reinventing the wheel here? Does something like this exist already for unit testing? Are there other / better ways to test jdbc code?
You could use [DBUnit](http://dbunit.sourceforge.net/) together with a [HSQLDB](http://hsqldb.org/) which can read its initial data from CSV files for example.
You have several options: * Mock the database with a Mock library, e.g. [JMock](http://www.jmock.org/). The huge drawback of this that your queries and the data will most likely be not tested at all. * Use a light weight database for the tests, such as [HSQLDB](http://hsqldb.org/). If your queries are simple, this is probably the easiest way to go. * Dedicate a database for the tests. [DBUnit](http://dbunit.sourceforge.net/) is a good option, or if you are using Maven, you can also use the [sql-maven-plugin](http://www.mojohaus.org/sql-maven-plugin/) to set up and tear down the database properly (be careful of dependencies between tests). I recommend this option as it will give you the biggest confidence that the queries work properly with your db vendor. Sometimes it is necessary and useful to make these tests configurable so that these tests are only executed if the database is available. This can be done with e.g. build properties.
How do I unit test jdbc code in java?
[ "", "java", "database", "unit-testing", "jdbc", "junit", "" ]
I have seen a codebase recently that I fear is violating alignment constraints. I've scrubbed it to produce a minimal example, given below. Briefly, the players are: * *Pool*. This is a class which allocates memory efficiently, for some definition of 'efficient'. *Pool* is guaranteed to return a chunk of memory that is aligned for the requested size. * *Obj\_list*. This class stores homogeneous collections of objects. Once the number of objects exceeds a certain threshold, it changes its internal representation from a list to a tree. The size of *Obj\_list* is one pointer (8 bytes on a 64-bit platform). Its populated store will of course exceed that. * *Aggregate*. This class represents a very common object in the system. Its history goes back to the early 32-bit workstation era, and it was 'optimized' (in that same 32-bit era) to use as little space as possible as a result. *Aggregate*s can be empty, or manage an arbitrary number of objects. In this example, *Aggregate* items are always allocated from *Pool*s, so they are always aligned. The only occurrences of *Obj\_list* in this example are the 'hidden' members in *Aggregate* objects, and therefore they are always allocated using *placement new*. Here are the support classes: ``` class Pool { public: Pool(); virtual ~Pool(); void *allocate(size_t size); static Pool *default_pool(); // returns a global pool }; class Obj_list { public: inline void *operator new(size_t s, void * p) { return p; } Obj_list(const Args *args); // when constructed, Obj_list will allocate representation_p, which // can take up much more space. ~Obj_list(); private: Obj_list_store *representation_p; }; ``` And here is Aggregate. Note that member declaration *member\_list\_store\_d*: ``` // Aggregate is derived from Lesser, which is twelve bytes in size class Aggregate : public Lesser { public: inline void *operator new(size_t s) { return Pool::default_pool->allocate(s); } inline void *operator new(size_t s, Pool *h) { return h->allocate(s); } public: Aggregate(const Args *args = NULL); virtual ~Aggregate() {}; inline const Obj_list *member_list_store_p() const; protected: char member_list_store_d[sizeof(Obj_list)]; }; ``` It is that data member that I'm most concerned about. Here is the pseudocode for initialization and access: ``` Aggregate::Aggregate(const Args *args) { if (args) { new (static_cast<void *>(member_list_store_d)) Obj_list(args); } else { zero_out(member_list_store_d); } } inline const Obj_list *Aggregate::member_list_store_p() const { return initialized(member_list_store_d) ? (Obj_list *) &member_list_store_d : 0; } ``` You may be tempted to suggest that we replace the char array with a pointer to the *Obj\_list* type, initialized to NULL or an instance of the class. This gives the proper semantics, but just shifts the memory cost around. If memory were still at a premium (and it might be, this is an EDA database representation), replacing the char array with a pointer to an *Obj\_list* would cost one more pointer in the case when *Aggregate* objects *do* have members. Besides that, I don't really want to get distracted from the main question here, which is alignment. I *think* the above construct is problematic, but can't really find more in the standard than some vague discussion of the alignment behavior of the 'system/library' *new*. So, does the above construct do anything more than cause an occasional pipe stall? **Edit**: I realize that there are ways to *replace* the approach using the embedded char array. So did the original architects. They discarded them because memory was at a premium. Now, if I have a reason to touch that code, I'll probably change it. However, my question, about the alignment issues inherent in this approach, is what I hope people will address. Thanks!
Ok - had a chance to read it properly. You have an alignment problem, and invoke undefined behaviour when you access the char array as an Obj\_list. Most likely your platform will do one of three things: let you get away with it, let you get away with it at a runtime penalty or occasionally crash with a bus error. Your portable options to fix this are: * allocate the storage with malloc or a global allocation function, but you think this is too expensive. * as Arkadiy says, make your buffer an Obj\_list member: ``` Obj_list list; ``` but you now don't want to pay the cost of construction. You could mitigate this by providing an inline do-nothing constructor to be used only to create this instance - as posted the default constructor would do. If you follow this route, strongly consider invoking the dtor ``` list.~Obj_list(); ``` before doing a placement new into this storage. Otherwise, I think you are left with non portable options: either rely on your platform's tolerance of misaligned accesses, or else use any nonportable options your compiler gives you. Disclaimer: It's entirely possible I'm missing a trick with unions or some such. It's an unusual problem.
If you want to ensure alignment of your structures, just do a ``` // MSVC #pragma pack(push,1) // structure definitions #pragma pack(pop) // *nix struct YourStruct { .... } __attribute__((packed)); ``` To ensure 1 byte alignment of your char array in Aggregate
What is the Performance, Safety, and Alignment of a Data member hidden in an embedded char array in a C++ Class?
[ "", "c++", "alignment", "" ]
I have several identical elements with different attributes that I'm accessing with SimpleXML: ``` <data> <seg id="A1"/> <seg id="A5"/> <seg id="A12"/> <seg id="A29"/> <seg id="A30"/> </data> ``` I need to remove a specific **seg** element, with an id of "A12", how can I do this? I've tried looping through the **seg** elements and *unset*ting the specific one, but this doesn't work, the elements remain. ``` foreach($doc->seg as $seg) { if($seg['id'] == 'A12') { unset($seg); } } ```
While [SimpleXML](http://de.php.net/manual/en/book.simplexml.php) provides [a way to remove](https://stackoverflow.com/a/16062633/367456) XML nodes, its modification capabilities are somewhat limited. One other solution is to resort to using the [DOM](http://de.php.net/manual/en/book.dom.php) extension. [dom\_import\_simplexml()](http://de.php.net/manual/en/function.dom-import-simplexml.php) will help you with converting your `SimpleXMLElement` into a `DOMElement`. Just some example code (tested with PHP 5.2.5): ``` $data='<data> <seg id="A1"/> <seg id="A5"/> <seg id="A12"/> <seg id="A29"/> <seg id="A30"/> </data>'; $doc=new SimpleXMLElement($data); foreach($doc->seg as $seg) { if($seg['id'] == 'A12') { $dom=dom_import_simplexml($seg); $dom->parentNode->removeChild($dom); } } echo $doc->asXml(); ``` outputs ``` <?xml version="1.0"?> <data><seg id="A1"/><seg id="A5"/><seg id="A29"/><seg id="A30"/></data> ``` By the way: selecting specific nodes is much more simple when you use XPath ([SimpleXMLElement->xpath](http://de.php.net/manual/en/function.simplexml-element-xpath.php)): ``` $segs=$doc->xpath('//seq[@id="A12"]'); if (count($segs)>=1) { $seg=$segs[0]; } // same deletion procedure as above ```
Contrary to popular belief in the existing answers, each Simplexml element node can be removed from the document just by itself and `unset()`. The point in case is just that you need to understand how SimpleXML actually works. First locate the element you want to remove: ``` list($element) = $doc->xpath('/*/seg[@id="A12"]'); ``` Then remove the element represented in `$element` you unset its *self-reference*: ``` unset($element[0]); ``` This works because the first element of any element is the element itself in Simplexml (self-reference). This has to do with its magic nature, numeric indices are representing the elements in any list (e.g. parent->children), and even the single child is such a list. Non-numeric string indices represent attributes (in array-access) or child-element(s) (in property-access). Therefore numeric indecies in property-access like: ``` unset($element->{0}); ``` work as well. Naturally with that xpath example, it is rather straight forward (in PHP 5.4): ``` unset($doc->xpath('/*/seg[@id="A12"]')[0][0]); ``` The full example code ([Demo](http://eval.in/16674)): ``` <?php /** * Remove a child with a specific attribute, in SimpleXML for PHP * @link http://stackoverflow.com/a/16062633/367456 */ $data=<<<DATA <data> <seg id="A1"/> <seg id="A5"/> <seg id="A12"/> <seg id="A29"/> <seg id="A30"/> </data> DATA; $doc = new SimpleXMLElement($data); unset($doc->xpath('seg[@id="A12"]')[0]->{0}); $doc->asXml('php://output'); ``` Output: ``` <?xml version="1.0"?> <data> <seg id="A1"/> <seg id="A5"/> <seg id="A29"/> <seg id="A30"/> </data> ```
Remove a child with a specific attribute, in SimpleXML for PHP
[ "", "php", "xml", "dom", "simplexml", "" ]
I have been slowly learning SQL the last few weeks. I've picked up all of the relational algebra and the basics of how relational databases work. What I'm trying to do now is learn how it's implemented. A stumbling block I've come across in this, is foreign keys in MySQL. I can't seem to find much about the other than that they exist in the [InnoDB](http://en.wikipedia.org/wiki/InnoDB) storage schema that MySQL has. What is a simple example of foreign keys implemented in MySQL? Here's part of a schema I wrote that doesn't seem to be working if you would rather point out my flaw than show me a working example. ``` CREATE TABLE `posts` ( `pID` bigint(20) NOT NULL auto_increment, `content` text NOT NULL, `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `uID` bigint(20) NOT NULL, `wikiptr` bigint(20) default NULL, `cID` bigint(20) NOT NULL, PRIMARY KEY (`pID`), Foreign Key(`cID`) references categories, Foreign Key(`uID`) references users ) ENGINE=InnoDB; ```
Assuming your categories and users table already exist and contain cID and uID respectively as primary keys, this should work: ``` CREATE TABLE `posts` ( `pID` bigint(20) NOT NULL auto_increment, `content` text NOT NULL, `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `uID` bigint(20) NOT NULL, `wikiptr` bigint(20) default NULL, `cID` bigint(20) NOT NULL, PRIMARY KEY (`pID`), Foreign Key(`cID`) references categories(`cID`), Foreign Key(`uID`) references users(`uID`) ) ENGINE=InnoDB; ``` The column name is required in the `references` clause.
**Edited:** Robert and Vinko state that you need to declare the name of the referenced column in the foreign key constraint. This is necessary in InnoDB, although in standard SQL you're permitted to omit the referenced column name if it's the same name in the parent table. One idiosyncrasy I've encountered in MySQL is that foreign key declaration will fail silently in several circumstances: * Your MySQL installation doesn't include the innodb engine * Your MySQL config file doesn't enable the innodb engine * You don't declare your table with the ENGINE=InnoDB table modifier * The foreign key column isn't exactly the same data type as the primary key column in the referenced table Unfortunately, MySQL gives no message that it has failed to create the foreign key constraint. It simply ignores the request, and creates the table without the foreign key (if you SHOW CREATE TABLE posts, you may see no foreign key declaration). I've always thought this is a bad feature of MySQL! **Tip:** the integer argument for integer data types (e.g. BIGINT(20)) is not necessary. It has nothing to do with the storage size or range of the column. BIGINT is always the same size regardless of the argument you give it. The number refers to how many digits MySQL will pad the column if you use the ZEROFILL column modifier.
Foreign keys in MySQL?
[ "", "sql", "mysql", "foreign-keys", "" ]
I created an ASMX file with a code behind file. It's working fine, but it is outputting XML. However, I need it to output JSON. The ResponseFormat configuration doesn't seem to work. My code-behind is: ``` [System.Web.Script.Services.ScriptService] public class _default : System.Web.Services.WebService { [WebMethod] [ScriptMethod(UseHttpGet = true,ResponseFormat = ResponseFormat.Json)] public string[] UserDetails() { return new string[] { "abc", "def" }; } } ```
From [WebService returns XML even when ResponseFormat set to JSON](http://forums.asp.net/p/1327142/2652827.aspx): > Make sure that the request is a POST request, not a GET. Scott Guthrie has a [post explaining why](http://weblogs.asp.net/scottgu/archive/2007/04/04/json-hijacking-and-how-asp-net-ajax-1-0-mitigates-these-attacks.aspx). > > Though it's written specifically for jQuery, this may also be useful to you: > [Using jQuery to Consume ASP.NET JSON Web Services](http://web.archive.org/web/20160424034823/http://encosia.com/using-jquery-to-consume-aspnet-json-web-services)
To receive a pure JSON string, without it being wrapped into an XML, you have to write the JSON string directly to the `HttpResponse` and change the `WebMethod` return type to `void`. ``` [System.Web.Script.Services.ScriptService] public class WebServiceClass : System.Web.Services.WebService { [WebMethod] public void WebMethodName() { HttpContext.Current.Response.Write("{property: value}"); } } ```
How to let an ASMX file output JSON
[ "", "c#", "json", "asmx", "" ]
If I want to have a case-insensitive string-keyed dictionary, which version of StringComparer should I use given these constraints: * The keys in the dictionary come from either C# code or config files written in english locale only (either US, or UK) * The software is internationalized and will run in different locales I normally use StringComparer.InvariantCultureIgnoreCase but wasn't sure if that is the correct case. Here is example code: ``` Dictionary< string, object> stuff = new Dictionary< string, object>(StringComparer.InvariantCultureIgnoreCase); ```
[This MSDN article](http://msdn.microsoft.com/en-us/library/ms973919.aspx#stringsinnet20_topic4) covers everything you could possibly want to know in great depth, including the Turkish-I problem. It's been a while since I read it, so I'm off to do so again. See you in an hour!
There are three kinds of comparers: * Culture-aware * Culture invariant * Ordinal Each comparer has a **case-sensitive** as well as a **case-insensitive** version. An **ordinal** comparer uses ordinal values of characters. This is the fastest comparer, it should be used for internal purposes. A **culture-aware** comparer considers aspects that are specific to the culture of the current thread. It knows the "Turkish i", "Spanish LL", etc. problems. It should be used for UI strings. The **culture invariant** comparer is actually not defined and can produce unpredictable results, and thus should never be used at all. *References* 1. [New Recommendations for Using Strings in Microsoft .NET 2.0](http://msdn.microsoft.com/en-us/library/ms973919.aspx)
Which Version of StringComparer to use
[ "", "c#", ".net", "string", "internationalization", "" ]
In a forms model, I used to get the current logged-in user by: ``` Page.CurrentUser ``` How do I get the current user inside a controller class in ASP.NET MVC?
If you need to get the user from within the controller, use the `User` property of Controller. If you need it from the view, I would populate what you specifically need in the `ViewData`, or you could just call User as I think it's a property of `ViewPage`.
I found that `User` works, that is, `User.Identity.Name` or `User.IsInRole("Administrator")`.
How to get the current user in ASP.NET MVC
[ "", "c#", ".net", "asp.net-mvc", "iis", "forms-authentication", "" ]
I tried this: ``` ALTER TABLE My.Table DROP MyField ``` and got this error: -MyField is not a constraint. -Could not drop constraint. See previous errors. There is just one row of data in the table and the field was just added. **EDIT:** Just to follow up, the sql was missing COLUMN indeed. Now I get even more seriously looking errors though: * The object 'some\_object\_\_somenumbers' is dependent on column 'MyField' * ALTER TABLE DROP COLUMN MyField failed because one or more objects access this column. **EDIT:** ``` ALTER TABLE TableName DROP Constraint ConstraintName ``` worked, after that I was able to use the previous code to remove the column. Credit goes to both of you, thanks.
Brian solved your original problem - for your new problem (The object 'some\_object\_\_somenumbers' is dependent on column 'MyField') it means you have a dependancy issue. Something like an index, foreign key reference, default value, etc. To drop the constraint use: ``` ALTER TABLE TableName DROP ConstraintName ``` Also - you'll need to drop all the constraints dependant on that column before it'll let you drop the column itself.
I think you are just missing the COLUMN keyword: ``` ALTER TABLE TableName DROP COLUMN ColumnName ``` You will also need to make sure that any constraint that is depending on ColumnName is dropped first. You can do this by: ``` ALTER TABLE TableName DROP ConstraintName ``` For each constraint that you have. If you have indexes based on the column, you will also need to drop those indexes first. ``` DROP INDEX TableName.IndexName ```
How to remove a field from SQLServer2005 table
[ "", "sql", "sql-server-2005", "" ]
I've got a java server (not web based, more like a big, many-threaded standalone application) that needs to talk to a MS SQL Server database. I just worked on a different project that ported a home-grown O/R layer from oracle to SQL Server, and it ran into significant problems because of too many oracle assumptions (locking, mostly). So What O/R layer should I use? Edit: I have heard of Hibernate, but everything else is useful! Specifically though, do any of these APIs/frameworks help with the peculiar shortcomings of SQL Servers locking strategy in a multi-threaded environment?
I've used Hibernate and iBATIS. Choosing one over the other depends upon the situation. Hibernate: * is much pickier about database schema * generates most of the sql for you * more features * more complex iBATIS: * works better when you want to work with existing schema * requires you to write your own sql * easier to learn They both work well with SQL Server and handle multi threading.
**Hibernate** is the usual choice. Besides that you can take a look at Oracle TopLink, iBatis, whatever suites you best.
Java O/R layer for SQL server?
[ "", "java", "sql-server", "database", "orm", "" ]
I have mapped several java classes like Customer, Assessment, Rating, ... to a database with Hibernate. Now i am thinking about a history-mode for all changes to the persistent data. The application is a web application. In case of deleting (or editing) data another user should have the possibility to see the changes and undo it. Since the changes are out of the scope of the current session, i don't know how to solve this in something like the Command pattern, which is recommended for undo functionality. For single value editing an approach like in this [question](https://stackoverflow.com/questions/141612/database-structure-to-track-change-history) sounds OK. But what about the deletion of a whole persistent entity? The simplest way is to create a flag in the table if this customer is deleted or not. The complexest way is to create a table for each class where deleted entities are stored. Is there anything in between? And how can i integrate these two things in a O/RM system (in my case Hibernate) comfortably, without messing around to much with SQL (which i want to avoid because of portability) and still have enough flexibility? Is there a best practice?
One way to do it would be to have a "change history" entity with properties for entity id of the entity changed, action (edit/delete), property name, orginal value, new value. Maybe also reference to the user performing the edit. A deletion would create entities for all properties of the deleted entity with action "delete". This entity would provide enough data to perform undos and viewing of change history.
One approach to maintaining audit/undo trails is to mark each version of an object's record with a version number. Finding the current version would be a painful effort if the this were a simple version number, so a reverse version numbering works best. "version' 0 is always the current and if you do an update the version numbers for all previous versions are incremented. Deleting an object is done by incrementing the version numbers on the current records and not inserting a new one at 0. Compared to an attribute-by-attribute approach this make for far simpler rollbacks or historic version views but does take more space.
Best practice to realize a long-term history-mode for a O/RM system(Hibernate)?
[ "", "java", "database", "hibernate", "orm", "" ]
I've been working with some C# legacy code and I've been seeing a lot of @ symbols in front of variable names. What does this signify or do? Currently I'm seeing it a lot in front of variables with common names that aren't reserved. E.g.: ``` MyProcedure(@step.LoadInstanceId, @step.ResultCode, @step.StatusCode); ``` Given that step isn't a reserved word, is there any reason that they should be escaped?
It's just a way to allow declaring reserved keywords as vars. ``` void Foo(int @string) ```
It allows you to use a reserved word, like 'public' for example, as a variable name. ``` string @public = "foo"; ``` I would not recommend this, as it can lead to unecessary confusion.
What does placing a @ in front of a C# variable name do?
[ "", "c#", "" ]
I have an abstract base class which acts as an interface. I have two "sets" of derived classes, which implement half of the abstract class. ( one "set" defines the abstract virtual methods related to initialization, the other "set" defines those related to the actual "work". ) I then have derived classes which use multiple inheritance to construct fully defined classes ( and does not add anything itself ). So: ( bad pseudocode ) ``` class AbsBase { virtual void init() = 0; virtual void work() = 0; } class AbsInit : public AbsBase { void init() { do_this(); } // work() still abs } class AbsWork : public AbsBase { void work() { do_this(); } // init() still abs } class NotAbsTotal : public AbsInit, public AbsWork { // Nothing, both should be defined } ``` First of all, can I do this? Can I inherit from two classes which are both derived from the same Base? (I hope so). Here is the "real problem", though (I lied a bit above to simplify the example). What I have really gone and done is add non abstract accessors methods to the base class: ``` class AbsBase { public: void init() { init_impl(); } void work() { work_impl(); } private: virtual void init_impl() = 0; virtual void work_impl() = 0; } ``` Because, a common idiom is to make all virtual methods private. Unfortunately, now both AbsInit, and AbsWork inherit these methods, and so NotAbsTotal inherits "two of each" ( I realize I may be butchering what is really happening at compile time ). Anyway, g++ complains that: "request for member init() is ambiguous" when trying to use the class. I assume that, had I used my AbsBase class as a pure interface, this would have been avoided ( assuming that the top example is valid ). So: - Am I way off with my implementation? - Is this a limitation of the idiom of making virtual methods private? - How do I refactor my code to do what I want? ( Provide one common interface, but allow a way to swap out implementations for "sets" of member functions ) Edit: Seems I am not the first one: <http://en.wikipedia.org/wiki/Diamond_problem> Seems Virtual Inheritance is the solution here. I have heard of virtual inheritance before, but I have not wrapped my head around it. I am still open to suggestions.
It looks like you want to do virtual inheritance. Whether that turns out to actually be a good idea is another question, but here's how you do it: ``` class AbsBase {...}; class AbsInit: public virtual AbsBase {...}; class AbsWork: public virtual AbsBase {...}; class NotAbsTotal: public AbsInit, public AbsWork {...}; ``` Basically, the default, non-virtual multiple inheritance will include a copy of *each base class* in the derived class, and includes all their methods. This is why you have two copies of AbsBase -- and the reason your method use is ambiguous is both sets of methods are loaded, so C++ has no way to know which copy to access! Virtual inheritance condenses all references to a virtual base class into one datastructure. This should make the methods from the base class unambiguous again. However, note: if there is additional data in the two intermediate classes, there may be some small additional runtime overhead, to enable the code to find the shared virtual base class.
It can be done, although it gives most the shivers. You need to use "virtual inheritance", the syntax for which is something like ``` class AbsInit: public virtual AbsBase {...}; class AbsWork: public virtual AbsBase {...}; class NotAbsTotal: public AbsInit, public AbsWork {...}; ``` Then you have to specify which function you want to use: ``` NotAbsTotal::work() { AbsInit::work_impl(); } ``` (UPDATED with correct syntax)
Multiple Inheritance from two derived classes
[ "", "c++", "inheritance", "multiple-inheritance", "" ]
In my spring application context file, I have something like: ``` <util:map id="someMap" map-class="java.util.HashMap" key-type="java.lang.String" value-type="java.lang.String"> <entry key="some_key" value="some value" /> <entry key="some_key_2" value="some value" /> </util:map> ``` In java class, the implementation looks like: ``` private Map<String, String> someMap = new HashMap<String, String>(); someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap"); ``` In Eclipse, I see a warning that says: **Type safety: Unchecked cast from Object to HashMap<String,String>** What went wrong?
The problem is that a cast is a runtime check - but due to type erasure, at runtime there's actually no difference between a `HashMap<String,String>` and `HashMap<Foo,Bar>` for any other `Foo` and `Bar`. Use `@SuppressWarnings("unchecked")` and hold your nose. Oh, and campaign for reified generics in Java :)
Well, first of all, you're wasting memory with the new `HashMap` creation call. Your second line completely disregards the reference to this created hashmap, making it then available to the garbage collector. So, don't do that, use: ``` private Map<String, String> someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap"); ``` Secondly, the compiler is complaining that you cast the object to a `HashMap` without checking if it is a `HashMap`. But, even if you were to do: ``` if(getApplicationContext().getBean("someMap") instanceof HashMap) { private Map<String, String> someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap"); } ``` You would probably still get this warning. The problem is, `getBean` returns `Object`, so it is unknown what the type is. Converting it to `HashMap` directly would not cause the problem with the second case (and perhaps there would not be a warning in the first case, I'm not sure how pedantic the Java compiler is with warnings for Java 5). However, you are converting it to a `HashMap<String, String>`. HashMaps are really maps that take an object as a key and have an object as a value, `HashMap<Object, Object>` if you will. Thus, there is no guarantee that when you get your bean that it can be represented as a `HashMap<String, String>` because you could have `HashMap<Date, Calendar>` because the non-generic representation that is returned can have any objects. If the code compiles, and you can execute `String value = map.get("thisString");` without any errors, don't worry about this warning. But if the map isn't completely of string keys to string values, you will get a `ClassCastException` at runtime, because the generics cannot block this from happening in this case.
Type safety: Unchecked cast
[ "", "java", "spring", "type-safety", "unchecked", "" ]
I need to create reports in a C# .NET Windows app. I've got an SQL Server 2005 database, Visual Studio 2005 and am quite OK with creating stored procedures and datasets. Can someone please point me in the right direction for creating reports? I just can't seem work it out. Some examples would be a good start, or a simple How-to tutorial... anything really that is a bit better explained than the MSDN docs. I'm using the CrystalDecisions.Windows.Forms.CrystalReportViewer control to display the reports, I presume this is correct. If I'm about to embark on a long and complex journey, what's the simplest way to create and display reports that can also be printed?
I have managed to make this work now. **Brief Overview** It works by having a 'data class' which is just a regular C# class containing variables and no code. This is then instantiated and filled with data and then placed inside an ArrayList. The ArrayList is bound to the report viewer, along with the name of the report to load. In the report designer '.Net Objects' are used, rather than communicating with the database. **Explanation** I created a class to hold the data for my report. This class is manually filled by me by manually retrieving data from the database. How you do this doesn't matter, but here's an example: ``` DataSet ds = GeneratePickingNoteDataSet(id); foreach (DataRow row in ds.Tables[0].Rows) { CPickingNoteData pickingNoteData = new CPickingNoteData(); pickingNoteData.delivery_date = (DateTime)row["delivery_date"]; pickingNoteData.cust_po = (int)row["CustomerPONumber"]; pickingNoteData.address = row["CustomerAddress"].ToString(); // ... and so on ... rptData.Add(pickingNoteData); } ``` The class is then put inside an ArrayList. Each element in the arraylist corresponds to one 'row' in the finished report. The first element in the list can also hold the report header data, and the last element in the list can hold the report footer data. And because this is an ArrayList, normal Array access can be used to get at them: ``` ((CPickingNoteData)rptData[0]).header_date = DateTime.Now; ((CPickingNoteData)rptData[rptData.Count-1]).footer_serial = GenerateSerialNumber(); ``` Once you have an arraylist full of data, bind it to your report viewer like this, where 'rptData' is of type 'ArrayList' ``` ReportDocument reportDoc = new ReportDocument(); reportDoc.Load(reportPath); reportDoc.SetDataSource(rptData); crystalReportViewer.ReportSource = reportDoc; ``` Now you will need to bind your data class to the report itself. You do this inside the designer: 1. Open the Field Explorer tab (which might be under the 'View' menu), and right-click "Database Fields" 2. Click on 'Project Data' 3. Click on '.NET Objects' 4. Scroll down the list to find your data class (if it isn't there, compile your application) 5. Press '>>' and then OK 6. You can now drag the class members onto the report and arrange them as you want.
Crystal is one possible option for creating reports. It has been around a long time and a lot of people seem to like it. You might want to take a look at SQL reporting services. I have used both but my preferance is SQL reporting services. Its pretty well integrated into studio and works similar to the other microsoft projects. Its also free with the sql express etc. This is a good article on beginning reporting services: <http://www.simple-talk.com/sql/learn-sql-server/beginning-sql-server-2005-reporting-services-part-1/>
Using Crystal Reports in Visual Studio 2005 (C# .NET Windows App)
[ "", "c#", ".net", "database", "visual-studio", "crystal-reports", "" ]
This [article](http://themechanicalbride.blogspot.com/2008/04/using-operators-with-generics.html) describes a way, in C#, to allow the addition of arbitrary value types which have a + operator defined for them. In essence it allows the following code: ``` public T Add(T val1, T val2) { return val1 + val2; } ``` This code does not compile as there is no guarantee that the T type has a definition for the '+' operator, but the effect is achieved with code like this: ``` public T Add(T val1, T val2) { //Num<T> defines a '+' operation which returns a value of type T return (new Num<T>(val1) + new Num<T>(val2)); } ``` Follow the link to see how the Num class achieves this. Anyways, on to the question. Is there any way to achieve the same effect in C or C++? For the curious, the problem I'm trying to solve is to allow a CUDA kernel to be more flexible/general by allowing it to operate on more types. **Update:** For .NET, Marc Gravell has made a [utility library](http://www.yoda.arachsys.com/csharp/miscutil/usage/genericoperators.html) which solves the operator problem very elegantly.
Due to the way templates are compiled in C++, simply doing: ``` template < class T > T add(T const & val1, T const & val2) { return val1 + val2; } ``` will work, you'll get a compile error for every type where an operator+ is not defined. C++ templates generate code for every type instantiation, so for every type T code will be generated that does the right thing. This way C++ doesn't need Num<> trickery. In plain C, this is not possible as far as I know.
**In C++ this is simply not an issue.** The code as in your first sample works if literally translated into C++ (ETA: as Pieter did), but I can't think of any situation where directly using + wouldn't work. You're looking for a solution to a problem that doesn't exist.
Operations on arbitrary value types
[ "", "c++", "c", "cuda", "gpgpu", "value-type", "" ]
In an application I work on, any business logic error causes an exception to be thrown, and the calling code handles the exception. This pattern is used throughout the application and works well. I have a situation where I will be attempting to execute a number of business tasks from inside the business layer. The requirement for this is that a failure of one task should not cause the process to terminate. Other tasks should still be able to execute. In other words, this is not an atomic operation. The problem I have is that at the end of the operation, I wish to notify the calling code that an exception or exceptions did occur by throwing an exception. Consider the following psuedo-code snippet: ``` function DoTasks(MyTask[] taskList) { foreach(MyTask task in taskList) { try { DoTask(task); } catch(Exception ex) { log.add(ex); } } //I want to throw something here if any exception occurred } ``` What do I throw? I have encountered this pattern before in my career. In the past I have kept a list of all exceptions, then thrown an exception that contains all the caught exceptions. This doesn't seem like the most elegant approach. Its important to preserve as many details as possible from each exception to present to the calling code. Thoughts? --- Edit: The solution must be written in .Net 3.5. I cannot use any beta libraries, or the AggregateException in .Net 4.0 as mentioned by [Bradley Grainger](/users/23633/bradley-grainger) (below) would be a nice solution for collection exceptions to throw.
The [Task Parallel Library extensions](http://msdn.microsoft.com/magazine/cc163340.aspx) for .NET (which [will become part of .NET 4.0](http://blogs.msdn.com/pfxteam/archive/2008/10/10/8994927.aspx)) follow the pattern suggested in other answers: collecting all exceptions that have been thrown into an AggregateException class. By always throwing the same type (whether there is one exception from the child work, or many), the calling code that handles the exception is easier to write. In the .NET 4.0 CTP, `AggregateException` has a public constructor (that takes `IEnumerable<Exception>`); it may be a good choice for your application. If you're targeting .NET 3.5, consider cloning the parts of the `System.Threading.AggregateException` class that you need in your own code, e.g., some of the constructors and the InnerExceptions property. (You can place your clone in the `System.Threading` namespace inside your assembly, which could cause confusion if you exposed it publicly, but will make upgrading to 4.0 easier later on.) When .NET 4.0 is released, you should be able to “upgrade” to the Framework type by deleting the source file containing your clone from your project, changing the project to target the new framework version, and rebuilding. Of course, if you do this, you need to carefully track changes to this class as Microsoft releases new CTPs, so that your code doesn't become incompatible. (For example, this seems like a useful general-purpose class, and they could move it from `System.Threading` to `System`.) In the worst case, you can just rename the type and move it back into your own namespace (this is very easy with most refactoring tools).
Two ways of the top of my head would be either make a custom exception and add the exceptions to this class and throw that the end : ``` public class TaskExceptionList : Exception { public List<Exception> TaskExceptions { get; set; } public TaskExceptionList() { TaskExceptions = new List<Exception>(); } } public void DoTasks(MyTask[] taskList) { TaskExceptionList log = new TaskExceptionList(); foreach (MyTask task in taskList) { try { DoTask(task); } catch (Exception ex) { log.TaskExceptions.Add(ex); } } if (log.TaskExceptions.Count > 0) { throw log; } } ``` or return true or false if the tasks failed and have a 'out List' variable. ``` public bool TryDoTasks(MyTask[] taskList, out List<Exception> exceptions) { exceptions = new List<Exception>(); foreach (MyTask task in taskList) { try { DoTask(task); } catch (Exception ex) { exceptions.Add(ex); } } if (exceptions.Count > 0) { return false; } else { exceptions = null; return true; } } ```
Throwing multiple exceptions in .Net/C#
[ "", "c#", ".net", "exception", "" ]
I want to setup a statistics monitoring platform to watch a specific service, but I'm not quiet sure how to go about it. Processing the intercepted data isn't my concern, just how to go about it. One idea was to setup a proxy between the client application and the service so that all TCP traffic went first to my proxy, the proxy would then delegate the intercepted messages to an awaiting thread/fork to pass the message on and recieve the results. The other was to try and sniff the traffic between client & service. My primary goal is to avoid any serious loss in transmission speed between client & application but get 100% complete communications between client & service. Environment: UBuntu 8.04 Language: c/c++ In the background I was thinking of using a sqlite DB running completely in memory or a 20-25MB memcache dameon slaved to my process. Update: Specifically I am trying to track the usage of keys for a memcache daemon, storing the # of sets/gets success/fails on the key. The idea is that most keys have some sort of separating character [`|\_-#] to create a sort of namespace. The idea is to step in between the daemon and the client, split the keys apart by a configured separator and record statistics on them.
You didn't mention one approach: you could modify memcached or your client to record the statistics you need. This is probably the easiest and cleanest approach. Between the proxy and the libpcap approach, there are a couple of tradeoffs: ``` - If you do the packet capture approach, you have to reassemble the TCP streams into something usable yourself. OTOH, if your monitor program gets bogged down, it'll just lose some packets, it won't break the cache. Same if it crashes. You also don't have to reconfigure anything; packet capture is transparent. - If you do the proxy approach, the kernel handles all the TCP work for you. You'll never lose requests. But if your monitor bogs down, it'll bog down the app. And if your monitor crashes, it'll break caching. You probably will have to reconfigure your app and/or memcached servers so that the connections go through the proxy. ``` In short, the proxy will probably be easier to code, but implementing it may be a royal pain, and it had better be perfect or its taking down your caching. Changing the app or memcached seems like the sanest approach to me. BTW: You have looked at memcached's built-in statistics reporting? I don't think its granular enough for what you want, but if you haven't seen it, take a look before doing actual work :-D
Exactly what are you trying to track? If you want a simple count of packets or bytes, or basic header information, then `iptables` will record that for you: ``` iptables -I INPUT -p tcp -d $HOST_IP --dport $HOST_PORT -j LOG $LOG_OPTIONS ``` If you need more detailed information, look into the `iptables ULOG` target, which sends each packet to userspace for analysis. See <http://www.netfilter.org> for *very* thorough docs.
Intercepting traffic to memcached for statistics/analysis
[ "", "c++", "c", "linux", "networking", "memcached", "" ]
In my C# source code I may have declared integers as: ``` int i = 5; ``` or ``` Int32 i = 5; ``` In the currently prevalent 32-bit world they are equivalent. However, as we move into a 64-bit world, am I correct in saying that the following will become the same? ``` int i = 5; Int64 i = 5; ```
No. The C# specification rigidly defines that `int` is an alias for `System.Int32` with exactly 32 bits. Changing this would be a *major* breaking change.
The `int` keyword in C# is defined as an alias for the `System.Int32` type and this is (judging by the name) meant to be a 32-bit integer. To the specification: > [CLI specification](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-335.pdf) section 8.2.2 (Built-in value and reference types) has a table with the following: > > * `System.Int32` - Signed 32-bit integer > > [C# specification](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf) section 8.2.1 (Predefined types) has a similar table: > > * `int` - 32-bit signed integral type This guarantees that both `System.Int32` in CLR and `int` in C# will always be 32-bit.
Is an int a 64-bit integer in 64-bit C#?
[ "", "c#", "64-bit", "32-bit", "primitive", "" ]
Is there any way that I can change how a Literal of a code snippet renders when it is used in the code that the snippet generates? Specifically I'd like to know if I can have a literal called say, $PropertyName$ and then get the snippet engine to render "\_$PropertyName$ where the first character is made lowercase. I can't afford R#. Please help :)
Unfortunately there seems to be no way. Snippets offer amazingly limited support for [transformation functions](http://msdn.microsoft.com/en-us/library/ms242312(VS.80).aspx) as you can see. You have to stick with the VS standard solution, which is to write two literals: one for the property name, and the other for the member variable name.
You can enter a upper first letter, then a property name, then a lower first letter. Try this snippet: ``` <?xml version="1.0" encoding="utf-8"?> <CodeSnippet Format="1.0.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"> <Header> <Title>Notifiable Property</Title> <Author>Nikolay Makhonin</Author> <Shortcut>propn</Shortcut> <Description>Property With in Built Property Changed method implementation.</Description> <SnippetTypes> <SnippetType>SurroundsWith</SnippetType> <SnippetType>Expansion</SnippetType> </SnippetTypes> </Header> <Snippet> <Declarations> <Literal> <ID>Type</ID> <Default>Type</Default> </Literal> <Literal> <ID>P</ID> <Default>P</Default> </Literal> <Literal> <ID>roperty</ID> <Default>ropertyName</Default> </Literal> <Literal> <ID>p</ID> <Default>p</Default> </Literal> <Literal> <ID>Ownerclass</ID> <ToolTip>The owning class of this Property.</ToolTip> <Function>ClassName()</Function> <Default>Ownerclass</Default> </Literal> </Declarations> <Code Language="CSharp"> <![CDATA[#region $P$$roperty$ private Field<$Type$> _$p$$roperty$; public static readonly string $P$$roperty$PropertyName = GetPropertyName(() => (($Ownerclass$)null).$P$$roperty$); public $Type$ $P$$roperty$ { get { return _$p$$roperty$; } set { Set(ref _$p$$roperty$, value); } } #endregion ]]> </Code> </Snippet> </CodeSnippet> ```
Formatting Literal parameters of a C# code snippet
[ "", "c#", "code-generation", "code-snippets", "" ]
I'm trying to access the command line and execute a command, and then return the output to my aspx page. A good example would be running dir on page load of an aspx page and returning the output via Response.Write(). I have tried using the code below. When I try debugging this it runs but never finishes loading and no output is rendered. I am using C# and .NET Framework 3.5sp1. Any help much appreciated. Thanks, Bryan ``` public partial class CommandLine : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { System.Diagnostics.Process si = new System.Diagnostics.Process(); si.StartInfo.WorkingDirectory = @"c:\"; si.StartInfo.UseShellExecute = false; si.StartInfo.FileName = "cmd.exe"; si.StartInfo.Arguments = "dir"; si.StartInfo.CreateNoWindow = true; si.StartInfo.RedirectStandardInput = true; si.StartInfo.RedirectStandardOutput = true; si.StartInfo.RedirectStandardError = true; si.Start(); string output = si.StandardOutput.ReadToEnd(); si.Close(); Response.Write(output); } } ```
You have a problem with the syntax of commandline arguments to cmd.exe. This is why cmd never exits. In order to have cmd.exe run a program and then quit, you need to send it the syntax "/c [command]". Try running the same code with the line ``` si.StartInfo.Arguments = "dir"; ``` replaced with ``` si.StartInfo.Arguments = "/c dir"; ``` and see if it works.
Most likely your problem is with the permissions. The user under which ASP.NET process runs is with very limited rights. So, either you have to set the proper permissions for that user, or run ASP.NET under some other user. This hides a security risks though, so you have to be very careful.
Running Command line from an ASPX page, and returning output to page
[ "", "c#", "asp.net", "" ]
Im trying to get into some basic JavaFX game development and I'm getting confused with some circle maths. I have a circle at (x:250, y:250) with a radius of 50. My objective is to make a smaller circle to be placed on the circumference of the above circle based on the position of the mouse. Where Im getting confused is with the coordinate space and the Trig behind it all. My issues come from the fact that the X/Y space on the screen is not centered at 0,0. But the top left of the screen is 0,0 and the bottom right is 500,500. My calculations are: ``` var xpos:Number = mouseEvent.getX(); var ypos:Number = mouseEvent.getY(); var center_pos_x:Number = 250; var center_pos_y:Number = 250; var length = ypos - center_pos_y; var height = xpos - center_pos_x; var angle_deg = Math.toDegrees(Math.atan(height / length)); var angle_rad = Math.toRadians(angle_deg); var radius = 50; moving_circ_xpos = (radius * Math.cos(angle_rad)) + center_pos_x; moving_circ_ypos = (radius * Math.sin(angle_rad)) + center_pos_y; ``` I made the app print out the angle (angle\_deg) that I have calculated when I move the mouse and my output is below: When the mouse is (in degrees moving anti-clockwise): * directly above the circle and horizontally inline with the center, the angle is -0 * to the left and vertically centered, the angle is -90 * directly below the circle and horizontally inline with the center, the angle is 0 * to the right and vertically centered, the angle is 90 So, what can I do to make it 0, 90, 180, 270?? I know it must be something small, but I just cant think of what it is... Thanks for any help (and no, this is not an assignment)
`atan(height/length)` is not enough to get the angle. You need to compensate for each quadrant, as well as the possibility of "division-by-zero". Most programming language libraries supply a method called `atan2` which take two arguments; `y` and `x`. This method does this calculation for you. More information on [Wikipedia: atan2](http://en.wikipedia.org/wiki/Atan2)
You can get away without calculating the angle. Instead, use the center of your circle (250,250) and the position of the mouse (xpos,ypos) to define a line. The line intersects your circle when its length is equal to the radius of your circle: ``` // Calculate distance from center to mouse. xlen = xpos - x_center_pos; ylen = ypos - y_center_pos; line_len = sqrt(xlen*xlen + ylen*ylen); // Pythagoras: x^2 + y^2 = distance^2 // Find the intersection with the circle. moving_circ_xpos = x_center_pos + (xlen * radius / line_len); moving_circ_ypos = y_center_pos + (ylen * radius / line_len); ``` Just verify that the mouse isn't at the center of your circle, or the line\_len will be zero and the mouse will be sucked into a black hole.
How to position a Node along a circular orbit around a fixed center based on mouse coordinates (JavaFX)?
[ "", "java", "geometry", "javafx", "trigonometry", "javafx-1", "" ]
I've been trying to use Firebug's profiler to better understand the source of some JavaScript performance issues we are seeing, but I'm a little confused by the output. When I profile some code the profiler reports **Profile (464.323 ms, 26,412 calls)**. I suspect that the 464.323 ms is the sum of the execution time for those 26,412 calls. However, when I drill down into the detailed results I see individual results with an *average* execution time greater than 464.323 ms, e.g. the result with the highest average time reports the following details: ``` Calls: **1** Percent: **0%** Own Time: **0.006 ms** Time: **783.506 ms** Avg: **783.506 ms** Min: **783.506 ms** Max: **783.506 ms** ``` Another result reports: ``` Calls: **4** Percent: **0.01%** Own Time: **0.032 ms** Time: **785.279 ms** Avg: **196.32 ms** Min: **0.012 ms** Max: **783.741 ms** ``` Between these two results the sum of the Time results is a lot more than 464.323. So, what do these various numbers mean? Which ones should I trust?
Each column has a description of what it means if you set your mouse to hover over it in Firebug. I'll assume you can read up on how each column works on your own then. However, you have definitely come across some odd behavior which needs to be explained. The *own time* is the amount of time the function spent executing code inside of itself. If the function calls no other functions, then *own time* should be the same as *time*. However, if there are nested function calls, then *time* also counts the time spent executing them. Therefore, *time* will almost always be larger than *own time*, and will in most cases add up to more than the total time reported by the profiler. However, no **single** function's *time* should be larger than the total time the profiler logged for JavaScript calls. This problem is definitely a bug, and I can see why you have trouble trusting Firebug when it gives you such a paradoxical output. I believe I've tracked down the reason this bug occurs: AJAX. It appears that AJAX calls are causing columns that count nested function calls to report incorrect information. They end up counting both the time of JavaScript execution **and** the request to the server. You can reproduce this profiler bug by doing the following: 1. Go to any site that uses AJAX. (I used <http://juicystudio.com/experiments/ajax/index.php>) 2. Enable Console/Script debugging. 3. Turn on the profiler. 4. Make an AJAX call. (Multiple ones may illuminate the issue more.) 5. Stop the profiler, examine the output. In this example, with regards to *time* vs. *own time*, the *own time* of each function adds up to the profiler's total time but the *time* column incorporates the amount of time the AJAX call took to talk to the server. This means that the *time* column is incorrect if you're looking for just the speed of JavaScript execution. It gets worst: since *time*, *average time*, *min* and *max* all count nested function calls, they're all incorrect if you're using AJAX. On top of that, any function that eventually uses AJAX (in a nested function call) will also report their time incorrectly. This means that a whole lot of functions may be reporting incorrect information! So don't trust any of those columns for now until Firebug fixes the issue. (It's possible they intended the behavior to be this way, though it is confusing at best to leave it this way.) If you're not using AJAX, then another issue is at play; let us know if you are or not.
If I understand things correctly it goes something like this: On the first line you'll see that the Own time is "only 0.006ms". That means that even though time spent in that function was 783.506ms most of it was spent inside functions called from that function. When I use Firebug to optimize code I try to reduce the "own time" of functions that are called the most. (obviously checking also for any unnecessary function calls to remove altogether)
Understanding Firebug profiler output
[ "", "javascript", "profiling", "firebug", "profiler", "" ]
Already implemented performance boosters : - Get compatible image of GraphicsConfiguration to draw on - Enable OpenGL pipeline in 1.5: Not possible due to severe artifacts So far I am fine, the main profiled bottleneck of the program is drawing an image with several thousand tiles. Unfortunately it is not regular, else I simply could set pixels and scale them. I accerelated the image with VolatileImages and own rendering routines (ignore repaint and draw it itself with a timer). The result was pleasing and would suffice, BUT: Choosing a JMenu which hovers normally over the part of the image is severely disturbed because the JMenu is overdrawn. Inacceptable and the layout couldn't be changed. I tried the GLJPanel of JOGL, but there is no visible performance improvement. So is there a possibitlity to use VolatileImages (or other accerelated lightweighted components like GLCanvas) and still get normal JMenu display and if yes, how ?
You could try to set the popups to non-leightweight. I am not quite sure if it works but it could, because the popup is a native component then and will not be overdrawn. Setting Popups to heavyweight: JPopupMenu.setDefaultLightWeightPopupEnabled(false) More Information: [Mixing heavy and light components](http://www.oracle.com/technetwork/articles/java/mixing-components-433992.html)
Here is some example code: ``` import javax.swing.*; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import java.awt.image.VolatileImage; import java.io.File; import java.io.IOException; import java.util.Timer; import java.util.TimerTask; public final class FastDraw extends JFrame { private static final transient double NANO = 1.0e-9; private BufferStrategy bs; private BufferedImage frontImg; private BufferedImage backImg; private int PIC_WIDTH, PIC_HEIGHT; private Timer timer; public FastDraw() { timer = new Timer(true); JMenu menu = new JMenu("Dummy"); menu.add(new JMenuItem("Display me !")); menu.add(new JMenuItem("Display me, too !")); JMenuBar menuBar = new JMenuBar(); menuBar.add(menu); setJMenuBar(menuBar); setIgnoreRepaint(true); setVisible(true); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { super.windowClosing(evt); timer.cancel(); dispose(); System.exit(0); } }); try { backImg = javax.imageio.ImageIO.read(new File(<insert a jpg picture here>)); frontImg = javax.imageio.ImageIO.read(<here, too>)); } catch (IOException e) { System.out.println(e.getMessage()); } PIC_WIDTH = backImg.getWidth(); PIC_HEIGHT = backImg.getHeight(); setSize(PIC_WIDTH, PIC_HEIGHT); createBufferStrategy(1); // Double buffering bs = getBufferStrategy(); timer.schedule(new Drawer(),0,20); } public static void main(String[] args) { new FastDraw(); } private class Drawer extends TimerTask { private VolatileImage img; public void run() { long begin = System.nanoTime(); Graphics2D g = (Graphics2D) bs.getDrawGraphics(); GraphicsConfiguration gc = g.getDeviceConfiguration(); if (img == null) img = gc.createCompatibleVolatileImage(PIC_WIDTH, PIC_HEIGHT); Graphics2D g2 = img.createGraphics(); do { int valStatus = img.validate(gc); if (valStatus == VolatileImage.IMAGE_OK) g2.drawImage(backImg,0,0,null); else { g.drawImage(frontImg, 0, 0, null); } // volatile image is ready g.drawImage(img,0,50,null); bs.show(); } while (img.contentsLost()); } } } ``` Resize the window to make the `JMenuBar` visible. Try to select a menu point. See?
Accelerate 2D images in Java *without* disturbing JMenus
[ "", "java", "performance", "swing", "2d", "" ]
Here's the deal. I have an XML document with a lot of records. Something like this: ``` print("<?xml version="1.0" encoding="utf-8" ?> <Orders> <Order> <Phone>1254</Phone> <City>City1</City> <State>State</State> </Order> <Order> <Phone>98764321</Phone> <City>City2</City> <State>State2</State> </Order> </Orders>"); ``` There's also an XSD schema file. I would like to extract data from this file and insert these records into a database table. First of course I would like to validate each order record. For example if there are 5 orders in the file and 2 of them fail validation I would like to insert the 3 that passed validation into the db and left the other 2. There can be thousands of records in one xml file. What would be the best approach here. And how would the validation go for this since I need to discard the failed records and only use the ones that passed validation. At the moment I'm using **XmlReaderSettings** to validate the XML document records. Should I extract these records into another XML file or a Dataset or a custom object before I insert into a DB. I'm using .Net 3.5. Any code or link is welcome.
You have a couple of options: 1. [XmlDataDocument](http://msdn.microsoft.com/en-us/library/system.xml.xmldatadocument(VS.80).aspx) or [XmlDocument](http://msdn.microsoft.com/en-us/library/system.xml.xmldocument(VS.80).aspx). The downside to this approach is that the data will be cached in memory, which is bad if you have a lot of it. On the other hand, you get good in-memory querying facilities with DataSet. XmlDocument requires that you use XPath queries to work on the data, whereas XmlDataDocument gives you an experience more like the DataSet functionality. 2. [XmlReader](http://msdn.microsoft.com/en-us/library/9d83k261(VS.80).aspx). This is a good, fast approach because the data isn't cached; you read it in a bit at a time as a stream. You move from one element to the next, and query information about that element in your application to decide what to do with it. This does mean that you maintain in your application's memory the tree level that you're at, but with a simple XML file structure like yours this should be very simple. I recommend option 2 in your case. It should scale well in terms of memory usage, and should provide the simplest implementation for processing a file.
If the data maps fairly cleanly to an object model, you could try using xsd.exe to generate some classes from the .xsd, and process the classes into your DAL of choice. The problem is that if the volume is high (you mention thousands of records), you will most likely have a *lot* of round-trips. Another option might be to pass the data "as is" through to the database and use SQL/XML to process the data in TSQL - presumably as a stored procedure that accepts a parameter of type xml (SQL Server 2005 etc).
Validating and Extracting XML record by record into Database
[ "", "c#", ".net", "xml", "linq", "linq-to-xml", "" ]
**Problem solved:** Thanks guys, see my answer below. I have a website running in Tomcat 5.5 hooked up to a MySQL5 database using Hibernate3. One record simply refuses to keep any changes performed on it. If I change the record programmatically, the values revert back to what they were previously. If I manually modify the record in the database, the values will revert (seemingly once the webapp accesses them). I have tried stopping Tomcat and changing the values manually then starting Tomcat again. Checking the database, the values remain changed after Tomcat has started the webapp but will revert back again once I load the site. I have also tried deleting the Tomcat work folder for the webapp and the .ser cache file. I have also checked the code for the values that are being reverted to and cannot find them. I have only noticed it on this one particular record. **Edit:** I've just had a look at the SQL output from Hibernate using hibernate.show\_sql=true. There is an update query logged for the table my row is in. Does anyone know how to resolve the ? for the columns to actual values?
You could temporarily enable the mysql query logging and see exactly what sql statement altered the value. Since you say it changes immediately after the server starts you should be able to figure out the statement pretty quickly. <http://dev.mysql.com/doc/refman/5.0/en/query-log.html>
To answer your question: > Does anyone know how to resolve the ? > for the columns to actual values? You can do this with [p6spy](http://www.p6spy.com/). Instructions for how to set this up in a Spring app are available [here](http://swik.net/Spring/Spring%27s+corner/Integrate+P6Spy+with+Spring/vq6). However, I think there's a mistake in these instructions, the file they refer to as p6spy.log should actually be name p6spy.properties.
Database record reverting after manual change
[ "", "java", "mysql", "tomcat5.5", "hibernate3", "" ]
I have a device that supports 4-color graphics (much like CGA in the old days). I wanted to use [PIL](http://www.pythonware.com/products/pil/) to read the image and convert it using my 4-color palette (of red, green, yellow, black), but I can't figure out if it's even possible at all. I found some mailing list archive posts that seem to suggest other people have tried to do so and failed. A simple python example would be much appreciated! Bonus points if you add something that then converts the image to a byte string where each byte represents 4 pixels of data (with each two bits representing a color from 0 to 3)
First: your four colour palette (black, green, red, yellow) has *no* blue component. So, you have to accept that your output image will hardly approximate the input image, unless there is no blue component to start with. Try this code: ``` import Image def estimate_color(c, bit, c_error): c_new= c - c_error if c_new > 127: c_bit= bit c_error= 255 - c_new else: c_bit= 0 c_error= -c_new return c_bit, c_error def image2cga(im): "Produce a sequence of CGA pixels from image im" im_width= im.size[0] for index, (r, g, b) in enumerate(im.getdata()): if index % im_width == 0: # start of a line r_error= g_error= 0 r_bit, r_error= estimate_color(r, 1, r_error) g_bit, g_error= estimate_color(g, 2, g_error) yield r_bit|g_bit def cvt2cga(imgfn): "Convert an RGB image to (K, R, G, Y) CGA image" inp_im= Image.open(imgfn) # assume it's RGB out_im= Image.new("P", inp_im.size, None) out_im.putpalette( ( 0, 0, 0, 255, 0, 0, 0, 255, 0, 255, 255, 0, ) ) out_im.putdata(list(image2cga(inp_im))) return out_im if __name__ == "__main__": import sys, os for imgfn in sys.argv[1:]: im= cvt2cga(imgfn) dirname, filename= os.path.split(imgfn) name, ext= os.path.splitext(filename) newpathname= os.path.join(dirname, "cga-%s.png" % name) im.save(newpathname) ``` This creates a PNG palette image with only the first four palette entries set to your colours. This sample image: [![](https://i.stack.imgur.com/BBxf1.jpg)](https://i.stack.imgur.com/BBxf1.jpg) becomes [![](https://i.stack.imgur.com/QxtCD.png)](https://i.stack.imgur.com/QxtCD.png) It's trivial to take the output of `image2cga` (yields a sequence of 0-3 values) and pack every four values to a byte. If you need help about what the code does, please ask and I will explain. ### EDIT1: Do not reinvent the wheel Of course, turns out I was too enthusiastic and —as Thomas discovered— the Image.quantize method can take a palette image as argument and do the quantization with far better results than my ad-hoc method above: ``` def cga_quantize(image): pal_image= Image.new("P", (1,1)) pal_image.putpalette( (0,0,0, 0,255,0, 255,0,0, 255,255,0) + (0,0,0)*252) return image.convert("RGB").quantize(palette=pal_image) ``` ### EDIT1, cont: Pack the pixels into bytes For "added value", here follows code to produce the packed string (4 pixels per byte): ``` import itertools as it # setup: create a map with tuples [(0,0,0,0)‥(3,3,3,3)] as keys # and values [chr(0)‥chr(255)], because PIL does not yet support # 4 colour palette images TUPLE2CHAR= {} # Assume (b7, b6) are pixel0, (b5, b4) are pixel1… # Call it "big endian" KEY_BUILDER= [ (0, 64, 128, 192), # pixel0 value used as index (0, 16, 32, 48), # pixel1 (0, 4, 8, 12), # pixel2 (0, 1, 2, 3), # pixel3 ] # For "little endian", uncomment the following line ## KEY_BUILDER.reverse() # python2.6 has itertools.product, but for compatibility purposes # let's do it verbosely: for ix0, px0 in enumerate(KEY_BUILDER[0]): for ix1, px1 in enumerate(KEY_BUILDER[1]): for ix2, px2 in enumerate(KEY_BUILDER[2]): for ix3, px3 in enumerate(KEY_BUILDER[3]): TUPLE2CHAR[ix0,ix1,ix2,ix3]= chr(px0+px1+px2+px3) # Another helper function, copied almost verbatim from itertools docs def grouper(n, iterable, padvalue=None): "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')" return it.izip(*[it.chain(iterable, it.repeat(padvalue, n-1))]*n) # now the functions def seq2str(seq): """Takes a sequence of [0..3] values and packs them into bytes using two bits per value""" return ''.join( TUPLE2CHAR[four_pixel] for four_pixel in grouper(4, seq, 0)) # and the image related function # Note that the following function is correct, # but is not useful for Windows 16 colour bitmaps, # which start at the *bottom* row… def image2str(img): return seq2str(img.getdata()) ```
John, I found that first link as well, but it didn't directly help me with the problem. It did make me look deeper into quantize though. I came up with this yesterday before going to bed: ``` import sys import PIL import Image PALETTE = [ 0, 0, 0, # black, 00 0, 255, 0, # green, 01 255, 0, 0, # red, 10 255, 255, 0, # yellow, 11 ] + [0, ] * 252 * 3 # a palette image to use for quant pimage = Image.new("P", (1, 1), 0) pimage.putpalette(PALETTE) # open the source image image = Image.open(sys.argv[1]) image = image.convert("RGB") # quantize it using our palette image imagep = image.quantize(palette=pimage) # save imagep.save('/tmp/cga.png') ``` TZ.TZIOY, your solution seems to work along the same principles. Kudos, I should have stopped working on it and waited for your reply. Mine is a bit simpler, although definately not more logical than yours. PIL is cumbersome to use. Yours explains what's going on to do it.
How do I convert any image to a 4-color paletted image using the Python Imaging Library?
[ "", "python", "image-processing", "python-imaging-library", "" ]
I want to be able to get a list of all differences between two JavaScript object graphs, with the property names and values where the deltas occur. For what it is worth, these objects are usually retrieved from the server as JSON and typically are no more than a handful of layers deep (i.e. it may be an array of objects that themselves have data and then arrays with other data objects). I want to not only see the changes to basic properties, but differences in the number of members of an array, etc. etc. If I don't get an answer, I will probably end up writing this myself, but hope someone has already done this work or know of someone who has. --- EDIT: These objects will typically be very close in structure to one another, so we are not talking about objects that are utterly different from one another, but may have 3 or 4 deltas.
After reviewing the existing answers, I noticed that the <https://github.com/flitbit/diff> library was not yet listed as a solution. From my research, this library seems to be the best in terms of active development, contributions and forks for solving the challenge of diffing objects. This is very handy for creating a diff on the server side and passing the client only the changed bits.
Here is a partial, naïve solution to my problem - I will update this as I further develop it. ``` function findDifferences(objectA, objectB) { var propertyChanges = []; var objectGraphPath = ["this"]; (function(a, b) { if(a.constructor == Array) { // BIG assumptions here: That both arrays are same length, that // the members of those arrays are _essentially_ the same, and // that those array members are in the same order... for(var i = 0; i < a.length; i++) { objectGraphPath.push("[" + i.toString() + "]"); arguments.callee(a[i], b[i]); objectGraphPath.pop(); } } else if(a.constructor == Object || (a.constructor != Number && a.constructor != String && a.constructor != Date && a.constructor != RegExp && a.constructor != Function && a.constructor != Boolean)) { // we can safely assume that the objects have the // same property lists, else why compare them? for(var property in a) { objectGraphPath.push(("." + property)); if(a[property].constructor != Function) { arguments.callee(a[property], b[property]); } objectGraphPath.pop(); } } else if(a.constructor != Function) { // filter out functions if(a != b) { propertyChanges.push({ "Property": objectGraphPath.join(""), "ObjectA": a, "ObjectB": b }); } } })(objectA, objectB); return propertyChanges; } ``` And here is a sample of how it would be used and the data it would provide (please excuse the long example, but I want to use something relatively non-trivial): ``` var person1 = { FirstName : "John", LastName : "Doh", Age : 30, EMailAddresses : [ "john.doe@gmail.com", "jd@initials.com" ], Children : [ { FirstName : "Sara", LastName : "Doe", Age : 2 }, { FirstName : "Beth", LastName : "Doe", Age : 5 } ] }; var person2 = { FirstName : "John", LastName : "Doe", Age : 33, EMailAddresses : [ "john.doe@gmail.com", "jdoe@hotmail.com" ], Children : [ { FirstName : "Sara", LastName : "Doe", Age : 3 }, { FirstName : "Bethany", LastName : "Doe", Age : 5 } ] }; var differences = findDifferences(person1, person2); ``` At this point, here is what the `differences` array would look like if you serialized it to JSON: ``` [ { "Property":"this.LastName", "ObjectA":"Doh", "ObjectB":"Doe" }, { "Property":"this.Age", "ObjectA":30, "ObjectB":33 }, { "Property":"this.EMailAddresses[1]", "ObjectA":"jd@initials.com", "ObjectB":"jdoe@hotmail.com" }, { "Property":"this.Children[0].Age", "ObjectA":2, "ObjectB":3 }, { "Property":"this.Children[1].FirstName", "ObjectA":"Beth", "ObjectB":"Bethany" } ] ``` The `this` in the `Property` value refers to the root of the object that was compared. So, this solution is not yet *exactly* what I need, but it is pretty darn close. Hope this is useful to someone out there, and if you have any suggestions for improvement, I am all-ears; I wrote this very late last night (i.e. early this morning) and there may be things I am completely overlooking. Thanks.
How can I get a list of the differences between two JavaScript object graphs?
[ "", "javascript", "json", "data-structures", "diff", "" ]
In C#, how do I set the Identity of a Thread? For example, if I have Thread MyThread, which is already started, can I change MyThread's Identity? Or is this not possible?
You can set the Identity of a thread by creating a new Principal. You can use any Identity that inherits from [System.Security.Principal.IIdentity](https://msdn.microsoft.com/en-us/library/system.security.principal.iidentity(v=vs.110).aspx), but you need a class that inherits from [System.Security.Principal.IPrincipal](https://msdn.microsoft.com/en-us/library/system.security.principal.iprincipal(v=vs.110).aspx) that takes the type of Identity you are using. For simplicity sake the .Net framework provides [GenericPrincipal](https://msdn.microsoft.com/en-us/library/system.security.principal.genericprincipal(v=vs.110).aspx) and [GenericIdentity](https://msdn.microsoft.com/en-us/library/system.security.principal.genericidentity(v=vs.110).aspx) classes which can be used like this: ``` using System.Security.Principal; // ... GenericIdentity identity = new GenericIdentity("M.Brown"); identity.IsAuthenticated = true; // ... System.Threading.Thread.CurrentPrincipal = new GenericPrincipal( identity, new string[] { "Role1", "Role2" } ); //... if (!System.Threading.Thread.CurrentPrincipal.IsInRole("Role1")) { Console.WriteLine("Permission denied"); return; } ``` This won't however give you windows rights to stuff using the new identity. But it can be useful if you are developing a web site and want to create your own user management. If you want to pretend to be a different Windows user than the account you are currently using then you need to use impersonation. An example of how to do this can be found in the Help for [System.Security.Principal.WindowsIdentity.Impersonate()](http://msdn.microsoft.com/en-us/library/chf6fbt4.aspx). There are limitations about which accounts the account you are running under can impersonate. In some cases the .Net framework does impersonation for you. One example of where this occurs is if you are developing a ASP.Net web site and you have Integrated Windows Authentication switched on for the virtual directory or site you are running in.
**Update for the accepted answer [apply ONLY on .NET framework 4.5 and above]** In `.NET 4.5` the property `IsAuthenticated` has no set accessor, so you can not set it directly as the accepted answer doing. You can use the following code for setting that property. ``` GenericIdentity identity = new GenericIdentity("someuser", "Forms"); Thread.CurrentPrincipal = new GenericPrincipal(identity, new string[] { "somerole" }); ```
Set Identity of Thread
[ "", "c#", ".net", "multithreading", "iidentity", "" ]
In my experience it seems that most people will tell you that it is unwise to force a garbage collection but in some cases where you are working with large objects that don't always get collected in the 0 generation but where memory is an issue, is it ok to force the collect? Is there a best practice out there for doing so?
The best practise is to not force a garbage collection. According to MSDN: > "It is possible to force garbage > collection by calling Collect, but > most of the time, this should be > avoided because it may create > performance issues. " However, if you can reliably test your code to confirm that calling Collect() won't have a negative impact then go ahead... Just try to make sure objects are cleaned up when you no longer need them. If you have custom objects, look at using the "using statement" and the IDisposable interface. This link has some good practical advice with regards to freeing up memory / garbage collection etc: <http://msdn.microsoft.com/en-us/library/66x5fx1b.aspx>
Look at it this way - is it more efficient to throw out the kitchen garbage when the garbage can is at 10% or let it fill up before taking it out? By not letting it fill up, you are wasting your time walking to and from the garbage bin outside. This analogous to what happens when the GC thread runs - all the managed threads are suspended while it is running. And If I am not mistaken, the GC thread can be shared among multiple AppDomains, so garbage collection affects all of them. Of course, you might encounter a situation where you won't be adding anything to the garbage can anytime soon - say, if you're going to take a vacation. Then, it would be a good idea to throw out the trash before going out. This MIGHT be one time that forcing a GC can help - if your program idles, the memory in use is not garbage-collected because there are no allocations.
Best Practice for Forcing Garbage Collection in C#
[ "", "c#", ".net", "garbage-collection", "" ]
Given an object: ``` let myObject = { "ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*" }; ``` How do I remove the property `regex` to end up with the following `myObject`? ``` let myObject = { "ircEvent": "PRIVMSG", "method": "newURI" }; ```
To remove a property from an object (mutating the object), you can do it by using the `delete` keyword, like this: ``` delete myObject.regex; // or, delete myObject['regex']; // or, var prop = "regex"; delete myObject[prop]; ``` Demo ``` var myObject = { "ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*" }; delete myObject.regex; console.log(myObject); ``` For anyone interested in reading more about it, Stack Overflow user [kangax](https://stackoverflow.com/users/130652/kangax) has written an incredibly in-depth blog post about the `delete` statement on their blog, *[Understanding delete](http://perfectionkills.com/understanding-delete)*. It is highly recommended. If you'd like a *new* object with all the keys of the original except some, you could use [destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#object_destructuring). Demo ``` let myObject = { "ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*" }; // assign the key regex to the variable _ indicating it will be unused const { regex: _, ...newObj } = myObject; console.log(newObj); // has no 'regex' key console.log(myObject); // remains unchanged ```
Objects in JavaScript can be thought of as maps between keys and values. The `delete` operator is used to remove these keys, more commonly known as object properties, one at a time. ``` var obj = { myProperty: 1 } console.log(obj.hasOwnProperty('myProperty')) // true delete obj.myProperty console.log(obj.hasOwnProperty('myProperty')) // false ``` The `delete` operator does not directly free memory, and it differs from simply assigning the value of `null` or `undefined` to a property, in that the property *itself* is removed from the object. Note that if the *value* of a deleted property was a reference type (an object), and another part of your program still holds a reference to that object, then that object will, of course, not be garbage collected until all references to it have disappeared. `delete` will only work on properties whose descriptor marks them as configurable.
How do I remove a property from a JavaScript object?
[ "", "javascript", "object", "properties", "" ]
I have a view using a master page that contains some javascript that needs to be executed using the OnLoad of the Body. What is the best way to set the OnLoad on my MasterPage only for certain views? On idea I tried was to pass the name of the javascript function as ViewData. But I dont really want my Controllers to have to know about the javascript on the page. I really don't like this approach... ``` <body onload="<%=ViewData["Body_OnLoad"]%>"> <asp:ContentPlaceHolder ID="MainContent" runat="server" /> ``` Edit - I suppose one idea would be to use jQuery's document ready event instead... Any other ideas?
I have been using the following pattern with my current MVC project and it seems to be working pretty good for my .js work thus far... Within my Master Page I load up my standard script files that I want to be used in all of my content pages (things like jquery.js, global.js, jquery-plugins, .css files, etc.). I then define whatever events that are needed in my master page (onLoad, onSave, etc.). Each content page that I create will have it's own .js file associated with it and I load that script file within the content .aspx page. Any .js events that need to be implemented differently between content pages are handled within the individual content .js file. So basically my Master Page has a set of .js functions that my content page scripts will implement. Right now I just store those template .js function signatures in a file and copy and paste them into every new content.js file that I need to create. However, I'm thinking about building a code generator or tool that would spit these template signatures out for me in any new .js file I need created (if .js has some form of interface capability or inheritance features let me know). So to recap: MasterPage.Master Loads: jquery.js, global.js, plugins.js ContentPage Loads: ContentPage.js Global.js contains functions that the master page invokes that do not change between content pages along with any other global routine functions. Each ContentPage.js implements it's own functions for the content page along with those functions the master page invokes that have different behavior.
Solution from Blog: [Using body onload with ASP.net 2.0 MasterPages](http://blog.thewightstuff.net/blog/2007/03/using-body-onload-with-aspnet-20.html) ``` MasterPage.master <head> <asp:ContentPlaceHolder runat="server" id="Headers"> </asp:ContentPlaceHolder> <script language=javascript> function mp_onload() { if(window.body_onload != null) window.body_onload(); } </script> </head> <body onload="mp_onload();"> Default.aspx <asp:Content ID="Content2" ContentPlaceHolderID="Headers" Runat="Server"> <script language="javascript"> function body_onload() { //do something } </script> </asp:Content> ```
Setting the Body's OnLoad attribute in an Asp.net MVC Master Page
[ "", "javascript", "asp.net-mvc", "master-pages", "" ]
I have this XML in a column in my table: ``` <keywords> <keyword name="First Name" value="|FIRSTNAME|" display="Jack" /> <keyword name="Last Name" value="|LASTNAME|" display="Jones" /> <keyword name="City" value="|CITY|" display="Anytown" /> <keyword name="State" value="|STATE|" display="MD" /> </keywords> ``` I'm getting a record out of that table using LINQ to SQL via this: ``` GeneratedArticle ga = db.GeneratedArticles.Single(p => p.GeneratedArticleId == generatedArticleId); ``` That works, I get my GeneratedArticle object just fine. I'd like to walk through the data in the ArticleKeywords field, which is XML. I started doing this: ``` var keywords = from k in ga.ArticleKeywords.Elements("Keywords") select k; foreach (var keyword in keywords) { //what goes here? } ``` I'm not 100% sure that I'm getting that data correctly. I need help with the proper syntax to get the value and display out of my XML field.
Here is a sample code: To read keywords we need to call *Elements("**keyword**")* not *Elements("**keywords**")* since *keywords* is a root node. ``` // IEnumerable sequence with keywords data var keywords = from kw in ga.ArticleKeywords.Elements("keyword") select new { Name = (string)kw.Attribute("name"), Value = (string)kw.Attribute("value"), Display = (string)kw.Attribute("display") }; foreach (var keyword in keywords) { var kw = "Name: " + keyword.Name + " Value: " + keyword.Value + " Display: " + keyword.Display; Console.WriteLine(kw); } ``` You can get attribute value using *foo.Attribute("bar").Value*, but this method would throw exception if attribute is missing. Safe way to get attribute value is *(string)foo.Attribute("bar")* - it will give you *null* if attribute is missing
Once again I am amazed that people don't even try their answers and people still up vote when they don't work. The .Elements will get the list of elements at the current root, which is not a keyword. Also the one using .Attributes["X"] does not even compile you need to use () of course again it would be operating on each instance of "keywords" not "keyword" You could use ``` var keywords = from kw in ga.ArticleKeywords.Element("keywords").Elements() ``` or ``` var keywords = from kw in ga.ArticleKeywords.Element("keywords").Elements("keyword") ``` or (this will get all the keyword elements regardless of level) ``` var keywords = from kw in ga.ArticleKeywords.Descendants("keyword") ```
How do I access the XML data in my column using LINQ to XML?
[ "", "c#", "xml", "linq-to-sql", "linq-to-xml", "" ]
I have a Perl application that parses MediaWiki SQL tables and displays data from multiple wiki pages. I need to be able to re-create the absolute image path to display the images, eg: `.../f/fc/Herbs.jpg/300px-Herbs.jpg` From MediaWiki Manual: > Image\_Authorisation: "the [image] path can be calculated easily from the file name and..." How is the path calculated?
One possible way would be to calculate the MD5 signature of the file (or the file ID in a database), and then build/find the path based on that. For example, say we get an MD5 signature like "1ff8a7b5dc7a7d1f0ed65aaa29c04b1e" The path might look like "/1f/f" or "/1f/ff/8a" The reason is that you don't want to have all the files in 1 folder, and you want to have the ability to "partition" them across different servers, or a SAN or whatever in an equally-spread-out way. The MD5 signature is a string of 16 "hex" characters. So our example of "/1f/ff/8a" gives us 256\*256\*256 folders to store the files in. That ought to be enough for anybody :) --- Update, due to popular demand: **NOTE** - I just realized we are talking specifically about how MediaWiki does it. This is **not** now MediaWiki does it, but another way in which it **could have been done**. By "MD5 signature" I mean doing something like this (code examples in Perl): ``` use Digest::MD5 'md5_hex'; my $sig = md5_hex( $file->id ); ``` $sig is now 32 alpha-numeric characters long: "1ff8a7b5dc7a7d1f0ed65aaa29c04b1e" Then build a folder structure like this: ``` my $path = '/usr/local/media'; map { mkdir($path, 0666); $path .= "/$_" } $sig =~ m/^(..)(..)(..)/; open my $ofh, '>', "$path/$sig" or die "Cannot open '$path/$sig' for writing: $!"; print $ofh "File contents"; close($ofh); ``` Folder structure looks like ``` / usr/ local/ media/ 1f/ f8/ a7/ 1ff8a7b5dc7a7d1f0ed65aaa29c04b1e ```
The accepted answer is incorrect: * The MD5 sum of a string is 32 hex characters (128 bits), not 16 * The file path is calculated from the MD5 sum of the filename, not the contents of the file itself * The first directory in the path is the first character, and the second directory is the first and second characters. The directory path is not a combination of the first 3 or 6 characters. The MD5 sum of 'Herbs.jpg' is fceaa5e7250d5036ad8cede5ce7d32d6. The first 2 characters are 'fc', giving the file path f/fc/, which is what is given in the example.
How does MediaWiki compose the image paths?
[ "", "php", "perl", "mediawiki", "" ]
How can I know in a C#-Application, in which direction the screen of the mobile device is orientated? (i.e. horizontal or vertical).
In Microsoft.WindowsMobile.Status there is a class which keeps track of all kinds of properties of your device. Besides the one you need, DisplayRotation, it also contains properties about phone coverage, Nr of missed calls, next appointment and many more. See [msdn](http://msdn.microsoft.com/en-us/library/microsoft.windowsmobile.status.systemproperty.aspx) for more info. You can also add an event-handler to be notified of changes of these properties.
Add a reference to Microsoft.WindowsCE.Forms to your project. Then you can reference the Microsoft.WindowsCE.Forms.**SystemSettings.ScreenOrientation** property, which will give you what you need. Incidentally, you can set this property, so it can be used to set your screen orientation also.
How to determine the orientation of the screen in C# for mobile devices?
[ "", "c#", "user-interface", "windows-mobile", "" ]
I've got a big big code base that includes two main namespaces: the engine and the application. The engine defines a vector3 class as a typedef of another vector3 class, with equality operators that sit in the engine namespace, not in the vector3 class. I added a class to the application that also had equality operators in the application namespace. When I tried to compile, unrelated but near-by vector3 comparisons failed because it couldn't find an appropriate equality operator. I suspected I was causing a conflict so moved my equality operators into the class I added, and the compile succeeded. ``` // engine.h namespace Engine { class Vector3Impl { ... }; typedef Vector3Impl Vector3; bool operator==(Vector3 const &lhs, Vector3 const &rhs) { ... } } // myfile.cpp #include "engine.h" namespace application { class MyClass { ... }; bool operator==(MyClass const &lhs, MyClass const &rhs) { ... } void myFunc(...) { if ( myClassA == myClassB ) { ... } // builds } void anotherFunc(...) { Engine::Vector3 a, b; ... if ( a == b ) { ... } // fails } } ``` However after thinking about it I can't see why the compile failed. There are no implicit conversions from vector3s to my class or vice-versa, and argument-dependent look-up should be pulling in the equality operator from the engine namespace and matching it. I've tried reproducing this bug in a sample C++ project but that refuses to break. There must be something in the big big code base that is causing this problem, but I'm not sure where to start looking. Something like the opposite of a rogue "using Engine"? Anyone got any ideas?
C++ Standard, 3.4.4.2 declares: > For each argument type T in the function call, there is a set of zero or more associated namespaces and a set of zero > or more associated classes to be considered. The sets of namespaces and classes is determined entirely by the types of > the function arguments (and the namespace of any template template argument). **Typedef names and using-declarations > used to specify the types do not contribute to this set**. ADL doesn't work with typedef's.
I once ran into the same problem with a compiler that didn't have Argument Dependent Lookup (Koenig Lookup - thanks @igor) (VC6 I think). This means that when it sees an operator, it just looks in the enclosing namespaces. So can you tell us what compiler you use? Moving to another compiler solved it. Very inconvenient indeed.
function overloading fail: why did these operators clash?
[ "", "c++", "operator-overloading", "overloading", "" ]
My php is weak and I'm trying to change this string: ``` http://www.example.com/backend.php?/c=crud&m=index&t=care ^ ``` to be: ``` http://www.example.com/backend.php?c=crud&m=index&t=care ^ ``` removing the `/` after the `backend.php?`. Any ideas on the best way to do this? Thanks!
I think that it's better to use simply [str\_replace](http://www.php.net/str_replace), like the manual says: > If you don't need fancy replacing > rules (like regular expressions), you > should always use this function > instead of ereg\_replace() or > preg\_replace(). ``` <? $badUrl = "http://www.site.com/backend.php?/c=crud&m=index&t=care"; $goodUrl = str_replace('?/', '?', $badUrl); ```
``` $str = preg_replace('/\?\//', '?', $str); ``` Edit: See CMS' answer. It's late, I should know better.
PHP removing a character in a string
[ "", "php", "string", "" ]
I'm trying to do an image capture on a high end Nokia phone (N95). The phone's internal camera is very good (4 megapixels) but in j2me I only seem to be able to get a maximum of 1360x1020 image out. I drew largely from this example <http://developers.sun.com/mobility/midp/articles/picture/> What I did was start with 640x480 and increase the width and height by 80 and 60, respectively until it failed. The line of code is: jpg = mVideoControl.getSnapshot("encoding=jpeg&quality=100&width=" + width + "&height=" + height); So the two issues are: 1. The phone throws an exception when getting an image larger than 1360x1020. 2. The higher resolution images appear to be just smoothed versions of the smaller ones. E.g. When I take a 640x480 image and increase it in photoshop I can't tell the difference between this and one that's supposedly 1360x1020. Is this a limitation of j2me on the phone? If so does anyone know of a way to get a higher resolution from within a j2me application and/or how to access the native camera from within another application?
This [explanation](http://www.forum.nokia.com/document/Java_ME_Developers_Library/?content=GUID-00C29EFF-1A32-49D6-9AF4-0E5D8F1EE772.html) on Nokia forum may help you. It says that "The maximum image size that can be captured depends on selected image format, encoding options and free heap memory available." and "It is thus strongly adviced that at least larger images (larger than 1mpix) are captured as JPEG images and in a common image size (e.g. 1600x1200 for 2mpix an so on). Supported common image sizes are dependent on product and platform version." So I suggest you to take some tries 1. with 1600x1200, 1024x768 and whatever image resolution your N95 guide mentions 2. with BMP and PNG as well. Anyway, based on my earlier experiences (that could be outdated), j2me implementations are full of bugs, so there may not be a working solution to your problem.
Your cameras resolution is natively: 2582 x 1944 . Try capturing there to see how that goes. This place: <http://developers.sun.com/mobility/midp/articles/picture/index.html> Mentions the use of: ``` byte[] raw = mVideoControl.getSnapshot(null); Image image = Image.createImage(raw, 0, raw.length); ``` The use of raw seems interesting, to get the native resolution.
Full Resolution Camera Access in j2me
[ "", "java", "java-me", "mobile", "camera", "mmapi", "" ]
I am performing a lot of JavaScript work in the browser and would like to have some of that backend functionality in the front-end. Specifically, it would be nice to have the functions `get()`, `save()`, `all()` and `count()` available to the client. Additionally, it would be great to have the field list of the model already available in the generated JavaScript object. Whether the current user can read or write the records is a separate issue I will deal with using Django's authentication. For the time being, retrieval would be a start. In short, is there code that would generate a JavaScript model from a Django model? Thanks.
It sounds like you're looking for a complete JavaScript interface to the model and queryset APIs. I can't imagine that this would have ever been done or even be a simple task. Not only would you need to somehow generate JavaScript instances of models (much more than JSON serialisation provides, since you also want the methods) but you'd need to expose a web service that can handle every kind of DB-API call. I can't even begin to imagine where to start and the security issues may be too numerous to easily overcome. The alternative (and much simpler) approach would be to use one of the various Django REST modules and JSON serialization. You could perform an AJAX GET request on a resource, which can be identified by a series of query parameters that would be equivalent to chained queryset filters. This would return the JSON representation of the model's values. You can then modify the JavaScript object and use an overloaded AJAX POST request to persist the changes back to the server. You wouldn't have access to the model's methods, so that functionality would have to be reimplemented but making any changes to a model should be straightforward enough - This is basically the JavaScript equivalent of using an HTML form to modify data.
You need a data serializer. You can do it with django built in serializers. It is documented on official django site. [djangoproject\_topics-serialization](http://docs.djangoproject.com/en/dev/topics/serialization/#topics-serialization)
Generate JavaScript objects out of Django Models
[ "", "javascript", "django", "django-models", "code-generation", "" ]
I am looking for a data structure that operates similar to a hash table, but where the table has a size limit. When the number of items in the hash reaches the size limit, a culling function should be called to get rid of the least-retrieved key/value pairs in the table. Here's some pseudocode of what I'm working on: ``` class MyClass { private Map<Integer, Integer> cache = new HashMap<Integer, Integer>(); public int myFunc(int n) { if(cache.containsKey(n)) return cache.get(n); int next = . . . ; //some complicated math. guaranteed next != n. int ret = 1 + myFunc(next); cache.put(n, ret); return ret; } } ``` What happens is that there are some values of `n` for which `myFunc()` will be called lots of times, but many other values of `n` which will only be computed once. So the cache could fill up with millions of values that are never needed again. I'd like to have a way for the cache to automatically remove elements that are not frequently retrieved. This feels like a problem that must be solved already, but I'm not sure what the data structure is that I would use to do it efficiently. Can anyone point me in the right direction? --- **Update** I knew this had to be an already-solved problem. It's called an LRU Cache and is easy to make by extending the LinkedHashMap class. Here is the code that incorporates the solution: ``` class MyClass { private final static int SIZE_LIMIT = 1000; private Map<Integer, Integer> cache = new LinkedHashMap<Integer, Integer>(16, 0.75f, true) { protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) { return size() > SIZE_LIMIT; } }; public int myFunc(int n) { if(cache.containsKey(n)) return cache.get(n); int next = . . . ; //some complicated math. guaranteed next != n. int ret = 1 + myFunc(next); cache.put(n, ret); return ret; } } ```
You are looking for an `LRUList`/`Map`. Check out `LinkedHashMap`: The `removeEldestEntry(Map.Entry)` method may be overridden to impose a policy for removing stale mappings automatically when new mappings are added to the map.
Googling "LRU map" and "I'm feeling lucky" gives you this: <http://commons.apache.org/proper/commons-collections//javadocs/api-release/org/apache/commons/collections4/map/LRUMap.html> > A Map implementation with a fixed > maximum size which removes the least > recently used entry if an entry is > added when full. Sounds pretty much spot on :)
What is a data structure kind of like a hash table, but infrequently-used keys are deleted?
[ "", "java", "algorithm", "data-structures", "caching", "" ]
I would like to print *only* the contents of a textarea element from a website page. In particular, I would like to ensure that nothing gets clipped by the boundary of the textarea as the contents will be quite large. What is the best strategy for tackling this?
Make a print stylesheet where all of the elements *except* the textarea are set in CSS to display: none;, and for the textarea, overflow: visible. Link it to the page with the link tag in the header set to media="print". You're done.
Make a different CSS with media set to print ``` <link rel="stylesheet" type="text/css" href="print.css" media="print" /> ``` <http://webdesign.about.com/cs/css/a/aa042103a.htm>
Printing only a textarea
[ "", "javascript", "printing", "textarea", "printing-web-page", "" ]
Background I have been asked by a client to create a picture of the world which has animated arrows/rays that come from one part of the world to another. The rays will be randomized, will represent a transaction, will fade out after they happen and will increase in frequency as time goes on. The rays will start in one country's boundary and end in another's. As each animated transaction happens a continuously updating sum of the amounts of all the transactions will be shown at the bottom of the image. The amounts of the individual transactions will be randomized. There will also be a year showing on the image that will increment every n seconds. The randomization, summation and incrementing are not a problem for me, but I am at a loss as to how to approach the animation of the arrows/rays. **My question is what is the best way to do this? What frameworks/libraries are best suited for this job?** I am most fluent in python so python suggestions are most easy for me, but I am open to any elegant way to do this. The client will present this as a slide in a presentation in a windows machine.
If you are adventurous use OpenGL :) You can draw bezier curves in 3d space on top of a textured plane (earth map), you can specify a thickness for them and you can draw a point (small cone) at the end. It's easy and it looks nice, problem is learning the basics of OpenGL if you haven't used it before but that would be fun and probably useful if your in to programing graphics. You can use OpenGL from python either with [pyopengl](http://pyopengl.sourceforge.net/) or [pyglet](http://www.pyglet.org/). If you make the animation this way you can capture it to an avi file (using [camtasia](http://www.techsmith.com/camtasia.asp) or something similar) that can be put onto a presentation slide.
> The client will present this as a slide in a presentation in a windows machine I think this is the key to your answer. Before going to a 3d implementation and writing all the code in the world to create this feature, you need to look at the presentation software. Chances are, your options will boil down to two things: 1. Animated Gif 2. Custom Presentation Scripts Obviously, an animated gif is not ideal due to the fact that it repeats when it is done rendering, and to make it last a long time would make a large gif. Custom Presentation Scripts would probably be the other way to allow him to bring it up in a presentation without running any side-programs, or doing anything strange. I'm not sure which presentation application is the target, but this could be valuable information. He sounds like he's more non-technical and requesting something he doesn't realize will be difficult. I think you should come up with some options, explain the difficulty in implementing them, and suggest another solution that falls into the 'bang for your buck' range.
How to create a picture with animated aspects programmatically
[ "", "python", "image", "graphics", "animation", "drawing", "" ]
I've got a WAR file that I need to add two files to. Currently, I'm doing this: ``` File war = new File(DIRECTORY, "server.war"); JarOutputStream zos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(war))); //Add file 1 File file = new File(DIRECTORY, "file1.jar"); InputStream is = new BufferedInputStream(new FileInputStream(file)); ZipEntry e = new ZipEntry("file1.jar"); zos.putNextEntry(e); byte[] buf = new byte[1024]; int len; while ((len = is.read(buf, 0, buf.length)) != -1) { zos.write(buf, 0, len); } is.close(); zos.closeEntry(); //repeat for file 2 zos.close(); ``` The result is that the previous contents get clobbered: the WAR has only the 2 files I just added in it. Is there some sort of append mode that I'm not using or what?
It seems this can't be done. I thought it was for a while, but it seems that it wasn't quite having the effect I wanted. Doing it this way resulted in the equivalent of two separate jar files concatinated together. The weird part was that the tools were making some sense of it. JAR found the first, original jar file and read me that. Glassfish's classloader was finding the later, new part, resulting in it loading only the added files as if they were all of the app. Weird. So I've resurted to creating a new war, adding the contents of the old, adding the new files, closing, and copying the new over the old.
Yeah, there's an extra boolean argument to the [FileOutputStream constructor](http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.io.File,%20boolean)) which lets you force it to append to the file rather than overwrite it. Change your code to ``` JarOutputStream zos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(war, True))); ``` and it should work the way you want.
How do I update a pre-existing Jar file
[ "", "java", "jar", "" ]
How do I load MS Word document (.doc and .docx) to memory (variable) without doing this?: *wordApp.Documents.Open* I don't want to open MS Word, I just want that text inside. You gave me answer for DOCX, but what about DOC? I want free and high performance solution - not to open 12.000 instances of Word to process all of them. :( Aspose is commercial product, and 900$ is a way too much for what I do.
You can use wordconv.exe which is part of the Office Compatibility Pack to convert from doc to docx. <http://www.microsoft.com/downloads/details.aspx?familyid=941b3470-3ae9-4aee-8f43-c6bb74cd1466&displaylang=en> Just call the command like so: "C:\Program Files\Microsoft Office\Office12\wordconv.exe" -oice -nme InputFile OutputFile I'm not sure if you need word installed for it to run but it does work. I use it locally as a windows shell command to convert old office files to 2007 format whenever I want.
If you are dealing with docx you can do this with out doing any interop with Word .docx file actually a ZIP contains an XML file , you can read the XML Please refer the below links <http://conceptdev.blogspot.com/2007/03/open-docx-using-c-to-extract-text-for.html> [Office (2007) Open XML File Formats](http://msdn.microsoft.com/en-us/library/aa338205.aspx)
How to load text of MS Word document in C# (.NET)?
[ "", "c#", ".net", "ms-word", "docx", "doc", "" ]
I am trying to use some pinvoke code to call a C function. The function fills a buffer with data. The structure is set up as a DWORD for the length, followed by a string. How do I extract the string from the IntPtr? ``` IntPtr buffer = Marshal.AllocHGlobal(nRequiredSize); PInvokedFunction(buffer, nRequiredSize); string s = Marshal.PtrToStringAuto(buffer + 4); //this is an error. Marshal.FreeHGlobal(buffer); ```
You should do this: ``` IntPtr sBuffer = new IntPtr( buffer.ToInt64() + 4 ); string s = Marshal.PtrToStringAuto( sBuffer ); ``` So your code is 64bit safe.
The best I could come up with was the following, though the use of the UnmanagedMemoryStream seems a bit of a hack. ``` IntPtr buffer = Marshal.AllocHGlobal((int)nRequiredSize); PInvokedFunction(buffer, nRequiredSize); UnmanagedMemoryStream memStream = new UnmanagedMemoryStream(buffer.ToPointer(), nRequiredSize); memStream.Seek(4, SeekOrigin.Begin); IntPtr ptr = new IntPtr(memStream.PositionPointer); string s = Marshal.PtrToStringAuto(ptr); Marshal.FreeHGlobal(buffer); ```
Pointer math in C#
[ "", "c#", "pinvoke", "pointer-arithmetic", "" ]
I'm starting a new application and looking at using an ORM -- in particular, SQLAlchemy. Say I've got a column 'foo' in my database and I want to increment it. In straight sqlite, this is easy: ``` db = sqlite3.connect('mydata.sqlitedb') cur = db.cursor() cur.execute('update table stuff set foo = foo + 1') ``` I figured out the SQLAlchemy SQL-builder equivalent: ``` engine = sqlalchemy.create_engine('sqlite:///mydata.sqlitedb') md = sqlalchemy.MetaData(engine) table = sqlalchemy.Table('stuff', md, autoload=True) upd = table.update(values={table.c.foo:table.c.foo+1}) engine.execute(upd) ``` This is slightly slower, but there's not much in it. Here's my best guess for a SQLAlchemy ORM approach: ``` # snip definition of Stuff class made using declarative_base # snip creation of session object for c in session.query(Stuff): c.foo = c.foo + 1 session.flush() session.commit() ``` This does the right thing, but it takes just under fifty times as long as the other two approaches. I presume that's because it has to bring all the data into memory before it can work with it. Is there any way to generate the efficient SQL using SQLAlchemy's ORM? Or using any other python ORM? Or should I just go back to writing the SQL by hand?
SQLAlchemy's ORM is meant to be used together with the SQL layer, not hide it. But you do have to keep one or two things in mind when using the ORM and plain SQL in the same transaction. Basically, from one side, ORM data modifications will only hit the database when you flush the changes from your session. From the other side, SQL data manipulation statements don't affect the objects that are in your session. So if you say ``` for c in session.query(Stuff).all(): c.foo = c.foo+1 session.commit() ``` it will do what it says, go fetch all the objects from the database, modify all the objects and then when it's time to flush the changes to the database, update the rows one by one. Instead you should do this: ``` session.execute(update(stuff_table, values={stuff_table.c.foo: stuff_table.c.foo + 1})) session.commit() ``` This will execute as one query as you would expect, and because at least the default session configuration expires all data in the session on commit you don't have any stale data issues. In the almost-released 0.5 series you could also use this method for updating: ``` session.query(Stuff).update({Stuff.foo: Stuff.foo + 1}) session.commit() ``` That will basically run the same SQL statement as the previous snippet, but also select the changed rows and expire any stale data in the session. If you know you aren't using any session data after the update you could also add `synchronize_session=False` to the update statement and get rid of that select.
``` session.query(Clients).filter(Clients.id == client_id_list).update({'status': status}) session.commit() ``` Try this =)
Efficiently updating database using SQLAlchemy ORM
[ "", "python", "orm", "sqlalchemy", "" ]
I've been doing some socket programming to transmit information across the wire. I've run into a problem with DataOutputStream.writeUTF(). It seems to allow strings of up to 64k but I have a few situations where I can run over this. Are there any good alternatives that support larger strings or do I need to roll my own?
It actually uses a two bytes to write the length of the string before using an algorithm that compacts it into one, two or three bytes per character. (See the documentation on java.io.DataOutput) It is close to UTF-8, but even though documented as being so, there are compatibility problems. If you are not terribly worried about the amount of data you will be writing, you can easily write your own by writing the length of the string first, and then the raw data of the string using the getBytes method. ``` // Write data String str="foo"; byte[] data=str.getBytes("UTF-8"); out.writeInt(data.length); out.write(data); // Read data int length=in.readInt(); byte[] data=new byte[length]; in.readFully(data); String str=new String(data,"UTF-8"); ```
`ObjectOutputStream.writeObject()` properly handles long strings (verified by looking at the source code). Write the string out this way: ``` ObjectOutputStream oos = new ObjectOutputStream(out); ... other write operations ... oos.writeObject(myString); ... other write operations ... ``` Read it this way: ``` ObjectInputStream ois = new ObjectInputStream(in); ... other read operations ... String myString = (String) ois.readObject(); ... other read operations ... ``` Another difference with `DataOutputStream` is that using `ObjectOutputStream` automatically writes a 4-byte stream header when instantiated, but its usually going to be a pretty small penalty to pay.
Writing large strings with DataOutputStream
[ "", "java", "dataoutputstream", "" ]
I need to execute a select and then update some of the rows in the `ResultSet` in an atomic way. The code I am using looks like (simplified): ``` stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); rs = stmt.executeQuery("SELECT ..."); while (rs.next()) { if (conditions_to_update) { rs.updateString(...); rs.updateRow(); } } ``` * Can I guarantee that the updates are going to be executed atomically ? If not, how could I assure that ? * What happens if any other process has changed the database row that you are updating via `updateRow()` ? Is there any way to lock the rows in the `ResultSet` ?
There's probably a whole heap of technologies and concepts that come into play here, and things start to get fairly sticky when you start considering multi-threaded / multi request applications. As Iassevk stated, you should look into using [Transactions](http://java.sun.com/docs/books/tutorial/jdbc/basics/transactions.html) to ensure the atomic nature of your updates - a very low-level example would be to do something along the lines of: ``` ... con.setAutoCommit(false); try { while (rs.next()) { if (conditions_to_update) { rs.updateString(...); rs.updateRow(); } } con.setAutoCommit(true); } catch (Exception ex) { //log the exception and rollback con.rollback(); } finally { con.close(); } ``` All the updates would then be batched into the same transaction. If any of the updates generated an Exception (such as an invalid value or the connection failing part way through the results), the whole lot would be rolled back. (Finally added because I am a champion of it ;p ) This however, won't address your second issue which is two competing methods trying to update the same table - a race condition. There are, in my mind, two main approaches here - each has it's merits and drawbacks. The easiest approach would be to [Lock the table](http://dev.mysql.com/doc/refman/5.0/en/lock-tables.html) - this would require minimal code changes but has a pretty big drawback. Working on the assumption that, as with most applications, it's more read that write: locking the table will prevent all other users from viewing the data, with the likelihood the code will hang, waiting for the lock to release before the connection time-out kicks in and throws an exception. The more complex approach is to ensure that the methods for performing these updates are implemented in a thread-safe manner. To that end: * All the updates for this table pass through a single Class * That class implements a Singleton pattern, or exposes the update methods as Static methods * The update methods utilise the [Synchronized](http://java.sun.com/docs/books/tutorial/essential/concurrency/syncmeth.html) keyword to prevent race conditions
> What happens if any other process has changed the database row that you are updating via updateRow() ? Is there any way to lock the rows in the ResultSet ? In Oracle, you can kinda mark certain rows for update by issuing the following SQL. ``` select cola, colB from tabA for update; ``` The next transaction/thread/app that tries to update this row will get an exception. see this for more details -- <http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:4530093713805>
Update more than one row atomically
[ "", "java", "database", "jdbc", "atomic", "" ]
I know it is a good practice to declare virtual destructors for base classes in C++, but is it always important to declare `virtual` destructors even for abstract classes that function as interfaces? Please provide some reasons and examples why.
It's even more important for an interface. Any user of your class will probably hold a pointer to the interface, not a pointer to the concrete implementation. When they come to delete it, if the destructor is non-virtual, they will call the interface's destructor (or the compiler-provided default, if you didn't specify one), not the derived class's destructor. Instant memory leak. For example ``` class Interface { virtual void doSomething() = 0; }; class Derived : public Interface { Derived(); ~Derived() { // Do some important cleanup... } }; void myFunc(void) { Interface* p = new Derived(); // The behaviour of the next line is undefined. It probably // calls Interface::~Interface, not Derived::~Derived delete p; } ```
The answer to your question is often, but not always. If your abstract class forbids clients to call delete on a pointer to it (or if it says so in its documentation), you are free to not declare a virtual destructor. You can forbid clients to call delete on a pointer to it by making its destructor protected. Working like this, it is perfectly safe and reasonable to omit a virtual destructor. You will eventually end up with no virtual method table, and end up signalling your clients your intention on making it non-deleteable through a pointer to it, so you have indeed reason not to declare it virtual in those cases. *[See item 4 in this article: <http://www.gotw.ca/publications/mill18.htm>]*
Why should I declare a virtual destructor for an abstract class in C++?
[ "", "c++", "inheritance", "virtual-destructor", "" ]
I would like to create a batch script, to go through 20,000 links in a DB, and weed out all the 404s and such. How would I get the HTTP status code for a remote url? Preferably not using curl, since I dont have it installed.
CURL would be perfect but since you don't have it, you'll have to get down and dirty with sockets. The technique is: 1. Open a socket to the server. 2. Send an HTTP HEAD request. 3. Parse the response. Here is a quick example: ``` <?php $url = parse_url('http://www.example.com/index.html'); $host = $url['host']; $port = $url['port']; $path = $url['path']; $query = $url['query']; if(!$port) $port = 80; $request = "HEAD $path?$query HTTP/1.1\r\n" ."Host: $host\r\n" ."Connection: close\r\n" ."\r\n"; $address = gethostbyname($host); $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_connect($socket, $address, $port); socket_write($socket, $request, strlen($request)); $response = split(' ', socket_read($socket, 1024)); print "<p>Response: ". $response[1] ."</p>\r\n"; socket_close($socket); ?> ``` **UPDATE: I've added a few lines to parse the URL**
If im not mistaken none of the php built-in functions return the http status of a remote url, so the best option would be to use sockets to open a connection to the server, send a request and parse the response status: pseudo code: ``` parse url => $host, $port, $path $http_request = "GET $path HTTP/1.0\nHhost: $host\n\n"; $fp = fsockopen($host, $port, $errno, $errstr, $timeout), check for any errors fwrite($fp, $request) while (!feof($fp)) { $headers .= fgets($fp, 4096); $status = <parse $headers > if (<status read>) break; } fclose($fp) ``` Another option is to use an already build http client class in php that can return the headers without fetching the full page content, there should be a few open source classes available on the net...
How do you get the HTTP status code for a remote domain in php?
[ "", "php", "" ]
Is there a (standardized) way to get the name of the current method using c++? Using GNU GCC you can do this by using the macro `__FUNCTION__` and `__PRETTY_FUNCTION__` (surrounded by 2 underscores), however, this is of course non portable. Is there a way to do this in standard c++ or a way to make it portable?
The `__func__` identifier is part of the C99 standard and is in the C++0x draft. The identifier `__func__` is implicitly declared by the compiler as if the following were at the very start of each function body: ``` static const char __func__[] = "function-name"; ``` where `function-name` is an implementation-defined string automatically provided by the compiler. Until support for those standards is available (or more widely available) you're stuck with compiler-specific gunk.
No...... but some things end up being non standard standards! see <http://msdn.microsoft.com/en-us/library/b0084kay(VS.80).aspx> which outlines the ANSI standard stuff, and then microsofs which includes *FUNCTION*
Getting the name of the current method in c++
[ "", "c++", "introspection", "" ]
It sounds a lot more complicated than it really is. So in Perl, you can do something like this: ``` foreach my $var (@vars) { $hash_table{$var->{'id'}} = $var->{'data'}; } ``` I have a JSON object and I want to do the same thing, but with a javascript associative array in jQuery. I've tried the following: ``` hash_table = new Array(); $.each(data.results), function(name, result) { hash_table[result.(name).extra_info.a] = result.(name).some_dataset; }); ``` Where data is a JSON object gotten from a $.getJSON call. It looks more or less like this (my JSON syntax may be a little off, sorry): ``` { results:{ datasets_a:{ dataset_one:{ data:{ //stuff } extra_info:{ //stuff } } dataset_two:{ ... } ... } datasets_b:{ ... } } } ``` But every time I do this, firebug throws the following error: "XML filter is applied to non-xml data"
I think you can use the JSON response as an associative array. So you should be able to go directly in and use the JSON. Assuming you received the above example: ``` $('result').innerHTML = data['results']['dataset_a']['dataset_two']['data']; // Or the shorter form: $('result').innerHTML = data.results.dataset_a.dataset_two.data; ``` Understand that I haven't tested this, but it's safer to use the square brackets with a variable than it is to use parenthesis plus the name with the dot accessor. Your example is failing because of some convoluted logic I just caught. ``` $.each(data.results), function(name, result) { hash_table[result.(name).extra_info.a] = result.(name).some_dataset; }); ``` Now, the foreach loop goes through the variable `data.results` to find the internal elements at a depth of 1. The item it finds is given to the lambda with the key of the item. AKA, the first result will be `name = "datasets_a" item = object`. Following me so far? Now you access the returned hash, the object in `item`, as though it has the child key in `name` ... "datasets\_a". But wait, this **is** the object! If all else fails... write your result JSON into a text field dynamically and ensure it is formatted properly.
Why would you want to change an array into another array ?-) -- why not simply access the data, if you want to simplify or filter, you can traverse the arrays of the object directly !-)
Dynamic Associative Array Creation in Javascript from JSON
[ "", "javascript", "jquery", "json", "" ]
What's the term for this design? ``` object.method1().method2().method3() ``` ..when all methods return \*this? I found the term for this a while ago, but lost it meanwhile. I have no clue how to search for this on google :) Also if anyone can think of a better title for the question, feel free to change it. Thanks **Update-Gishu**: After reading about it, I feel that your question is misleading w.r.t. code snippet provided.. (Feel free to rollback) *Method Chaining* ``` object.method1().method2().method3() ``` *Fluent Interfaces* ``` private void makeFluent(Customer customer) { customer.newOrder() .with(6, "TAL") .with(5, "HPK").skippable() .with(3, "LGV") .priorityRush(); } ```
Looks to me like you are describing a fluent interface. Ive also heard it referred to as pipelineing or chaining. Update-Gishu: <http://martinfowler.com/bliki/FluentInterface.html>
> It chains these method calls, which is why this is called [method chaining](https://isocpp.org/wiki/faq/references#method-chaining)
What's the term for design ala "object.method1().method2().method3()"?
[ "", "c++", "" ]
I have a text file where I want to change only the first line of the file. The file could be millions of rows long, so I'd rather not have to loop over everything, so I'm wondering if there is another way to do this. I'd also like to apply some rules to the first line so that I replace instances of certain words with other words. Is this possible?
A `RandomAccessFile` will do the trick, unless the length of the resulting line is different from the length of the original line. If it turns out you are forced to perform a copy (where the first line is replaced and the rest of the data shall be copied as-is), I suggest using a `BufferedReader` and `BufferedWriter`. First use `BufferedReader`'s `readLine()` to read the first line. Modify it and write it to the `BufferedWriter`. Then use a `char[]` array to perform a brute-force copy of the remainder of the file. This will be more efficient than doing the copy line by line. Let me know if you need details.. Another option is to perform the reading and writing inside the same file. It'll be a bit more complex though. :) Let me know if you need details on this as well..
If the new line has a different amount of characters (bytes) than the original first line, you will have to re-write the whole file to get rid of the gap or avoid overwriting part of the second line. Of course, various tools like `String.replaceFirst(String regex, String replacement)` ([javadoc](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#replaceFirst(java.lang.String,%20java.lang.String))) or the `RandomAccessFile` ([javadoc](http://java.sun.com/j2se/1.4.2/docs/api/java/io/RandomAccessFile.html)) can help you with this task.
Replace first line of a text file in Java
[ "", "java", "" ]
Hi Guys could you please help me refactor this so that it is sensibly pythonic. ``` import sys import poplib import string import StringIO, rfc822 import datetime import logging def _dump_pop_emails(self): self.logger.info("open pop account %s with username: %s" % (self.account[0], self.account[1])) self.popinstance = poplib.POP3(self.account[0]) self.logger.info(self.popinstance.getwelcome()) self.popinstance.user(self.account[1]) self.popinstance.pass_(self.account[2]) try: (numMsgs, totalSize) = self.popinstance.stat() for thisNum in range(1, numMsgs+1): (server_msg, body, octets) = self.popinstance.retr(thisNum) text = string.join(body, '\n') mesg = StringIO.StringIO(text) msg = rfc822.Message(mesg) name, email = msg.getaddr("From") emailpath = str(self._emailpath + self._inboxfolder + "\\" + email + "_" + msg.getheader("Subject") + ".eml") emailpath = self._replace_whitespace(emailpath) file = open(emailpath,"wb") file.write(text) file.close() self.popinstance.dele(thisNum) finally: self.logger.info(self.popinstance.quit()) def _replace_whitespace(self,name): name = str(name) return name.replace(" ", "_") ``` Also in the \_replace\_whitespace method I would like to have some kind of cleaning routine which takes out all illegal characters which could cause processing. Basically I want to write the email to the inbox directory in a standard way. Am i doing something wrong here?
This isn't refactoring (it doesn't need refactoring as far as I can see), but some suggestions: You should use the email package rather than rfc822. Replace rfc822.Message with email.Message, and use email.Utils.parseaddr(msg["From"]) to get the name and email address, and msg["Subject"] to get the subject. Use os.path.join to create the path. This: ``` emailpath = str(self._emailpath + self._inboxfolder + "\\" + email + "_" + msg.getheader("Subject") + ".eml") ``` Becomes: ``` emailpath = os.path.join(self._emailpath + self._inboxfolder, email + "_" + msg.getheader("Subject") + ".eml") ``` (If self.\_inboxfolder starts with a slash or self.\_emailpath ends with one, you could replace the first + with a comma also). It doesn't really hurt anything, but you should probably not use "file" as a variable name, since it shadows a built-in type (checkers like pylint or pychecker would warn you about that). If you're not using self.popinstance outside of this function (seems unlikely given that you connect and quit within the function), then there's no point making it an attribute of self. Just use "popinstance" by itself. Use xrange instead of range. Instead of just importing StringIO, do this: ``` try: import cStringIO as StringIO except ImportError: import StringIO ``` If this is a POP mailbox that can be accessed by more than one client at a time, you might want to put a try/except around the RETR call to continue on if you can't retrieve one message. As John said, use "\n".join rather than string.join, use try/finally to only close the file if it is opened, and pass the logging parameters separately. The one refactoring issue I could think of would be that you don't really need to parse the whole message, since you're just dumping a copy of the raw bytes, and all you want is the From and Subject headers. You could instead use popinstance.top(0) to get the headers, create the message (blank body) from that, and use that for the headers. Then do a full RETR to get the bytes. This would only be worth doing if your messages were large (and so parsing them took a long time). I would definitely measure before I made this optimisation. For your function to sanitise for the names, it depends how nice you want the names to be, and how certain you are that the email and subject make the filename unique (seems fairly unlikely). You could do something like: ``` emailpath = "".join([c for c in emailpath if c in (string.letters + string.digits + "_ ")]) ``` And you'd end up with just alphanumeric characters and the underscore and space, which seems like a readable set. Given that your filesystem (with Windows) is probably case insensitive, you could lowercase that also (add .lower() to the end). You could use emailpath.translate if you want something more complex.
I don't see anything significant wrong with that code -- is it behaving incorrectly, or are you just looking for general style guidelines? A few notes: 1. Instead of `logger.info ("foo %s %s" % (bar, baz))`, use `"foo %s %s", bar, baz`. This avoids the overhead of string formatting if the message won't be printed. 2. Put a `try...finally` around opening `emailpath`. 3. Use `'\n'.join (body)`, instead of `string.join (body, '\n')`. 4. Instead of `msg.getaddr("From")`, just `msg.From`.
Incoming poplib refactoring using windows python 2.3
[ "", "python", "email", "refactoring", "poplib", "" ]
I am attempting to load an activex object on the same page where my flex application resides. Is this possible? Can I have 2 object tags on one page? As of right now the flex application loads fine but when I attempt to access the activeX control it says its null. But if I have the same activex control on its own webpage it works perfectly fine. Any Ideas? Thanks in advance.
One of the issues was that my browser was caching the page, I realized that once I made a change to the name of the ActiveX object and the error thrown was still referencing the old name of the ActiveX object. The other error was I had a Var with the same name of the ActiveX object inside the javascript code, that seemed to be causing it to fail, although I am not entirely sure why. Once I removed that variable the script worked fine. I had run into that same problem the day before just didn't notice it the second time around, because I have been working on this integration for a few days straight now.
Whoops, I found the error. It was a simple error in my javascript code. Turns out it works fine adding another Object tag and loading another activex control. Chalk this up as a learning experience.
Loading ActiveX object on Flex application html page
[ "", "javascript", "html", "apache-flex", "activex", "" ]