Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have some client-side JavaScript that sets form fields. When the page posts back, those fields are reset. Why is this? Aren't the field values captured and put in the ViewState when the postback occurs? EDIT: When I break the debugger on Page\_Load(), before any code executes after the postback, the form field values are empty.
Are the form elements that are being populated from your client-side javascript set as disabled? If so, ASP.NET will ignore the value. For example: ``` <asp:TextBox ID="TextBox1" Enabled="False" Runat="Server" /> <script type="text/javascript"> document.forms[0].elements["TextBox1"].style.disabled = false; document.forms[0].elements["TextBox1"].value = "Value set from Javascript"; </script> ``` When this code runs, ASP.NET thinks that the textbox is disabled, and therefore discards its value in the postback, so the value of TextBox1.Text will always be blank. As far as I know, this behavior applies to all form elements. If ASP.NET thinks they are disabled, and they are subsquently enabled and populated client-side, the value won't be available on the postback.
Yes. It sounds like you have something else going wrong (perhaps an OnLoad handler that isn't checking the IsPostback field and therefore overwriting your changed values?).
Client-side JS and ASP.NET Postback
[ "", "asp.net", "javascript", "postback", "" ]
Is there any easy way to get the defines (at least the WM\_ stuff) from windows.h in C#?
Sure, you can copy them out of the code listing here at the Pinvoke website: <http://www.pinvoke.net/default.aspx/Enums/WindowsMessages.html>
Another option is to use the PInvoke Interop Assistant. It contains a data base of almost every constant defined via windows.h and provides the ability to translate C header code on the fly. <http://www.codeplex.com/clrinterop>
defines from Windows.h in C#?
[ "", "c#", "winapi", "" ]
## Background I have two objects which have bidirectional association between them in a C# project I am working on. I need to be able to check for value equality (vs reference equality) for a number of reasons (e.g to use them in collections) and so I am implementing IEquatable and the related functions. ## Assumptions * I am using C# 3.0, .NET 3.5, and Visual Studio 2008 (although it shouldn't matter for equality comparison routine issue). ## Constraints Any solution must: * Allow for bidirectional association to remain intact while permitting checking for value equality. * Allow the external uses of the class to call Equals(Object obj) or Equals(T class) from IEquatable and receive the proper behavior (such as in System.Collections.Generic). ## Problem When implementing IEquatable to provide checking for value equality on types with bidirectional association, infinite recursion occurs resulting in a stack overflow. **NOTE:** Similarly, using all of the fields of a class in the GetHashCode calculation will result in a similar infinite recursion and resulting stack overflow issue. --- ## Question **How do you check for value equality between two objects which have bidirectional association without resulting in a stack overflow?** --- ## Code **NOTE:** This code is notional to display the issue, not demonstrate the actual class design I'm using which is running into this problem ``` using System; namespace EqualityWithBiDirectionalAssociation { public class Person : IEquatable<Person> { private string _firstName; private string _lastName; private Address _address; public Person(string firstName, string lastName, Address address) { FirstName = firstName; LastName = lastName; Address = address; } public virtual Address Address { get { return _address; } set { _address = value; } } public virtual string FirstName { get { return _firstName; } set { _firstName = value; } } public virtual string LastName { get { return _lastName; } set { _lastName = value; } } public override bool Equals(object obj) { // Use 'as' rather than a cast to get a null rather an exception // if the object isn't convertible Person person = obj as Person; return this.Equals(person); } public override int GetHashCode() { string composite = FirstName + LastName; return composite.GetHashCode(); } #region IEquatable<Person> Members public virtual bool Equals(Person other) { // Per MSDN documentation, x.Equals(null) should return false if ((object)other == null) { return false; } return (this.Address.Equals(other.Address) && this.FirstName.Equals(other.FirstName) && this.LastName.Equals(other.LastName)); } #endregion } public class Address : IEquatable<Address> { private string _streetName; private string _city; private string _state; private Person _resident; public Address(string city, string state, string streetName) { City = city; State = state; StreetName = streetName; _resident = null; } public virtual string City { get { return _city; } set { _city = value; } } public virtual Person Resident { get { return _resident; } set { _resident = value; } } public virtual string State { get { return _state; } set { _state = value; } } public virtual string StreetName { get { return _streetName; } set { _streetName = value; } } public override bool Equals(object obj) { // Use 'as' rather than a cast to get a null rather an exception // if the object isn't convertible Address address = obj as Address; return this.Equals(address); } public override int GetHashCode() { string composite = StreetName + City + State; return composite.GetHashCode(); } #region IEquatable<Address> Members public virtual bool Equals(Address other) { // Per MSDN documentation, x.Equals(null) should return false if ((object)other == null) { return false; } return (this.City.Equals(other.City) && this.State.Equals(other.State) && this.StreetName.Equals(other.StreetName) && this.Resident.Equals(other.Resident)); } #endregion } public class Program { static void Main(string[] args) { Address address1 = new Address("seattle", "washington", "Awesome St"); Address address2 = new Address("seattle", "washington", "Awesome St"); Person person1 = new Person("John", "Doe", address1); address1.Resident = person1; address2.Resident = person1; if (address1.Equals(address2)) // <-- Generates a stack overflow! { Console.WriteLine("The two addresses are equal"); } Person person2 = new Person("John", "Doe", address2); address2.Resident = person2; if (address1.Equals(address2)) // <-- Generates a stack overflow! { Console.WriteLine("The two addresses are equal"); } Console.Read(); } } } ```
If redesigning the class structure to remove the bidirectional association is possible and reduces the number of problems associated with the implementation, then this is preferred solution. If this redesign is not possible or introduces equal or greater implementation issues, then one possible solution is to use a specialized Equals method to be called by Equals methods of the classes involved in the bidirectional association. As Mehrdad stated, this shouldn't be too big of a deal since the requirements explicitly ask for this coupling, so you are not introducing one by doing this. --- ## Code Here is an implementation of this that keeps the specialized methods checking only their own fields. This reduces maintenance problems vs having each class do a per-property comparison of the other class. ``` using System; namespace EqualityWithBiDirectionalAssociation { public class Person : IEquatable<Person> { private string _firstName; private string _lastName; private Address _address; public Person(string firstName, string lastName, Address address) { FirstName = firstName; LastName = lastName; Address = address; } public virtual Address Address { get { return _address; } set { _address = value; } } public virtual string FirstName { get { return _firstName; } set { _firstName = value; } } public virtual string LastName { get { return _lastName; } set { _lastName = value; } } public override bool Equals(object obj) { // Use 'as' rather than a cast to get a null rather an exception // if the object isn't convertible Person person = obj as Person; return this.Equals(person); } public override int GetHashCode() { string composite = FirstName + LastName; return composite.GetHashCode(); } internal virtual bool EqualsIgnoringAddress(Person other) { // Per MSDN documentation, x.Equals(null) should return false if ((object)other == null) { return false; } return ( this.FirstName.Equals(other.FirstName) && this.LastName.Equals(other.LastName)); } #region IEquatable<Person> Members public virtual bool Equals(Person other) { // Per MSDN documentation, x.Equals(null) should return false if ((object)other == null) { return false; } return (this.Address.EqualsIgnoringPerson(other.Address) // Don't have Address check it's person && this.FirstName.Equals(other.FirstName) && this.LastName.Equals(other.LastName)); } #endregion } public class Address : IEquatable<Address> { private string _streetName; private string _city; private string _state; private Person _resident; public Address(string city, string state, string streetName) { City = city; State = state; StreetName = streetName; _resident = null; } public virtual string City { get { return _city; } set { _city = value; } } public virtual Person Resident { get { return _resident; } set { _resident = value; } } public virtual string State { get { return _state; } set { _state = value; } } public virtual string StreetName { get { return _streetName; } set { _streetName = value; } } public override bool Equals(object obj) { // Use 'as' rather than a cast to get a null rather an exception // if the object isn't convertible Address address = obj as Address; return this.Equals(address); } public override int GetHashCode() { string composite = StreetName + City + State; return composite.GetHashCode(); } internal virtual bool EqualsIgnoringPerson(Address other) { // Per MSDN documentation, x.Equals(null) should return false if ((object)other == null) { return false; } return (this.City.Equals(other.City) && this.State.Equals(other.State) && this.StreetName.Equals(other.StreetName)); } #region IEquatable<Address> Members public virtual bool Equals(Address other) { // Per MSDN documentation, x.Equals(null) should return false if ((object)other == null) { return false; } return (this.City.Equals(other.City) && this.State.Equals(other.State) && this.StreetName.Equals(other.StreetName) && this.Resident.EqualsIgnoringAddress(other.Resident)); } #endregion } public class Program { static void Main(string[] args) { Address address1 = new Address("seattle", "washington", "Awesome St"); Address address2 = new Address("seattle", "washington", "Awesome St"); Person person1 = new Person("John", "Doe", address1); address1.Resident = person1; address2.Resident = person1; if (address1.Equals(address2)) // <-- No stack overflow! { Console.WriteLine("The two addresses are equal"); } Person person2 = new Person("John", "Doe", address2); address2.Resident = person2; if (address1.Equals(address2)) // <-- No a stack overflow! { Console.WriteLine("The two addresses are equal"); } Console.Read(); } } } ``` --- ## Output > The two addresses are equal. > > The two addresses are equal.
You are coupling classes too tightly and mixing values and references. You should either consider checking reference equality for one of the classes or make them aware of each other (by providing an `internal` specialized `Equals` method for the specific class or manually checking value equality of the other class). This shouldn't be a big deal since your requirements explicitly ask for this coupling so you are not introducing one by doing this.
Value Equality with Bidirectional Association in C#
[ "", "c#", ".net", "equals", "iequatable", "" ]
I have a .jar file I'm putting together. I want to create a really really simple .properties file with configurable things like the user's name & other stuff, so that they can hand-edit rather than my having to include a GUI editor. What I'd like to do is to be able to search, in this order: 1. a specified properties file (`args[0]`) 2. MyApp.properties in the current directory (the directory from which Java was called) 3. MyApp.properties in the user's directory (the [user.home](http://www.mindspring.com/~mgrand/java-system-properties.htm) system property?) 4. MyApp.properties in the directory where the application .jar is stored I know how to access #1 and #3 (I think), but how can I determine at runtime #2 and #4?
#2 is the ["user.dir"](http://java.sun.com/javase/6/docs/api/java/lang/System.html#getProperties()) system property. #3 is the "user.home" property. #4 is a bit of a kludge no matter how you approach it. Here's an alternate technique that works if you have a class loaded from a JAR not on the system classpath. ``` CodeSource src = MyClass.class.getProtectionDomain().getCodeSource(); if (src != null) { URL url = new URL(src.getLocation(), "MyApp.properties"); ... } else { /* Fail... */ } ```
For 4, you could try this. Get the classpath: ``` String classpath = System.getProperty("java.class.path"); ``` Then search it for the name of your application jar: ``` int jarPos = classpath.indexOf("application.jar"); ``` Parse out the path leading up to it: ``` int jarPathPos = classpath.lastIndexOf(File.pathSeparatorChar, jarPos) + 1; String path = classpath.substring(jarPathPos, jarPos); ``` Then append `MyApp.properties`. Make sure to check for `jarPos == -1`, meaning the jar isn't found if the classpath (perhaps when running in your dev environment).
Accessing properties files outside the .jar?
[ "", "java", "properties", "jar", "" ]
Is it possible to update the URL of an rss `<link>` tag dynamically, so that when the RSS icon in the location bar is clicked, the browser will direct the user to the updated URL? For example, using Jquery: ``` <link id="feed_url" rel="alternate" type="application/rss+xml" title="RSS" href="/feed" /> <script type="text/javascript"> $("#feed_url").attr("href", "/feed?foo=bar"); </script> ``` The user should now be redirected to `/feed?foo=bar` rather than `/foo`. Note, the values in the query string are determined on the fly on the client-side so the URL must be updated through Javascript. I cannot determine these values on the server side.
Many browsers will parse the link tag on DocumentComplete and not reparse it later if it changes. So technically it may be updated, but the browser may not notice. You'll have to test in different browsers.
Why would you use javascript to update the URL? Why not just change the HTML? You're changing the template/view in order to add the JavaScript, so I don't really see any advantage to sending the browser the wrong feed address, and then using JavaScript of all things to correct the address. If you want to dynamically generate/change the RSS link, that should be done server-side. You could store the feed addresses for different page in the database and insert them into the page dynamically when the page is requested. e.g. ``` <link id="feed_url" rel="alternate" type="application/rss+xml" title="<? echo $page['RSS']['title'] ?>" href="<? echo $page['RSS']['url'] ?>" /> ```
Updating RSS <link> URL with Javascript?
[ "", "javascript", "rss", "" ]
I have to keep thousands of strings in memory to be accessed serially in Java. Should I store them in an array or should I use some kind of List ? Since arrays keep all the data in a contiguous chunk of memory (unlike Lists), would the use of an array to store thousands of strings cause problems ?
I suggest that you use a profiler to test which is faster. My personal opinion is that you should use Lists. I work on a large codebase and a previous group of developers used arrays **everywhere**. It made the code very inflexible. After changing large chunks of it to Lists we noticed no difference in speed.
The Java way is that you should consider what data *abstraction* most suits your needs. Remember that in Java a List is an abstract, not a concrete data type. You should declare the strings as a List, and then initialize it using the ArrayList implementation. ``` List<String> strings = new ArrayList<String>(); ``` This separation of Abstract Data Type and specific implementation is one the key aspects of object oriented programming. An ArrayList implements the List Abstract Data Type using an array as its underlying implementation. Access speed is virtually identical to an array, with the additional advantages of being able to add and subtract elements to a List (although this is an O(n) operation with an ArrayList) and that if you decide to change the underlying implementation later on you can. For example, if you realize you need synchronized access, you can change the implementation to a Vector without rewriting all your code. In fact, the ArrayList was specifically designed to replace the low-level array construct in most contexts. If Java was being designed today, it's entirely possible that arrays would have been left out altogether in favor of the ArrayList construct. > Since arrays keep all the data in a contiguous chunk of memory (unlike Lists), would the use of an array to store thousands of strings cause problems ? In Java, all collections store only references to objects, not the objects themselves. Both arrays and ArrayList will store a few thousand references in a contiguous array, so they are essentially identical. You can consider that a contiguous block of a few thousand 32-bit references will always be readily available on modern hardware. This does not guarantee that you will not run out of memory altogether, of course, just that the contiguous block of memory requirement is not difficult to fufil.
Array or List in Java. Which is faster?
[ "", "java", "arrays", "list", "performance", "" ]
Does JavaScript have a built-in function like PHP's `addslashes` (or `addcslashes`) function to add backslashes to characters that need escaping in a string? For example, this: > This is a demo string with > 'single-quotes' and "double-quotes". ...would become: > This is a demo string with > \'single-quotes\' and > \"double-quotes\".
<http://locutus.io/php/strings/addslashes/> ``` function addslashes( str ) { return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0'); } ```
You can also try this for the double quotes: ``` JSON.stringify(sDemoString).slice(1, -1); JSON.stringify('my string with "quotes"').slice(1, -1); ```
Escaping Strings in JavaScript
[ "", "javascript", "string", "escaping", "quotes", "backslash", "" ]
I want to comment out all calls to an API (java.util.Logging, in my case) in my codebase. Is there a good library to accomplish this easily? I tried Eclipse ASTParser, but that is tied to Eclipse. I am now struggling with PMD's parser. I haven't yet looked at it, but can Jackpot do this? Any other suggestions?
If you wanted to comment out this: ``` Log.doLog("Here is a" /* With a block comment to make it hard */ + " multiline log statement" ); doSomethingEssential(); ``` then you'd have a trickier time of it because you'd need to parse the code to some extend to know where to put the comments. I.e. you want to be able to do this: ``` // Log.doLog("Here is a" /* With a block comment to make it hard */ // + " multiline log statement" // ); // Line break inserted here doSomethingEssential(); ``` It's much more trivial to do this instead: ``` if (false) Log.doLog("Here is a" /* With a block comment to make it hard */ + " multiline log statement" ); ``` The 'if false' part ends up being optimised out by the compiler and the Log statement won't make it to the final .class file. That way all you need is a search/replace step in your build script that replaces all occurences of ``` "Log.doLog(" ``` with either ``` "if (false) Log.doLog(" or "if (true) Log.doLog(" ``` without resorting to tricky parsing of the code.
I know this isn't what you asked for, but I just want to draw your attention to the fact that you can turn logging [OFF](http://java.sun.com/j2se/1.5.0/docs/api/java/util/logging/Level.html#OFF) in your configuration file.
How to comment out calls to a specific API in Java source code
[ "", "java", "parsing", "" ]
I have an string array filled with words from a sentence. ``` words[0] = "the" words[1] = "dog" words[2] = "jumped" words[3] = "over" words[4] = "the" words[5] = "wall." words[6] = "the" words[7] = "cat" words[8] = "fell" words[9] = "off" words[10] = "the" words[10] = "house." ``` etc. (Stupid example, but it works for this) Each word will be a key with it's following word as it's value. so "over" => "the". Some keys can have multiple values. For example, "the" => "dog" || "wall" || "cat" || "house". The value is randomly chosen from those for that key. When the program runs it picks a word at random and makes a sentence. So it could be something like: "the cat fell off the dog". I tried implementing a map (map myMap;) but this allows only one value per key (I think). Hope I explained this right.
you can use a multimap from the STL and use the call ``` pair<iterator, iterator> equal_range(const key_type& k) ``` to get a range of iterators that match your key personally i find this slightly clunky due to having to deal with iterator ranges rather than just getting an object back that represents all values for that key. to get around that you could also store a vector in a regular map and add your strings to the vector.
[`std::multimap`](http://en.cppreference.com/w/cpp/container/multimap) The link provides an excellent example. Quoted below: ``` int main() { multimap<const char*, int, ltstr> m; m.insert(pair<const char* const, int>("a", 1)); m.insert(pair<const char* const, int>("c", 2)); m.insert(pair<const char* const, int>("b", 3)); m.insert(pair<const char* const, int>("b", 4)); m.insert(pair<const char* const, int>("a", 5)); m.insert(pair<const char* const, int>("b", 6)); cout << "Number of elements with key a: " << m.count("a") << endl; cout << "Number of elements with key b: " << m.count("b") << endl; cout << "Number of elements with key c: " << m.count("c") << endl; cout << "Elements in m: " << endl; for (multimap<const char*, int, ltstr>::iterator it = m.begin(); it != m.end(); ++it) cout << " [" << (*it).first << ", " << (*it).second << "]" << endl; } ```
I need to have a key with multiple values. What datastructure would you recommend?
[ "", "c++", "data-structures", "key", "" ]
What is the line ``` #!/usr/bin/env python ``` in the first line of a python script used for?
In UNIX and Linux this tells which binary to use as an interpreter (see also [Wiki page](http://en.wikipedia.org/wiki/Shebang_(Unix))). For example shell script is interpreted by `/bin/sh`. ``` #!/bin/sh ``` Now with python it's a bit tricky, because you can't assume where the binary is installed, nor which you want to use. Thus the `/usr/bin/env` trick. It's use whichever python binary is first in the `$PATH`. You can check that executing `which python` With the interpreter line you can run the script by chmoding it to executable. And just running it. Thus with script beginning with ``` #!/usr/bin/env python ``` these two methods are equivalent: ``` $ python script.py ``` and (assuming that earlier you've done `chmod +x script.py`) ``` $ ./script.py ``` --- This is useful for creating system wide scripts. ``` cp yourCmd.py /usr/local/bin/yourCmd chmod a+rx /usr/local/bin/yourCmd ``` And then you call it from anywhere just with ``` yourCmd ```
This is called a [shebang](http://en.wikipedia.org/wiki/Shebang_(Unix)) line: > In computing, a shebang (also called a hashbang, hashpling, or pound bang) refers to the characters "#!" when they are the first two characters in a text file. Unix-like operating systems take the presence of these two characters as an indication that the file is a script, and try to execute that script using the interpreter specified by the rest of the first line in the file. For instance, shell scripts for the Bourne shell start with the first line:
Python source header comment
[ "", "python", "unix", "shebang", "" ]
The first parameter to a C# extension method is the instance that the extension method was called on. I have adopted an idiom, without seeing it elsewhere, of calling that variable "self". I would not be surprised at all if others are using that as well. Here's an example: ``` public static void Print(this string self) { if(self != null) Console.WriteLine(self); } ``` However, I'm starting to see others name that parameter "@this", as follows: ``` public static void Print(this string @this) { if(@this != null) Console.WriteLine(@this); } ``` And as a 3rd option, some prefer no idiom at all, saying that "self" and "@this" don't give any information. I think we all agree that *sometimes* there is a clear, meaningful name for the parameter, specific to its purpose, which is better than "self" or "@this". Some go further and say you can *always* come up with a more valuable name. So this is another valid point of view. **What other idioms have you seen? What idiom do you prefer, and why?**
I have seen obj and val used. I do not like @this. We should try to avoid using keywords. I have never seen self but I like it.
I name it fairly normally, based on the use. So "source" for the source sequence of a LINQ operator, or "argument"/"parameter" for an extension doing parameter/argument checking, etc. I don't think it has to be particularly related to "this" or "self" - that doesn't give any extra information about the *meaning* of the parameter. Surely that's the most important thing. EDIT: Even in the case where there's not a lot of obvious meaning, I'd prefer *some* meaning to *none*. What information is conferred by "self" or "@this"? Merely that it's the first parameter in an extension method - and that information is already obvious by the fact that the parameter is decorated with `this`. In the example case where `theStringToPrint`/`self` option is given, I'd use `outputText` instead - it conveys everything you need to know about the parameter, IMO.
What idiom (if any) do you prefer for naming the "this" parameter to extension methods in C#, and why?
[ "", "c#", ".net", "c#-3.0", "extension-methods", "idioms", "" ]
I want to read the contents of following file types using C#: 1. RTF 2. PDF 3. HTML 4. MS Word Is there any common API in .Net for reading all file type contents?
There is no built in support for reading most of those file types. HTML is plain text so you can use the System.IO/StreamReader to read it, but you must parse it yourself. There are third party components which will read these file types, but I am not sure if there is one all encompassing component. For PDFs, I believe [iTextSharp](http://itextsharp.sourceforge.net/) allows you to read. For RTF/Word, You can use the [Primary Interop Assemblies](http://msdn.microsoft.com/en-us/library/aax7sdch.aspx)
I've used [Aspose](http://www.aspose.com/) before it's a very powerful product it's reasonably pricey so would only recommend it if your application also needs to create new word/pdf/rtf documents. I agree with the other comments about just using System.IO for reading HTML files.
Reading file contents using C#
[ "", "c#", "file", "" ]
When I run an sql query using the ZF wrappers, all the numeric values return as strings. What do I need to change so the values will return in the same data type as they are in the DB?
I implemented a lot of the `Zend_Db` code in Zend Framework. As other have stated, the reason that `Zend_Db` returns strings instead of native PHP integers or floats is that PHP's database extensions return strings. And the reason for that is that there might be no native PHP type to represent certain database type. For example, MySQL's `BIGINT` is a 64-bit signed integer. By default, the PHP `int` type is limited to 32-bit values, so if you fetch data from the database and implicitly convert it to `int`, some values might be truncated. There are several other similar cases, for `float` and dates, etc. Using the string representation for all data types is the best way to remain simple and consistent, be safe about avoiding data loss, and avoid writing lots of vendor-specific special-case code to do data type mapping. That extra code would incur a performance penalty, too. So if you have specific cases where you need database results to be mapped to native PHP data types, you should implement it yourself in your application code (e.g. in a custom `Zend_Db_Table_Row` class).
Databases typically return result sets as text. Unless your db adaptor converts things for you (and to sounds like yours does not), all values will come back as strings--dates, enums, etc. as well as integers. If you are dealing with a small number of tables with only a few integer fields, just hand convert them. If you are dealing with a slightly more complex situation, you could iterate through the columns using the database definitions (see `sqlite_fetch_column_types()`, etc.). If your situation is more complex than seems reasonable for these solutions, consider switching to a more featureful framework.
fetching an Integer from DB using Zend Framework returns the value as a string
[ "", "php", "mysql", "zend-framework", "" ]
Pointer to members are not used very much but they are really powerful, how have you used them and what's the coolest things you've done? **Edit:** This is not so much to list things that are possible, for example listing *boost::bind* and *boost::function* aren't good. Instead maybe a cool usage with them? I know they're very cool in themselves but that's not what this is about.
I once was needed to operate with criteria data as pure structure to be able to store the list of all criteria in the queue. And I had to bind the structure with the GUI and other filter elements, etc. So I came up with the solution where pointers to members are used as well as pointers to member functions. Let's say you have an ``` struct Criteria { typedef std::string Criteria::* DataRefType; std::string firstname; std::string lastname; std::string website; }; ``` Than you can wrap criteria field and bind with the string representation of the field with ``` class Field { public: Field( const std::string& name, Criteria::DataRefType ref ): name_( name ), ref_( ref ) {} std::string getData( const Criteria& criteria ) { return criteria.*ref_; } std::string name_; private: Criteria::DataRefType ref_; }; ``` Then you can register all the fields to use whenever you want: GUI, serialization, comparison by field names, etc. ``` class Fields { public: Fields() { fields_.push_back( Field( "First Name", &Criteria::firstname ) ); fields_.push_back( Field( "Last Name", &Criteria::lastname ) ); fields_.push_back( Field( "Website", &Criteria::website ) ); } template < typename TFunction > void forEach( TFunction function ) { std::for_each( fields_.begin(), fields_.end(), function ); } private: std::vector< Field > fields_; }; ``` By calling for instance `fields.forEach( serialization );` or ``` GuiWindow( Criteria& criteria ): criteria_( criteria ) { fields_.forEach( std::bind1st( std::mem_fun( &GuiWindow::bindWithGui ), this ) ); } void bindWithGui( Field field ) { std::cout << "name " << field.name_ << " value " << field.getData( criteria_ ) << std::endl; }; ```
Pointers to member function are great for creating psuedo lamba expressions with for\_each ``` vector<SomeClass*> v = getAVector(); for_each(v.begin(), v.end(), mem_fun(&SomeClass::print)); ```
What's the best use you've had with pointer to members and member functions?
[ "", "c++", "" ]
I'm looking for a good parser generator that I can use to read a custom text-file format in our large commercial app. Currently this particular file format is read with a handmade recursive parser but the format has grown and complexified to the point where that approach has become unmanageable. It seems like the ultimate solution would be to build a proper grammar for this format and then use a real parser generator like yacc to read it, but I'm having trouble deciding which such generator to use or even if they're worth the trouble at all. I've looked at ANTLR and Spirit, but our project has specific constraints beyond [earlier answers](https://stackoverflow.com/questions/428892/what-parser-generator-do-you-recommend) that make me wonder if they're as appropriate for us. In particular, I need: * **A parser that generates C or C++ code with MSVC.** ANTLR 3 doesn't support C++; it claims to generate straight C but the docs on getting it to actually work are sort of confusing. * **Severely constrained memory usage.** Memory is at a huge premium in our app and even tiny leaks are fatal. I need to be able to override the parser's memory allocator to use our custom malloc(), or at the very least I need to give it a contiguous pool from which it draws all its memory (and which I can deallocate en bloc afterwards). I can spare about 200kb for the parser executable itself, but whatever dynamic heap it allocates in parsing has to get freed afterwards. * **Good performance.** This is less critical but we ought to be able to parse 100kb of text in no more than a second on a 3ghz processor. * **Must be GPL-free.** We can't use GNU code. I like ANTLRworks' IDE and debugging tools, but it looks like getting its C target to actually work with our app will be a huge undertaking. Before I embark on that palaver, is ANTLR the right tool for this job? The text format in question looks something like: ``` attribute "FluxCapacitance" real constant asset DeLorean { //comment foo bar baz model "delorean.mdl" animation "gullwing.anm" references "Marty" loadonce } template TimeMachine { attribute FluxCapacitance 10 asset DeLorean } ```
> ANTLR 3 doesn't support C++; it claims > to generate straight C but the docs on > getting it to actually work are sort > of confusing. It does generate C, and furthermore, it works with Visual Studio and C++. I know this because I've done it before and submitted a patch to get it to work with stdcall. > Memory is at a huge premium in our app > and even tiny leaks are fatal. I need > to be able to override the parser's > memory allocator to use our custom > malloc(), or at the very least I need > to give it a contiguous pool from > which it draws all its memory (and > which I can deallocate en bloc > afterwards). I can spare about 200kb > for the parser executable itself, but > whatever dynamic heap it allocates in > parsing has to get freed afterwards. The antlr3c runtime, last time I checked does not have a memory leak, and uses the Memory pool paradigm which you describe. However, it does have one shortcoming in the API which the author refuses to change, which is that if you request the string of a node, it will create a new copy each time until you free the entire parser. I have no comment on the ease of using a custom malloc, but it does have a macro to define what malloc function to use in the entire project. As for the executable size, my compilation was about 100 kb in size including a small interpreter. My suggestion to you is to keep learning ANTLR, because it still fits your requirements and you probably need to sacrifice a little more time before it will start working for you.
We use [Boost Spirit](http://spirit.sourceforge.net/) successfully in our application. The [Boost license](http://www.boost.org/LICENSE_1_0.txt) is a very liberal one, so there is no problem using it in commercial applications. [Quote from the documentation:](http://spirit.sourceforge.net/distrib/spirit_1_8_5/libs/spirit/doc/introduction.html) > Spirit is an object-oriented recursive-descent parser generator framework implemented using template meta-programming techniques. Expression templates allow us to approximate the syntax of Extended Backus-Normal Form (EBNF) completely in C++. > The Spirit framework enables a target grammar to be written exclusively in C++. Inline EBNF grammar specifications can mix freely with other C++ code and, thanks to the generative power of C++ templates, are immediately executable. In retrospect, conventional compiler-compilers or parser-generators have to perform an additional translation step from the source EBNF code to C or C++ code.
Is the ANTLR parser generator best for a C++ app with constrained memory?
[ "", "c++", "c", "parsing", "antlr", "" ]
I have a SQL Server table that contains users & their grades. For simplicity's sake, lets just say there are 2 columns - `name` & `grade`. So a typical row would be Name: "John Doe", Grade:"A". I'm looking for one SQL statement that will find the percentages of all possible answers. (A, B, C, etc...) Also, is there a way to do this without defining all possible answers (open text field - users could enter 'pass/fail', 'none', etc...) The final output I'm looking for is A: 5%, B: 15%, C: 40%, etc...
I have tested the following and this does work. The answer by gordyii was close but had the multiplication of 100 in the wrong place and had some missing parenthesis. ``` Select Grade, (Count(Grade)* 100 / (Select Count(*) From MyTable)) as Score From MyTable Group By Grade ```
1. The most efficient (using over()). ``` select Grade, count(*) * 100.0 / sum(count(*)) over() from MyTable group by Grade ``` 2. Universal (any SQL version). ``` select Grade, count(*) * 100.0 / (select count(*) from MyTable) from MyTable group by Grade; ``` 3. With CTE, the least efficient. ``` with t(Grade, GradeCount) as ( select Grade, count(*) from MyTable group by Grade ) select Grade, GradeCount * 100.0/(select sum(GradeCount) from t) from t; ```
How to calculate percentage with a SQL statement
[ "", "sql", "sql-server", "t-sql", "" ]
What is the sizeof the union in C/C++? Is it the sizeof the largest datatype inside it? If so, how does the compiler calculate how to move the stack pointer if one of the smaller datatype of the union is active?
The Standard answers all questions in section 9.5 of the C++ standard, or section 6.5.2.3 paragraph 5 of the C99 standard (or paragraph 6 of the C11 standard, or section 6.7.2.1 paragraph 16 of the C18 standard): > In a union, at most one of the data members can be active at any time, that is, the value of at most one of the data members can be stored in a union at any time. [Note: one special guarantee is made in order to simplify the use of unions: If a POD-union contains several POD-structs that share a common initial sequence (9.2), and if an object of this POD-union type contains one of the POD-structs, it is permitted to inspect the common initial sequence of any of POD-struct members; see 9.2. ] The size of a union is sufficient to contain the largest of its data members. Each data member is allocated as if it were the sole member of a struct. That means each member share the same memory region. There *is* at most one member active, but you can't find out which one. You will have to store that information about the currently active member yourself somewhere else. Storing such a flag in addition to the union (for example having a struct with an integer as the type-flag and an union as the data-store) will give you a so called "discriminated union": An union which knows what type in it is currently the "active one". One common use is in lexers, where you can have different tokens, but depending on the token, you have different informations to store (putting `line` into each struct to show what a common initial sequence is): ``` struct tokeni { int token; /* type tag */ union { struct { int line; } noVal; struct { int line; int val; } intVal; struct { int line; struct string val; } stringVal; } data; }; ``` The Standard allows you to access `line` of each member, because that's the common initial sequence of each one. There exist compiler extensions that allow accessing all members disregarding which one currently has its value stored. That allows efficient reinterpretation of stored bits with different types among each of the members. For example, the following may be used to dissect a float variable into 2 unsigned shorts: ``` union float_cast { unsigned short s[2]; float f; }; ``` That can come quite handy when writing low-level code. If the compiler does not support that extension, but you do it anyway, you write code whose results are not defined. So be certain your compiler has support for it if you use that trick.
A `union` always takes up as much space as the largest member. It doesn't matter what is currently in use. ``` union { short x; int y; long long z; } ``` An instance of the above `union` will always take at least a `long long` for storage. *Side note*: As noted by [Stefano](https://stackoverflow.com/questions/740577/sizeof-a-union-in-c-c/740653#740653), the actual space any type (`union`, `struct`, `class`) will take does depend on other issues such as alignment by the compiler. I didn't go through this for simplicity as I just wanted to tell that a union takes the biggest item into account. **It's important to know that the actual size *does* depend on alignment**.
sizeof a union in C/C++
[ "", "c++", "c", "sizeof", "unions", "" ]
For a while I had been running JavaScript component initialization by waiting for the "onload" event to fire and executing a `main()` of sorts. It seemed cleaner and you could be sure the ID state of your DOM was in order. But after some time of putting that through its paces I found that the component's initialization was choked off by any sort of resource hanging during the load (images, css, iframes, flash, etc.). Now I have moved the initialization invocation to the end of the HTML document itself using inlined `<script />` execution and found that it pushes the initialization before other external resources. Now I wonder if there are some pitfalls that come with doing that instead of waiting for the "onload". Which method are you using? **EDIT**: Thanks. It seems each library has a specialized function for `DOMContentLoaded`/`readyState` implementation differences. I use prototype so [this](http://www.prototypejs.org/api/document/observe) is what I needed.
For me, we use jquery, and its document ready state ensures that the DOM is loaded, but is not waiting for resources like you say. You can of course to this without a javascript framework, it does require a function you can create for example: [document ready](http://snipplr.com/view/6156/documentready/) Now, for the most part putting script at the end of the page sure ensure the rest of the page is there, but making sure the DOM is ready is never a bad thing.
Jquery has $(document).ready() The ideal point at which to run most scripts is when the document is ready, and not necessarily when it is "loaded". [See here](http://encosia.com/2009/03/25/document-ready-and-pageload-are-not-the-same/)
Initializing JS components at the end of HTML or on "onload"?
[ "", "javascript", "ajax", "initialization", "" ]
I have the following simple scenario: A DialogForm with a Button, the Button\_click throws an exception. A MainForm with a button and a Label, in the click I show a new instance of the DialogForm inside a Catch block. If I run this setup in regular WinForms, I can catch the Exception as expected. If I run this in WinMobile (I've tested on WM5 and WM6 Pro) I can see with a Debugger that the Catch block is entered but the Exception keeps propagating up and the App dies. The code in MainForm looks like this: ``` try { using (DialogForm frm = new DialogForm()) { DialogResult r = frm.ShowDialog(); label1.Text = r.ToString(); } } catch (Exception ex) { label1.Text = ex.Message; } ``` ### Edit: I investigated a little further, with a catch {} block around this code and around Application.Run() and the app still quits. Apparently it is **not** a runaway Exception, that is caught and handled just fine. But after this operation it looks like the Application performs an unwanted Exit().
After tinkering on I found something that works: ``` try { // show Dialog that Throws } catch (Exception ex) { label1.Text = ex.Message; Application.DoEvents(); // this solves it } ``` The bounty is still open for anyone who can tell me **why** the DoEvents() is necessary.
The reason you need 'DoEvents' is that this clears the message que while the form is still available. What is happening is that there are still messages waiting to be processed against the form throwing the exception. By calling 'DoEvents' here you are alowing them to be processed before the using block cleans up the form and stops the messages on the que from being processed.
WindowsMobile: Application Exits after handling Exception from DialogForm
[ "", "c#", "winforms", "exception", "windows-mobile", "" ]
Is there a way to generate an arbitrary number of rows that can be used in a JOIN similar to the Oracle syntax: ``` SELECT LEVEL FROM DUAL CONNECT BY LEVEL<=10 ```
Hate to say this, but `MySQL` is the only `RDBMS` of the big four that doesn't have this feature. In `Oracle`: ``` SELECT * FROM dual CONNECT BY level < n ``` In `MS SQL` (up to `100` rows): ``` WITH hier(row) AS ( SELECT 1 UNION ALL SELECT row + 1 FROM hier WHERE row < n ) SELECT * FROM hier ``` or using hint up to `32768` ``` WITH hier(row) AS ( SELECT 1 UNION ALL SELECT row + 1 FROM hier WHERE row < 32768 ) SELECT * FROM hier OPTION (MAXRECURSION 32767) -- 32767 is the maximum value of the hint ``` In `PostgreSQL`: ``` SELECT * FROM generate_series (1, n) ``` In `MySQL`, nothing.
In MySql, it is my understand that you can get more than one row with a SELECT with no table (or DUAL). Therefore, to get multiple rows, you *do* need a real or temporary table with at least the required number of rows. However, *you do not need to build a temporary table* as you can use *ANY* existing table which has at least the number of rows required. So, if you have a table with at least the required number of rows, use: ``` SELECT @curRow := @curRow + 1 AS row_number FROM sometable JOIN (SELECT @curRow := 0) r WHERE @curRow<100; ``` Just replace "sometable" with the name of any table of yours with at least the required number of rows. PS: The "r" is a table "alias": I could have used "AS r". Any subquery in a FROM or JOIN clause creates a "derived table" which, as with all tables, must have a name or alias. (See MySql manual: 13.2.9.8. Subqueries in the FROM Clause)
How do I make a row generator in MySQL?
[ "", "sql", "mysql", "generator", "" ]
New to this website, so let me know if I'm not posting in an accepted manner. I've frequently coded something along the lines of the sample below(with stuff like Dispose ommited for clarity. ). My question is, are the volatiles needed as shown? Or does the ManualResetEvent.Set have an implicit memory barrier as I've read Thread.Start does? Or would an explicit MemoryBarrier call be better than the volatiles? Or is it completely wrong? Also, the fact that the "implicit memory barrier behavior" in some operations is not documented as far as I've seen is quite frutrating, is there a list of these operations somewhere? Thanks, Tom : ``` class OneUseBackgroundOp { // background args private string _x; private object _y; private long _z; // background results private volatile DateTime _a private volatile double _b; private volatile object _c; // thread control private Thread _task; private ManualResetEvent _completedSignal; private volatile bool _completed; public bool DoSomething(string x, object y, long z, int initialWaitMs) { bool doneWithinWait; _x = x; _y = y; _z = z; _completedSignal = new ManualResetEvent(false); _task = new Thread(new ThreadStart(Task)); _task.IsBackground = true; _task.Start() doneWithinWait = _completedSignal.WaitOne(initialWaitMs); return doneWithinWait; } public bool Completed { get { return _completed; } } /* public getters for the result fields go here, with an exception thrown if _completed is not true; */ private void Task() { // args x, y, and z are written once, before the Thread.Start // implicit memory barrier so they may be accessed freely. // possibly long-running work goes here // with the work completed, assign the result fields _a, _b, _c here _completed = true; _completedSignal.Set(); } } ```
Note that this is off the cuff, without studying your code closely. I don't *think* Set performs a memory barrier, but I don't see how that's relevant in your code? Seems like more important would be if Wait performs one, which it does. So unless I missed something in the 10 seconds I devoted to looking at your code, I don't believe you need the volatiles. Edit: Comments are too restrictive. I'm now referring to Matt's edit. Matt did a good job with his evaluation, but he's missing a detail. First, let's provide some definitions of things thrown around, but not clarified here. A volatile read reads a value and then invalidates the CPU cache. A volatile write flushes the cache, and then writes the value. A memory barrier flushes the cache and then invalidates it. The .NET memory model ensures that all writes are volatile. Reads, by default, are not, unless an explicit VolatileRead is made, or the volatile keyword is specified on the field. Further, interlocked methods force cache coherency, and all of the synchronization concepts (Monitor, ReaderWriterLock, Mutex, Semaphore, AutoResetEvent, ManualResetEvent, etc.) call interlocked methods internally, and thus ensure cache coherency. Again, all of this is from Jeffrey Richter's book, "CLR via C#". I said, initially, that I didn't *think* Set performed a memory barrier. However, upon further reflection about what Mr. Richter said, Set would be performing an interlocked operation, and would thus also ensure cache coherency. I stand by my original assertion that volatile is not needed here. Edit 2: It looks as if you're building a "future". I'd suggest you look into [PFX](http://www.microsoft.com/downloads/details.aspx?FamilyId=348F73FD-593D-4B3C-B055-694C50D2B0F3&displaylang=en), rather than rolling your own.
The volatile keyword should not confused as to making \_a, \_b, and \_c thread-safe. See [here](https://stackoverflow.com/questions/154551/volatile-vs-interlocked-vs-lock) for a better explanation. Further, the ManualResetEvent does not have any bearing on the thread-safety of \_a, \_b, and \_c. You have to manage that separately. EDIT: With this edit, I am attempting to distill all of the information that has been put in various answers and comments regarding this question. The basic question is whether or not the result variables (\_a, \_b, and \_c) will be 'visible' at the time the flag variable (\_completed) returns true. For a moment, let's assume that none of the variables are marked volatile. In this case, it would be possible for the result variables to be set ***after*** the flag variable is set in Task(), like this: ``` private void Task() { // possibly long-running work goes here _completed = true; _a = result1; _b = result2; _c = result3; _completedSignal.Set(); } ``` This is clearly not what we want, so how do we deal with this? If these variables are marked volatile, then this reordering will be prevented. But that is what prompted the original question - *are the volatiles required or does the ManualResetEvent provide an implicit memory barrier such that reordering does not occur, in which case the volatile keyword is not really necessary?* If I understand correctly, wekempf's position is that the WaitOne() function provides an implicit memory barrier which fixes the problem. ***BUT*** that doesn't seem sufficient to me. The main and background threads **could** be executing on two separate processors. So, if Set() does not also provide an implicit memory barrier, then the Task() function could end up being executed like this on one of the processors (even with the volatile variables): ``` private void Task() { // possibly long-running work goes here _completedSignal.Set(); _a = result1; _b = result2; _c = result3; _completed = true; } ``` I have searched high and low for information regarding memory barriers and the EventWaitHandles, and I have come up with nothing. The only reference I have seen is the one wekempf has made to Jeffrey Richter's book. The problem I have with this is that the EventWaitHandle is meant to synchronize threads, not access to data. I have never seen any example where EventWaitHandle (e.g., ManualResetEvent) is used to synchronize access to data. As such, I'm hard-pressed to believe that EventWaitHandle does anything with regard to memory barriers. Otherwise, I would expect to find ***some*** reference to this on the internet. EDIT #2: This is a response to wekempf's response to my response... ;) I managed to read the section from Jeffrey Richter's book at amazon.com. From page 628 (wekempf quotes this too): > Finally, i should point out that whenever a thread calls an interlocked method, the CPU forces cache coherency. So if you are manipulating variables via interlocked methods, you do not have to worry about all of this memory model stuff. Furthermore, all thread synchronization locks (**Monitor**, **ReaderWriterLock**, **Mutex**, **Semaphone**, **AutoResetEvent**, **ManualResetEvent**, etc.) call interlocked methods internally. So it would seem that, as wekempf pointed out, that the result variables do ***not*** require the volatile keyword in the example as shown since the ManualResetEvent ensures cache coherency. Before closing this edit, there are two additional points I'd like to make. First, my initial assumption was that the background thread would potentially run multiple times. I obviously overlooked the name of the class (OneUseBackgroundOp)! Given that it is only run once, it is not clear to me why the DoSomething() function calls WaitOne() in the manner that it does. What is the point of waiting initialWaitMs milliseconds if the background thread may or may not be done at the time DoSomething() returns? Why not just kickoff the background thread and use a lock to synchronize access to the results variables ***OR*** simply execute the contents of the Task() function as part of the thread that calls DoSomething()? Is there a reason not to do this? Second, it seems to me that not using some kind of locking mechanism on the results variables is still a bad approach. True, it is not needed in the code as shown. But at some point down the road, another thread may come along and try to access the data. It would be better in my mind to prepare for this possibility now rather than try to track down mysterious behavior anomalies later. Thanks to everyone for bearing with me on this. I've certainly learned a lot by participating in this discussion.
Does an EventWaitHandle have any implicit MemoryBarrier?
[ "", "c#", ".net", "vb.net", "multithreading", "volatile", "" ]
I've been going through Head First Design Patterns (just came in recently) and I was reading about the strategy pattern, and it occurred to me that it might be a great way to implement a common way of calculating taxes etc. on all of the particular objects I use at work, but I had a question about it. Here's what I was thinking: ``` public interface ITax { decimal ProvincialTaxRate { get; set; } // Yes, I'm Canadian :) decimal CalculateTax(decimal subtotal); } public SaskatchewanTax { public decimal ProvincialTaxRate { get; set; } public SaskatchewanTax() { ProvincialTaxRate = new decimal(0.05f); } public decimal CalculateTax(subtotal) { return ProvincialTaxRate * subtotal + FederalTaxRate * subtotal; } } public OntarioTax { public decimal ProvincialTaxRate { get; set; } public OntarioTax() { ProvincialTaxRate = new decimal(0.08f); } public decimal CalculateTax(decimal subtotal) { return ProvincialTaxRate * subtotal + FederalTaxRate * subtotal; } } ``` You may have noticed that there is no declaration of FederalTaxRate and that's what I wanted to ask. Where should that go? * Passing it in to the constructor for each concrete ITax seems redundant and would allow for incorrect behaviour (all tax calculators must share the exact same federal tax rate). * Likewise, creating a member of ITax would allow them to be inconsistent as well. Should all tax calculators inherit from some other class where it's defined statically as well as ITax? ``` public class TaxCalculator { public static decimal FederalTaxRate = new decimal(0.05f); } ```
I think this is a common case of pattern abuse. If you check your two "strategies", they do EXACTLY the same thing. The only thing that changes is the ProvincialTaxRate. I'd keep things DRY and don't overuse this pattern (or any other), here you gain a little bit of flexibility, but then you also have 2 classes that don't pull their weights, and probably **You Ain't Gonna Need** that flexibility. This is common when you learn a new technology or insight, you want to apply it everywhere (it happens to every one of us), even if doing it harms the code readability and maintainability. My opinion: keep it simple Regards **EDIT (In response to the author comment on my answer)** I did not try to make fun of you, or anyone. This is a common mistake, I did it MANY times, and learned it the hard way, not only with patterns but also with fancy frameworks, servers, new buzzword technologies, you name it. The authors of the book themselves warn the readers not to overuse patterns, and the upvotes in this answer clearly indicate something too. But if for some reason you still want to implement the pattern, here's my humble opinion: * Make a superclass for both strategies, this superclass would be abstract and should contain the shared rate value of their child strategies (FederalTaxRate) * Inherit and implement the abstract method "Calculate" in each subclass (here you'll see that both methods are the same, but let's continue) * Try to make each concrete strategy immutable, always favor immutability as Joshua Bloch says. For that, remove the setter of ProvincialTaxRate and specify the value on it's constructor or directly in its declaration. * Lastly, I'd create some static factory methods in the StrategySuperclass so that you decouple your clients from the implementations or concrete strategies (that can very well be protected classes now) **Edit II:** Here's a pastie with some (pseudo) code to make the solution a bit more clear <http://pastie.org/441068> Hope it helps Regards
In my opinion, you have the right solution - create a base class that contains the Canadian federal fax rate from which all of your derived classes can inherit. Statically defining it is a perfectly fine idea. You could also make the FederalTaxRate define only an accessor function for the tax rate, so that you could presumably define it at runtime from a file or something else. I don't think that this is uniquely the best solution, but it will work perfectly well. Design patterns shouldn't get in the way of your common sense, and I think that common sense will solve this problem just fine.
strategy pattern in C#
[ "", "c#", "design-patterns", "strategy-pattern", "" ]
I have a dataset obtained from MySQL that goes like this: ``` Array ( [0] => Array ( [views] => 14 [timestamp] => 06/04 [views_scaled] => 4.9295774647887 [unix_time] => 1239022177 ) [1] => Array ( [views] => 1 [timestamp] => 19/04 [views_scaled] => 0.35211267605634 [unix_time] => 1240194544 ) ... ... ... ) 1 ``` (it's post-processed, 'timestamp' was really a timestamp before, but that doesn't matter anyways) The array is stored on `$results`, and in the middle of my code I do something like this: ``` $results = array_merge($results, $new_days); $a = $results; foreach ($results as $row) { $unix_time[] = $row['unix_time']; } $b = $results; ``` **The problem:** `$a` and `$b` are both different. The first one shows the array as it's supposed to, and the second one has the same `count()`, but it's fourth element is a duplicate from the last one. As far as I know, I'm not passing anything by reference, so `$results` Isn't meant to change (maybe the pointer, but not it's content). I'm using PHP 5.2.4 on Mac OS X 10.5.2. **The obvious question:** Is this somehow the intended behavior, a bug or I'm doing something wrong here? (not a boolean answer please ;) --- **EDIT:** Thank you all for the interest, I don't know exactly how much extra code should I post, I don't do much before except for retrieving the data from the DB and a `foreach` to parse the timestamp and build a new array (`$new_days`) for the missing days. This is all working fine. This code goes after the one I've posted early: ``` array_multisort($unix_time, SORT_ASC, $results); $days = implode('|', array_pluck('timestamp', $results)); $views = implode('|', array_pluck('views', $results)); $views_scaled = implode(',', array_pluck('views_scaled', $results)); ``` (`array_pluck()` is a custom function to generate an array from a column in a typical DB-dumped dataset) --- **EDIT 2:** Thanks again, here's [the full snippet](http://snipplr.com/view/14259/ignorance-or-bug-on-phps-foreach-construct/) and the output from the `$results` array [`$a`](http://snipplr.com/view/14257/) and [`$b`](http://snipplr.com/view/14258/) (also referenced in the code's comments).
Inspecting your code snippet, really quickly (just about to leave the office for the day), it is probably to do with something passing by reference in your (first) loop. Try using normal by value and just storing everything into a fresh result array. (will remove any mysteries that could be going on). Could also try making the second $row in the second foreach a different name.. beats me - can't tell you with really looking at this more. also this line and following block of code won't execute ``` if ($last_day != $day_before_this_one AND $last_day) ``` could have something to do with it, new days will never fill up and the merge could be doing something funky. Wouldn't call this an answer but its a start to look at I guess
The problem is the first foreach loop, as was already mentioned. Here's the reasoning... ``` <? // set up an example array and loop through it using references (&) $my_array = array(1,2,3,4); foreach($my_array as &$item) { $item = $item+.1; } // 1st loop, $item points to: $my_array[0], which is now 1.1 // 2nd, $item -> $my_array[1], which is now 2.1 // 3rd, $item -> $my_array[2], which is now 3.1 // 4th, $item -> $my_array[3], which is now 4.1 // looping done, but $item is still pointing to $my_array[3] // next foreach loop foreach($my_array as $item) { var_dump($my_array); print $item."<br>"; } // notice the & in the output of the var_dump, if you actually run this code. // 1st loop: the value of $my_array[0] is assigned to $item, which is still a pointer/reference to $my_array[3] // first loop.. array(1.1,2.1,3.1,1.1) // grabbing [0] and putting into [3] // next loop... array(1.1,2.1,3.1,2.1) // grabbing [1] and putting into [3] // next loop... array(1.1,2.1,3.1,3.1) // grabbing [2] and putting into [3] (here's where the magic happens!) // last loop... array(1.1,2.1,3.1,3.1) // grabbing [3] and putting into [3] (but [3] is the same as [2] !!!) ?> ``` I hope this makes sense! Basically the second to last value will be repeated because the last value is replaced during the second loop.
Reusing reference variable from first loop in a second loop corrupts my array data
[ "", "php", "arrays", "codeigniter", "dataset", "foreach", "" ]
I would like some feedback on how we can best write a generic function that will enable two Lists to be compared. The Lists contain class objects and we would like to iterate through one list, looking for the same item in a second List and report any differences. We already have a method to compare classes, so we need feedback on how we can feed the method (shown below) from two Lists. For example, say we have a simple "Employee" class that has three properties, Name, ID, Department. We want to report the differences between List and another List. Note: Both lists will always contain the same number of items. As mentioned above, we have a generic method that we use to compare two classes, how can we incorporate this method to cater for Lists, i.e. from another method, loop through the List and feed the classes to the generic method .... but how do we find the equivalent class in the second List to pass to the method below; ``` public static string CompareTwoClass_ReturnDifferences<T1, T2>(T1 Orig, T2 Dest) where T1 : class where T2 : class { // Instantiate if necessary if (Dest == null) throw new ArgumentNullException("Dest", "Destination class must first be instantiated."); var Differences = CoreFormat.StringNoCharacters; // Loop through each property in the destination foreach (var DestProp in Dest.GetType().GetProperties()) { // Find the matching property in the Orig class and compare foreach (var OrigProp in Orig.GetType().GetProperties()) { if (OrigProp.Name != DestProp.Name || OrigProp.PropertyType != DestProp.PropertyType) continue; if (OrigProp.GetValue(Orig, null).ToString() != DestProp.GetValue(Dest, null).ToString()) Differences = Differences == CoreFormat.StringNoCharacters ? string.Format("{0}: {1} -> {2}", OrigProp.Name, OrigProp.GetValue(Orig, null), DestProp.GetValue(Dest, null)) : string.Format("{0} {1}{2}: {3} -> {4}", Differences, Environment.NewLine, OrigProp.Name, OrigProp.GetValue(Orig, null), DestProp.GetValue(Dest, null)); } } return Differences; } ``` Any suggestions or ideas appreciated? Edit: Targeting .NET 2.0 so LINQ is out of the question.
> .... but how do we find the equivalent class in the second List to pass to the method > below; This is your actual problem; you must have at least one immutable property, a id or something like that, to identify corresponding objects in both lists. If you do not have such a property you, cannot solve the problem without errors. You can just try to guess corresponding objects by searching for minimal or logical changes. If you have such an property, the solution becomes really simple. ``` Enumerable.Join( listA, listB, a => a.Id, b => b.Id, (a, b) => CompareTwoClass_ReturnDifferences(a, b)) ``` --- > thanks to you both danbruc and Noldorin for your feedback. both Lists will be the same > length and in the same order. so the method above is close, but can you modify this > method to pass the enum.Current to the method i posted above? Now I am confused ... what is the problem with that? Why not just the following? ``` for (Int32 i = 0; i < Math.Min(listA.Count, listB.Count); i++) { yield return CompareTwoClass_ReturnDifferences(listA[i], listB[i]); } ``` The Math.Min() call may even be left out if equal length is guaranted. --- Noldorin's implementation is of course smarter because of the delegate and the use of enumerators instead of using ICollection.
This solution produces a result list, that contains all differences from both input lists. You can compare your objects by any property, in my example it is ID. The only restriction is that the lists should be of the same type: ``` var DifferencesList = ListA.Where(x => !ListB.Any(x1 => x1.id == x.id)) .Union(ListB.Where(x => !ListA.Any(x1 => x1.id == x.id))); ```
Compare two Lists for differences
[ "", "c#", ".net", "list", ".net-2.0", "" ]
I'm trying to use ADO to create several tables at once, into MS Access. Is it possible to do multiple statements in the one operation? For instance: ``` ... // I have omitted the field details CString sQuery = "CREATE TABLE [Table1] (..., PRIMARY KEY ([ID])); \nCREATE TABLE [Table2] (..., PRIMARY KEY ([ID]));"; oRecordset.Open(oDatabase.m_pConnection, sQuery) ``` This fails due to a `"Syntax Error in CREATE TABLE statement"`, although each of the create statements work on their own perfectly. Is there a way of doing this sort of thing? There will also be statements to add constraints, add indexing, etc., and I'd really like to be able to do it so that I don't have to split up the string into separate parts.
ADO to MS Access does not support batch SQL statements. You need to run each statement as a separate execution.
ADO isn't the issue: the ACE/Jet engine simply does not support multiple SQL statements within a single operation. In other words, ACE/JET SQL lacks procedural syntax found in most 'industrial-strength' SQL products. See @David-W-Fenton's answer for more detail. Bottom line: You will need to issue a `Connection.Execute` for each `CREATE TABLE` statement i.e. client side procedural code. But they can (perhaps should) all be run in the same transaction, of course.
Running multiple SQL statements in the one operation
[ "", "sql", "ms-access", "" ]
Other than MongoDB and Memcached, what key-value stores run on Windows? Most of the ones I've seen seem to only run on Linux (Hypertable, Redis, Lightcloud). Related links: [Is there a business proven cloud store / Key=>Value Database? (Open Source)](https://stackoverflow.com/questions/639545/is-there-a-business-proven-cloud-store-keyvalue-database-open-source) <http://www.metabrew.com/article/anti-rdbms-a-list-of-distributed-key-value-stores/>
I would take a look at this article from [highscalability.com](http://highscalability.com/drop-acid-and-think-about-data). It describes a few options that you may want to consider, including [Tokyo Cabinet/Tyrant](http://tokyocabinet.sourceforge.net/), [CouchDB](http://couchdb.apache.org/) and [MongoDB](http://www.mongodb.org/display/DOCS/Home).
[Berkeley DB](http://en.wikipedia.org/wiki/Berkeley_DB) is [available](http://www.oracle.com/technology/products/berkeley-db/index.html). I'm surprised no-one has mentioned it yet. You can build it on Windows either with a native or Cygwin toolchain, but it's probably best with MSVC if you're going to be linking it with `C#`.
Key Value Database For Windows?
[ "", "c#", "asp.net", "windows", "memcached", "key-value", "" ]
I have this code that edits addresses in a game to get unlimited ammo and what not, and I found out that the addresses are different for every computer, sometimes every time you restart the game, so how would I manage making this work still even though they change.
If you get the address you're looking for, and then search for that address in memory to find the address of the pointer to that data, and then search for *that* address in memory so you can find the address of the pointer to it, and so on, you may eventually find an address that does not change. Then, at runtime, you can use that as a starting point and dereference it to find the location you're looking for. Of course, that all depends on how the data is laid out internally. It can get very complicated.
Signature matching for the record contents in the heap. Maybe using edit distance against specific known content. No harm I'm answering, since you had to ask, you probably don't have the chops to pull it off.
Keeping address in C++ hacking game code?
[ "", "c++", "memory-address", "" ]
I'm working on a client-server program for the first time, and I'm feeling woefully inadequate on where to begin for what I'm doing. I'm going to use [Google Protocol Buffers](http://code.google.com/p/protobuf/) to transfer binary data between my client and my server. I'm going to be using the Python variant. The basic idea, as I understand, is that the client will serialize the data, send it to the server, which will then deserialize the data. The problem is, I'm really not sure where to begin for sending binary data to the server. I was hoping it'd be something "simple" like an HTTP request, but I've been searching around Google for ways to transfer binary data and getting lost in the vast multitude of tutorials, guides and documentation. I can't even tell if I'm barking up the wrong tree by investigating HTTP transfers (I was hoping to use it, so I could knock it up a notch to HTTPS if security is necessary). I really don't want to have to go to the level of socket programming, though - I'd like to use the libraries available before turning to that. (I'd also prefer standard Python libraries, though if there's the perfect 3rd party library I'll live.) So, if anyone has a good starting point (or wants to explain a bit themselves) on how a good way to transfer binary data via Python, I'd be grateful. The server I'm running is currently running Apache with mod\_python, by the way.
Any time you're going to move binary data from one system to another there a couple of things to keep in mind. Different machines store the same information differently. This has implication both in memory and on the network. More info here (<http://en.wikipedia.org/wiki/Endianness>) Because you're using python you can cut yourself some slack here (assuming the client and server will both by in python) and just use cPickle to serialize your data. If you really want binary, you're going to have to get comfortable with python's struct module (<http://docs.python.org/library/struct.html>). And learn how to pack/unpack your data. I would first start out with simple line-protocol servers until you get past the difficulty of network communication. If you've never done it before it can get confusing very fast. How to issue commands, how to pass data, how to re-sync on errors etc... If you already know the basics of client/server protocol design, then practice packing and unpacking binary structures on your disk first. I also refer to the RFCs of HTTP and FTP for cases like this. -------EDIT BASED ON COMMENT-------- Normally this sort of thing is done by sending the server a "header" that contains a checksum for the file as well as the size of the file in bytes. Note that I don't mean an HTTP header, you can customize it however you want. The chain of events needs to go something like this... ``` CLIENT: "UPLOAD acbd18db4cc2f85cedef654fccc4a4d8 253521" SERVER: "OK" (server splits the text line to get the command, checksum, and size) CLIENT: "010101101010101100010101010etc..." (up to 253521 bytes) (server reasembles all received data into a file, then checksums it to make sure it matches the original) SERVER: "YEP GOT IT" CLIENT: "COOL CYA" ``` This is overly simplified, but I hope you can see what I'm talking about here.
I'm not sure I got your question right, but maybe you can take a look at the [twisted project](http://twistedmatrix.com/trac/). As you can see in the FAQ, "Twisted is a networking engine written in Python, supporting numerous protocols. It contains a web server, numerous chat clients, chat servers, mail servers, and more. Twisted is made up of a number of sub-projects which can be accessed individually[...]". The documentation is pretty good, and there are lots of examples on the internet. Hope it helps.
How do you transfer binary data with Python?
[ "", "python", "http", "file", "client-server", "protocol-buffers", "" ]
How can I resolve this? ``` >>> class unslice: ... def __getitem__(self, item): print type(item), ":", item ... >>> u = unslice() >>> u[1,2] # using an extended slice <type 'tuple'> : (1, 2) >>> t = (1, 2) >>> u[t] # or passing a plain tuple <type 'tuple'> : (1, 2) ``` Rational: I'm currently overengineering a sorted associative collection with the ability to return ranges of items. It is quite likely that I will want to store tuples of small integers (or even more pathologically wierd values like Ellipsis) in the collection (as keys), and will need some kind of sane way of differentiating extended slices from plain keys In the one-dimensional case, it's sort of a non-issue. I can't think of any real reason I would want to collect values of type `slice`, especially since `xrange` values are functionally similar and more recognizable to pythonistas (in my judgement). All other extended slice constructs are tuples of `slice`, `Ellipsis` or plain-old python values No other type of extended slice seems to be in common use for any kind of collection except multidimensional arrays as in NumPy. I do need to support n-dimensional axes, similar to oct-trees or GiS indices.
From [the docs](http://docs.python.org/reference/expressions.html#index-917): > There is ambiguity in the formal > syntax here: anything that looks like > an expression list also looks like a > slice list, so any subscription can be > interpreted as a slicing. Rather than > further complicating the syntax, this > is disambiguated by defining that in > this case the interpretation as a > subscription takes priority over the > interpretation as a slicing (this is > the case if the slice list contains no > proper slice nor ellipses). Similarly, > when the slice list has exactly one > short slice and no trailing comma, the > interpretation as a simple slicing > takes priority over that as an > extended slicing. As such, I don't think it's possible to distinguish `u[1,2]`-as-extended-slice from `u[1,2]`-as-tuple-key.
Since there is no way to differentiate between the calls u[x,y] and u[(x,y)], you should shift one of the two operations you are trying to define off to an actual method. You know, something named u.slice() or u.range() or u.getslice() or u.getrange() or something like that. Actually, when writing my *own* programs, I generally find that when I'm trying to overload a Python operation with two quite distinct semantics, it means that **both** of the things I am doing need to be turned into named methods! Because if the two are so similar in meaning that neither one has an obviously superior claim to getting to use the braces [] getitem shortcut, then probably my code will be more readable if **both** operations get real, readable, explicit method names. But, it's hard to say more since you haven't told us how on earth you've gotten into this mess. Why would you want to both store things under tuples **and** get ranges of things? One suspects you are doing something to complicated to begin with. :-) Oh, and other languages with this problem make you say a[1][2] to do multi-dimensional access to easily distinguish from a[1,2]. Just so you know there's another option.
Sorted collections: How do i get (extended) slices right?
[ "", "python", "" ]
**EDIT**: Copied wrong part of function into this question, below is the appropriate one. ``` $values = mysql_query("SELECT lname, fname, email, dtelephone, etelephone, contactwhen, thursday, friday, saturday, sunday, monday, comments FROM volunteers_2009 WHERE venue_id = $venue_id"); while ($rowr = mysql_fetch_row($values)) { for ($j=0;$j<$i;$j++) { $csv_output .= $rowr[$j].", "; } $csv_output .= "\n"; } ``` I have comments that may have a comma in it, and even double quotes, when it has a comma in the comment field, it throws off the entire csv file. The code below is how it loads the data into the csv string, to put into a csv file. How do I get it to export the comments field data properly?
Enclose the field in double quotes. Double up any embedded double quotes. ``` ordinary field,"field with , in it","field with double double quote ("""")" ``` Note that this is very, very close to the question [Dealing with commas in a CSV file](https://stackoverflow.com/questions/769621/dealing-with-commas-in-a-csv-file)
You should check out [`fputcsv()`](http://php.net/fputcsv). There are some useful comments there as well. > ``` > int fputcsv ( resource $handle , array $fields [, string $delimiter = ',' > [, string $enclosure = '"' ]] ) > ``` > > **fputcsv()** formats a line (passed > as a fields array) as CSV and write it (terminated by a newline) to > the specified file handle.
Need to export string w/ commas in it properly into a CSV file
[ "", "php", "mysql", "csv", "" ]
Which is the fastest way of calling a native library from Java? The ones I know about are * [NativeCall](http://johannburkard.de/software/nativecall/) - what we're currently using * [JNA](http://jna.java.net/) - haven't used it, but looks reasonable * [JNI](http://java.sun.com/j2se/1.4.2/docs/guide/jni/) - looks horrendous to write, but we'll do it if we get the speed
[Swig](http://www.swig.org/) makes JNI easier too. In terms of speed, I suspect there will be subtle variations - I strongly suggest you pick a call that you know you'll be making a lot, and benchmark all of the solutions offered.
JNI is the fastest. JNA is very slow compared to JNI (the call overhead is probably one order of magnitude), but it is a fantastic library because it makes native access so easy. JNA is great if you need to make an occasional call to some native API. If you care about performance, I wouldn't use it in any "tight loops." I'm not sure where NativeCall fits in the spectrum.
Which is the fastest way to access native code from Java?
[ "", "java", "java-native-interface", "native", "" ]
I am going to be writing a PHP mailing list system. Ideally, I would like for the templates styles to be easy to manage. In my current system, I have the styles all hardcoded in the template like this: ``` <a href="http://blah/blah/blah" style="color: #a8a8a8;">click here</a> ``` This works alright until the person managing the template decides that they want to change the color of the link text. What I'd really like is to have something process the HTML and style definitions and output the HTML with the appropriate HTML. What I am hoping for is something that will take the following input: ``` <style type="text/css"> a { color: #a8a8a8; } </style> <a href="http://blah/blah/blah">click here</a> ``` ... and generate... ``` <a href="http://blah/blah/blah" style="color: #a8a8a8;">click here</a> ``` ... such that if the stylesheet is updated, the "rendered" HTML will all reflect these changes. It would be great if this could be used with either inline `<style></style>` tags or by using external CSS `links`. I'm doing this because my experience has shown that some (most? all?) of the webmail clients I have used do not appear to honor style information, external or otherwise. If I've missed something here and there is a more simple way to do this, would love to hear about those suggestions too. :) **EDIT** I did some more queries and found another Stackoverflow question that [discusses CSS Selectors](https://stackoverflow.com/questions/260605/php-css-selector-library) and I think I will try to use something like phpQuery to handle this.
I decided to look into handling this with [phpQuery](http://code.google.com/p/phpquery/). I believe it provides the cleanest solution to my problem.
**Update:** I rewrote this after I realized I misunderstood your question. You could code up a PHP script that translates all the style blocks into hard-coded styles for each HTMLElement. The pseudo code could be: ``` 1. load up an XML parser for the HTML email generated by your mailing list program 2. xpath get all "style" nodes 3. for each node, parse for the id and/or class of the CSS style (you'll need some regexes for these) 4. for each id and/or class found, look up that node by attribute id or class (using xpath) and append to the existing value of the style attribute ```
What is the best way to process external CSS stylesheets and inject into inline CSS elements?
[ "", "php", "css", "" ]
What are some ways you can shoot yourself in the foot when using [`boost::shared_ptr`](http://www.boost.org/doc/libs/release/libs/smart_ptr/shared_ptr.htm)? In other words, what pitfalls do I have to avoid when I use [`boost::shared_ptr`](http://www.boost.org/doc/libs/release/libs/smart_ptr/shared_ptr.htm)?
Cyclic references: a `shared_ptr<>` to something that has a `shared_ptr<>` to the original object. You can use `weak_ptr<>` to break this cycle, of course. --- I add the following as an example of what I am talking about in the comments. ``` class node : public enable_shared_from_this<node> { public : void set_parent(shared_ptr<node> parent) { parent_ = parent; } void add_child(shared_ptr<node> child) { children_.push_back(child); child->set_parent(shared_from_this()); } void frob() { do_frob(); if (parent_) parent_->frob(); } private : void do_frob(); shared_ptr<node> parent_; vector< shared_ptr<node> > children_; }; ``` In this example, you have a tree of nodes, each of which holds a pointer to its parent. The frob() member function, for whatever reason, ripples upwards through the tree. (This is not entirely outlandish; some GUI frameworks work this way). The problem is that, if you lose reference to the topmost node, then the topmost node still holds strong references to its children, and all its children also hold a strong reference to their parents. This means that there are circular references keeping all the instances from cleaning themselves up, while there is no way of actually reaching the tree from the code, this memory leaks. ``` class node : public enable_shared_from_this<node> { public : void set_parent(shared_ptr<node> parent) { parent_ = parent; } void add_child(shared_ptr<node> child) { children_.push_back(child); child->set_parent(shared_from_this()); } void frob() { do_frob(); shared_ptr<node> parent = parent_.lock(); // Note: parent_.lock() if (parent) parent->frob(); } private : void do_frob(); weak_ptr<node> parent_; // Note: now a weak_ptr<> vector< shared_ptr<node> > children_; }; ``` Here, the parent node has been replaced by a weak pointer. It no longer has a say in the lifetime of the node to which it refers. Thus, if the topmost node goes out of scope as in the previous example, then while it holds strong references to its children, its children don't hold strong references to their parents. Thus there are no strong references to the object, and it cleans itself up. In turn, this causes the children to lose their one strong reference, which causes them to clean up, and so on. In short, this wont leak. And just by strategically replacing a shared\_ptr<> with a weak\_ptr<>. Note: The above applies equally to std::shared\_ptr<> and std::weak\_ptr<> as it does to boost::shared\_ptr<> and boost::weak\_ptr<>.
Creating multiple unrelated `shared_ptr`'s to the same object: ``` #include <stdio.h> #include "boost/shared_ptr.hpp" class foo { public: foo() { printf( "foo()\n"); } ~foo() { printf( "~foo()\n"); } }; typedef boost::shared_ptr<foo> pFoo_t; void doSomething( pFoo_t p) { printf( "doing something...\n"); } void doSomethingElse( pFoo_t p) { printf( "doing something else...\n"); } int main() { foo* pFoo = new foo; doSomething( pFoo_t( pFoo)); doSomethingElse( pFoo_t( pFoo)); return 0; } ```
What are potential dangers when using boost::shared_ptr?
[ "", "c++", "boost", "pointers", "shared-ptr", "" ]
I have a textbox on my website and I need to store whatever the user enters into my database, and retrieve it at a later time. I need to store it exactly as the user entered, including special characters, carriage returns, etc. What process should I use in PHP to store this in my database field (which is a 'text' field)? Should I use PHP's html\_encode or anything like that? Thankyou. Edit: I also need to store correct formatting i.e tabs and multiple spaces.
You shouldn't html-encode the data when writing it to the datastorage - that way you could use your data also for something else (e.g. emails, PDF documents and so on). As [Assaf](https://stackoverflow.com/questions/716656/php-storing-text-in-mysql-database/716661#716661) already said: it's mandatory to avoid SQL injections by escaping the input or using parameterized insert-queries. You should, no, let's say, **must** however html-encode your data when showing it on an HTML page! That will render dangerous HTML or Javascript code useless as the HTML-tags present in the data will not be recognized as HTML-tags by the browser any more. The process is a little more complicated when you'll allow the users to post data with HTML-tags inside. You then have to skip the output-encoding in favor of an input-sanitizing which can be arbitrary complex depending on your needs (allowed tags e.g.).
Use [mysql\_real\_escape\_string()](https://www.php.net/manual/en/function.mysql-real-escape-string.php): ``` $safetext = mysql_real_escape_string($_POST['text']); $query = "INSERT INTO my_table (`my_field`) VALUES ('$safetext')"; mysql_query($query); ``` That should work.
PHP - Storing Text in MySQL Database
[ "", "php", "mysql", "text", "html-encode", "" ]
I'm trying to overload the assignment operator and would like to clear a few things up if that's ok. I have a non member function, `bool operator==( const MyClass& obj1, const myClass& obj2 )` defined oustide of my class. I can't get at any of my private members for obvious reasons. So what I think I need to do is to overload the assignment operator. And make assignments in the non member function. With that said, I think I need to do the following: 1. use my functions and copy information using `strcpy` or `strdup`. I used `strcpy`. 2. go to the assignment operator, bool MyClass::operator=( const MyClass& obj1 ); 3. Now we go to the function overloading (==) and assign obj2 to obj1. I don't have a copy constructor, so I'm stuck with these: ``` class Class { private: m_1; m_2; public: .. }; void Class::Func1(char buff[]) const { strcpy( buff, m_1 ); return; } void Class::Func2(char buff[]) const { strcpy( buff, m_2 ); return; } bool Class& Class::operator=(const Class& obj) { if ( this != &obj ) // check for self assignment. { strcpy( m_1, obj.m_1 ); // do this for all other private members. } return *this; } bool operator== (const Class& obj1, const Class& obj2) { Class MyClass1, MyClass2; MyClass1 = obj1; MyClass2 = obj2; MyClass2 = MyClass1; // did this change anything? // Microsofts debugger can not get this far. return true; } ``` So as you can probably tell, I'm completely lost in this overloading. Any tips? I do have a completed version overloading the same operator, only with `::`, so my private members won't lose scope. I return my assignments as true and it works in `main`. Which is the example that I have in my book. Will overloading the assignment operator and then preforming conversions in the `operator==` non member function work? Will I then be able to assign objects to each other in main after having completed that step?
I am guessing that you want to compare the two objects. In that case, you can just overload the operator == in class "Class". You don't need assignment operator. ``` class Class { public: Class(int i) : m_i(i){} bool operator==( const Class& rhs) { return m_i == rhs.m_i; } private: int m_i; }; int main() { Class t1(10), t2(10); bool b = (t1 == t2); } ```
You have a couple of obvious mistakes here and there is some confusion about what you are actually trying to achieve. Firstly, the assignment operator `operator =` is meant to copy the value from one instance to another. The return value of the assignment operator is almost always a non constant reference to the target of the copy, so that you can chain assignments: ``` Class & operator=(const Class &rhs) { // copy the members return *this; } ``` The comparison operator `operator ==` is meant to perform a comparison of two instances. It returns a boolean true if they are equal: ``` boolean operator==(const Class &rhs) const { // check if they are equal return something; } ``` The confusion is why are you trying to copy values around, or maybe assign to the instances in the comparison operator?
Overloading = in C++
[ "", "c++", "operator-overloading", "" ]
I'm using mod\_wsgi and was wondering if it's possible to over-write the print() command (since it's useless). Doing this doesn't work: ``` print = myPrintFunction ``` Since it's a syntax error. :(
Print is not a function in Python 2.x, so this is not directly possible. You can, however, [override sys.stdout](http://code.activestate.com/recipes/119404/). If you are on Python 3.0 in which [print is now a function](http://docs.python.org/3.0/whatsnew/3.0.html#print-is-a-function) what you have would then work, assuming you have the right signature. Also see [a related question](https://stackoverflow.com/questions/550470/overload-print-python) in this site.
Would ``` import sys sys.stdout = MyFileWrapper() ``` or something similar work?
Python - Overridding print()
[ "", "python", "python-3.x", "mod-wsgi", "wsgi", "" ]
I have a raw pixel data in a `byte[]` from a DICOM image. Now I would like to convert this `byte[]` to an `Image` object. I tried: ``` Image img = Image.FromStream(new MemoryStream(byteArray)); ``` but this is not working for me. What else should I be using ?
You have to do the following 1. Identify the PIXEL DATA tag from the file. You may use FileStream to read byte by byte. 2. Read the pixel data 3. Convert it to RGB 4. Create a BitMap object from the RGB 5. Use Graphics class to draw the BitMap on a panel.
One thing to be aware of is that a dicom "image" is not necessarily just image data. The dicom file format contains much more than raw image data. This may be where you're getting hung up. Consider checking out the dicom file standard which you should be able to find linked on the wikipedia article for dicom. This should help you figure out how to parse out the information you're actually interested in.
How to create an image from a raw data of DICOM image
[ "", "c#", "dicom", "" ]
What namespace do I need to get my extension to work Here is my Extension Method ``` using System; using System.Collections.Generic; using System.Web; using System.Data; namespace MyUtilities { public static class DataReaderExtensions { public static DataTable ToDataTable(IDataReader reader) { DataTable table = new DataTable(); table.Load(reader); return table; } } } ``` When I try to use it in like this ``` Session["Master"] = cust.GetCustomerOrderSummary((string)Session["CustomerNumber"]).ToDataTable(); ``` it doesn't work. This is .net 2.0
You can't. C# 2.0 doesn't have extension methods at all. You can use extension methods from C# 3.0 in Visual Studio 2008 *targeting* .NET 2.0 as described in my ["C#/.NET versions" article](http://csharpindepth.com/Articles/Chapter1/Versions.aspx) but you can't persuade a C# 2.0 compiler to act as if it understands what extension methods are.
The tags say .NET 2.0; If you are using C# 3.0 (i.e. VS 2008) and targetting .NET 2.0, you can do this by declaring the ExtensionAttribute - or (easier) just reference [LINQBridge](https://www.nuget.org/packages/LinqBridge/). ``` namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method)] public sealed class ExtensionAttribute : Attribute { } } ``` With this in place, extension methods will work in .NET 2.0 with C# 3.0.
Extension Method in C# 2.0
[ "", "c#", ".net-2.0", "extension-methods", "" ]
I'm binding an ASP.NET control to the result of a LINQ query. I'd like to HtmlEncode one of the properties of the contained objects before binding to the control, but I want to do it without altering the data because I do a DataContext.SubmitChanges() later on. How can this be done? Code that won't work: ``` var ds = (from s in dc.SearchResults orderby s.datetime descending select s) .Take(int.Parse(ConfigurationManager.AppSettings["RecentItemQty"])); foreach (SearchResult sr in ds) sr.Query = Server.HtmlEncode(sr.Query); rSearches.DataSource = ds; rSearches.DataBind(); ```
Dummy me. I just need to HtmlEncode it within the OnItemDataBound() event.
Your could encode it when you do your binding... ``` <asp:YourDataBoundControl> <ItemTemplate> Query: <span><%# Server.HtmlEncode((string)Eval("Query")) %></span> </ItemTemplate> </asp:YourDataBoundControl> ```
HtmlEncode string within IQueryable without altering bound data
[ "", "c#", "asp.net", "linq-to-sql", "data-binding", "iqueryable", "" ]
I'm looking for a way to interact with the GNU `libparted` library from Python, but so far what I've found, a [GSOC](http://code.google.com/soc) [project from 2005](http://pylibparted.tigris.org) and an [Ubuntu/debian package](https://edge.launchpad.net/ubuntu/+source/python-parted) that's been [dropped from the archive](http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=379034), have been disheartening. Is there something I'm missing, or should I just get used to manipulating `libparted` from the command line / trying to fix the bitrot that's occurred in the other packages?
You mean like the [pyparted](https://github.com/rhinstaller/pyparted) library?
The reason debian dropped the package is lack of a maintainer. If you are willing (and able) to maintain the existing package and become their maintainer that would be a great contribution to FOSS.
Python bindings for libparted?
[ "", "python", "" ]
In Java, when should static non final variables be used? For example ``` private static int MY_VAR = 0; ``` Obviously we are not talking about constants here. ``` public static final int MY_CONSTANT = 1; ``` In my experience I have often justified them when using a singleton, but then I end up needing to have more than one instance and cause myself great headache and re-factoring. It seems it is rare that they should be used in practice. What do you think?
Statistics-gathering might use non-final variables, e.g. to count the number of instances created. On the other hand, for that sort of situation you probably want to use `AtomicLong` etc anyway, at which point it can be final. Alternatively if you're collecting more than one stat, you could end up with a `Statistics` class and a final reference to an instance of it. It's certainly pretty rare to have (justifiably) non-final static variables.
When used as a cache, logging, statistics or a debug switch are the obvious reasonable uses. All private, of course. If you have mutable object assigned to a final field, that is morally the same as having a mutable field. Some languages, such as Fan, completely disallow mutable statics (or equivalent).
Best Practice: Java static non final variables
[ "", "java", "static", "" ]
Is there a well-established approach for documenting Java "properties" file contents, including: * specifying the data type/contents expected for a given key * specifying whether a key is required for the application to function * providing a description of the key's meaning Currently, I maintain (by hand) a .properties file that is the default, and I write a prose description of the data type and description of each key in a comment before. This does not lead to a programmatically accessible properties file. I guess what I'm looking for is a "getopt" equivalent for properties files... [EDIT: Related] * [Java Configuration Frameworks](https://stackoverflow.com/questions/25765/)
I have never seen a standard way of doing it. What I would probably do is: * wrap or extend the [java.util.Properties](http://java.sun.com/javase/6/docs/api/java/util/Properties.html) class * override (of extending) or provide a method (if wrapping) the store method (or storeToXML, etc) that writes out a comment for each line. * have the method that stores the properties have some sort of input file where you describe the properties of each one. It doesn't get you anything over what you are doing by hand, except that you can manage the information in a different way that might be easier to deal with - for example you could have a program that spit out the comments to read in. It would potentially give you the programmatic access that you need, but it is a roll-your-own sort of thing. Or it might just be too much work for too little to gain (which is why there isn't something obvious out there). If you can specify the sort of comments you want to see I could take a stab at writing something if I get bored :-) (it is the sort of thing I like to do for fun, sick I know :-). Ok... I got bored... here is something that is at least a start :-) ``` import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; public class PropertiesVerifier { private final Map<String, PropertyInfo> optionalInfo; private final Map<String, PropertyInfo> requiredInfo; { optionalInfo = new HashMap<String, PropertyInfo>(); requiredInfo = new HashMap<String, PropertyInfo>(); } public PropertiesVerifier(final PropertyInfo[] infos) { for(final PropertyInfo info : infos) { final Map<String, PropertyInfo> infoMap; if(info.isRequired()) { infoMap = requiredInfo; } else { infoMap = optionalInfo; } infoMap.put(info.getName(), info); } } public void verifyProperties(final Properties properties) { for(final Entry<Object, Object> property : properties.entrySet()) { final String key; final String value; key = (String)property.getKey(); value = (String)property.getValue(); if(!(isValid(key, value))) { throw new IllegalArgumentException(value + " is not valid for: " + key); } } } public boolean isRequired(final String key) { return (requiredInfo.get(key) != null); } public boolean isOptional(final String key) { return (optionalInfo.get(key) != null); } public boolean isKnown(final String key) { return (isRequired(key) || isOptional(key)); } public Class getType(final String key) { final PropertyInfo info; info = getPropertyInfoFor(key); return (info.getType()); } public boolean isValid(final String key, final String value) { final PropertyInfo info; info = getPropertyInfoFor(key); return (info.verify(value)); } private PropertyInfo getPropertyInfoFor(final String key) { PropertyInfo info; info = requiredInfo.get(key); if(info == null) { info = optionalInfo.get(key); if(info == null) { // should be a better exception maybe... depends on how you // want to deal with it throw new IllegalArgumentException(key + " is not a valid property name"); } } return (info); } protected final static class PropertyInfo { private final String name; private final boolean required; private final Class clazz; private final Verifier verifier; protected PropertyInfo(final String nm, final boolean mandatory, final Class c) { this(nm, mandatory, c, getDefaultVerifier(c)); } protected PropertyInfo(final String nm, final boolean mandatory, final Class c, final Verifier v) { // check for null name = nm; required = mandatory; clazz = c; verifier = v; } @Override public int hashCode() { return (getName().hashCode()); } @Override public boolean equals(final Object o) { final boolean retVal; if(o instanceof PropertyInfo) { final PropertyInfo other; other = (PropertyInfo)o; retVal = getName().equals(other.getName()); } else { retVal = false; } return (retVal); } public boolean verify(final String value) { return (verifier.verify(value)); } public String getName() { return (name); } public boolean isRequired() { return (required); } public Class getType() { return (clazz); } } private static Verifier getDefaultVerifier(final Class clazz) { final Verifier verifier; if(clazz.equals(Boolean.class)) { // shoudl use a singleton to save space... verifier = new BooleanVerifier(); } else { throw new IllegalArgumentException("Unknown property type: " + clazz.getCanonicalName()); } return (verifier); } public static interface Verifier { boolean verify(final String value); } public static class BooleanVerifier implements Verifier { public boolean verify(final String value) { final boolean retVal; if(value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false")) { retVal = true; } else { retVal = false; } return (retVal); } } } ``` And a simple test for it: ``` import java.util.Properties; public class Main { public static void main(String[] args) { final Properties properties; final PropertiesVerifier verifier; properties = new Properties(); properties.put("property.one", "true"); properties.put("property.two", "false"); // properties.put("property.three", "5"); verifier = new PropertiesVerifier( new PropertiesVerifier.PropertyInfo[] { new PropertiesVerifier.PropertyInfo("property.one", true, Boolean.class), new PropertiesVerifier.PropertyInfo("property.two", false, Boolean.class), // new PropertiesVerifier.PropertyInfo("property.three", // true, // Boolean.class), }); System.out.println(verifier.isKnown("property.one")); System.out.println(verifier.isKnown("property.two")); System.out.println(verifier.isKnown("property.three")); System.out.println(verifier.isRequired("property.one")); System.out.println(verifier.isRequired("property.two")); System.out.println(verifier.isRequired("property.three")); System.out.println(verifier.isOptional("property.one")); System.out.println(verifier.isOptional("property.two")); System.out.println(verifier.isOptional("property.three")); System.out.println(verifier.getType("property.one")); System.out.println(verifier.getType("property.two")); // System.out.println(verifier.getType("property.tthree")); System.out.println(verifier.isValid("property.one", "true")); System.out.println(verifier.isValid("property.two", "false")); // System.out.println(verifier.isValid("property.tthree", "5")); verifier.verifyProperties(properties); } } ```
You could use some of the features in the [Apache Commons Configuration](http://commons.apache.org/configuration/) package. It at least provides type access to your properties. There are only conventions in the traditional java properties file. Some I've seen include providing, like you said, an example properties file. Another is to provide the default configuration with all the properties, but commented out. If you really want to require something, maybe you're not looking for a properties file. You could use an XML configuration file and specify a schema with datatypes and requirements. You can use jaxb to compile the schema into java and read it i that way. With validation you can make sure the required properties are there. The best you could hope for is when you execute your application, it reads, parses, and validates the properties in the file. If you absolutely had to stay properties based and didn't want to go xml, but needed this parsing. You could have a secondary properties file that listed each property that could be included, its type, and whether it was required. You'd then have to write a properties file validator that would take in a file to validate as well as a validation schema-like properties file. Something like ``` #list of required properties required=prop1,prop2,prop3 #all properties and their types prop1.type=Integer prop2.type=String ``` I haven't looked through all of the Apache Configuration package, but they often have useful utilities like this. I wouldn't be surprised if you could find something in there that would simplify this.
Best-practice for documenting available/required Java properties file contents
[ "", "java", "configuration-files", "" ]
So I have a website that queries a database with information about music, with id3 information and file location information. I would like to use [THIS](http://musicplayer.sourceforge.net/) to add a little playable mp3 player beside each of the search results, but I can't figure out how to do this without generating the xspf file, which would mean I would need an xspf file for every file in the database, which I don't want to do.
An [XSPF](http://en.wikipedia.org/wiki/XSPF) file is fairly small. It's just an XML document with song locations and titles. Just generate it dynamically. ``` <? header('Content-type: application/xspf+xml'); $tracks = array( 'Song 1' => '/media/song1.ogg', 'Second Song' => '/media/second_song.ogg', '3rd Song' => '/media/3rd_song.mp3' ); $xml = new XmlWriter(); $xml->startDocument('1.0','UTF-8'); $xml->startElement('playlist'); $xml->writeAttribute('version','1'); $xml->writeAttribute('xmlns','http://xspf.org/ns/0/'); $xml->startElement('trackList'); foreach ($tracks as $title => $location) { $xml->startElement('track'); $xml->startElement('title', $title); $xml->startElement('location', $location); $xml->endElement(); // track } $xml->endElement(); // trackList $xml->endElement(); // playlist $xml->endDocument(); $xml->flush(); ?> ```
Never mind, found out you don't need a playlist for one song if you don't want to.
Online Flash Mp3 Player Music Button
[ "", "php", "html", "flash", "mp3", "" ]
Is anyone aware of a way to have [VIM style folding](http://www.linux.com/articles/114138) in Visual Studio? I use #region blocks in c# class files and they're great, but unfortunately there's no equivalent functionality for javascript and css. The site/app I'm currently working on has a rather lot of css selectors and javascript and navigating the monolithic files is becoming difficult. One option that we've considered is breaking up the css and javascript into separate files similiar to jquery modules, but then that introduces performance problems in terms of increasing the overall number of http requests. If anyone has any suggestions for managing the madness, I'd be greatly appreciative! **Update**: Richard Kimber suggests [using the bookmarking features](http://blog.dogma.co.uk/2009/02/javascriptcss-bookmark-tip-for-visual.html) of visual studio to make navigating by headings more manageable. This is a step in the right direction, but not as useful as code folding/blocking.
I know I'm not really helping with this one, but have you heard of [ViEmu](http://www.viemu.com/). It is a, lets say, vim emulation within VS. Although it does not support all of vim's features, it does bring a flavor of it to VS navigation. I haven't used it myself, but others talk pretty good of it, so you might want to give it a shot.
I found a Microsoft extension that improved the JavaScript text editor for Visual Studio 2010. <http://visualstudiogallery.msdn.microsoft.com/en-us/872d27ee-38c7-4a97-98dc-0d8a431cc2ed> I have used it, and it gives all of the following for JavaScript files: * Brace Matching * Outlining / Code-folding * Current Word Highlighting * IntelliSense Doc-Comments Support
Vim style folding for CSS/javascript in Visual Studio
[ "", "javascript", "css", "visual-studio", "code-organization", "" ]
I am attempting to generate datamatrix barcodes from within itext. This works fine for most of my codes but not for some codes. One example is: > HEnSh0701003-2V1 This produces a non square barcode for some reason. When I use encoders from other companies (such as IDAutomation) I do get a valid square barcode. Does anyone have an idea why this is happening? I am looking for a solution so I can use the embedded iTest DataMatrix class and not have to use a third party one. A sample of the code I am using: ``` BarcodeDatamatrix bar = new BarcodeDatamatrix(); bar.setOptions(BarcodeDatamatrix.DM_AUTO); bar.generate("HEnSh0701003-2V1"); bcd.addCell(bar.createImage()); ``` where bcd is a PdfTable with 2 columns.
I ran into this exact issue. I ended up digging into the iText source code to figure this one out. iText is resizing the barcode to fit the text you provided. iText supports the following sizes for datamatrix barcodes: 10x10, 12x12, 8x18, 14x14, 8x32, 16x16, 12x26, 18x18, 20x20, 12x36, 22x22, 16x36, 24x24, 26x26, 16x48, 32x32, 36x36, 40x40, 44x44, 48x48, 52x52, 64x64, 72x72, 80x80, 88x88, 96x96, 104x104, 120x120, 132x132, 144x144 As you can see, there are a number of non-square sizes in there. What I did was create a list of square barcode sizes and then try each size while checking the return value of the generate() call. ``` // supported square barcode dimensions int[] barcodeDimensions = {10, 12, 14, 16, 18, 20, 22, 24, 26, 32, 36, 40, 44, 48, 52, 64, 72, 80, 88, 96, 104, 120, 132, 144}; BarcodeDatamatrix barcode = new BarcodeDatamatrix(); barcode.setOptions(BarcodeDatamatrix.DM_AUTO); // try to generate the barcode, resizing as needed. for (int generateCount = 0; generateCount < barcodeDimensions.length; generateCount++) { barcode.setWidth(barcodeDimensions[generateCount]); barcode.setHeight(barcodeDimensions[generateCount]); int returnResult = barcode.generate(text); if (returnResult == BarcodeDatamatrix.DM_NO_ERROR) { return barcode.createImage(); } } throw new Exception("Error generating barcode."); ```
Thanks JonMR For those who need it, here is the same code in VB.net ``` Private Function GetDataMatrixBarcode(ByVal message As String) As iTextSharp.text.Image Dim barcode As BarcodeDatamatrix = New BarcodeDatamatrix() Dim barcodeDimensions() As Integer = New Integer() {10, 12, 14, 16, 18, 20, 22, 24, 26, 32, 36, 40, 44, 48, 52, 64, 72, 80, 88, 96, 104, 120, 132, 144} Dim returnResult As Integer barcode.Options = BarcodeDatamatrix.DM_AUTO For generateCount As Integer = 0 To barcodeDimensions.Length - 1 barcode.Width = barcodeDimensions(generateCount) barcode.Height = barcodeDimensions(generateCount) returnResult = barcode.Generate(message) If returnResult = BarcodeDatamatrix.DM_NO_ERROR Then Return barcode.CreateImage End If Next Throw New Exception("Error generating datamatrix barcode for text '" & message & "'") End Function ```
iText datamatrix generation problem
[ "", "java", "itext", "barcode", "" ]
I am transferring a large static website of 500+ pages to a Joomla installation but what I am wanting to do, rather than code a 500+ line .htaccess file, is to use PHP's built in 301 header redirect to dynamically redirect requests that come in to the new URL. So for example, after I move the site, the following URL would 404 without a redirect- <http://www.foo.com/old_page.html> I would want it to redirect to ``` http://www.foo.com/old-page.php ``` So I would like to create a MySQL database of old URLs and their corresponding new URL and then, if the server is going to return a 404, for it first to check the DB for the existing old URL, and if matched, to issue a 301 redirect to the new URL. Right, am I making sense here? How would I do that? I can "talk" the logic but not really sure where to begin or how to accomplish it because, while I understand PHP, I don't really understand how this would work with Apache (or even if it would for example...)? And if you know of any scripts out there that are already doing this, all the better.
In your Apache configuration, set an ErrorDocument of whatever /404handler.php script you like. In its run context, **$\_SERVER['REQUEST\_URI']** will be the URI of the original page requested. Do your database lookup, and if you find a page you want to redirect do, use **header("Location: " . $wherever)** to redirect to it.
The simplest way that I can think of would be to use [mod\_rewrite](http://www.addedbytes.com/apache/url-rewriting-for-beginners/) (link is to a great introduction tutorial) to redirect ALL incoming requests to a single PHP script (or use a flag so that this redirect only happens if the request is for a file that does not exist), with the requested address passed as part of the query string. From there, have the PHP script look up where that request should go to, and redirect to it. So if someone tries to open <http://www.foo.com/old_page.html>, the mod\_rewrite would send to something like <http://www.foo.com/redirect.php?page=old_page.html>. redirect.php then does a database lookup to see what the new address for "old\_page.html" is, and redirects to there.
301 redirect with PHP and MySQL on 404
[ "", "php", "mysql", "apache", "redirect", "http-status-code-301", "" ]
I have a legacy data table in SQL Server 2005 that has a PK with no identity/autoincrement and no power to implement one. As a result, I am forced to create new records in ASP.NET manually via the ole "SELECT MAX(id) + 1 FROM table"-before-insert technique. Obviously this creates a race condition on the ID in the event of simultaneous inserts. What's the best way to gracefully resolve the event of a race collision? I'm looking for VB.NET or C# code ideas along the lines of detecting a collision and then re-attempting the failed insert by getting yet another max(id) + 1. Can this be done? Thoughts? Comments? Wisdom? Thank you! NOTE: What if I cannot change the database in any way?
Not being able to change database schema is harsh. If you insert existing PK into table you will get SqlException with a message indicating PK constraint violation. Catch this exception and **retry insert a few times** until you succeed. If you find that collision rate is too high, you may try `max(id) + <small-random-int>` instead of `max(id) + 1`. Note that with this approach your ids will have gaps and the id space will be exhausted sooner. Another possible approach is to **emulate autoincrementing id** outside of database. For instance, create a static integer, `Interlocked.Increment` it every time you need next id and use returned value. The tricky part is to initialize this static counter to good value. I would do it with `Interlocked.CompareExchange`: ``` class Autoincrement { static int id = -1; public static int NextId() { if (id == -1) { // not initialized - initialize int lastId = <select max(id) from db> Interlocked.CompareExchange(id, -1, lastId); } // get next id atomically return Interlocked.Increment(id); } } ``` Obviously the latter works only if all inserted ids are obtained via `Autoincrement.NextId` of single process.
Create an auxiliary table with an identity column. In a transaction insert into the aux table, retrieve the value and use it to insert in your legacy table. At this point you can even delete the row inserted in the aux table, the point is just to use it as a source of incremented values.
How to avoid a database race condition when manually incrementing PK of new row
[ "", "c#", "sql-server", "database", "vb.net", "asp.net-2.0", "" ]
I was wondering how expensive Java's string encoding conversion algorithms are, say, for a piece of text is in EBCDIC that needs to be converted to UTF-16, or for a similar conversion of a large file. Are there any benchmarks on the cost of this conversion? Benchmarks for multiple encodings would be better.
This is an O(n) algorithm. The time it takes to execute will increase more or less linearly with the length of the string you're converting (though if you are converting millions of very short strings, the overhead of the function calls will add to this). In almost all situations this won't be a bottleneck. You could probably encode very large strings many tens of megabytes in size in negligible time. I don't have actual benchmark data though.
I suspect it's negligible. I would be more worried about the cost of allocating new String objects if you're converting thousands of Strings, or the allocation of huge byte arrays, if you're converting very large Strings. But even then only in extreme circumstances.
How expensive is java's string encoding conversion?
[ "", "java", "unicode", "encoding", "" ]
I am implementing a stack in JavaScript. Consider: ``` Stack{0,1,2,3} Top:0 ``` Now the user pops the value of 2: ``` Stack{0,1,3} Top:0 ``` Is this an acceptable behavior for a stack? I am rolling my own stack, but is there any built in code that would do this for me? ### My code: ``` function Stack() //Creating Stack Object { // Create an empty array of cards. this.cards = new Array(); //Cards array inside stack object this.push = pushdata; //Call pushdata function on push operation this.pop = popdata; //Call popdata function on pop operation this.printStack = showStackData; //Call showStackData function on printstack operation } function pushdata(data) { this.cards.push(data); } function popdata(data) { return this.cards.pop(); } function showStackData() { return this.cards; } var a = new Stack(); //Create stack Object a.push(12); //Push Data onto Stack a.push(32); a.push(42); var z = a.pop(); document.write("Data Popped: " + z); document.write("Stack Output: " + a.printStack()); ``` If a stack is not the correct type of data structure for this application, what would be the correct one?
> Is it Legal doing the above operation in stack? That's not a traditional stack operation. A data structure that allowed you to do that couldn't really be called a stack; it's more of a plain old list. > If stack will not permits removing the data in between top and start.what are the alter datastructure used in javascript for above logic? Is there something wrong with a simple [Array](http://docs.sun.com/source/816-6408-10/array.htm)? It gives you the random-access item writing you want: ``` var a= [0, 1, 2, 3]; a.splice(1, 1); // a==[0, 2, 3] ``` plus stack-style convenience methods for accessing both front-loaded and tail stacks (and, consequently, queues): push/pop/shift/unshift. There's not much point making your own Stack() wrapper class when Array() already covers it IMO. Whilst a computer scientist might be interested in things like the algorithmic complexity of linked lists for stacks, in practice you aren't going to be able to improve on the optimised Array implementation built into modern JavaScript interpreters from higher-level code.
Not possible to do it with Pop (without popping other stuff along the way). You should look into providing another way for the user to find where the number 2 is located and another method for the user to extract that, such as using array splice. But by then this is no longer a stack. <http://www.w3schools.com/jsref/jsref_splice.asp>
Stack operation in JavaScript
[ "", "javascript", "data-structures", "stack", "" ]
Given a list of IP addresses how do I programmatically check if the local machine still has active TCP connections to these IP Addresses? I am using C#.
``` using System.Net.NetworkInformation IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties(); TcpConnectionInformation[] tcpInfoList = properties.GetActiveTcpConnections(); ```
Call [GetExtendedTcpTable](http://www.pinvoke.net/default.aspx/iphlpapi/GetExtendedTcpTable.html) and check through the list for your target addresses
Best way to check if a TCP connection is active
[ "", "c#", ".net", "tcp", "connection", "ip-address", "" ]
Is there a nicer way of doing the following: ``` try: a.method1() except AttributeError: try: a.method2() except AttributeError: try: a.method3() except AttributeError: raise ``` It looks pretty nasty and I'd rather not do: ``` if hasattr(a, 'method1'): a.method1() else if hasattr(a, 'method2'): a.method2() else if hasattr(a, 'method3'): a.method3() else: raise AttributeError ``` to maintain maximum efficiency.
Perhaps you could try something like this: ``` def call_attrs(obj, attrs_list, *args): for attr in attrs_list: if hasattr(obj, attr): bound_method = getattr(obj, attr) return bound_method(*args) raise AttributeError ``` You would call it like this: ``` call_attrs(a, ['method1', 'method2', 'method3']) ``` This will try to call the methods in the order they are in in the list. If you wanted to pass any arguments, you could just pass them along after the list like so: ``` call_attrs(a, ['method1', 'method2', 'method3'], arg1, arg2) ```
A slight change to the second looks pretty nice and simple. I really doubt you'll notice any performance difference between the two, and this is a bit nicer than a nested try/excepts ``` def something(a): for methodname in ['method1', 'method2', 'method3']: try: m = getattr(a, methodname) except AttributeError: pass else: return m() raise AttributeError ``` The other very readable way is to do.. ``` def something(a): try: return a.method1() except: pass try: return a.method2() except: pass try: return a.method3() except: pass raise AttributeError ``` While long, it's very obvious what the function is doing.. Performance really shouldn't be an issue (if a few try/except statements slow your script down noticeably, there is probably a bigger issue with the script structure)
Nested try statements in python?
[ "", "python", "try-catch", "" ]
I'm trying to use SQLAlchemy to implement a basic users-groups model where users can have multiple groups and groups can have multiple users. When a group becomes empty, I want the group to be deleted, (along with other things associated with the group. Fortunately, SQLAlchemy's cascade works fine with these more simple situations). The problem is that cascade='all, delete-orphan' doesn't do exactly what I want; instead of deleting the group when the group becomes empty, it deletes the group when *any* member leaves the group. Adding triggers to the database works fine for deleting a group when it becomes empty, except that triggers seem to bypass SQLAlchemy's cascade processing so things associated with the group don't get deleted. What is the best way to delete a group when all of its members leave and have this deletion cascade to related entities. I understand that I could do this manually by finding every place in my code where a user can leave a group and then doing the same thing as the trigger however, I'm afraid that I would miss places in the code (and I'm lazy).
The way I've generally handled this is to have a function on your user or group called leave\_group. When you want a user to leave a group, you call that function, and you can add any side effects you want into there. In the long term, this makes it easier to add more and more side effects. (For example when you want to check that someone is allowed to leave a group).
I think you want `cascade='save, update, merge, expunge, refresh, delete-orphan'`. This will prevent the "delete" cascade (which you get from "all") but maintain the "delete-orphan", which is what you're looking for, I think (delete when there are no more parents).
SQLAlchemy many-to-many orphan deletion
[ "", "python", "sqlalchemy", "" ]
Where in a Windows (Vista) system should I place data that ought to be readable *and* writable by everyone, i.e. every user of the computer? Vista's concepts of C:\Users\xxx\AppData\something, C:\Program Files and C:\ProgramData directories and UAC are a bit confusing. Furthermore, is there any ready solution to determine those locations with Java? I suppose that it requires some interaction with native libraries, since System.getProperties has just user.home and user.dir, neither of which is globally writable.
In vista c:\ProgramData is the place, this replaces what used to be C:\Documents and Settings\AllUsers\AppData in XP. I'm not sure about the specifics of doing this in java.. but, the ALLUSERSPROFILE environment variable gives you the path if you can get hold of that. You should always use this instead of hard coding the path, because the folder name changes on different internationalized versions of the OS.
If you need to allow users that do not have administrator privileges to modify the global settings then the proper approach is to create an installer for the application and during the install set the permissions on the "Common Application Data" folder such that users area allowed to write to it. See this post: [Where to put common writable application files?](https://stackoverflow.com/questions/147016/where-to-put-common-writable-application-files)
Where to put global application data in Vista?
[ "", "java", "windows-vista", "permissions", "directory", "global", "" ]
Is there a way in MS-Access to delete the data in all the tables at once. We run a database in access, save the data every month and then delete all the data in access. But it requires deleting data from a lot of tables. Isn't there a simpler/easier way to do so?
Why don't you keep an empty copy of the database on hand. At the end of the month, save the existing database, then copy the empty database in its place.
Craig's answer is simple and sensible. If you really want a programmatic solution, the following VBA script will clear all the data from every table excluding the hidden tables. It requires DAO to be enabled - in Visual Basic Editor, go to Tools -> References, and tick Microsoft DAO 3.6 Object Library, then OK: ``` Public Sub TruncateTables() 'Majority of code taken from a data dictionary script I can no longer source nor find the author On Error GoTo Error_TruncateTables Dim DB As DAO.Database Dim TDF As DAO.TableDef Dim strSQL_DELETE As String Set DB = CurrentDb() For Each TDF In DB.TableDefs If Left(TDF.Name, 4) <> "MSys" Then strSQL_DELETE = "DELETE FROM " & TDF.Name & ";" DB.Execute strSQL_DELETE End If Next MsgBox "Tables have been truncated", vbInformation, "TABLES TRUNCATED" DB.Close Exit_Error_TruncateTables: Set TDF = Nothing Set DB = Nothing Exit Sub Error_TruncateTables: Select Case Err.Number Case 3376 Resume Next 'Ignore error if table not found Case 3270 'Property Not Found Resume Next Case Else MsgBox Err.Number & ": " & Err.Description Resume Exit_Error_TruncateTables End Select End Sub ```
How to delete data in all ms-access tables at once?
[ "", "sql", "ms-access", "" ]
Do you know a site that offers a tutorial with sample source code for a 3-tier application (the usual data access layer, business layer and UI layer)? The simple, readable and intuitive the source code. Best practices that are applied to the code are welcome as well.
Take a look at [Appfuse](http://appfuse.org) , it's a quick-starter for java web application, provided with different frameworks : Tapestry , Spring MVC / Struts2 /JSF + Hibernate / Hibatis. It's based on a Maven build, all basic configurations done for you... One of the few 'realistic' sample that come to my mind... Another one is [the Petstore application from sun](http://java.sun.com/developer/technicalArticles/J2EE/petstore/), and looking for 'petstore download' on Google, you can find stuff that seems interesting (to me anyway, i didn't give it a look :-), like this [spring petstore](http://code.google.com/p/spring-petstore/), "an Ajax based application with DWR, Spring and Hibernate"...
The sample application I'm aware of are the following: * The famous [Java Pet Store](http://java.sun.com/developer/releases/petstore/) from Sun. In the version I've downloaded, it used a wide range of Java EE technologies, but it didn't use any modern MVC framework. * From the Spring project you have several applications: JPetStore, Pet Clinic and more. All come with the spring download. * The Seam framework has an [Hotel Booking application](http://docs.jboss.org/seam/latest/reference/en-US/html/tutorial.html) * You can also have a look at the 3 tier open source applications such as [Liferay](http://www.liferay.com/), but bare in mind that they may by very large. I'm not familiar with any that I can recommend, so please google for CRM/ERP/Protals etc. (sourceforge and freshmeat.net might be good sources as well) * Although it is backed by a CMS and not database, [Artifactory](http://sourceforge.net/projects/artifactory/) may also serve as a good example. Hope these help.
Java and J2EE code examples for 3-tier apps
[ "", "java", "jakarta-ee", "" ]
According to everything I've seen, the following C++ program should be displaying a balloon tool tip from the tray icon when I left-click in the application window, yet it's not working. Can anyone tell me what I'm missing? This is on XP with version 6.0 of Shell32.dll (verified with DllGetVersion). Thanks! ``` #include "stdafx.h" #include "shellapi.h" LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { MSG msg; WNDCLASS wc; memset(&wc, 0, sizeof(wc)); wc.lpfnWndProc = WndProc; wc.hInstance = hInstance; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wc.lpszClassName = "sysTrayTest"; RegisterClass(&wc); HWND hWnd = CreateWindow("sysTrayTest", "", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, 500, 500, NULL, NULL, hInstance, NULL); if (hWnd) { ShowWindow(hWnd, nCmdShow); while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return 0; } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_DESTROY: { NOTIFYICONDATA nid; memset(&nid, 0, sizeof(NOTIFYICONDATA)); nid.cbSize = sizeof(NOTIFYICONDATA); nid.hWnd = hWnd; nid.uID = 1; Shell_NotifyIcon(NIM_DELETE, &nid); PostQuitMessage(0); } break; case WM_CREATE: { NOTIFYICONDATA nid; memset(&nid, 0, sizeof(NOTIFYICONDATA)); nid.cbSize = sizeof(NOTIFYICONDATA); nid.hWnd = hWnd; nid.uID = 1; nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP; nid.uCallbackMessage = WM_USER + 200; nid.hIcon = LoadIcon(NULL, IDI_INFORMATION); lstrcpy (nid.szTip, "Test Tip"); Shell_NotifyIcon(NIM_ADD, &nid); } break; case WM_LBUTTONDOWN: { NOTIFYICONDATA nid; memset(&nid, 0, sizeof(NOTIFYICONDATA)); nid.cbSize = sizeof(NOTIFYICONDATA); nid.hWnd = hWnd; nid.uID = 1; nid.uFlags = NIF_INFO; lstrcpy(nid.szInfo, "Test balloon tip"); lstrcpy(nid.szInfoTitle, "Test Title"); nid.dwInfoFlags = NIIF_INFO; nid.uTimeout = 15000; Shell_NotifyIcon(NIM_MODIFY, &nid); } break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } ```
Bah, I figured it out. For some reason with the headers I have... sizeof(NOTIFYICONDATA) == 508 whereas... NOTIFYICONDATA`_`V3`_`SIZE == 504 NOTIFYICONDATA`_`V2`_`SIZE == 488 NOTIFYICONDATA`_`V1`_`SIZE == 88 If I specify either V2 or V3 instead of sizeof(NOTIFYICONDATA) the balloon tips show up just fine.
Have you checked in the registry under ... HKEY\_CURRENT\_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced ... for EnableBalloonTips? It's something very common for users to turn off.
Why aren't Shell_NotifyIcon balloon tips working?
[ "", "c++", "winapi", "tooltip", "windows-shell", "notifyicon", "" ]
Is there a Maven alternative or port for the .NET world? I would love to use a good dependency management system that the Java world has, but I don't find anything comparable for .NET projects...
[NMaven](http://incubator.apache.org/nmaven/) has been the first/official effort to provide [Apache Maven](http://maven.apache.org/) for .NET; the project failed to clear the high bar of requirements for an official Apache project and was retired from the Apache Incubator in November 2008. There have been several efforts to fork and survive the project, but only one of them ([NPanday](http://incubator.apache.org/npanday/)) managed to do so and has been able to rejoin the Apache Incubator in August 2010. Sadly also the NPanday project was retired in January 2015 because it is lacking active committers. * Active projects (as of July 2015) + none * Inactive projects (as of July 2015) + [NMaven: Maven plugins that do .NET Builds.](http://nmaven.codeplex.com/) + [Byldan: A .NET version of Maven. Written in C#.](http://byldan.codeplex.com/) + [NPanday: a project to integrate Apache Maven into .NET development environments.](http://incubator.apache.org/npanday/)
[NuGet](http://nuget.codeplex.com/) (formerly called NuPack) addresses some of the features of Maven. You can read about it at [Phil Haack](http://haacked.com/archive/2010/11/09/nuget-ctp2-released.aspx), [Scott Hanselman](http://www.hanselman.com/blog/PDC10BuildingABlogWithMicrosoftUnnamedPackageOfWebLove.aspx) and, of course, [Scott Guthrie](http://weblogs.asp.net/scottgu/archive/2010/10/06/announcing-nupack-asp-net-mvc-3-beta-and-webmatrix-beta-2.aspx).
Is there a Maven alternative or port for the .NET world?
[ "", "java", ".net", "maven-2", "build-process", "build", "" ]
There is a website which you can query with a domain and it will return a list of all the websites hosted on that IP. I remember there being a method in C# that was something like ReturnAddresses or something of that sort. Does anyone have any idea how this is done? Quering a hostname or IP and having returned a list of hostnames aka other websites hosted on the same server? the website is: <http://www.yougetsignal.com/tools/web-sites-on-web-server/>
After reading the comments, bobince is definitely right and these 2 should be used in tandem with each other. For best results you should use the reverse DNS lookup here as well as to use the passive DNS replication. ``` string IpAddressString = "208.5.42.49"; //eggheadcafe try { IPAddress hostIPAddress = IPAddress.Parse(IpAddressString); IPHostEntry hostInfo = Dns.GetHostByAddress(hostIPAddress); // Get the IP address list that resolves to the host names contained in // the Alias property. IPAddress[] address = hostInfo.AddressList; // Get the alias names of the addresses in the IP address list. String[] alias = hostInfo.Aliases; Console.WriteLine("Host name : " + hostInfo.HostName); Console.WriteLine("\nAliases :"); for(int index=0; index < alias.Length; index++) { Console.WriteLine(alias[index]); } Console.WriteLine("\nIP address list : "); for(int index=0; index < address.Length; index++) { Console.WriteLine(address[index]); } } catch(SocketException e) { Console.WriteLine("SocketException caught!!!"); Console.WriteLine("Source : " + e.Source); Console.WriteLine("Message : " + e.Message); } catch(FormatException e) { Console.WriteLine("FormatException caught!!!"); Console.WriteLine("Source : " + e.Source); Console.WriteLine("Message : " + e.Message); } catch(ArgumentNullException e) { Console.WriteLine("ArgumentNullException caught!!!"); Console.WriteLine("Source : " + e.Source); Console.WriteLine("Message : " + e.Message); } catch(Exception e) { Console.WriteLine("Exception caught!!!"); Console.WriteLine("Source : " + e.Source); Console.WriteLine("Message : " + e.Message); } ``` courtesy of <http://www.eggheadcafe.com/community/aspnet/2/83624/system-dns-gethostbyaddre.aspx>
Jeremy's answer is based around [Reverse DNS](http://en.wikipedia.org/wiki/Reverse_DNS), which is the normal programmatical way to look up IP->hostname. It relies an a PTR record being set up for that server; this is often but not always set up to something useful. For example look up, thedailywtf.com and you'll get 74.50.106.245, but since there is no PTR record for “245.106.50.74.in-addr.arpa”, Dns.GetHostEntry() won't return anything useful. Similarly, many server farms will just give you a generic hostname like 123.45.67.89-dedicated.bigexamplehost.com. What yougetsignal is doing is different, it's “Passive DNS Replication”. They run some DNS servers people are querying, and remember every hostname that was looked up. Then you can query their records of past lookups by the address that was returned. Put 74.50.106.245 into yougetsignal and you'll get a list of hostnames that previously resolved to the dailywtf server when people queried them, not anything to do with the Reverse DNS PTR entry.
Reverse IP Domain Check?
[ "", "c#", "dns", "" ]
This may seem frivolous to some of you, but which of the following 2 methods of **iteration** over a STL container is better? **Why**? ``` class Elem; typedef vector<Elem> ElemVec; ElemVec elemVec; // Method 0 for (ElemVec::iterator i = elemVec.begin(); i != elemVec.end(); ++i) { Elem& e = *i; // Do something } // Method 1 for (int i = 0; i < elemVec.size(); ++i) { Elem& e = elemVec.at(i); // Do something } ``` Method 0 seems like cleaner STL, but Method 1 achieves the same with lesser code. Simple iteration over a container is what appears *all* over the place in any source code. So, I'm inclined to pick Method 1 which seems to reduce visual clutter and code size. PS: I know iterators can do much more than a simple index. But, please keep the reply/discussion focused on simple iteration over a container like shown above.
The first version works with any container and so is more useful in template functions that take any container a s a parameter. It is also conceivably slightly more efficient, even for vectors. The second version only works for vectors and other integer-indexed containers. It'd somewhat more idiomatic for those containers, will be easily understood by newcomers to C++, and is useful if you need to do something else with the index, which is not uncommon. As usual, there is no simple "this one is better" answer, I'm afraid.
If you don't mind a (very?) small loss of efficiency, i'd recommend using [Boost.Foreach](http://www.boost.org/doc/libs/1_35_0/doc/html/foreach.html) ``` BOOST_FOREACH( Elem& e, elemVec ) { // Your code } ```
C++ STL: Which method of iteration over a STL container is better?
[ "", "c++", "stl", "iterator", "containers", "" ]
I'm a C# developer who is working through ["Real World Haskell"](http://book.realworldhaskell.org/) in order to truly understand functional programming, so that when I learn F#, I'll really grok it and not just "write C# code in F#", so to speak. Well, today I came across an example which I thought I understood 3 different times, only to then see something I missed, update my interpretation, and recurse (and curse too, believe me). Now I believe that I do actually understand it, and I have written a detailed "English interpretation" below. Can you Haskell gurus please confirm that understanding, or point out what I have missed? Note: The Haskell code snippet (quoted directly from the book) is defining a custom type that is meant to be isomorphic to the built in Haskell list type. **The Haskell code snippet** ``` data List a = Cons a (List a) | Nil defining Show ``` ***EDIT: After some responses, I see one misunderstanding I made, but am not quite clear on the Haskell "parsing" rules that would correct that mistake. So I've included my original (incorrect) interpretation below, followed by a correction, followed by the question that still remains unclear to me.*** **EDIT: Here is my original (incorrect) "English interpretation" of the snippet** 1. I am defining a type called "List". 2. The List type is parameterised. It has a single type parameter. 3. There are 2 value constructors which can be used to make instances of List. One value constructor is called "Nil" and the other value constructor is called "Cons". 4. If you use the "Nil" value constructor, then there are no fields. 5. The "Cons" value constructor has a single type parameter. 6. If you use the "Cons" value constructor, there are 2 fields which must be provided. The first required field is an instance of List. The second required field is an instance of a. 7. (I have intentionally omitted anything about "defining Show" because it is not part of what I want to focus on right now). **The corrected interpretation would be as follows (changes in BOLD)** 8. I am defining a type called "List". 9. The List type is parameterised. It has a single type parameter. 10. There are 2 value constructors which can be used to make instances of List. One value constructor is called "Nil" and the other value constructor is called "Cons". 11. If you use the "Nil" value constructor, then there are no fields. **5. (this line has been deleted ... it is not accurate) The "Cons" value constructor has a single type parameter.** 12. **If you use the "Cons" value constructor, there are 2 fields which must be provided. The first required field is an instance of a. The second required field is an instance of "List-of-a".** 13. (I have intentionally omitted anything about "defining Show" because it is not part of what I want to focus on right now). **The question which is still unclear** The initial confusion was regarding the portion of the snippet that reads "Cons a (List a)". In fact, that is the part that is still unclear to me. People have pointed out that each item on the line after the "Cons" token is a *type*, not a value. So that means this line says "The Cons value constructor has 2 fields: one of type 'a' and the other of type 'list-of-a'." That is very helpful to know. However, something is still unclear. When I create instances using the Cons value constructor, those instances "interpret" the first 'a' as meaning "place the value passed in here." But they do *not* interpret the second 'a' the same way. For example, consider this GHCI session: ``` *Main> Cons 0 Nil Cons 0 Nil *Main> Cons 1 it Cons 1 (Cons 0 Nil) *Main> ``` When I type "Cons 0 Nil", it uses the "Cons" value constructor to create an instance of List. From 0, it learns that the type parameter is "Integer". So far, no confusion. However, it *also* determines that the *value* of the first field of the Cons is 0. Yet it determines *nothing* about the *value* of the second field ... it only determines that the second field has a *type* of "List Integer". So my question is, why does "a" in the first field mean "the type of this field is 'a' *and* the value of this field is 'a'", while "a" in the second field means *only* "the type of this field is 'List of a'"? **EDIT: I believe I have now seen the light, thanks to several of the responses. Let me articulate it here. (And if somehow it is *still* incorrect in some fashion, please by all means let me know!)** In the snippet "Cons a (List a)", we are saying that the "Cons" value constructor has two fields, and that the first field is of type 'a', and that the second field is of type 'List of a'. **That is all we are saying!** In particular, we are saying *NOTHING* about values! This is a key point I was missing. Later, we want to create an instance, using the "Cons" value constructor. We type this into the interpreter: "Cons 0 Nil". This **explicitly** tells the Cons value constructor to use 0 for the value of the first field, and to use Nil as the value for the second field. And that's all there is to it. Once you know that the value constructor definition specifies *nothing but types*, everything becomes clear. Thanks everyone for the helpful responses. And as I said, if anything is still off, please by all means tell me about it. Thanks.
> * The "Cons" value constructor has a single type parameter. Nope: you've already parametrized it when you declared `data List a`. One effective property of this is that if I have a Nil :: List Int, I can't interchange it with a Nil :: List Char. > * If you use the "Cons" value constructor, there are 2 fields which must be provided. The first required field is an instance of List. The second required field is an instance of a. You've got it swapped: the first required field is an instance of a, the second field is an instance of List. [This chapter of Real World Haskell](http://book.realworldhaskell.org/read/defining-types-streamlining-functions.html) may be of interest. > Thanks. That is the chapter I'm on right now. So ... when the code says "Cons a (List a)", I thought the "Cons a" part of that was stating that the Cons value constructor was parameterised. They haven't yet covered the syntax for parameterised types, so I guessed that the syntax must require re-stating "a" if you intend to use a. But you're saying that's not necessary? And therefore that's not what that "a" means? Nope. Once we declare a parameter in our type, we get to reuse it otherwise to say "that type should be used there." It's a little bit like an `a -> b -> a` type signature: a is parameterizing the type, but then I have to use the same a as the return value. > OK, but this is confusing. It seems that the first "a" means "the first field is an instance of a", Nope, that is *not* true. It just means that the data type parametrizes over some type a. > and it ALSO means "the first field has the same value as the value they passed in for a". In other words, it specifies type AND value. No, that is also not true. Here's an instructive example, the syntax of which you may or may not have seen before: ``` foo :: Num a => a -> a ``` This is a fairly standard signature for a function that takes a number and does something to it and gives you another number. What I actually mean by "a number" in Haskell-speak, though, is some arbitrary type "a" that implements the "Num" class. Thus, this parses to the English: > Let a indicate a type implementing the Num typeclass, then the signature of this method is one parameter with the type a, and the return value of the type a Something similar happens with data. It also occurs to me that the instance of List in the specification of Cons is also confusing you: be really careful when parsing that: whereas Cons is specifying a constructor, which is basically a pattern that Haskell is going to wrap the data into, (List a) looks like a constructor but is actually simply a type, like Int or Double. a is a type, NOT a value in any sense of the term. **Edit:** In response to the most recent edit. I think a dissection is first called for. Then I'll deal with your questions point by point. Haskell data constructors are a little weird, because you define the constructor signature, and you don't have to make any other scaffolding. Datatypes in Haskell don't have any notion of member variable. (Note: there's an alternate syntax that this way of thinking is more amenable to, but let's ignore that for now). Another thing is that Haskell code is dense; its type signature are like that to. So expect to see the same symbol reused in different contexts. Type inferencing also plays a big role here. So, back to your type: ``` data List a = Cons a (List a) | Nil ``` I chunk this into several pieces: ``` data List a ``` This defines the name of the type, and any parameterized types that it will have later on. Note that you will only see this show up in other type signatures. ``` Cons a (List a) | Nil ``` This is the name of the data constructor. **This IS NOT a type**. We can, however, pattern match for it, ala: ``` foo :: List a -> Bool foo Nil = True ``` Notice how List a is the type in the signature, and Nil is both the data constructor and the "thing" we pattern match for. ``` Cons a (List a) ``` These are the types of the values we slot into the constructor. Cons has two entries, one is of type a, and one is of type List a. > So my question is, why does "a" in the first field mean "the type of this field is 'a' and the value of this field is 'a'", while "a" in the second field means only "the type of this field is 'List of a'"? Simple: don't think of it as us specifying the type; think of it has Haskell is inferencing the type out of it. So, for our intents and purposes, we're simply sticking a 0 in there, and a Nil in the second section. Then, Haskell looks at our code and thinks: * Hmm, I wonder what the type of Cons 0 Nil is * Well, Cons is a data constructor for List a. I wonder what the type of List a is * Well, a is used in the first parameter, so since the first parameter is an Int (another simplification; 0 is actually a weird thing that is typeclassed as Num), so that's mean a is a Num * Hey, well, that also means that the type of Nil is List Int, even though there's nothing there that would actually say that (Note, that's not actually how it's implemented. Haskell can do a lot of weird things while inferencing types, which is partially why the error messages suck.)
Analogies are usually lacking in all sorts of ways, but since you know C# I thought this might be helpful. This is how I would describe the `List a` definition in C#, maybe this clears some things up (or more likely, confuses you even more). ``` class List<A> { } class Nil<A> : List<A> { public Nil() {} } class Cons<A> : List<A> { public A Head; public List<A> Tail; public Cons(A head, List<A> tail) { this.Head = head; this.Tail = tail; } } ``` As you can see; * the `List` type has a single type parameter (`<A>`), * the `Nil` constructor doesn't have any parameters, * and the `Cons` constructor has two parameters, a value `head` of type `A` and a value `tail` of type `List<A>`. Now, in Haskell the `Nil` and `Cons` are just constructors for the `List a` data type, in C# they are also types in and of themselves, so that's where the analogy fails. But I hope this gives you some intuitive sense of what the different `A`'s represent. (And please do comment on how this horrible comparison doesn't do justice to Haskell's data types.)
Please confirm or correct my "English interpretation" of this Haskell code snippet
[ "", "c#", "haskell", "types", "f#", "algebraic-data-types", "" ]
> ## Duplicate > > * [Managing date formats differences between PHP and MySQL](https://stackoverflow.com/questions/415092/managing-date-formats-differences-between-php-and-mysql) > * [PHP/MySQL: Convert from YYYY-MM-DD to DD Month, YYYY?](https://stackoverflow.com/questions/744010/php-mysql-convert-from-yyyy-mm-dd-to-dd-month-yyyy) > * [Format DATETIME column using PHP after printing](https://stackoverflow.com/questions/668735/format-datetime-column-using-php-after-printing) > * [date formatting in php](https://stackoverflow.com/questions/638011/date-formatting-in-php/638022) Dear All, I have a PHP page where i wil be displaying some data from Mysql db. I have 2 dates to display on this page.In my db table, Date 1 is in the format d/m/Y (ex: 11/11/2002) and Date 2 is in the format d-m-Y (ex : 11-11-2002) I need to display both of this in the same format .The format i have stored in a variable $dateFormat='m/d/Y' Can any one guide me Thanks in advance
Use `strtotime` to convert the strings into a Unix timestamp, then use the `date` function to generate the correct output format. Since you're using the UK date format "d/m/Y", and strtotime expects a US format, you need to convert it slighly differently: ``` $date1 = "28/04/2009"; $date2 = "28-04-2009"; function ukStrToTime($str) { return strtotime(preg_replace("/^([0-9]{1,2})[\/\. -]+([0-9]{1,2})[\/\. -]+([0-9]{1,4})/", "\\2/\\1/\\3", $str)); } $date1 = date($dateFormat, ukStrToTime($date1)); $date2 = date($dateFormat, ukStrToTime($date2)); ```
You should be all set with this: ``` echo date($dateFormat, strtotime($date1)); echo date($dateFormat, strtotime($date2)); ```
PHP converting date format
[ "", "php", "mysql", "datetime", "" ]
I am trying to create an app in Qt/C++ with Qt4.5 and want the any active windows to change opacity on a mouseover event... As i understand it, there is no explicit mouseover event in Qt. However, I got rudimentary functioning by reimplementing QWidget's mousemoveevent() in the class that declares my mainwindow. But the mainwindow's mousemoveevent is not called whenever the mouse travels over any of the group boxes i have created in there (understandbly since QGroupbox has its own reimplementation of mousemoveevent). So as a cheap work around, I am still using the mousemoveevent of my mainwindow but a query the global mouse position and based on the (x,y) position of the mainwindow (obtained through ->pos()) and the window size (-> size -> rHeight and rWidth), I check if the mouse is within the bounds of the area of the mainwindow and change the opacity thus. This has had very limited success. The right border works fine, the the left changes opacity 4 pixels early. The top does not work (presumably because the mouse goes through the menubar and title bar) and the bottom changes way too early. I thought of creating an empty container QWidget class and then place all the rest in there, but i felt that it would still not solve the big issue of the base widget not receiving the mousemoveevent if it has already been implemented in a child widget. ***Please suggest any corrections/errors I have made in my method or any alternate methods to achieve this.*** p.s. I doubt this matters, but I am working Qt Creator IDE, not Qt integration into VS2008 (it's the same classes anyways - different compiler though, *mingw*)
Installing event filters for each of your child widgets might do the trick. This will allow your main window to receive child events such as the ones from you group boxes. You can find example code [here](http://doc.trolltech.com/4.5/qobject.html#eventFilter).
You may be interested in Event filters. QObject proves a way to intercept all events zipping around your application. <http://doc.trolltech.com/4.5/eventsandfilters.html#event-filters>
mouse over transparency in Qt
[ "", "c++", "qt", "transparency", "mouseover", "opacity", "" ]
I have an .aspx page setup. I have a lot of placeholders that need to be replaced. First name, last name, city, state, etc, etc. How do I go about doing this in an efficient manner? Drop a bunch of... ``` <asp:Label runat="server" id="Label_FirstName" Text="" /> ``` ...everywhere? Or is there a way to use the data binding syntax in the normal page area: ``` <% FirstName %> ``` Thanks in advance!
Note that ``` <asp:Label runat="server" id="Label_FirstName" Text="" /> ``` will escape your strings (for example, replace < and > with &lt; and &gt;), but ``` <%= FirstName %> ``` will not. If that's your intention that's fine then, but be aware that you might open a channel for [XSS attacks](http://en.wikipedia.org/wiki/Cross-site_scripting). To escape your strings properly, you might want to have ``` <%= System.Web.HttpUtility.HtmlEncode(FirstName) %> ``` instead.
You can certainly use: ``` <%= FirstName %> ``` Where FirstName is a property of the page. It doesn't necessarily have to be a property in the class, you can access pretty much anything from that line. **Update:** As DrJokepu pointed out, if the data you are displaying is coming from user input, then it opens a XSS vulnerability. As was pointed out you use HtmlEncode to avoid that, in that case a more short syntax would be: ``` <%= Server.HtmlEncode(FirstName) %> ``` And if you have a base page, you can get define a method and get away with: ``` <%= HtmlEncode(FirstName) %> ``` --- If you go with asp.net labels, do EnableViewState = false where appropiate, so you avoid sending/receiving unnecessary viewstate. --- For formatting use ids/css classes, and have the styles in a css stylesheet. The css can be cached by the browser regardless of whether the content is dynamic. --- For lists of info, you can use ListView or Repeaters and still control the specific html that will be sent over the wire.
Is there a best practice for string replacement in .aspx pages?
[ "", "c#", "asp.net", "data-binding", "templates", "replace", "" ]
I just got some C code that uses extern "C" to declare external functions like this: ``` extern "C" void func(); ``` Is this valid C? I'm getting an error at this line, but I'm not sure if it's because of this or something else.
No, it's not valid C. It should only be used in C++ code to refer to functions defined in C code. The `extern "C"` should be surrounded in a `ifdef __cplusplus`/`#endif` block: ``` // For one function #ifdef __cplusplus extern "C" #endif void func(); // For more than one function #ifdef __cplusplus extern "C" { #endif void func1(); void func2(); #ifdef __cplusplus } #endif ```
this is a C++ notation to tell the compiler/linker to use C calling standards. Usually that line is wrapped in an pre-processor statement. ``` #ifdef __cplusplus extern "C" { #endif // stuff #ifdef __cplusplus } #endif ```
Does extern "C" have any effect in C?
[ "", "c++", "c", "extern-c", "" ]
I've got your average e-Commerce app, I store ITEM\_IMAGE\_NAME in the database, and sometimes managers MISSPELL the image name. To avoid "missing images" (red X in IE), every time I display the list of products, I check the server for the image related to the product, and if that file doesn't exist - I replace it with default image. As far as i can tell this doesn't affect performance, but I was wondering **if there are any alternatives to fix a "missing image" problem.** I'm using ASP.NET + C# (.NET 3.5) Some code: ``` foreach (Item item in Items) { string path = Path.Combine("~/images/", item.categoryImage); item.categoryImage = File.Exists(Server.MapPath(path)) ? item.categoryImage : GetImageDependingOnItemType(); } ```
You might consider something with javascript ``` <img src="image.jpg" onerror="this.onerror=null;this.src='default.jpg'"> ``` Edit: Or program a 404.aspx returning a default image, if a nonexisting image was requested.
``` <style> .fallback { background-image: url("fallback.png"); } </style> <img class="fallback" src="missing.png" width="400" height="300"> ``` If `missing.png` loads, it will cover the space allocated for it, as if the fallback were not specified. (Assuming it's not transparent.) If `missing.png` fails to load, the space will instead be filled with `fallback.png`. You'll still get a little "broken image" icon, but I prefer it that way... a little hint that says "fix me". If your images aren't all the same size, you'll notice that the background tiles by default. You can use `background-repeat: no-repeat;` if you don't like that.
Best way to display default image if specified image file is not found?
[ "", "c#", "asp.net", "language-agnostic", "" ]
I am involved with a software project written in Qt and built with qmake and gcc on Linux. We have to link to a third-party library that is of fairly low quality and spews tons of warnings. I would like to use -W -Wall on our source code, but pass -w to the nasty third-party library to keep the console free of noise and clutter so we can focus on our code quality. In qmake, is there a way to conditionally add CFLAGS/CXXFLAGS to certain files and libraries?
Jonathan, I think the problem is where your source files are including header files from 3rd party libraries, and you want to switch off the warnings for the latter. Kevin, i think you can use pragmas to control warnings : [gcc diagnostic pragmas](http://gcc.gnu.org/onlinedocs/gcc-4.3.3/gcc/Diagnostic-Pragmas.html#Diagnostic-Pragmas "gcc diagnostic pragmas") You could add these before and after any #includes for 3rd party libs.
What if you include your library using -isystem. In the project file e.g.: ``` QMAKE_CXXFLAGS += -isystem /usr/local/boost_1_44_0 ```
Conditionally disable warnings with qmake/gcc?
[ "", "c++", "gcc", "conditional-statements", "compiler-warnings", "qmake", "" ]
Given a composite format string provided by the user (for use with `String.Format`) and a set of types representing the arguments that would be used to format the composite format string, how can you check that the user-provided value is valid? It should be pretty easy to create a regular expression to check that the general syntax of the argument placeholders match "`{index[,alignment][:formatString]}`" per [the documentation](http://msdn.microsoft.com/en-us/library/txafckwd.aspx). And not too much more difficult to verify that the indexes of the placeholders in the composite format string are less than the actual number of typed arguments (i.e. they don't reference an argument that won't be given). However, given the types for the arguments that will be passed in are known, it should also be possible to validate the "`:formatString`" is appropriate for those types. For example, you want to validate the user doesn't specify "`{0:dddd MMMM}`" as a format string when the first argument type (0 index) is a number (`String.Format("{0:dddd MMMM}", 1234)` yields "`dddd MMMM`"). The quantity of "`:formatString`" options by type is [too large](http://john-sheehan.com/blog/wp-content/uploads/msnet-formatting-strings.pdf) to want to manually check everything. Is there any other way? Or do you just have to live with the user potentially specifying a bad format string? Assume there are no custom [`IFormatProvider`](http://msdn.microsoft.com/en-us/library/system.iformatprovider.aspx), [`ICustomFormatter`](http://msdn.microsoft.com/en-us/library/system.icustomformatter.aspx) or [`IFormattable`](http://msdn.microsoft.com/en-us/library/system.iformattable.aspx) implementations in play here. Just basic types already in the .NET Framework. Bonus points for addressing the custom stuff.
There is no inbuilt way of doing this, AFAIK. You could code every common case manually, but I don't recommend it. (**edit**) One pragmatic option might be `try/catch` - test the format as early as possible when the user enters it....
Sorry, but the way to do it is: ``` try { string.Format(godKnowsWhat, aBunchOfArguments); } catch(FormatException) { // use exception for control flow lol } ``` Yep, kinda bad.
How do you validate a composite format string in C# against its target argument types?
[ "", "c#", "validation", "string.format", "" ]
I work in a company doing C++ development on VC6, and we're considering a move to VS 2008. What are the benefits of upgrading? What are the cons? Any guides/steps on migrating project files, or gotchas I should be aware of? Are people ok with moving to the different development interface?
For me, the biggest reason to upgrade to 2008 is the level of standards compliance in the C++ compiler. It is **vastly** improved from VC6 and is capable of using most libraries that you are familiar with or want to use. Including STL, BOOST and TR1. The downsides are the normal issues with upgrading. For example, improved standards compliance means that it may break some of your code which depended on non-standard behavior. No specific examples come to mind but I'm sure they're out there.
The benefits are: * You will be moving from a 5+ year old compiler which had poor template support to one which is much more up to date and standards compliant. * You will spend less time investigating compilation issues which turn out to be a known problem with the compiler and not a problem with your code. * Widely available C++ literature and documentation will be much more relevant to your compiler. Cons are: - It may take some time, time which might have been otherwise spent for instance adding new functionality to your product. The biggest issue in porting is likely to be any code you have which is non-compliant yet VC6 allowed to compile. This code may fail to compile on VS2008. I guess also some of the Win32 API's may have changed, likewise for the MFC & ATL classes. The easiest way to get a feel for the size of the problem is to tackle a single small project which has no dependencies on other VC projects. See how many errors you get and how long it takes to fix them.
From Visual Studio C++ 6.0 to VS 2008?
[ "", "c++", "visual-studio", "ide", "build", "" ]
If I have a: ``` Dictionary<string, int> ``` How do I copy all the values into a: ``` List<int> ``` Object? The solution needs to be something compatible with the 2.0 CLR version, and C# 2.0 - and I really dont have a better idea, other than to loop through the dictionary and add the values into the List object one-by-one. But this feels very inefficient. Is there a better way?
It's probably worth noting that you should step back and ask yourself if you really need the items stored in a list with random indexed access, or if you just need to enumerate each of the keys or values from time to time. You can easily iterate over the ICollection of MyDictionary.Values. ``` foreach (int item in dict.Values) { dosomething(item); } ``` Otherwise, if you actually need to store it as an IList, there's nothing particularly inefficient about copying all the items over; that's just an O(n) operation. If you don't need to do it that often, why worry? If you're annoyed by writing the code to do that, use: ``` IList<int> x=new List<int>(dict.Values); ``` which wraps the code that you'd write into a copy constructor that already implements the code you were planning to write. That's lines-of-code-efficient, which is probably what you actually care about; it's no more space-or-time efficient than what you'd write.
This should work even on 2.0 (forgive the C# 3.0 use of "var"): ``` var dict = new Dictionary<string, int>(); var list = new List<int>(dict.Values); ```
How do I Copy the Values of an IDictionary into an IList Object in .Net 2.0?
[ "", "c#", ".net", "generics", "performance", "c#-2.0", "" ]
Is it possible to use a relative path to an SQLite database file in the context.xml file of a Java web application? At present, I have: ``` <?xml version="1.0" encoding="UTF-8"?> <Context path="/mywebapp"> <Resource name="jdbc/mydb" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="myusername" password="mypassword" driverClassName="org.sqlite.JDBC" url="jdbc:sqlite://Users/me/NetBeansProjects/MyApp/web/my.db"/> </Context> ``` As you can see, the url attribute of the Resource tag currently specifies an absolute path to my.db. However, I am working on this project with a small team of developers as a class project. We are sharing the code through Subversion and currently, every time one of us updates our project, we have to manually replace the above path with the correct path for our computer. Thanks in advance. --- **UPDATE:** It appears that relative paths are not relative to the context.xml file, but to CATALINA\_HOME. Unfortunately that directory (where Tomcat is located) is in another user's home folder (1) to which I have ony read access: (1) /home/myprof/Tomcat/bin/ (2) /home/me/NetBeansProjects/MyApp/web/my.db I cannot include /me in the relative path because, as stated above, this project will run on multiple computers via a svn repository and the directory in which the project files are contained (2) will change. However, since all of the accounts are on a shared virtual network, CATALINA\_HOME (1) will not change. --- Also, how can I get the path to the database file my.db from the context.xml file above inside a servlet?
I found the answer to my question [here](https://stackoverflow.com/questions/2242980). The solution is to get the resource rather than try to parse the database URL out of the context.xml file.
I have found following examples of using JDBC with SQLite: * For memory access: ``` jdbc:sqlite::memory: ``` * For relative paths: ``` jdbc:sqlite:relative/path.db ``` * For absolute paths: ``` jdbc:sqlite:/absolute/path.db ```
Relative path to SQLite DB in context.xml
[ "", "java", "sqlite", "netbeans", "jakarta-ee", "relative-path", "" ]
Yes I've seen [this](https://stackoverflow.com/questions/665494/c-why-funct-bool-instead-of-predicatet) but I couldn't find the answer to my specific question. Given a lambda **testLambda** that takes T and returns a boolean (I can make it either Predicate or Func that's up to me) I need to be able to use both List.FindIndex(testLambda) (takes a Predicate) and List.Where(testLambda) (takes a Func). Any ideas how to do both?
Easy: ``` Func<string,bool> func = x => x.Length > 5; Predicate<string> predicate = new Predicate<string>(func); ``` Basically you can create a new delegate instance with any *compatible* existing instance. This also supports variance (co- and contra-): ``` Action<object> actOnObject = x => Console.WriteLine(x); Action<string> actOnString = new Action<string>(actOnObject); Func<string> returnsString = () => "hi"; Func<object> returnsObject = new Func<object>(returnsString); ``` If you want to make it generic: ``` static Predicate<T> ConvertToPredicate<T>(Func<T, bool> func) { return new Predicate<T>(func); } ```
I got this: ``` Func<object, bool> testLambda = x=>true; int idx = myList.FindIndex(x => testLambda(x)); ``` Works, but ick.
How to convert Func<T, bool> to Predicate<T>?
[ "", "c#", ".net-3.5", "lambda", "" ]
I am planning to write a code library to access some hardware at a low-level (i.e. flipping register bits and such). Previously, I wrote everything as C functions and used extern "C" to make the library compile for both C and C++ code. So, both C and C++ users merely had to include the header file and call the functions as they were. Now, I am thinking of organising things as classes. For example, I can put all the functions to initialise, configure, transmit and receive a UART in a class. This works fine in C++ but how about C? I can't extern "C" an entire class. One thing that I was thinking of: write everything in standard C functions escaped with extern "C". Then, provide a wrapper class for C++, that has a bunch of inline methods that call these 'C' functions. ``` int foo_bar (int *address, int data) {...} // extern C stuff int foo::bar (int *address, int data) { return foo_bar(address, data); } // inline method ``` Is that okay? Any other ideas? Best practices?
There is some precedent for what you're proposing - Microsoft's MFC classes are just C++ wrappers around the C-compatible Windows API. Before you start though, you should have some goal in mind beyond just creating busywork for yourself. The C++ should be easier to work with than the C, or you're not gaining anything.
One solid reason for doing this is if your C interface uses the typical "handle" idiom to represent resources. ``` OpaqueThingHandle t = CreateOpaqueThing(); DoStuffWithOpaqueThing(t); DestroyOpaqueThing(t); ``` In C, to achieve information hiding, the `OpaqueThingHandle` is often a typedef for `void *` so that clients have no visibility of how it is implemented. C++ wrappers will be able to add something genuinely useful simply by applying RAAI - mapping construction and destruction on to the functions that aquire or free the resource identified by the handle type: ``` class OpaqueThing : boost::noncopyable { OpaqueThingHandle handle; public: OpaqueThing() : handle(CreateOpaqueThing()) {} ~OpaqueThing() { DestroyOpaqueThing(handle); } void DoStuff() { DoStuffWithOpaqueThing(handle); } }; ```
Co-mingling low-level C/C++ code
[ "", "c++", "c", "" ]
I was wondering if anyone knew of a way to access a hidden field (by client id) within a table row using jquery. ``` $("#tblOne").find("tr").click(function() { var worker = $(this).find(":input").val(); }); ``` I find that the above works for a row that has only one input, but I need some help figuring out a way to get the value by the inputs name. Here's the example of a table row. How would I access the two fields by their id's? ``` <table id="tblOne"> <tr> <td> <asp:HiddenField id="hdnfld_Id" Text='<% Eval("ID") %>'></asp:HiddenField> </td> <td> <asp:HiddenField id="hdnfld_Id2" Text='<% Eval("ID2") %>'></asp:HiddenField> </td> </tr> </table> ```
With the way you have it setup right now, you could do this: ``` $('tr td', '#tblOne').eq(0).find(':input').val(); // find input in 1st TD $('tr td', '#tblOne').eq(1).find(':input').val(); // find input in 2nd TD ``` Using this you don't have to worry about the input's ClientID.
I normally use a positive lookup to match the id, this method avoids requiring the client id (id contains foo) $(this).find("input[id\*='foo']").val();
Jquery Hidden Field in Table
[ "", "javascript", "jquery", "row", "html-table", "hidden-field", "" ]
**EDIT!!** I should add that this site runs perfectly locally. It's only when deployed that there's this issue **ORIGINAL POST:** I have a site I just put up <http://splattonet0.web704.discountasp.net/> Which loads the Index view of the Home controller just fine. However, when one clicks the links to the left, the webserver is looking for the relative paths (ie E:\web\splattonet0\htdocs\Home\AboutMe) which is incorrect, since Home folder is of course under a folder called "Views" I've made MVC sites before and have never had this problem. I can't see any difference between this or any other site I've done. My code in my master template for the link section is as follows: ``` <div id="navContainer"> <ul id="mainNav"> <li><a href="/Home/Index" title="Home">Home</a></li> <li><a href="/Home/AboutMe" title="About Us">About Me</a></li> <li><a href="/Skills/Index" title="Skills">Skills</a></li> <li><a href="/Home/Resume" title="Resume">Resume</a></li> <li><a href="/Home/Experience" title="Experience">Experience</a></li> <li><a href="/Home/SitesIveDesigned" title="Websites I've developed">My Websites</a></li> <li><a href="/Home/References" title="References">References</a></li> <li><a href="/Home/Projects" title="Projects">Projects</a></li> <li><a href="/Home/Hobbies" title="Hobbies">Hobbies</a></li> ....etc </ul> </div> ``` I have the same problem with and without the preceeding foreslash in the href property. I've decided to keep it there since that is how my other sites (that work!) are styled. Can anyone shed some light on this for me? Thanks! **FURTHER EDIT:** I have been asked to provide code from an MVC site on this server I have written and that works fine. The link code in the other site ([YorkCentre](http://yorkcentreconservative.ca/)) is the same style: `<li><a href="/Controller/Action">text</a></li>` The code: ``` <li><a href="/News/Index">Archived News</a></li> <li><a href="/Home/BoardOfDirectors">Board Of Directors</a></li> <li><a href="/Media/Index">In The Media</a> ... </ul> ```
I have resolved the problem! In DiscountASP I have changed the Application Pool Pipeline Mode from Classic to Integrated and that results in my views being properly rendered.
/Home/Index should be calling the "Index" action of the "Home" controller, assuming you're using default routes. The fact that "Home" is under the "Views" folder is irrelevant for MVC.
MVC site using relative paths for links instead of view syntax
[ "", "c#", "asp.net", "asp.net-mvc", "" ]
This is not academic code or a hypothetical quesiton. The original problem was converting code from HP11 to HP1123 Itanium. Basically it boils down to a compile error on HP1123 Itanium. It has me really scratching my head when reproducing it on Windows for study. I have stripped all but the most basic aspects... You may have to press control D to exit a console window if you run it as is: ``` #include "stdafx.h" #include <iostream> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { char blah[6]; const int IAMCONST = 3; int *pTOCONST; pTOCONST = (int *) &IAMCONST; (*pTOCONST) = 7; printf("IAMCONST %d \n",IAMCONST); printf("WHATISPOINTEDAT %d \n",(*pTOCONST)); printf("Address of IAMCONST %x pTOCONST %x\n",&IAMCONST, (pTOCONST)); cin >> blah; return 0; } ``` Here is the output ``` IAMCONST 3 WHATISPOINTEDAT 7 Address of IAMCONST 35f9f0 pTOCONST 35f9f0 ``` All I can say is what the heck? Is it undefined to do this? It is the most counterintuitive thing I have seen for such a simple example. **Update:** Indeed after searching for a while the Menu Debug >> Windows >> Disassembly had exactly the optimization that was described below. ``` printf("IAMCONST %d \n",IAMCONST); 0024360E mov esi,esp 00243610 push 3 00243612 push offset string "IAMCONST %d \n" (2458D0h) 00243617 call dword ptr [__imp__printf (248338h)] 0024361D add esp,8 00243620 cmp esi,esp 00243622 call @ILT+325(__RTC_CheckEsp) (24114Ah) ``` Thank you all!
Looks like the compiler is optimizing ``` printf("IAMCONST %d \n",IAMCONST); ``` into ``` printf("IAMCONST %d \n",3); ``` since you *said* that `IAMCONST` is a `const int`. But since you're taking the address of `IAMCONST`, it has to actually be located on the stack somewhere, and the `const`ness can't be enforced, so the memory at that location (`*pTOCONST`) is mutable after all. In short: you casted away the `const`ness, don't do that. Poor, defenseless C... ### Addendum Using GCC for x86, with `-O0` (no optimizations), the generated assembly ``` main: leal 4(%esp), %ecx andl $-16, %esp pushl -4(%ecx) pushl %ebp movl %esp, %ebp pushl %ecx subl $36, %esp movl $3, -12(%ebp) leal -12(%ebp), %eax movl %eax, -8(%ebp) movl -8(%ebp), %eax movl $7, (%eax) movl -12(%ebp), %eax movl %eax, 4(%esp) movl $.LC0, (%esp) call printf movl -8(%ebp), %eax movl (%eax), %eax movl %eax, 4(%esp) movl $.LC1, (%esp) call printf ``` copies from `*(bp-12)` on the stack to `printf`'s arguments. However, using `-O1` (as well as `-Os`, `-O2`, `-O3`, and other optimization levels), ``` main: leal 4(%esp), %ecx andl $-16, %esp pushl -4(%ecx) pushl %ebp movl %esp, %ebp pushl %ecx subl $20, %esp movl $3, 4(%esp) movl $.LC0, (%esp) call printf movl $7, 4(%esp) movl $.LC1, (%esp) call printf ``` you can clearly see that the constant `3` is used instead. If you are using Visual Studio's `CL.EXE`, `/Od` disables optimization. This varies from compiler to compiler. Be warned that the C specification [allows](http://en.wikipedia.org/wiki/Type_punning) the C compiler to assume that the target of any `int *` pointer never overlaps the memory location of a `const int`, so you really shouldn't be doing this at all if you want predictable behavior.
The constant value IAMCONST is being inlined into the printf call. What you're doing is at best wrong and in all likelihood is undefined by the C++ standard. My **guess** is that the C++ standard leaves the compiler free to inline a const primitive which is local to a function declaration. The reason being that the value should not be able to change. Then again, it's C++ where should and can are very different words.
Does the evil cast get trumped by the evil compiler?
[ "", "c++", "" ]
I have some C# code I'm trying to convert to VB.NET. There are some external dependencies I'm referencing in each project. The C# line is ``` TWriteFileCommand writeFile = (TWriteFileCommand)CommunicationLink.CreateCommand(TOPKernel.TCommand.CommandType.WriteFile); ``` I don't really understand what the TWriteFileCommand in parathesis after the equal sign is for in that statement. When I try to do it in VB.NET, I keep getting errors because I can't get a reference to the CreateCommand function. The closest I've gotten is this: ``` Dim MyAppBase As OPSupport.App.AppBase Dim writeFile As TWriteFileCommand writeFile = MyAppBase.CommunicationLink.CreateCommand(TOPKernel.TCommand.CommandType.WriteFile) ``` However, I have a green underline after the equal sign @ MyAppBase that flags an error "Variable MyAppBase is used before it has been assigned a value. A null reference exception could result at runtime." What am I missing? Why in the C# code is the instance fine and what do I need to get the equivalent instance in VB.NET? Please advise.
The direct equivalent is: ``` Dim writeFile As TWriteFileCommand writeFile = DirectCast(CommunicationLink.CreateCommand(TOPKernel.TCommand.CommandType.WriteFile), TWriteFileCommand) ```
That is a cast; if `CreateCommand` returns `object`, `CommandBase`, or anything like that - it does the type-check to `TWriteFileCommand`. If you have compiling C# code - can you use reflector to do the translation? This shows you C# and equivalent VB at a flip of a drop-down. I'm not sure what the `MyAppBase` is doing; that didn't exist in the C# - why did you add it to the VB? **edit** I don't "do" VB, but I looked it up in reflector; `(Foo)bar` becomes `DirectCast(bar, Foo)`.
Convert code C# to VB - Function references
[ "", "c#", "vb.net", "" ]
I'm implementing a event system: Various pieces of code will post events to a central place where they will be distributed to all listeners. The main problem with this approach: When an exception happens during event processing, I can't tell anymore who posted the event. So my question is: Is there an efficient way to figure out who called the constructor and remember that in Python 2.5? More info: The simple way would be to use the traceback module to get a copy of the stack in the constructor and remember that. Alas, I only need this information rarely, so I'm wondering if there was a way to cache this or whether I could just remember the topmost stack frame and work my way back in the rare case that I actually need this data.
``` import sys def get_caller(ext=False): """ Get the caller of the caller of this function. If the optional ext parameter is given, returns the line's text as well. """ f=sys._getframe(2) s=(f.f_code.co_filename, f.f_lineno) del f if ext: import linecache s=(s[0], s[1], linecache.getline(s[0], s[1])) return s def post_event(e): caller=get_caller(True) print "Event %r posted from %r"%(e, caller) ## Testing the functions. def q(): post_event("baz") post_event("foo") print "Hello!" q() ``` results in ``` Event 'foo' posted from ('getcaller.py', 20, 'post_event("foo")\n') Hello! Event 'baz' posted from ('getcaller.py', 17, '\tpost_event("baz")\n') ```
You could simply store a reference to the caller's frame object, but this is probably a bad idea. This keeps the frames alive, and also holds references to all the local variables used, so it may impact performance if they happen to be using large chunks of memory, and could have even worse effects if they're relying (incorrectly) on finalization to destroy resources like locks and filehandles when they go out of scope. That means you'd need to hold a string representation of the stacktrace instead, which is not ideal for your purposes (need to actually do some processing to get it, even though it's rarely needed). Unfortunately, there doesn't seem to be much way around this, though you could consider disabling it until you set some configuration option. That way you'd get better performance for the common case, but could still enable the setting when trying to diagnose failures. If your calling function alone (or some small number of parent callers) is enough to distinguish the route (ie. the trace is always the same when called via func1(), and there's no func2 -> func1() vs func3() -> func1() to distinguish between ), you could maintain a hash based on filename and line number of the calling frame (or the last two calling frames etc). However this probably doesn't match your situation, and where it doesn't, you'd end up with bogus stack traces. Note that if you do want the caller's frame, using [`inspect.currentframe(depth)`](http://docs.python.org/library/inspect.html#inspect.currentframe) is probably a better way to get it.
Locating (file/line) the invocation of a constructor in python
[ "", "python", "exception", "event-handling", "stack-trace", "" ]
I have a requirement where I have to fetch some records from the database and then I have to show 50 records per page on a JSP. The page will be having First, Previous, Next and Last buttons on the screen. Has anyone implemented similar functionality in struts or similar framework? also i dont want to get all records at once. please guide me how to implement? Thanks in Advance
I use the [Displaytag](http://displaytag.sourceforge.net/1.2/) library for this. It works great in combination with Struts and jsp and provides sorting and pagination.
maybe you can try some JQuery plugin that handles all client-side processing and take data from the server-side code. You migh try <http://www.datatables.net/> because it handles pagination, filtering, ordering and has much more features. Here is explained how you can integrate DataTables with java servlet application <http://www.codeproject.com/KB/java/JQuery-DataTables-Java.aspx>.
pagination in struts
[ "", "java", "struts2", "" ]
How to convert all elements from enum to string? Assume I have: ``` public enum LogicOperands { None, Or, And, Custom } ``` And what I want to archive is something like: ``` string LogicOperandsStr = LogicOperands.ToString(); // expected result: "None,Or,And,Custom" ```
``` string s = string.Join(",",Enum.GetNames(typeof(LogicOperands))); ```
You have to do something like this: ``` var sbItems = new StringBuilder() foreach (var item in Enum.GetNames(typeof(LogicOperands))) { if(sbItems.Length>0) sbItems.Append(','); sbItems.Append(item); } ``` Or in Linq: ``` var list = Enum.GetNames(typeof(LogicOperands)).Aggregate((x,y) => x + "," + y); ```
All Enum items to string (C#)
[ "", "c#", ".net", "enums", "" ]
Has anyone written any code where the application in its lifetime learn and improve itself (using observed data stored in a KB),are there any frameworks for this?
I wrote a learning `Tic Tac Toe` (or `Noughts and Crosses`) game once. Does that count? It basically maintained a 39 element array which was for each game state. At the end of each game, it would add one to all the states during that game if it had won. Or subtract one if it had lost (including rotations and mirror images for faster learning). When deciding on a move, it only had to consult a few possibilities and choose the one with the highest score. It ended up getting quite good but not by playing a person, that was taking too long. It had to be set loose playing another copy of itself, a random bot and a hard-coded rule bot for many, many thousands of games. When I unleashed it, it had 10 starting levels of intelligence which were just different stages during its learning process. My son is currently playing against the dumbest level - he's only four years old so I don't want to be too rough on him, so they'll learn together (although he occasionally beats me at `Connect Four`, so maybe I should put some more pressure on him).
I would suggest starting to look at alot of advanced AI topics on the web: such topics include neural networks, genetic programming ect (wikipedia them). Good places to look also include University research into higher levels of AI. (ie. I know of a team of people that wrote a program which extrapolated the laws of motion from making a computer watch a pendulum swing with a camera; very cool stuff) <http://blog.wired.com/wiredscience/2009/04/newtonai.html> It is a really big field and alot of code will need to be written by you; what you should really focus on is the concepts behind the learning algorithms, that way you can program or adapt the ones you find to your needs. I think that will be your best bet for creating a learning algorithm. I hope that helps.
Autonomous Software
[ "", "c#", "self", "" ]
I have a python (2.5.4) script which I run in cygwin (in a DOS box on Windows XP). I want to include a pound sign (£) in the output. If I do so, I get this error: ``` SyntaxError: Non-ASCII character '\xa3' in file dbscan.py on line 253, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details ``` OK. So I looked at that PEP, and now tried adding this to the beginning of my script: ``` # coding=cp437 ``` That stopped the error, but the output shows ú where it should show £. I've tried ISO-8859-1 as well, with the same result. Does anyone know which encoding I need? Or where I could look to find out?
There are two encodings involved here: * The encoding of your source code, which must be correct in order for your input file to mean what you think it means * The encoding of the output, which must be correct in order for the symbols emitted to display as expected. It seems your output encoding is off now. If this is running in a terminal window in Cygwin, it is that terminal's encoding that you need to match. **EDIT**: I just ran the following Python program in a (native) Windows XP terminal window, thought it was slightly interesting: ``` >>> ord("£") 156 ``` 156 is certainly not the codepoint for the pound sign in the Latin1 encoding you tried. It doesn't [seem to be](http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1252.TXT) in Window's Codepage 1252 either, which I would expect my terminal to use ... Weird.
The Unicode for a pound sign is 163 (decimal) or A3 in hex, so the following should work regardless of the encoding of your script, as long as the output encoding is working correctly. ``` print u"\xA3" ```
What encoding do I need to display a GBP sign (pound sign) using python on cygwin in Windows XP?
[ "", "python", "encoding", "python-2.5", "" ]
I have read this excellent [Multi-column list article](http://www.alistapart.com/articles/multicolumnlists), as well as [this question on SO](https://stackoverflow.com/questions/486349/dividing-long-list-of-li-tags-into-columns). I've come to the conclusion that there is no cross-browser way to turn a long unordered list into *n* columns of equal length. So far, I have been reduced to multiple-ul solutions like this: ``` //Three columns. string col1 = string.Empty; string col2 = string.Empty; string col3 = string.Empty; int currItem = 0; int collectionCount = myItemCollection.Count; foreach item in myItemCollection { currItem++; if (currItem < collectionCount * .33) { col1 = col1 + item.someProperty } else if (currItem < collectionCount * .67) { col2 = col2 + item.someProperty } else { col3 = col3 + item.someProperty } } string allColumns = @"<ul>" + col1 + "</ul><ul>" col2 + "</ul><ul>" + col3 + "</ul>"; Response.Write(allColumns); ``` Is there a simpler way to separate my list into groups of three, or better yet, to simply write the appropriate closing/starting ul tags when an element is the last item in a "third"?
This is how I personally would choose to implement it. ``` const int numColumns = 3; const int numColumns = 3; var columnLength = (int)Math.Ceiling((double)myItemCollection.Count / 3); for (int i = 0; i < myItemCollection.Count; i++) { if (i % columnLength == 0) { if (i > 0) Response.Write("</ul>"); Response.Write("<ul>"); } Response.Write(myItemCollection[i].SomeProperty); } if (i % columnLength == 0) Response.Write("</ul>"); ``` You avoid string concatenation altogether (there's really no need when you're just writing to a stream, and if you weren't you'd want to xse `StringBuilder`) as well as those nasty floating point operations which could potentially cause inaccuracies for long lists (at the very least they're unnecesary). Anyway, hope that helps...
This is too late, but Response.Write will output in an unpredictable place, most likely ahead of all other output. The "proper" code should be building controls on CreateChildren, Page\_Load or any other place: ``` List<string> items = new List<string>() { "aaa", "bbb", "ccc", "ddd", "eee" }; int colSize = (int)Math.Ceiling(items.Count / 3.0); HtmlGenericControl ul = null; for (int i = 0; i < items.Count; i++) { if (i % colSize == 0) { ul = new HtmlGenericControl("ul"); Page.Form.Controls.Add(ul); } HtmlGenericControl li = new HtmlGenericControl("li"); li.InnerText = items[i]; ul.Controls.Add(li); } ``` This way you don't need to be concerned about rendering and tracking opening/closing tags.
What is the best way divide content between n columns?
[ "", "c#", "asp.net", "html", "css", "" ]
I want to to make to make the ordering in my query conditional so if it satisfiess the condition it should be ordered by descending For instance: ``` SELECT * FROM Data ORDER BY SortOrder CASE WHEN @Direction = 1 THEN DESC END ```
Don't change the `ASC` or `DESC`, change the sign of the thing being sorted-by: ``` SELECT * FROM table ORDER BY CASE WHEN @Direction = 1 THEN -id else id END asc; ``` The OP asks: > Guys, I am not the SQL Expert, please explain me what means the id and -id, does it controls the ordering direction? id is just whatever column you're sorting by; -id is just the negation of that, id \* -1. If you're sorting by more than one column, you'll need to negate each column: ``` SELECT * FROM table ORDER BY CASE WHEN @Direction = 1 THEN -id else id END CASE WHEN @Direction = 1 THEN -othercolumn else othercolumn END ; ``` If you're ordering by a non numeric column, you'll need to find an expression that makes that column "negative"; writing a function to do that may help.
``` SELECT * FROM Data ORDER BY Case WHEN @Direction = 1 THEN SortOrder END DESC, Case WHEN 1=1 THEN SortOrder END ```
MS Sql: Conditional ORDER BY ASC/DESC Question
[ "", "sql", "sql-server", "sql-order-by", "" ]
A wide range of structures is used in Win32 programming. Many times only some of their fields are used and all the other fields are set to zero. For example: ``` STARTUPINFO startupInfo; // has more than 10 member variables ZeroMemory( &startupInfo, sizeof( startupInfo ) ); //zero out startupInfo.cb = sizeof( startupInfo ); //setting size is required according to MSDN startupInfo.dwFlags = STARTF_FORCEOFFFEEDBACK; //Now call CreateProcess() passing the startupInfo into it ``` I want to stop copy-pasting such code and instead use an abstraction that would care about zeroing and setting parameters. Let's presume I only need the struct initialized as in example, and no other tuning is ever needed. Is the following a good solution? What are possible problems? ``` class CStartupInfo : public STARTUPINFO { public: CStartupInfo() { ZeroMemory( this, sizeof( STARTUPINFO ) ); cb = sizeof( STARTUPINFO ); dwFlags = STARTF_FORCEOFFFEEDBACK; } }; ``` I'm in particular concerned about the ZeroMemory() call - looks like I fully control the code and the class has no vtable and calling ZeroMemory() this way is safe and there's no big difference between the two code snippets except that the latter provides an abstraction. Are there any caveats?
I think this is a fine way to make such structures more bulletproof. I'm not sure why others seem to not like the technique. I use it occasionally, but not as often as I otherwise might because it doesn't seem to be very well liked by coworkers for some reason. I don't see it used in published material very often - the only one I could find in a quick Google right now is an article by Paul DiLascia in MSJ August 1997 (<http://www.microsoft.com/MSJ/0897/C0897.aspx>): > `CRebarInfo` and `CRebarBandInfo` are programmer-friendly C++ versions of the C structs `REBARINFO` and `REBARBANDINFO`, with constructors that initialize the objects to all zeroes before setting the `cbSize` member appropriately. I can't think of much in the way of drawbacks (except the lack of acceptance). If anyone else can point to something more concrete, I'd appreciate it.
For structures you can do: ``` STARTUPINFO startup_info = { sizeof(STARTUPINFO), 0 }; startup_info.dwFlags = STARTF_FORCEOFFFEEDBACK; ``` which I find is a neat trick to initialise these sort of structures. However the catch is that the cb (or size/length) field must be the first one in the structure. You could also just do the extended version if need be: ``` STARTUPINFO startup_info = { 0 }; startup_info.cb = sizeof(STARTUPINFO); startup_info.dwFlags = STARTF_FORCEOFFFEEDBACK; ``` If you want to wrap the structures with a class I'd recommend you try ATL/WTL first since the structures you're wrapping might already exist as classes there. If you were still keen on creating your own class I would suggest that you create a constructor that takes every element of the structure in order, with default parameters specified, so that it's easier to change those values later on.
Zeroing out a struct in the constructor
[ "", "c++", "winapi", "" ]
In PHP with DOM, I have a DomElement object which represents an <identity/> element. I have one case where I need to change this so its element name is <person/>, but keep the same child elements and attributes. What would be the simplest way of changing an element name of a DomElement and keeping its children and attributes? *Edit: I have just found a [very similar question](https://stackoverflow.com/questions/237786/is-there-a-better-way-to-change-a-domelement-tagname-property-in-php) (though it doesn't have very good answers).*
Could you use `importNode()` to copy the childNodes of your `<identity>` element to a newly created `<person>` element? ``` function changeName($node, $name) { $newnode = $node->ownerDocument->createElement($name); foreach ($node->childNodes as $child){ $child = $node->ownerDocument->importNode($child, true); $newnode->appendChild($child, true); } foreach ($node->attributes as $attrName => $attrNode) { $newnode->setAttribute($attrName, $attrNode); } $newnode->ownerDocument->replaceChild($newnode, $node); return $newnode; } $domElement = changeName($domElement, 'person'); ``` Perhaps something like that would work, or you could try using `cloneChild()`. Edit: Actually, I just realized that the original function would lose the placement of the node. As per the question thomasrutter linked to, `replaceChild()` should be used.
Thanks to your post, I could quickly solve the same issue for me. However, I had a DOM\_NOT\_FOUND exception. This is probably a PHP Version issue, since the original post is 5 years old. According to the PHP Documentation (Feb 2014) ``` DOM_NOT_FOUND Raised if oldnode is not a child of this node. ``` So, I have replaced ``` $newnode->ownerDocument->replaceChild($newnode, $node); ``` with ``` $node->parentNode->replaceChild($newnode, $node); ``` Here is the complete function (tested): ``` public static function changeTagName($node, $name) { $childnodes = array(); foreach ($node->childNodes as $child){ $childnodes[] = $child; } $newnode = $node->ownerDocument->createElement($name); foreach ($childnodes as $child){ $child2 = $node->ownerDocument->importNode($child, true); $newnode->appendChild($child2); } foreach ($node->attributes as $attrName => $attrNode) { $attrName = $attrNode->nodeName; $attrValue = $attrNode->nodeValue; $newnode->setAttribute($attrName, $attrValue); } $node->parentNode->replaceChild($newnode, $node); return $newnode; } ``` It is also worth mentioning that when you want to use this function, you should traverse the DOM Tree in reversed order as explained in other posts. UPDATE: After months of using and updating to PHP Version 5.5.15 on windows, I had an error saying $attr could not be converted to a string. So I updated third for-each loop above.
How can I change the name of an element in DOM?
[ "", "php", "xml", "dom", "" ]
Is it possible to write some C or C++ code and compile to binaries, then use those binaries with php? Is it also possible to write a php library using C and C++ ? If so, please tell how can I do so?
PHP is modular in design -- it consists of the "engine" and many extensions, some of which are essential (e.g. the "standard" extension) and some are optional. They can be compiled-in or loaded dynamically (via php.ini settings or the `dl()` function). You can easily write your own PHP extension in C/C++, if you are willing to learn the API. Start with the documentation on how to ["hack the Zend Engine"](http://www.php.net/manual/en/internals2.php).
You might want to check out [SWIG](http://www.swig.org/), a general tool for wrapping libraries so that they may be called from a variety of languages. PHP is supported by SWIG, as are Perl and Lua (the targets I've personally used). Quoting from the features list at the [SWIG website](http://www.swig.org/compare.html): > SWIG currently generates wrapper code > for eighteen different target > languages: > > * Allegro CL > * C# > * CFFI > * CLISP > * Chicken > * Guile > * Java > * Lua > * Modula-3 > * Mzscheme > * OCAML > * Octave > * Perl > * PHP > * Python > * R > * Ruby > * Tcl > * UFFI > > In addition to this, the parse tree > can be exported as XML and Lisp > s-expressions. Experimental work is > also available for a Pike module. Some of its features are dependent on back-end support in the per-language wrapper generators, but in general it provides easy to use wrappers for passing all plain-data value types in and out of functions. Where the target language has the concept, it can usually map object models as well.
Is it possible to use C++ binaries from php
[ "", "php", "" ]
I'm an experienced C programmer dipping my toes in OO design (specifically C++). I have a particular piece of code I hate and would like to clean up using C++. The code implements a display tree for use in a 3d graphics app. It is a linked list of entries which have a type field specifying whether the entry is a window, geometry feature or light etc. In particular geometry features can either be a single piece of geometry of a collection of sub features, which is indicated by the presence of a separate structure. Being a linked list it is a flat structure but the order implies hierarchy. Also, each entry has an attribute structure which is able to be propagated down the list. A separate function allows this list to be traversed and a provided function pointer to be executed on traversal of the list. Each function used in this way must take proper care to maintain the attribute structure as it is propagated down the list and this is a frequent cause of rendering bugs (usually things not realising they should be redrawn because they are part of a group of entries, for example) While some aspects of OO design jump right out at me I am interested to hear: 1. how i would best implement being able to pass a function pointer down a list (or vector - are STL vectors ok for lists like this?) 2. whether i would be right to implement windows and geometry features as related (or even the same) classes 3. how to best design a class that can have a collection of itself 4. any suggestions regarding attribute transferral between objects (e.g color, scale). the desired behaviour is that modifying a feature will alter the attributes of that feature and any sub-features it contains, and modifying a sub-feature will only modify that feature. I realize this is a long and broad question, so appreciate your thoughts on any of the above queries. thanks!
1) Use [boost::function](http://www.boost.org/doc/libs/1_38_0/doc/html/function/tutorial.html) and stl algorithms like `for_each count_if` 2) Divide model from the view. It will be ok. 3) [GoF design pattern Composite](http://www.vincehuston.org/dp/composite.html) 4) To implement reaction on changes take a look at [GoF design pattern Observer](http://www.vincehuston.org/dp/observer.html)
1. you can have your function pointer, but usually in OO every object should know how to handle its data, and there is polymorphism for special c(l)as(s)es
OO design - propagating attributes
[ "", "c++", "oop", "" ]
I am trying out the VisualVM program that comes with the new JDKs. I am doing profiling on it and trying to profile CPU on only methods in a particular package. I put the following in the "Profile Only Classes:" ``` jig.* ``` Where jig is the package I want to instrument. Unfortunately I get back results on other methods that are not in that package or any subpackages.
The only way I can reproduce your problem is if I leave the "Profile new Runnables" box checked. When I leave that checked, the profiler picks up code started as new threads, even if that code does not meet the filtering criteria. I guess this is unclear functionality. You should make sure you uncheck that box before you do your profiling activity. Just be aware that with it unchecked, that probably means you won't see profile information of any of your own code that happens to be started as a separate Thread. (But I figure there's a good chance you're not doing that, so you have nothing to be concerned about.)
Actually there's an opened bug about that: <https://java.net/jira/browse/VISUALVM-546> I totally agree with the submitter (and with your disappointing about the "strange" behavior of VisualVM). Even with "Profile new Runnables" checked the filter must be honored in my opinion. Profiling it's an important task to do especially with large project typically deployed on application-server where it's the common-way (and the right-way) have threads for background tasks and to serve user requests. I invite everybody to vote for give attention from the VisualVM developers.
Limiting Profiling in Visual VM
[ "", "java", "profiling", "visualvm", "" ]
I am trying to include the following Tag In Google App Engine Web Application: <http://www.djangosnippets.org/snippets/1357/> Is there any configuration of this file to make it work with Google App Engine? Cause I followed the Django Template tutorials: <http://docs.djangoproject.com/en/dev/howto/custom-template-tags/> and have this structure: ``` templatetags/ __init__.py range_template.py ``` in the Template file, I have {%load range\_template%} But I am getting the error: TemplateSyntaxError: 'range\_template' is not a valid tag library: Could not load template library from django.templatetags.range\_template, No module named range\_template The other thing that might be a problem why this ain't working is, the INSTALL\_APPS settings.py file. Not sure how to configure it. I have a settings.py file in the root of my application and included this: INSTALLED\_APPS = ('templatetags') Any advice would be greatly appreciated.
try doing the following: ``` $ python ./manage.py startapp foo ``` Add foo to installed apps: ``` INSTALLED_APPS += ('foo',) ``` And move your templatetags directory into your foo app. Something like: ``` ./djangoproject __init__.py settings.py urls.py etc.. foo/ __init__.py templatetags/ __init__.py range_template.py ``` Django convention is that template tag code resides in apps, in directories named templatetags ([see docs](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/)). I assume the same would be true for GAE.
In case someone searches for this, I wrote a small article in 2008 about this: <http://daily.profeth.de/2008/04/using-custom-django-template-helpers.html>
Django Custom Template Tags In Google App Engine
[ "", "python", "django", "google-app-engine", "" ]
C# 2005 I am using a simple encrypt and descrypt for a IP address. The app on the remote server will encrypt the ip address and the client will decrypt it. However, when the client descrypts the IP I only get some of the IP address back. The rest is rubbish. Before: 123.456.78.98 After: fheh&^G.78.98 Many thanks, ``` /// Encrypt the SIP IP address in the remote server private void encryptSIP_IP(string sip_ip) { TripleDESCryptoServiceProvider encrypt = new TripleDESCryptoServiceProvider(); /// Private key byte[] key = { 0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 144, 89, 55, 34, 21, 13, 8, 5, 3, 2, 1, 0}; encrypt.Key = key; byte[] byteSIP = System.Text.Encoding.Default.GetBytes(sip_ip); ICryptoTransform encryptor = encrypt.CreateEncryptor(); byte[] encrypted_sip = encryptor.TransformFinalBlock(byteSIP, 0, byteSIP.Length); /// This will decrypt in the client application private void decryptSIP_IP(byte[] encrypted_sip) { TripleDESCryptoServiceProvider decrypt = new TripleDESCryptoServiceProvider(); /// Private key byte[] key = { 0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 144, 89, 55, 34, 21, 13, 8, 5, 3, 2, 1, 0 }; decrypt.Key = key; ICryptoTransform decryptor = decrypt.CreateDecryptor(); byte[] original = decryptor.TransformFinalBlock(encrypted_sip, 0, encrypted_sip.Length); string ip = System.Text.Encoding.Default.GetString(original); } } ```
Along with a key you need an [Initialization Vector](http://en.wikipedia.org/wiki/Initialization_vector) (8 bytes for your case): ``` // To Encrypt encrypt.IV = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; // Use same IV to decrypt decrypt.IV = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; ```
As darin already said, you need to set the Initialization Vector. If possible, choose a random one for each encryption process and transfer/save it in clear text. By the way, you should look into CryptoStream instead of working with TransformBlock/TransformFinalBlock ... it's much cleaner, imho.
c# encryption and decryption
[ "", "c#", "encryption", "" ]
Suppose I have these packages in my application - foo.bar and foo.foobar, And I want to send all log4j log messages that are coming from foo.bar package to foobar.log file and the log messages coming from foo.foobar to foofoobar.log file, how should I configure the log4j.xml file?
You can use appender-ref in the logger configuration: ``` <logger name="foo.bar"> <level value="debug"/> <appender-ref ref="FILE1" /> </logger> ``` Have a look [here](http://wiki.apache.org/logging-log4j/Log4jXmlFormat) for full examples.
I suggest also to set additivty to "false" when you have overlapping hierarchies and don't want duplicate log messages. i.e: ``` <logger name="foo.bar"> <level value="debug"/> <appender-ref ref="FILE1" /> </logger> <logger name="foo.bar.xyz" additivity="false"> <level value="debug"/> <appender-ref ref="FILE2" /> </logger> ``` This way messages directed to FILE2 won't be written to FILE1
Logging the log messages from different packages into different files
[ "", "java", "logging", "log4j", "" ]
Assuming this is a "singleton" implementation: Am I guaranteed that this will only call productCatalogLoader.load() once, and also that no nullpointers can happen ? Any way to make this simpler ? ``` private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); private ProductCatalog productCatalog; public ProductCatalog get() { if (this.productCatalog == null) { reload(); } return this.productCatalog; } public void reload() { lock.writeLock().lock(); try { if (this.productCatalog != null) return; this.productCatalog = productCatalogLoader.load(); } finally { lock.writeLock().unlock(); } } ``` } Edit: This was a modestly successful attempt reduce much more complex code to a simple question sample. Several people caught on to the fact that my singleton was too complex ;) (Actually there's also a quartz timer calling reload, but the "reload" implementation is a bit different IRL). I got the answer I needed anyway, broken double checked locking.
this looks like [broken double checked locking](http://en.wikipedia.org/wiki/Double_checked_locking_pattern). the problem is this.productCatalog can be assigned before the object is fully contructed. say we have ``` var foo = new ProductCatalog(); foo.blah = "blah blah"; this.productCatalog = foo; ``` the can be reordered as ``` var foo = new ProductCatalog(); this.productCatalog = foo; foo.blah = "blah blah"; ```
The best way to make it simpler, IMO, is to use a "normal" lock unless you really have good evidence that it's causing a bottleneck: ``` private final Object lock = new Object(); private ProductCatalog productCatalog; public ProductCatalog get() { synchronized (lock) { if (this.productCatalog == null) { this.productCatalog = productCatalogLoader.load(); } return this.productCatalog; } } ``` In the vast majority of cases, this will be good enough, and you don't need to worry about memory model technicalities. EDIT: As to whether reading the data changed in the write lock without acquiring the read lock is safe - I *suspect* not, but I wouldn't like to say for certain. Is there any benefit in your approach to using normal (and safe on Java 1.5+, if you're careful) double-checked locking using a volatile variable? ``` private final Object lock = new Object(); private volatile ProductCatalog productCatalog; public ProductCatalog get() { if (this.productCatalog == null) { synchronized (lock) { if (this.productCatalog == null) { this.productCatalog = productCatalogLoader.load(); } } } return this.productCatalog; } ``` I believe that's the lazy initialization technique recommended in Effective Java 2nd edition, for situations where static initializers aren't enough. Note that `productCatalog` has to be volatile for this to work - and I think that's *effectively* what you're missing by not taking out the read lock in your code.
Is it safe to use writeLock without readlock?
[ "", "java", "concurrency", "" ]
I am looking for a .Net class/library to use with currency acronyms in the same way the TimeZoneInfo class works with timezones. I need to populate a drop down list with these acronyms and store the result in a databse. This value will be used to retrieve up to date exchange rates from the web at a later stage. Any ideas?
``` CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures); IEnumerable<string> currencySymbols = cultures.Select<CultureInfo, string>(culture => new RegionInfo(culture.LCID).ISOCurrencySymbol); ``` Is it what you are looking for?
You might be better off generating the list yourself and putting it in a database along with related information. I've used this approach fairly successfully ``` Country Currency Name Symbol Code USA US Dollar $ USD ``` There are a couple of benefits 1. Reporting is much easier as you can join on this table and format the output as necessary 2. Changes in the sector can be catered for 3. Complicated scenarios such as countries supporting multiple currencies can be handled
Currency Library
[ "", "c#", "asp.net-mvc", "cultureinfo", "" ]
I noticed, as well as saw in the [Essential C# 3.0](https://rads.stackoverflow.com/amzn/click/com/0321533925) book, that paramters are usually defined as *T* or *TEntity* For example: ``` public class Stack<T> { } ``` or ``` public class EntityCollection<TEntity> { } ``` How do you decide which name to use? Thanks
Here is my set of rules * If there is one parameter, I name it T * If there is more than one parameter, I pick a meaningful name and prefix with T. For example TKey, TValue For a semi-official opinion, it's worth looking at the framework design guidelines on the subject: * <http://blogs.msdn.com/brada/archive/2005/12/02/497340.aspx>
I fetched the .NET Framework 4.6 source code from <http://referencesource.microsoft.com/dotnet46.zip>. Extracted it and processed the data to extract the generic parameter name from all generic class declarations. Note: I only extracted the generic parameter name from generic classes with only one generic parameter. So this does not take into consideration the generic classes with multiple generic parameters. ``` grep -nohrP "class \w+<T\w*>" | sed -e 's/.*\<//' -e 's/>//' | sort | uniq -cd | sort -bgr ``` Result: ``` 361 T 74 TChannel 51 TKey 33 TResult 30 TSource 28 T_Identifier 18 TElement 12 TEntity 11 TInputOutput 7 TItem 6 TLeftKey 6 TFilterData 5 T_Query 4 T_Tile 4 TInput 3 TValue 3 TRow 3 TOutput 3 TEventArgs 3 TDataReader 3 T1 2 TWrapper 2 TVertex 2 TValidationResult 2 TSyndicationItem 2 TSyndicationFeed 2 TServiceType 2 TServiceModelExtensionElement 2 TResultType 2 TMessage 2 TLocationValue 2 TInnerChannel 2 TextElementType 2 TException 2 TEnum 2 TDuplexChannel 2 TDelegate 2 TData 2 TContract 2 TConfigurationElement 2 TBinder 2 TAttribute ```
What are the type parameter naming guidelines?
[ "", "c#", ".net", "generics", "naming-conventions", "" ]
I just don't get it as it would be so useful to convert one generic container into the other? ``` Stack <IType> stack = new Stack<SomeType>(); ```
Are you talking about conversions like so? ``` IFoo<Child> child = ...; IFoo<Parent> parent = child; ``` If so, this is what is known as covariance. This is usually paired with it's counterpart contravariant. This feature is indeed not available in the current version of C#. But it will be available in next version of both C# and VB.Net. Some articles about the upcoming release * <http://blogs.msdn.com/ericlippert/archive/2007/10/16/covariance-and-contravariance-in-c-part-one.aspx> * <http://www.leading-edge-dev.de/?p=246>
While what @JaredPar says is true, there are some work-arounds for collections that are available today. For instance, you can use the Cast IEnumerable extension if there is a legal cast from one type to another. ``` List<Foo> list = barList.Cast<Foo>().ToList(); ``` Or you could explicitly convert from one type to another using Select. ``` List<double> dList = intList.Select( i => Convert.ToDouble( i ) ).ToList(); ``` Note that both of these methods will produce a new collection of the appropriate type, not simply assign the collection to a variable of a different type as will be available under certain conditions in the next versions of C#/VB.
Why is conversion between with different type parameters is NOT allowed?
[ "", "c#", ".net", "generics", "covariance", "contravariance", "" ]
I have this code to represent bank: ``` class Bank { friend class InvestmentMethod; std::vector<BaseBankAccount*> accounts; public: //... ``` BaseBankAccount is an abstract class for all accounts in a bank: ``` class BaseBankAccount { public: BaseBankAccount() {} virtual int getInterest() const = 0; virtual int getInvestedSum() const = 0; virtual void increaseDepositSum(int additionalSum) = 0; virtual void close(std::string& reason) = 0; virtual ~BaseBankAccount() {} }; ``` The problem is, when I manipulate with pointers to derived class objects through pointers to base class objects, the set of methods I can call is restricted by BaseBankAccount public interface - no matter what type the REAL object is. For example, not every account has an option to increase sum invested already - so, I didn`t include this method in a base class: ``` class BankAccount: public BaseBankAccount { protected: BaseDeposit* deposit; double sumInvested; public: BankAccount(int sum, int term, int inter): sumInvested(sum), depositTerm(term), interest(inter) {} int getInterest() const { return interest; } int getInvestedSum() const { return sumInvested; } void prolong(int increaseTerm) { depositTerm += increaseTerm; } void increaseInvestment(double addition) { sumInvested += addition; } virtual ~BankAccount() {} }; ``` then, I want to call it: ``` Bank bank1(...); bank1.accounts[i]->increaseInvestment(1000.0); ``` So, what can I do to get access to the interface of derived class objects in this case? As far as I know, **downcasting to concrete type** each time I need to call specific functionality **is not good**. Create one more abstract class derived from this to expand the interface? Create parallel hierarchy for each specific type I need to implement (looks a bit heavy thing to do)?
A solution to accessing more derived class features from a base class is the visitor pattern. ``` class BaseBankAccount { public: ... virtual void AcceptVisitor(IVisitor& v) = 0; }; class AccountTypeA : public BaseBankAccount { public: void TypeAFeature() {...} void AcceptVisitor(IVisitor& v) { v.VisitAccountTypeA(*this); } }; class AccountTypeB : public BaseBankAccount { public: void TypeBFeature() {...} void AcceptVisitor(IVisitor& v) { v.VisitAccountTypeB(*this); } }; class IVisitor { public: virtual void VisitAccountTypeA(AccountTypeA& account) = 0; virtual void VisitAccountTypeB(AccountTypeB& account) = 0; }; class ConcreteVisitor : public IVisitor{ public: void VisitAccountTypeA(AccountTypeA& account) { account.TypeAFeature(); //Can call TypeA features } void VisitAccountTypeB(AccountTypeB& account) { account.TypeBFeature(); //Can call TypeB Features } }; ``` The interaction is not immediately obvious. You define a pure virtual method AcceptVisitor in your base class, which takes an Object of type IVisitor as a parameter. IVisitor has one Method per derived class in the hierarchy. Each derived class implements AcceptVisitor differently and calls the method corresponding to its concrete type (AccountTypeA & AccountTypeB), and passes a concrete reference to itself to the method. You implement the functionality that uses the more derived types of your hierachy in objects deriving from IVisitor. Wikipedia: [Visitor Pattern](http://en.wikipedia.org/wiki/Visitor_pattern)
The restrictioon to base class public interface (and by the way, aren't there some 'virtual's missing in what you posted) is what C++ does. If you need to access specific functions that belong only to a derived class, then you need to cast the pointer to that class using dynamic\_cast. If you find the need to use dynamic\_cast a lot, then your design is possibly wanting, but it's very difficult to comment on this without kniowing exact details of the business domain you are dealing with. One possible way round the problem is to provide methods that access components of an account. For example, a base class method GetPortfolio() could returbn a Portfolio object pointer but only for account classes that have Portfolios. For other classes you define their GetPortfolio() method as returning NULL. Once you have the Portfolio pointer, you work on the portfolio interface (which itself may represent a class heirarchy) rather thean the BankAccount.
Manipulating with pointers to derived class objects through pointers to base class objects
[ "", "c++", "inheritance", "pointers", "" ]
I'm trying to test a method. I want to ensrur that there is a method call in that method (calling service) the code look like this: ``` using(proxy = new Proxy()) { proxy.CallService(); } ``` I swap the proxy with fake object (using TypeMock) but get error because of the fake object disposed in the end of block. I don't want to remove that "using" block. Thanks
Disclaimer: I work at Typemock If you are using the Arrange Act Assert API you can use Members.ReturnRecursiveFakes when you are creating your fake object (Note: this is the default from version 5.2.0) This will automatically fake the Dispose method as well. so your test will be something like this: ``` var fake = Isolate.Fake.Instance<Proxy>(Members.ReturnRecursiveFakes); Isolate.WhenCalled(() => fake.CallService()).IgnoreCall(); Isolate.Swap.NextInstance<Proxy>().With(fake); UnderTest classUnderTest = new ClassUnderTest(); classUnderTest.MethodUnderTest(); // assuming the Proxy instance is used here. Isolate.Verify.WasCalledWithAnyArguments(()=>fake.CallService()); ``` I want to add to what Jon Skeet said that I would create a separate test that will ensure that the Dispose method is called. I think it is a good practice to assert one thing in each test method, that way when a test breaks up you'll know the reason immediately.
Make the mock object expect to be disposed too. (I don't know TypeMock, but in some other mocking frameworks this would just be a case of calling `Dispose` yourself during the "record" phase.) In fact, I'd say that without that the test is wrong anyway, because presumably you want to be certain that the proxy *is* being disposed.
bypass dispose for testing
[ "", "c#", "tdd", "typemock", "" ]
I'm working on a C# Server application for a game engine I'm writing in ActionScript 3. I'm using an authoritative server model as to prevent cheating and ensure fair game. So far, everything works well: When the client begins moving, it tells the server and starts rendering locally; the server, then, tells everyone else that client X has began moving, among with details so they can also begin rendering. When the client stops moving, it tells the server, which performs calculations based on the time the client began moving and the client render tick delay and replies to everyone, so they can update with the correct values. The thing is, when I use the default 20ms tick delay on server calculations, when the client moves for a rather long distance, there's a noticeable tilt forward when it stops. If I increase slightly the delay to 22ms, on my local network everything runs very smoothly, but in other locations, the tilt is still there. After experimenting a little, I noticed that the extra delay needed is pretty much tied to the latency between client and server. I even boiled it down to a formula that would work quite nicely: delay = 20 + (latency / 10). So, how would I proceed to obtain the latency between a certain client and the server (I'm using asynchronous sockets). The CPU effort can't be too much, as to not have the server run slowly. Also, is this really the best way, or is there a more efficient/easier way to do this?
Sorry that this isn't directly answering your question, but generally speaking you shouldn't rely too heavily on measuring latency because it can be quite variable. Not only that, you don't know if the ping time you measure is even symmetrical, which is important. There's no point applying 10ms of latency correction if it turns out that the ping time of 20ms is actually 19ms from server to client and 1ms from client to server. And latency in application terms is not the same as in networking terms - you may be able to ping a certain machine and get a response in 20ms but if you're contacting a server on that machine that only processes network input 50 times a second then your responses will be delayed by an extra 0 to 20ms, and this will vary rather unpredictably. That's not to say latency measurement it doesn't have a place in smoothing predictions out, but it's not going to solve your problem, just clean it up a bit. On the face of it, the problem here seems to be that that you're sent information in the first message which you use to extrapolate data from until the last message is received. If all else stays constant then the movement vector given in the first message multiplied by the time between the messages will give the server the correct end position that the client was in at roughly now-(latency/2). But if the latency changes at all, the time between the messages will grow or shrink. The client may know he's moved 10 units, but the server simulated him moving 9 or 11 units before being told to snap him back to 10 units. The general solution to this is to not assume that latency will stay constant but to send periodic position updates, which allow the server to verify and correct the client's position. With just 2 messages as you have now, all the error is found and corrected after the 2nd message. With more messages, the error is spread over many more sample points allowing for smoother and less visible correction. It can never be perfect though: all it takes is a lag spike in the last millisecond of movement and the server's representation will overshoot. You can't get around that if you're predicting future movement based on past events, as there's no real alternative to choosing either correct-but-late or incorrect-but-timely since information takes time to travel. (Blame Einstein.)
One thing to keep in mind when using [ICMP](http://http:/en.wikipedia.org/wiki/Internet_Control_Message_Protocol) based [pings](http://http:/en.wikipedia.org/wiki/Ping) is that networking equipment will often give ICMP traffic lower priority than *normal* packets, especially when the packets cross network boundaries such as WAN links. This can lead to pings being dropped or showing higher latency than traffic is actually experiencing and lends itself to being an indicator of problems rather than a measurement tool. The increasing use of [Quality of Service](http://http:/en.wikipedia.org/wiki/Quality_of_service) (QoS) in networks only exacerbates this and as a consequence though ping still remains a useful tool, it needs to be understood that it may not be a true reflection of the network latency for non-ICMP based *real* traffic. There is a good post at the Itrinegy blog [How do you measure Latency (RTT) in a network these days?](http://blogs.itrinegy.com/2009/02/how-do-you-measure-latency-rtt-in-a-network-these-days/) about this.
How do I obtain the latency between server and client in C#?
[ "", "c#", ".net", "sockets", "client-server", "latency", "" ]
I'm using jcreatorLE and JDK 1.6 to run my program. I don't know why I get an error when I try to run. Could somebody explain the reason to me? **This is the code for the Server:** ``` import java.io.*; import java.net.*; class ServidorTCP { // variable to wait for connections private static ServerSocket servidor = null; // Variable to process client connections private static Socket conexion = null; // To send data to the client private static DataOutputStream salida = null; // Read the client private static DataInputStream entrada = null; public static void main(String args[]) { // args [0] is the port number to be listened to int puerto = new Integer(args[0]).intValue(); // opening of the socket try { // Port where the client requests pending servidor = new ServerSocket(puerto); System.out.println("Servidor TCP iniciado..."); boolean ejecutar = true; // It is starting to respond to requests while (ejecutar) { System.out.println("\nWaiting for Connections..."); conexion = servidor.accept(); // Connection is expected // The connection was established with the client entrada = new DataInputStream(conexion.getInputStream()); salida = new DataOutputStream(conexion.getOutputStream()); System.out.println("\nConexion recibida...\n"); String inicio = entrada.readUTF(); System.out.println("Reception Date: "+new java.util.Date()); System.out.println("From: "+(conexion.getInetAddress()).toString()); System.out.println("received: "+inicio); salida.writeUTF(inicio.toUpperCase()); entrada.close(); salida.close(); conexion.close(); } // Close the socket System.out.println("\ntransmission completed...\n"); servidor.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` **This is the code for the client socket program:** ``` import java.io.*; import java.net.*; class ClienteTCP { private static Socket cliente = null; private static DataInputStream entrada = null; private static DataOutputStream salida = null; public static void main(String args[]) { int len = new Integer(args.length); String cadena = ""; System.out.println("\nNumero de arg: "+len); for (int i=2; i<len;i++) { cadena = cadena + args[i]; cadena = cadena + " "; } System.out.println("\nLa Cadena: "+cadena); int puerto = new Integer(args[1]).intValue(); try { cliente = new Socket(args[0],puerto); entrada = new DataInputStream(cliente.getInputStream()); salida = new DataOutputStream(cliente.getOutputStream()); //SENDING INFORMATION DATA System.out.println("\nEnviando datos al servidor: "+cadena); salida.writeUTF(cadena); //Recibiendo la información System.out.println("Recibido: "+entrada.readUTF()); entrada.close(); salida.close(); //Cierre del socket cliente.close(); System.out.println("\nConexion terminada...\n"); } catch (Exception e) { e.printStackTrace(); } } } ``` **This is the result from running it:** ``` [Loaded java.lang.Object from shared objects file] [Loaded java.io.Serializable from shared objects file] [Loaded java.lang.Comparable from shared objects file] [Loaded java.lang.CharSequence from shared objects file] [Loaded java.lang.String from shared objects file] [Loaded java.lang.reflect.GenericDeclaration from shared objects file] [Loaded java.lang.reflect.Type from shared objects file] [Loaded java.lang.reflect.AnnotatedElement from shared objects file] [Loaded java.lang.Class from shared objects file] [Loaded java.lang.Cloneable from shared objects file] [Loaded java.lang.ClassLoader from shared objects file] [Loaded java.lang.System from shared objects file] [Loaded java.lang.Throwable from shared objects file] [Loaded java.lang.Error from shared objects file] [Loaded java.lang.ThreadDeath from shared objects file] [Loaded java.lang.Exception from shared objects file] [Loaded java.lang.RuntimeException from shared objects file] [Loaded java.security.ProtectionDomain from shared objects file] [Loaded java.security.AccessControlContext from shared objects file] [Loaded java.lang.ClassNotFoundException from shared objects file] [Loaded java.lang.LinkageError from shared objects file] [Loaded java.lang.NoClassDefFoundError from shared objects file] [Loaded java.lang.ClassCastException from shared objects file] [Loaded java.lang.ArrayStoreException from shared objects file] [Loaded java.lang.VirtualMachineError from shared objects file] [Loaded java.lang.OutOfMemoryError from shared objects file] [Loaded java.lang.StackOverflowError from shared objects file] [Loaded java.lang.IllegalMonitorStateException from shared objects file] [Loaded java.lang.ref.Reference from shared objects file] [Loaded java.lang.ref.SoftReference from shared objects file] [Loaded java.lang.ref.WeakReference from shared objects file] [Loaded java.lang.ref.FinalReference from shared objects file] [Loaded java.lang.ref.PhantomReference from shared objects file] [Loaded java.lang.ref.Finalizer from shared objects file] [Loaded java.lang.Runnable from shared objects file] [Loaded java.lang.Thread from shared objects file] [Loaded java.lang.Thread$UncaughtExceptionHandler from shared objects file] [Loaded java.lang.ThreadGroup from shared objects file] [Loaded java.util.Dictionary from shared objects file] [Loaded java.util.Map from shared objects file] [Loaded java.util.Hashtable from shared objects file] [Loaded java.util.Properties from shared objects file] [Loaded java.lang.reflect.AccessibleObject from shared objects file] [Loaded java.lang.reflect.Member from shared objects file] [Loaded java.lang.reflect.Field from shared objects file] [Loaded java.lang.reflect.Method from shared objects file] [Loaded java.lang.reflect.Constructor from shared objects file] [Loaded sun.reflect.MagicAccessorImpl from shared objects file] [Loaded sun.reflect.MethodAccessor from shared objects file] [Loaded sun.reflect.MethodAccessorImpl from shared objects file] [Loaded sun.reflect.ConstructorAccessor from shared objects file] [Loaded sun.reflect.ConstructorAccessorImpl from shared objects file] [Loaded sun.reflect.DelegatingClassLoader from shared objects file] [Loaded sun.reflect.ConstantPool from shared objects file] [Loaded sun.reflect.FieldAccessor from shared objects file] [Loaded sun.reflect.FieldAccessorImpl from shared objects file] [Loaded sun.reflect.UnsafeFieldAccessorImpl from shared objects file] [Loaded sun.reflect.UnsafeStaticFieldAccessorImpl from shared objects file] [Loaded java.lang.Iterable from shared objects file] [Loaded java.util.Collection from shared objects file] [Loaded java.util.AbstractCollection from shared objects file] [Loaded java.util.List from shared objects file] [Loaded java.util.AbstractList from shared objects file] [Loaded java.util.RandomAccess from shared objects file] [Loaded java.util.Vector from shared objects file] [Loaded java.lang.Appendable from shared objects file] [Loaded java.lang.AbstractStringBuilder from shared objects file] [Loaded java.lang.StringBuffer from shared objects file] [Loaded java.lang.StackTraceElement from shared objects file] [Loaded java.nio.Buffer from shared objects file] [Loaded sun.misc.AtomicLong from shared objects file] [Loaded sun.misc.AtomicLongCSImpl from shared objects file] [Loaded java.lang.Boolean from shared objects file] [Loaded java.lang.Character from shared objects file] [Loaded java.lang.Number from shared objects file] [Loaded java.lang.Float from shared objects file] [Loaded java.lang.Double from shared objects file] [Loaded java.lang.Byte from shared objects file] [Loaded java.lang.Short from shared objects file] [Loaded java.lang.Integer from shared objects file] [Loaded java.lang.Long from shared objects file] [Loaded java.io.ObjectStreamField from shared objects file] [Loaded java.util.Comparator from shared objects file] [Loaded java.lang.String$CaseInsensitiveComparator from shared objects file] [Loaded java.security.Guard from shared objects file] [Loaded java.security.Permission from shared objects file] [Loaded java.security.BasicPermission from shared objects file] [Loaded java.lang.RuntimePermission from shared objects file] [Loaded java.util.AbstractMap from shared objects file] [Loaded sun.misc.SoftCache from shared objects file] [Loaded java.lang.ref.ReferenceQueue from shared objects file] [Loaded java.lang.ref.ReferenceQueue$Null from shared objects file] [Loaded java.lang.ref.ReferenceQueue$Lock from shared objects file] [Loaded java.util.HashMap from shared objects file] [Loaded java.lang.annotation.Annotation from shared objects file] [Loaded java.util.Map$Entry from shared objects file] [Loaded java.util.HashMap$Entry from shared objects file] [Loaded java.security.AccessController from shared objects file] [Loaded java.lang.reflect.ReflectPermission from shared objects file] [Loaded java.security.PrivilegedAction from shared objects file] [Loaded sun.reflect.ReflectionFactory$GetReflectionFactoryAction from shared objects file] [Loaded java.util.Stack from shared objects file] [Loaded sun.reflect.ReflectionFactory from shared objects file] [Loaded java.lang.ref.Reference$Lock from shared objects file] [Loaded java.lang.ref.Reference$ReferenceHandler from shared objects file] [Loaded java.lang.ref.Finalizer$FinalizerThread from shared objects file] [Loaded java.util.Enumeration from shared objects file] [Loaded java.util.Hashtable$EmptyEnumerator from shared objects file] [Loaded java.util.Iterator from shared objects file] [Loaded java.util.Hashtable$EmptyIterator from shared objects file] [Loaded java.util.Hashtable$Entry from shared objects file] [Loaded sun.misc.Version from shared objects file] [Loaded java.lang.Runtime from shared objects file] [Loaded sun.reflect.Reflection from shared objects file] [Loaded java.util.Collections from shared objects file] [Loaded java.util.Set from shared objects file] [Loaded java.util.AbstractSet from shared objects file] [Loaded java.util.Collections$EmptySet from shared objects file] [Loaded java.util.Collections$EmptyList from shared objects file] [Loaded java.util.Collections$EmptyMap from shared objects file] [Loaded java.util.Collections$ReverseComparator from shared objects file] [Loaded java.util.Collections$SynchronizedMap from shared objects file] [Loaded java.io.File from shared objects file] [Loaded java.io.FileSystem from shared objects file] [Loaded java.io.Win32FileSystem from shared objects file] [Loaded java.io.WinNTFileSystem from shared objects file] [Loaded java.io.ExpiringCache from shared objects file] [Loaded java.util.LinkedHashMap from shared objects file] [Loaded java.io.ExpiringCache$1 from shared objects file] [Loaded java.util.LinkedHashMap$Entry from shared objects file] [Loaded sun.security.action.GetPropertyAction from shared objects file] [Loaded java.lang.StringBuilder from shared objects file] [Loaded java.util.Arrays from shared objects file] [Loaded java.lang.Math from shared objects file] [Loaded sun.misc.JavaIODeleteOnExitAccess from shared objects file] [Loaded java.io.File$1 from shared objects file] [Loaded sun.misc.SharedSecrets from shared objects file] [Loaded sun.misc.Unsafe from shared objects file] [Loaded java.lang.IncompatibleClassChangeError from shared objects file] [Loaded java.lang.NoSuchMethodError from shared objects file] [Loaded sun.jkernel.DownloadManager from shared objects file] [Loaded java.lang.ThreadLocal from shared objects file] [Loaded sun.jkernel.DownloadManager$1 from shared objects file] [Loaded java.util.concurrent.atomic.AtomicInteger from shared objects file] [Loaded java.lang.Class$3 from shared objects file] [Loaded java.lang.reflect.Modifier from shared objects file] [Loaded sun.reflect.LangReflectAccess from shared objects file] [Loaded java.lang.reflect.ReflectAccess from shared objects file] [Loaded sun.jkernel.DownloadManager$2 from shared objects file] [Loaded java.lang.ClassLoader$3 from shared objects file] [Loaded java.io.ExpiringCache$Entry from shared objects file] [Loaded java.lang.ClassLoader$NativeLibrary from shared objects file] [Loaded java.io.Closeable from shared objects file] [Loaded java.io.InputStream from shared objects file] [Loaded java.io.FileInputStream from shared objects file] [Loaded java.io.FileDescriptor from shared objects file] [Loaded java.io.Flushable from shared objects file] [Loaded java.io.OutputStream from shared objects file] [Loaded java.io.FileOutputStream from shared objects file] [Loaded java.io.FilterInputStream from shared objects file] [Loaded java.io.BufferedInputStream from shared objects file] [Loaded java.util.concurrent.atomic.AtomicReferenceFieldUpdater from shared objects file] [Loaded java.util.concurrent.atomic.AtomicReferenceFieldUpdater$AtomicReferenceFieldUpdaterImpl from shared objects file] [Loaded sun.reflect.misc.ReflectUtil from shared objects file] [Loaded java.io.FilterOutputStream from shared objects file] [Loaded java.io.PrintStream from shared objects file] [Loaded java.io.BufferedOutputStream from shared objects file] [Loaded java.io.Writer from shared objects file] [Loaded java.io.OutputStreamWriter from shared objects file] [Loaded sun.nio.cs.StreamEncoder from shared objects file] [Loaded java.nio.charset.Charset from shared objects file] [Loaded java.nio.charset.spi.CharsetProvider from shared objects file] [Loaded sun.nio.cs.FastCharsetProvider from shared objects file] [Loaded sun.nio.cs.StandardCharsets from shared objects file] [Loaded sun.util.PreHashedMap from shared objects file] [Loaded sun.nio.cs.StandardCharsets$Aliases from shared objects file] [Loaded sun.nio.cs.StandardCharsets$Classes from shared objects file] [Loaded sun.nio.cs.StandardCharsets$Cache from shared objects file] [Loaded sun.nio.cs.HistoricallyNamedCharset from shared objects file] [Loaded sun.nio.cs.MS1252 from shared objects file] [Loaded java.lang.Class$1 from shared objects file] [Loaded sun.reflect.ReflectionFactory$1 from shared objects file] [Loaded sun.reflect.NativeConstructorAccessorImpl from shared objects file] [Loaded sun.reflect.DelegatingConstructorAccessorImpl from shared objects file] [Loaded sun.misc.VM from shared objects file] [Loaded java.nio.charset.CharsetEncoder from shared objects file] [Loaded sun.nio.cs.SingleByteEncoder from shared objects file] [Loaded sun.nio.cs.MS1252$Encoder from shared objects file] [Loaded java.nio.charset.CodingErrorAction from shared objects file] [Loaded java.nio.charset.CharsetDecoder from shared objects file] [Loaded sun.nio.cs.SingleByteDecoder from shared objects file] [Loaded sun.nio.cs.MS1252$Decoder from shared objects file] [Loaded java.nio.ByteBuffer from shared objects file] [Loaded java.nio.HeapByteBuffer from shared objects file] [Loaded java.nio.Bits from shared objects file] [Loaded java.nio.ByteOrder from shared objects file] [Loaded java.lang.Readable from shared objects file] [Loaded java.nio.CharBuffer from shared objects file] [Loaded java.nio.HeapCharBuffer from shared objects file] [Loaded java.nio.charset.CoderResult from shared objects file] [Loaded java.nio.charset.CoderResult$Cache from shared objects file] [Loaded java.nio.charset.CoderResult$1 from shared objects file] [Loaded java.nio.charset.CoderResult$2 from shared objects file] [Loaded sun.nio.cs.Surrogate$Parser from shared objects file] [Loaded sun.nio.cs.Surrogate from shared objects file] [Loaded java.io.BufferedWriter from shared objects file] [Loaded java.lang.Terminator from shared objects file] [Loaded sun.misc.SignalHandler from shared objects file] [Loaded java.lang.Terminator$1 from shared objects file] [Loaded sun.misc.Signal from shared objects file] [Loaded sun.misc.NativeSignalHandler from shared objects file] [Loaded java.io.Console from shared objects file] [Loaded sun.misc.JavaIOAccess from shared objects file] [Loaded java.io.Console$1 from shared objects file] [Loaded java.io.Console$1$1 from shared objects file] [Loaded java.lang.Shutdown from shared objects file] [Loaded java.util.ArrayList from shared objects file] [Loaded java.lang.Shutdown$Lock from shared objects file] [Loaded java.lang.ApplicationShutdownHooks from shared objects file] [Loaded java.util.IdentityHashMap from shared objects file] [Loaded sun.misc.OSEnvironment from shared objects file] [Loaded sun.io.Win32ErrorMode from shared objects file] [Loaded sun.misc.JavaLangAccess from shared objects file] [Loaded java.lang.System$2 from shared objects file] [Loaded java.lang.NullPointerException from shared objects file] [Loaded java.lang.ArithmeticException from shared objects file] [Loaded java.lang.Compiler from shared objects file] [Loaded java.lang.Compiler$1 from shared objects file] [Loaded sun.misc.Launcher from shared objects file] [Loaded java.net.URLStreamHandlerFactory from shared objects file] [Loaded sun.misc.Launcher$Factory from shared objects file] [Loaded java.security.SecureClassLoader from shared objects file] [Loaded java.net.URLClassLoader from shared objects file] [Loaded sun.misc.Launcher$ExtClassLoader from shared objects file] [Loaded sun.security.util.Debug from shared objects file] [Loaded sun.misc.JavaNetAccess from shared objects file] [Loaded java.net.URLClassLoader$7 from shared objects file] [Loaded java.util.StringTokenizer from shared objects file] [Loaded java.security.PrivilegedExceptionAction from shared objects file] [Loaded sun.misc.Launcher$ExtClassLoader$1 from shared objects file] [Loaded sun.misc.MetaIndex from shared objects file] [Loaded java.io.Reader from shared objects file] [Loaded java.io.BufferedReader from shared objects file] [Loaded java.io.InputStreamReader from shared objects file] [Loaded java.io.FileReader from shared objects file] [Loaded sun.nio.cs.StreamDecoder from shared objects file] [Loaded java.lang.reflect.Array from shared objects file] [Loaded java.util.Locale from shared objects file] [Loaded java.util.concurrent.ConcurrentMap from shared objects file] [Loaded java.util.concurrent.ConcurrentHashMap from shared objects file] [Loaded java.util.concurrent.locks.Lock from shared objects file] [Loaded java.util.concurrent.locks.ReentrantLock from shared objects file] [Loaded java.util.concurrent.ConcurrentHashMap$Segment from shared objects file] [Loaded java.util.concurrent.locks.AbstractOwnableSynchronizer from shared objects file] [Loaded java.util.concurrent.locks.AbstractQueuedSynchronizer from shared objects file] [Loaded java.util.concurrent.locks.ReentrantLock$Sync from shared objects file] [Loaded java.util.concurrent.locks.ReentrantLock$NonfairSync from shared objects file] [Loaded java.util.concurrent.locks.AbstractQueuedSynchronizer$Node from shared objects file] [Loaded java.util.concurrent.ConcurrentHashMap$HashEntry from shared objects file] [Loaded java.lang.CharacterDataLatin1 from shared objects file] [Loaded java.io.ObjectStreamClass from shared objects file] [Loaded sun.net.www.ParseUtil from shared objects file] [Loaded java.util.BitSet from shared objects file] [Loaded java.net.URL from shared objects file] [Loaded java.net.Parts from shared objects file] [Loaded java.net.URLStreamHandler from shared objects file] [Loaded sun.net.www.protocol.file.Handler from shared objects file] [Loaded java.util.HashSet from shared objects file] [Loaded sun.misc.URLClassPath from shared objects file] [Loaded sun.net.www.protocol.jar.Handler from shared objects file] [Loaded sun.misc.Launcher$AppClassLoader from shared objects file] [Loaded sun.misc.Launcher$AppClassLoader$1 from shared objects file] [Loaded java.lang.SystemClassLoaderAction from shared objects file] [Loaded java.lang.StringCoding from shared objects file] [Loaded java.lang.ThreadLocal$ThreadLocalMap from shared objects file] [Loaded java.lang.ThreadLocal$ThreadLocalMap$Entry from shared objects file] [Loaded java.lang.StringCoding$StringDecoder from shared objects file] [Loaded java.net.URLClassLoader$1 from shared objects file] [Loaded sun.misc.URLClassPath$3 from shared objects file] [Loaded sun.misc.URLClassPath$Loader from shared objects file] [Loaded sun.misc.URLClassPath$JarLoader from shared objects file] [Loaded java.security.PrivilegedActionException from shared objects file] [Loaded sun.misc.URLClassPath$FileLoader from shared objects file] [Loaded sun.misc.Resource from shared objects file] [Loaded sun.misc.URLClassPath$FileLoader$1 from shared objects file] [Loaded sun.nio.ByteBuffered from shared objects file] [Loaded java.security.CodeSource from shared objects file] [Loaded java.security.PermissionCollection from shared objects file] [Loaded java.security.Permissions from shared objects file] [Loaded java.net.URLConnection from shared objects file] [Loaded sun.net.www.URLConnection from shared objects file] [Loaded sun.net.www.protocol.file.FileURLConnection from shared objects file] [Loaded java.net.ContentHandler from shared objects file] [Loaded java.net.UnknownContentHandler from shared objects file] [Loaded sun.net.www.MessageHeader from shared objects file] [Loaded java.io.FilePermission from shared objects file] [Loaded java.io.FilePermission$1 from shared objects file] [Loaded java.security.Policy from shared objects file] [Loaded sun.security.provider.PolicyFile from shared objects file] [Loaded java.security.Policy$UnsupportedEmptyCollection from shared objects file] [Loaded java.io.FilePermissionCollection from shared objects file] [Loaded java.security.AllPermission from shared objects file] [Loaded java.security.UnresolvedPermission from shared objects file] [Loaded java.security.BasicPermissionCollection from shared objects file] [Loaded java.security.Principal from shared objects file] [Loaded java.security.cert.Certificate from shared objects file] [Loaded ServidorTCP from file:/C:/Users/administrador/Documents/] [Loaded java.lang.IndexOutOfBoundsException from shared objects file] [Loaded java.lang.ArrayIndexOutOfBoundsException from shared objects file] Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at ServidorTCP.main(ServidorTCP.java:21) [Loaded java.util.AbstractList$Itr from shared objects file] [Loaded java.util.IdentityHashMap$KeySet from shared objects file] [Loaded java.util.IdentityHashMap$IdentityHashMapIterator from shared objects file] [Loaded java.util.IdentityHashMap$KeyIterator from shared objects file] [Loaded java.io.DeleteOnExitHook from shared objects file] [Loaded java.util.LinkedHashSet from shared objects file] [Loaded java.util.HashMap$KeySet from shared objects file] [Loaded java.util.LinkedHashMap$LinkedHashIterator from shared objects file] [Loaded java.util.LinkedHashMap$KeyIterator from shared objects file] Process completed. ```
You have to specify the port number at the command line. It is always useful to know how to read the logs. See. In your logs you have a bunch of class names, but there is only one related to your code: ``` Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at ServidorTCP.main(ServidorTCP.java:21) ``` The rest of them are all about java.lang, java.util, java.io, etc, classes that you didn't coded. If you look at that error line it says: ``` java.lang.ArrayIndexOutOfBoundsException: ``` That means that you attempted to access an **array out of its bounds**. That is if the array size is 5 you probably attempted to access the 6th element. That's illegal, that's an exception ( more formally a RuntimeException that means you have a programming mistake ) Then the log adds information where that happened. ``` at ServidorTCP.main(ServidorTCP.java:21) ``` In the class ServidorTCP ( in java file ServidorTCP at line 21. You can take a look at that file at that line this is what it shows: ``` 20: // args [0] is the port number to be heard 21: int puerto = new Integer(args[0]).intValue(); ``` That says, the value of the variable "puerto" will be a new Integer created with the content of **args[0]** That is the first element of the args array. That array is defined in the main method: ``` public static void main(String args[]){ ``` And filled automatically with the command line arguments. So, if you ran your program without providing an argument the search of index 0 in the array args will fail. I don't know exactly where in jcreator you can add command line arguments, but I'm pretty sure somewhere in a "Run" menu, or in the "Run" configuration or something like that, there should be something like "program arguments" You can fill that value with a port number, try using 8085. # **OR** You can also change the line 21 of the server and initialize it like this: ``` //int puerto = new Integer(args[0]).intValue(); int puerto = 8085; // por mis pistolas :) ``` And see it run.
Sounds like when you're starting the server you're not giving it any command-line arguments. In other words, you're running something like: ``` java -cp . ServidorTCP ``` when you should be running ``` java -cp . ServidorTCP 40000 ``` (to start the server on port 40000) If you're starting the program from the IDE, you need to find out how to pass in arguments when it starts the program.
Why am I getting an error when I try to run my socket program in Java?
[ "", "java", "networking", "sockets", "" ]
I am trying to move a file from server `\\abc\\C$\\temp\\coll.zip` to another server `\\def\\c$\\temp`. I am trying to use `File.Copy(source,destination)`. But I am getting the error in source path saying: `Couldn't find the part of the path.` I am not sure what is wrong with the source path.
You could use a C# @ Verbatim and also use checks in the code like this: ``` string source = @"\\abc\C$\temp\coll.zip"; string destination = @"\\def\c$\temp\coll.zip"; string destDirectory = Path.GetDirectoryName(destination) if (File.Exists(source) && Directory.Exists(destDirectory)) { File.Copy(source, destination); } else { // Throw error or alert } ```
Make sure that your "\" characters are escaped if you are using C#. You have to double the backslashes or prefix the string literal with @, like this: `string fileName = @"\\abc\C$\temp\coll.zip";` or `string fileName = "\\\\abc\\C$\\temp\\coll.zip";`
move zip file using file.copy()
[ "", "c#", "" ]