Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I am looking for the definition of when I am allowed to do forward declaration of a class in another class's header file: Am I allowed to do it for a base class, for a class held as a member, for a class passed to member function by reference, etc. ?
Put yourself in the compiler's position: when you forward declare a type, all the compiler knows is that this type exists; it knows nothing about its size, members, or methods. This is why it's called an *incomplete type*. Therefore, you cannot use the type to declare a member, or a base class, since the compiler would need to know the layout of the type. Assuming the following forward declaration. ``` class X; ``` Here's what you can and cannot do. **What you can do with an incomplete type:** * Declare a member to be a pointer or a reference to the incomplete type: ``` class Foo { X *p; X &r; }; ``` * *Declare* functions or methods which accept/return incomplete types: ``` void f1(X); X f2(); ``` * *Define* functions or methods which accept/return pointers/references to the incomplete type (but without using its members): ``` void f3(X*, X&) {} X& f4() {} X* f5() {} ``` **What you cannot do with an incomplete type:** * Use it as a base class ``` class Foo : X {} // compiler error! ``` * Use it to declare a member: ``` class Foo { X m; // compiler error! }; ``` * *Define* functions or methods using this type ``` void f1(X x) {} // compiler error! X f2() {} // compiler error! ``` * Use its methods or fields, in fact trying to dereference a variable with incomplete type ``` class Foo { X *m; void method() { m->someMethod(); // compiler error! int i = m->someField; // compiler error! } }; ``` --- When it comes to templates, there is no absolute rule: whether you can use an incomplete type as a template parameter is dependent on the way the type is used in the template. For instance, `std::vector<T>` requires its parameter to be a complete type, while `boost::container::vector<T>` does not. Sometimes, a complete type is required only if you use certain member functions; [this is the case for `std::unique_ptr<T>`](https://stackoverflow.com/questions/6012157/is-stdunique-ptrt-required-to-know-the-full-definition-of-t), for example. A well-documented template should indicate in its documentation all the requirements of its parameters, including whether they need to be complete types or not.
The main rule is that you can only forward-declare classes whose memory layout (and thus member functions and data members) do not need to be known in the file you forward-declare it. This would rule out base classes and anything but classes used via references and pointers.
When can I use a forward declaration?
[ "", "c++", "forward-declaration", "c++-faq", "" ]
Greetings. I have written a little python script that calls MySQL in a subprocess. [Yes, I know that the right approach is to use MySQLdb, but compiling it under OS X Leopard is a pain, and likely more painful if I wanted to use the script on computers of different architectures.] The subprocess technique works, provided that I supply the password in the command that starts the process; however, that means that other users on the machine could see the password. The original code I wrote can be seen [here](http://armagons-isles.blogspot.com/2009/03/python-subprocess-wrapper-for-mysql.html). This variant below is very similar, although I will omit the test routine to keep it shorter: ``` #!/usr/bin/env python from subprocess import Popen, PIPE # Set the command you need to connect to your database mysql_cmd_line = "/Applications/MAMP/Library/bin/mysql -u root -p" mysql_password = "root" def RunSqlCommand(sql_statement, database=None): """Pass in the SQL statement that you would like executed. Optionally, specify a database to operate on. Returns the result.""" command_list = mysql_cmd_line.split() if database: command_list.append(database) # Run mysql in a subprocess process = Popen(command_list, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) #print "Asking for output" #needs_pw = process.stdout.readline() #print "Got: " + needs_pw # pass it in the password process.stdin.write(mysql_password + "\n") # pass it our commands, and get the results #(stdout, stderr) = process.communicate( mysql_password + "\n" + sql_statement) (stdout, stderr) = process.communicate( sql_statement ) return stdout ``` I am suspicious that the MySQL password prompt is not actually on stdout (or stderr), although I don't know how that could be or if it means I could trap it. I did try reading output first, before supplying a password, but it didn't work. I also tried passing the password Again, if I supply the password on the command line (and thus have no code between the "Popen" and "communicate" functions) my wrapped function works. --- *Two new thoughts, months laster:* 1. Using [pexpect](http://pexpect.sourceforge.net/pexpect.html) would let me supply a password. It simulates a tty and gets all output, even that which bypasses stdout and stderr. 2. There is a project called [MySQL Connector/Python](https://launchpad.net/myconnpy), in early alpha, that will allow provide a pure python library for accessing MySQL, without requiring you to compile any C-code.
You could simply build a my.cnf file and point to that on the mysql command. Obviously you'll want to protect that file with permissions/acls. But it shouldn't be really an more/less secure then having the password in your python script, or the config for your python script. So you would do something like ``` mysql_cmd_line = "/Applications/MAMP/Library/bin/mysql --defaults-file=credentials.cnf" ``` and your config would look about like this ``` [client] host = localhost user = root password = password socket = /var/run/mysqld/mysqld.sock ```
The only secure method is to use a MySQL cnf file as one of the other posters mentions. You can also pass a MYSQL\_PWD env variable, but that is insecure as well: <http://dev.mysql.com/doc/refman/5.0/en/password-security.html> Alternatively, you can communicate with the database using a Unix socket file and with a little bit of tweaking you can control permissions at the user id level. Even better, you can use the free BitNami stack DjangoStack that has Python and MySQLDB precompiled for OS X (And Windows and Linux) <http://bitnami.org/stacks>
Supplying password to wrapped-up MySQL
[ "", "python", "mysql", "subprocess", "" ]
I have many `boost::shared_ptr<MyClass>` objects, and at some point I intentionally want to `delete` some of them to free some memory. (I know at that point that I will never need the pointed-to `MyClass` objects anymore.) How can I do that? I guess you can't just call `delete()` with the raw pointer that I get with `get()`. I've seen a function `get_deleter(shared_ptr<T> const & p)` in `boost::shared_ptr`, but I'm not sure how to use it, and also it says *experimental* right next to it. (I think I have Boost 1.38.) Maybe just assign a new empty `boost::shared_ptr` to the variable? That should throw away the old value and delete it.
You just do ``` ptr.reset(); ``` See the [shared\_ptr manual](http://www.boost.org/doc/libs/release/libs/smart_ptr/shared_ptr.htm). It is equivalent to ``` shared_ptr<T>().swap(ptr) ``` You call `reset` on every smart pointer that should not reference the object anymore. The last such `reset` (or any other action that causes the reference count drop to zero, actually) will cause the object to be free'ed using the deleter automatically. Maybe you are interested in the [Smart Pointer Programming Techniques](http://www.boost.org/doc/libs/release/libs/smart_ptr/sp_techniques.html). It has an entry about [delayed deallocation](http://www.boost.org/doc/libs/release/libs/smart_ptr/sp_techniques.html#delayed).
If you want to be able to intentionally delete objects (I do all the time) then you have to use single ownership. You have been lured into using shared\_ptr when it is not appropriate to your design.
How to intentionally delete a boost::shared_ptr?
[ "", "c++", "memory-management", "boost", "shared-ptr", "" ]
I am looking for Perl implementation in Java. Something like Jython is for Python. I found PLJava but it needs both JVM and Perl compiler installed. I need something which does not need a Perl compiler. I need to run some Perl code in a Java class. UPDATES: * I figured out that PLJAVA is what I need. Does anybody know some tutorial? * Has anybody played with the Inline::Java module. * I also could not install Inline::Java.
Jython isn't fully compatible with CPython (or whatever you would rather call the original C++ Python interpreter), but wherever either differs from the language spec is a bug. Unfortunately, Perl 5 is much more complex and lacks any formal language specifications at all -- the language effectively being defined as "what does the `perl` executable do" -- so there exists no other implementation of the Perl 5 language aside from the Perl 5 interpreter. Unfortunate, but that's history. Perl 6 does have a language spec and multiple (incomplete) implementations, but that's not likely to be useful to you. [PLJava](http://search.cpan.org/dist/PLJava/README.pod) was an attempt to do exactly what you want, call Perl from Java. It does so via JNI (stuffing native code into Java) linking to `libperl`. However, it's not been updated since 2004 and I don't know how well it works. ### Edit I hadn't seen [Inline::Java::PerlInterpreter](http://search.cpan.org/dist/Inline-Java/Java/PerlInterpreter/PerlInterpreter.pod) before -- unfortunately it doesn't seem to work with my system Perl.
Update: There is another options that could be viable: Jerl. Jerl translates a micro-Perl interpreter into Java bycode using NestedVM. In this sense Jerl is almost a Java implementation of Perl. I haven't tested it though and it is reasonable to expect a loss in performances . Nonetheless it's a solution worth of investigation. Jerl is hosted here: <https://code.google.com/p/jerl/>. Sadly not, at least not a complete and usable one. Perl is a difficult language to port to other VMs mainly because of its highly dynamic nature and for historical reasons related to how the language has been developed over the years; theoretical issues about perl parsability are, in my humble opinion, of secondary importance. Perl does not have an a formal specification nor an official grammar: Perl implementation is Perl's own formal specification. This means that to write an alternative implementation of Perl one has to know intimately the internals of the current one and this is obviously a big barrier to the development of such a project. Here lies the real difficulty in porting Perl to other VMs. Additionaly, the dynamic nature of Perl poses other technical problems related to an efficient implementation on the Java virtual machine that is engineered to support statically typed languages. There have been some efforts like this one for example: <http://www.ebb.org/perljvm/>. A newer one is cited here: <http://use.perl.org/~Ovid/journal/38837>. Both were abandoned at one point or another not because of infeasability but only because the effort required was too big for a research/hobby project. A new interesting alternative that is proceeding steadly is language-P by Mattia Barbon: <http://search.cpan.org/dist/Language-P/>. It is an implementation of Perl on the NET clr. The implementation is still incomplete but I know that the man behind the project is a very persistent one and that the project has been going forward slowly but steadily. Maybe Perl on the CLR will come first. :D
Is there a Perl implementation in Java?
[ "", "java", "perl", "" ]
It's weird that this is the first time I've bumped into this problem, but: How do you define a constructor in a C# interface? **Edit** Some people wanted an example (it's a free time project, so yes, it's a game) IDrawable +Update +Draw To be able to Update (check for edge of screen etc) and draw itself it will always need a `GraphicsDeviceManager`. So I want to make sure the object has a reference to it. This would belong in the constructor. Now that I wrote this down I think what I'm implementing here is `IObservable` and the `GraphicsDeviceManager` should take the `IDrawable`... It seems either I don't get the XNA framework, or the framework is not thought out very well. **Edit** There seems to be some confusion about my definition of constructor in the context of an interface. An interface can indeed not be instantiated so doesn't need a constructor. What I wanted to define was a signature to a constructor. Exactly like an interface can define a signature of a certain method, the interface could define the signature of a constructor.
As already well noted, you can't have constructors on an Interface. But since this is such a highly ranked result in Google some 7 years later, I thought I would chip in here - specifically to show how you could use an abstract base class in tandem with your existing Interface and maybe cut down on the amount of refactoring needed in the future for similar situations. This concept has already been hinted at in some of the comments but I thought it would be worth showing how to actually do it. So you have your main interface that looks like this so far: ``` public interface IDrawable { void Update(); void Draw(); } ``` Now create an abstract class with the constructor you want to enforce. Actually, since it's now available since the time you wrote your original question, we can get a little fancy here and use generics in this situation so that we can adapt this to other interfaces that might need the same functionality but have different constructor requirements: ``` public abstract class MustInitialize<T> { public MustInitialize(T parameters) { } } ``` Now you'll need to create a new class that inherits from both the IDrawable interface and the MustInitialize abstract class: ``` public class Drawable : MustInitialize<GraphicsDeviceManager>, IDrawable { GraphicsDeviceManager _graphicsDeviceManager; public Drawable(GraphicsDeviceManager graphicsDeviceManager) : base (graphicsDeviceManager) { _graphicsDeviceManager = graphicsDeviceManager; } public void Update() { //use _graphicsDeviceManager here to do whatever } public void Draw() { //use _graphicsDeviceManager here to do whatever } } ``` Then just create an instance of Drawable and you're good to go: ``` IDrawable drawableService = new Drawable(myGraphicsDeviceManager); ``` The cool thing here is that the new Drawable class we created still behaves just like what we would expect from an IDrawable. If you need to pass more than one parameter to the MustInitialize constructor, you can create a class that defines properties for all of the fields you'll need to pass in.
You can't. It's occasionally a pain, but you wouldn't be able to call it using normal techniques anyway. In a blog post I've suggested [static interfaces](http://codeblog.jonskeet.uk/2008/08/29/lessons-learned-from-protocol-buffers-part-4-static-interfaces/) which would only be usable in generic type constraints - but could be really handy, IMO. One point about if you *could* define a constructor within an interface, you'd have trouble deriving classes: ``` public class Foo : IParameterlessConstructor { public Foo() // As per the interface { } } public class Bar : Foo { // Yikes! We now don't have a parameterless constructor... public Bar(int x) { } } ```
Interface defining a constructor signature?
[ "", "c#", "interface", "constructor", "" ]
1. I have SQL Server 2000, **it doesn't support MultipleActiveResults**. 2. I have to do multiple inserts, and it's done with one connection per insertion. 3. I want to begin a transaction before all insertions and finish it after all insertions. 4. How do I do it?
What is the reason you don't use one connection and multiple commands (actually one command recreated in loop)? Maybe this solution will work for you: ``` public static void CommandExecNonQuery(SqlCommand cmd, string query, SqlParameter[] prms) { cmd.CommandText = query; cmd.Parameters.AddRange(prms); cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } static void Main(string[] args) { string insertQuery = @"INSERT TESTTABLE (COLUMN1, COLUMN2) " + "VALUES(@ParamCol1, @ParamCol2)"; using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand command = connection.CreateCommand()) { SqlTransaction transaction = null; try { // BeginTransaction() Requires Open Connection connection.Open(); transaction = connection.BeginTransaction(); // Assign Transaction to Command command.Transaction = transaction; for (int i = 0; i < 100; i++) CommandExecNonQuery(command, insertQuery, new SqlParameter[] { new SqlParameter("@ParamCol1", i), new SqlParameter("@ParamCol2", i.ToString()) }); transaction.Commit(); } catch { transaction.Rollback(); throw; } finally { connection.Close(); } } } } ``` Also see [Sql Server Transactions - ADO.NET 2.0 - Commit and Rollback - Using Statement - IDisposable](http://davidhayden.com/blog/dave/archive/2005/10/14/2515.aspx)
You didn't specify if you're using .NET 2.0, but I'll make that assumption. C# 3.0 sample code is listed below: ``` using (var tx = new TransactionScope()) { // Execute multiple DB statements inside here ts.Complete(); } ``` If any of the DB statements fail, the ts.complete will never be reached and the transaction will be rolled back automatically at the end of the using statement. However, one caveat to this approach is that you'll end up leveraging the DTC if you use multiple connections, which means slower performance. Edited to change SqlTransaction to TransactionScope An example of forcing a single SQL connection to avoid using the DTC: ``` using (var tx = new TransactionScope()) using (var db = new SqlConnection(connString)) { // Command 1 using (var cmd = db.CreateCommand()) { cmd.CommandText = "select..."; using (var reader = cmd.ExecuteReader()) { // Process results or store them somewhere for later } } // Command 2 using (var cmd = db.CreateCommand()) { cmd.CommandText = "select..."; using (var reader = cmd.ExecuteReader()) { // Process results or store them somewhere for later } } // Command 3 using (var cmd = db.CreateCommand()) { cmd.CommandText = "select..."; using (var reader = cmd.ExecuteReader()) { // Process results or store them somewhere for later } } tx.Complete(); } ```
How to use a single SqlTransaction for multiple SqlConnections in .NET?
[ "", ".net", "sql", "sql-server", "sql-server-2000", "transactions", "" ]
I have a text field that can be 30 characters in length, however it can achieve around 2.000 characters. For "future safety", it would be nice if this new column could support until 3.000 characters. I think the average size of this field is 250 characters. **Which SQL Server 2000 data type is better to increase performance and disk space?**
Do you need unicode or nonunicode data? Use either varchar(3000) or nvarchar (3000). Don't use text or ntext as they become problematic to query or update. To design for average length makes no sense.
If your field is going to hold up to 3000 characters, you should probably make sure your datatype will allow for something that big. Design based upon your maximum, not your average.
Creating a new text column in a SQL Server Table: which type should I choose?
[ "", "sql", "sql-server", "database", "database-design", "data-structures", "" ]
The question header is clear, i want to know why its different and why, when to select it for my project?
[I wrote a blog post on this a while ago](http://blogs.teamb.com/craigstuntz/2008/07/17/37825/ "The ADO.NET Entity Framework vs. NHibernate and Other ORMs"). In short, it takes a fundamentally different approach to ORM than Hibernate, ECO, and the other ORMs that I have looked at. You may think this approach is better, worse, or unimportant, but if you look deep enough it's hard to dispute that it is different. But don't take my word on it. If you're really interested in this subject, I strongly recommend reading [this technical paper](http://portal.acm.org/citation.cfm?id=1412331.1412334 "Compiling mappings to bridge applications and databases") and [this interview](http://queue.acm.org/detail.cfm?id=1394137) in ACM Queue.
This is probably not the answer you are looking for but I dont think you should use it in your project. It is very young and not very complete. Wait until the next version comes out. If you insist on using Entity Framework there are a few good things about it. A nice one is the way it allows for complex mapping in a very simple way. And of course because it is a microsoft technology the IDE integration is nice. But like I said, I tried it and I dont beleive it is ready for real use. Anyway good luck at your project
What makes The ADO.NET Entity Framework different than other ORM in the market?
[ "", "c#", ".net", "vb.net", "entity-framework", "ado.net", "" ]
`If you set the innerHTML of a <div> to innerHTML = '<a href="Something/C%23">C#</a><br />';` What seems to actually get 'rendered' is: ``` <div> <a href="Something/C#">C#</a><br /> </div> ``` What is the proper way to escape this so the link will stay "Something/C%23" ? **UPDATE**: I noticed a weird little thing here. If you use a function to build up the link. The extra %25 escaping is not needed. Weird. ex. ``` function buildLink(tg, nm) { return '<a href="Something/' + tg + '">' + nm + '</a><br />'; } ```
Try this: ``` <a href="Something/C%2523">C#</a><br /> ``` Expand the "`%`" to "`%25`" and you get what you want. Then the "`%25`" is converted back to the percent character and the subsequent `23` is not reinterpreted.
It's worth noting that many browsers will render a link to "`Something/C%23`" as "`Something/C#`" as a "friendly" URL. Check your `div` using Firebug or a similar tool to make sure it's actually being set incorrectly. If so, then you need to escape the percent sign as `%25`: ``` innerHTML = '<a href="Something/C%2523">C#</a><br />'; ```
innerHTML and C%23 (C#) in anchor hrefs - Firefox
[ "", "javascript", "firefox", "escaping", "innerhtml", "" ]
Something that can do two-way bean synchronization with components, and also more fancy (advanced) stuff?
There is also the [JGoodies Binding](https://binding.dev.java.net/) project. The author has a fairly detailed [presentation](http://www.jgoodies.com/articles/binding.pdf) on it. It works using PropertyChangeListeners, if I recall correctly. I haven't used it myself, but other developers in my workplace have experimented with it and had fairly positive impressions.
Well, there's the [Beans Binding](https://beansbinding.dev.java.net/) project, for starters. There's an example on [java.net](http://weblogs.java.net/pub/a/2008/03/20/synchronizing-properties-with-beans-binding.html). If you use NetBeans, there's support [built in](http://www.netbeans.org/kb/60/java/gui-binding.html).
What are usable databinding libraries for Swing?
[ "", "java", "swing", "data-binding", "" ]
After much research I am a little confused by which identity tracker I should use in sql. From what I understand scope\_identity will give me the last id updated from any table and ident\_current will will return the last id from a specified table. So given that information it would seem to me the best version to use (if you know which table you will be updating) is ident\_current. Yet, upon reading it seems most people prefer to use scope\_identity. What is the reasoning behind this and is there a flaw in my logic?
In that case you need to write the table name, what happens if you decide to change the table name? You then also must not forget to update your code to reflect that. I always use SCOPE\_IDENTITY unless I need the ID from the insert that happens in a trigger then I will use @@IDENTITY Also the bigger difference is that IDENT\_CURRENT will give you the identity from another process that did the insert (in other words last generated identity value from any user) so if you do an insert and then someone does an insert before you do a SELECT IDENT\_CURRENT you will get that other person's identity value See also [6 Different Ways To Get The Current Identity Value](http://wiki.lessthandot.com/index.php/6_Different_Ways_To_Get_The_Current_Identity_Value) which has some code explaining what happens when you put triggers on the table
From what I've read scope\_identity() *should* be the right answer, however it looks like there is a bug in SQL 2005 and SQL 2008 that can come into play if your insert results in a parallel query plan. Take a look at the following articles for more details: [`@@IDENTITY vs SCOPE_IDENTITY() vs IDENT_CURRENT` - Retrieve Last Inserted Identity of Record](http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/) Article: [Six reasons you should be nervous about parallelism](https://sqlblog.org/2009/03/21/six-reasons-you-should-be-nervous-about-parallelism) See section titled: ***1. #328811, "`SCOPE_IDENTITY()` sometimes returns incorrect value"***
scope_identity vs ident_current
[ "", "sql", "sql-server", "t-sql", "" ]
In the following C# code snippet I have a '`while`' loop inside a '`foreach`' loop and I wish to jump to the next item in '`foreach`' when a certain condition occurs. ``` foreach (string objectName in this.ObjectNames) { // Line to jump to when this.MoveToNextObject is true. this.ExecuteSomeCode(); while (this.boolValue) { // 'continue' would jump to here. this.ExecuteSomeMoreCode(); if (this.MoveToNextObject()) { // What should go here to jump to next object. } this.ExecuteEvenMoreCode(); this.boolValue = this.ResumeWhileLoop(); } this.ExecuteSomeOtherCode(); } ``` '`continue`' would jump to the beginning of the '`while`' loop not the '`foreach`' loop. Is there's a keyword to use here, or should I just use goto which I don't really like.
The following should do the trick ``` foreach (string objectName in this.ObjectNames) { // Line to jump to when this.MoveToNextObject is true. this.ExecuteSomeCode(); while (this.boolValue) { if (this.MoveToNextObject()) { // What should go here to jump to next object. break; } } if (! this.boolValue) continue; // continue foreach this.ExecuteSomeOtherCode(); } ```
Use the break keyword. That will exit the while loop and continue execution outside it. Since you don't have anything after the while, it would loop around to the next item in the foreach loop. Actually, looking at your example more closely, you actually want to be able to advance the for loop without exiting the while. You can't do this with a foreach loop, but you can break down a foreach loop to what it actually automates. In .NET, a foreach loop is actually rendered as a .GetEnumerator() call on the IEnumerable object (which your this.ObjectNames object is). The foreach loop is basically this: ``` IEnumerator enumerator = this.ObjectNames.GetEnumerator(); while (enumerator.MoveNext()) { string objectName = (string)enumerator.Value; // your code inside the foreach loop would be here } ``` Once you have this structure, you can call enumerator.MoveNext() within your while loop to advance to the next element. So your code would become: ``` IEnumerator enumerator = this.ObjectNames.GetEnumerator(); while (enumerator.MoveNext()) { while (this.ResumeWhileLoop()) { if (this.MoveToNextObject()) { // advance the loop if (!enumerator.MoveNext()) // if false, there are no more items, so exit return; } // do your stuff } } ```
Continue in while inside foreach
[ "", "c#", "foreach", "keyword", "while-loop", "continue", "" ]
How do I set a null value for an optional DateTime parameter in a constructor? I'm using the following constructor below and I want the optional parameter admissionDate to be a null DateTime. Setting it to Nothing actually gives it a value (something like #12:00:00 #). ``` Public Sub New(ByVal obj1 as Object, Optional ByVal admissionDate As DateTime = System.Data.SqlTypes.SqlDateTime.Null) ```
I'd suggest using James Curran's solution but use Overloading instead of an optional parameter, as a workaround for the error you mentioned ("Optional parameters cannot have structure types") : ``` Public Sub New(ByVal obj1 As Object, ByVal admissionDate As Nullable(Of DateTime)) //Your code here End Sub Public Sub New(Byval obj1 As Object) Me.New(obj1, Nothing) End Sub ``` You can also use DateTime? instead of Nullable(Of DateTime) in the latest version of VB (not sure about the older versions).
You'll need a Nullable DateTime. In C#, that's `Nullable<DateTime>` or `DateTime?`. I'm not sure of the VB.NET syntax, but I think it's something like `Nullable(Of DateTime)` ``` Public Sub New(ByVal obj1 as Object, _ Optional ByVal admissionDate As Nullable(Of DateTime) = Null) ```
Setting SqlDateTime.Null in a constructor
[ "", ".net", "sql", "vb.net", "datetime", "" ]
I am trying to workout a way to programatically create a key for [Memcached](http://en.wikipedia.org/wiki/Memcached), based on the method name and parameters. So if I have a method, ``` string GetName(int param1, int param2); ``` it would return: ``` string key = "GetName(1,2)"; ``` I know you can get the MethodBase using reflection, but how do I get the parameters values in the string, not the parameter types?
What you're looking for is an interceptor. Like the name says, an interceptor intercepts a method invocation and allows you to perform things before and after a method is called. This is quite popular in many caching and logging frameworks.
You can't get method parameter values from reflection. You'd have to use the debugging/profiling API. You can get the parameter names and types, but not the parameters themselves. Sorry...
Using reflection to get method name and parameters
[ "", "c#", ".net", "memcached", "system.reflection", "" ]
How can I read and modify "NTFS Alternate Data Streams" using .NET? It seems there is no native .NET support for it. Which Win32 API's would I use? Also, how would I use them, as I don't think this is documented?
Not in .NET: <http://support.microsoft.com/kb/105763> ``` #include <windows.h> #include <stdio.h> void main( ) { HANDLE hFile, hStream; DWORD dwRet; hFile = CreateFile( "testfile", GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, 0, NULL ); if( hFile == INVALID_HANDLE_VALUE ) printf( "Cannot open testfile\n" ); else WriteFile( hFile, "This is testfile", 16, &dwRet, NULL ); hStream = CreateFile( "testfile:stream", GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, 0, NULL ); if( hStream == INVALID_HANDLE_VALUE ) printf( "Cannot open testfile:stream\n" ); else WriteFile(hStream, "This is testfile:stream", 23, &dwRet, NULL); } ```
Here is a version for C# ``` using System.Runtime.InteropServices; class Program { static void Main(string[] args) { var mainStream = NativeMethods.CreateFileW( "testfile", NativeConstants.GENERIC_WRITE, NativeConstants.FILE_SHARE_WRITE, IntPtr.Zero, NativeConstants.OPEN_ALWAYS, 0, IntPtr.Zero); var stream = NativeMethods.CreateFileW( "testfile:stream", NativeConstants.GENERIC_WRITE, NativeConstants.FILE_SHARE_WRITE, IntPtr.Zero, NativeConstants.OPEN_ALWAYS, 0, IntPtr.Zero); } } public partial class NativeMethods { /// Return Type: HANDLE->void* ///lpFileName: LPCWSTR->WCHAR* ///dwDesiredAccess: DWORD->unsigned int ///dwShareMode: DWORD->unsigned int ///lpSecurityAttributes: LPSECURITY_ATTRIBUTES->_SECURITY_ATTRIBUTES* ///dwCreationDisposition: DWORD->unsigned int ///dwFlagsAndAttributes: DWORD->unsigned int ///hTemplateFile: HANDLE->void* [DllImportAttribute("kernel32.dll", EntryPoint = "CreateFileW")] public static extern System.IntPtr CreateFileW( [InAttribute()] [MarshalAsAttribute(UnmanagedType.LPWStr)] string lpFileName, uint dwDesiredAccess, uint dwShareMode, [InAttribute()] System.IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, [InAttribute()] System.IntPtr hTemplateFile ); } public partial class NativeConstants { /// GENERIC_WRITE -> (0x40000000L) public const int GENERIC_WRITE = 1073741824; /// FILE_SHARE_DELETE -> 0x00000004 public const int FILE_SHARE_DELETE = 4; /// FILE_SHARE_WRITE -> 0x00000002 public const int FILE_SHARE_WRITE = 2; /// FILE_SHARE_READ -> 0x00000001 public const int FILE_SHARE_READ = 1; /// OPEN_ALWAYS -> 4 public const int OPEN_ALWAYS = 4; } ```
How to read and modify NTFS Alternate Data Streams using .NET
[ "", "c#", ".net", "ntfs", "alternate-data-stream", "" ]
How dangerous is this php code? What can be done about it? ``` $name = $_POST["user"]; $pwd = $_POST["pwd"]; $query = "SELECT name,pwd FROM users WHERE name = '$name' AND pwd = '$pwd'"; ```
Possible Problems: 1. SQL Injection 2. XSS Injection (if this code was an insert query, it would be a definite problem) 3. Plain Text Password Your SQL Statement can be problematic. It is bad practice to leave yourself open for SQL injection. [SQL Injection is bad](http://en.wikipedia.org/wiki/SQL_injection). Trust me. If you want to display the $user on an HTML page, then you may not want to include the ability for people to "hack" your layout by typing in commands like ``` <H1>HI MOM</H1> ``` or a bunch of [javascript](http://en.wikipedia.org/wiki/Cross-site_scripting). Also, never store your password in plain text (good catch cagcowboy!). It gives too much power to people administering (or hacking) your database. You should never NEED to know someone's password. Try tactics like these: ``` // mostly pulled from http://snippets.dzone.com/posts/show/2738 function MakeSafe($unsafestring) { $unsafestring= htmlentities($unsafestring, ENT_QUOTES); if (get_magic_quotes_gpc()) { $unsafestring= stripslashes($unsafestring); } $unsafestring= mysql_real_escape_string(trim($unsafestring)); $unsafestring= strip_tags($unsafestring); $unsafestring= str_replace("\r\n", "", $unsafestring); return $unsafestring; } // Call a function to make sure the variables you are // pulling in are not able to inject sql into your // sql statement causing massive doom and destruction. $name = MakeSafe( $_POST["user"] ); $pwd = MakeSafe( $_POST["pwd"] ); // As suggested by cagcowboy: // You should NEVER store passwords decrypted. // Ever. // sha1 creates a hash of your password // pack helps to shrink your hash // base64_encode turns it into base64 $pwd = base64_encode(pack("H*",sha1($pwd))) ```
It's this dangerous: ![xkcd bobby tables](https://imgs.xkcd.com/comics/exploits_of_a_mom.png)
How dangerous is this PHP code?
[ "", "php", "security", "sql-injection", "" ]
Does anyone knows a good 2D engine for Java with sprites, animations and collisions handling?
JGame is probably what you're looking for. You might also want to check out this question ( <https://stackoverflow.com/questions/293079/java-2d-game-frameworks> ) that has a list of Engines out there and a bit of feedback on some of them. Hope it's helpful.
[Slick2D](http://slick.cokeandcode.com/) seems to be a pretty solid choice. It's widely used and it is based on OpenGL (via [LWJGL](http://www.lwjgl.org/)) so you can get some pretty good performance if you need it.
A good 2d engine for Java?
[ "", "java", "graphics", "2d", "sprite", "" ]
I am reading a list of assigned rights from an exchange mailbox, these values are returned via the AccessFlag property which returns 20001 in Hex, it looks like 2000 represents the READ permission and the 1 represents FULL permission. What I want to do is display that value as READ & FULL permissions set.
If you want is as a string, you need an enum. So if you have something like this: ``` [Flags] enum Permissions { Read = 0x20000, Full = 0x00001 } ``` Then you can cast your return value and use ToString() ``` string val = ((Permissions )myValue).ToString(); ``` And it will come out something like this: ``` Read, Full ``` Note that the Flags attribute is important for this type of enum.
To be honest I'm not sure what you're asking for. If you have a value from the AccessFlag, and you want to see if it has either of those flag, you can use a bitwise and e.g. ``` If((accessFlag & 0x2000) != 0) // It has FULL If((accessFlag & 0x1) != 0) // It has READ If((accessFlag & 0x2001) != 0) // It has READ AND FULL ``` Is this what you're looking for?
C# Converting Hex Values
[ "", "c#", "hex", "" ]
I have a list of tuples of unicode objects: ``` >>> t = [('亀',), ('犬',)] ``` Printing this out, I get: ``` >>> print t [('\xe4\xba\x80',), ('\xe7\x8a\xac',)] ``` which I guess is a list of the utf-8 byte-code representation of those strings? but what I want to see printed out is, surprise: ``` [('亀',), ('犬',)] ``` but I'm having an inordinate amount of trouble getting the bytecode back into a human-readable form.
> but what I want to see printed out is, surprise: > > [('亀',), ('犬',)] What do you want to see it printed out on? Because if it's the console, it's not at all guaranteed your console can display those characters. This is why Python's ‘repr()’ representation of objects goes for the safe option of \-escapes, which you will always be able to see on-screen and type in easily. As a prerequisite you should be using Unicode strings (u''). And, as mentioned by Matthew, if you want to be able to write u'亀' directly in source you need to make sure Python can read the file's encoding. For occasional use of non-ASCII characters it is best to stick with the escaped version u'\u4e80', but when you have a lot of East Asian text you want to be able to read, “# coding=utf-8” is definitely the way to go. > print '[%s]' % ', '.join([', '.join('(%s,)' % ', '.join(ti) for ti in t)]) That would print the characters unwrapped by quotes. Really you'd want: ``` def reprunicode(u): return repr(u).decode('raw_unicode_escape') print u'[%s]' % u', '.join([u'(%s,)' % reprunicode(ti[0]) for ti in t]) ``` This would work, but if the console didn't support Unicode (and this is especially troublesome on Windows), you'll get a big old UnicodeError. In any case, this rarely matters because the repr() of an object, which is what you're seeing here, doesn't usually make it to the public user interface of an application; it's really for the coder only. However, you'll be pleased to know that Python 3.0 behaves exactly as you want: * plain '' strings without the ‘u’ prefix are now Unicode strings * repr() shows most Unicode characters verbatim * Unicode in the Windows console is better supported (you can still get UnicodeError on Unix if your environment isn't UTF-8) Python 3.0 is a little bit new and not so well-supported by libraries, but it might well suit your needs better.
First, there's a slight misunderstanding in your post. If you define a list like this: ``` >>> t = [('亀',), ('犬',)] ``` ...those are not `unicode`s you define, but `str`s. If you want to have `unicode` types, you have to add a `u` before the character: ``` >>> t = [(u'亀',), (u'犬',)] ``` But let's assume you actually want `str`s, not `unicode`s. The main problem is, `__str__` method of a list (or a tuple) is practically equal to its `__repr__` method (which returns a string that, when evaluated, would create exactly the same object). Because `__repr__` method should be encoding-independent, strings are represented in the safest mode possible, i.e. each character outside of ASCII range is represented as a hex character (`\xe4`, for example). Unfortunately, as far as I know, there's no library method for printing a list that is locale-aware. You could use an almost-general-purpose function like this: ``` def collection_str(collection): if isinstance(collection, list): brackets = '[%s]' single_add = '' elif isinstance(collection, tuple): brackets = '(%s)' single_add =',' else: return str(collection) items = ', '.join([collection_str(x) for x in collection]) if len(collection) == 1: items += single_add return brackets % items >>> print collection_str(t) [('亀',), ('犬',)] ``` Note that this won't work for all possible collections (sets and dictionaries, for example), but it's easy to extend it to handle those.
How to print tuples of unicode strings in original language (not u'foo' form)
[ "", "python", "unicode", "" ]
I'm looking to add a "Download this File" function below every video on one of my sites. I need to force the user to download the file, instead of just linking to it, since that begins playing a file in the browser sometimes. The problem is, the video files are stored on a separate server. Any way I can force the download in PHP?
You could try something like this: ``` <?php // Locate. $file_name = 'file.avi'; $file_url = 'http://www.myremoteserver.com/' . $file_name; // Configure. header('Content-Type: application/octet-stream'); header("Content-Transfer-Encoding: Binary"); header("Content-disposition: attachment; filename=\"".$file_name."\""); // Actual download. readfile($file_url); // Finally, just to be sure that remaining script does not output anything. exit; ``` I just tested it and it works for me. Please note that for `readfile` to be able to read a remote url, you need to have your [`fopen_wrappers`](http://us.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen) enabled.
Tested download.php file is ``` function _Download($f_location, $f_name){ $file = uniqid() . '.pdf'; file_put_contents($file,file_get_contents($f_location)); header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Length: ' . filesize($file)); header('Content-Disposition: attachment; filename=' . basename($f_name)); readfile($file); } _Download($_GET['file'], "file.pdf"); ``` and the link to download is ``` <a href="download.php?file=http://url/file.pdf"> Descargar </a> ```
php - How to force download of a file?
[ "", "php", "download", "remote-server", "" ]
I'm extending a utility class that bundles a set of images and .xml description files. Currently I keep all the files in a directory and load them from there. The directory looks like this: ``` 8.png 8.xml 9.png 9.xml 10.png 10.xml ... ... 50.png 50.xml ... ``` Here's my current constructor. It is lightning fast and does what I need it to do. (I've stripped out some of the error checking to make it easier to read): ``` public DivineFont(String directory ) { File dir = new File(directory); //children is an array that looks like this: '10.fnt', '11.fnt', etc. String[] children = dir.list(fntFileFilter); fonts = new Hashtable<Integer, AngelCodeFont>(100); AngelCodeFont buffer; int number; String fntFile; String imgFile; for(int k = 0; k < children.length; k++ ) { number = Integer.parseInt( children[k].split("\\.")[0] ); fntFile = directory + File.separator + number + ".xml"; imgFile = directory + File.separator + number + ".png"; buffer = new AngelCodeFont(fntFile, imgFile); fonts.put(number, buffer); } } ``` For the sake of webstart and cleanliness, I've been trying to load these resources from a Jar instead. I've got it working, but the load time went from instantaneous to a few seconds, and that's not acceptable. Here's the code I tried (again, error checking stripped): (This isn't the *best* way to do what I want to do, it's a mock-up to see if the idea worked. It didn't. The two for-loops is in no way the source of the problem; it's the process of creating all those InputStreams that slows it down) ``` public DivineFont(String jarFileName ) { JarFile jarfile = new JarFile(jarFileName); Enumeration<JarEntry> em = jarfile.entries(); ArrayList<Integer> fontHeights = new ArrayList<Integer>(100); for (Enumeration em1 = jarfile.entries(); em1.hasMoreElements(); ) { String fileName = em1.nextElement().toString(); if( fileName.endsWith(".fnt") ) { fontHeights.add( Integer.parseInt(fileName.split("\\.")[0] ) ); } } fonts = new Hashtable<Integer, AngelCodeFont>(100); AngelCodeFont buffer; int number; for(int k = 0; k < fontHeights.size(); k++ ) { number = fontHeights.get(k); InputStream fntFileStream = jarfile.getInputStream(jarfile.getEntry(number + ".xml")); InputStream pngFileStream = jarfile.getInputStream(jarfile.getEntry(number + ".png")); buffer = new AngelCodeFont(String.valueOf(number), fntFileStream, pngFileStream ); fonts.put(number, buffer); } } ``` Anyone know of a better way to work with .jar files besides the way I've tried here? Here's the [AngelCodeFont API](http://slick.cokeandcode.com/javadoc/org/newdawn/slick/AngelCodeFont.html). If it was absolutely necessary I could submit a patch for that, but I'd rather not have to. It seems to me that there's probably a way to do what I want to do, I'm just not familiar with it. I'm not terribly against quickly dumping the jar to a temporary directory and then reading the files from there, but if there's a way to do it reading directly from the jar quickly, I'd much rather do that. Also: Compression isn't an issue at all. The only reason I'm using a jar is for the packing issue.
Well, I found the answer. The answer to my original question was "Wrong question." The Jar file wasn't the issue, it was the library I was using to load the images. When I was loading from the file system, the image was being named "38.png", etc. When I was loading from the Jar, I was simply naming it "38". The Image loader class inside the library uses the file extension of the name to identify which image loader to use. If there is no file extension, it uses a slower, basic image loader. When I changed this line: ``` buffer = new AngelCodeFont(String.valueOf(number), fntFileStream, pngFileStream ); ``` to this line: ``` buffer = new AngelCodeFont( number + ".png", fntFileStream, pngFileStream ); ``` We have ourselves a winner. Thanks for the help anyway guys. It took me a few hours to figure this out, but if not for your posts, I probably would have continued to assume the blame was Java's rather than the Library I'm using.
*Opening* a JAR is a very expensive operation. So you may want to open the JAR once and keep the `JarFile` instance in a static field somewhere. In your case, you will also want to read all entries and keep them in a hashmap for instant access of the resource you need. Another solution is to put the JAR on the classpath and use ``` DivineFont.class.getContextClassLoader().getResource*("/8.png"); ``` Mind the "/"! If you omit it, Java will search in the same directory (package) in which it finds the file DivineFont.class. Getting things from the classpath has been optimized to death in Java.
Extracting files from a Jar more efficently
[ "", "java", "jar", "compression", "zip", "" ]
I'm trying to unit test a method that performs a fairly complex operation, but I've been able to break that operation down into a number of steps on mockable interfaces like so: ``` public class Foo { public Foo(IDependency1 dp1, IDependency2 dp2, IDependency3 dp3, IDependency4 dp4) { ... } public IEnumerable<int> Frobnicate(IInput input) { var step1 = _dependency1.DoSomeWork(input); var step2 = _dependency2.DoAdditionalWork(step1); var step3 = _dependency3.DoEvenMoreWork(step2); return _dependency4.DoFinalWork(step3); } private IDependency1 _dependency1; private IDependency2 _dependency2; private IDependency3 _dependency3; private IDependency4 _dependency4; } ``` I'm using a mocking framework (Rhino.Mocks) to generate mocks for purposes of testing, and structuring the code in the fashion shown here has been very effective thus far. But how do I unit test this method without having one big test that needs every mock object and every expectation set every time? For example: ``` [Test] public void FrobnicateDoesSomeWorkAndAdditionalWorkAndEvenMoreWorkAndFinalWorkAndReturnsResult() { var fakeInput = ...; var step1 = ...; var step2 = ...; var step3 = ...; var fakeOutput = ...; MockRepository mocks = new MockRepository(); var mockDependency1 = mocks.CreateMock<IDependency1>(); Expect.Call(mockDependency1.DoSomeWork(fakeInput)).Return(step1); var mockDependency2 = mocks.CreateMock<IDependency2>(); Expect.Call(mockDependency2.DoAdditionalWork(step1)).Return(step2); var mockDependency3 = mocks.CreateMock<IDependency3>(); Expect.Call(mockDependency3.DoEvenMoreWork(step2)).Return(step3); var mockDependency4 = mocks.CreateMock<IDependency4>(); Expect.Call(mockDependency4.DoFinalWork(step3)).Return(fakeOutput); mocks.ReplayAll(); Foo foo = new Foo(mockDependency1, mockDependency2, mockDependency3, mockDependency4); Assert.AreSame(fakeOutput, foo.Frobnicate(fakeInput)); mocks.VerifyAll(); } ``` This seems incredibly brittle. Any change to the implementation of Frobnicate causes this test to fail (like breaking down step 3 into 2 sub-steps). It's an all-in-one sort of thing, so trying to use multiple smaller tests isn't going to work. It starts to approach write-only code for future maintainers, myself included next month when I've forgotten how it works. There has to be a better way! Right?
Test each implementation of IDependencyX in isolation. Then you will know that each individual step of that process is correct. When testing them individually, test every possible input and special condition. Then do an integration test of Foo, using the real implementations of IDependencyX. Then you will know that all the individual parts are plugged together correctly. It's often enough to just test with one input, because you are only testing simple glue code.
Lots of dependencies suggest that there are intermediate concepts lying implicit in the code, so perhaps some of the dependencies can be packaged up and this code made simpler. Alternatively, perhaps what you've got is some kind of chain of handlers. In which case, you write unit tests for each link in the chain, and integration tests to make sure they all fit together.
How can I avoid large multi-step unit tests?
[ "", "c#", "unit-testing", "inversion-of-control", "mocking", "rhino-mocks", "" ]
I'm having some trouble figuring out how to slice python lists, it is illustrated as follows: ``` >>> test = range(10) >>> test [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> test[3:-1] [3, 4, 5, 6, 7, 8] >>> test[3:0] [] >>> test[3:1] [] >>> test [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ``` To my understanding, python slice means lst[start:end], and including start, excluding end. So how would i go about finding the "rest" of a list starting from an element n? Thanks a lot for all your help!
You can leave one end of the slice open by not specifying the value. ``` test[3:] = [3, 4, 5, 6, 7, 8, 9] test[:3] = [0, 1, 2] ```
If you're using a variable as the range endpoint, you can use `None`. ``` start = 4 end = None test[start:end] ```
How to slice a list from an element n to the end in python?
[ "", "python", "list", "sequence", "slice", "" ]
I have a C++ class and I am trying to run it in Ubuntu: ``` #ifndef WRONGPARAMETEREXCEPTION_H_ #define WRONGPARAMETEREXCEPTION_H_ #include <iostream> #include <exception> #include <string> using namespace std; #pragma once class WrongParameterException: public exception { public: WrongParameterException(char* message): exception(message) {}; virtual ~WrongParameterException() throw() {}; }; #endif ``` when I try to compile it, the compiler gives me this error: ``` WrongParameterException.h: In constructor ‘WrongParameterException::WrongParameterException(char*)’: WrongParameterException.h:14: error: no matching function for call to ‘std::exception::exception(char*&)’ /usr/include/c++/4.3/exception:59: note: candidates are: std::exception::exception() /usr/include/c++/4.3/exception:57: note: std::exception::exception(const std::exception&) ``` Can anyone tell me what am I doing wrong? I tried changing the message variable to `string` or `const string` or `const string&` but it didn't help. Here is how I use the new exception that I created from main: ``` try { if ((strToInt1 == -1) || (parameters[1] == NULL) || (strToInt3 == -1) || (parameters[3] != NULL)) { throw WrongParameterException("Error in the config or commands file"); } } catch(WrongParameterException e) { log.addMsg(e.what()); } ```
First, `#pragma once` is the wrong way to go about it, learn about header include guards. [Related question on SO](https://stackoverflow.com/a/34884735/13986) explains why using `#pragma once` is the wrong way to go about it. Wikipedia explains how to use [include guards](https://en.wikipedia.org/wiki/Include_guard) which serve the same purpose without any of the downsides. Second, you are calling the constructor of std::exception with a parameter it does not know, in this case a pointer to a character array. ``` #include <stdexcept> #include <string> class WrongParameterException : public std::runtime_error { public: WrongParameterException(const std::string& message) : std::runtime_error(message) { }; }; ``` Would probably be what you want. For more information on exceptions, check out [C++ FAQ Lite article on Exceptions](http://www.parashift.com/c++-faq-lite/exceptions.html "Exceptions") and the [exceptions article](http://www.cplusplus.com/doc/tutorial/exceptions.html) at cplusplus.com. Good luck!
std::exception does not have a constructor that takes any kind of string, only a virtual what() method that returns the exception description. You will have to store the string yourself and return it from there.
Creating new exception in C++
[ "", "c++", "linux", "exception", "ubuntu", "" ]
Java 5 has introduced many features that can be make logging statements less cluttering, such as variable number of arguments and printf. That can alleviate all the message building code that happens when something is logged, as well as the surrounding `if`. For example, instead of writing: ``` if (log.isDebugEnabled() { log.debug("User id: "+uid+", Request id:" + rid +", Client IP: "+ip+" blah blah blah"); } ``` I would like to write: ``` log.debug("User id: %s, Request id: %s, Client IP: %s blah blah blah", uid, rid, ip); ``` or something like that. Do you know a logging framework or an extension to a logging framework that can help with that?
[Log5j](http://code.google.com/p/log5j/) is exacly what you need.
[Simple Logging Facade for Java (SLF4J)](http://www.slf4j.org/) > The Simple Logging Facade for Java or > (SLF4J) is intended to serve as a > simple facade for various logging APIs > allowing to the end-user to plug in > the desired implementation at > deployment time. SLF4J also supports a > bridging legacy APIs as well as a > source code migration tool. > > SLF4J API offers an advanced > abstraction of various logging > systems, including JDK 1.4 logging, > log4j and logback. Features include > parameterized logging and MDC support. Example: ``` logger.info("{} {}!", "Hello", "world"); ``` produces "Hello world!" but only if info level is enabled.
Is there a log4j or commons logging extension or other logging framework that is designed for Java 5 or higher?
[ "", "java", "logging", "log4j", "java-5", "" ]
I'm using Oracle 10g and Hibernate 2.1 (old version, but not allowed to upgrade to fix). I've got a table with a not nullable column named TIN, varchar2(9). This column is used to stage data loaded from flat files and so can store any string of length 9, including 9 spaces (that is: ' ') if the input file had 9 spaces. What I've noticed is that: 1. Oracle 10g automatically converts empty strings to NULL. So if you execute: ``` SELECT NVL('', 'Input string converted to NULL') FROM dual; ``` the result is 'Input string converted to NULL', not ''. I think this is relevant to the problem. 2. When Hibernate reads a record where the TIN value is 9 spaces (or any number of spaces) with no other character, it stores the value in memory as ''. Hibernate then seems to trick itself into thinking, so to speak, that the value has changed from 9 spaces to an empty string. Then if the record is written back to the database, Hibernate tries to to write an empty string rather than 9 spaces and Oracle apparently converts this to null and then throws a not-null constraint violation. For reference, here's the HBM for this column: ``` <property name="tin" type="java.lang.String" column="TIN" not-null="true" length="9"> ``` My question is, how do I instruct Hibernate not to convert values that only contain spaces to empty strings? Update 1: I just went back and tested strings like ' text ' and found that Hibernate trims these spaces too, making the string 'text' and fooling itself into thinking that the value changed. I must be missing something. This doesn't seem like default behavior. Update 2: It looks like the hbm2java Ant task that converts the HBM to Java source might be the source of the String trims. Still investigating. Thanks, Jeff Edit: Changed question wording to be more precise.
Turned out that the issue wasn't with Hibernate. The project I'm working on was set up to generate Java POJOs from the HBM files using the hbm2java Ant task. This in turn references a source template for getters/setters/equals/toString/etc that was written to trim all java.lang.String properties in the setter. To fix the problem I passivated the one class with which I was having problems so that it would no longer be generated on each build and then removed the trim on the TIN property.
One way to deal with this is to [create a Hibernate UserType](http://www.hibernate.org/169.html). There are instructions in the link at hibernate.org with some already-made classes for String escaping. I realize this doesn't directly answer 'how do I tell hibernate not to convert 9 spaces to empty string', but it will solve the storage problem on the database side. There are 2 implementations on that page - one that escapes all strings (may handle your 9 spaces case in your desired manner), and one that only escapes the value ''. It sounds like the former may be a better fit for you. For the record - I am utilizing this method myself. All you need to do is have the class in your classpath, and set the 'type' attribute in your HBM.xml to the fully qualified classname (i.e add type="my.fully.qualified.HibernateUserType" to your property element). On the Java side your classes will still deal directly with java.lang.String and the values you expect to see, but on the hibernate side, they will use the UserType class.
How do I prevent Hibernate from trimming strings?
[ "", "java", "oracle", "hibernate", "" ]
We have a web service that we will be hosting on a public web server and it will be contacted by web services hosted on web servers within the walls of a hospital. We have written both pieces of the software so we have complete control over what is implemented. We would like to secure communications between the two web servers. Currently the only thing we have in place is https on the public web server and a guid to identify the clients. There are network level types of authorization we can support but I don’t like relying on these since not all of our customers (hospitals) will be able to do the same thing. Some will not have the ability to give us a static IP and some will not be able to do a VPN, so we cant solely rely on those methods. *What techniques are you using or do you recommend to authorize communications to your web services?* Our main concern is keeping people from getting a hospitals ID (currently just a GUID) and getting data from our web service that is intended for the hospital. We will employ other networking level security measures to limit the public access to our system but I feel a software solution is necessary as well. The system is not yet in production but is nearing the completion of development. Its developed in C# on .net 3.5 FWIW I was thinking of some sort of token based authorization because I know a previous employer used something along those lines. However, I do not know specifically what to look for or any other information on the topic. **Edit:** While I would like to use WCF, currently no one on the team (including myself) has any experience using it and we've already developed the web services along with the code that interacts with them. All of the web references where added using the .net 2.0 method (from vs.net08, targeted to .net 3.5) and we would prefer to not completely redo that. I wont say that WCF is not an option, but I don't think we will go with that option willingly.
Could you use something like Basic Authentication over https to provide username password challenging? I believe the Microsoft SOAP supports it fairly well. You pretty much just use IIS to configure basic auth (must use SSL), and in your C# just pass ICredentials to your proxy. From googling, it looks like other languages support basic auth over SOAP too.
Client certificates can be used to provide credentials from a caller to your webservices; it's not that hard to take the passed cert and do any additional evaluation to dictate what that cert has visibility into.
What should we implement to authorize clients to use our web service?
[ "", "c#", "web-services", "security", "http-authentication", "" ]
I have two triggers After Insert or Update and Instead of Insert. It appears that the after trigger is not running or sending the correct data. I have verified the correct operation of Z\_UpdateStageTable stored procedure and the Instead of Insert trigger. Removing the Instead of Insert trigger doesn't have any affect. The After Insert, Update trigger was working correctly at one time, I haven't made any changes to it. I have tried deleting it and adding it, but it still doesn't run or have the correct data. Any Ideas? Instead of Insert: ``` ALTER TRIGGER [DeleteExistingFilter] ON [dbo].[Z_MobileSyncFilters] INSTEAD OF INSERT AS BEGIN SET NOCOUNT ON; DELETE FROM Z_MobileSyncFilters WHERE UserID = (SELECT UserID FROM INSERTED); INSERT INTO Z_MobileSyncFilters SELECT * FROM INSERTED; END ``` After Insert, Update: ``` TRIGGER [UpdateStageTable] ON [dbo].[Z_MobileSyncFilters] AFTER INSERT,UPDATE AS BEGIN SET NOCOUNT ON; DECLARE @AllWos AS VARCHAR(5000); DECLARE @PmWos AS VARCHAR(5000); DECLARE @RepWos AS VARCHAR(5000); SET @AllWos = (SELECT AllWos FROM INSERTED); SET @RepWos = (SELECT AllWos FROM INSERTED); SET @PmWos = (SELECT AllWos FROM INSERTED); EXEC Z_UpdateStageTable @AllWos; EXEC Z_UpdateStageTable @RepWos; EXEC Z_UpdateStageTable @PmWos; END ```
Is there a typo in the `SET` part of the `AFTER` trigger? You're selecting the same thing into three different variables. Rather than confirming the behavior of `Z_UpdateStageTable`, I'd try to replace it with something dirt simple (a parameterless sql statement, say) to test whether the trigger's being called. It's possible that the sproc's not being called with what you think it's being called with.
You can add `PRINT` statements to the trigger and manually insert from ManagementStudio/Enterprise Manager to see where the trigger fails. I see a problem when you insert multiple records in a single statement, as the `SELECT FROM Inserted` will return more than 1 record. You can also update the `SET` statement to `SELECT @Var = AllWos FROM Inserted`
After insert, update trigger not running
[ "", "sql", "sql-server", "triggers", "" ]
I have a loop going, but there is the possibility for exceptions to be raised inside the loop. This of course would stop my program all together. To prevent that, I catch the exceptions and handle them. But then the rest of the iteration runs even though an exception occurred. Is there a keyword to use in my `except:` clause to just skip the rest of the current iteration?
You are looking for [`continue`](https://docs.python.org/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops).
``` for i in iterator: try: # Do something. pass except: # Continue to next iteration. continue ```
How to skip iterations in a loop?
[ "", "python", "" ]
When I last worked in programming, we were trying to move away from `DataReaders` and the traditional ADO.NET API toward Object Relational Mapping (ORM). To do this, we generated a `DataContext` of our DB via `sqlmetal`. There was then a thin data layer that made the `DataContext` `private`, and any code needing to access the database would have to use a `public` method in this thin data layer. These methods were basically stored procedures; they would perform queries on the database via LINQ to SQL. Is this a common approach today? I mean, is everyone whose using the .NET 3.5 framework really running sqlmetal in their build process, or what? It almost seemed like a hack at the time. Basically, I'd like to know if LINQ to SQL and sqlmetal is what to expect if I'm go to write a DAL today at a .NET 3.5 shop that doesn't employ a third-party, open-source ORM.
Your approach is good. I currently use Astroria services ([ADO.NET Data Services](http://msdn.microsoft.com/en-us/data/bb931106.aspx)). There was a nice introduction in [MSDN Magazine](http://msdn.microsoft.com/en-us/magazine/cc748663.aspx) about this. I also like the new [PLINQO](http://code.google.com/p/codesmith/) (requires [CodeSmith Tools](http://www.codesmithtools.com/) though). This is very slick in my opinion. When I have such a DAL (service layer), I just consume this service from my client application (Silverlight or ASP.NET MVC).
It is still considered best practice to have some sort of data access layer. Whether this is best achieved with a ORM is a heavily debated issue. There is one faction that generally argues that ORM's are the way to go. Another faction argues that stored procedures and database centric is the best route. Also, this may not be exactly the poster you meant, but it similar (and also the one in my cubicle) <http://download.microsoft.com/download/4/a/3/4a3c7c55-84ab-4588-84a4-f96424a7d82d/NET35_Namespaces_Poster_LORES.pdf>
.NET and database layers
[ "", "c#", "database", "linq-to-sql", "entity-framework", "" ]
I've a table with large number of rows (10K+) and it primary key is GUID. The primary key is clustered. The query performance is quite low on this table. Please provide suggestions to make it efficient.
You need to use newsequentialid() instead see here [Some Simple Code To Show The Difference Between Newid And Newsequentialid](http://sqlblog.com/blogs/denis_gobo/archive/2009/02/05/11743.aspx)
A clustered index on GUID is not a good design. The very nature of GUID is that it's random, while a clustered index physically orders the records by the key. The two things are completely at odds. For every insert SQL has to reorder the records on disk! Remove clustering from this index! The time to use clustering is when you have a "natural" order to the data: time inserted, account number, etc. For time fields, clustering is almost free. For account number, it might be free or cheap (when account numbers are assigned sequentially). While there may be technical ways around the GUID issue, the best idea is to understand when to use clustering.
Improving performance of cluster index GUID primary key
[ "", "sql", "primary-key", "performance", "guid", "clustered-index", "" ]
It sometimes want to block my thread while waiting for a event to occur. I usually do it something like this: ``` private AutoResetEvent _autoResetEvent = new AutoResetEvent(false); private void OnEvent(object sender, EventArgs e){ _autoResetEvent.Set(); } // ... button.Click += OnEvent; try{ _autoResetEvent.WaitOne(); } finally{ button.Click -= OnEvent; } ``` However, it seems that this should be something that I could extract to a common class (or perhaps even something that already exists in the framework). I would like to be able to do something like this: ``` EventWaiter ew = new EventWaiter(button.Click); ew.WaitOne(); EventWaiter ew2 = new EventWaiter(form.Closing); ew2.WaitOne(); ``` But I can't really find a way to construct such a class (I can't find a good valid way to pass the event as an argument). Can anyone help? To give an example of why this can be useful, consider something like this: ``` var status = ShowStatusForm(); status.ShowInsertUsbStick(); bool cancelled = WaitForUsbStickOrCancel(); if(!cancelled){ status.ShowWritingOnUsbStick(); WriteOnUsbStick(); status.AskUserToRemoveUsbStick(); WaitForUsbStickToBeRemoved(); status.ShowFinished(); }else{ status.ShowCancelled(); } status.WaitUntilUserPressesDone(); ``` This is much more concise and readable than the equivalent code written with the logic spread out between many methods. But to implement WaitForUsbStickOrCancel(), WaitForUsbStickToBeRemoved and WaitUntilUserPressesDone() (assume that the we get an event when usb sticks are inserted or removed) I need to reimplement "EventWaiter" each time. Of course you have to be careful to never run this on the GUI-thread, but sometimes that is a worthwhile tradeoff for the simpler code. The alternative would look something like this: ``` var status = ShowStatusForm(); status.ShowInsertUsbStick(); usbHandler.Inserted += OnInserted; status.Cancel += OnCancel; //... void OnInserted(/*..*/){ usbHandler.Inserted -= OnInserted; status.ShowWritingOnUsbStick(); MethodInvoker mi = () => WriteOnUsbStick(); mi.BeginInvoke(WritingDone, null); } void WritingDone(/*..*/){ /* EndInvoke */ status.AskUserToRemoveUsbStick(); usbHandler.Removed += OnRemoved; } void OnRemoved(/*..*/){ usbHandler.Removed -= OnRemoved; status.ShowFinished(); status.Done += OnDone; } /* etc */ ``` I find that much harder to read. Admittedly, it is far from always that the flow will be so linear, but when it is, I like the first style. It is comparable to using ShowMessage() and Form.ShowDialog() - they also block until some "event" occurs (though they will run a message-loop if they are called on the gui-thread).
I modified Dead.Rabit's class EventWaiter to handle `EventHandler<T>`. So you can use for waiting all events type of `EventHandler<T>`, that means your delegate is something like `delegate void SomeDelegate(object sender, T EventsArgs)`. ``` public class EventWaiter<T> { private AutoResetEvent _autoResetEvent = new AutoResetEvent(false); private EventInfo _event = null; private object _eventContainer = null; public EventWaiter(object eventContainer, string eventName) { _eventContainer = eventContainer; _event = eventContainer.GetType().GetEvent(eventName); } public void WaitForEvent(TimeSpan timeout) { EventHandler<T> eventHandler = new EventHandler<T>((sender, args) => { _autoResetEvent.Set(); }); _event.AddEventHandler(_eventContainer, eventHandler); _autoResetEvent.WaitOne(timeout); _event.RemoveEventHandler(_eventContainer, eventHandler); } } ``` And for example I use that for waiting to get Url from HttpNotificationChannel when I registering to windows push notification service. ``` HttpNotificationChannel pushChannel = new HttpNotificationChannel(channelName); //ChannelUriUpdated is event EventWaiter<NotificationChannelUriEventArgs> ew = new EventWaiter<NotificationChannelUriEventArgs>(pushChannel, "ChannelUriUpdated"); pushChannel.Open(); ew.WaitForEvent(TimeSpan.FromSeconds(30)); ```
Don't pass the event, pass a delegate that matches the event handler signature. This actually sounds hacky to me, so be aware of potential dead lock issues.
Blocking and waiting for an event
[ "", "c#", ".net", "events", "" ]
I need a open-source/free C# tool or library that can do financial charting for a student project. It needs to be able to do a open-high-low-close chart, and be able to graph various technical indicators that I calculate, all from within a Windows form. Any recommendations?
Try [ZedGraph](http://sourceforge.net/projects/zedgraph/). You can do almost anything with that library. Note: It's free and open source.
Microsoft has released a [chart control](http://www.microsoft.com/downloads/details.aspx?FamilyId=130F7986-BF49-4FE5-9CA8-910AE6EA442C&displaylang=en) for .NET 3.5. You can get support at [this forum.](http://social.msdn.microsoft.com/Forums/en-US/MSWinWebChart/threads/)
C# financial charting library for Windows Forms?
[ "", "c#", "winforms", "charts", "financial", "" ]
I've seen methods like this: ``` public void Foo(List<string> list) { list.Add("Bar"); } ``` Is this good practice to modify parameters in a method? Wouldn't this be better? ``` public List<string> Foo(List<string> list) { // Edit List<string> newlist = new List<string>(list); newlist.Add("Bar"); return newlist; } ``` It just feels like the first example has unexpected side effects.
In the example you've given, the first seems a lot nicer to me than the second. If I saw a method that accepted a list and also returned a list, my first assumption would be that it was returning a new list and not touching the one it was given. The second method, therefore, is the one with unexpected side effects. As long as your methods are named appropriately there's little danger in modifying the parameter. Consider this: ``` public void Fill<T>(IList<T> list) { // add a bunch of items to list } ``` With a name like "Fill" you can be pretty certain that the method will modify the list.
Frankly, in this case, both methods do more or less the same thing. Both will modify the `List` that was passed in. If the objective is to have lists immutable by such a method, the second example should make a copy of the `List` that was sent in, and then perform the `Add` operation on the new `List` and then return that. I'm not familiar with C# nor .NET, so my guess would be something along the line of: ``` public List<string> Foo(List<string> list) { List<string> newList = (List<string>)list.Clone(); newList.Add("Bar"); return newList; } ``` This way, the method which calls the `Foo` method will get the newly created `List` returned, and the original `List` that was passed in would not be touched. This really is up to the "contract" of your specifications or API, so in cases where `List`s can just be modified, I don't see a problem with going with the first approach.
Are methods that modify reference type parameters bad?
[ "", "c#", "side-effects", "" ]
So the teacher has posed this assignment: You have been hired by the United Network Command for Law Enforcement, and you have been given files containing null cyphers you have to decrypt. So for the first file given (as an example), every other letter is correct (ie: 'hielqlpo' is hello (assuming you start with the first letter). My first question is, how do I read in a file? The document is on my desktop in a folder and the file is named document01.cry. I'm not sure the command I need to put that file into the program. I'm also not overly sure how to grab a letter and skip a letter, but honestly I want to tinker with that before I post that question! So for now...my question is as stated in the title: How do you grab a file for reading in C++? If it makes a difference (As I'm sure it does), I'm using Visual C++ 2008 Express Edition (because it's free and I like it! I've also attached what I have so far, please keep in mind it's -very- basic...and I added the `getchar();` at the end so when it does run properly, the window stays open so I can see it (as Visual Express tends to close the window as soon as it's done running.) The code so far: ``` #include<iostream> using namespace std; int main() { while (! cin.eof()) { int c = cin.get() ; cout.put(c) ; } getchar(); } ``` PS: I realize that this code grabs and puts out every character. For now that's fine, once I can read in the file I think I can tinker with it from there. I'm also poking at a book or two I have on C++ to see it anything pops up and screams "Pick me!" Thanks again! EDIT:: Also curious, is there a way to input the file you want? (I.e.: ``` char filename; cout << "Please make sure the document is in the same file as the program, thank you!" << endl << "Please input document name: " ; cin >> filename; cout << endl; ifstream infile(filename, ios::in); ``` This code doesn't work. It shoots back an error saying the char can't be converted to a const char \*. How can this problem be fixed? EDIT 2: Never mind about said part 2, I found it out! Thanks again for the assistance!
I figured it out! To be honest no one answer helped, it was a combination of the three, plus the comments from them. Thank you all very much! I've attached the code I used, as well as a copy of the document. The program reads in every character, then spits out the deciphered text. (IE: 1h.e0l/lqo is hello) The next step (extra credit) is to set it up so the user inputs how many characters to skip before reading in the next character to input. This step I intend to do on my own, but again, thank you very much for all the assistance everyone! Proving once again how awesome this site is, one line of code at a time! EDIT:: Code adjusted to accept user input, as well as allow for multiple uses without recompiling (I realize it looks like a huge sloppy mess, but that's why it's EXTREMELY commented...because in my mind it looks nice and neat) ``` #include<iostream> #include<fstream> //used for reading/writing to files, ifstream could have been used, but used fstream for that 'just in case' feeling. #include<string> //needed for the filename. #include<stdio.h> //for goto statement using namespace std; int main() { program: char choice; //lets user choose whether to do another document or not. char letter; //used to track each character in the document. int x = 1; //first counter for tracking correct letter. int y = 1; //second counter (1 is used instead of 0 for ease of reading, 1 being the "first character"). int z; //third counter (used as a check to see if the first two counters are equal). string filename; //allows for user to input the filename they wish to use. cout << "Please make sure the document is in the same file as the program, thank you!" << endl << "Please input document name: " ; cin >> filename; //getline(cin, filename); cout << endl; cout << "'Every nth character is good', what number is n?: "; cin >> z; //user inputs the number at which the character is good. IE: every 5th character is good, they would input 5. cout << endl; z = z - 1; //by subtracting 1, you now have the number of characters you will be skipping, the one after those is the letter you want. ifstream infile(filename.c_str()); //gets the filename provided, see below for incorrect input. if(infile.is_open()) //checks to see if the file is opened. { while(!infile.eof()) //continues looping until the end of the file. { infile.get(letter); //gets the letters in the order that that they are in the file. if (x == y) //checks to see if the counters match... { x++; //...if they do, adds 1 to the x counter. } else { if((x - y) == z) //for every nth character that is good, x - y = nth - 1. { cout << letter; //...if they don't, that means that character is one you want, so it prints that character. y = x; //sets both counters equal to restart the process of counting. } else //only used when more than every other letter is garbage, continues adding 1 to the first { //counter until the first and second counters are equal. x++; } } } cout << endl << "Decryption complete...if unreadable, please check to see if your input key was correct then try again." << endl; infile.close(); cout << "Do you wish to try again? Please press y then enter if yes (case senstive)."; cin >> choice; if(choice == 'y') { goto program; } } else //this prints out and program is skipped in case an incorrect file name is used. { cout << "Unable to open file, please make sure the filename is correct and that you typed in the extension" << endl; cout << "IE:" << " filename.txt" << endl; cout << "You input: " << filename << endl; cout << "Do you wish to try again? Please press y then enter if yes (case senstive)." ; cin >> choice; if(choice == 'y') { goto program; } } getchar(); //because I use visual C++ express. } ``` EDIT::: I tried inserting the text, but I couldn't get it to come out right, it kept treating some of the characters like coding (ie an apostrophe apparently is the equivalent of the bold command), but you could just try putting in "0h1e.l9lao" without the parenthesis into a .txt and it should give the same outcome. Thanks again everyone for the help!
To do file operations, you need the correct include: ``` #include <fstream> ``` Then, in your main function, you can open a file stream: ``` ifstream inFile( "filename.txt", ios::in ); ``` or, for output: ``` ofstream outFile( "filename.txt", ios::out ); ``` You can then use inFile as you would use cin, and outFile as you would use cout. To close the file when you are done: ``` inFile.close(); outFile.close(); ```
How do you get a file in C++?
[ "", "c++", "file", "io", "" ]
We are ready in our company to move everything to Python instead of C#, we are a consulting company and we usually write small projects in C# we don't do huge projects and our work is more based on complex mathematical models not complex software structures. So we believe IronPython is a good platform for us because it provides standard GUI functionality on windows and access to all of .Net libraries. I know Ironpython studio is not complete, and in fact I had a hard time adding my references but I was wondering if someone could list some of the pros and cons of this migration for us, considering Python code is easier to read by our clients and we usually deliver a proof-of-concept prototype instead of a full-functional code, our clients usually go ahead and implement the application themselves
My company, Resolver Systems, develops what is probably the biggest application written in IronPython yet. (It's called Resolver One, and it's a Pythonic spreadsheet). We are also hosting the Ironclad project (to run CPython extensions under IronPython) and that is going well (we plan to release a beta of Resolver One & numpy soon). The reason we chose IronPython was the .NET integration - our clients want 100% integration on Windows and the easiest way to do that right now is .NET. We design our GUI (without behaviour) in Visual Studio, compile it into a DLL and subclass it from IronPython to add behaviour. We have found that IronPython is faster at some cases and slower at some others. However, the IronPython team is very responsive, whenever we report a regression they fix it and usually backport it to the bugfix release. If you worry about performance, you can always implement a critical part in C# (we haven't had to do that yet). If you have experience with C#, then IronPython will be natural for you, and easier than C#, especially for prototypes. Regarding IronPython studio, we don't use it. Each of us has his editor of choice (TextPad, Emacs, Vim & Wing), and everything works fine.
There are a lot of reasons why you want to switch from C# to python, i did this myself recently. After a lot of investigating, here are the reasons why i stick to CPython: * Performance: There are some articles out there stating that there are always cases where ironpython is slower, so if performance is an issue * Take the original: many people argue that new features etc. are always integrated in CPython first and you have to wait until they are implemented in ironpython. * Licensing: Some people argue this is a timebomb: nobody knows how the licensing of ironpython/mono might change in near future * Extensions: one of the strengths of python are the thousands of extensions which are all usable by CPython, as you mentioned mathematical problems: numpy might be a suitable fast package for you which might not run as expected under IronPython (although [Ironclad](http://www.resolversystems.com/documentation/index.php/Ironclad)) * Especially under Windows you have a native GUI-toolkit with wxPython which also looks great under several other platforms and there are pyQT and a lot of other toolkits. They have nice designer like wxGlade, but here VisualStudio C# Designer is easier to use. * Platform independence (if this is an issue): CPython is ported to really a lot of platforms, whereas ironpython can only be used on the major platforms (recently read a developer was sad that he couldn't get mono to run under his AIX) Ironpython is a great work, and if i had a special .NET library i would have to use, IronPython might be the choice, but for general purpose problems, people seem to suggest using the original CPython, unless Guido changes his mind.
Pros and cons of IronPython and IronPython Studio
[ "", "python", "ironpython", "ironpython-studio", "" ]
I am using Login Control available in ASP.NET 2.0 in the login page. Once the user is authenticated successfully against database, I am redirecting the user to home.aspx. Here, I want to pass on the User's name too to the home.aspx so that the user will be greeted with his/her name in the home.aspx. Ex: Welcome Smith I am extracting the User's name from the users table in my database during the time I check for the login credentials. Could someone please tell me how to do this in a secure way (may be not to secure, but a little)? Thanks,
One good place for that kind of data would be in session. Try something like this on the first page: ``` this.Session["UserName"] = userName; ``` and then subsequent pages in that session for that user could access `this.Session["UserName"]`. The best thing to do though is to create a static class to manage `Session` for you like so: ``` using System; using System.Web; static class SessionManager { public static String UserName { get { return HttpContext.Current.Session["UserName"].ToString(); } set { HttpContext.Current.Session["UserName"] = value; } } // add other properties as needed } ``` Then your application can access session state like this: ``` SessionManager.UserName ``` This will give you maximum flexibility and scalability moving forward.
As [ScottS](https://stackoverflow.com/questions/620134/pass-values-or-data-from-one-page-to-another-when-you-use-login-control-in-asp-ne/620177#620177) said, if you're using the standard login controls and a membership provider this information is already available to you in User.Identity.Name. The only reason I'm posting an answer is to mention the [LoginName](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.loginname.aspx) control, which you can drop on a page/master page and have this done automatically for you: ``` <asp:LoginName id="LoginName1" runat="server" FormatString ="Welcome, {0}" /> ``` This will render out "Welcome, Zhaph" when the user is logged in, or nothing if they are not. You can also combine this quite nicely with the [LoginView](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.loginview.aspx) and [LoginStatus](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.loginstatus.aspx) controls: ``` <asp:LoginView ID="RegisterLink" runat="server"> <AnonymousTemplate> <div class="titleRegistration"> <a href="/Users/Register.aspx">Register</a> or </div> </AnonymousTemplate> <LoggedInTemplate> <div class="titleRegistration"> Welcome back <asp:LoginName ID="LoginName1" runat="server" /> - </div> </LoggedInTemplate> </asp:LoginView> <asp:LoginStatus ID="lsGeneral" runat="server" LogoutPageUrl="/Users/Logout.aspx" /> ``` This combination of controls will do the following: 1. If the user isn't logged in display: Register or Login 2. If the user is logged in display: Welcome back Zhaph - Logout The Login links is populated by the settings in web.config, and generated by the LoginStatus control.
pass values or data from one page to another when you use Login control in ASP.NET 2.0
[ "", "c#", "asp.net", "asp.net-2.0", "" ]
I think sometimes I don't need to use ELSEIF and not repeat stuff by maybe doing multiple checks inline. I've done this before. I'm trying this simple line and just can't make it work. I read that: OR is the same as || AND is the same as && Code (The short way, but doesn't work): ``` if($subdom<>'www' or $subdom<>'nosub') {do some stuff if any of the two are meet} ``` I also tried this: Code: ``` if((subdom!='www') || ($subdom!='nosub')){} ``` What will be the correct operators to check for any of the two? Is it || or &&. Should we use != or <> also? Some Info found after question answered: > $a && $b > //And //TRUE if both $a and $b are TRUE. > > $a || $b > //Or //TRUE if either $a or $b is TRUE. Either of these will work as the comparison: **!==** (not equal identical), but not **!=** as it will mean "does not assign" **<>** will do the trick without too much merry go round.
Your expression is always true, considering your example, check the table with different input values for $subdom: $expr = ($subdom!='www') || ($subdom!='nosub'); ``` $subdom ($subdom!='www') ($subdom!='nosub') result ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯ www | false | true | true | nosub | true | false | true | anything | true | true | true | blah! | true | true | true | ``` I think you're wanting to use the AND (&&) operator here...
You have to carefully think through the logic that you're trying to express. Right now, your logic says "If the subdomain isn't 'www' or the subdomain isn't 'nosub'". If either one of those is true, the code will be executed. Let's try some test cases on this: * **nosub**: this isn't "www", so that condition is true, execute the code * **random**: this isn't "www" or "nosub", so both conditions are true, execute the code * **www**: this isn't "nosub", so that condition is true, execute the code Basically what you've done is made it so everything will be true. What you're actually trying to express is "The subdomain isn't 'www' AND it isn't 'nosub'". That is, if it's NEITHER of those, you want to execute the code. The correct if statement would be: `if ($subd != 'nosub' && $subd != 'www')`. If you have trouble with this, it may be better to change your process of coming up with the logic that you put inside the if statement. Here is a description of how you could build it up. First, start with the condition that you're considering "good". The "good" condition is "$subd is one of 'www' or 'nosub'". The if statement for this would be: `if ($subd == 'www' || $subd == 'nosub')` Now, you're trying to write code to handle the condition not being good, so you need to take the opposite of the good condition. To take the opposite of a boolean condition, you surround the whole thing with a NOT. In code: `if !($subd == 'www' || $subd == 'nosub')` *(note the exclamation point in front)*. If you want to move that negation inside (as you had been trying to do originally), it's a property of boolean algebra (I hope this is the right term, it's been a long time since I learned this) that when you move a negation into a relation like that, you negate both the operands, and also change the operator from an AND to an OR, or vice versa. So in this case, when you move the negative inside the parentheses, both the `==` become `!=` and the `||` becomes `&&`, resulting in: `if ($subd != 'www' && $subd != 'nosub)`, as I had given above. **Edit again**: The properties I mention in the last paragraph are called [De Morgan's laws](http://en.wikipedia.org/wiki/De_Morgan%27s_laws).
Multiple Inline Conditions AND OR vs ELSEIF
[ "", "php", "" ]
If 'Test' is an ordinary class, is there any difference between: ``` Test* test = new Test; ``` and ``` Test* test = new Test(); ```
Let's get pedantic, because there are differences that can actually affect your code's behavior. Much of the following is taken from comments made to an Old New Thing article Sometimes the memory returned by the new operator will be initialized, and sometimes it won't depending on whether the type you're newing up is a [POD (plain old data)](https://stackoverflow.com/questions/146452/what-are-pod-types-in-c), or if it's a class that contains POD members and is using a compiler-generated default constructor. * In C++1998 there are 2 types of initialization: zero and default * In C++2003 a 3rd type of initialization, value initialization was added. Assume: ``` struct A { int m; }; // POD struct B { ~B(); int m; }; // non-POD, compiler generated default ctor struct C { C() : m() {}; ~C(); int m; }; // non-POD, default-initialising m ``` In a C++98 compiler, the following should occur: * `new A` - indeterminate value * `new A()` - zero-initialize * `new B` - default construct (B::m is uninitialized) * `new B()` - default construct (B::m is uninitialized) * `new C` - default construct (C::m is zero-initialized) * `new C()` - default construct (C::m is zero-initialized) In a C++03 conformant compiler, things should work like so: * `new A` - indeterminate value * `new A()` - value-initialize A, which is zero-initialization since it's a POD. * `new B` - default-initializes (leaves B::m uninitialized) * `new B()` - value-initializes B which zero-initializes all fields since its default ctor is compiler generated as opposed to user-defined. * `new C` - default-initializes C, which calls the default ctor. * `new C()` - value-initializes C, which calls the default ctor. So in all versions of C++ there's a difference between `new A` and `new A()` because A is a POD. And there's a difference in behavior between C++98 and C++03 for the case `new B()`. This is one of the dusty corners of C++ that can drive you crazy. When constructing an object, sometimes you want/need the parens, sometimes you absolutely cannot have them, and sometimes it doesn't matter.
`new Thing();` is explicit that you want a constructor called whereas `new Thing;` is taken to imply you don't mind if the constructor isn't called. If used on a struct/class with a user-defined constructor, there is no difference. If called on a trivial struct/class (e.g. `struct Thing { int i; };`) then `new Thing;` is like `malloc(sizeof(Thing));` whereas `new Thing();` is like `calloc(sizeof(Thing));` - it gets zero initialized. The gotcha lies in-between: ``` struct Thingy { ~Thingy(); // No-longer a trivial class virtual WaxOn(); int i; }; ``` The behavior of `new Thingy;` vs `new Thingy();` in this case changed between C++98 and C++2003. See [Michael Burr's explanation](https://stackoverflow.com/a/620402/8735401) for how and why.
Do the parentheses after the type name make a difference with new?
[ "", "c++", "constructor", "initialization", "new-operator", "c++-faq", "" ]
Looking into possibility of making an USB distributed application that will autostart on insertion of an USB stick and shutdown when removing the stick Will use .Net and C#. Looking for suggestion how to approach this using C#? --- Update: Two possible solutions implementing this as a service. - override WndProc or - using WMI query with ManagementEventWatcher
You can use WMI, it is easy and it works a lot better than WndProc solution with services. Here is a simple example: ``` using System.Management; ManagementEventWatcher watcher = new ManagementEventWatcher(); WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2"); watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived); watcher.Query = query; watcher.Start(); watcher.WaitForNextEvent(); ```
This works well for me, plus you can find out more information about the device. ``` using System.Management; private void DeviceInsertedEvent(object sender, EventArrivedEventArgs e) { ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"]; foreach (var property in instance.Properties) { Console.WriteLine(property.Name + " = " + property.Value); } } private void DeviceRemovedEvent(object sender, EventArrivedEventArgs e) { ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"]; foreach (var property in instance.Properties) { Console.WriteLine(property.Name + " = " + property.Value); } } private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { WqlEventQuery insertQuery = new WqlEventQuery("SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'"); ManagementEventWatcher insertWatcher = new ManagementEventWatcher(insertQuery); insertWatcher.EventArrived += new EventArrivedEventHandler(DeviceInsertedEvent); insertWatcher.Start(); WqlEventQuery removeQuery = new WqlEventQuery("SELECT * FROM __InstanceDeletionEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'"); ManagementEventWatcher removeWatcher = new ManagementEventWatcher(removeQuery); removeWatcher.EventArrived += new EventArrivedEventHandler(DeviceRemovedEvent); removeWatcher.Start(); // Do something while waiting for events System.Threading.Thread.Sleep(20000000); } ```
Detecting USB drive insertion and removal using windows service and c#
[ "", "c#", ".net", "windows", "windows-services", "wmi", "" ]
I've put together a basic applet where the user selects a file from their hard drive, it reads the first line of this file and passes that off to JavaScript for some additional preprocessing, and then when you click a button it tries to upload that file through an HTTP POST request. I found a very basic open source applet for uploading files that I copied and modified for this last bit. The trouble is, though, it doesn't quite work. It seems like it's running fine, but then I run into two snags related to permissions. The messages in the Java Console say that the applet had access denied errors on the following two permissions: ``` java.lang.RuntimePermission setFactory java.io.FilePermission read ``` I find this strange, because I thought I had granted permission to the applet already when I built it with the "self-signed" option checked in NetBeans, and then clicked to confirm the little security pop-up in the browser. Also, the part that I coded myself, where it reads the file and passes the first line on to JavaScript works fine. This is a pretty clear indicator that the applet is able to read from the local file system! The trouble doesn't start until I actually try to start the upload. One thing to note, I suppose, is that the upload process seems to run in a new thread, whereas the rest of it all runs in the main class without creating threads. I am a total novice to Java and know very little about threads in Java; do I need to pass the permissions onto this new thread somehow? Or something to that effect? Thanks in advance.
You probably need to ask the security manager (code, not administrator) for permission to do a privileged operation. For various reasons, it's not generally a good thing for an applet to be able to open a local file, so it's guarded pretty heavily. The basic key is to call `AccessController.doPrivileged()` and there's a [good little tutorial](http://faq.javaranch.com/java/HowCanAnAppletReadFilesOnTheLocalFileSystem) on it at the Java Ranch FAQ.
I had a similar problem which took forever to solve. It turns out applet methods called from JavaScript have no permissions, even if you explicitly grant them in a policy file. This workaround worked for me (adding commands to a queue which the applet loops through): <http://blog.carrythezero.com/?p=5> Make sure you understand the dangers here: Anyone can modify JavaScript on a page and change what's getting fed into the applet. In my case I know the code is never going on a webserver, and the class is unsigned so it will fail unless in the specific location granted by my policy file.
Java Applet Permissions
[ "", "java", "upload", "permissions", "applet", "" ]
I'm hoping to make a quick script to log-out/restart windows at a set time. For example, start a script to "Restart windows in ten minutes". For this implementation I don't need it to run in the background or pop=up on its own. I just want to set the script and walk away knowing that the computer will log-out/restart at a set time. **Why would I want to do this?** On a corporate network, sometimes system logs will be reviewed and if one is found to be leaving X minutes too early, then complications arise. Kinda annoying. **Did I already Google it?** Yep. I found [this](http://kvance.livejournal.com/985732.html). But it wasn't too helpful. It requires a framework I couldn't find, and likely couldn't install since we don't have admin privs on these machines. I'd like to use Python for it, and I'd really like for it to look like the user did it, not a script. Perhaps screen scraping would be the only way, and if so just point me to a quick guide or IDE and I'll post the source code for everyone. **EDIT**: I also ran into [this](http://sourceforge.net/projects/pywinauto/)
The shutdown command in batch will shutdown the computer -s to turn it off, -f to force it, -t xx to have it shutdown in x seconds, use the subprocess module in python to call it. Since you want it to shutdown at a specific time, to automate the job completely you'd need to use something like autosys. Set the script up to call shutdown with a value for T equal to time you want to shut down - current time in seconds. Run it before you leave for the day, or have it set to run on start up and just ignore that stupid window it brings up.
[PsShutdown](http://technet.microsoft.com/en-us/sysinternals/bb897541.aspx) is probably what you are looking for.
Programmatically restart windows to make system logs think user logged out
[ "", "python", "windows", "automation", "" ]
I'm making a little memory leak finder in my program, but my way of overloading new and delete (and also new[] and delete[]) doesn't seem to do anything. ``` void* operator new (unsigned int size, const char* filename, int line) { void* ptr = new void[size]; memleakfinder.AddTrack(ptr,size,filename,line); return ptr; } ``` The way I overloaded `new` is shown in the code snippet above. I guess it's something with the operator returning void\* but I do not know what to do about it.
``` void* ptr = new void[size]; ``` Can't do that. Fix it. Never ever try to overload new/delete globally. Either have them in a base class and derive all your objects from this class or use a namespace or a template allocator parameter. Why, you may ask. Because in case your program is more than a single file and using STL or other libraries you are going to screw up. Here's a distilled version of `new` operator from VS2005 `new.cpp`: ``` void * operator new(size_t size) _THROW1(_STD bad_alloc) { // try to allocate size bytes void *p; while ((p = malloc(size)) == 0) if (_callnewh(size) == 0) { // report no memory static const std::bad_alloc nomem; _RAISE(nomem); } return (p); } ```
Maybe you can do what you want with a little bit of preprocessor magic: ``` #include <iostream> using namespace std; void* operator new (size_t size, const char* filename, int line) { void* ptr = new char[size]; cout << "size = " << size << " filename = " << filename << " line = " << line << endl; return ptr; } #define new new(__FILE__, __LINE__) int main() { int* x = new int; } ```
How to obtain the source location in an overload of operator new
[ "", "c++", "operator-overloading", "new-operator", "delete-operator", "" ]
Alright, I have a Django view, like this: ``` @render_to('home/main.html') def login(request): # also tried Client.objects.select_related().all() clients = Client.objects.all() return {'clients':clients} ``` And I have a template, `main.html`, like this: ``` <ul> {% for client in clients %} <li>{{ client.full_name }}</li> <ul> {% for pet in client.pets.all %} <li>{{ pet.full_name }}</li> {% endfor %} </ul> {% endfor %} </ul> ``` I also print out all the queries in [`sql_queries`](http://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-debug) at the bottom of my base template. When I run this view, the following queries are made: ``` SELECT `home_client`.`id`, ... FROM `home_client`; SELECT `home_pet`.`id`, ... FROM `home_pet` WHERE `home_pet`.`client_id` = 1; SELECT `home_client`.`id`, ... FROM `home_client` WHERE `home_client`.`id` = 1; SELECT `home_client`.`id`, ... FROM `home_client` WHERE `home_client`.`id` = 1; SELECT `home_pet`.`id`, ... FROM `home_pet` WHERE `home_pet`.`client_id` = 2; SELECT `home_client`.`id`, ... FROM `home_client` WHERE `home_client`.`id` = 2; ``` My question is, why are all these queries being made? Shouldn't it just be 1 query to retrieve all the clients and a query per client to retrieve all the pets from each client? I have 2 clients in the `home_client` table, so it should be 3 queries total. Most troubling of all is that queries 3 and 4 are 100% identical. I don't want to "prematurely optimize" or anything but I do want to make sure Django isn't being wildly inefficient. Any help on this would be appreciated. Thanks.
Does Client 1 have 2 Pets and Client 2 have 1 Pet? If so, that would indicate to me that `Pet.full_name` or something else you're doing in the Pet display loop is trying to access its related Client's details. Django's ORM doesn't use an [identity map](http://martinfowler.com/eaaCatalog/identityMap.html), so accessing the Client foreign key from any of your Pet objects would require hitting the database again to retrieve that Client. P.S. [`select_related`](http://docs.djangoproject.com/en/dev/ref/models/querysets/#id4) won't have any effect on the data you're using in this scenario as it only follows foreign-key relationships, but the pet-to-client relationship is many-to-one. **Update:** if you want to avoid having to change the logic in `Pet.full_name` or having to perform said logic in the template instead for this case, you could alter the way you get a handle on each Client's Pets in order to prefill the ForeignKey cache with for each Pet with its Client: ``` class Client(models.Model): # ... def get_pets(self): for pet in self.pets.all(): setattr(pet, '_client_cache', self) yield pet ``` ...where the `'client'` part of `'_client_cache'` is whatever attribute name is used in the Pet class for the ForeignKey to the Pet's Client. This takes advantage of the way Django implements access to ForeignKey-related objects using its `SingleRelatedObjectDescriptor` class, which looks for this cache attribute before querying the database. Resulting template usage: ``` {% for pet in client.get_pets %} ... {% endfor %} ```
Django uses a cache. The RDBMS uses a cache. Don't prematurely optimize the queries. You can play with bulk queries in your view function instead of one-at-a-time queries in your template. ``` @render_to('home/main.html') def login(request): # Query all clients clients = Client.objects.all() # Assemble an in-memory table of pets pets = collections.defaultdict(list) for p in Pet.objects.all(): pets[pet.client].append(p) # Create clients and pets tuples clientsPetTuples = [ (c,pets[c]) for c in clients ] return {'clientPets': clientsPetTuples} ``` However, you don't seem to have any evidence that your template is the slowest part of your application. Further, this trades off giant memory use against SQL use. Until you have measurements that prove that your template queries are actually slow, you shouldn't be over thinking the SQL. Don't worry about the SQL until you have evidence.
Django - queries made repeat/inefficient
[ "", "python", "django", "" ]
I wrote this simple test code, by adapting a piece from a book, to help me understand the working of generic methods in Java. The line that I marked is *supposed* to work, why isn't it? ``` import java.util.*; class Test { public static void main(String args[]){ List<Number> input = null; List<Number> output=null; output = Test.process(input); // fail, why?? } public static <E extends Number> List <? super E> process (List <E> nums){ List <E>eList = new ArrayList<E>(); return eList; } } ``` edit: Well, the code works when changing `List<? super E>` to `List<E>`, that's great, but I'm still not sure if I may have missed something or if the book I took this from may have a mistake. Please read the question as it appears there: 16. Given a method declared as: > public static < E extends Number > List > < ? super E > process (List nums) A programmer wants to use this method like this: ``` // INSERT DECLARATIONS HERE output = process(input); ``` Which pairs of declarations could be placed at // INSERT DECLARATIONS HERE to allow the code to compile? (Choose all that apply.) ``` A. ArrayList<Integer> input = null; ArrayList<Integer> output = null; B. ArrayList<Integer> input = null; List<Integer> output = null; C. ArrayList<Integer> input = null; List<Number> output = null; D. List<Number> input = null; ArrayList<Integer> output = null; E. List<Number> input = null; List<Number> output = null; F. List<Integer> input = null; List<Integer> output = null; G. None of the above. ``` Answer: B, E, and F are correct. The return type of process is definitely declared as a `List`, not an `ArrayList`, so A and D are wrong. C is wrong because the return type evaluates to `List<Integer>`, and that can't be assigned to a variable of type `List<Number>`. Of course all these would probably cause a `NullPointerException` since the variables are still null—but the question only asked us to get the code to compile. None of the options mentioned on the book have worked on my code. Can I safely mark it as a mistake on Kathy Sierra's part or am I missing something here?
The problem is that you are declaring the return type of your method as ``` List<? super E>, i.e. List<? super Number> ``` but assigning it to a ``` List<Number> ``` So you should either assign it to a ``` List<? super Number> ``` or declare the return type as ``` List<E> i.e. List<Number> ``` (Verbose formatting because inline code does not show generics correctly.) If the book claims assigning the return value of the method is possible in the way you describe it then indeed it seems to be a mistake in the book. It would be correct if the method returned a List of E (as above).
try: ``` import java.util.*; class Test { public static void main(String args[]){ List<Number> input = null; List<Number> output=null; output = Test.process(input); // fail, why?? } public static <E extends Number> List <E> process (List <E> nums){ List <E>eList = new ArrayList<E>(); return eList; } } ```
Generic Method Fail
[ "", "java", "generics", "" ]
Wondering if anyone knows of a set of T4 templates for generating C# POCO classes and also mapping XML files for NHibernate from a set of tables in a database. I saw that David Hayden has created T4 for generating FluentNH code based upon a DBML model, but I'm not quite ready to use FluentNH yet as there isn't even an official release yet (although I love the idea). Anyone know of any T4 templates for using plain NHibernate?
Follow-up: I decided to write my own code generator for NHibernate xml mapping file and POCO classes. I modeled it after the Linq to SQL generator in the T4 Toolbox project. I plan to post about the experience and provide a download on [my site](http://nathanwdavis.com/) as soon as I get the chance. Let me know if you're interested and I'll hurry it up.
May not be the answer you are looking for, but I spent a good amount of time a couple months ago looking everywhere for the same thing. I couldn't find any, though. Not sure if you're set on using T4 for any particular reason, but I ended up using CodeSmith for code generation because there are several templates already available. There are a handful for MyGeneration, but CodeSmith was much farther along. NOTE: If you do find some, though, you should post it here as I, and probably other people, would be rabidly interested in finding some well done T4 templates for nHibernate.
T4 template for NHibernate? - not Fluent NHibernate
[ "", "c#", ".net", "nhibernate", "t4", "" ]
I have an `XElement` and inside that element I have another XML fragment. How do I retrieve the XML? If I try the following, I get only the value: ``` string str = "<Root><Node1>value1</Node1><Node2></Node2></Root>"; XElement elem = XElement.Parse(str); string innerXml = elem.value; ```
Eric White just posted a blog article to do exactly that - convert XElement to XmlNode and back. Check it out [here](http://blogs.msdn.com/ericwhite/archive/2008/12/22/convert-xelement-to-xmlnode-and-convert-xmlnode-to-xelement.aspx). Marc
Try something like this: ``` var x = elem.Descendants(); ``` This will return you all the descendants of the root node - if you want a specific one you can pass its name as a string parameter to this same method. **Edit:** If you *really* need it as a string you can aggregate the nodes. Here is an extension method that will do the trick: ``` public static String InnerXml(this XElement source) { return source.Descendants().Select(x => x.ToString()).Aggregate(String.Concat); } ```
How can I get an XML fragment as a string from an XElement?
[ "", "c#", "xml", "linq", "" ]
I have a question. How can i invoke a web service and get the result from a C# desktop application. I am making a desktop app and I want it to be able to connect to my online ASP.net web services. How is this possible?
1. In Solution Explorer, right-click your project node and select Add **Service** Reference. 2. Enter the URL where your service WSDL is located. This is usually the URL of the service itself. 3. This generates a strongly-typed proxy class in a new Services References folder in your project. 4. Write code in your desktop app to instantiate the proxy class and invoke methods on it. The rest works like magic. :) AB Kolan was also correct, but Add **Web** Reference uses the old-style web services framework whereas Add **Service** References uses the new WCF stack. Important note: It is **not** required that the service itself use WCF for you to use WCF on the client side. WCF on the client is typically the best choice for any service, provided you can take a dependency on .NET 3.0 and above.
Add a Web Reference to the webservice in your Desktop App project reference. Doing so would generate a Proxy for the Webservice called Reference.cs You can access your webservice using the proxy.
Calling ASP.net Web Service from C# Application
[ "", "c#", "asp.net", "web-services", "desktop", "invoke", "" ]
I can't seem to get inline Javascript indenting properly in Vim. Consider the following: ``` $(document).ready(function() { // Closing brace correctly indented $("input").focus(function() { $(this).closest("li").addClass("cur-focus"); }); // <-- I had to manually unindent this // Closing brace incorrectly indented $("input").blur(function() { $(this).closest("li").removeClass("cur-focus"); }); // <-- This is what it does by default. Argh! }); ``` Vim seems to insist on automatically indenting the closing brace shown in the second case there. It does the same if I re-indent the whole file. How do I get it to automatically indent using the more standard JS indenting style seen in the first case?
Use [JavaScript Indent: Javascript indenter (HTML indent is included)](http://www.vim.org/scripts/script.php?script_id=3081) by Preston Koprivica. Thanks for the heads-up from [oligofren](https://stackoverflow.com/questions/620247/how-do-i-fix-incorrect-inline-javascript-indentation-in-vim/4183349#4183349) - give him an up-vote.
The most comprehensive and bug-free Javascript indentation script is [the one by Preston Koprivica](http://www.vim.org/scripts/script.php?script_id=3081). The so called OOP script that is in the proposed answer has severe bugs, and does not indent code properly that has square brackets.
How do I fix incorrect inline Javascript indentation in Vim?
[ "", "javascript", "vim", "" ]
I have a solution that contains several c# projects and I would like to be able to set the output path and other properties on all the projects together in a single place. Property Sheets (vsprops) do not seem to be able available for C# projects and the $(SolutionDir) variable is ignored. Are there any other methods to set properties across several C# projects? **Update** By Following the information in the answer by Bas Bossink I was able to set the output path of several projects by creating a common csproj and importing it into the individual project. A few other points: * When building in Visual Studio if changes are made to the common project it is necessary to touch/reload any projects that reference it for the changes to be picked up. * Any properties which are also set in a individual project will override the common properties. * Setting $(SolutionDir) as the output path via the Visual Studio UI does not work as expected because the value is treated as a string literal rather than getting expanded. However, Setting $(SolutionDir) directly into the csproj file with a text editor works as expected.
A csproj file is already an msbuild file, this means that csproj files can also use an import element as described [here](http://msdn.microsoft.com/en-us/library/92x05xfs.aspx). The import element is exactly what you require. You could create a Common.proj that contains something like: ``` <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5"xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <OutputPath>$(SolutionDir)output</OutputPath> <WarningLevel>4</WarningLevel> <UseVSHostingProcess>false</UseVSHostingProcess> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> </PropertyGroup> </Project> ``` You can import this Common.proj in each of your csprojs, for instance like so: ``` <Import Project="..\Common.proj" /> ``` The import statement should precede any tasks that depend on the properties defined in Common.proj I hope this helps. I can't confirm your problems with the $(SolutionDir) variable I've used it many times. I do know however that this variable does not get set when you run an msbuild command via the commandline on a specific project that is contained in a solution. It will be set when you build your solution in Visual Studio.
Unfortunately, these bits of information such as output path are all stored inside the individual \*.csproj files. If you want to batch-update a whole bunch of those, you'll have to revert to some kind of a text-updating tool or create a script to touch each of those files. For things like this (apply changes to a bunch of text files at once) I personally use [WildEdit](http://www.textpad.com/products/wildedit/index.html) by Helios Software - works like a charm and it's reasonably priced. But I'm sure there are tons of free alternatives out there, too.
How to set the output path of several visual C# projects
[ "", "c#", "visual-studio", "" ]
I use an extension method to convert float arrays into byte arrays: ``` public static unsafe byte[] ToByteArray(this float[] floatArray, int count) { int arrayLength = floatArray.Length > count ? count : floatArray.Length; byte[] byteArray = new byte[4 * arrayLength]; fixed (float* floatPointer = floatArray) { fixed (byte* bytePointer = byteArray) { float* read = floatPointer; float* write = (float*)bytePointer; for (int i = 0; i < arrayLength; i++) { *write++ = *read++; } } } return byteArray; } ``` I understand that an array is a pointer to memory associated with information on the type and number of elements. Also, it seems to me that there is no way of doing a conversion from and to a byte array without copying the data as above. Have I understood this? Would it even be impossible to write IL to create an array from a pointer, type and length without copying data? **EDIT:** Thanks for the answers, I learned some fundamentals and got to try out new tricks! After initially accepting Davy Landman's answer I found out that while his brilliant StructLayout hack does convert byte arrays into float arrays, it does not work the other way around. To demonstrate: ``` [StructLayout(LayoutKind.Explicit)] struct UnionArray { [FieldOffset(0)] public Byte[] Bytes; [FieldOffset(0)] public float[] Floats; } static void Main(string[] args) { // From bytes to floats - works byte[] bytes = { 0, 1, 2, 4, 8, 16, 32, 64 }; UnionArray arry = new UnionArray { Bytes = bytes }; for (int i = 0; i < arry.Bytes.Length / 4; i++) Console.WriteLine(arry.Floats[i]); // From floats to bytes - index out of range float[] floats = { 0.1f, 0.2f, 0.3f }; arry = new UnionArray { Floats = floats }; for (int i = 0; i < arry.Floats.Length * 4; i++) Console.WriteLine(arry.Bytes[i]); } ``` It seems that the CLR sees both arrays as having the same length. If the struct is created from float data, the byte array's length is just too short.
Yes, the type information and data is in the same memory block, so that is impossible unless you overwrite the type information in a float array to fool the system that it's byte array. That would be a really ugly hack, and could easily blow up... Here's how you can convert the floats without unsafe code if you like: ``` public static byte[] ToByteArray(this float[] floatArray) { int len = floatArray.Length * 4; byte[] byteArray = new byte[len]; int pos = 0; foreach (float f in floatArray) { byte[] data = BitConverter.GetBytes(f); Array.Copy(data, 0, byteArray, pos, 4); pos += 4; } return byteArray; } ```
You can use a really ugly hack to temporary change your array to byte[] using memory manipulation. This is really fast and efficient as it doesn't require cloning the data and iterating on it. I tested this hack in both 32 & 64 bit OS, so it should be portable. The source + sample usage is maintained at <https://gist.github.com/1050703> , but for your convenience I'll paste it here as well: ``` public static unsafe class FastArraySerializer { [StructLayout(LayoutKind.Explicit)] private struct Union { [FieldOffset(0)] public byte[] bytes; [FieldOffset(0)] public float[] floats; } [StructLayout(LayoutKind.Sequential, Pack = 1)] private struct ArrayHeader { public UIntPtr type; public UIntPtr length; } private static readonly UIntPtr BYTE_ARRAY_TYPE; private static readonly UIntPtr FLOAT_ARRAY_TYPE; static FastArraySerializer() { fixed (void* pBytes = new byte[1]) fixed (void* pFloats = new float[1]) { BYTE_ARRAY_TYPE = getHeader(pBytes)->type; FLOAT_ARRAY_TYPE = getHeader(pFloats)->type; } } public static void AsByteArray(this float[] floats, Action<byte[]> action) { if (floats.handleNullOrEmptyArray(action)) return; var union = new Union {floats = floats}; union.floats.toByteArray(); try { action(union.bytes); } finally { union.bytes.toFloatArray(); } } public static void AsFloatArray(this byte[] bytes, Action<float[]> action) { if (bytes.handleNullOrEmptyArray(action)) return; var union = new Union {bytes = bytes}; union.bytes.toFloatArray(); try { action(union.floats); } finally { union.floats.toByteArray(); } } public static bool handleNullOrEmptyArray<TSrc,TDst>(this TSrc[] array, Action<TDst[]> action) { if (array == null) { action(null); return true; } if (array.Length == 0) { action(new TDst[0]); return true; } return false; } private static ArrayHeader* getHeader(void* pBytes) { return (ArrayHeader*)pBytes - 1; } private static void toFloatArray(this byte[] bytes) { fixed (void* pArray = bytes) { var pHeader = getHeader(pArray); pHeader->type = FLOAT_ARRAY_TYPE; pHeader->length = (UIntPtr)(bytes.Length / sizeof(float)); } } private static void toByteArray(this float[] floats) { fixed(void* pArray = floats) { var pHeader = getHeader(pArray); pHeader->type = BYTE_ARRAY_TYPE; pHeader->length = (UIntPtr)(floats.Length * sizeof(float)); } } } ``` And the usage is: ``` var floats = new float[] {0, 1, 0, 1}; floats.AsByteArray(bytes => { foreach (var b in bytes) { Console.WriteLine(b); } }); ```
C# unsafe value type array to byte array conversions
[ "", "c#", "arrays", "pointers", "type-conversion", "unsafe", "" ]
I just came to know that there are *data* breakpoints. I have worked for the last 5 years in C++ using Visual Studio, and I have never used data breakpoints. Can someone throw some light on what data breakpoints are, when to use them and *how* to use them with VS? As per my understanding we can set a data breakpoint when we want to check for changes to a variable's value. In this case, we can set a data breakpoint with a condition on the variable value. Any other examples?
Definition: > Data breakpoints allow you to break > execution when the value stored at a > specified memory location changes. From MSDN: [How to: Set a Data Breakpoint](https://msdn.microsoft.com/en-us/library/350dyxd0(v=vs.100).aspx): **How to Set a Memory Change Breakpoint** 1. From the Debug Menu, choose New Breakpoint and click New Data Breakpoint —or— in the Breakpoints window Menu, click the New dropdown and choose New Data Breakpoint. The New Breakpoint dialog box appears. 2. In the Address box, enter a memory address or expression that evaluates to a memory address. For example, &foo to break when the contents of variable foo change. 3. In the Byte Count box, enter the number of bytes you want the debugger to watch. For example, if you enter 4, the debugger will watch the four bytes starting at &foo and break if any of those bytes change value. 4. Click OK.
Good ol' [Daniel LeCheminant has a solid answer](https://stackoverflow.com/questions/621535/what-are-data-breakpoints/621537#621537) on *what* a data breakpoint does, so i'll toss in some anecdotes that highlight useful uses: Any scenario where you know *what* will change, but have little or no idea *where* the code changing it lives (since otherwise you could simply use a conditional breakpoint). Specifically, **"Impossible" scenarios** - program is crashing, because variable `X` is `NULL`, when variable `X` should never be `NULL` because no code anywhere ever sets variable `X` to `NULL`. Put a normal breakpoint in the code that initializes `X`, and when it is hit, set up a data breakpoint to watch for the change to `NULL`. Somewhat more common is the case where memory is released *too early*, and there are still pointers to it hanging around: use data breakpoints to find out who's releasing the memory. **Tedious scenarios** - a 3rd-party library is doing bad, nasty, horrible things to your data structures. You know it's happening, because *someone* is trashing your data and obviously your code is perfect. But you don't know where, or when. Sure, you could single-step through a megabyte of disassembled DLL... but why bother, when you can set a data breakpoint on your data, sit back, and wait for it to get trashed! **Heisenbugs** - similar to the impossible scenario, but they go away when you watch too closely, such that normal breakpoints - even conditional breakpoints - are useless. Timing and user-input sensitive logic is particularly vulnerable to this sort of thing. Since data breakpoints don't require the debugger to actually break at all until *the time is right*, assuming you can come up with a memory location that will only change when that elusive bug actually occurs you can use data breakpoints to set a trap for the Heisenbug and catch it *in flagrante delicto*. **Spaghetti scenarios** - common in old, rotten code bases where global data is accessed *everywhere*. Yeah, you could use plain ol' conditional breakpoints... but you'd need hundreds of them. Data breakpoints make it easy.
What are data breakpoints?
[ "", "c++", "visual-studio", "debugging", "breakpoints", "conditional-breakpoint", "" ]
Having some problems figuring out the regex to match this: ``` function Array() { [native code] } ``` I'm trying to only match the text that will occur where "Array" is.
Are you trying to find out what type a variable is in javascript? If that's what want you can just compare the object's constructor to the constructor that you think created it: ``` var array = new Array(); if(array.constructor == Array) alert("Is an array"); else alert("isn't an array"); ``` This isn't really the best way to go about things in javascript. Javascript doesn't have a type system like C# does that guarantees you that a variable will have certain members if it's created by a certain constructor because javascript is a pretty dynamic languages and anything that an object gets from its constructor can be overwritten at runtime. Instead it's really better to use duck typing and ask your objects what they can do rather than what they are: <http://en.wikipedia.org/wiki/Duck_typing> ``` if(typeof(array.push) != "undefined") { // do something with length alert("can push items onto variable"); } ```
In Perl, you'd use: ``` m/^\s*function\s+(\w+)\s*\(/; ``` The variable '`$1`' would capture the function name. If the `function` keyword might not be at the start of the line, then you have to work (a little) harder. [Edit: two '`\s*`' sequences added.] --- Question about whether this works...here's my test case: Test script: ``` while (<>) { print "$1\n" if (m/^\s*function\s+(\w+)\s*\(/); } ``` Test input lines (yes, deliberately misaligned): ``` function Array() { ... } function Array2 () { ... } func Array(22) { ... } ``` Test output: ``` Array Array2 ``` Tested with Perl 5.10.0 on Solaris 10 (SPARC): I don't believe the platform or version is a significant factor - I'd expect it to work the same on any plausible version of Perl.
Regex: problem creating matching pattern
[ "", "javascript", "regex", "" ]
I'm working on a site that will send out a significant number of emails. I want to set up both header and footer text, or maybe even templates to allow the users to easily edit these emails if they need to. If I embed the HTML inside C# string literals, it's ugly and they would have to worry about escaping. Including flat files for the header and footer might work, but something about it just doesn't feel right. What would be ideal what be to use a `.ASPX` page as a template somehow, then just tell my code to serve that page, and use the HTML returned for the email. Is there a nice and easy way to do this? Is there a better way to go about solving this problem? **Updated:** I added an answer that enables you to use a standard .aspx page as the email template. Just replace all the variables like you normally would, use databinding, etc. Then just capture the output of the page, and voila! You have your HTML email! **UPDATED WITH CAVEAT!!!:** I was using the MailDefinition class on some aspx pages just fine, but when trying to use this class during a server process that was running, it failed. I believe it was because the MailDefinition.CreateMailMessage() method requires a valid control to reference, even though it doesn't always do something. Because of this, I would recommend my approach using an aspx page, or Mun's approach using an ascx page, which seems a little better.
There's a ton of answers already here, but I stumbled upon a great article about how to use Razor with email templating. Razor was pushed with ASP.NET MVC 3, but MVC is not required to use Razor. This is pretty slick processing of doing email templates As the article identifies, "The best thing of Razor is that unlike its predecessor(webforms) it is not tied with the web environment, we can easily host it outside the web and use it as template engine for various purpose. " [Generating HTML emails with RazorEngine - Part 01 - Introduction](http://mehdi.me/generating-html-emails-with-razorengine-introduction/) [Leveraging Razor Templates Outside of ASP.NET: They’re Not Just for HTML Anymore!](http://www.codemag.com/Article/1103081) [Smarter email templates in ASP.NET with RazorEngine](http://blog.falafel.com/smarter-email-templates-in-asp-net-with-razorengine/) **Similar Stackoverflow QA** [Templating using new RazorEngine API](https://stackoverflow.com/q/28606132/92166) [Using Razor without MVC](https://stackoverflow.com/questions/4808348/using-razor-without-mvc) [Is it possible to use Razor View Engine outside asp.net](https://stackoverflow.com/questions/3628895/is-it-possible-to-use-razor-view-engine-outside-asp-net)
You might also want to try loading a control, and then rendering it to a string and setting that as the HTML Body: ``` // Declare stringbuilder to render control to StringBuilder sb = new StringBuilder(); // Load the control UserControl ctrl = (UserControl) LoadControl("~/Controls/UserControl.ascx"); // Do stuff with ctrl here // Render the control into the stringbuilder StringWriter sw = new StringWriter(sb); Html32TextWriter htw = new Html32TextWriter(sw); ctrl.RenderControl(htw); // Get full body text string body = sb.ToString(); ``` You could then construct your email as usual: ``` MailMessage message = new MailMessage(); message.From = new MailAddress("from@email.com", "from name"); message.Subject = "Email Subject"; message.Body = body; message.BodyEncoding = Encoding.ASCII; message.IsBodyHtml = true; SmtpClient smtp = new SmtpClient("server"); smtp.Send(message); ``` You user control could contain other controls, such as a header and footer, and also take advantage of functionality such as data binding.
Can I set up HTML/Email Templates with ASP.NET?
[ "", "c#", "asp.net", "email", "templates", "" ]
...where each object also has references to other objects within the same array? When I first came up with this problem I just thought of something like ``` var clonedNodesArray = nodesArray.clone() ``` would exist and searched for information on how to clone objects in JavaScript. I did find [a question](https://stackoverflow.com/questions/122102/what-is-the-most-efficent-way-to-clone-a-javascript-object) on Stack Overflow (answered by the very same @JohnResig) and he pointed out that with jQuery you could do ``` var clonedNodesArray = jQuery.extend({}, nodesArray); ``` to clone an object. I tried this though, and this only copies the references of the objects in the array. So if I ``` nodesArray[0].value = "red" clonedNodesArray[0].value = "green" ``` the value of both nodesArray[0] and clonedNodesArray[0] will turn out to be "green". Then I tried ``` var clonedNodesArray = jQuery.extend(true, {}, nodesArray); ``` which deep copies an Object, but I got "*too much recursion*" and "*control stack overflow*" messages from both [Firebug](https://en.wikipedia.org/wiki/Firebug_%28software%29) and [Opera Dragonfly](https://en.wikipedia.org/wiki/Opera_Dragonfly) respectively. How would you do it? Is this something that shouldn't even be done? Is there a reusable way of doing this in JavaScript?
### Creating a deep copy with `structuredClone` The modern way to deep copy an array in JavaScript is to use [structuredClone](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone): ``` array2 = structuredClone(array1); ``` This function is relatively new (Chrome 98, Firefox 94) and is [currently available](https://caniuse.com/?search=structuredClone) to about 95% of users, so may not ready for production without a polyfill. As an alternative, you can use one of the well-supported JSON-based solutions below. ### Creating a deep copy with `JSON.parse` A general solution, that accounts for all possible objects inside an Array of objects may not be possible. That said, if your array contains objects that have JSON-serializable content (no functions, no `Number.POSITIVE_INFINITY`, etc.) one simple way to avoid loops, at a performance cost, is this pure vanilla one-line solution. ``` let clonedArray = JSON.parse(JSON.stringify(nodesArray)) ``` To summarize the comments below, the primary advantage of this approach is that it also clones the contents of the array, not just the array itself. The primary downsides are its limit of only working on JSON-serializable content, and it's performance is ~30 times slower than the spread method. If you have shallow objects in the array, and IE6 is acceptable, a better approach is to use the spread operator combined with the .map array operator. For a two levels deep situation (like the array in the Appendix below): ``` clonedArray = nodesArray.map(a => {return {...a}}) ``` The reasons are two fold: 1) It is much, much faster (see below for a benchmark comparison) and it will also allow any valid object in your array. \*Appendix: The performance quantification is based on cloning this array of objects a million times: ``` [{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic1.jpg?raw=true', id: '1', isFavorite: false}, {url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic2.jpg?raw=true', id: '2', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic3.jpg?raw=true', id: '3', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic4.jpg?raw=true', id: '4', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic5.jpg?raw=true', id: '5', isFavorite: true},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic6.jpg?raw=true', id: '6', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic7.jpg?raw=true', id: '7', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic8.jpg?raw=true', id: '8', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic9.jpg?raw=true', id: '9', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic10.jpg?raw=true', id: '10', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic11.jpg?raw=true', id: '11', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic12.jpg?raw=true', id: '12', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic13.jpg?raw=true', id: '13', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic14.jpg?raw=true', id: '14', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic15.jpg?raw=true', id: '15', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic16.jpg?raw=true', id: '16', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic17.jpg?raw=true', id: '17', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic18.jpg?raw=true', id: '18', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic19.jpg?raw=true', id: '19', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic20.jpg?raw=true', id: '20', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic21.jpg?raw=true', id: '21', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic22.jpg?raw=true', id: '22', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic23.jpg?raw=true', id: '23', isFavorite: false}] ``` either using: ``` let clonedArray = JSON.parse(JSON.stringify(nodesArray)) ``` or: ``` clonedArray = nodesArray.map(a => {return {...a}}) ``` The map/spread approach took 0.000466 ms per pass and the `JSON.parse` and `JSON.stringify` 0.014771 ms per pass.\*
I solved cloning of an array of objects with [Object.assign](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) ``` const newArray = myArray.map(a => Object.assign({}, a)); ``` or even shorter with [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator) ``` const newArray = myArray.map(a => ({...a})); ```
How do you clone an array of objects in JavaScript?
[ "", "javascript", "" ]
Is it possible to obtain class summary at runtime in C#? I would like to obtain class summary through reflection and then write it to console. By class summary I mean summary comments before class definition, something like this: ``` /// <summary> /// some description /// </summary> class SomeClass { } ``` I don't know if these comments are available after compiling the code, but if they are maybe there is a way to obtain them in code. Thanks in advance for help.
I once messed with this a while back, and used this guys solution. Worked pretty good: <http://jimblackler.net/blog/?p=49>
I maintain the [Jolt.NET](http://jolt.codeplex.com) project on CodePlex and have implemented a feature that performs this very task. Please refer to the [Jolt](http://jolt.codeplex.com/Wiki/View.aspx?title=Jolt) library for more information. In essence, the library allows you to programatically locate and query an XML doc comments file for an assembly using the metadata types in `System.Reflection` (i.e. `MethodInfo`, `PropertyInfo`, etc...).
Is it possible to obtain class summary at runtime?
[ "", "c#", "reflection", "class", "comments", "summary", "" ]
I have a script that sends out emails every minute. When it starts its loop, it queries the database for all entries that are equal to the current utc time. I would like to have it find all entries in the database that correspond to the current time down to the minute. So there is a 'time' column that stores the utc time: '2009-03-06 20:18:31'. When it searches is there any way to ignore the seconds attribute with out changing how I store the time? EDIT: I'm using mysql server. Thanks!
this was the actual sql statement that I used. Notice that it was heavy influenced by Quassnoi's response but there are some key differences. I used the UTC\_TIMESTAMP instead of NOW(). ``` select * from table where time < UTC_TIMESTAMP() + INTERVAL(1) MINUTE - INTERVAL (EXTRACT(SECOND FROM UTC_TIMESTAMP())) SECOND and time >= UTC_TIMESTAMP() - INTERVAL (EXTRACT(SECOND FROM UTC_TIMESTAMP())) SECOND; ```
In **MySQL**: ``` SELECT * FROM table WHERE time >= NOW() - INTERVAL EXTRACT(SECOND FROM NOW()) SECOND AND time < NOW() - INTERVAL (EXTRACT(SECOND FROM NOW()) + 60) SECOND ``` This will efficiently use an index on `time` field.
Select all rows that correspond to a time
[ "", "sql", "mysql", "" ]
How can I check the language of user's browser by PHP? I need to show a different page for people in US and in UK. I tried the following code unsuccessfully ``` <?php if(ereg("us", $_SERVER["HTTP_ACCEPT_LANGUAGE"])) include('http://page.com/us.txt'); else include('http://page.com/uk.txt'); ?> ``` I run a specific code for people in US and for them in UK.
Likely just a case sensitivity issue; eregi('en-us') or preg\_match('/en-us/i') should have picked it up. However, just looking for ‘en-us’ in the header may get it wrong sometimes, in particular when both the US and UK languages are listed. “Accept-Language” is actually quite a complicated header, which really you'd want a proper parser for. If you have PECL the whole job is already done for you: <http://www.php.net/manual/en/function.http-negotiate-language.php> I don't know why the other answers are going for the User-Agent header; this is utterly bogus. User-Agent is not mandated to hold a language value in any particular place, and for some browsers (eg. Opera, and some minor browser I've never heard of called ‘Internet Explorer’) it will not at all. Where it *does* contain a language, that'll be the of language the browser build was installed in, not the user's preferred language which is what you should be looking at. (This setting will default to the build language, but can be customised by the user from the preferences UI.)
Try this: ``` <? if(preg_match('/en-us/i', $_SERVER['HTTP_USER_AGENT'])) include('http://page.com/us.txt'); else include('http://page.com/uk.txt'); ?> ```
Checking browser's language by PHP?
[ "", "php", "browser", "" ]
Okay, I'm aware that the standard dictates that a C++ implementation may choose in which order arguments of a function are evaluated, but are there any implementations that actually 'take advantage' of this in a scenario where it would actually affect the program? Classic Example: ``` int i = 0; foo(i++, i++); ``` Note: I'm not looking for someone to tell me that the order of evaluation can't be relied on, I'm well aware of that. I'm only interested in whether any compilers actually do evaluate out of a left-to-right order because my guess would be that if they did lots of poorly written code would break (rightly so, but they would still probably complain).
It depends on the argument type, the called function's calling convention, the archtecture and the compiler. On an x86, the [Pascal](http://en.wikipedia.org/wiki/X86_calling_conventions#pascal) calling convention evaluates arguments left to right whereas in the C calling convention ([\_\_cdecl](http://msdn.microsoft.com/en-us/library/zkwh89ks(VS.80).aspx)) it is right to left. Most programs which run on multiple platforms do take into account the calling conventions to skip surprises. There is a nice [article](http://blogs.msdn.com/oldnewthing/archive/2004/01/08/48616.aspx) on Raymond Chen' blog if you are interested. You may also want to take a look at the [Stack and Calling](http://gcc.gnu.org/onlinedocs/gccint/Stack-and-Calling.html) section of the GCC manual. **Edit:** So long as we are splitting hairs: My answer treats this not as a language question but as a platform one. The language standard does not gurantee or prefer one over the other and leaves it as **unspecified**. Note the wording. It does not say this is undefined. Unspecified in this sense means something you cannot count on, non-portable behavior. I don't have the C spec/draft handy but it should be similar to that from my n2798 draft (C++) > Certain other aspects and operations of the abstract machine are described in this International Standard as unspecified (for example, order of evaluation of arguments to a function). Where possible, this International Standard defines a set of allowable behaviors. These define the nondeterministic aspects of the abstract machine. An instance of the abstract machine can thus have more than one possible execution sequence for a given program and a given input.
I found answer in [c++ standards](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf). Paragraph 5.2.2.8: > The order of evaluation of arguments is unspecified. All side effects of argument expression evaluations take effect before the function is entered. The order of evaluation of the postfix expression and the argument expression list is > unspecified. In other words, It depends on compiler only.
Do compilers take advantage of the indeterminate sequencing of function arguments?
[ "", "c++", "compiler-optimization", "operator-precedence", "order-of-execution", "" ]
I have created a class file in the App\_Code folder in my application. I have a session variable ``` Session["loginId"] ``` I want to access this session variables in my class, but when I am writing the following line then it gives error ``` Session["loginId"] ``` Can anyone tell me how to access session variables within a class which is created in app\_code folder in ASP.NET 2.0 (C#)
(Updated for completeness) You can access session variables from any page or control using `Session["loginId"]` and from any class (e.g. from inside a class library), using `System.Web.HttpContext.Current.Session["loginId"].` But please read on for my original answer... --- I always use a wrapper class around the ASP.NET session to simplify access to session variables: ``` public class MySession { // private constructor private MySession() { Property1 = "default value"; } // Gets the current session. public static MySession Current { get { MySession session = (MySession)HttpContext.Current.Session["__MySession__"]; if (session == null) { session = new MySession(); HttpContext.Current.Session["__MySession__"] = session; } return session; } } // **** add your session properties here, e.g like this: public string Property1 { get; set; } public DateTime MyDate { get; set; } public int LoginId { get; set; } } ``` This class stores one instance of itself in the ASP.NET session and allows you to access your session properties in a type-safe way from any class, e.g like this: ``` int loginId = MySession.Current.LoginId; string property1 = MySession.Current.Property1; MySession.Current.Property1 = newValue; DateTime myDate = MySession.Current.MyDate; MySession.Current.MyDate = DateTime.Now; ``` This approach has several advantages: * it saves you from a lot of type-casting * you don't have to use hard-coded session keys throughout your application (e.g. Session["loginId"] * you can document your session items by adding XML doc comments on the properties of MySession * you can initialize your session variables with default values (e.g. assuring they are not null)
Access the Session via the thread's HttpContext:- ``` HttpContext.Current.Session["loginId"] ```
How to access session variables from any class in ASP.NET?
[ "", "c#", "asp.net", "session-variables", "" ]
Is there a clipboard changed or updated event that i can access through C#?
I think you'll have to use some p/invoke: ``` [DllImport("User32.dll", CharSet=CharSet.Auto)] public static extern IntPtr SetClipboardViewer(IntPtr hWndNewViewer); ``` See [this article on how to set up a clipboard monitor in c#](https://web.archive.org/web/20131104125500/http://www.radsoftware.com.au/articles/clipboardmonitor.aspx) Basically you register your app as a clipboard viewer using ``` _ClipboardViewerNext = SetClipboardViewer(this.Handle); ``` and then you will recieve the `WM_DRAWCLIPBOARD` message, which you can handle by overriding `WndProc`: ``` protected override void WndProc(ref Message m) { switch ((Win32.Msgs)m.Msg) { case Win32.Msgs.WM_DRAWCLIPBOARD: // Handle clipboard changed break; // ... } } ``` (There's more to be done; passing things along the clipboard chain and unregistering your view, but you can get that from [the article](https://web.archive.org/web/20131104125500/http://www.radsoftware.com.au/articles/clipboardmonitor.aspx))
For completeness, here's the control I'm using in production code. Just drag from the designer and double click to create the event handler. ``` using System; using System.ComponentModel; using System.Runtime.InteropServices; using System.Windows.Forms; using System.Drawing; namespace ClipboardAssist { // Must inherit Control, not Component, in order to have Handle [DefaultEvent("ClipboardChanged")] public partial class ClipboardMonitor : Control { IntPtr nextClipboardViewer; public ClipboardMonitor() { this.BackColor = Color.Red; this.Visible = false; nextClipboardViewer = (IntPtr)SetClipboardViewer((int)this.Handle); } /// <summary> /// Clipboard contents changed. /// </summary> public event EventHandler<ClipboardChangedEventArgs> ClipboardChanged; protected override void Dispose(bool disposing) { ChangeClipboardChain(this.Handle, nextClipboardViewer); } [DllImport("User32.dll")] protected static extern int SetClipboardViewer(int hWndNewViewer); [DllImport("User32.dll", CharSet = CharSet.Auto)] public static extern bool ChangeClipboardChain(IntPtr hWndRemove, IntPtr hWndNewNext); [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam); protected override void WndProc(ref System.Windows.Forms.Message m) { // defined in winuser.h const int WM_DRAWCLIPBOARD = 0x308; const int WM_CHANGECBCHAIN = 0x030D; switch (m.Msg) { case WM_DRAWCLIPBOARD: OnClipboardChanged(); SendMessage(nextClipboardViewer, m.Msg, m.WParam, m.LParam); break; case WM_CHANGECBCHAIN: if (m.WParam == nextClipboardViewer) nextClipboardViewer = m.LParam; else SendMessage(nextClipboardViewer, m.Msg, m.WParam, m.LParam); break; default: base.WndProc(ref m); break; } } void OnClipboardChanged() { try { IDataObject iData = Clipboard.GetDataObject(); if (ClipboardChanged != null) { ClipboardChanged(this, new ClipboardChangedEventArgs(iData)); } } catch (Exception e) { // Swallow or pop-up, not sure // Trace.Write(e.ToString()); MessageBox.Show(e.ToString()); } } } public class ClipboardChangedEventArgs : EventArgs { public readonly IDataObject DataObject; public ClipboardChangedEventArgs(IDataObject dataObject) { DataObject = dataObject; } } } ```
How do I monitor clipboard changes in C#?
[ "", "c#", "events", "clipboard", "" ]
I'm using the [`datetime`](https://docs.python.org/3/library/datetime.html) module, i.e.: ``` >>> import datetime >>> today = datetime.datetime.now() >>> print(today) 2009-03-06 13:24:58.857946 ``` and I would like to compute the day of year that takes leap years into account. e.g. today (March 6, 2009) is the 65th day of 2009. I see a two options: 1. Create a `number_of_days_in_month = [31, 28, ...]` array, decide if it's a leap year and manually sum up the days. 2. Use `datetime.timedelta` to make a guess & then binary search for the correct day of the year: ``` >>> import datetime >>> YEAR = 2009 >>> DAY_OF_YEAR = 62 >>> d = datetime.date(YEAR, 1, 1) + datetime.timedelta(DAY_OF_YEAR - 1) ``` These both feel pretty clunky & I have a gut feeling that there's a more "Pythonic" way of calculating the day of the year. Any ideas/suggestions?
Use [`datetime.timetuple()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.timetuple) to convert your `datetime` object to a [`time.struct_time`](https://docs.python.org/3/library/time.html#time.struct_time) object then get its [`tm_yday`](https://docs.python.org/3/library/time.html#time.struct_time) property: ``` from datetime import datetime day_of_year = datetime.now().timetuple().tm_yday # returns 1 for January 1st ```
You could use [`strftime`](https://docs.python.org/3/library/datetime.html#datetime.datetime.strftime) with a [`%j` format string](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes): ``` >>> import datetime >>> today = datetime.datetime.now() >>> today.strftime('%j') '065' ``` but if you wish to do comparisons or calculations with this number, you would have to convert it to `int()` because `strftime()` returns a string. If that is the case, you are better off using [DzinX's](https://stackoverflow.com/questions/620305/convert-year-month-day-to-day-of-year-in-python/623312#623312) answer.
Convert Year/Month/Day to Day of Year in Python
[ "", "python", "datetime", "" ]
I'm looking for something that may or may not exist. Is there such a thing as an 'English grammar rules engine' available on the Windows platform (specifically for something like .NET or C#)? Specifically, **I'm looking for something that would be able to take a sentence in the 'future tense' and change it to the 'past tense' (based on English grammar rules)** ... like: *Work on widget software and then meet with Ricardo* to this: *Worked on widget software and then met with Ricardo* **Is there a rules engine that does that already?**
Talk to [this guy](http://web.mit.edu/linguistics/people/faculty/chomsky/index.html), he might have some ideas for you. In general, English is too ambiguous for this type of thing. For example: > Cut paper in half. Is this an imperative command, or a past-tense sentence fragment? And my personal favourite: > Time flies like an arrow; fruit flies like a banana. Any human can parse that, but only because of a great deal of semantic knowledge. That being said, there are some things that might be worth looking into, like [SharpNLP](http://www.codeplex.com/sharpnlp)
As others have stated, this is a very hard problem and has not been solved in the general case. However, there are some systems that do pretty well. Princeton's [WordNet](http://wordnet.princeton.edu/) is one of them. It can identify parts of speech, synonyms, etc (perhaps including tense) with some degree of accuracy. I think you may be interested in [these functions](http://wordnet.princeton.edu/wordnet/man/morph.3WN.html), which appear to find the root of a word given a particular conjugation and may also be able to find a particular conjugation given the root (but that page doesn't provide examples, so I can't be sure I'm interpreting the docs correctly).
C#: Grammar rules engine for English?
[ "", "c#", "rule-engine", "" ]
I have this loaded before the radio buttons with corresponding color variable: ``` <script type="text/javascript"> //<![CDATA[ images = {"Black":"http:\/\/ecx.images-amazon.com\/images\/I\/31XwBA2m8pL.jpg", "Slate":"http:\/\/ecx.images-amazon.com\/images\/I\/31SqWkrSb6L.jpg", "White":"http:\/\/ecx.images-amazon.com\/images\/I\/31OJufgJT2L.jpg"}; //]]> </script> ``` Here is the jQuery function. The best I can do so far is make the first image disappear, leaving the `alt` attribute. ``` function change_large_product_image(url) { jQuery('.largeprod img').attr('src', url); return false; } ``` Here is a sample source for the radio button. ``` <label for="Black" style="background: #fff url(http://ecx.images-amazon.com/images/I/11TeKFAzJsL._SL30_.jpg) center center no-repeat;" title="Black" > Black </label> <input id="color_black" name="color" onclick="change_large_product_image(images['Black'])" type="radio" value="Black" /> ```
What is the value of the parameter, `url`? It looks like you may need to decode the URL string to remove the '\' characters. ``` function change_large_product_image(url) { jQuery('.largeprod img').attr('src', decodeURI(url)); return false; } ``` In addition, consider taking thaBadDawg's suggestion.
The easier way to solve the problem is not to try and change the src, but empty the container and put a new img in its place. For example. ``` <div class"largeprod"><img src="...old..." /></div> ``` And using jQuery to clear it out and reload it ``` $('.largeprod').empty().append('<img src="...new..."/>'); ``` If you want to get really clever with it you can "preload" the image in a non-displayed div, then clone and drop it in where you want to. I use a system where I put images (and large pieces of content) into that hidden div, save it's id and where it is going into an array and then when the image finishes loading, the onload event triggers and the moves it to where it is supposed to go.
How to pass a JSON URL to a jQuery function?
[ "", "javascript", "jquery", "json", "" ]
What would be the best way to implement a most-recently-used cache of objects? Here are the requirements and restrictions... * Objects are stored as key/value Object/Object pairs, so the interface would be a bit like Hashtable get/put * A call to 'get' would mark that object as the most recently used. * At any time, the least recently used object can be purged from the cache. * Lookups and purges must be fast (As in Hashtable fast) * The number of Objects may be large, so list lookups are not good enough. * **The implementation must be made using JavaME, so there is little scope for using third-party code or neat library classes from the standard Java libraries.** For this reason I'm looking more for algorithmic answers rather than recommendations of off-the-peg solutions.
Java Collections provide [LinkedHashMap](http://java.sun.com/javase/6/docs/api/java/util/LinkedHashMap.html) out of the box, which is well-suited to building caches. You probably don't have this in Java ME, but you can grab the source code here: [`http://kickjava.com/src/java/util/LinkedHashMap.java.htm`](http://kickjava.com/src/java/util/LinkedHashMap.java.htm) If you can't just copy-paste it, looking at it should get you started implementing one for inclusion in your mobile app. The basic idea is just to include a linked list through the map elements. If you keep this updated whenever someone does put or get, you can efficiently track access order and use order. The docs contain instructions for building an MRU Cache by overriding the [`removeEldestEntry(Map.Entry)`](http://java.sun.com/javase/6/docs/api/java/util/LinkedHashMap.html#removeEldestEntry(java.util.Map.Entry)) method. All you really have to do is make a class that extends `LinkedHashMap` and override the method like so: ``` private static final int MAX_ENTRIES = 100; protected boolean removeEldestEntry(Map.Entry eldest) { return size() > MAX_ENTRIES; } ``` There's also a [constructor](http://java.sun.com/javase/6/docs/api/java/util/LinkedHashMap.html#LinkedHashMap(int,%20float,%20boolean)) that lets you specify whether you want the class to store things in order by insertion or by use, so you've got a little flexibility for your eviction policy, too: ``` public LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) ``` Pass **true** for use-order and **false** for insertion order.
A ConcurrentLinkedHashMap is difficult to construct, due to the locking requirements. A LinkedHashMap with a lock is straightforward, but not always performant. A concurrent version would attempt to reduce the amount of locking, either by lock splitting or ideally making CAS operations to make locking very cheap. If the CAS operations ever do become expensive, then similarly bucket splitting can be helpful. As an LRU requires writes for every access operation, and uses a doubly-linked list, this is very tricky to implement with pure CAS operations. I've attempted it, but I need to continue to mature my algorithm. If you search for ConcurrentLinkedHashMap, you'll see my project page... If Java ME doesn't support CAS operations, which I'd expect to be true, then basic synchronization is all you can do. This is probably good enough with a LHM, given that I've only seen performance problems at high thread count on the server-side. So +1 to the answers above.
How to implement a most-recently-used cache
[ "", "java", "algorithm", "caching", "java-me", "mru", "" ]
Suppose someone is editing a HTML form, and their session times out, how can one have Django re-authenticate that individual without losing the content the user had entered into the form? The snippet [Django Snippets: Require login across entire site](http://www.djangosnippets.org/snippets/136/) suggests how to do site-wide authentication, but I expect it will lose the GET component of the string (namely because request.path does not include it), and definitely lose the POST data. How can one preserve the POST and GET across those inconvenient timeouts. I find that finessed web-sites tend to handle this intelligently, and I'd like to be able to do it in Django (as would others, I imagine!). Thoughts would be appreciated. Thank you.
I have two suggestions. ## Redirect/Middleware Since you're already using middleware to handle the login requirement, you could modify this middleware. Or possibly, create another middleware class that is called after the login middleware. These ideas are intertwined so it may make more sense to modify the existing one. 1. If not logged in, capture the GET and POST data in the middleware, and store it in the session 2. If the user is authenticated, check for the value(s) set in #1. If they exist, modify request.GET and request.POST to reflect it, and delete the session data. I think this should work cleanly, and many people would find it useful. It'd be a great post on [djangosnippets.org](http://djangosnippets.org). ## Ajax technique This is less practical if you already have your form handling in place, but could create a better user experience. If you POST asynchronously, your Javascript handler could recognize a "login required" response code, and then display a popup dialog requesting login. On completion, the user could resubmit the form.
Add `onsubmit` handler to all your forms that would check session via JS and prompt use to login before proceeding. This way form submit would not really happen before user is logged in again. And make sure you verify that logged in user stays the same across sessions.
How does one enable authentication across a Django site, and transparently preserving any POST or GET data?
[ "", "python", "django", "authentication", "wsgi", "middleware", "" ]
I am working with ImageMagick and am wondering what the best way to read image data in from StdOut of the ImageMagick process. I an invoking the command to the process like so: /opt/local/bin/convert -resize 8000@ - - and then piping a byte array to the process for processing. what is the best way to read data from a process like this?
You might want to look at [Apache Commons Exec](http://commons.apache.org/exec/index.html) this gives you a good way of running executables and passing the results into Java. It's similar to using the method Michael mentioned except should allow you more control. There are some good examples of usage on the [tutorial](http://commons.apache.org/exec/tutorial.html) page.
Just want to post a code sample using ImageMagick via Apache commons exec for completeness ``` try { StringBuffer sb = new StringBuffer(); sb.append(this.validPathToImageMagickCommand); sb.append('\u0020'); for (int i = 0; i < args.size(); i++) { String s = args.get(i); sb.append(s); } CommandLine cl = CommandLine.parse(sb.toString()); PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(output, System.err, new ByteArrayInputStream(inputBytes)); byAs = new ByteArrayInputStream(inputBytes); pumpStreamHandler.setProcessOutputStream(byAs); DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(pumpStreamHandler); int exitValue = executor.execute(cl); outputBytes = output.toByteArray(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (byAs != null) byAs.close(); if (output != null) output.close(); } catch (IOException e) { System.out.println(e); } } ```
How would you read image data in from a program like Image Magick In Java?
[ "", "java", "image-processing", "" ]
I find myself breaking strings constantly just to get them on the next line. And of course when I go to change those strings (think logging messages), I have to reformat the breaks to keep them within the 80 columns. How do most people deal with this?
"A foolish consistency is the hobgoblin of little minds, adored by little statesmen and philosophers and divines." The important part is "foolish". The 80-column limit, like other parts of PEP 8 is a pretty strong suggestion. But, there is a limit, beyond which it could be seen as foolish consistency. I have the indentation guides and edge line turned on in Komodo. That way, I know when I've run over. The questions are "why?" and "is it worth fixing it?" Here are our common situations. **logging messages**. We try to make these easy to wrap. They look like this ``` logger.info( "unique thing %s %s %s", arg1, arg2, arg3 ) ``` **Django filter expressions**. These can run on, but that's a good thing. We often knit several filters together in a row. But it doesn't have to be one line of code, multiple lines can make it more clear what's going on. This is an example of functional-style programming, where a long expression is sensible. We avoid it, however. **Unit Test Expected Result Strings**. These happen because we cut and paste to create the unit test code and don't spend a lot of time refactoring it. When it bugs us we pull the strings out into separate string variables and clean the `self.assertXXX()` lines up. We generally don't have long lines of code because we don't use lambdas. We don't strive for fluent class design. We don't pass lots and lots of arguments (except in a few cases). We rarely have a lot of functional-style long-winded expressions. When we do, we're not embarrassed to break them up and leave an intermediate result lying around. If we were functional purists, we might have gas with intermediate result variables, but we're not purists.
I recommend trying to stay true to 80-column, but not at *any cost*. Sometimes, like for logging messages, it just makes more sense to keep 'em long than breaking up. But for most cases, like complex conditions or list comprehensions, breaking up is a good idea because it will help you divide the complex logic to more understandable parts. It's easier to understand: ``` print sum(n for n in xrange(1000000) if palindromic(n, bits_of_n) and palindromic(n, digits)) ``` Than: ``` print sum(n for n in xrange(1000000) if palindromic(n, bits_of_n) and palindromic(n, digits)) ``` It may look the same to you if you've just written it, but after a few days those long lines become hard to understand. --- Finally, while PEP 8 dictates the column restriction, it also says: > A style guide is about consistency. Consistency with this style guide > is important. Consistency within a project is more important. > Consistency within one module or function is most important. > > But most importantly: know when to be inconsistent -- sometimes the > style guide just doesn't apply. When in doubt, use your best judgment. > Look at other examples and decide what looks best. And don't hesitate > to ask!
Do you have a hard time keeping to 80 columns with Python?
[ "", "python", "" ]
I was wondering what could be the **size of an object of an empty class**. It surely could *not* be 0 bytes since it should be possible to reference and point to it like any other object. But, how big is such an object? I used this small program: ``` #include <iostream> using namespace std; class Empty {}; int main() { Empty e; cerr << sizeof(e) << endl; return 0; } ``` The output I got on both Visual C++ and Cygwin-g++ compilers was **1 byte**! This was a little surprising to me since I was expecting it to be of the size of the machine word (32 bits or 4 bytes). Can anyone explain **why** the size of 1 byte? **Why not** 4 bytes? Is this dependent on compiler or the machine too? Also, can someone give a more cogent reason for why an empty class object **will not** be of size 0 bytes?
Quoting [Bjarne Stroustrup's C++ Style and Technique FAQ](http://www.stroustrup.com/bs_faq2.html#sizeof-empty), the reason the size is non-zero is "To ensure that the addresses of two different objects will be different." And the size can be 1 because alignment doesn't matter here, as there is nothing to actually look at.
The standard states that all most derived objects have sizeof() >= 1: > Unless it is a bit-field (class.bit), a most derived object shall have a non-zero size and shall occupy one or more bytes of storage. Base class sub-objects may have zero size. > [ISO/IEC FDIS 14882:1998(E) intro.object](http://www.kuzbass.ru:8086/docs/isocpp/intro.html#intro.object)
C++: What is the size of an object of an empty class?
[ "", "c++", "class", "object", "" ]
I was playing with a project of mine today and found an interesting little snippet, given the following pattern, you can safely cleanup a thread, even if it's forced to close early. My project is a network server where it spawns a new thread for each client. I've found this useful for early termination from the remote side, but also from the local side (I can just call `.Abort()` from inside my processing code). Are there any problems you can see with this, or any suggestions you'd make to anyone looking at a similar approach? Test case follows: --- ``` using System; using System.Threading; class Program { static Thread t1 = new Thread(thread1); static Thread t2 = new Thread(thread2); public static void Main(string[] args) { t1.Start(); t2.Start(); t1.Join(); } public static void thread1() { try { // Do our work here, for this test just look busy. while(true) { Thread.Sleep(100); } } finally { Console.WriteLine("We're exiting thread1 cleanly.\n"); // Do any cleanup that might be needed here. } } public static void thread2() { Thread.Sleep(500); t1.Abort(); } } ``` For reference, without the try/finally block, the thread just dies as one would expect.
Aborting another thread at all is just a bad idea unless the whole application is coming down. It's too easy to leave your program in an unknown state. Aborting your *own* thread is occasionally useful - ASP.NET throws a `ThreadAbortException` if you want to prematurely end the response, for example - but it's not a terribly nice design. Safe clean-up of a thread should be mutual - there should be some shared flag *requesting* that the thread shuts down. The thread should check that flag periodically and quit appropriately.
Whether or not this will "safely" cleanup a thread cannot be discerned from a general code sample unfortunately. It's highly dependent upon the actual code that is executed within the thread. There are multiple issues you must consider. Each represents a potential bug in the code. 1. If the thread is currently in native code, it will not immediately respect the Thread.Abort call. It will do all of the work it wants to do in native code and will not throw until the code returns back to managed. Until this happens thread2 will hang. 2. Any native resources that are not freed in a finally block will be leaked in this scenario. All native resources should be freed in a finally block but not all code does this and it's an issue to consider. 3. Any locks that are not freed in a finally block will remain in a lock'd state and can lead to future dead locks. There are other issues which are slipping my mind at the moment. But hopefully this will give you some guidance with your application.
C# Threading Patterns - is this a good idea?
[ "", "c#", ".net", "multithreading", "" ]
I have RSS feed that I want to modify on fly, all I need is the text (and linefeeds) so everything else must be removed ( All images, styles, links ) How can I do this easily with ASP.NET c#
Regex cannot parse XML. Do not use regex to parse XML. Do not pass Go. Do not collect £200. You need a proper XML parser. Load the RSS into an [XMLDocument](http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx), then use [innerText](http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.innertext.aspx) to get only text content. Note that even when you've extracted the description content from RSS, it can contain active HTML. That is: ``` <description> &lt;em&gt;Fish&lt;/em&gt; &amp;amp; chips </description> ``` can, when parsed properly as XML then read as text give you either the literal string: ``` <em>Fish</em> &amp; chips ``` or, the markup: > *Fish* & chips The fun thing about RSS is that you don't really know which is right. In RSS 2.0 it is explicitly HTML markup (the second case); in other versions it's not specified. Generally you should assume that descriptions *can* contain entity-encoded HTML tags, and if you want to further strip those from the final text you'll need a second parsing step. (Unfortunately, since this is legacy HTML and not XML it's harder to parse; a regex will be even more useless than it is for parsing XML. There isn't a built-in HTML parser in .NET, but there are third-party libraries such as the [HTML Agility Pack](http://html-agility-pack.net/?z=codeplex).)
``` string pattern = @"<(.|\n)*?>"; return Regex.Replace(htmlString, pattern, string.Empty); ```
Strip away all HTML tags and formatting (RegEx)
[ "", "c#", "asp.net", "" ]
I'm trying to find the best way to save the state of a simple application. From a DB point-of-view there are 4/5 tables with date fields and relationships off course. Because the app is simple, and I want the user to have the option of moving the data around (usb pen, dropbox, etc), I wanted to put all data in a single file. What is the best way/lib to do this? XML usually is the best format for this (readability & openness), but I haven't found any great lib for this without doing SAX/DOM.
If you want to use XML, take a look at [XStream](http://x-stream.github.io/) for simple serialization of Java objects into XML. Here is ["Two minute tutorial"](http://x-stream.github.io/tutorial.html). If you want something simple, standard [Java Properties format](http://en.wikipedia.org/wiki/.properties) can be also a way to store/load some small data.
consider using plain JAXB annotations that come with the JDK: ``` @XmlRootElement private class Foo { @XmlAttribute private String text = "bar"; } ``` here's a [blog-post of mine](http://netzwerg.ch/2007/10/simple-jaxb.html) that gives more details on this simple usage of JAXB (it also mentiones a more "classy" JAXB-based approach -- in case you need better control over your XML schema, e.g. to guarantee backwards compatibility)
Best way to save data in a Java application?
[ "", "java", "database", "settings", "state", "" ]
Our customer is using our software (Java Swing application started using Webstart) besides other software like MS Office, to do his job. From time to time there are important events he has to deal with in our software without much delay. The customer wants to have a prominent notification then. Now he might be using Excel at the moment, so popping up a message box will not suffice (although the entry in the task bar will be flashing). We need some mechanism like the Outlook notifier, i.e. a popup that is always visible but does not steal the focus. The notifier should be displayed all the time until the reason for the message has gone (the user has solved the issue) or the user has closed the message (like in outlook). Additionally we want to display a tray icon and maybe play a sound. I've tried the Java6 java.awt.SystemTray as well as the JDIC (version 0.9 since we already have that lib in the classpath of that project) equivalent, but I did not find a way to set the timeout of the TrayIcon.displayMessage method, and the message seems not to be always on top. Is there any other option besides JNI to achieve the requested behavior? If JNI is the only choice and since Windows is the only platform of our customers, is the Outlook notifier an Outlook only feature, or is it freely usable through the Windows API? Or what other options exist to notify the user about an important task to perform in one software without hindering him to complete his current task in another software. A system modal dialog therefore is no option!
Try using [setAlwaysOnTop](http://java.sun.com/javase/6/docs/api/java/awt/Window.html#setAlwaysOnTop(boolean)) on your JFrame/JWindow.
With OS X the obvious answer would be to use [Growl](http://growl.info/). But there exists a little project doing a similar service on windows environments. It's called [Snarl](http://www.fullphat.net/). This might give you a new option to try. Drawback: You'll have to install a tool on the client's machines. From your description I assume you have a defined group of users on company workplaces, right? So this might acceptable, nevertheless.
How to notify the user of important events for a desktop application?
[ "", "java", "winapi", "swing", "usability", "java-native-interface", "" ]
Is there a way to get functionality similar to `mkdir -p` on the shell from within Python. I am looking for a solution other than a system call. I am sure the code is less than 20 lines, and I am wondering if someone has already written it?
For Python ≥ 3.5, use [`pathlib.Path.mkdir`](https://docs.python.org/library/pathlib.html#pathlib.Path.mkdir): ``` import pathlib pathlib.Path("/tmp/path/to/desired/directory").mkdir(parents=True, exist_ok=True) ``` The `exist_ok` parameter was added in Python 3.5. --- For Python ≥ 3.2, [`os.makedirs`](https://docs.python.org/library/os.html#os.makedirs) has an [optional third argument `exist_ok`](https://docs.python.org/3/library/os.html?highlight=exist_ok#os.makedirs) that, when `True`, enables the `mkdir -p` functionality—*unless* `mode` is provided and the existing directory has different permissions than the intended ones; in that case, `OSError` is raised as previously: ``` import os os.makedirs("/tmp/path/to/desired/directory", exist_ok=True) ``` --- For even older versions of Python, you can use `os.makedirs` and ignore the error: ``` import errno import os def mkdir_p(path): try: os.makedirs(path) except OSError as exc: # Python ≥ 2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): pass # possibly handle other errno cases here, otherwise finally: else: raise ```
In Python >=3.2, that's ``` os.makedirs(path, exist_ok=True) ``` In earlier versions, use [@tzot's answer](https://stackoverflow.com/a/600612/11343).
mkdir -p functionality in Python
[ "", "python", "path", "directory-structure", "mkdir", "" ]
Should dynamic business objects for a site be stored in the users session or use ASP.Net caching (objects such as orders, profile information etc)? I have worked with sites that used sessions to store business objects, but I was wondering...What are the advantages or disadvantages of caching?
If the objects are shareable between user sessions, then use the cache. If the objects are unique to each session -- perhaps because they are governed by permissions -- then store it in the session. The in-process session itself is stored in the cache so the deciding factor really should be the scope of the data.
Caching is just that -- caching. You can never rely on entries being there, so no assumptions must be made in that respect: be prepared to go straight to the DB (or wherever else) to refetch data. Session, on the other hand, is more suited towards storing objects, though personally I try to avoid session store in favour of a DB. I usually do that by abstracting away the store behind an opaque *ISessionStoreService* interface: ``` interface ISessionStore { T GetEntry<T>(string key); void SaveEntry<T>(string key, T entry); } ``` and then "dependency-injecting" appropriate implementation, be it *InmemorySessionStore*, *DbSessionStore* or whatever.
Data cache vs session object in ASP.Net
[ "", "c#", "asp.net", "session", "caching", "" ]
I just looked at one of those libraries that is of the naming schema "something-Linq" expecting to gain some more knowledge on how to construct expression trees in an elegant way - and was disappointed. Because all I could find were methods that extended IEnumerable - of course with "normal" C# code. Now I have this question: Do non-expression extensions for IEnumerable really justify the name of the library to have "Linq" in it? Or is the author just jumping on a hype trying to get more downloads for his IEnumerable extension library and I was right in expecting IQueryable and expressions when seeing "Linq" in the name of the library? Edit: I would argue that there is a difference between Linq-to-... and something-Linq libraries. IMHO Linq-to-... are linq provider libraries, something-Linq are linq extensions. I think Linq provider libraries may choose if they expose IQueryable or IEnumerable in their results - linq extensions do not have that choice. As far as I am concerned they must be able to work with both kinds of provider libraries. That means for me that all linq extensions must provide both Queryable and Enumerable extensions. Edit 2: A very lively discussion took place between Jon and me in the comments of his answer. I volunteered to create a blogpost to hopefully clarify things: [Mapping the uncharted waters of LINQ](http://saftsack.fs.uni-bayreuth.de/~dun3/archives/mapping-the-unchartered-waters-of-linq/253.html) Edit 3: For anybody who is interested in the discussion - I really encourage you to go to my blog post. Skip the post itself because it is horrible - and go straight to the discussion and explanations by Jon.
LINQ doesn't imply expression trees to me. It implies data access in the general style of LINQ. LINQ to Objects doesn't have any expression trees in it, but is still definitely LINQ IMO. LINQ to XML is a bit more specious - it's really just an XML API which exposes `IEnumerable<T>` in various ways, both as input and output. That means it works really well with LINQ to Objects, but it's not implementing any of the standard operators itself. However, you do typically *use* it with LINQ to Objects, and the result is "LINQ-like" code, so I guess it's not too bad. I certainly have no problem with non-expression extensions being called LINQ-to-whatever - indeed, such a stance would be hypocritical given my [MoreLINQ](http://code.google.com/p/morelinq/) and [Push LINQ](http://msmvps.com/blogs/jon_skeet/archive/2008/01/04/quot-push-quot-linq-revisited-next-attempt-at-an-explanation.aspx) projects. To me there are two main questions: * Is the API about data access and processing? * Does it attempt to make the access/processing fluent, ideally (but not necessarily) conforming to the query expression pattern to enable the language features of VB9 and C#3 to help with readable code?
Short answer: **Marketing gimmick** People uses the term "Linq-something" or "something-linq" as a marketing gimmick to give the customer/developer an idea what the library is. This saves the marketing (or documentation developer) time in explaining what the library does.
When does a library deserve the be called "Linq-something" or "something-Linq"?
[ "", "c#", ".net", "linq", "extension-methods", "" ]
I have created a couple of different structures in a program. I now have a structure with nested structures however I cannot work out how to initialize them correctly. The structures are listed below. ``` /***POINT STRUCTURE***/ struct Point{ float x; //x coord of point float y; //y coord of point }; /***Bounding Box STRUCTURE***/ struct BoundingBox{ Point ymax, ymin, xmax, xmin; }; /***PLAYER STRUCTURE***/ struct Player{ vector<float> x; //players xcoords vector<float> y; //players ycoords BoundingBox box; float red,green,blue; //red, green, blue colour values float r_leg, l_leg; //velocity of players right and left legs int poly[3]; //number of points per polygon (3 polygons) bool up,down; }; ``` I then attempt to intialse a newly created Player struct called player. ``` //Creates player, usings vectors copy and iterator constructors Player player = { vector<float>(xcords,xcords + (sizeof(xcords) / sizeof(float)) ), //xcords of player vector<float>(ycords,ycords + (sizeof(ycords) / sizeof(float)) ), //ycoords of playe box.ymax = 5; //create bounding box box.ymin = 1; box.xmax = 5; box.xmin = 1; 1,1,1, //red, green, blue 0.0f,0.0f, //r_leg,l_leg {4,4,4}, //number points per polygon true,false}; //up, down ``` This causes several different errors, concerning box. Stating the box has no clear identifier and missing struct or syntax before '.'. I then tried just to create a Player struct and initialise it's members as follows: ``` Player bob; bob.r_leg = 1; ``` But this causes more errors, as the compiler thinks bob has no identifier or is missing some syntax. I googled the problem but I did not find any articles showing me how to initalise many different members of nested structures within the (parent) structure. Any help on this subject would be greatly appreciated :-) !!!
You initialize it normally with `{ ... }`: ``` Player player = { vector<float>(xcords,xcords + (sizeof(xcords) / sizeof(float)) ), vector<float>(ycords,ycords + (sizeof(ycords) / sizeof(float)) ), 5, 1, 5, 1, 5, 1, 5, 1, 1.0f,1.0f,1.0f, //red, green, blue 0.0f,0.0f, //r_leg,l_leg {4,4,4}, //number points per polygon true,false }; ``` Now, that is using "brace elision". Some compilers warn for that, even though it is completely standard, because it could confuse readers. Better you add braces, so it becomes clear what is initialized where: ``` Player player = { vector<float>(xcords,xcords + (sizeof(xcords) / sizeof(float)) ), vector<float>(ycords,ycords + (sizeof(ycords) / sizeof(float)) ), { { 5, 1 }, { 5, 1 }, { 5, 1 }, { 5, 1 } }, 1.0f, 1.0f, 1.0f, //red, green, blue 0.0f, 0.0f, //r_leg,l_leg { 4, 4, 4 }, //number points per polygon true, false }; ``` If you only want to initialize the `x` member of the points, you can do so by omitting the other initializer. Remaining elements in aggregates (arrays, structs) will be value initialized to the "right" values - so, a `NULL` for pointers, a `false` for bool, zero for ints and so on, and using the constructor for user defined types, roughly. The row initializing the points looks like this then ``` { { 5 }, { 5 }, { 5 }, { 5 } }, ``` Now you could see the danger of using brace elision. If you add some member to your struct, all the initializers are "shifted apart" their actual elements they should initialize, and they could hit other elements accidentally. So you better always use braces where appropriate. Consider using constructors though. I've just completed your code showing how you would do it using brace enclosed initializers.
You can add default values to a structure like so: ``` struct Point{ Point() : x(0), y(0) { }; float x; float y; }; ``` or ``` struct Point{ Point() { x = 0; y = 0; }; float x; float y; }; ``` For adding those values during construction, add parameters to constructors like this: ``` struct Point{ Point(float x, float y) { this->x = x; this->y = y; }; float x; float y; }; ``` and instantiate them with these: ``` Point Pos(10, 10); Point *Pos = new Point(10, 10); ``` This also works for your other data structures.
How to initialize nested structures in C++?
[ "", "c++", "data-structures", "initialization", "nested", "structure", "" ]
we are trying to use the Google YouTube API to upload videos from our website to YouTube through the browser directly. The API works in two steps, in the first step we need to create an Video object with all the metadata like title,tags,description, category etc. Then we need to send a request with this object to YouTube and get a Token object generated as a response. This token object has a Token Value and a Token URL as its members. In second step they suggest that we should create a Form with the action attribute set to the Token URL. This form should have a file upload control and a hidden field with the Token Value as its value. When this form is posted, it would upload the video to YouTube. This works great if we have it as a two step process, asking users for the metadata first and then redirecting them on to second page for the actual video upload. However, we are trying to accomplish this in a single page, appearing as a single step to the user. We have a MasterPage with the 'aspnetForm' specified in it, because of which we cant have another form with `runat='server'` property. We have tried modifying the aspnetFrom's action attribute using JavaScript/code-behind but it stays the same, whatever we do. We have also tried to put another nested form, whose action tag would be set on the button click event, after the first response from YouTube with token is received. But even this doesn't work, as the form isn't created at the time this method is called.. We have tried several approaches but none seems to work.. any suggestions on this would be great. If you have any more questions to understand the situation clearly.. please let me know.. --- Update: Thanks for the responses guys. We changed the business logic a little bit to resolve the issue. It was long back and I am not looking for a resolution as of now.. However, the question is still open and getting responses. I really appreciate all the help and hence, would leave the question open for any further discussions.
I would create a form that you display to the user with text fields for the metadata and a file upload control for the video. Then in the code that handles the postback, you can submit the metadata off to the YouTube API to get the Token Value. You then craft an [HttpWebRequest](http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx) with the Token Value passed into the `Create` method of the `WebRequest` object and set the `Method` property to `Post`. You then add the uploaded video (see [dr evil's answer to "Upload files with HTTPWebrequest (multipart/form-data)"](https://stackoverflow.com/questions/566462/upload-files-with-httpwebrequest-multipart-form-data/567460#567460) for more a walk through of that), and when you call `GetResponse()` your file will be submitted. Things to watch out for: 1. `ScriptTimeout`: If you're allowing your users to upload large files to YouTube - if it takes a while for you to transmit it, then your script could be terminated prematurely. 2. Bandwidth: You'll have both the upload to your servers and then the upload to YouTube to account for - by allowing the user to upload directly to YouTube in a two step process you never touch the video, and it never goes near your servers - this might be an issue for you or your hosting provider - for example, my host doesn't count traffic through FTP in my monthly bandwidth, but does include files uploaded/downloaded through the website.
<http://code.google.com/apis/youtube/2.0/developers_guide_dotnet.html#Direct_Upload>
YouTube API integration ASP.NET - upload video with a single page
[ "", "c#", "asp.net", "youtube-api", "" ]
I have an object that I ended up with via a reflection call: `object readOnlyCollectionObject = propertyInfo.GetValue(someEntity, null);` I know this object is a generic ReadOnlycollection. It could be a `ReadOnlyCollection<Cat>`, `ReadOnlyCollection<Dog>`, etc. For argument sake, lets just say it is a `ReadOnlyCollection<T>`. Even though a Dog derives from an object, I know that a `ReadOnlyCollection<Dog>` does not derive from a `ReadOnlyCollection<object>`. So even if I use reflection to call the CopyTo method I still need to know the specific type of ReadOnlyCollection, which is what I want to avoid. I want to know how to get all the elements out of the ReadOnlyCollection as an array of object references without having to know the specific type (T) of the `ReadOnlyCollection<T>`.
Many other answers mention Cast() and ToArray, those all have a problem with the type. As you say, you won't know which specialized IEnumerable your property will implement. However, you can be sure that they will all implement the non-generic ICollection interface. ``` ICollection readOnlyCollectionObject = (ICollection)propertyInfo.GetValue(someEntity, null); object[] objs = new ArrayList(readOnlyCollectionObject).ToArray(); ``` or ``` ICollection readOnlyCollectionObject = (ICollection)propertyInfo.GetValue(someEntity, null); object[] objs = new object[readOnlyCollectionObject.Count]; for (int i = 0; i < readOnlyCollectionObject.Count; i++) objs[i] = readOnlyCollectionObject[i]; ``` Edit: Forgot to update the cast from IEnumerable to ICollection
Well, you can use the [Cast](http://msdn.microsoft.com/en-us/library/bb341406.aspx) extension method on the *readonly* collection and then convert it to an array of objects but, based on the fact that in c# arrays are *covariant*, you can simply do: ``` object[] objs = myReadOnlyCollection.ToArray(); ``` *(edit)* As Pop Catalin mentioned, the only works if `T` is a reference type. Use the Cast method otherwise. *(edit2)* Your update to the question changes things quite a bit ... I think that what you're trying to do is not possible. You want to cast to a explicit Type at *compile time* that is only available at *runtime*. In this case, the only way you have to access the collection is with reflection.
object[] from ReadOnlyCollection<T>
[ "", "c#", "arrays", "generics", "object", "readonly-collection", "" ]
I've got a very simple stored procedure : ``` create procedure spFoo(v varchar(50)) as insert into tbFoo select v ``` I've got 50 values to insert into tbFoo, which means in my c# code I call spFoo 50 times. This is a pretty inefficient way of doing this, especially if there's some lag between my program and the database. What do you usually do in this situation ? I'm using SQL Server 2008 but it's probably unrelated.
If your problem is multiple rows trying to be passed in then as of SQL Server 2008 you have a new parameter type [Table-Valued](https://msdn.microsoft.com/en-us/library/bb510489(SQL.100).aspx). Which allows you to pass a .Net Datatable directly into a stored procedure through a .NET SQLParamter of Type Structured. ``` tvpParam.SqlDbType = SqlDbType.Structured ``` However if the problem is that there are 50 columns in 1 row that you are trying to populate then you would be better passing them all in as separate parameters and change the Procedure rather than trying to get slick with either code or T-SQL. There's a good [article](https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/table-valued-parameters) that demonstrates how to use table valued parameters in SQL Server and through .NET in both C# and VB.Net. Hope this helps.
Actually, a cool feature of SQL Server 2008 is [table valued parameters](http://msdn.microsoft.com/en-us/library/bb510489.aspx). setup: ``` create type fooTableType as table (v varchar(50)); go create proc spFoo(@t fooTableType readonly) as insert into tbFoo(v) select v from @t go ``` then your C# code gens: ``` declare @t as fooTableType insert @t(v) values('beyond'),('all'),('recognition') exec spFoo(@t) ``` here's some rough C# code to do that: ``` using (SqlCommand cmd=new SqlCommand()) { StringBuilder sql = new StringBuilder(); for(int i=0; i<50; i++) { sql.AppendFormat(",(@v{i})",i); cmd.Parameters.AddWithValue("@v"+i.ToString(),values[i]); } cmd.CommandText = "declare @t as fooTableType; insert @t(v) values" + sql.ToString().Substr(1) + "; exec spFoo(@t);" cmd.CommandType = CommandType.Text; cmd.Connection = myConnection; cmd.ExecuteNonQuery(); } ``` I would generally agree that such an optimization is not absolutely necessary. Perhaps it is OCD but I wouldn't be able to leave it as a loop of cmd.ExecuteNonQuery(). Check out CertifiedCrazy's [answer](https://stackoverflow.com/questions/629455/how-should-i-optimize-multiple-calls-in-my-net-code-to-a-trivial-stored-procedur/629504#629504) for a cleaner version of the C# code. Also note that this technique is limited to 2100 total parameters - this a limitation of the underlying TDS protocol.
How should I optimize multiple calls in my .net code to a trivial stored procedure?
[ "", ".net", "sql", "optimization", "stored-procedures", "" ]
Several processes with the same name are running on host. What is the cross-platform way to get PIDs of those processes by name using **python** or **jython**? 1. I want something like `pidof` but in python. (I don't have `pidof` anyway.) 2. I can't parse `/proc` because it might be unavailable (on HP-UX). 3. I do not want to run `os.popen('ps')` and parse the output because I think it is ugly (field sequence may be different in different OS). 4. Target platforms are Solaris, HP-UX, and maybe others.
You can use psutil (<https://github.com/giampaolo/psutil>), which works on Windows and UNIX: ``` import psutil PROCNAME = "python.exe" for proc in psutil.process_iter(): if proc.name() == PROCNAME: print(proc) ``` On my machine it prints: ``` <psutil.Process(pid=3881, name='python.exe') at 140192133873040> ``` EDIT 2017-04-27 - here's a more advanced utility function which checks the name against processes' name(), cmdline() and exe(): ``` import os import psutil def find_procs_by_name(name): "Return a list of processes matching 'name'." assert name, name ls = [] for p in psutil.process_iter(): name_, exe, cmdline = "", "", [] try: name_ = p.name() cmdline = p.cmdline() exe = p.exe() except (psutil.AccessDenied, psutil.ZombieProcess): pass except psutil.NoSuchProcess: continue if name == name_ or cmdline[0] == name or os.path.basename(exe) == name: ls.append(p) return ls ```
There's no single cross-platform API, you'll have to check for OS. For posix based use /proc. For Windows use following code to get list of all pids with coresponding process names ``` from win32com.client import GetObject WMI = GetObject('winmgmts:') processes = WMI.InstancesOf('Win32_Process') process_list = [(p.Properties_("ProcessID").Value, p.Properties_("Name").Value) for p in processes] ``` You can then easily filter out processes you need. For more info on available properties of Win32\_Process check out [Win32\_Process Class](http://msdn.microsoft.com/en-us/library/aa394372%28VS.85%29.aspx)
Cross-platform way to get PIDs by process name in python
[ "", "python", "cross-platform", "jython", "hp-ux", "" ]
I've been reading recently about [Stackless Python](http://www.stackless.com/) and it seems to have many advantages compared with vanilla cPython. It has all those cool features like infinite recursion, microthreads, continuations, etc. and at the same time is faster than cPython (around 10%, if [the Python wiki](http://www.python.org/dev/implementations/) is to be believed) *and* compatible with it (at least versions 2.5, 2.6 and 3.0). All these looks almost too good to be true. However, [TANSTAAFL](http://en.wikipedia.org/wiki/TANSTAAFL), I don't see much enthusiasm for Stackless among the Python community, and [PEP 219](http://www.python.org/dev/peps/pep-0219/) has never come into realization. Why is that? What are the drawbacks of Stackless? What skeletons are hidden in Stackless' closet? (I know Stackless doesn't offer real concurrency, just an easier way of programming in the concurrent way. It doesn't really bother me.)
I don't know where that "Stackless is 10% faster" on the Wiki came from, but then again I've never tried to measure those performance numbers. I can't think of what Stackless does to make a difference that big. Stackless is an amazing tool with several organizational/political problems. The first comes from history. Christian Tismer started talking about what eventually became Stackless about 10 years ago. He had an idea of what he wanted, but had a hard time explaining what he was doing and why people should use it. This is partially because his background didn't have the CS training regarding ideas like coroutines and because his presentations and discussion are very implementation oriented, which is hard for anyone not already hip-deep in continuations to understand how to use it as a solution to their problems. For that reason, the initial documentation was poor. There were some descriptions of how to use it, with the best from third-party contributors. At PyCon 2007 I gave a talk on "[Using Stackless](http://dalkescientific.com/StacklessPyCon2007-Dalke.pdf)" which went over quite well, according to the PyCon survey numbers. Richard Tew has done a great job collecting these, updating [stackless.com](http://stackless.com), and maintaining the distribution when new Python releases comes up. He's an employee of [CCP Games](http://ccpgames.com/), developers of EVE Online, which uses Stackless as an essential part of their gaming system. CCP games is also the biggest real-world example people use when they talk about Stackless. The main tutorial for Stackless is Grant Olson's "[Introduction to Concurrent Programming with Stackless Python](http://www.grant-olson.net/files/why_stackless.html)", which is also game oriented. I think this gives people a skewed idea that Stackless is games-oriented, when it's more that games are more easily continuation oriented. Another difficulty has been the source code. In its original form it required changes to many parts of Python, which made Guido van Rossum, the Python lead, wary. Part of the reason, I think, was support for call/cc that was later removed as being "too much like supporting a goto when there are better higher-level forms." I'm not certain about this history, so just read this paragraph as "Stackless used to require too many changes." Later releases didn't require the changes, and Tismer continued to push for its inclusion in Python. While there was some consideration, the official stance (as far as I know) is that CPython is not only a Python implementation but it's meant as a reference implementation, and it won't include Stackless functionality because it can't be implemented by Jython or Iron Python. There are absolutely no plans for "*significant changes to the code base*". That quote and reference hyperlink from Arafangion's (see the comment) are from roughly 2000/2001. The structural changes have long been done, and it's what I mentioned above. Stackless as it is now is stable and mature, with only minor tweaks to the code base over the last several years. One final limitation with Stackless - there is no strong advocate for Stackless. Tismer is now deeply involved with [PyPy](http://pypy.org/), which is an implementation of Python for Python. He has implemented the Stackless functionality in PyPy and considers it much superior to Stackless itself, and feels that PyPy is the way of the future. Tew maintains Stackless but he isn't interested in advocacy. I considered being in that role, but couldn't see how I could make an income from it. Though if you want training in Stackless, feel free to [contact me](http://mailto:dalke@dalkescientific.com)! :)
it took quite long to find this discussion. At that time I was not on PyPy but had a 2-years affair with psyco, until health stopped this all quite abruptly. I'm now active again and designing an alternative approach - will present it on EuroPython 2012. Most of Andrews statements are correct. Some minor additions: Stackless was significantly faster than CPython, 10 years ago, because I optimized the interpreter loop. At that time, Guido was not ready for that. A few years later, people did similar optimizations and even more and better ones, which makes Stackless a little bit slower, as expected. On inclusion: well, in the beginning I was very pushy and convinced that Stackless is the way to go. Later, when it was almost possible to get included, I lost interest in that and preferred to let it stay this way, partially out of frustration, partially to keep control of Stackless. The arguments like "other implementations cannot do it" felt always lame to me, as there are other examples where this argument could also be used. I thought I better forget about that and stay in good friendship with Guido, having my own distro. Meanwhile things are changing again. I'm working on PyPy and Stackless as an extension Will talk about that sometimes later Cheers -- Chris
What are the drawbacks of Stackless Python?
[ "", "python", "python-stackless", "" ]
I query a model: ``` Members.objects.all() ``` And it returns: ``` Eric, Salesman, X-Shop Freddie, Manager, X2-Shop Teddy, Salesman, X2-Shop Sean, Manager, X2-Shop ``` What I want is to know the best Django way to fire a `group_by` query to my database, like: ``` Members.objects.all().group_by('designation') ``` Which doesn't work, of course. I know we can do some tricks on `django/db/models/query.py`, but I am just curious to know how to do it without patching.
If you mean to do aggregation you can use the [aggregation features of the ORM](http://docs.djangoproject.com/en/stable/topics/db/aggregation/#topics-db-aggregation): ``` from django.db.models import Count result = (Members.objects .values('designation') .annotate(dcount=Count('designation')) .order_by() ) ``` This results in a query similar to ``` SELECT designation, COUNT(designation) AS dcount FROM members GROUP BY designation ``` and the output would be of the form ``` [{'designation': 'Salesman', 'dcount': 2}, {'designation': 'Manager', 'dcount': 2}] ``` If you don't include the `order_by()`, you may get incorrect results if the default sorting is not what you expect. If you want to include multiple fields in the results, just add them as arguments to `values`, for example: ``` .values('designation', 'first_name', 'last_name') ``` ### References: * Django documentation: [`values()`](https://docs.djangoproject.com/en/stable/ref/models/querysets/#django.db.models.query.QuerySet.values), [`annotate()`](https://docs.djangoproject.com/en/stable/ref/models/querysets/#django.db.models.query.QuerySet.annotate), and [`Count`](https://docs.djangoproject.com/en/stable/ref/models/querysets/#django.db.models.Count) * Django documentation: [Aggregation](https://docs.djangoproject.com/en/stable/topics/db/aggregation), and in particular the section entitled [Interaction with default ordering or `order_by()`](https://docs.djangoproject.com/en/stable/topics/db/aggregation/#interaction-with-default-ordering-or-order-by)
An easy solution, but not the proper way is to use [raw SQL](http://docs.djangoproject.com/en/dev/topics/db/sql/#topics-db-sql): ``` results = Members.objects.raw('SELECT * FROM myapp_members GROUP BY designation') ``` Another solution is to use the `group_by` property: ``` query = Members.objects.all().query query.group_by = ['designation'] results = QuerySet(query=query, model=Members) ``` You can now iterate over the results variable to retrieve your results. Note that `group_by` is not documented and may be changed in future version of Django. And... why do you want to use `group_by`? If you don't use aggregation, you can use `order_by` to achieve an alike result.
How to query as GROUP BY in Django?
[ "", "python", "django", "django-models", "group-by", "" ]
I am reading a result from a MS SQL 2008 Database with a column type of dbtype.time from a datareader, using c# with DAAB 4.0 framework. My problem is the MSDN docs say dbtype.time should map to a timespan but the only close constructor for timespan I see accepts a long, and the result returned from the datareader cannot be cast to a long, or directly to a timespan. I found this [Article](http://blogs.msdn.com/usisvde/archive/2007/11/14/time-for-ado-net.aspx) whichs shows datareader.getTimeSpan() method, but the datareader in daab 4.0 does not seem to have this method. So how do I convert the result from the datareader to a timespan object ?
`GetTimeSpan` is a method of `OleDbDataReader` and `SqlDataReader` (but not of the more generic IDataReader interface which DAAB's `ExecuteReader` returns). I'm assuming that the `IDataReader` instance which DAAB has returned to you is actually an instance of `SqlDataReader`. This allows you to access the `GetTimeSpan` method by casting the `IDataReader` instance appropiately: ``` using (IDataReader dr = db.ExecuteReader(command)) { /* ... your code ... */ if (dr is SqlDataReader) { TimeSpan myTimeSpan = ((SqlDataReader)dr).GetTimeSpan(columnIndex) } else { throw new Exception("The DataReader is not a SqlDataReader") } /* ... your code ... */ } ``` Edit: If the `IDataReader` instance is not a `SqlDataReader` then you might be missing the `provider` attribute of your connection string defined in your app.config (or web.config).
Have you tried a direct cast like this? ``` TimeSpan span = (TimeSpan)reader["timeField"]; ``` I just tested this quickly on my machine and works fine when "timeField" is a Time datatype in the database (SQL).
How to Convert Datareader Result of DbType.Time to Timespan Object?
[ "", "c#", "time", "data-access", "timespan", "daab", "" ]
A list of paragraphs (`<p>`) is given. As soon as the user clicks on paragraph A the class of paragraph A changes to "activated". Now the user selects paragraph B and all the paragraphs between A and B change their class to "activated". By clicking on B again, only A remains with the class "active". By clicking on A the class "active" gets removed on all paragraphs between A and B (including A and B). It shouldn't be possible to "deactivate" any paragraph between A and B. The selection between A and B should always be a uninterrupted list of selected paragraphs. Can anyone give me a hint on how to realize this with Prototype/Scriptaculous? The application is implemented in Rails, so any hint in RJS would even be more appreciated!
OK, in the meantime and with the help of a coworker I came up with an own answer to this problem: ``` <script type="text/javascript"> // holds paragraph A (first selected paragraph) var a_selected = null; // holds paragraph B (second selected paragraph) var b_selected = null; // holds all 'active' paragraphs var selected_paras = []; function class_flipper_init() { // reset paragraphs A and B a_selected = null; b_selected = null; var paragraphs = $$("#foobar p"); paragraphs.each(function(paragraph, index) { // if user clicks on a paragraph paragraph.observe("click", function(event) { // if A and B are 'active': reset everything. if(b_selected != null) { selected_paras.each(function(i) { toggleStyle(i); }) a_selected = null b_selected = null return } // if A is 'active' if(a_selected != null) { // if A is 'active' and selected B is below A: // select all paragraphs between A and B if(a_selected < index) { b_selected = index; for (var i = a_selected + 1; i <= index; i++ ) { toggleStyle(paragraphs[i]) } } // if A is 'active' and selected B is above A: // select all paragraphs between A and B else if(a_selected > index) { b_selected = index; for (var i = a_selected - 1; i >= index; i-- ) { toggleStyle(paragraphs[i]) } } // if A == B else { toggleStyle(paragraph) a_selected = null } } // if A is selected else { a_selected = index; toggleStyle(paragraph) } }); }); } function toggleStyle(paragraph) { // remove active class if (paragraph.hasClassName("active")) { paragraph.removeClassName("active"); selected_paras = selected_paras.without(paragraph) } // set active class else { paragraph.addClassName("active"); selected_paras.push(paragraph) } } </script> ``` `class_flipper_init()` is called everytime the page (or in my case a certain partial) is loaded. Please don't hesitate to submit a solution written in "pure" RJS or something more elegant. :-)
I've tested the code below and it does what you want, although it's a bit convoluted. The key to it is holding the paragraphs in an array, which is achieved using Prototype's [$$](http://www.prototypejs.org/api/utility#method-$$) function. ``` <style type="text/css"> .activated { background-color: yellow; } </style> . . . <div id="container"> <p>This is paragraph 1.</p> <p>This is paragraph 2.</p> <p>This is paragraph 3.</p> <p>This is paragraph 4.</p> <p>This is paragraph 5.</p> <p>This is paragraph 6.</p> </div> <script type="text/javascript"> Event.observe(document, "dom:loaded", function() { var paragraphs = $$("#container p"); paragraphs.each(function(paragraph, index) { paragraph.observe("click", function(event) { // A clicked; toggle activated class on A if (index == 0) { toggleStyle(paragraphs[0]); // A clicked; remove activated class from A + 1 through to B // if present for (var i = 1; i <= paragraphs.length; i++) { if (paragraphs[i] && paragraphs[i].hasClassName("activated")) { paragraphs[i].removeClassName("activated"); } } } // A + 1 clicked; toggle activated class on A + 1 if (index > 0 && paragraphs[0].hasClassName("activated")) { for (var i = 1; i <= index; i++) { toggleStyle(paragraphs[i]); } } }); }); }); function toggleStyle(paragraph) { if (paragraph.hasClassName("activated")) { paragraph.removeClassName("activated"); } else { paragraph.addClassName("activated"); } } </script> ```
Prototype/Scriptaculous: Selecting groups of paragraphs (<p>) by clicking on them
[ "", "javascript", "ruby-on-rails", "dom", "prototypejs", "scriptaculous", "" ]
I used log4j in a java program. I initialized it with : ``` BasicConfigurator.configure(); // logger configuration try { logger.setLevel(Level.DEBUG); } catch (Exception e) { System.out.println("Logfile not found"); } ``` But, during the execution of the program i get 3 log statements instead of one. For example, ``` 3 lines 1047 [main] INFO ibis.Preproc.Ratings - Added AS TIMEZONE to tZones[0] = GMT-12:00 1047 [main] INFO ibis.Preproc.Ratings - Added AS TIMEZONE to tZones[0] = GMT-12:00 1047 [main] INFO ibis.Preproc.Ratings - Added AS TIMEZONE to tZones[0] = GMT-12:00 ``` instead of one line ``` 1047 [main] INFO ibis.Preproc.Ratings - Added AS TIMEZONE to tZones[0] = GMT-12:00 ``` Are there any extra configurations to be done to log4j to avoid this?
I've experienced similar behavior, and it turned out that Log4J was configured more than once; using the BasicConfigurator, but also with a log4j.xml file I had forgotten about. Could it be that there's an additional Log4J configuration somewhere on the classpath?
Most probably you have more than one Appenders. See the log4j [manual](http://logging.apache.org/log4j/1.2/manual.html) (Section: Appenders and Layouts): > Each enabled logging request for a given logger will be forwarded to all the appenders in that logger as well as the appenders higher in the hierarchy. You can try setting the additivity flag to false.
repeated logging in log 4j in java
[ "", "java", "log4j", "" ]
I often find myself doing: ``` foo = foo ?? x; ``` Why can't I do: ``` foo ??= x; ``` **Edit**: I know it's not part of the language... My question is "why not"? I find the necessity to repeat "foo" to be unpleasing and potentially error-prone. It looks just as ugly as: ``` foo = foo + x; ```
The null-coalescing assignment operator `??=` was introduced in C# 8.0 <https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#null-coalescing-assignment>
When I think about it, ``` foo = foo ?? x ``` is really just ``` foo = foo != null ? foo : x ``` and at that point, the analogy to += starts to fall apart.
Why can't I do ??= in C#?
[ "", "c#", "language-features", "" ]
What is the difference between a static member function and an extern "C" linkage function ? For instance, when using "makecontext" in C++, I need to pass a pointer to function. Google recommends using extern "C" linkage for it, because "makecontext" is C. But I found out that using static works as well. Am I just lucky or... ``` class X { public: static void proxy(int i) {} } makecontext(..., (void (*)(void)) X::proxy, ...); ``` vs ``` extern "C" void proxy(int i) {} makecontext(..., (void (*)(void)) proxy, ...); ``` EDIT: Can you show a compiler or architecture where the static member version does not work (and it's not a bug in the compiler) ?
Yes, you are just lucky :) The extern "C" is one language linkage for the C language that every C++ compiler has to support, beside extern "C++" which is the default. Compilers may supports other language linkages. GCC for example supports extern "Java" which allows interfacing with java code (though that's quite cumbersome). extern "C" tells the compiler that your function is callable by C code. That can, but not must, include the appropriate calling convention and the appropriate C language name mangling (sometimes called "decoration") among other things depending on the implementation. If you have a static member function, the calling convention for it is the one of your C++ compiler. Often they are the same as for the C compiler of that platform - so i said you are just lucky. If you have a C API and you pass a function pointer, better always put one to a function declared with extern "C" like ``` extern "C" void foo() { ... } ``` Even though the function pointer type does not contain the linkage specification but rather looks like ``` void(*)(void) ``` The linkage is an integral part of the type - you just can't express it directly without a typedef: ``` extern "C" typedef void(*extern_c_funptr_t)(); ``` The Comeau C++ compiler, in strict mode, will emit an error for example if you try to assign the address of the extern "C" function of above to a `(void(*)())`, beause this is a pointer to a function with C++ linkage.
Note, that `extern C` is the **recommended** way of C/C++ interoperability. [Here](http://www.stroustrup.com/bs_faq2.html#callC) is the master talking about it. To add to eduffy's answer: note that static functions and variables in the global namespace are deprecated. Use an anonymous namespace at least. Back to `extern C`: if you don't use extern C you will have to know the exact mangled name and use it. That is much more of a pain.
static vs extern "C"/"C++"
[ "", "c++", "function-pointers", "static-members", "linkage", "extern-c", "" ]
I have written a class that checks a POP3 account and I'd like it to execute on a thread other than the UI thread. To do this, I've chosen the asynchronous route. In order to get the result from pop3delegate.BeginInvoke(null,null) I need to call EndInvoke but doing this in the UI thread blocks rendering the UI unusable. I could use the IAsyncResult object and check the IsComplete property, but this involves putting in a loop which checks and this in turn locks up the UI. What I'm looking for is a way to get a percentage complete or some sort of a status from the POP3 class, which in turn updates the UI and also allows the UI to be usable to do other tasks. I'll also need to call the EndInvoke method at some point in order to catch any exceptions thrown on the worker thread. Any suggestions?
Try using BackgroundWorker class, its was designed to do exactly what you need. Example and more details on msdn: <http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx>
Try the [Backgroundworker](https://stackoverflow.com/questions/74880/delegating-a-task-in-and-getting-notified-when-it-completes-in-c) class.
Calling synchronous methods asynchronously on the UI thread
[ "", "c#", "multithreading", "asynchronous", "" ]
I am using an api which takes a name of 21 char max to represent an internal session which has a lifetime of around "two days". I would like the name not to be meaningfull using some kind of hasing ? md5 generates 40 chars, is there something else i could use ? For now i use 'userid[:10]' + creation time: ddhhmmss + random 3 chars. Thanks,
If I read your question correctly, you want to generate some arbitrary identifier token which must be 21 characters max. Does it need to be highly resistant to guessing? The example you gave isn't "crytographically strong" in that it can be guessed by searching well less than 1/2 of the entire possible keyspace. You don't say if the characters can be all 256 ASCII characters, or if it needs to be limited to, say, printable ASCII (33-127, inclusive), or some smaller range. There is a Python module designed for [UUID](http://docs.python.org/library/uuid.html)s (Universals Unique IDentifiers). You likely want uuid4 which generates a random UUID, and uses OS support if available (on Linux, Mac, FreeBSD, and likely others). ``` >>> import uuid >>> u = uuid.uuid4() >>> u UUID('d94303e7-1be4-49ef-92f2-472bc4b4286d') >>> u.bytes '\xd9C\x03\xe7\x1b\xe4I\xef\x92\xf2G+\xc4\xb4(m' >>> len(u.bytes) 16 >>> ``` 16 random bytes is very unguessable, and there's no need to use the full 21 bytes your API allows, if all you want is to have an unguessable opaque identifier. If you can't use raw bytes like that, which is probably a bad idea because it's harder to use in logs and other debug messages and harder to compare by eye, then convert the bytes into something a bit more readable, like using base-64 encoding, with the result chopped down to 21 (or whatever) bytes: ``` >>> u.bytes.encode("base64") '2UMD5xvkSe+S8kcrxLQobQ==\n' >>> len(u.bytes.encode("base64")) 25 >>> u.bytes.encode("base64")[:21] '2UMD5xvkSe+S8kcrxLQob' >>> ``` This gives you an extremely high quality random string of length 21. You might not like the '+' or '/' which can be in a base-64 string, since without proper escaping that might interfere with URLs. Since you already think to use "random 3 chars", I don't think this is a worry of yours. If it is, you could replace those characters with something else ('-' and '.' might work), or remove them if present. As others have pointed out, you could use .encode("hex") and get the hex equivalent, but that's only 4 bits of randomness/character \* 21 characters max gives you 84 bits of randomness instead of twice that. Every bit doubles your keyspace, making the theoretical search space much, much smaller. By a factor of 2E24 smaller. Your keyspace is still 2E24 in size, even with hex encoding, so I think it's more a theoretical concern. I wouldn't worry about people doing brute force attacks against your system. **Edit**: P.S.: The uuid.uuid4 function uses libuuid if available. That gets its entropy from os.urandom (if available) otherwise from the current time and the local ethernet MAC address. If libuuid is not available then the uuid.uuid4 function gets the bytes directly from os.urandom (if available) otherwise it uses the random module. The random module uses a default seed based on os.urandom (if available) otherwise a value based on the current time. Probing takes place for every function call, so if you don't have os.urandom then the overhead is a bit bigger than you might expect. Take home message? If you know you have os.urandom then you could do ``` os.urandom(16).encode("base64")[:21] ``` but if you don't want to worry about its availability then use the uuid module.
The hexadecimal representation of MD5 has very poor randomness: you only get 4 bits of entropy per character. Use random characters, something like: ``` import random import string "".join([random.choice(string.ascii_letters + string.digits + ".-") for i in xrange(21)]) ``` In the choice put all the acceptable characters. While using a real hash function such as SHA1 will also get you nice results *if used correctly*, the added complexity and CPU consumption seems not justified for your needs. You only want a random string.
Python and random keys of 21 char max
[ "", "python", "encryption", "key", "" ]
I have a single buffer, and several pointers into it. I want to sort the pointers based upon the bytes in the buffer they point at. qsort() and stl::sort() can be given custom comparision functions. For example, if the buffer was zero-terminated I could use strcmp: ``` int my_strcmp(const void* a,const void* b) { const char* const one = *(const char**)a, const two = *(const char**)b; return ::strcmp(one,two); } ``` however, if the buffer is not zero-terminated, I have to use memcmp() which requires a length parameter. Is there a tidy, efficient way to get the length of the buffer into my comparision function without a global variable?
Is there a reason you can't null-terminate your buffers? If not, since you're using C++ you can write your own function object: ``` struct MyStrCmp { MyStrCmp (int n): length(n) { } inline bool operator< (char *lhs, char *rhs) { return ::strcmp (lhs, rhs, length); } int length; }; // ... std::sort (myList.begin (), myList.end (), MyStrCmp (STR_LENGTH)); ```
With std::sort, you can use a Functor like this: ``` struct CompString { CompString(int len) : m_Len(len) {} bool operator<(const char *a, const char *b) const { return std::memcmp(a, b, m_Len); } private: int m_Len; }; ``` Then you can do this: ``` std::sort(begin(), end(), CompString(4)); // all strings are 4 chars long ``` **EDIT:** from the comment suggestions (i guess both strings are in a common buffer?): ``` struct CompString { CompString (const unsigned char* e) : end(e) {} bool operator()(const unsigned char *a, const unsigned char *b) const { return std::memcmp(a, b, std::min(end - a, end - b)) < 0; } private: const unsigned char* const end; }; ```
memcmp sort
[ "", "c++", "c", "performance", "sorting", "stl", "" ]
My table has the following columns: ``` A | B | C | D | E | F ``` I want to displays this as follow: ``` MyColumn | MyColumn2 A | B C | D E | F ``` As you can see i want to display the columns as pairs with a custom column name. The pairs are Column A and B, column C and D and column C and D.
``` select A as [Col 1], B as [Col 2] from table union all select C,D from table union all select E,F from table ```
This won't scale to a billion columns but... ``` Select A as MyColumn, B as MyColumn2 from Table UNION Select C as MyColumn, D as MyColumn2 from Table UNION Select E as MyColumn, F as MyColumn2 from Table ``` This query will remove the duplicates though. So say there's one record in the table > Hello | World | Hello | World | Hello | World My select will only return > Hello | World Sambo's will return all three...
SQL Convert column to row
[ "", "sql", "row", "" ]
I had an article, but I lost it. It showed and described a couple of C/C++ tricks that people should be careful. One of them interested me but now that I am trying to replicate it I'm not being able to put it to compile. The concept was that it is possible to change by accident the value of a `const` in C/C++ It was something like this: ``` const int a = 3; // I promise I won't change a const int *ptr_to_a = &a; // I still promise I won't change a int *ptr; ptr = ptr_to_a; (*ptr) = 5; // I'm a liar; a is now 5 ``` I wanted to show this to a friend but now I'm missing a step. Does anyone know what's missing for it to start compiling and working? ATM I'm getting **invalid conversion from 'const int\*' to 'int\*'** but when I read the article I tried and it worked great.
you need to cast away the constness: ``` linux ~ $ cat constTest.c #include <stdio.h> void modA( int *x ) { *x = 7; } int main( void ) { const int a = 3; // I promisse i won't change a int *ptr; ptr = (int*)( &a ); printf( "A=%d\n", a ); *ptr = 5; // I'm a liar, a is now 5 printf( "A=%d\n", a ); *((int*)(&a)) = 6; printf( "A=%d\n", a ); modA( (int*)( &a )); printf( "A=%d\n", a ); return 0; } linux ~ $ gcc constTest.c -o constTest linux ~ $ ./constTest A=3 A=5 A=6 A=7 linux ~ $ g++ constTest.c -o constTest linux ~ $ ./constTest A=3 A=3 A=3 A=3 ``` also the common answer doesn't work in g++ 4.1.2 ``` linux ~ $ cat constTest2.cpp #include <iostream> using namespace std; int main( void ) { const int a = 3; // I promisse i won't change a int *ptr; ptr = const_cast<int*>( &a ); cout << "A=" << a << endl; *ptr = 5; // I'm a liar, a is now 5 cout << "A=" << a << endl; return 0; } linux ~ $ g++ constTest2.cpp -o constTest2 linux ~ $ ./constTest2 A=3 A=3 linux ~ $ ``` btw.. this is never recommended... I found that g++ doesn't allow this to happen.. so that may be the issue you are experiencing.
Note any attempt to cast away constness is undefined by the standard. From 7.1.5.1 of the standard: > Except that any class member declared > mutable can be modified, any > attempt to modify a const object > during its lifetime > results in undefined behavior. And right after this example is used: ``` const int* ciq = new const int (3); // initialized as required int* iq = const_cast<int*>(ciq); // cast required *iq = 4; // undefined: modifies a const object ``` So in short what you want to do isn't possible using standard C++. Further when the compiler encounters a declaration like ``` const int a = 3; // I promisse i won't change a ``` it is free to replace any occurance of 'a' with 3 (effectively doing the same thing as `#define a 3`)
C/C++ changing the value of a const
[ "", "c++", "constants", "" ]
I have a C# WPF application that needs to consume data that is exposed on a webpage as a HTML table. [After getting inspiration from this url](http://blogs.msdn.com/bethmassi/archive/2008/04/25/querying-html-with-linq-to-xml.aspx) I tried using Linq to Xml to parse the Html document, but this only works if the HTML document is extremely well formed (and doesn't have any comments or HTML entities inside it). I have managed to get a working solution using this technique, but it is far from ideal. I am after a solution that is intended for parsing HTML. I have hacked "solutions" before, but they are brittle. I am after a robust way of parsing/manipulating the document. I'd ideally like something that makes the task as easy as it would be from Javascript/JQuery. Does anyone know of a good .Net library or utility for parsing/manipulating HTML?
~~Even though it's not LINQ based,~~ I suggest researching the [HTML Agility Pack](https://html-agility-pack.net/) from CodePlex. *Note: Html Agility Pack now supports Linq to Objects (via a LINQ to Xml Like interface)* From the HTML Agility Pack page: > This is an agile HTML parser that builds a read/write DOM and supports plain XPATH or XSLT (you actually don't HAVE to understand XPATH nor XSLT to use it, don't worry...). It is a .NET code library that allows you to parse "out of the web" HTML files. The parser is very tolerant with "real world" malformed HTML. The object model is very similar to what proposes System.Xml, but for HTML documents (or streams).
There's a LINQ to HTML library here: <http://www.superstarcoders.com/linq-to-html.aspx>
C# Is there a LINQ to HTML, or some other good .Net HTML manipulation API?
[ "", "c#", ".net", "linq", "" ]
I'm making a Scorched Earth like game in Java (for my exam project :D), but I have this problem. I'm drawing a window (JFrame), setting layout to BorderLayout, applying an extended JPanel, and packing the window, but after it has been packed, it's showing some extended white space at the left and bottom border. This is my main class: ``` public class Main { public static void main(String[] args) { javax.swing.JFrame frame = new javax.swing.JFrame("game title"); panel p = new panel(new java.awt.Dimension(512, 512)); frame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(new java.awt.BorderLayout()); frame.getContentPane().add(p, java.awt.BorderLayout.CENTER); frame.pack(); frame.setResizable(false); frame.setVisible(true); } } ``` panel is my JPanel class, which in the constructor is setting it's preferred size to the argument (512x512). I've tested this on both Windows and Linux, and the error it at both places, and the size of the white gap differs from OS to OS. This is my panel class: ``` class panel extends javax.swing.JPanel{ panel(java.awt.Dimension size){ setPreferredSize(size); } public void paint(java.awt.Graphics g){ g.setColor(java.awt.Color.BLUE); g.fillRect(0, 0, 512, 512); } } ``` Please help!
I solved the problem by removing: ``` setResizable(false); ```
I've tried to reproduce this without your `panel` class (which needs a better name and should at least be named using CamelCase): ``` import javax.swing.*; public class Main { public static void main(String[] args) { JFrame frame = new JFrame("game title"); JPanel p = new JPanel(); p.setPreferredSize(new java.awt.Dimension(512, 512)); p.setBackground(java.awt.Color.BLUE); frame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(new java.awt.BorderLayout()); frame.getContentPane().add(p, java.awt.BorderLayout.CENTER); frame.pack(); frame.setResizable(false); frame.setVisible(true); } } ``` This produces a window with a blue 512x512 panel in it and no differently-colored border. So the problem must be with your `panel` class.
Java Swing packs the window wrong
[ "", "java", "swing", "" ]
I have a Struts (1.3.8) application that I'd like to convert to Tapestry 5. There will probably not be time to do the whole conversion in one fell swoop. I'd like to deliver new functionality in Tapestry and convert existing Struts / JSPs as time permits. Has anyone attempted something like this? Can Struts and Tapestry co-exist?
Without ever using Tapestry, I'd say that any two frameworks should be able to co-exist because in the `web.xml` you define how the urls map to servlets/filters. For example, in Wicket there is a filter which checks for Wicket classes that implement the request handler. If nothing matches, the request is passed up the chain. This would allow you to continue to use Struts for certain actions. If you have some URLs that you want to preserve, you can just change the Struts action to forward to the new internal URL; eventually all your struts actions will be, essentially, url-rewriting actions, and you can just rip out struts and replace it with a url re-writing filter. If none of your new URLs will conflict with your old urls, then there is nothing difficult to do. Just set up the new framework and its request handlers. When a struts action is encountered (`/doSomething.do`) the Struts `ActionServlet` will dispatch the request to the action. In the `struts-config.xml` you can forward to the right place, either a JSP or a tile or a Tapestry URL. I imagine there is a way, in Tapestry, to forward to an arbitrary url after you're done processing a request; just forward to a Struts action if you need to. The one sticky problem I can foresee is if Struts and Tapestry have conflicting requirements for third-party libs. If that doesn't work you might be seriously out of luck for any kind of easy migration.
If you did Struts the way most people do it, you probably have all of your Struts urls starting with /action or ending with .do. As Mr. Shiny and New pointed out, that means you can filter different URLs with the Tapestry filter and the Struts filter or servlet. I've used both and I would strongly recommend that you try to keep Tapestry from having to deal with Struts URLs. With Struts you can pretty much hand-code the URL so it shouldn't be a problem to link to Tapestry pages, but if you want Tapestry to link back to Struts URLs you may have trouble using it the standard way. Ideally, you can split off a portion of your app (like internal admin functions) and have them be completely independent.
Piecemeal Conversion from Struts to Tapestry 5
[ "", "java", "jsp", "frameworks", "struts", "tapestry", "" ]
I was working on some encryption/decryption algorithms and I noticed that the encrypted byte[] arrays always had a length of 33, and the char[] arrays always had a length of 44. Does anyone know why this is? (I'm using Rijndael encryption.)
[Padding](http://www.di-mgt.com.au/cryptopad.html) and [text encoding](http://en.wikipedia.org/wiki/Binary-to-text_encoding). Most encryption algorithms have a block size, and input needs to be padded up to a multiple of that block size. Also, turning binary data into text usually involves the [Base64 algorithm](http://en.wikipedia.org/wiki/Base64), which expands 3 bytes into 4 characters.
That's certainly not true for all encryption algorithms, it must just be a property of the particular one you're using. Without knowing what algorithm it is, I can only guess, but the ratio 33/44 suggests that the algorithm might be compressing each character into 6 bits in the output byte array. That probably means it's making the assumption that no more than 64 distinct characters are used, which is a good assumption for plain text (in fact, that's how base64 decoding works). But again, without knowing what algorithm you're using, this is all guesswork.
Why does an encrypted byte array have a different length from its char[] representation?
[ "", "c#", "encryption", "" ]
Anyone know of a (reliable) date recurrence calculator, we're trying to implement something in our app which would allow a schedule to be created, similar to those for recurring meetings in Outlook. We have tried chronos but discovered some cases where it breaks down, I'd really appreciate knowing if anyone has successfully used any of the other options out there. Cheers, Robin
This is a frequent question on the joda time mailing list and the usual answer is to try [RFC 2445](http://code.google.com/p/google-rfc-2445/). Disclaimer: I have not used it myself.
Check out Quartz, it's a really handy tool: <http://www.quartz-scheduler.org/>
Whats the best java date recurrence pattern calculator
[ "", "java", "date", "recurrence", "" ]
I am listening for the loaded event of a Page. That event fires first and then all the children fire their load event. I need an event that fires when ALL the children have loaded. Does that exist?
I hear you. I also am missing an out of the box solution in WPF for this. Sometimes you want some code to be executed after all the child controls are loaded. Put this in the constructor of the parent control ``` Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(() => {code that should be executed after all children are loaded} )); ``` Helped me a few times till now.
`Loaded` is the event that fires after all children have been `Initialized`. There is no `AfterLoad` event as far as I know. If you can, move the children's logic to the `Initialized` event, and then `Loaded` will occur after they have all been initialized. See [MSDN - Object Lifetime Events](http://msdn.microsoft.com/en-us/library/ms754221.aspx).
Is there a "All Children loaded" event in WPF
[ "", "c#", ".net", "wpf", "" ]
How do you detect the main hard drive letter such as C: drive?
Try ``` Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.System)); ``` That will return (normally) C:\ But it depends on how you define the "main" hard drive. This will give you the drive Windows is installed on.
This should work (assuming you want the drive that windows is on): ``` string rootDrive = Path.GetPathRoot(Environment.SystemDirectory); ```
How do you detect the main hard drive letter such as C: drive?
[ "", "c#", "" ]