Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have the following class ``` class MCustomer : DomanEntity { public MCustomer() { } public virtual iCustomerEntity CustomerDetials { get; set; } public virtual SolicitationPreferences SolicitationPreferences { get; set; } } public interface iCustomerEntity { Contact Contact { get; set; } } public class PersonEntity: DomanEntity, iCustomerEntity { public PersonEntity() { Intrests = new List<Intrest>(); Children = new List<PersonEntity>(); } public virtual Contact Contact { get; set; } public virtual DateTime BirthDate { get; set; } public virtual IList<Intrest> Intrests { get; set; } public virtual PersonEntity Spouse { get; set; } public virtual IList<PersonEntity> Children { get; set; } } ``` When I use fluent NHibernate AutoMapping I receive this error: > NHibernate.MappingException: An association from the table MCustomer refers to an unmapped class: Calyx.Core.Domain.CRM.iCustomerEntity How do I set up a property in my domain model that has an Interface type?
<https://www.hibernate.org/hib_docs/nhibernate/html/inheritance.html> Its a standard Nhibernate pattern. I'm trying to do the same thing
I don't think, that you can do that. When you would try to load your MCustomer (`session.Load<MCustomer>(id)`), NHibernate would only know, that you want to get MCustomer, that has an iCustomerEntity. It would not know which implementation (PersonEntity or CoderEntity?) to use. How would it know which mapping to use to retrieve the data for iCustomerEntity?
Automap a property whose type is Interface
[ "", "c#", "nhibernate", "fluent-nhibernate", "" ]
Now in my program in c# that simulates the working of a lan-messenger I need to show the people who are currently online with one remote host-name on each line. However the problem here is that in order to do that I am using the function ``` //edited this line out, can't find a .Append for listBox or .AppendLine //listBox.Append(String ); listBox.Items.Add(new ListItem(String)); ``` On doing so, the carriage return and new line character(ie.. \r and \n) are being displayed as tiny little rectangular boxes at the end of the hostname. How do I get rid of that?
You could use: ``` listBox.Append(String.Replace("\r\n", "")); ``` to get rid of those characters
Another option would be to consider creating an extension method for the custom trim that you are trying to achieve. ``` /// <summary> /// Summary description for Helper /// </summary> public static class Helper { /// <summary> /// Extension Method For Returning Custom Trim /// No Carriage Return or New Lines Allowed /// </summary> /// <param name="str">Current String Object</param> /// <returns></returns> public static string CustomTrim(this String str) { return str.Replace("\r\n", ""); } } ``` Your line of code then looks like this: ``` listBox.Items.Add(new ListItem(myString.CustomTrim()); ```
Listbox data
[ "", "c#", "listbox", "" ]
The System.Exception.HResult property is protected. How can I peek inside an exception and get the HResult without resorting to reflection or other ugly hacks? --- Here's the situation: I want to write a backup tool, which opens and reads files on a system. I open the file with FileAccess.Read and FileShare.ReadWrite, according to [this guidance](https://stackoverflow.com/questions/897796/how-do-i-open-an-already-opened-file-with-a-net-streamreader), because I don't care if the file is open for writing at the time I read it. In some cases, when a file I am reading is open by another app, the System.IO.FileStream.Read() method throws a System.IO.IOException, "The process cannot access the file because another process has locked a portion of the file". This is [error 33](http://msdn.microsoft.com/en-us/library/ms681382.aspx), or I think HResult 0x80070021. [**EDIT**: I believe this can be returned when another process calls [LockFileEx](http://msdn.microsoft.com/en-us/library/aa365203.aspx) to lock a byte range within a file.] I'd like to pause and retry when I get this error. I think this is the appropriate action to take here. If the locking process releases the byte-range lock quickly, then I can proceed reading the file. How can I distinguish an IOException for this reason, from others? I can think of these ways: * private reflection - don't wanna do that. Perf will stink. * call Exception.ToString() and parse the string. Feels hacky. Won't work in i18n versions. I don't like these options. Isn't there a better, cleaner way? --- I just searched around and found [System.Runtime.InteropServices.Marshal.GetHRForException](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.gethrforexception.aspx). Will that return a uint like 0x80070021?
For .Net Framework 4.5 and above, you can use the `Exception.HResult` property: ``` int hr = ex.HResult; ``` For older versions, you can use [`Marshal.GetHRForException`](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.gethrforexception.aspx) to get back the HResult, but this [has significant side-effects and is not recommended](https://blogs.msdn.microsoft.com/yizhang/2013/01/18/marshal-gethrforexception-does-more-than-just-get-hr-for-exception/): ``` int hr = Marshal.GetHRForException(ex); ```
For what it's worth, **System.Exception.HResult** is no longer protected in .NET 4.5 -- only the setter is protected. That doesn't help with code that might be compiled with more than one version of the framework.
How do I determine the HResult for a System.IO.IOException?
[ "", "c#", ".net", "exception", "hresult", "" ]
I'm importing data from an Excel sheet on to a `DataTable` using the following code: ``` OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties=Excel 8.0"); con.Open(); _myDataSet = new DataSet(); OleDbDataAdapter myCommand = new OleDbDataAdapter(" SELECT * FROM [" + "Sheet1" + "$]", con); myCommand.Fill(_myDataSet); con.Close(); ``` I have a `Date` column in the Excel sheet in the format `dd/MM/yyyy`. The above code is failing when the date is `dd/MM/yyyy` (eg. `27/12/2009`). How to specify the date format? EDIT (adding more details): It is not throwing any exception. Data is imported to the `DataSet` until the row where an invalid `Date` format is encountered. I have the date as `dd/MM/yyyy` in Excel sheet. When I import using `OleDbDataAdapter`, it is expecting the date in the Excel sheet to be in `MM/dd/yyyy`. No naturally when it encounters a date such as `27/2/2009` it stops the process of importing, though no error/exception is thrown. So I'm having only partial results in `DataTable`. Please help.
Pulling in Date or other mixed-data column items in the past has bit me with Excel. It seems that their provider "peeks" ahead XX rows (depending on Provider version) to determine what the column type is *at runtime*. The prior answers that apply properties to your connection have helped me in the past, but do **not** help when you have BLANK dates and/or different values in the column itself - it confuses the Excel driver. What I recommend is that you use [FileHelpers](http://www.filehelpers.com/) or another third-party library instead. Infragistics Excel component has treated me very well, while FileHelpers is opensource.
When linking Excel spreadsheets in MS Access, a problem arises when a column has mixed data types. For example, if the first row in the column is "Text" and the remaining are Numeric, the Numeric fields will be formatted as Text and #Error out. Likewise with Dates and non-Dates mixed in the same column. There are some nice attempts at answers up there, but here is the **simple** solution to read these Mixed data types without a data type mismatch error: Try adding "**IMEX=1**" to your MS Access SQL, such as: SELECT Type, Width, Weight FROM [Excel 8.0;**IMEX=1**;DATABASE=C:\TEMP\MySpreadsheet.xls].MyExcelTable Thanks, Brian Jasmer
DateTime format mismatch on importing from Excel Sheet
[ "", "c#", "" ]
Does anybody know how to execute javascript functions in an html that is loaded via ajax? I mean the html contains both plain text and javascript. In my case it seems that only the in-line javascript (eg. onclick="dosomething();return false") gets executed. The pre-defined functions which are wrapped by < script language = "javascript >are unfortunately ignored.. i have search couple articles through the site but the results are either use getScript to load a pure js or use eval. please help me out of this! Thank you very much!
### File 1: ``` <script type="text/javascript"> function test() { alert('i got loaded dynamically!'); } </script> ``` ### File 2: ``` $.get('file1.html', function(html) { $(document).append(html); test(); // alerts "i got loaded dynamically!" }); ``` [See it in action](http://jsbin.com/idela).
According to [the doco](http://docs.jquery.com/Ajax/jQuery.ajax#options), if you use `$.ajax` and specify a data type of `"html"`, included script tags are evaluated when inserted in the DOM. Make sure your server is returning the correct data type, see [Specifying the Data Type for AJAX requests](http://docs.jquery.com/Specifying_the_Data_Type_for_AJAX_Requests) for more info If that doesn't help, Artem's approach also works well, providing you only make the request **once**. If you are making the same `$.get` call over and over, you'll end up with multiple copies of yourFunctionCall in the head, and Strange Things will happen :-)
jquery ajax and html
[ "", "javascript", "jquery", "html", "ajax", "" ]
Imagine I created this class: ``` public class ColoredPolygon { public Point[] Vertices { get; set; } public Brush Brush { get; set; } } ``` Inside Visual Studio isn't difficult to see which "Brush" is the class and which is the property. But something tells me that is not a best practice to name a property after its class. How would you name this property? **Update** One more question about naming: How do you name Arrays? With the plural or with singular?
I would call it `Brush`. The [Design Guidelines for Developing Class Libraries](http://msdn.microsoft.com/en-us/library/ms229042.aspx) actually says: > Consider giving a property the same > name as its type (in the [section about naming Type members](http://msdn.microsoft.com/en-us/library/ms229012.aspx)). The text following the statement suggests to do this for properties that are of Enum types, but you can find plenty of examples of this approach for other types of objects in the .NET framework, for instance the `Brush` and `Color` properties of the `Pen` class. Nothing to worry about, if `Brush` is a descriptive name for your property you should use that name, especially since it would even follow the naming pattern that you can see within the framework.
FillBrush is a good, descriptive name (and I've upvoted) but, honestly, don't worry about it until it actually becomes a real problem. In your case, it may not be the best name, but if it **were** the best name, I'd keep it until the context dictated otherwise. I have a few examples where the name of the class and the property is the same, but since the property usually is qualified by a variable name (or `this.`), I don't worry too much about it. I find the following pretty readable: ``` var poly = new ColoredPolygon(); poly.Brush = Brushes.Green; ```
Help me name this property (C#)
[ "", "c#", "naming-conventions", "naming", "" ]
I need to implement 256 bit AES encryption, but all the examples I have found online use a "KeyGenerator" to generate a 256 bit key, but I would like to use my own passkey. How can I create my own key? I have tried padding it out to 256 bits, but then I get an error saying that the key is too long. I do have the unlimited jurisdiction patch installed, so thats not the problem :) Ie. The KeyGenerator looks like this ... ``` // Get the KeyGenerator KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128); // 192 and 256 bits may not be available // Generate the secret key specs. SecretKey skey = kgen.generateKey(); byte[] raw = skey.getEncoded(); ``` [Code taken from here](http://java.sun.com/developer/technicalArticles/Security/AES/AES_v1.html) **EDIT** I was actually padding the password out to 256 bytes, not bits, which is too long. The following is some code I am using now that I have some more experience with this. ``` byte[] key = null; // TODO byte[] input = null; // TODO byte[] output = null; SecretKeySpec keySpec = null; keySpec = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); cipher.init(Cipher.ENCRYPT_MODE, keySpec); output = cipher.doFinal(input) ``` The "TODO" bits you need to do yourself :-)
Share the `password` (a `char[]`) and `salt` (a `byte[]`—8 bytes selected by a `SecureRandom` makes a good salt—which doesn't need to be kept secret) with the recipient out-of-band. Then to derive a good key from this information: ``` /* Derive the key, given password and salt. */ SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); KeySpec spec = new PBEKeySpec(password, salt, 65536, 256); SecretKey tmp = factory.generateSecret(spec); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); ``` The magic numbers (which could be defined as constants somewhere) 65536 and 256 are the key derivation iteration count and the key size, respectively. The key derivation function is iterated to require significant computational effort, and that prevents attackers from quickly trying many different passwords. The iteration count can be changed depending on the computing resources available. The key size can be reduced to 128 bits, which is still considered "strong" encryption, but it doesn't give much of a safety margin if attacks are discovered that weaken AES. Used with a proper block-chaining mode, the same derived key can be used to encrypt many messages. In [Cipher Block Chaining (CBC)](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_(CBC)), a random initialization vector (IV) is generated for each message, yielding different cipher text even if the plain text is identical. CBC may not be the most secure mode available to you (see AEAD below); there are many other modes with different security properties, but they all use a similar random input. In any case, the outputs of each encryption operation are the cipher text *and* the initialization vector: ``` /* Encrypt the message. */ Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secret); AlgorithmParameters params = cipher.getParameters(); byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV(); byte[] ciphertext = cipher.doFinal("Hello, World!".getBytes(StandardCharsets.UTF_8)); ``` Store the `ciphertext` and the `iv`. On decryption, the `SecretKey` is regenerated in exactly the same way, using using the password with the same salt and iteration parameters. Initialize the cipher with this key *and* the initialization vector stored with the message: ``` /* Decrypt the message, given derived key and initialization vector. */ Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv)); String plaintext = new String(cipher.doFinal(ciphertext), StandardCharsets.UTF_8); System.out.println(plaintext); ``` --- Java 7 included API [support for AEAD cipher modes](https://docs.oracle.com/javase/7/docs/api/javax/crypto/Cipher.html), and the "SunJCE" provider included with OpenJDK and Oracle distributions implements these beginning with Java 8. One of these modes is strongly recommended in place of CBC; it will protect the integrity of the data as well as their privacy. --- A `java.security.InvalidKeyException` with the message "Illegal key size or default parameters" means that the cryptography strength *is* limited; the unlimited strength jurisdiction policy files are not in the correct location. In a JDK, they should be placed under `${jdk}/jre/lib/security` Based on the problem description, it sounds like the policy files are not correctly installed. Systems can easily have multiple Java runtimes; double-check to make sure that the correct location is being used.
## Consider using the [Spring Security Crypto Module](http://docs.spring.io/spring-security/site/docs/3.1.x/reference/crypto.html) > The Spring Security Crypto module provides support for symmetric encryption, key generation, and password encoding. The code is distributed as part of the core module but has no dependencies on any other Spring Security (or Spring) code. It's provides a simple abstraction for encryption and seems to match what's required here, > The "standard" encryption method is 256-bit AES using PKCS #5's PBKDF2 (Password-Based Key Derivation Function #2). This method requires Java 6. The password used to generate the SecretKey should be kept in a secure place and not be shared. The salt is used to prevent dictionary attacks against the key in the event your encrypted data is compromised. A 16-byte random initialization vector is also applied so each encrypted message is unique. A look at the [internals](http://grepcode.com/file/repo1.maven.org/maven2/org.springframework.security/spring-security-core/3.1.4.RELEASE/org/springframework/security/crypto/encrypt/AesBytesEncryptor.java#53 "grepcode.com - org.springframework.security.crypto.encrypt.AesBytesEncryptor") reveals a structure similar to [erickson's answer](https://stackoverflow.com/a/992413/277307). As noted in the question, this also requires the *Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy* (else you'll encounter [`InvalidKeyException: Illegal Key Size`](https://stackoverflow.com/questions/3862800/invalidkeyexception-illegal-key-size/3864325)). It's downloadable for [Java 6](http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html "Java 6 Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files"), [Java 7](http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html "Java 7 Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files") and [Java 8](http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html). ### Example usage ``` import org.springframework.security.crypto.encrypt.Encryptors; import org.springframework.security.crypto.encrypt.TextEncryptor; import org.springframework.security.crypto.keygen.KeyGenerators; public class CryptoExample { public static void main(String[] args) { final String password = "I AM SHERLOCKED"; final String salt = KeyGenerators.string().generateKey(); TextEncryptor encryptor = Encryptors.text(password, salt); System.out.println("Salt: \"" + salt + "\""); String textToEncrypt = "*royal secrets*"; System.out.println("Original text: \"" + textToEncrypt + "\""); String encryptedText = encryptor.encrypt(textToEncrypt); System.out.println("Encrypted text: \"" + encryptedText + "\""); // Could reuse encryptor but wanted to show reconstructing TextEncryptor TextEncryptor decryptor = Encryptors.text(password, salt); String decryptedText = decryptor.decrypt(encryptedText); System.out.println("Decrypted text: \"" + decryptedText + "\""); if(textToEncrypt.equals(decryptedText)) { System.out.println("Success: decrypted text matches"); } else { System.out.println("Failed: decrypted text does not match"); } } } ``` And sample output, ``` Salt: "feacbc02a3a697b0" Original text: "*royal secrets*" Encrypted text: "7c73c5a83fa580b5d6f8208768adc931ef3123291ac8bc335a1277a39d256d9a" Decrypted text: "*royal secrets*" Success: decrypted text matches ```
Java 256-bit AES Password-Based Encryption
[ "", "java", "encryption", "cryptography", "passwords", "aes", "" ]
How do I set an environment variable in C++? * They do not need to persist past program execution * They only need to be visible in the current process * Preference for platform independent but for my problem only needs to work on Win32/64 Thanks
``` NAME putenv - change or add an environment variable SYNOPSIS #include &ltstdlib.h> int putenv(char *string); DESCRIPTION The putenv() function adds or changes the value of environment variables. The argument string is of the form name=value. If name does not already exist in the environment, then string is added to the environment. If name does exist, then the value of name in the environment is changed to value. The string pointed to by string becomes part of the environment, so altering the string changes the environment. ``` On Win32 it's called \_putenv I believe. See [SetEnvironmentVariable](http://msdn.microsoft.com/en-us/library/ms686206.aspx) also if you're a fan of long and ugly function names.
There's also `setenv`, which is slightly more flexible than `putenv`, in that `setenv` checks to see whether the environment variable is already set and won't overwrite it, if you set the "overwrite" argument indicating that you don't want to overwrite it, and also in that the name and value are separate arguments to `setenv`: ``` NAME setenv - change or add an environment variable SYNOPSIS #include <stdlib.h> int setenv(const char *name, const char *value, int overwrite); int unsetenv(const char *name); Feature Test Macro Requirements for glibc (see feature_test_macros(7)): setenv(), unsetenv(): _POSIX_C_SOURCE >= 200112L || /* Glibc versions <= 2.19: */ _BSD_SOURCE DESCRIPTION The setenv() function adds the variable name to the environment with the value value, if name does not already exist. If name does exist in the environment, then its value is changed to value if overwrite is nonzero; if overwrite is zero, then the value of name is not changed (and setenv() returns a success status). This function makes copies of the strings pointed to by name and value (by contrast with putenv(3)). The unsetenv() function deletes the variable name from the environment. If name does not exist in the environment, then the function succeeds, and the environment is unchanged. ``` I'm not saying either is better or worse than the other; it just depends on your application. See <http://man7.org/linux/man-pages/man3/setenv.3.html>
Set local environment variables in C++
[ "", "c++", "c", "manpage", "" ]
I am working on making an expression class: ``` template<typename T, typename U> class expression { public: expression(T vala, U valb, oper o){val1 = vala; val2 = valb; op = o;} operator bool{return(val1 op val2);} private: T val1; U val2; oper op; }; ``` as you can see, this is somewhat pseudocode, because I need an operator class. My original thought was to create an array of all possible operators, and then convert it through a string, but that wouldn't work because of the sheer number of operators, and how to convert it to a string except through a two dimensional array, where n[0][0] has the first operator, and n[0][1] has that operators string. Does anybody have any suggestions to adding an operator value to my expression class?
Maybe a function pointer. Instead of ... ``` operator bool{return(val1 op val2);} ``` ... code it as ... ``` operator bool{return op(val1, val2);} ``` ... in which case `op` can be a pointer to a (any) function which takes two parameters and which returns bool. ``` template<typename T, typename U> class expression { public: //define pointer-to-function type typedef bool *oper(const T& val1, const U& val2); ... etc ... ```
Similar methods are used in c++ expression templates techniqueue. You create expression as a class with a method such as apply or evaluate. This method takes the parameters and applies the expression. Have a look what expression templates are using. <http://www.angelikalanger.com/Articles/Cuj/ExpressionTemplates/ExpressionTemplates.htm> [https://www.cct.lsu.edu/~hkaiser/spring\_2012/files/ExpressionTemplates-ToddVeldhuizen.pdf](http://ubiety.uwaterloo.ca/%7Etveldhui/papers/Expression-Templates/exprtmpl.html) As an example in your case: ``` struct isEqual { template <typename T, typename U> bool operator()(T a, U b) { return a == b; } }; template <typename T, typename OP> struct expression { T& a; T& b; OP& op; expression(T a, T b, OP op) : a(a), b(b), op(op) {} void eval() { op(a,b); } }; int main() { expression<int, isEqual> exp(1,2,isEqual()); exp.eval(); } ```
How to make an "operator" variable? (C++)
[ "", "c++", "operators", "expression", "operator-keyword", "" ]
I'd like to know what kind of performance impact Html helpers have on C# ASP.NET MVC views, especially when setting attribute parameters, and what kind of advantages they have overall (why use them?) With Html Helpers: ``` <%= Html.TextBox("firstName", Model.FirstName, new { @disabled = "disabled", @class = "myCssClass" }) %> ``` Direct Html: ``` <input type="text" class="myCssClass" name="firstName" disabled="disabled" text="<%= Model.FirstName %>"/> ``` I have quite a few pages that contain between 5 and 15 of such inputs. On top of that Html Helpers allow you to render the form (think Html.BeginForm()) etc. so you potentially end up with 20 or even more Html Helper calls. I think some of them use reflection too, e.g. when you set attributes like the disabled one above. Isn't there a huge performance impact to do this? Why on earth is it considered better practice to use those helpers? Please somebody give me a good reason :) I'd like to use them but I really fear the performance impact they have. Are there any real advantages to using Html helpers?
The overhead of doing reflection is something that people really like to worry about. Outside of synthetic benchmarks, however, it becomes a pretty boring topic! In the context of a real production application (where you are doing CRUD operations against a databases or consuming a webservice for example), the overhead of using html helpers is going to be insignificant compared to the overhead of doing that kind of context switch. Really not something to worry about especially considering the benefits html helpers provide such as automatically restoring form values from ViewData/Model, and validation support. Bottom line: use html helpers when possible. You can always use straight html if you encounter a rare limitation that you need to work around.
> Are there any real advantages to using Html helpers? The biggest advantage I see in using HtmlHelpers is to provide an abstraction layer for your markup. If in the future you wanted to change the structure of your markup you only need to change the output generated from the helpers, as opposed to going through all your views and making manual changes. It also promotes consistency amongst teams of developers. Those developers aren't required to know the exact details of the markup structure and css classes your UI is based on. As an example, I'm currently developing a new UI framework for the company I work for based on Bootstrap. I have created a set of HtmlHelpers that generate the appropriate markup and css classes for the various Bootstrap components. This is all done in a Fluent API which is nice for developers to use, without any in-depth knowledge required of Bootstrap, plus with the added benefit of having Intellisense available. Telerik's [Kendo UI](http://demos.kendoui.com/web/overview/index.html) framework is based on the same concept. Take a look at some of their code samples. As for reflection and performance, I really wouldn't worry considering the number of calls likely to be involved in a few HtmlHelper methods. See this [post](https://stackoverflow.com/a/1112213/295813) for reasons why.
C# MVC: Performance and Advantages of MVC Html Helpers vs. Direct HTML in views
[ "", "c#", "asp.net-mvc", "" ]
I am trying to do pretty much the same, as is for example on Sourceforge. After a user creates some data, I generate a file and I want it to be offered to him after a page load. However, I know almost nothing about javascript and simple copy-paste of ``` <script type="text/javascript"> var download_url = "http://downloads.sourceforge.net/sourceforge/itextsharp/itextsharp-4.1.2-dll.zip?use_mirror=dfn"; function downloadURL() { if (download_url.length != 0 && !jQuery.browser.msie) { window.location.href = download_url; } } jQuery(window).load(downloadURL); </script> ``` is not enough. It is important for the user to download the file, so how to do that? A question related to the previous is - where to store the file i created? Once while using the asp.net development server and then on the real IIS server? And how should this address look? When I tried ``` setTimeout("window.location.href='file://localhost/C:/Downloads/file.pdf'", 2000); ``` I was getting nothing, with HTTP an error of unknown address.
See [Haack's DownloadResult](http://haacked.com/archive/2008/05/10/writing-a-custom-file-download-action-result-for-asp.net-mvc.aspx) example. It explains (I think) exactly what you're truing to do. Except you would provide the timeout call with your download action url.
You can create your own PdfResult which extends ActionResult like this: ``` public class PdfResult : ActionResult { public byte[] Content { get; set; } public string FileName { get; set; } public override void ExecuteResult(ControllerContext context) { var response = context.HttpContext.Response; response.AddHeader("content-disposition", "attachment; filename=" + this.FileName); response.AddHeader("content-length", this.Content.Length.ToString()); response.ContentType = "application/pdf"; using (MemoryStream memoryStream = new MemoryStream(this.Content)) { memoryStream.WriteTo(response.OutputStream); } response.End(); } ``` Then in your action you can simply return the file as follows: ``` public ActionResult Pdf(string param1...) { var content = GeneratePdf(); //etc var fileName = AssignFileName(); return new PdfResult { Content = content, FileName = fileName + ".pdf" }; } ```
Load file after page is complete without redirecting
[ "", "javascript", "jquery", "asp.net-mvc", "file", "download", "" ]
Can anyone tell me what is wrong with this? The file is renamed using a time stamp but the extension doesn't get extracted and placed in the new name. ``` $filenameext = pathinfo($filename, PATHINFO_EXTENSION); $today = getdate(); $uniqueStr = $today[year]; $uniqueStr .= $today[mon]; $uniqueStr .= $today[wday]; $uniqueStr .= $today[mday]; $uniqueStr .= $today[hours]; $uniqueStr .= $today[minutes]; $uniqueStr .= $today[seconds]; $filename = $uniqueStr.".".$filenameext; ``` The full code: ``` <?php $folder = 'images/'; $orig_w = 500; if( isset($_POST['submit']) ) { $imageFile = $_FILES['image']['tmp_name']; $filenameext = pathinfo($filename, PATHINFO_EXTENSION); $today = getdate(); $uniqueStr = $today[year]; $uniqueStr .= $today[mon]; $uniqueStr .= $today[wday]; $uniqueStr .= $today[mday]; $uniqueStr .= $today[hours]; $uniqueStr .= $today[minutes]; $uniqueStr .= $today[seconds]; $filename = $uniqueStr.".".$filenameext; list($width, $height) = getimagesize($imageFile); $src = imagecreatefromjpeg($imageFile); $orig_h = ($height/$width)* $orig_w; $tmp = imagecreatetruecolor($orig_w, $orig_h); imagecopyresampled($tmp, $src, 0,0,0,0,$orig_w,$orig_h,$width,$height); imagejpeg($tmp, $folder.$filename,100); imagedestroy($tmp); imagedestroy($src); $filename = urlencode($filename); header("Location: crop.php?filename=$filename&height=$orig_h"); } ``` ?>
This should work fine - can you print your $filename right before pathinfo()? Edit after you posted your code: so let me get this straight ``` $imageFile = $_FILES['image']['tmp_name']; $filenameext = pathinfo($filename, PATHINFO_EXTENSION); ``` You read in $imageFile but parse an uninitialized variable $filename?
Do not trust the filename extension to describe the file format accurately. Don't trust the mime type either. ``` $sourceFile = $_FILES['photoupload']['tmp_name']; list($width, $height, $type, $attr) = getimagesize($sourceFile); $filetype = image_type_to_extension($type, true); // $filetype includes the dot. if ('.jpeg' == $filetype) { $filetype = '.jpg'; // use jpg, not the 'jpeg' the function would return } ```
Extracting File Extension in PHP (image upload script)
[ "", "php", "image", "file", "upload", "" ]
## Heading I want to pass some variables from one page to another but I don't want them to appear in the URL. When I use a form to post the an ActionResult it works fine. However, when I do this ``` return RedirectToAction("Trackers",new{page = 1, orderby=desc}); ``` I get the URL: <http://examplesite.com/Trackers?page=1&orderby=desc> Is there any way I can get the following URL instead but still pass the page and orderby variables "behind the scenes"? <http://examplesite.com/Trackers> Thanks TheLorax
I'm not sure it's a good idea to do what you're suggesting, however, you might be able to use the TempData (same place as the ViewData) to save your information before the redirect. I believe that after your next request, anything in the temp data is cleared out.
You could pass a Model object containing the page number and the orderby instead of an anonymous object, and have your view inherit the model class of the object you are passing. Your model object with the page number and orderby then becomes available to the view, without employing a query string This is not, however, the preferred method of doing this. Your model objects should be reserved for their intended purpose, which is passing actual data to your view.
ASP.NET MVC parsing variables wihout URL query string
[ "", "c#", "asp.net-mvc", "query-string", "" ]
I want to use jQuery's great live functionality for a mouseenter event, but it's currently unsupported. Below is my first go at a solution, but it doesn't seem optimal. Suggestions? Improvements? ``` // mouseenter emulation jQuery('.selector').live('mouseover',function (e) { // live sees all mouseover events within the selector // only concerned about events where the selector is the target if (this != e.target) return; // examine relatedTarget's parents to see if target is a parent. // if target is a parent, we're "leaving" not entering var entering = true; jQuery(e.relatedTarget).parents().each(function () { if (this == e.target) { entering = false; return false; // found; stop searching } }); if (!entering) return; /* the rest of my code */ }); ``` I can't check target's children for relatedTarget b/c there's not an easy way to get all child nodes. I can't check directly if target's parents have relatedTarget as a parent and thus "entering" target, b/c for mouseover, it could be entering from an adjacent sibling and not a parent. This solution works ok. I've tested it, and it seems fine, but how could I improve it? It also suffers from how the DOM is laid out. Some part of the selector elements must be exposed to see the mouseover event, but that's rarely a problem in the examples that I'm trying this on. Still, if there's a way to guarantee that it will be seen, that would be nice. I guess I want to know if I'm approaching this right, and if not, what's better?
It's been a while now with no takers, so I'm assuming there's nothing better. I'm using this in a couple projects now, so I'll take it out of the unanswered questions pile. Hope others find it useful, and if you find a bug or come up with something better, let me know.
I ended up doing: ``` $("#id").delegate(".selector", "mouseover", function(){ if(!$(this).hasClass("bound")){ $(this).hover(function(){ alert('entering'); }, function(){ alert('leaving'); }).mouseover().addClass("bound"); } }); ```
How should I emulate a mouseenter event using jquery's live functionality?
[ "", "javascript", "jquery", "events", "mouse", "" ]
I'm using [FlatPack](http://flatpack.sourceforge.net/) to parse and load data from flat files. This requires loading a config file that stores mappings of the columns of the flat file. I have a constant to define the location of the mapping file: ``` private static final String MAPPING_FILE = "src/com/company/config/Maping.pzmap.xml"; ``` I have a parse(File dataFile) method that actually does the parsing: ``` private void parse(File dataFile) throws FileNotFoundException, SQLException { Parser parser; log.info("Parsing " + dataFile.getName()); FileReader mappingFileReader = new FileReader(MAPPING_FILE); FileReader dataFileReader = new FileReader(dataFile); parser = DefaultParserFactory.getInstance().newFixedLengthParser(mappingFileReader, dataFileReader); parser.setHandlingShortLines(true); DataSet dataSet = parser.parse(); //process the data } ``` When I jar up everything and run it as a jar - it bombs out on `FileReader mappingFileReader = new FileReader(MAPPING_FILE);` with a `FileNotFoundException`. That file is inside the jar though. How do I get to it? I've looked at [this question](https://stackoverflow.com/questions/600146/run-exe-which-is-packaged-inside-jar) and [this question](https://stackoverflow.com/questions/463972/creating-a-new-file-using-an-existing-file-within-a-jar) about accessing files inside jars and they both recommend temporarily extracting the file. I don't want to do that though.
if it's inside a JAR, it's not a File, generally speaking. You should load the data using [`Class.getResourceAsStream(String)`](http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)), or something similar.
I think it is solved just here: <http://www.velocityreviews.com/forums/t129474-beginner-question-how-to-access-an-xml-file-inside-a-jar-without-extracting-it.html>
How do I access a config file inside the jar?
[ "", "java", "jar", "" ]
I have been working with the [Boost C++ Libraries](http://en.wikipedia.org/wiki/Boost_C++_Libraries) for quite some time. I absolutely love the Boost [Asio C++ library](http://en.wikipedia.org/wiki/Asio_C++_library) for network programming. However I was introduced to two other libraries: [POCO](http://pocoproject.org) and [Adaptive Communication Environment (ACE) framework](http://en.wikipedia.org/wiki/Adaptive_Communication_Environment). I would like to know the good and bad of each.
As rdbound said, Boost has a "near STL" status. So if you don't *need* another library, stick to Boost. However, I use [POCO](http://pocoproject.org/) because it has some advantages for my situation. The good things about POCO IMO: * Better thread library, especially a Active Method implementation. I also like the fact that you can set the thread priority. * More comprehensive network library than `boost::asio`. However `boost::asio` is also a very good library. * Includes functionality that is not in Boost, like XML and database interface to name a few. * It is more integrated as one library than Boost. * It has clean, modern and understandable C++ code. I find it far easier to understand than most of the Boost libraries (but I am not a template programming expert :)). * It can be used on a lot of platforms. Some disadvantages of POCO are: * It has limited documentation. This somewhat offset by the fact that the source is easy to understand. * It has a far smaller community and user base than, say, Boost. So if you put a question on Stack Overflow for example, your chances of getting an answer are less than for Boost * It remains to be seen how well it will be integrated with the new C++ standard. You know for sure that it will not be a problem for Boost. I never used ACE, so I can't really comment on it. From what I've heard, people find POCO more modern and easier to use than ACE. Some answers to the comments by Rahul: 1. I don't know about versatile and advanced. The POCO thread library provides some functionality that is not in Boost: `ActiveMethod` and `Activity`, and `ThreadPool`. IMO POCO threads are also easier to use and understand, but this is a subjective matter. 2. POCO network library also provides support for higher level protocols like HTTP and SSL (possibly also in `boost::asio`, but I am not sure?). 3. Fair enough. 4. Integrated library has the advantage of having consistent coding, documentation and general "look and feel". 5. Being cross-platform is an important feature of POCO, this is not an advantage in relation to Boost. Again, you should probably only consider POCO if it provides some functionality you need and that is not in Boost.
I've used all three so here's my $0.02. I really want to vote for Doug Schmidt and respect all the work he's done, but to be honest I find ACE mildly buggy and hard to use. I think that library needs a reboot. It's hard to say this, but I'd shy away from ACE for now unless there is a compelling reason to use TAO, or you need a single code base to run C++ on both Unix variants and Windows. TAO is fabulous for a number of difficult problems, but the learning curve is intense, and there's a reason CORBA has a number of critics. I guess just do your homework before making a decision to use either. If you are coding in C++, boost is in my mind a no-brainer. I use a number of the low level libraries and find them essential. A quick grep of my code reveals shared\_ptr, program\_options, regex, bind, serialization, foreach, property\_tree, filesystem, tokenizer, various iterator extensions, alogrithm, and mem\_fn. These are mostly low-level functionality that really ought to be in the compiler. Some boost libraries are very generic; it can be work to get them to do what you want, but it's worthwhile. Poco is a collection of utility classes that provide functionality for some very concrete common tasks. I find the libraries are well-written and intuitive. I don't have to spend much time studying documentation or writing silly test programs. I'm currently using Logger, XML, Zip, and Net/SMTP. I started using Poco when libxml2 irritated me for the last time. There are other classes I could use but haven't tried, e.g. Data::MySQL (I'm happy with mysql++) and Net::HTTP (I'm happy with libCURL). I'll try out the rest of Poco eventually, but that's not a priority at this point.
ACE vs Boost vs POCO
[ "", "c++", "boost", "poco-libraries", "ace", "" ]
I'm trying to implement a custom TableRenderer as described in [this tutorial](http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#renderer). I'd like to have the renderer line-wrap each text that is to long for the given cell. The idea is, to use a TextArea as renderer, as it supports line wrapping. However, the following code does not behave as expected: ``` public class LineWrapCellRenderer extends JTextArea implements TableCellRenderer { @Override public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { this.setText((String)value); this.setWrapStyleWord(true); this.setLineWrap(true); return this; } } ``` I set this renderer with ``` table.setDefaultRenderer(String.class, new LineWrapCellRenderer()); ``` But the cell entries stay unwrapped. If I add `this.setBackground(Color.YELLOW)` to the `getTableCellRendererComponent()` method, all cells are yellow as expected, but not wrapped. Any ideas? **UPDATE:** As Michael Borgwardt stated in the comments, the problem is not the line wrap, but the row height: JTables rows are fixed size, so if a cell is getting higher (cause the text is now multi-lined), we have to increase the row height. But how much? I will check if this is worth another SO-question. If not, I will add this solution here. **Update2:** The following code will determine the row height (if placed in `getTableCellRendererComponent()`): ``` int fontHeight = this.getFontMetrics(this.getFont()).getHeight(); int textLength = this.getText().length(); int lines = textLength / this.getColumns() +1;//+1, cause we need at least 1 row. int height = fontHeight * lines; table.setRowHeight(row, height); ```
The problem is that the height of rows in JTable is fixed, so it's not just a matter of having a renderer that wraps; I'm not sure why it doesn't, but if it did, the wrapped text would be cropped - or maybe that's exactly what you're seeing. To adjust row heights, you need to set them individually. [Heres' some code for that](https://web.archive.org/web/20061217042643/http://www.exampledepot.com/egs/javax.swing.table/RowHeight.html): ``` int rows = 10; int cols = 5; JTable table = new JTable(rows, cols); // Set the 1st row to 60 pixels high table.setRowHeight(0, 60); // Set the height of all rows to 32 pixels high, // regardless if any heights were assigned to particular rows table.setRowHeight(32); // the height of the 1st row is set to 32 pixels high // Returns the preferred height of a row. // The result is equal to the tallest cell in the row. public int getPreferredRowHeight(JTable table, int rowIndex, int margin) { // Get the current default height for all rows int height = table.getRowHeight(); // Determine highest cell in the row for (int c=0; c<table.getColumnCount(); c++) { TableCellRenderer renderer = table.getCellRenderer(rowIndex, c); Component comp = table.prepareRenderer(renderer, rowIndex, c); int h = comp.getPreferredSize().height + 2*margin; height = Math.max(height, h); } return height; } // The height of each row is set to the preferred height of the // tallest cell in that row. public void packRows(JTable table, int margin) { packRows(table, 0, table.getRowCount(), margin); } // For each row >= start and < end, the height of a // row is set to the preferred height of the tallest cell // in that row. public void packRows(JTable table, int start, int end, int margin) { for (int r=0; r<table.getRowCount(); r++) { // Get the preferred height int h = getPreferredRowHeight(table, r, margin); // Now set the row height using the preferred height if (table.getRowHeight(r) != h) { table.setRowHeight(r, h); } } } ```
Hi I had your same problem but the solution I implemented is inspired by the sample available from the Java Tutorial for drawing multiline text and draws the text on the cell using the text APIs. <http://java.sun.com/docs/books/tutorial/2d/text/drawmulstring.html> ``` import java.awt.Component; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.font.FontRenderContext; import java.awt.font.LineBreakMeasurer; import java.awt.font.TextLayout; import java.text.AttributedCharacterIterator; import java.text.AttributedString; import java.text.BreakIterator; import javax.swing.JTable; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; public class MultilineTableCell implements TableCellRenderer { class CellArea extends DefaultTableCellRenderer { /** * */ private static final long serialVersionUID = 1L; private String text; protected int rowIndex; protected int columnIndex; protected JTable table; protected Font font; private int paragraphStart,paragraphEnd; private LineBreakMeasurer lineMeasurer; public CellArea(String s, JTable tab, int row, int column,boolean isSelected) { text = s; rowIndex = row; columnIndex = column; table = tab; font = table.getFont(); if (isSelected) { setForeground(table.getSelectionForeground()); setBackground(table.getSelectionBackground()); } } public void paintComponent(Graphics gr) { super.paintComponent(gr); if ( text != null && !text.isEmpty() ) { Graphics2D g = (Graphics2D) gr; if (lineMeasurer == null) { AttributedCharacterIterator paragraph = new AttributedString(text).getIterator(); paragraphStart = paragraph.getBeginIndex(); paragraphEnd = paragraph.getEndIndex(); FontRenderContext frc = g.getFontRenderContext(); lineMeasurer = new LineBreakMeasurer(paragraph,BreakIterator.getWordInstance(), frc); } float breakWidth = (float)table.getColumnModel().getColumn(columnIndex).getWidth(); float drawPosY = 0; // Set position to the index of the first character in the paragraph. lineMeasurer.setPosition(paragraphStart); // Get lines until the entire paragraph has been displayed. while (lineMeasurer.getPosition() < paragraphEnd) { // Retrieve next layout. A cleverer program would also cache // these layouts until the component is re-sized. TextLayout layout = lineMeasurer.nextLayout(breakWidth); // Compute pen x position. If the paragraph is right-to-left we // will align the TextLayouts to the right edge of the panel. // Note: this won't occur for the English text in this sample. // Note: drawPosX is always where the LEFT of the text is placed. float drawPosX = layout.isLeftToRight() ? 0 : breakWidth - layout.getAdvance(); // Move y-coordinate by the ascent of the layout. drawPosY += layout.getAscent(); // Draw the TextLayout at (drawPosX, drawPosY). layout.draw(g, drawPosX, drawPosY); // Move y-coordinate in preparation for next layout. drawPosY += layout.getDescent() + layout.getLeading(); } table.setRowHeight(rowIndex,(int) drawPosY); } } } public Component getTableCellRendererComponent( JTable table, Object value,boolean isSelected, boolean hasFocus, int row,int column ) { CellArea area = new CellArea(value.toString(),table,row,column,isSelected); return area; } } ``` It resizes row heigth too but it does it well only when this renderer is used for a single column. And this is the way I used to invoke it for render my table. ``` final int wordWrapColumnIndex = ...; myTable = new JTable() { public TableCellRenderer getCellRenderer(int row, int column) { if (column == wordWrapColumnIndex ) { return wordWrapRenderer; } else { return super.getCellRenderer(row, column); } } }; ```
How to wrap lines in a jtable cell?
[ "", "java", "swing", "jtable", "" ]
I'm developing a web application that will enable users to post short status updates similar to Twitter. The only way I can think of storing these posts is to have a large "status\_updates" table that stores EVERY user's status updates: ``` -------------------------------------- | table: status_updates | -------------------------------------| | id | user_who_posted | update_text | -------------------------------------- ``` This method requires something like this SQL query to get each user's updates: ``` SELECT * FROM status_updates where user_who_posted="username" ``` and I think that wouldn't be very inefficient. Is there a better way of doing this?
Build a user table, and have the `user_id` be an integer foreign key to that user table. Then, build an index on the `user_id` field to allow for rapid retrieval. In short: ``` status_updates: -------------------------------------- | status_id | user_id | status | -------------------------------------- | 1 | 1 | Woot! | -------------------------------------- | 2 | 1 | Yeah! | -------------------------------------- | 3 | 2 | Hello! | -------------------------------------- users: -------------------------- | user_id | username | -------------------------- | 1 | 'Joe' | -------------------------- | 2 | 'John' | -------------------------- ``` Then, to retrieve, you would do this: ``` select u.username, s.status from status_updates s inner join users u on s.user_id = u.user_id where u.username = 'John' ``` This will retrieve: ``` ------------------------- | username | status | ------------------------- | John | Hello! | ------------------------- ``` Do with that what you will. That will be very performant on millions of rows, so long as you build your indexes right. What RDBMS are you using, so I can point you to the right spot for that?
This actually can be very efficient as long as you properly set up an index for the status\_updates table on user. If you are truly worried about the table becoming very, very large you may want to look into [horizontal partitioning](http://en.wikipedia.org/wiki/Shard_(database_architecture)) of your database(s).
What is a better way to store status updates in a database?
[ "", "sql", "database", "database-design", "" ]
I read few books on spring2.5 on these topic, but still cannot grab the concepts when to use @initBinder. can anyone share any reference or explain in what situation i can use this on web application? How propertyEditor relate to it?
Well I can't really put it any better than the books, but if your controller has any public methods annotated with @InitBinder, then these methods will be called by the container just before each request is processed, passing in the WebDataBinder being used by the framework. The most common reason to do this is when you want to customise the way that Spring tries to bind request parameters on to your model, for example if your model has custom datatypes that Spring can't handle out of the box. You register your PropertyEditors against the WebDataBinder. A trivial example would be if you use the JodaTime library in your model, and you want to bind timestamp strings on to a Joda DateTime object. With Spring 2.0, you use to have to override the protected initBinder() method from the controller superclass, but Spring 2.5 removes the need to do that, you can just use annotations now.
Another reason beside what skaffman mentioned, would be to set a custom validator on your WebDataBinder. What I will usually do is use JSR-303 bean validation, and then bind a validator that provides additional validation not provided by JSR-303. Inside your controller: ``` @InitBinder protected void initBinder(WebDataBinder webDataBinder) { Validator validator = webDataBinder.getValidator(); webDataBinder.setValidator(new UserFormValidator(validator)); } ``` What I'm doing is taking in the bean validator, calling that inside my custom validator, and then calling my custom validations. Something like this: ``` public class UserFormValidator implements Validator { private Validator validator; public AuthUserFormValidator(Validator validator) { this.validator = validator; } @Override public boolean supports(Class<?> clazz) { return UserForm.class.equals(clazz); } @Override public void validate(Object target, Errors errors) { // Run the bean validation... validator.validate(target, errors); // Do your custom validation on userForm here... UserForm userForm = (UserForm) target; // Validation on userForm... } } ```
spring initBinder and webbindinginitializer example
[ "", "java", "spring", "spring-mvc", "" ]
Recently I have been reading more and more about people using custom attributes in their HTML tags, mainly for the purpose of embedding some extra bits of data for use in javascript code. I was hoping to gather some feedback on whether or not using custom attributes is a good practice, and also what some alternatives are. It seems like it can really simplify *both* server side and client side code, but it also isn't W3C compliant. Should we be making use of custom HTML attributes in our web apps? Why or why not? For those who think custom attributes are a good thing: what are some things to keep in mind when using them? For those who think custom attributes are bad thing: what alternatives do you use to accomplish something similar? **Update:** I'm mostly interested in the *reasoning* behind the various methods, as well as points as to why one method is better than another. I think we can all come up with 4-5 different ways to accomplish the same thing. (hidden elements, inline scripts, extra classes, parsing info from ids, etc). **Update 2:** It seems that the HTML 5 `data-` attribute feature has a lot of support here (and I tend to agree, it looks like a solid option). So far I haven't seen much in the way of rebuttals for this suggestion. Are there any issues/pitfalls to worry about using this approach? Or is it simply a 'harmless' invalidation of the current W3C specs?
HTML 5 explicitly allows custom attributes that begin with `data`. So, for example, `<p data-date-changed="Jan 24 5:23 p.m.">Hello</p>` is valid. Since it's officially supported by a standard, I think this is the best option for custom attributes. And it doesn't require you to overload other attributes with hacks, so your HTML can stay semantic. Source: [http://www.w3.org/TR/html5/dom.html#embedding-custom-non-visible-data-with-the-data-\*-attributes](http://www.w3.org/TR/html5/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
Here's a technique I've been using recently: ``` <div id="someelement"> <!-- { someRandomData: {a:1,b:2}, someString: "Foo" } --> <div>... other regular content...</div> </div> ``` The comment-object ties to the parent element (i.e. #someelement). Here's the parser: **<http://pastie.org/511358>** To get the data for any particular element simply call **`parseData`** with a reference to that element passed as the only argument: ``` var myElem = document.getElementById('someelement'); var data = parseData( myElem ); data.someRandomData.a; // <= Access the object staight away ``` --- It can be more succinct than that: ``` <li id="foo"> <!--{specialID:245}--> ... content ... </li> ``` Access it: ``` parseData( document.getElementById('foo') ).specialID; // <= 245 ``` --- The only disadvantage of using this is that it cannot be used with self-closing elements (e.g. `<img/>`), since the comments must be *within* the element to be considered as that element's data. --- **EDIT**: Notable benefits of this technique: * Easy to implement * Does *not* invalidate HTML/XHTML * Easy to use/understand (basic JSON notation) * Unobtrusive and semantically cleaner than most alternatives --- Here's the parser code (copied from the **<http://pastie.org/511358>** hyperlink above, in case it ever becomes unavailable on pastie.org): ``` var parseData = (function(){ var getAllComments = function(context) { var ret = [], node = context.firstChild; if (!node) { return ret; } do { if (node.nodeType === 8) { ret[ret.length] = node; } if (node.nodeType === 1) { ret = ret.concat( getAllComments(node) ); } } while( node = node.nextSibling ); return ret; }, cache = [0], expando = 'data' + +new Date(), data = function(node) { var cacheIndex = node[expando], nextCacheIndex = cache.length; if(!cacheIndex) { cacheIndex = node[expando] = nextCacheIndex; cache[cacheIndex] = {}; } return cache[cacheIndex]; }; return function(context) { context = context || document.documentElement; if ( data(context) && data(context).commentJSON ) { return data(context).commentJSON; } var comments = getAllComments(context), len = comments.length, comment, cData; while (len--) { comment = comments[len]; cData = comment.data.replace(/\n|\r\n/g, ''); if ( /^\s*?\{.+\}\s*?$/.test(cData) ) { try { data(comment.parentNode).commentJSON = (new Function('return ' + cData + ';'))(); } catch(e) {} } } return data(context).commentJSON || true; }; })(); ```
Custom attributes - Yea or nay?
[ "", "javascript", "html", "xhtml", "custom-attribute", "" ]
I wanted to add to my `jdk6\jre\lib\security\java.policy` file an interdiction to create some classes that are blacklisted by appengine. For example I want my local jvm to throw an exception when the application tries to instantiate `javax.naming.NamingException`. It is possible? I will try to explain my specific problem here. Google offers an service (GAE-google app engine) that has some limitations on what classes can be used. For example doesn't instantiate JNDI classes that are in javax.naming package. They also offer an testing server that can be used to tests this application on my machine, but this server allows such classes and can exacute the code. You find out that you used a blacklisted class only after you upload your application to google. I was thinking if such class blacklist enforcement couldn't be done on the development jvm. Else i'm thinking that this would be easy they might already provide such a policy file.
You could write a small loader application that creates a [new, custom classloader](http://www.javaworld.com/jw-03-2000/jw-03-classload.html). Your application classes could then be loaded using this classloader. In the custom classloader, you can then throw ClassNotFoundException when your application tries to access a class that you want to blacklist. You will need to overload the load() method. This method will be responsible for throwing the exception on your blacklisted classes ordelegating to the parent Classloader if the class is allowed. A sample implementation: ``` public Class loadClass(String name) throws ClassNotFoundException { if(name.equals("javax.lang.ClassIDontLike")){ throw new ClassNotFoundException("I'm sorry, Dave. I'm afraid I can't do that."); } return super.loadClass(name, false); } ``` (Of course, a real implementation can be way more sophisticated than this) Because the classes of your application are loaded through this Classloader, and you are only delegating the loadClass() invokations to the parent classloader when you want to, you can blacklist any classes that you need. I am pretty sure that this is the method that Google uses to blacklist classes in their server. They load every app in a specific Classloader. This is also similar to the way that Tomcat isolates the different Web Applications.
Wouldn't you rather get compilation errors than runtime errors while testing your program? You could configure your IDE or compiler to warn you when an undesired class is instantiated. I know AspectJ has some nice features for this: You can define compilation warnings/errors on join points and get feedback in e.g. Eclipse. To use this in Eclipse, you simply install the AspectJ plugin and write a suitable aspect. To get the errors while compiling from a command line or script, you would actually have to use the AspectJ compiler, but I doubt that you would need that.
Can i deny access to a jvm class by configuring java.policy file?
[ "", "java", "security", "google-app-engine", "policy", "classloader", "" ]
We're rewriting our CMS at the moment and we want our clients to be able to re-order items in a table using a "position" field. So, if they mark an items as position 1 it goes at the top, then position 2 underneath it etc. The problem is that we don't want to them to have to fill in a position every time, only if they want to re-order something so the position field will often be blank. So you might have the following... Car - 1 Bike - 2 House Computer Dog This causes a problem because if you use the following SQL... ``` SELECT ProductName FROM Products ORDER BY Position DESC; ``` All the blank ones go to the top, not the bottom. Can they be put into the correct order using a SQL statement?
``` SELECT ProductName FROM Products ORDER BY CASE WHEN Position is null THEN 1 ELSE 0 END, Position ``` If you want to order by Position Descending while maintaining nulls at the bottom, this will do it: ``` ORDER BY CASE WHEN Position is null THEN 1 ELSE 0 END, Position desc ``` If you want consistent sorting (you might be paging), then add ProductName or ProductID on the end to break all the ties between unpositioned products. ``` ORDER BY CASE WHEN Position is null THEN 1 ELSE 0 END, Position, ProductID ```
``` SELECT ProductName FROM Products ORDER BY COALESCE(position, (SELECT MAX(position) + 1 FROM Products)) ``` Alternatively, you can use: ``` SELECT * FROM ( SELECT ProductName FROM Products WHERE position IS NOT NULL ORDER BY position ) q UNION ALL SELECT ProductName FROM Products WHERE position IS NULL ``` This will be more efficient, since the first subquery will use the index on `position` for ordering is there is one.
Order by integer with blank fields at the bottom
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I'm trying to learn myself some C++ from scratch at the moment. I'm well-versed in python, perl, javascript but have only encountered C++ briefly, in a classroom setting in the past. Please excuse the naivete of my question. I would like to split a string using a regular expression but have not had much luck finding a clear, definitive, efficient and complete example of how to do this in C++. In perl this is action is common, and thus can be accomplished in a trivial manner, ``` /home/me$ cat test.txt this is aXstringYwith, some problems and anotherXY line with similar issues /home/me$ cat test.txt | perl -e' > while(<>){ > my @toks = split(/[\sXY,]+/); > print join(" ",@toks)."\n"; > }' this is a string with some problems and another line with similar issues ``` I'd like to know how best to accomplish the equivalent in C++. EDIT: I think I found what I was looking for in the boost library, as mentioned below. [boost regex-token-iterator](http://www.boost.org/doc/libs/1_36_0/libs/regex/doc/html/boost_regex/ref/regex_token_iterator.html) (why don't underscores work?) I guess I didn't know what to search for. ``` #include <iostream> #include <boost/regex.hpp> using namespace std; int main(int argc) { string s; do{ if(argc == 1) { cout << "Enter text to split (or \"quit\" to exit): "; getline(cin, s); if(s == "quit") break; } else s = "This is a string of tokens"; boost::regex re("\\s+"); boost::sregex_token_iterator i(s.begin(), s.end(), re, -1); boost::sregex_token_iterator j; unsigned count = 0; while(i != j) { cout << *i++ << endl; count++; } cout << "There were " << count << " tokens found." << endl; }while(argc == 1); return 0; } ```
The boost libraries are usually a good choice, in this case [Boost.Regex](http://www.boost.org/doc/libs/1_39_0/libs/regex/doc/html/index.html). There even is [an example](http://www.boost.org/doc/libs/1_39_0/libs/regex/doc/html/boost_regex/ref/regex_token_iterator.html#boost_regex.ref.regex_token_iterator.examples) for splitting a string into tokens that already does what you want. Basically it comes down to something like this: ``` boost::regex re("[\\sXY]+"); std::string s; while (std::getline(std::cin, s)) { boost::sregex_token_iterator i(s.begin(), s.end(), re, -1); boost::sregex_token_iterator j; while (i != j) { std::cout << *i++ << " "; } std::cout << std::endl; } ```
If you want to minimize use of iterators, and pithify your code, the following should work: ``` #include <string> #include <iostream> #include <boost/regex.hpp> int main() { const boost::regex re("[\\sXY,]+"); for (std::string s; std::getline(std::cin, s); ) { std::cout << regex_replace(s, re, " ") << std::endl; } } ```
C++ tokenize a string using a regular expression
[ "", "c++", "regex", "split", "tokenize", "" ]
There have been occasions where I would want to override a method in a class with an extension method. Is there any way to do that in C#? For example: ``` public static class StringExtension { public static int GetHashCode(this string inStr) { return MyHash(inStr); } } ``` A case where I've wanted to do this is to be able to store a hash of a string into a database and have that same value be used by all the classes that use the string class's hash (i.e. Dictionary, etc.) Since the built-in .NET hashing algorithm is not guaranteed to be compatible from one version of the framework to the next, I want to replace it with my own. There are other cases I've run into where I'd want to override a class method with an extension method as well so it's not just specific to the string class or the `GetHashCode` method. I know I could do this with subclassing off an existing class but it would be handy to be able to do it with an extension in a lot of cases.
No; an extension method never takes priority over an instance method with a suitable signature, and never participates in polymorphism (`GetHashCode` is a `virtual` method).
If the method has a different signature, then it can be done -- so in your case: no. But otherwise you need to use inheritance to do what you are looking for.
Is there any way in C# to override a class method with an extension method?
[ "", "c#", "extension-methods", "overriding", "" ]
In MSSQL you can convert a string into an integer like this: ``` CONVERT(INT, table.column) ``` Is there any C# expression that Linq to SQL would translate to this? In C# you can normally do the same by using `int.Parse()`, but unfortunately, trying to use `int.Parse()` in a Linq query results in an error: > Method 'Int32 Parse(System.String)' has no supported translation to SQL. Is there any C# expression that Linq to SQL would translate to `CONVERT(INT, ...)`?
C# has [`Convert.ToInt32()`](http://msdn.microsoft.com/en-us/library/sf1aw27b.aspx) which should do what you're looking for.
[Convert.ToInt32](http://msdn.microsoft.com/en-us/library/system.convert.toint32.aspx) should work. Check out [this article](http://msdn.microsoft.com/en-us/library/bb399342.aspx) for information on the translations.
C# Linq to SQL: How to express "CONVERT([...] AS INT)"?
[ "", "c#", "linq", "linq-to-sql", "" ]
I'm looking for an API or a combination of API's where I can send "Anjuna, India" and get back a list of places nearby. The data is mostly for "third world" countries, less so for Europe/US. Any suggestions/ideas about how to structure this?
You could make use of a couple of Yahoo's Geo APIs in the following manner. 1. Get woeid (Where On Earth Identifier) for input location(s) 2. Determine neighboring places A quick example, combining those APIs together with Yahoo's YQL would provide neighbor locations for "Anjuna, India" using the query: ``` SELECT * FROM geo.places.neighbors WHERE neighbor_woeid IN ( SELECT woeid FROM geo.places WHERE text="Anjuna, India" LIMIT 1 ) ``` [Try this in YQL Console](http://tinyurl.com/o7lnan) (must be logged in)
You would need place lists with coordinates. Then go trought that list and calculate distance between cities. Then sort results by least distance. I have not done any GPS programming tho.
An API to send a text string place, and get text strings back of places nearby
[ "", "php", "geolocation", "geotagging", "" ]
php noob here - I've cobbled together this script to display a list of images from a folder with opendir, but I can't work out how (or where) to sort the array alphabetically ``` <?php // opens images folder if ($handle = opendir('Images')) { while (false !== ($file = readdir($handle))) { // strips files extensions $crap = array(".jpg", ".jpeg", ".JPG", ".JPEG", ".png", ".PNG", ".gif", ".GIF", ".bmp", ".BMP", "_", "-"); $newstring = str_replace($crap, " ", $file ); //asort($file, SORT_NUMERIC); - doesnt work :( // hides folders, writes out ul of images and thumbnails from two folders if ($file != "." && $file != ".." && $file != "index.php" && $file != "Thumbnails") { echo "<li><a href=\"Images/$file\" class=\"thickbox\" rel=\"gallery\" title=\"$newstring\"><img src=\"Images/Thumbnails/$file\" alt=\"$newstring\" width=\"300\" </a></li>\n";} } closedir($handle); } ?> ``` Any advice or pointers would be much appreciated!
You need to read your files into an array first before you can sort them. How about this? ``` <?php $dirFiles = array(); // opens images folder if ($handle = opendir('Images')) { while (false !== ($file = readdir($handle))) { // strips files extensions $crap = array(".jpg", ".jpeg", ".JPG", ".JPEG", ".png", ".PNG", ".gif", ".GIF", ".bmp", ".BMP", "_", "-"); $newstring = str_replace($crap, " ", $file ); //asort($file, SORT_NUMERIC); - doesnt work :( // hides folders, writes out ul of images and thumbnails from two folders if ($file != "." && $file != ".." && $file != "index.php" && $file != "Thumbnails") { $dirFiles[] = $file; } } closedir($handle); } sort($dirFiles); foreach($dirFiles as $file) { echo "<li><a href=\"Images/$file\" class=\"thickbox\" rel=\"gallery\" title=\"$newstring\"><img src=\"Images/Thumbnails/$file\" alt=\"$newstring\" width=\"300\" </a></li>\n"; } ?> ``` Edit: This isn't related to what you're asking, but you could get a more generic handling of file extensions with the [pathinfo()](http://php.net/pathinfo) function too. You wouldn't need a hard-coded array of extensions then, you could remove any extension.
## Using [`opendir()`](http://php.net/opendir) `opendir()` does not allow the list to be sorted. You'll have to perform the sorting manually. For this, add all the filenames to an array first and sort them with [`sort()`](http://php.net/sort): ``` $path = "/path/to/file"; if ($handle = opendir($path)) { $files = array(); while ($files[] = readdir($dir)); sort($files); closedir($handle); } ``` And *then* list them using `foreach`: ``` $blacklist = array('.','..','somedir','somefile.php'); foreach ($files as $file) { if (!in_array($file, $blacklist)) { echo "<li>$file</a>\n <ul class=\"sub\">"; } } ``` ## Using [`scandir()`](http://php.net/scandir) This is a lot easier with `scandir()`. It performs the sorting for you by default. The same functionality can be achieved with the following code: ``` $path = "/path/to/file"; $blacklist = array('somedir','somefile.php'); // get everything except hidden files $files = preg_grep('/^([^.])/', scandir($path)); foreach ($files as $file) { if (!in_array($file, $blacklist)) { echo "<li>$file</a>\n <ul class=\"sub\">"; } } ``` ## Using [`DirectoryIterator`](http://www.php.net/manual/en/class.directoryiterator.php) (preferred) ``` $path = "/path/to/file"; $blacklist = array('somedir','somefile.php'); foreach (new DirectoryIterator($path) as $fileInfo) { if($fileInfo->isDot()) continue; $file = $path.$fileInfo->getFilename(); echo "<li>$file</a>\n <ul class=\"sub\">"; } ```
Sort and display directory list alphabetically using opendir() in php
[ "", "php", "sorting", "directory", "" ]
I would like to force a core dump at a specific location in my C++ application. I know I can do it by doing something like: ``` int * crash = NULL; *crash = 1; ``` But I would like to know if there is a cleaner way? I am using Linux by the way.
Raising of signal number 6 (`SIGABRT` in Linux) is one way to do it (though keep in mind that SIGABRT is not *required* to be 6 in all POSIX implementations so you may want to use the `SIGABRT` value itself if this is anything other than quick'n'dirty debug code). ``` #include <signal.h> : : : raise (SIGABRT); ``` Calling `abort()` will also cause a core dump, and you can even do this *without* terminating your process by calling `fork()` followed by `abort()` in the child only - see [this answer](https://stackoverflow.com/a/131539/60462) for details.
A few years ago, Google released the [coredumper](http://code.google.com/p/google-coredumper/) library. > # Overview > > The coredumper library can be compiled into applications to create core dumps of the running program -- without terminating. It supports both single- and multi-threaded core dumps, even if the kernel does not natively support multi-threaded core files. > > Coredumper is distributed under the terms of the BSD License. > > # Example > > This is by no means a complete example; it simply gives you a feel for what the coredumper API looks like. > > ``` > #include <google/coredumper.h> > ... > WriteCoreDump('core.myprogram'); > /* Keep going, we generated a core file, > * but we didn't crash. > */ > ``` It's not what you were asking for, but maybe it's even better :)
How to programmatically cause a core dump in C/C++
[ "", "c++", "c", "linux", "coredump", "abort", "" ]
I'm writing C++ console programs. After compilation, when I run the program from my file browser, cmd.exe automatically closes such that I can't see my programs output. The only way to work around this I've found is to run the program from inside cmd.exe Is there anyway to keep cmd.exe open after a program finishes running? Is there a setting I can change somewhere? I don't want to run a batch script with cmd.exe /K Thanks! [Edit] Don't know if this matters, but I'm on Vista x64
Have your application ask for a keypress before exiting - that's the easiest fix!
You can setup a shortcut with the /K switch when launching cmd.exe to have it not terminate after running a given command: ``` cmd.exe /K YourProgram.exe ```
Holding cmd.exe open on Vista
[ "", "c++", "cmd", "vista64", "" ]
I'm thinking of designing & implementing my own SQL-equivalent (DDL+DML) that is... 1. a pure relational algebraic language, and 2. has an elegant Lisp-/Scheme-like syntax Assuming an RDBMS such as MySQL, where exactly would I need to start my language design work? On top of the storage engine layer such as InnoDB? I don't know what all RDBMS functionality generally sits atop a Storage Engine? My current intuitive understanding is that the bulk of the work needed to create an RDBMS (such as MySQL) would already have been done within the storage engine (specifically, in InnoDB), and all you would need to do is create a wrapper language around it. But I also know that if that were really true, why would MySQL be existing in the first place!
I suspect that the best way to go around this would be to create a translator between your language and SQL, mainly because you won't be able to get more functionality from a rdbms than what's provided via its SQL dialect. MySQL existence has nothing to do with the difficulty of the work done by storage engines, [storage engines in MySQL](http://dev.mysql.com/tech-resources/articles/storage-engine/part_1.html) really do most of the grunt work, leaving MySQL to parse and optimize SQL and the retrieve the data from the engine, respecting the corresponding semantics of the engine. Most rdbms do not expose storage engines to users/administrators so in that respect MySQL is somewhat unique, which makes more reasonable to create a translator, that way you'll be able (by changing a few syntax rules) to use more than one rdbms via your app. Additionally, you probably won't be able to generate a pure relational language over existing database technology, check [The Third Manifesto](http://thethirdmanifesto.com/) for more information. All that said, I would really first look at all existing SQL wrappers, maybe [some will suit your taste](http://en.wikipedia.org/wiki/SQL#Alternatives_to_SQL).
It shouldn't take you long if you actually write it in lisp. I wrote a simple database engine in Lisp in about an afternoon. Here's an example of what it looks like: ``` (select movies (<= 1990 year 2000) (member director '(terry-gilliam tim-burton))) ``` Here, 'select' is a macro. It scans the predicates that follow it for symbols that are field names and binds them to the fields in the database. Then it writes a function that binds those fields to the values of a record passed to the function, and filters the table using that function. The macro expands to something like this: ``` (flet ((filter (item) (let ((year (movie-year item)) (director (movie-director item))) (and (<= 1990 year 2000) (member director '(terry-gilliam tim-burton)))))) (loop for item in movies if (filter item) collect item)) ``` The cool thing about doing it this way (actually in Lisp, rather than just using a Lisp-like syntax) is that you get compilation for free. On my system, the code above isn't interpreted by the database engine, it's actually a compiled part of the program (can't do that in C, now can you?). As a result it's fast, even though the database code itself (the code for 'select' and table definitions) is only a few lines long. The database is entirely memory resident, but it doesn't matter... you could just change the macro to accommodate external databases and even write it do use indices. It was good enough for the project I was working on, so I didn't add indices or anything fancy. My favorite part about it is that while it keeps all the conciseness of SQL, the code is no different than the code around it because it's all Lisp. You can introduce variables into your search term without having to worry about quoting them.
Designing SQL alternative?
[ "", "sql", "lisp", "scheme", "innodb", "dsl", "" ]
I have this situation where I am reading about 130K records containing dates stored as String fields. Some records contain blanks (nulls), some contain strings like this: 'dd-MMM-yy' and some contain this 'dd/MM/yyyy'. I have written a method like this: ``` public Date parsedate(String date){ if(date !== null){ try{ 1. create a SimpleDateFormat object using 'dd-MMM-yy' as the pattern 2. parse the date 3. return the parsed date }catch(ParseException e){ try{ 1. create a SimpleDateFormat object using 'dd/MM/yyy' as the pattern 2. parse the date 3. return parsed date }catch(ParseException e){ return null } } }else{ return null } } ``` So you may have already spotted the problem. **I am using the try .. catch as part of my logic**. It would be better is I can determine before hand that the String actually contains a parseable date in some format then attempt to parse it. So, is there some API or library that can help with this? I do not mind writing several different Parse classes to handle the different formats and then creating a factory to select the correct6 one, but, how do I determine which one? Thanks.
See [Lazy Error Handling in Java](http://apocalisp.wordpress.com/2008/06/04/throwing-away-throws/) for an overview of how to eliminate try/catch blocks using an `Option` type. [Functional Java](http://code.google.com/p/functionaljava) is your friend. In essence, what you want to do is to wrap the date parsing in a function that doesn't throw anything, but indicates in its return type whether parsing was successful or not. For example: ``` import fj.F; import fj.F2; import fj.data.Option; import java.text.SimpleDateFormat; import java.text.ParseException; import static fj.Function.curry; import static fj.Option.some; import static fj.Option.none; ... F<String, F<String, Option<Date>>> parseDate = curry(new F2<String, String, Option<Date>>() { public Option<Date> f(String pattern, String s) { try { return some(new SimpleDateFormat(pattern).parse(s)); } catch (ParseException e) { return none(); } } }); ``` OK, now you've a reusable date parser that doesn't throw anything, but indicates failure by returning a value of type `Option.None`. Here's how you use it: ``` import fj.data.List; import static fj.data.Stream.stream; import static fj.data.Option.isSome_; .... public Option<Date> parseWithPatterns(String s, Stream<String> patterns) { return stream(s).apply(patterns.map(parseDate)).find(isSome_()); } ``` That will give you the date parsed with the first pattern that matches, or a value of type Option.None, which is type-safe whereas null isn't. If you're wondering what `Stream` is... [it's a lazy list](http://functionaljava.googlecode.com/svn/artifacts/2.19/javadoc/fj/data/Stream.html). This ensures that you ignore patterns after the first successful one. No need to do too much work. Call your function like this: ``` for (Date d: parseWithPatterns(someString, stream("dd/MM/yyyy", "dd-MM-yyyy")) { // Do something with the date here. } ``` Or... ``` Option<Date> d = parseWithPatterns(someString, stream("dd/MM/yyyy", "dd-MM-yyyy")); if (d.isNone()) { // Handle the case where neither pattern matches. } else { // Do something with d.some() } ```
Don't be too hard on yourself about using try-catch in logic: this is one of those situations where Java forces you to so there's not a lot you can do about it. But in this case you could instead use [`DateFormat.parse(String, ParsePosition)`](http://java.sun.com/javase/6/docs/api/java/text/DateFormat.html#parse(java.lang.String,%20java.text.ParsePosition)).
Determine if a String is a valid date before parsing
[ "", "java", "date", "parsing", "" ]
Is there any way of creating a function that accepts any version of a given template class? e.g. this works: ``` ostream& operator << (ostream &out,const Vector<int>& vec); ``` but this doesn't: ``` ostream& operator << (ostream &out,const Vector& vec); ``` Is it possible to get the second line to work somehow for any version of vector? e.g. `vector<int>` and `vector<double>` without having to write 2 separate functions? Added to question: I've made op<< a template function like you've suggested. In order to make it a friend function of the vector class I tried adding the following to the Vector class definition, but it didn't work: ``` friend ostream& operator << (ostream &out, const Vector<T>& vec); ``` any ideas what can be done to fix it?
As already pointed out something like this should work: ``` template <typename T> ostream& operator << (ostream &out,const Vector<T>& vec) { // body here } ``` As for the friend requirement, that is most easily handled like this: ``` template <typename T> ostream& operator << (ostream &out,const Vector<T>& vec) { vec.print_on( out ); return out; } ``` **However**, normally I would think of any output operator like this that requires access to the internals of the class to be showing you a mistake in your `Vector` class. It really only ought to need to use the public interface to do the display. The other thing is that you might also want to template the output stream itself so that you can preserve its type: ``` template <typename O, typename C, typename T> std::basic_ostream<O, C>& operator << (std::basic_ostream<O, C> &out,const Vector<T>& vec) { vec.print_on( out ); return out; } ``` The `Vector`'s `print_on` can still use `ostream`.
Sure, make it a template function: ``` template <typename T> ostream& operator << (ostream &out,const Vector<T>& vec); ```
using a template class as an argument
[ "", "c++", "templates", "" ]
I have the following template String: `"Hello [Name] Please find attached [Invoice Number] which is due on [Due Date]"`. I also have String variables for name, invoice number and due date - what's the best way to replace the tokens in the template with the variables? (Note that if a variable happens to contain a token it should NOT be replaced). --- **EDIT** With thanks to @laginimaineb and @alan-moore, **here's my solution:** ``` public static String replaceTokens(String text, Map<String, String> replacements) { Pattern pattern = Pattern.compile("\\[(.+?)\\]"); Matcher matcher = pattern.matcher(text); StringBuffer buffer = new StringBuffer(); while (matcher.find()) { String replacement = replacements.get(matcher.group(1)); if (replacement != null) { // matcher.appendReplacement(buffer, replacement); // see comment matcher.appendReplacement(buffer, ""); buffer.append(replacement); } } matcher.appendTail(buffer); return buffer.toString(); } ```
The most efficient way would be using a matcher to continually find the expressions and replace them, then append the text to a string builder: ``` Pattern pattern = Pattern.compile("\\[(.+?)\\]"); Matcher matcher = pattern.matcher(text); HashMap<String,String> replacements = new HashMap<String,String>(); //populate the replacements map ... StringBuilder builder = new StringBuilder(); int i = 0; while (matcher.find()) { String replacement = replacements.get(matcher.group(1)); builder.append(text.substring(i, matcher.start())); if (replacement == null) builder.append(matcher.group(0)); else builder.append(replacement); i = matcher.end(); } builder.append(text.substring(i, text.length())); return builder.toString(); ```
I really don't think you need to use a templating engine or anything like that for this. You can use the [`String.format`](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#format(java.lang.String,%20java.lang.Object...)) method, like so: ``` String template = "Hello %s Please find attached %s which is due on %s"; String message = String.format(template, name, invoiceNumber, dueDate); ```
How to replace a set of tokens in a Java String?
[ "", "java", "regex", "templates", "" ]
So I'm looking for ideas on how to best replicate the functionality seen on digg. Essentially, you submit a URL of your page of interest, digg then crawl's the DOM to find all of the IMG tags (likely only selecting a few that are above a certain height/width) and then creates a thumbnail from them and asks you which you would like to represent your submission. While there's a lot going on there, I'm mainly interested in the best method to retrieve the images from the submitted page.
While you could try to parse the web page HTML can be such a mess that you would be best with something close but imperfect. 1. Extract everything that looks like an image tag reference. 2. Try to fetch the URL 3. Check if you got an image back Just looking for and capturing the content of src="..." would get you there. Some basic manipulation to deal with relative vs. absolute image references and you're there. Obviously anytime you fetch a web asset on demand from a third party you need to take care you aren't being abused.
I suggest cURL + regexp.
Replicate Digg's Image-Suggestions from Submitted URL with PHP
[ "", "php", "image-manipulation", "web-crawler", "digg", "" ]
I need to allow client users to extend the data contained by a JPA entity at runtime. In other words I need to add a *virtual column* to the entity table at runtime. This *virtual column* will only be applicable to certain *data rows* and there could possibly be quite a few of these *virtual columns*. As such I don't want to create an actual additional column in the database, but rather I want to make use of additional entities that represent these *virtual columns*. As an example, consider the following situation. I have a *Company* entity which has a field labelled *Owner*, which contains a reference to the *Owner* of the *Company*. At runtime a client user decides that all *Companies* that belong to a specific *Owner* should have the extra field labelled *ContactDetails*. My preliminary design uses two additional entities to accomplish this. The first basically represents the *virtual column* and contains information such as the field name and type of value expected. The other represents the actual data and connects an entity row to a *virtual column*. For example, the first entity might contain the data "ContactDetails" while the second entity contains say "555-5555." Is this the right way to go about doing this? Is there a better alternative? Also, what would be the easiest way to *automatically* load this data when the original entity is loaded? I want my DAO call to return the entity together with its *extensions*. EDIT: I changed the example from a field labelled *Type* which could be a *Partner* or a *Customer* to the present version as it was confusing.
Perhaps a simpler alternative could be to add a CLOB column to each Company and store the extensions as an XML. There is a different set of tradeoffs here compared to your solution but as long as the extra data doesn't need to be SQL accessible (no indexes, fkeys and so on) it will probably be simple than what you do now. It also means that if you have some fancy logic regarding the extra data you would need to implement it differently. For example if you need a list of all possible extension types you would have to maintain it separately. Or if you need searching capabilities (find customer by phone number) you will require lucene or similar solution. I can elaborate more if you are interested. EDIT: To enable searching you would want something like [lucene](http://lucene.apache.org/java/docs/) which is a great engine for doing free text search on arbitrary data. There is also [hibernate-search](https://www.hibernate.org/410.html) which integrates lucene directly with hibernate using annotations and such - I haven't used it but I heard good things about it. For fetching/writing/accessing data you are basically dealing with XML so any XML technique should apply. The best approach really depends on the actual content and how it is going to be used. I would suggest looking into [XPath](http://www.w3schools.com/XPath/default.asp) for data access, and maybe look into defining your own hibernate [usertype](http://www.jroller.com/eyallupu/entry/hibernate_compositeusertype_and_annotations) so that all the access is encapsulated into a class and not just plain String.
I've run into more problems than I hoped I would and as such I decided to dumb down the requirements for my first iteration. I'm currently trying to allow such *Extensions* only on the entire *Company* entity, in other words, I'm dropping the whole *Owner* requirement. So the problem could be rephrased as "How can I add *virtual columns* (entries in another entity that act like an additional column) to an entity at runtime?" My current implementation is as follow (irrelevant parts filtered out): ``` @Entity class Company { // The set of Extension definitions, for example "Location" @Transient public Set<Extension> getExtensions { .. } // The actual entry, for example "Atlanta" @OneToMany(fetch = FetchType.EAGER) @JoinColumn(name = "companyId") public Set<ExtensionEntry> getExtensionEntries { .. } } @Entity class Extension { public String getLabel() { .. } public ValueType getValueType() { .. } // String, Boolean, Date, etc. } @Entity class ExtensionEntry { @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "extensionId") public Extension getExtension() { .. } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "companyId", insertable = false, updatable = false) public Company getCompany() { .. } public String getValueAsString() { .. } } ``` The implementation as is allows me to load a *Company* entity and Hibernate will ensure that all its *ExtensionEntries* are also loaded and that I can access the *Extensions* corresponding to those *ExtensionEntries*. In other words, if I wanted to, for example, display this additional information on a web page, I could access all of the required information as follow: ``` Company company = findCompany(); for (ExtensionEntry extensionEntry : company.getExtensionEntries()) { String label = extensionEntry.getExtension().getLabel(); String value = extensionEntry.getValueAsString(); } ``` There are a number of problems with this, however. Firstly, when using FetchType.EAGER with an @OneToMany, Hibernate uses an outer join and as such will return duplicate Companies (one for each ExtensionEntry). This can be solved by using Criteria.DISTINCT\_ROOT\_ENTITY, but that in turn will cause errors in my pagination and as such is an unacceptable answer. The alternative is to change the FetchType to LAZY, but that means that I will always "manually" have to load *ExtensionEntries*. As far as I understand, if, for example, I loaded a List of 100 *Companies*, I'd have to loop over and query each of those, generating a 100 SQL statements which isn't acceptable performance-wise. The other problem which I have is that ideally I'd like to load all the *Extensions* whenever a *Company* is loaded. With that I mean that I'd like that @Transient getter named getExtensions() to return all the *Extensions* for any *Company*. The problem here is that there is no foreign key relation between *Company* and *Extension*, as *Extension* isn't applicable to any single *Company* instance, but rather to all of them. Currently I can get past that with code like I present below, but this will not work when accessing referenced entities (if for example I have an entity *Employee* which has a reference to *Company*, the *Company* which I retrieve through employee.getCompany() won't have the *Extensions* loaded): ``` List<Company> companies = findAllCompanies(); List<Extension> extensions = findAllExtensions(); for (Company company : companies) { // Extensions are the same for all Companies, but I need them client side company.setExtensions(extensions); } ``` So that's were I'm at currently, and I have no idea how to proceed in order to get past these problems. I'm thinking that my entire design might be flawed, but I'm unsure of how else to try and approach it. Any and all ideas and suggestions are welcome!
Extending JPA entity data at runtime
[ "", "java", "hibernate", "jpa", "runtime", "" ]
I did recently attach the 3rd version of Dijkstra algorithm for shortest path of single source into my project. I realize that there are many different implementations which vary strongly in performance and also do vary in the quality of result in large graphs. With my data set (> 100.000 vertices) the runtime varies from 20 minutes to a few seconds. Th shortest paths also vary by 1-2%. Which is the best implementation you know? **EDIT:** My Data is a hydraulic network, with 1 to 5 vertices per node. Its comparable to a street map. I made some modifications to a already accelerated algorithm (using a sorted list for all remaining nodes) and now find to the same results in a fraction of time. I have searched for such a thing quite a while. I wonder if such a implementation already exists. I can not explain the slight differences in results. I know that Dijkstra is not heuristic, but all the implementations seem to be correct. The faster solutions have the results with shorter paths. I use double precision math exclusively. **EDIT 2:** I found out that the differences in the found path are indeed my fault. I had inserted special handling for some vertices (only valid in one direction) and forgot about that in the other implementation. **BUT** im still more than surprised that Dijkstra can be accelerated dramatically by the following change: In general a Dijkstra algorithm contains a loop like: ``` MyListType toDoList; // List sorted by smallest distance InsertAllNodes(toDoList); while(! toDoList.empty()) { MyNodeType *node = *toDoList.first(); toDoList.erase(toDoList.first()); ... } ``` If you change this a little bit, it works the same, but performs better: ``` MyListType toDoList; // List sorted by smallest distance toDoList.insert(startNode); while(! toDoList.empty()) { MyNodeType *node = *toDoList.first(); toDoList.erase(toDoList.first()); for(MyNeigborType *x = node.Neigbors; x != NULL; x++) { ... toDoList.insert(x->Node); } } ``` It seems, that this modification reduces the runtime by a order not of magnitude, but a order of exponent. It reduced my runtime form 30 Seconds to less than 2. I can not find this modification in any literature. It's also very clear that the reason lies in the sorted list. insert/erase performs much worse with 100.000 elements that with a hand full of. **ANSWER:** After a lot of googling i found it myself. The answer is clearly: **[boost graph lib](http://www.boost.org/doc/libs/1_39_0/libs/graph/doc/dijkstra_shortest_paths.html)**. Amazing - i had not found this for quite a while. If you think, that there is no performance variation between Dijkstra implementations, see [wikipedia](http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Running_time).
The best implementations known for road networks (>1 million nodes) have query times expressed in **micro**seconds. See for more details the 9th DIMACS Implementation Challenge(2006). Note that these are not simply Dijkstra, of course, as the whole point was to get results faster.
May be I am not answering your question. My point is why to use Dijkstra when there are pretty much more efficient algorithms for your problem. If your graph fullfills the triangular property (it is an euclidian graph) |ab| +|bc| > |ac| (the distance from node a to node b plus distance from node b to node c is bigger than the distance from node a to node c) then you can apply the A\* algorithm. This algorithm is pretty efficient. Otherwise consider using heuristics. The implementation is not the major issue. The algorithm to be used does matter.
What is the fastest Dijkstra implementation you know (in C++)?
[ "", "c++", "performance", "algorithm", "" ]
With LINQ I get four elements out of some XML, each element can have a different name (Book, Magazine, Article). How do I get the name of the element I'm currently processing, e.g. something like **ElementType()** below: ``` using System; using System.Linq; using System.Xml.Linq; namespace TestXmlElement2834 { class Program { static void Main(string[] args) { XElement content = new XElement("content", new XElement("book", new XAttribute("id", "1")), new XElement("article", new XAttribute("id", "2")), new XElement("book", new XAttribute("id", "3")), new XElement("magazine", new XAttribute("id", "4")) ); var contentItems = from contentItem in content.Descendants() select new ContentItem { Id = contentItem.Attribute("id").Value Type = contentItem.ElementType() //PSEUDO-CODE }; foreach (var contentItem in contentItems) { Console.WriteLine(contentItem.Id); } Console.ReadLine(); } } class ContentItem { public string Id { get; set; } public string Type { get; set; } } } ```
Is [`XElement.Name`](http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.name.aspx) what you're after? (Use the [`XName.LocalName`](http://msdn.microsoft.com/en-us/library/system.xml.linq.xname.localname.aspx) property to then get the local part of the element name.) If you could say what you want the output to be, that would help :) (I originally thought you meant the [type of node](http://msdn.microsoft.com/en-us/library/system.xml.linq.xobject.nodetype.aspx) (attribute, element etc), but it'll always be `XElement` in your case...)
You want [XElement.Name](http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.name.aspx).
How can I get the type of element being processed by LINQ-to-XML?
[ "", "c#", "xml", "linq", "" ]
I am having this weired issue that CSV attachment sent via email using .NET SmtpClient appeared at the bottom of the email rather than attachment in Lotus Note. I just don’t know how to figure it out and I have no access to client computer makes debugging very hard. What are the possible steps I can take and possible gotchas I need to be aware of? Code is as below: ``` var smtpClient = new SmtpClient { Host = ConfigurationManager.AppSettings["smtpServer"], Port = Convert.ToInt32(ConfigurationManager.AppSettings["smtpPort"]) }; var mailMessage = new MailMessage(); mailMessage.Attachments.Add(new Attachment(attachment, contentType)); //ContentType = "text/csv"; //attachment is the temp file disk path ``` Thanks.
This is a bit of a reach, but you may want to set the content-disposition of the attachment. ``` var mailMessage = new MailMessage(); Attachment data = new Attachment(attachment, contentType); ContentDisposition disposition = data.ContentDisposition; disposition.FileName = "message.csv"; mailMessage.Attachments.Add(data); ``` Adapted from: <http://msdn.microsoft.com/en-us/library/system.net.mail.attachment.contentdisposition.aspx>
Try not setting the content type and just setting the extension. Windows should be able to handle that if it has an extension and it may force it to handle it as an attachment instead of attempting to display it inline. Make sure that your file that you are attaching has an extension.
c# generated csv file sent via email embedded to bottom of email in lotus note
[ "", "c#", ".net", "email", "csv", "lotus-notes", "" ]
I am wondering what is the best way to use properties when dealing with collections. For example I have a class Foo and I want to have a list of that class stored. Which of the following should be used: ``` private List<Foo> myList; private List<Foo> myOtherList = new List<Foo>(); ``` now for the property: ``` public List<Foo> ListOfFoo { get { return myList; } set { myList= new List<Foo>(value); } } ``` Or should the set just be to the value? ``` public List<Foo> ListOfFoo { get { return myList; } set { myList= value; } } ```
Choose ``` private List<Foo> myOtherList = new List<Foo>(); ``` becuse the other just declares a reference (which is set to null), the sample above declares a reference to a list, creates a list and assignes that new list to the reference. Choose ``` public List<Foo> ListOfFoo { get { return myList; } set { myList= new List<Foo>(value); } } ``` When you want myList to NOT refelect any changes that happen to the list after it is assigned to myList e.g. ``` List<string> myFirstList = new List<string>(); myFirstList.Add("Hello"); myFirstList.Add("World"); List<string> mySecondList = new List<string>(myFirstList); // mySecondList now contains Hello & world myFirstList.Add("Boyo"); // myFrist List now contains Hello, world & Boyo // mySecondList still contains Hello & world ``` Choose ``` public List<Foo> ListOfFoo { get { return myList; } set { myList= value; } } ``` When you want both references to point to the same object e.g. ``` List<string> myFirstList = new List<string>(); myFirstList.Add("Hello"); myFirstList.Add("World"); List<string> mySecondList = myFirstList; // mySecondList now contains Hello & world myFirstList.Add("Boyo"); // myFrist List now contains Hello, world & Boyo // mySecondList "also" contains Hello, world & Boyo ``` The "also" above is in quotes, because actually, there is only one list, and both my first and my second point to the same list.
Generally you don't want to use properties of a rich type like `List<T>` (normally one would use `Collection<T>`), and generally properties of a collection type are read-only - the collection itself can be modified with methods like `Clear`, `Add` etc., and this is normally sufficient. For example: ``` class Foo { Collection<Bar> _bars = new Collection<Bar>(); public Collection<Bar> Bars { get { return _bars; } } } ``` This also leaves you open to validate modifications to the collection by implementing a descendant of `Collection<T>` and overriding the `InsertItem`, `SetItem` etc. methods.
Correct usage of properties when dealing with a collection
[ "", "c#", "collections", "properties", "" ]
Im creating a simple web service in a console app. (PersonService) this is my Program.cs below im trying to add a service reference to a different console app (PersonClient) how can i do this? i tried adding it by right clicking, add service reference, pointing to the refernce etc... but it wont work. ``` [DataContract] public class Person { [DataMember] public string FirstName { get; set; } [DataMember] public string LastName { get; set; } } [ServiceContract] public interface IPersonLookup { [OperationContract] Person GetPerson(int identifier); } public class PersonService : IPersonLookup { public PersonService() { } public Person GetPerson(int identifier) { Person p = new Person(); p.FirstName="Jane"; p.LastName="Doe"; return p; } } class Program { static void Main(string[] args) { using (ServiceHost host = new ServiceHost(typeof(PersonService))) { WSHttpBinding binding = new WSHttpBinding(); host.AddServiceEndpoint(typeof(IPersonLookup), binding, "http://localhost:9090/PersonService"); host.Open(); Console.WriteLine("Listening...."); Console.ReadLine(); } } } ```
**Solution:** 1. Create a console application using visual studio. 2. Right click on the project and click on "Add Service Reference...". 3. On the window, you will find the "Advanced" button at the bottom. 4. Click on the button and it will open service reference settings window. It has a button at bottom called "Add Web Reference".
You need to read about WCF MEX Endpoints. Here's a [blog post that may help](http://bloggingabout.net/blogs/dennis/archive/2006/11/09/WCF-Part-4-_3A00_-Make-your-service-visible-through-metadata.aspx).
add a web service reference to a console app
[ "", "c#", "visual-studio", "wcf", "web-services", "console", "" ]
I just notice if i pass a value such as 1 in a function parameter it will work if it excepts int, long and i assume the others. However if i do int i = value, it doesnt. I was wondering, what type is it?
``` (1).GetType().ToString() //is System.Int32 ```
You can suffix literal integers to make the type explicit, otherwise the value will be implicitly interpreted as though it were the target type (assuming it doesn't overflow the target). ``` var myLong = 123L; var myInt = 123; var myByte = (byte)123; // i'm not aware of a suffix for this one // unsigned variants var myULong = 123UL; var myUInt = 123U; ```
In C# what type are integer literals?
[ "", "c#", "integer", "" ]
I was wondering if anybody knew how to do a mail merge using an Excel file as a datasource, to fill in fields on a Word template? I wish to use the interop for Word if i could...but am having a few difficulties finding code for this. Does anybody have any syntax for this? Thank you in advance.
A very useful method for learning how to automate specific actions in MS Word is to actually perform the action manually with 'Record Macro' enabled. Once you have the VBA macro its easy enough to convert this to VB.NET or C# that uses interop. I tend to tweak the VBA first manually in Word so I can then test this first before converting to a .NET language using the interop layer. I don't know much about mailmerge, but this is some of the VBA generated whilst I recorded a macro: ``` ActiveDocument.MailMerge.MainDocumentType = wdFormLetters ActiveDocument.MailMerge.OpenDataSource Name:= _ "c:\Arrays.xlsx", ConfirmConversions:=False, _ ReadOnly:=False, LinkToSource:=True, AddToRecentFiles:=False, _ PasswordDocument:="", PasswordTemplate:="", WritePasswordDocument:="", _ WritePasswordTemplate:="", Revert:=False, Format:=wdOpenFormatAuto, _ Connection:= _ "Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=c:\Arrays.xlsx;Mode=Read;Extended Properties=""HDR=YES;IMEX=1;"";Jet OLEDB:System database="""";Jet OLEDB:Registry Path="""";Jet OLEDB:Engine Type=37;Jet OLEDB:Database Loc" _ , SQLStatement:="SELECT * FROM `Sheet1$`", SQLStatement1:="", SubType:= _ wdMergeSubTypeAccess ``` I haven't included the full code here, but hopefully this give you some ideas.
Word (at least in the 2007 version, which is what I'm looking at) can do this out of the box. Just select the Excel file as the datasource. What are you trying to do in your code?
Mail Merge (Excel to Word) using C#
[ "", "c#", "email", "interop", "ms-word", "mailmerge", "" ]
I was listening to the podcast about PowerShell 2.0 [that Scott Hanselman did](http://www.hanselminutes.com/default.aspx?showID=180). In that episode, they talked about the possibilities to extend your application to expose functionality for PowerShell. Now this sounds interesting. Have any of you done such extensions that exposes functionality in your application? If so, what kind of functionallity? EDIT: To be more precise: I am not interested in hosting PowerShell in my application. I'm more interested in opening up my application with an API-like interface. So a PowerShell Provider seems to be the technology I'm looking for more insight in.
There are multiple ways to leverage PowerShell in a custom application. The beauty of the PowerShell Automation engine is that you don't have to deal with handling parameters, formatting output, and bunch of other PITA things that you would have to handle yourself. To throw an object down the pipeline in PowerShell, you override the ProcessRecord Method and call WriteObject ``` protected override void ProcessRecord() { // Get the current processes Process[] processes = Process.GetProcesses(); // Write the processes to the pipeline making them available // to the next cmdlet. The second parameter of this call tells // PowerShell to enumerate the array, and send one process at a // time to the pipeline. WriteObject(processes, true); } ``` You can write Cmdlets that allow an admin to automate the server side of an application. Cmdlets are always task based units of functionality with verb-noun naming convention. For example, Get-Process, or Restart-Service. Cmdlets do one thing and do it very well. There is all kinds of incredible power that comes with combining cmdlets together. Also, if your app has some sort of data store, its also possible to write a provider which would allow someone to browse and/or manage the data store using cmds like cd (set-location) and md (new-item). A provider is what the PS team wrote so you can cd into the registry with cd hklm: or the certificate store with cd cert: You can also host PowerShell itself in your application. There is some good information on all three of these options on MSDN [here](http://msdn.microsoft.com/en-us/library/ms714469(VS.85).aspx) Considering the interest in providers, here are some examples on [how to create a PowerShell Provider.](http://msdn.microsoft.com/en-us/library/ms714636(VS.85).aspx) There has been a few discussions about design and using a set of cmdlets or to expose something with a Provider. When you implement a provider, you also get a few cmdlets, such as Get-item, New-item, Get-Location, Set-Location. However, I have found that having some cmdlets for specific tasks in addition to a provider can be very helpful.
Here's a good book on this side of powershell (which doesn't get much coverage in most books). [Professional Poweshell Programming](https://rads.stackoverflow.com/amzn/click/com/0470173939) Using this book (and some trips to msdn), I was able to have a custom powershell host up and runnning in a day. A few days later, I had custom cmdlets that interact with the gui (to build treeviews, grids, diagrams, menus, etc.)
How to expose functionality to PowerShell from within your application
[ "", "c#", "powershell", "" ]
I would like to wrap form elements with labels as such ``` <label for="email">E-mail <input type="text" name="email" id="email" /></label> ``` The only option I could find is to alter the placement; however it only accepts 'prepend' and 'append': ``` <!-- prepend --> <label for="email">E-mail</label> <input type="text" name="email" id="email" /> <!-- append --> <input type="text" name="email" id="email" /> <label for="email">E-mail</label> ``` That is not what I am after. I could alter the Zend\_Form\_Decorator\_Label class, but that is the last alternative.
This doesn't seem to be possible unfortunately, you'll probably have to write a custom decorator. It should be pretty simple, though. Please note im just going to write this here, it's untested but based off another decorator so it should work with little/no modification ``` class Your_Form_Decorator_Date extends Zend_Form_Decorator_Abstract { public function render($content) { $element = $this->getElement(); $name = $element->getFullyQualifiedName(); return '<label for="'.$name.'">'. $element->getLabel() . ' '.$content.'</label>'; } } ``` Now if you add the correct prefix to your form. ``` $this->addPrefixPath('Your_Form', 'Your/Form/'); ``` You should be able to use this to wrap your input (FormElement decorator) in a label tag. Sorry I haven't had a chance to actually test this but given how my other decorators work. It should be fine. EDIT: Thanks for pointing out that the label text wasn't being rendered gnarf. This is now fixed.
I guess you shouldn't use that ;) It's because label's contents arethe description of the field. It's nonsense to include the element into description. If you need, you can wrap both into a div or something like that. Only reason for this are badly written CSSs :)
In Zend Framework how do you wrap form elements in a label using decorators?
[ "", "php", "zend-framework", "forms", "decorator", "" ]
It appears to from my simple testing but I'm wondering if this is guaranteed? Are there conditions where the ordering will be not be guaranteed? **Edit**: The case I'm particularly interested in is if I populate a map with a large number of entries, will the order of the itertator be the same across multiple runs of my executable? What if the entries are inserted in a different order?
Yes, it maintains an internal order, so iteration over a set that isn't changing should always be the same. From [here](http://www.cplusplus.com/reference/stl/map/): > Internally, the elements in the map > are sorted from lower to higher key > value following a specific strict weak > ordering criterion set on > construction.
`std::map` is a *sorted* container, so, yes, order is guaranteed (the same as the ordering you use implicitly or explicitly in its constructor). Do **not** count on this for the popular (though not-yet-stanard) `hashmap` though -- it has very many advantages in many cases wrt `std::map`, but **not** a predictable order of iteration!
Does an STL map always give the same ordering when iterating from begin() to end()?
[ "", "c++", "stl", "dictionary", "iterator", "" ]
I have a table which maps String->Integer. Rather than create an enum statically, I want to populate the enum with values from a database. Is this possible ? So, rather than delcaring this statically: ``` public enum Size { SMALL(0), MEDIUM(1), LARGE(2), SUPERSIZE(3) }; ``` I want to create this enum dynamically since the numbers {0,1,2,3} are basically random (because they are autogenerated by the database's AUTOINCREMENT column).
No. Enums are always fixed at compile-time. The only way you could do this would be to dyamically generate the relevant bytecode. Having said that, you should probably work out which aspects of an enum you're actually interested in. Presumably you weren't wanting to use a `switch` statement over them, as that would mean static code and you don't know the values statically... likewise any other references in the code. If you really just want a map from `String` to `Integer`, you can just use a `Map<String, Integer>` which you populate at execution time, and you're done. If you want the `EnumSet` features, they would be somewhat trickier to reproduce with the same efficiency, but it may be feasible with some effort. So, before going any further in terms of thinking about implementation, I suggest you work out what your real requirements are. (EDIT: I've been assuming that this enum is fully dynamic, i.e. that you don't know the names or even how many values there are. If the set of names is fixed and you *only* need to fetch the ID from the database, that's a very different matter - see [Andreas' answer](https://stackoverflow.com/questions/851466/populate-an-enum-with-values-from-database/851506#851506).)
This is a bit tricky, since the population of those values happens at class-load time. So you will need a static access to a database connection. As much as I value his answers, I think Jon Skeet may be wrong this time. Take a look at this: ``` public enum DbEnum { FIRST(getFromDb("FIRST")), SECOND(getFromDb("second")); private static int getFromDb(String s) { PreparedStatement statement = null; ResultSet rs = null; try { Connection c = ConnectionFactory.getInstance().getConnection(); statement = c.prepareStatement("select id from Test where name=?"); statement.setString(1, s); rs = statement.executeQuery(); return rs.getInt(1); } catch (SQLException e) { throw new RuntimeException("error loading enum value for "+s,e); } finally { try { rs.close(); statement.close(); } catch (SQLException e) { //ignore } } throw new IllegalStateException("have no database"); } final int value; DbEnum(int value) { this.value = value; } } ```
Populate an enum with values from database
[ "", "hashmap", "enumeration", "java", "" ]
Do I need to pass back any HTTP headers to tell the browser that my server won't be immediately closing the connection and to display as the HTML is received? Is there anything necessary to get the HTML to incrementally display like flush()? This technique used to be used for things like chat, but I'm thinking about using it for a COMET type application.
[Long polling](http://en.wikipedia.org/wiki/Push_technology#Long_polling) is a common technique to do something like this; to briefly summarise, it works as follows: 1. The client sends an XHR to the server. * If there is data ready, the server returns this immediately. * If not, the server keeps the connection open until data does become available, then it returns this. * If the request times-out, go back to 1). 2. The page running on the client receives this data, and does what it does with it. 3. Go back to 1) This is how Facebook [implements its chat feature](http://www.hfadeel.com/Blog/?p=128). [This article](http://cometdaily.com/2007/11/16/more-on-long-polling/) also clears up some of the misconceptions of long-polling, and details some of the benefits of doing so.
The client will close the connection when it does not receive any data for a certain time. This timeout cannot be influenced by HTTP headers. It is client-specific and usually set to 120 seconds IIRC. So all you have to do is send small amounts of data regularly to avoid hitting the timeout.
How to display HTML to the browser incrementally over a long period of time?
[ "", "php", "xmlhttprequest", "comet", "" ]
I want to secure events stored in one table, which has relations to others. Events are inserted through windows service, that is connecting to hardware and reading from the hardware. In events table is PK, date and time, and 3 different values. The problem is that every admin can log in and insert/update/delete data in this table e.g. using sql management studio. I create triggers to prevent update and delete, so if admin doesn't know triggers, he fail to change data, but if he knows trigger, he can easily disable trigger and do whatever he wants. So after long thinking I have one idea, to add new column (field) to table and store something like checksum in this field, this checksum will be calculated based on other values. This checksum will be generated in insert/update statements. If someone insert/update something manually I will know it, because if I check data with checksum, there will be mismatches. My question is, if you have similar problem, how do you solve it? What algorithm use for checksum? How to secure against delete statement (I know about empty numbers in PK, but it is not enough) ? I'm using SQL Server 2005.
Anything you do at the server level the admin can undo. That's the very definition of its role and there's nothing you can do to prevent it. In SQL 2008 you can request auditing of the said SQL server with X events, see <http://msdn.microsoft.com/en-us/library/cc280386.aspx>. This is CC compliant solution that is tamper evident. That means the admin can stop the audit and do its mischievous actions, but the stopping of the audit is recorded. In SQL 2005 the auditing solution recommended is using the [profiler infrastructure](http://msdn.microsoft.com/en-us/library/ms187346.aspx). This can be made tamper evident when correctly deployed. You would prevent data changes with triggers and constraints and audit DDL changes. If the admin changes the triggers, this is visible in the audit. If the admin stops the audit, this is also visible in the audit. Do you plan this as a one time action against a rogue admin or as a feature to be added to your product? Using digital signatures to sign all your application data can be very costly in app cycles. You also have to design a secure scheme to show that records were not deleted, including last records (ie. not a simple gap in an identity column). Eg. you could compute [CHECSUM\_AGG](http://msdn.microsoft.com/en-us/library/ms188920.aspx) over [BINARY\_CHECKSUM(\*)](http://msdn.microsoft.com/en-us/library/ms173784.aspx), sign the result in the app and store the signed value for each table after each update. Needles to say, this will slow down your application as basically you serialize every operation. For individual rows cheksums/hashes you would have to compute the entire signature in your app, and that would require possibly values your app does not yet have (ie. the identity column value *to be* assigned to your insert). And how far do you want to go? A simple hash can be broken if the admin gets hold of your app and monitors what you hash, in what order (this is trivial to achieve). He then can recompute the same hash. An HMAC requires you to store a secret in the application which is basically impossible against a a determined hacker. These concerns may seem overkill, but if this is an application you sell for instance then all it takes is for *one* hacker to break your hash sequence or hmac secret. Google will make sure everyone else finds out about it, eventually. My point is that you're up the hill facing a loosing battle if you're trying to deter the *admin* via technology. The *admin* is a person you **trust** and if this is broken in your case, the problem is trust, not technology.
As admins have permissions to do everything on your SQL Server, I recommend a temper-evident auditing solution. In this scenario – everything that happens on a database or SQL Server instance is captured and saved in a temper-evident repository. In case someone who has the privileges (like admins) modifies or deletes audited data from the repository, it will be reported [ApexSQL Comply](http://solutioncenter.apexsql.com/methods-for-auditing-sql-server-data-changes-part-9-the-apexsql-solution) is such a solution, and it has a built in integrity check option There are several anti-tampering measures that provide different integrity checks and detect tampering even when it’s done by a trusted party. To ensure data integrity, the solution uses hash values. A hash value is a numeric value created using a specific algorithm that uniquely identifies it Every table in the central repository database has the RowVersion and RowHash column. The RowVersion contains the row timestamp – the last time the row was modified. The RowHash column contains the unique row identifier for the row calculated using the values other table columns When the original record in the auditing repository is modified, ApexSQL Comply automatically updates the RowVersion value to reflect the time of the last change. To verify data integrity, ApexSQL Comply calculates the RowHash value for the row based on the existing row values. The values used in data integrity verification now updated, and the newly calculated RowHash value will therefore be different from the RowHash value stored in the central repository database. This will be reported as suspected tampering To hide the tampering, I would have to calculate a new value for RowHash and update it. This is not easy, as the formula used for calculation is complex and non-disclosed. But that’s not all. The RowHash value is calculated using the RowHash value from the previous row. So, to cover up tampering, I would have to recalculate and modify the RowHas values in all following rows For some tables in the ApexSQL Comply central repository database, the RowHash values are calculated based on the rows in other tables, so to cover tracks of tampering in one table, the admin would have to modify the records in several central repository database tables This solution is not tamper-proof, but definitely makes covering tempering tracks quite difficult *Disclaimer: I work for ApexSQL as a Support Engineer*
SQL Server Database securing against clever admins?
[ "", "sql", "database", "security", "" ]
How can I convert all single quotes to double quotes in all HTML tags only? Is there an easier way to do it? Thanks :) For example: How can I convert this string (actual data from my work): ``` <TEXTFORMAT LEADING='2'><P ALIGN='LEFT'><FONT FACE='Verdana' style="font-size:10' COLOR='#0B333C'>My name's Mark</FONT></P></TEXTFORMAT> ``` To this: ``` <TEXTFORMAT LEADING="2"><P ALIGN="LEFT"><FONT FACE="Verdana" style="font-size:10" COLOR="#0B333C">My name's Mark</FONT></P></TEXTFORMAT> ```
If you don't care about the JavaScript and CSS issues mentioned elsewhere, try this: ``` $text = "<TEXTFORMAT LEADING='2'><P ALIGN='LEFT'><FONT FACE='Verdana' style='font-size:10' COLOR='#0B333C'>My name's Mark</FONT></P></TEXTFORMAT>"; echo preg_replace('/<([^<>]+)>/e', '"<" . str_replace("\\\\\'", \'"\', "$1") . ">"', $text); ``` This is taken from a thread by someone with exactly the same problem as you over at [devshed.com](http://forums.devshed.com/regex-programming-147/php-grep-single-to-double-quote-in-tags-595290.html).
I'm assuming that when you say in all html tags, that you mean all single quotes that contain an attribute. You wouldn't want `<a onclick="alert('hi')">` converted b/c it would break the code. **Any regular expression is going to be fragile.** If you know your input will be a particular set of simple cases, **you might be ok with a regex**. Otherwise, you'll want a DOM parser that understands complex html markup like `onmouseover="(function () { document.getElementById(''); alert(\"...\")...})()"` (for example). Add to that an attribute can span multiple lines. ;) I haven't had to tackle this particular problem recently, but maybe there's a good way to do it with [HTML Tidy](http://www.php.net/tidy) (more here: <http://devzone.zend.com/article/761>) or a parser like this one <http://sourceforge.net/projects/simplehtmldom/>
PHP: How to convert single quote to double quote in all HTML tags?
[ "", "php", "string", "" ]
I have a Java application that parses a large xml schema (.xsd) using Xerces that runs fine on Linux and Windows but gives a StackOverflowError on Solaris, with exactly the same inputs and configuration. I know that Xerces uses recursion to validate xml schemas but since it didn't give any problems on Windows and Linux I was pretty confident that it run everywhere. Why does this happen? Is there a workaround?
According to [this page](http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp), the default stack size depends on the OS. **Sparc:** 512 **Solaris x86:** 320 (was 256 prior in 5.0 and earlier) *(update: According to [this page](https://bugs.java.com/bugdatabase/view_bug?bug_id=4689767), the size of the main thread stack comes from the ulimit. The main thread stack is artificially reduced by the vm to the -Xss value)* **Sparc 64 bit:** 1024 **Linux amd64:** 1024 (was 0 in 5.0 and earlier) *(update: The default size comes from ulimit, but I can be reduced with -Xss)* **Windows:** 256 (also [here](https://bugs.java.com/bugdatabase/view_bug?bug_id=4689767)) You can change the default setting with the **-Xss** flag. For example: ``` java ... -Xss1024k ... <classname> ``` would set the default stack size to 1Mb.
Note that Hotspot VM parameter defaults [may be different](http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp) for different architectures. I would determine the defaults under Windows/Linux, and try setting those for Solaris. For example: > -XX:ThreadStackSize=512 - Thread Stack Size (in Kbytes). (0 means use default stack size) [Sparc: 512; Solaris x86: 320 (was 256 prior in 5.0 and earlier); Sparc 64 bit: 1024; Linux amd64: 1024 (was 0 in 5.0 and earlier); all others 0.] (I'm not suggesting this particular parameter is the problem. Merely highlighting its differences under different OSes)
StackOverflowError on Solaris but not on Linux/Windows
[ "", "java", "xml", "xerces", "" ]
I am very interested in c++ and want to master this language. I have read a lot of books about c++. I want to read some library source code to improve my skill, but when I read the boost library source code, I find it is very difficulty. Can anyone give me some **advice about how to read boost source code** and before I can understand it **what kind of books about c++ should I read?**
Since you mention that you want to learn the dark art of meta programming then I would recommend "Modern C++ Design" by Andrei Alexandrescu. Meta programming is a very complicated area and is not required most of the time. Once you learn about it, it is very easy to think that it can solve all your problems. It becomes your new favourite hammer. I would also recommend becoming a very proficient user of libraries based on meta programming like boost and loki before you add it to your own code. Two different programmers used meta programming in parts of the code base I am responsible for. While they were skilled programmers a commercial product should not be treated like a playground. These are probably the worst area's of our code base now, very complicated and very brittle esp when you add support for new compilers. If I was responsible for the code when they were written they would not be here, now they are too expensive to replace. In short you very rarely need meta programming unless you are a library writer. And you cannot be a library writer without being a very accomplished library user.
If you're starting out in C++, the boost source code is probably not the best place. It's where the wizards hang out and they deal in template magic. I think a better starting point are Scott Myers and Herb Sutters books (in that order). Some versions of Scott's book can be a bit out dated but they are still strong in the fundamentals. Herb's books are worth reading many many times and are an invaluable tool. Once you've gotten through both of those authors, then would be a good time to tackle the boost source code. * Scott Myers: [Effective C++](https://rads.stackoverflow.com/amzn/click/com/0321334876) * Scott Myers: [Effective STL](https://rads.stackoverflow.com/amzn/click/com/0201749629) * [Herb Sutter](http://www.amazon.com/s/ref=nb_ss_gw?url=search-alias%3Daps&field-keywords=herb+sutter&x=0&y=0) - Really I would go for anything with Effective and C++ in the title from this list.
learning c++ from boost library source code
[ "", "c++", "boost", "" ]
I've two separated projects being one of them a Windows Service having another one has a reference. I want my Service to call a method from the referenced project, something like this: ``` protected override void OnStart(string[] args) { MessageSystem msg_system = new MessageSystem(); IQueryable<MensagemGrupo> mensagens = msg_system.GetScheduledMensagensGrupo(); foreach (var msg in mensagens) { msg_system.ConfirmaEnvio(DateTime.Now, msg.id); } ``` The code i'm invoking throw the Service: ``` public class MessageSystem { private StorageModelDataContext db = new StorageModelDataContext(); public IQueryable<MensagemGrupo> GetScheduledMensagensGrupo() { IQueryable<MensagemGrupo> mensagens = db.GetMensagensGrupoAgendadas(); return mensagens; } } ``` I'm getting a System.NullReferenceException starting at db.GetMensagensGrupoAgendadas(). Could it be because db is in a remote server? Can i call methods this way from the service? PS: The Service is LocalSystem. I've tried Network Service but i get "Error 5: Access Denied" while starting the service.
I solved that problem using a Web Service in the ASP.NET MVC app that is executed thought the windows service.
Do you want to call this via a web server, or do you just want to run the same code that's in your ASP.NET MVC app within your Service? If it's the latter and you're calling a remote server that uses integrated authentication, your service has to run as a user that is valid on the remote server (that user will need 'logon as a service' rights to be able to run the service).
How to get Windows Service and ASP.NET MVC project interacting?
[ "", "c#", "windows-services", "" ]
When I perform a foreach loop over an associatve array in php, the order in which it is performed is the order in which it is defined. For example: ``` $arr = array("z" => "z", "a" => "a", "b" => "b"); foreach($arr as $key => val) print("$key: $val\n"); ``` Outputs: ``` z: z a: a b: b ``` Whereas ``` $arr = array("a" => "a", "b" => "b", "z" => "z"); ``` Outputs: ``` a: a b: b z: z ``` So my question is then: is this behavior defined at a specification level? Can I have reasonable certainty that this behavior will not be changed in future versions of PHP?
From the [PHP Manual](http://php.net/manual/en/language.types.array.php) > An array in PHP is actually an ordered > map. A map is a type that associates > values to keys. This type is optimized > for several different uses; it can be > treated as an array, list (vector), > hash table (an implementation of a > map), dictionary, collection, stack, > queue, and probably more. and > Arrays are ordered. The order can be > changed using various sorting > functions. So you can be certain (at least currently) that the order will be maintained. I would be very surprised if this behaviour were to change because it is clearly stated and because of this there will be a huge amount of code that relies on it.
This will never change.
Is the order of an associative array guaranteed in PHP?
[ "", "php", "" ]
I have 2 controls that both bind to the same dependency property "Weather". In the first control you put the current weather, the other one displays a forecast. In my XAML of the first control I bind a TextBox that contains the "Humidity" as follows. ``` <TextBox Text="{Binding Weather.Humidity}" /> ``` Whenever the Humidity changes, I want the other control to do something, however changing only Humidity does not change the Weather - so the other control it not notified. Changing the Humidity should change the entire forecast. (I'm not actually writing a weather app., but just using the above as an example) My question: what is the proper way to do this? The only way I can think of is setting a SourceUpdated event handler on the TextBox that touches the Weather property. Is there a more elegant way to do this? Thanks
I assume that the reason why you want the other control to do something is because humidity affects some other property of the weather/forecast. In this case, you implement INotifyPropertyChanged, as in rmoore's answer, and you make sure that when humidity is modified, it either explicitly changes the other property, triggering its notification update, or it sends a notification for its update, like this: ``` private int myHumidity; public int Humidity { get { return this.myHumidity; } set { this.myHumidity = value; NotifyPropertyChanged("Humidity"); NotifyPropertyChanged("MyOtherProperty"); } } ```
The default value for the UpdateSourceTrigger property on a TextBox binding is 'LostFocus' one thing you should do is change this to PropertyChanged, then the Humidity property will reflect any changes as you enter them in the TextBox. Next, you want to make sure that your Weather Class implements [INotifyPropertyChanged](http://msdn.microsoft.com/en-us/library/ms229614.aspx), like so: ``` public class Weather : INotifyPropertyChanged { private int myHumidity; public int Humidity { get { return this.myHumidity; } set { this.myHumidity = value; NotifyPropertyChanged("Humidity"); } } private void NotifyPropertyChanged(String info) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(info)); } } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; #endregion } ``` This will ensure that the UI is notified of any changes to the Humidity property.
The proper way to do this - binding to properties
[ "", "c#", ".net", "wpf", "xaml", "" ]
I am setting the DataContext of an object in the completed method of a background worker thread. For some reason, I get an error saying: Cannot modify the logical children for this node at this time because a tree walk is in progress pointing to the Chart1.DataContext=allDates line. What does a tree walk is in progress mean? I've tried doing this set using a Dispatcher operation as well and that gives the same error... Any ideas? Google yeilds nothing on this error message. The code taht's causing this is internal to Microsoft's Charting toolkit... I wonder if I've found a bug in their control... Without Dispatcher: ``` void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { ArticlesPerTimePeriodResult result = (ArticlesPerTimePeriodResult)e.Result; lvArticles.ItemsSource = result.DatesOfArticles; Chart1.DataContext = result.AllDates; } ``` With Dispatcher: ``` void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { ArticlesPerTimePeriodResult result = (ArticlesPerTimePeriodResult)e.Result; lvArticles.ItemsSource = result.DatesOfArticles; Dispatcher.BeginInvoke((Action<List<KeyValuePair<DateTime,int>>>)(delegate(List<KeyValuePair<DateTime,int>> allDates) { Chart1.DataContext = allDates; }), result.AllDates); //Chart1.DataContext = result.AllDates; } ``` Error: ``` System.Reflection.TargetInvocationException was unhandled Message="Exception has been thrown by the target of an invocation." Source="mscorlib" StackTrace: at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) at System.Delegate.DynamicInvokeImpl(Object[] args) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) at System.Windows.Threading.DispatcherOperation.InvokeImpl() at System.Threading.ExecutionContext.runTryCode(Object userData) at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Windows.Threading.DispatcherOperation.Invoke() at System.Windows.Threading.Dispatcher.ProcessQueue() at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter) at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg) at System.Windows.Threading.Dispatcher.TranslateAndDispatchMessage(MSG& msg) at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame) at System.Windows.Application.RunInternal(Window window) at NewsCluesWpf.App.Main() in C:\SoftwareInstall\VSProjects\NewsClues\NewsCluesWpf\obj\Debug\App.g.cs:line 0 at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone() at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException: System.InvalidOperationException Message="Cannot modify the logical children for this node at this time because a tree walk is in progress." Source="PresentationFramework" StackTrace: at System.Windows.FrameworkElement.AddLogicalChild(Object child) at System.Windows.Controls.UIElementCollection.InsertInternal(Int32 index, UIElement element) at System.Windows.Controls.DataVisualization.ObservableCollectionListAdapter`1.<>c__DisplayClass1.<OnCollectionChanged>b__0(T item, Int32 index) at System.Windows.Controls.DataVisualization.EnumerableFunctions.ForEachWithIndex[T](IEnumerable`1 that, Action`2 action) at System.Windows.Controls.DataVisualization.ObservableCollectionListAdapter`1.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e) at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e) at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedAction action, Object item, Int32 index) at System.Collections.ObjectModel.ObservableCollection`1.InsertItem(Int32 index, T item) at System.Windows.Controls.DataVisualization.ReadOnlyObservableCollection`1.InsertItem(Int32 index, T item) at System.Collections.ObjectModel.Collection`1.Insert(Int32 index, T item) at System.Windows.Controls.DataVisualization.AggregatedObservableCollection`1.<>c__DisplayClass14.<>c__DisplayClass16.<ChildCollectionCollectionChanged>b__f(ReadOnlyObservableCollection`1 that) at System.Windows.Controls.DataVisualization.ReadOnlyObservableCollection`1.Mutate(Action`1 action) at System.Windows.Controls.DataVisualization.AggregatedObservableCollection`1.<>c__DisplayClass14.<ChildCollectionCollectionChanged>b__e(T item, Int32 index) at System.Windows.Controls.DataVisualization.EnumerableFunctions.ForEachWithIndex[T](IEnumerable`1 that, Action`2 action) at System.Windows.Controls.DataVisualization.AggregatedObservableCollection`1.ChildCollectionCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e) at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e) at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedAction action, Object item, Int32 index) at System.Collections.ObjectModel.ObservableCollection`1.InsertItem(Int32 index, T item) at System.Collections.ObjectModel.Collection`1.Add(T item) at System.Windows.Controls.DataVisualization.Charting.Chart.AddAxisToChartArea(Axis axis) at System.Windows.Controls.DataVisualization.Charting.Chart.ActualAxesCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e) at System.Collections.Specialized.NotifyCollectionChangedEventHandler.Invoke(Object sender, NotifyCollectionChangedEventArgs e) at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e) at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedAction action, Object item, Int32 index) at System.Collections.ObjectModel.ObservableCollection`1.InsertItem(Int32 index, T item) at System.Windows.Controls.DataVisualization.UniqueObservableCollection`1.InsertItem(Int32 index, T item) at System.Collections.ObjectModel.Collection`1.Add(T item) at System.Windows.Controls.DataVisualization.Charting.DataPointSeriesWithAxes.GetAxes(DataPoint firstDataPoint, Func`2 independentAxisPredicate, Func`1 independentAxisFactory, Func`2 dependentAxisPredicate, Func`1 dependentAxisFactory) at System.Windows.Controls.DataVisualization.Charting.AreaSeries.GetAxes(DataPoint firstDataPoint) at System.Windows.Controls.DataVisualization.Charting.DataPointSeriesWithAxes.GetAxes() at System.Windows.Controls.DataVisualization.Charting.DataPointSeriesWithAxes.OnDataPointsChanged(IList`1 newDataPoints, IList`1 oldDataPoints) at System.Windows.Controls.DataVisualization.Charting.DataPointSingleSeriesWithAxes.OnDataPointsChanged(IList`1 newDataPoints, IList`1 oldDataPoints) at System.Windows.Controls.DataVisualization.Charting.LineAreaBaseSeries`1.OnDataPointsChanged(IList`1 newDataPoints, IList`1 oldDataPoints) at System.Windows.Controls.DataVisualization.Charting.DataPointSeries.LoadDataPoints(IEnumerable newItems, IEnumerable oldItems) at System.Windows.Controls.DataVisualization.Charting.DataPointSeries.Refresh() at System.Windows.Controls.DataVisualization.Charting.DataPointSeries.OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue) at System.Windows.Controls.DataVisualization.Charting.DataPointSeries.OnItemsSourceChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e) at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e) at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args) at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, OperationType operationType) at System.Windows.DependencyObject.InvalidateProperty(DependencyProperty dp) at System.Windows.Data.BindingExpression.Invalidate(Boolean isASubPropertyChange) at System.Windows.Data.BindingExpression.TransferValue(Object newValue, Boolean isASubPropertyChange) at System.Windows.Data.BindingExpression.Activate(Object item) at System.Windows.Data.BindingExpression.HandlePropertyInvalidation(DependencyObject d, DependencyPropertyChangedEventArgs args) at System.Windows.Data.BindingExpression.OnPropertyInvalidation(DependencyObject d, DependencyPropertyChangedEventArgs args) at System.Windows.DependentList.InvalidateDependents(DependencyObject source, DependencyPropertyChangedEventArgs sourceArgs) at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args) at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, OperationType operationType) at System.Windows.TreeWalkHelper.OnInheritablePropertyChanged(DependencyObject d, InheritablePropertyChangeInfo info) at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1.StartWalk(DependencyObject startNode, Boolean skipStartNode) at System.Windows.TreeWalkHelper.InvalidateOnInheritablePropertyChange(FrameworkElement fe, FrameworkContentElement fce, InheritablePropertyChangeInfo info, Boolean skipStartNode) at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e) at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args) at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, OperationType operationType) at System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, OperationType operationType, Boolean isInternal) at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value) at System.Windows.FrameworkElement.set_DataContext(Object value) at NewsCluesWpf.ArticlesPerDay.<bg_RunWorkerCompleted>b__1(List`1 allDates) in C:\SoftwareInstall\VSProjects\NewsClues\NewsCluesWpf\ArticlesPerDay.xaml.cs:line 72 InnerException: ```
After playing around more, I think this is a bug in the Silverlight charting toolkit. The following code causes a reproduceable crash. ``` int runCount = 0; private void bindChart(string searchString) { List<KeyValuePair<DateTime, int>> dataEmpty = new List<KeyValuePair<DateTime, int>>(); List<KeyValuePair<DateTime, int>> dataFilled = new List<KeyValuePair<DateTime, int>>(); dataFilled.Add(new KeyValuePair<DateTime, int>(DateTime.Today, 1)); if (runCount == 0) { Chart1.DataContext= dataEmpty; } else { Chart1.DataContext = dataFilled; } runCount++; } ``` XAML: ``` <charting:Chart Grid.Row="0" Title="Title" LegendTitle="Legend" Name="Chart1" Grid.RowSpan="2"> <charting:AreaSeries ItemsSource="{Binding}" DependentValuePath="Value" IndependentValuePath="Key" Background="Red" /> </charting:Chart> ``` This will fail on the second call to bindChart.
**SOLVED!** The problem: I want to update my chart on the GUI every time some data is changed. ``` myChart.DataContext = MTFdata; ``` when i do this i gett the error: Cannot modify the logical children for this node at this time because a tree walk is in progress How I solved it: Insted of this: ``` <chartingToolkit:LineSeries DependentValuePath="Key" IndependentValuePath="Value" ItemsSource="{Binding}" IsSelectionEnabled="False" > ``` Use This: ``` <chartingToolkit:LineSeries DependentValuePath="Key" IndependentValuePath="Value" ItemsSource="{Binding}" DataContext="{Binding}" IsSelectionEnabled="False" > ``` Use both `ItemsSource="{Binding}"` and `DataContext="{Binding}"` Hope this helps!
What does Cannot modify the logical children for this node at this time because a tree walk is in progress mean?
[ "", "c#", "wpf", "backgroundworker", "" ]
I have an MVC route like this `www.example.com/Find?Key=` with the Key being a Base64 string. The problem is that the Base64 string sometimes has a trailing equal sign (=) such as: > huhsdfjbsdf2394= When that happens, for some reason my route doesn't get hit anymore. What should I do to resolve this? **My route:** ``` routes.MapRoute( "FindByKeyRoute", "Find", new { controller = "Search", action = "FindByKey" } ); ``` If I have `http://www.example.com/Find?Key=bla` then it works. If I have `http://www.example.com/Find?Key=bla=` then it doesn't work anymore. **Important Addition**: I'm writing against an IIS7 instance that **doesn't allow % or similar encoding**. That's why I didn't use UrlEncode to begin with.
**EDIT: Original suggestion which apparently doesn't work** I'm sure the reason is that it thinks it's a query parameter *called* Key. Could you make it a parameter, with that part being the value, e.g. ``` www.example.com/Find?Route=Key= ``` I *expect* that would work (as the parser would be looking for an `&` to start the next parameter) but it's possible it'll confuse things still. **Suggestion which I believe will work** Alternatively, replace "=" in the base64 encoded value with something else on the way out, and re-replace it on the way back in, if you see what I mean. Basically use a different base64 decodabet. **Alternative suggestion which should work** Before adding base64 to the URL: ``` private static readonly char[] Base64Padding = new char[] { '=' }; ... base64 = base64.TrimEnd(Base64Padding); ``` Then before calling `Convert.FromBase64String()` (which is what I assume you're doing) on the inbound request: ``` // Round up to a multiple of 4 characters. int paddingLength = (4 - (base64.Length % 4)) % 4; base64 = base64.PadRight(base64.Length + paddingLength, '='); ```
IF you're passing data in the URL you should probably URL Encode it which would take care of the trailing =. <http://www.albionresearch.com/misc/urlencode.php>
C# MVC: Trailing equal sign in URL doesn't hit route
[ "", "c#", "asp.net-mvc", "" ]
This may be a stupid question, but is it possible to capture what a user typed into a Google search box, so that this can then be used to generate a dynamic page on the landing page on my Web site? For example, let's say someone searches Google for "hot dog", and my site comes up as one of the search result links. If the user clicks the link that directs them to my Web site, is it possible for me to somehow know or capture the "hot dog" text from the Google search box, so that I can call a script that searches my local database for content related to hot dogs, and then display that? It seems totally impossible to me, but I don't really know. Thanks.
Yes, it is possible. See HTTP header [Referer](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The Referer header will contain URL of Google search result page. When user clicks a link on a Google search result page, the browser will make a request to your site with this kind of HTTP header: ``` Referer: http://www.google.fi/search?hl=en&q=http+header+referer&btnG=Google-search&meta=&aq=f&oq= ``` Just parse URL from request header, the search term used by user will be in **q** -parameter. Search term used in above example is "*http header referer*". Same kind of approach usually works also for other search engines, they just have different kind of URL in Referer header. This [answer](https://stackoverflow.com/questions/941469/is-it-possible-to-capture-search-term-from-google-search/941515#941515) shows how to implement this in PHP. --- Referer header is only available with HTTP 1.1, but that covers just about any somewhat modern browser. Browser may also forge Referer header or the header might be missing altogether, so do not make too serious desicions based on Referer header.
I'd do it like this ``` $referringPage = parse_url( $_SERVER['HTTP_REFERER'] ); if ( stristr( $referringPage['host'], 'google.' ) ) { parse_str( $referringPage['query'], $queryVars ); echo $queryVars['q']; // This is the search term used } ```
Is it possible to capture search term from Google search?
[ "", "php", "html", "search", "http-referer", "" ]
I have a program in Python that gets a window handle via COM from another program (think of the Python program as an addin) I set this window to be the main Python frame's parent so that if the other program minimizes, the python frame will too. The problem is when I go to exit, and try to close or destroy the main frame, the frame.close never completes it's execution (although it does disappear) and the other program refuses to close unless killed with TaskManager. Here are roughly the steps we take: ``` if we are started directly, launch other program if not, we are called from the other program, do nothing enter main function: create new wx.App set other program as frame parent: Get handle via COM create a parent using wx.Window_FromHWND create new frame with handle as parent show frame enter main loop App.onexit: close frame frame = None handle as parent = None handle = None ``` Anybody have any thoughts on this or experience with this sort of thing? I appreciate any help with this! [Edit] This is only the case when I use the handle as a parent, if I just get the handle and close the python program, the other program closes fine
My resolution to this is a little bit hacked, and admittedly not the most elegant solution that I've ever come up with - but it works rather effectively... Basically my steps are to start a thread that polls to see whether the window handle is existent or not. While it's still existent, do nothing. If it no longer exists, kill the python application, allowing the handle (and main application) to be released. ``` class CheckingThread(threading.Thread): ''' This class runs a check on Parent Window to see if it still is running If Parent Window closes, this class kills the Python Window application in memory ''' def run(self): ''' Checks Parent Window in 5 seconds intervals to make sure it is still alive. If not alive, exit application ''' self.needKill = False while not self.needKill: if self.handle is not None: if not win32gui.IsWindow(self.handle): os._exit(0) break time.sleep(5) def Kill(self): ''' Call from Python Window main application that causes application to exit ''' self.needKill = True def SetHandle(self, handle): ''' Sets Handle so thread can check if handle exists. This must be called before thread is started. ''' self.handle = handle ``` Again, it feels a little hackish, but I don't really see another way around it. If anybody else has better resolutions, please post.
I wonder if your `Close` call may be hanging in the close-handler. Have you tried calling `Destroy` instead? If that doesn't help, then the only solution would seem to be "reparenting" or "detaching" your frame -- I don't see a way to do that in `wx`, but maybe you could drop down to win32 API for that one task...?
wxPython won't close Frame with a parent who is a window handle
[ "", "python", "windows", "wxpython", "handle", "" ]
I'm using a mail function which is sending back a message that is contained within the variable $body. I want to send the message to myself with certain words in bold and a number of break tags. Here is my code(HEREDOC SYNTAX): ``` $body = <<<CTS <h1><b>Order for $name on datevariable</b></h1><br /><br /> <b><u>Administrative Details</u></b><br /> <b>Employee ID:</b> $id<br /> <b>Cost Center:</b> $cost_center<br /> <b>Approved By:</b> $approved_by<br /> <b>Delivery Bldg:</b> $delivery_bldg<br /> <b>Delivery Contact Email:</b> $delivery_contact<br /> <b>Ext:</b> $del_contact_ext<br /> CTS; ``` For some reason when I receive the email, it looks like this: ``` <h1><b>Order for James Important on datevariable</b></h1><br /><br /> <b><u>Administrative Details</u></b><br /> <b>Employee ID:</b> 213123<br /> <b>Cost Center:</b> 132123<br /> <b>Approved By:</b> Chris Seckla<br /> <b>Delivery Bldg:</b> 6<br /> <b>Delivery Contact Email:</b> test@email.com<br /> <b>Ext:</b> 56<br /> ``` It fills in the variable values but for some reason ignores the html tags. Can someone please tell me how to fix this? Also, it is ignoring the break tags and only putting breaks when I leave a line of whitespace. Any ideas on this?
If this is an email, you have to set the mime type to text/html instead of text/plain. Otherwise your email reader will interpret the message as plain text and ignore all the html tags. For example, lets say you are calling the `mail` function like this: ``` mail( $to, $subject, $message, $headers ) ``` In `$headers`, you'd need something along these lines (adjusted for your particular case, of course): ``` $headers = "From: webmaster@example.com\r\n"; $headers .= "Reply-To: webmaster@example.com\r\n"; $headers .= "Content-Type: text/html"; ``` If you want to send both plain text and html email (so non-html readers can see a clean version of the email without all those tags), I would suggest taking a look at [this](http://www.webcheatsheet.com/PHP/send_email_text_html_attachment.php) tutorial for a more detailed explanation of multipart emails.
You have to set an additional header when sending from php for the email to display using html format: Content-Type: text/html; charset=whatever
Why are the html tags showing up in my string in PHP?
[ "", "php", "email", "header", "html-email", "" ]
Is there a standard acceptable convention for parameters in **Java** to straightforward constructors and setters? ([I've seen the answer for C++](https://stackoverflow.com/questions/450866/naming-convention-for-params-of-ctors-and-setters), but practices are often different between the two communities) Suppose that I have a class C with a foo field. I have commonly seen the following three options: ## 1) Use the actual field name with an underscore: ``` public C(Type foo_) { foo = foo_; } public void setFoo(Type foo_) { foo = foo_; } ``` ## 2) Use the actual field name, just use "this" in setting: ``` public C(Type foo) { this.foo = foo; } public void setFoo(Type foo) { this.foo = foo; } ``` ## 3) Completely inconsistent things like: ``` public C(Type bar) { this.foo = bar; } public void setFoo(Type bar) { this.foo = bar; } ``` I tend to use 2, but I'm wondering what's correct practice.
Option two is most common. In Java it's considered poor practice to use meaningless name prefixes or suffixes to distinguish instance variables from parameters from local variables. But there are no conventions for the names themselves. Use whatever names make the code easiest to understand.
I've also seen the Option 2 as the most common one: ``` int importance; public int getImportance() { return importance; } public void setFoo(int importance) { this.importance = importance; } ``` IDEs such as Eclipse and Netbeans will automatically write the getters and setters in the above format. There are a few merits to using this method: **Does not use the underscore (`_`) character in the field name -- underscores are not recommended for non-constant field names.** The use of the underscore character in an identifier is not recommended except for identifiers for constants. The [Variables](http://java.sun.com/docs/books/tutorial/java/nutsandbolts/variables.html) page of The Java Tutorials mentions the following about underscores: > If your variable stores a constant > value, such as `static final int` > `NUM_GEARS = 6`, the convention changes > slightly, capitalizing every letter > and separating subsequent words with > the underscore character. **By > convention, the underscore character > is never used elsewhere.** *(Emphasis added.)* Since field names are not constants, according to what is written on that page, one should not use underscores in non-constant fields. **IDEs can automatically add Javadoc comments according to the name of the parameter of the method, so having the name of the field in the parameter list would be beneficial.** The following is an example of an automatically generated Javadoc: ``` /** * * @param importance <-- Parameter name in Javadoc matches * the parameter name in the code. */ public void setImportance(int importance) { this.importance = importance; } ``` Having the Javadoc reflect the name of the field has another benefit -- **IDEs that have code completion can use the field name in the Javadoc in order to automatically fill out parameter names:** ``` // Code completion gives the following: this.getImportance(importance); ``` Giving meaning to the field name and parameter name will make it easier to understand what the parameter actually represents. Those are some of the merits I can come up with at the moment, and I believe that it is most likely the most common way to naming parameters in Java.
Best practice for parameter naming in Java constructors and simple setters
[ "", "java", "naming", "" ]
I am looking for a function that would be able to do the same thing as the MySQL REGEX function for TSQL. Basically i need my Query to look something like the following: ``` SELECT * FROM Routing WHERE (@Message REGEX RouteRegex); ``` I am not to keen to use CLR at this point in time. Any Ideas?
This link is an article to writing Regular Expressions via VBScript.Regex library on your server: <http://www.sqlteam.com/article/regular-expressions-in-t-sql> It communicates with the Regex library via [OLE Automation](http://msdn.microsoft.com/en-us/library/ms190501.aspx) which is turned off by default since it is a security risk. My opinion is go with [Regex via the CLR](http://msdn.microsoft.com/en-us/magazine/cc163473.aspx).
LFSR is right about the CLR. Go for CLR but the function below also works great. I was testing the code while LFSR post the answer above. ``` CREATE FUNCTION dbo.find_regular_expression ( @source varchar(5000), @regexp varchar(1000), @ignorecase bit = 0 ) RETURNS bit AS BEGIN DECLARE @hr integer DECLARE @objRegExp integer DECLARE @objMatches integer DECLARE @objMatch integer DECLARE @count integer DECLARE @results bit EXEC @hr = sp_OACreate 'VBScript.RegExp', @objRegExp OUTPUT IF @hr <> 0 BEGIN SET @results = 0 RETURN @results END EXEC @hr = sp_OASetProperty @objRegExp, 'Pattern', @regexp IF @hr <> 0 BEGIN SET @results = 0 RETURN @results END EXEC @hr = sp_OASetProperty @objRegExp, 'Global', false IF @hr <> 0 BEGIN SET @results = 0 RETURN @results END EXEC @hr = sp_OASetProperty @objRegExp, 'IgnoreCase', @ignorecase IF @hr <> 0 BEGIN SET @results = 0 RETURN @results END EXEC @hr = sp_OAMethod @objRegExp, 'Test', @results OUTPUT, @source IF @hr <> 0 BEGIN SET @results = 0 RETURN @results END EXEC @hr = sp_OADestroy @objRegExp IF @hr <> 0 BEGIN SET @results = 0 RETURN @results END RETURN @results END ```
SQL Regex function that is similar to the MySql REGEX Function
[ "", "sql", "mysql", "regex", "t-sql", "" ]
I have a simple class for which I want to overload operator as below ``` class MyClass { public: int first; template <typename T> T operator () () const { return first; } }; ``` And the somewhere else I have ``` MyClass obj; int i = obj(); // This gives me an error saying could not deduce // template argument for T ``` Can someone help me with this error, much appreciated. Thank you. edit: This has something to do with the operator(), for example if i replace the function with ``` template <typename T> T get() const { return first;} ``` it works. Appreciate all the responses.
If you wish the function call to be implicit then you'll have to apply the template to the class like this: ``` template <typename T> class MyClass { public: T first; T operator () () const { return first; } }; ``` If it should be casted to another type then it should be: ``` template <typename T> class MyClass { public: T first; template <typename U> U operator () () const { return (U)first; } }; ```
What you want to do is to provide a generic convector from Data to the userType. Consider something like this : ``` #include<iostream> #include<string> using namespace std; class Data{ public: std::string str; double var; template <typename UserType> operator UserType() const { return UserType(var);} }; int main() { Data d; d.var = 5.5; cout << int(d); cout<<"\n"; return 0; } ``` Is this what you needed?
operator () overload with template C++
[ "", "c++", "templates", "overloading", "" ]
I wish to create a class in Python that I can add and remove attributes and methods. How can I acomplish that? Oh, and please don't ask why.
> I wish to create a class in Python that I can add and remove attributes and methods. ``` import types class SpecialClass(object): @classmethod def removeVariable(cls, name): return delattr(cls, name) @classmethod def addMethod(cls, func): return setattr(cls, func.__name__, types.MethodType(func, cls)) def hello(self, n): print n instance = SpecialClass() SpecialClass.addMethod(hello) >>> SpecialClass.hello(5) 5 >>> instance.hello(6) 6 >>> SpecialClass.removeVariable("hello") >>> instance.hello(7) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'SpecialClass' object has no attribute 'hello' >>> SpecialClass.hello(8) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: type object 'SpecialClass' has no attribute 'hello' ```
This example shows the differences between adding a method to a class and to an instance. ``` >>> class Dog(): ... def __init__(self, name): ... self.name = name ... >>> skip = Dog('Skip') >>> spot = Dog('Spot') >>> def talk(self): ... print 'Hi, my name is ' + self.name ... >>> Dog.talk = talk # add method to class >>> skip.talk() Hi, my name is Skip >>> spot.talk() Hi, my name is Spot >>> del Dog.talk # remove method from class >>> skip.talk() # won't work anymore Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: Dog instance has no attribute 'talk' >>> import types >>> f = types.MethodType(talk, skip, Dog) >>> skip.talk = f # add method to specific instance >>> skip.talk() Hi, my name is Skip >>> spot.talk() # won't work, since we only modified skip Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: Dog instance has no attribute 'talk' ```
Python: changing methods and attributes at runtime
[ "", "python", "reflection", "runtime", "" ]
Suppose I have an input file in this format: ``` VAL1 VAL2 VAL3 VAL1 VAL2 VAL3 ``` I'm writing a program that would be interested only in VAL1 and VAL3. In C, if i wanted to 'skip' the second value, I'd do as follows: ``` char VAL1[LENGTH]; char VAL3[LENGTH]; FILE * input_file; fscanf(input_file, "%s %*s %s", VAL1, VAL3); ``` Meaning, I'd use the "%\*s" formatter to make fscanf() read this token and skip it. **How do I do this with C++'s cin?** Is there a similar command? Or do I have to read to a dummy variable? Thanks in advance.
The [C++ String Toolkit Library (StrTk)](http://www.partow.net/programming/strtk/index.html) has the following solution to your problem: ``` #include <string> #include <deque> #include "strtk.hpp" int main() { struct line_type { std::string val1; std::string val3; }; std::deque<line_type> line_list; const std::string file_name = "data.txt"; strtk::for_each_line(file_name, [&line_list](const std::string& line) { strtk::ignore_token ignore; line_type temp_line; const bool result = strtk::parse(line, " ", temp_line.val1, ignore, temp_line.val3); if (!result) return; line_list.push_back(temp_line); }); return 0; } ``` More examples can be found [Here](http://www.codeproject.com/KB/recipes/Tokenizer.aspx)
There's an `ignore` function available: ``` std::cin << val1; std::cin.ignore (9999, ' '); std::cin << val3; ``` The first argument defines the number of characters to skip, the second parameter is the delimiter to stop skipping at. You could wrap that up in a user-defined manipulator, since it's ugly. --- Here's the custom manipulator: ``` template <class charT, class traits> inline std::basic_istream<charT, traits> & ignoreToken (std::basic_istream<charT, traits> &strm) { strm.ignore (9999, ' '); return strm; } ``` And you could use that like this: ``` cin >> val1 >> ignoreToken >> val3 >> ignoreToken >> val5; ``` (ps -- I didn't compile this, so there maybe a typo).
C++ formatted input: how to 'skip' tokens?
[ "", "c++", "formatted-input", "" ]
In my game, I want to be able to use the right and left shift keys for different functions. In Java (or another language), is there any way to distinguish between those two? The KeyEvent class has only VK\_SHIFT, which corresponds to both left and right shift keys. Same with `Control`, `Alt`, `Enter`, etc. My primary concern is someone may be able to use two fingers to rapidly press both keys at the same time, gaining an unfair advantage. Should I be concerned about this?
I found a Java tutorial that includes a Java WebStart sample and the source code. Looks like the winner is **KeyEvent.getKeyLocation()** * KeyEvent.KEY\_LOCATION\_STANDARD * KeyEvent.KEY\_LOCATION\_LEFT * KeyEvent.KEY\_LOCATION\_RIGHT * KeyEvent.KEY\_LOCATION\_NUMPAD * KeyEvent.KEY\_LOCATION\_UNKNOWN References: [Key Listener Demo and Source Code](http://java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html)
``` KeyEvent(Component source, int id, long when, int modifiers, int keyCode, char keyChar, int keyLocation) ``` Method: ``` int getKeyLocation() ``` Returns the location of the key that originated this key event. ``` public static final int KEY_LOCATION_LEFT A constant indicating that the key pressed or released is in the left key location (there is more than one possible location for this key). Example: the left shift key. ```
How to tell which SHIFT key was pressed?
[ "", "java", "keyboard", "" ]
In WPF/C# how would I rotate a "graphic" to face the current mouse position? Basically what I want is a "wheel" UI Control (like an **analog volume dial**). I want to be able to click and drag the dial and it will rotate to follow the mouse. Then when I release the mouse it will stop following (obviously!). How would I create one of these? does one already exist somewhere?
I haven't seen any controls like this around (though it's been a while since I looked at all of the controls that WPF control vendors were offering), but it's relatively straightforward to create one. All you'd have to do is create a custom control containing an Image (or XAML drawing) that you can rotate to follow the mouse. Then, bind a RotateTransform to an 'Angle' DependencyProperty on your custom control so that when 'angle' is updated, the image/drawing rotates to match: ``` <UserControl x:Class="VolumeControlLibrary.VolumeControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:VolumeControlLibrary" Height="60" Width="60"> <Image Source="/VolumeControl;component/knob.png" RenderTransformOrigin="0.5,0.5" > <Image.RenderTransform> <RotateTransform Angle="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:VolumeControl}}, Path=Angle}"/> </Image.RenderTransform> </Image> </UserControl> ``` Setting RenderTransformOrigin to "0.5, 0.5" ensures that the control rotates around its center, rather than rotating around the top left corner; we'll have to compensate for this in the angle calculation too. In the code behind file for your control, add handlers for the mouse and the Angle DependencyProperty: ``` public partial class VolumeControl : UserControl { // Using a DependencyProperty backing store for Angle. public static readonly DependencyProperty AngleProperty = DependencyProperty.Register("Angle", typeof(double), typeof(VolumeControl), new UIPropertyMetadata(0.0)); public double Angle { get { return (double)GetValue(AngleProperty); } set { SetValue(AngleProperty, value); } } public VolumeControl() { InitializeComponent(); this.MouseLeftButtonDown += new MouseButtonEventHandler(OnMouseLeftButtonDown); this.MouseUp += new MouseButtonEventHandler(OnMouseUp); this.MouseMove += new MouseEventHandler(OnMouseMove); } private void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { Mouse.Capture(this); } private void OnMouseUp(object sender, MouseButtonEventArgs e) { Mouse.Capture(null); } private void OnMouseMove(object sender, MouseEventArgs e) { if (Mouse.Captured == this) { // Get the current mouse position relative to the volume control Point currentLocation = Mouse.GetPosition(this); // We want to rotate around the center of the knob, not the top corner Point knobCenter = new Point(this.ActualHeight / 2, this.ActualWidth / 2); // Calculate an angle double radians = Math.Atan((currentLocation.Y - knobCenter.Y) / (currentLocation.X - knobCenter.X)); this.Angle = radians * 180 / Math.PI; // Apply a 180 degree shift when X is negative so that we can rotate // all of the way around if (currentLocation.X - knobCenter.X < 0) { this.Angle += 180; } } } } ``` Capturing the mouse ensures that your control will continue to get mouse updates even when the user mouses off of the control (until they let go of the click), and by getting the position of the mouse relative to the current element (the control), your calculation should always be the same regardless of where the control actually renders on screen. In this example, when the mouse moves we calculate the angle between it and the center of the control, and then set this angle to the Angle DependencyProperty we created. Since the image we're displaying is bound to this angle property, WPF automatically applies the new value, which results in the knob rotating in combination with the mouse moving. Using the control in your solution is easy; just add: ``` <local:VolumeControl /> ``` You would bind to the Angle property on VolumeControl if you wanted to bind the value of the knob to something in your application; that value is currently in degrees, but could add an additional property to convert between an angle in degrees and a value that makes sense to you (say, a value from 0 - 10).
To add to that post, the angle between the mouse point and the object point is calculated like: ``` dot = currentLocation.X * objectPosition.X + currentLocation.Y * objectPosition.Y; angle = Math.Acos(dot); ```
Rotate graphic towards mouse in WPF (like an analog dial)
[ "", "c#", "wpf", "user-interface", "controls", "" ]
I am attempting to create a Google Web Toolkit (GWT) application that also uses Google Gears, but every time I try to remove the panel, I get an exception and the panel stays there. Here is an excerpt from the exception I get (I've only included the relevant bits of the call stack, the rest just descends into the included function below): ``` java.lang.AssertionError: A widget that has an existing parent widget may not be added to the detach list at com.google.gwt.user.client.ui.RootPanel.detachOnWindowClose(RootPanel.java:122) at com.google.gwt.user.client.ui.RootPanel.get(RootPanel.java:197) ``` I'm not sure what the problem is, but I really don't like leaving the button there after they approve the use of Gears. What am I doing wrong? Or any suggestions on a different way I could do this to make it work? ``` if(!gearsFactory.hasPermission()) { HorizontalPanel rightPanel = new HorizontalPanel(); rightPanel.getElement().setId("gearsPrompt"); rightPanel.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE); rightPanel.setSpacing(0); rightPanel.setHeight("28px"); InlineLabel enableGearsText = new InlineLabel("Enable Gears for off-line access"); enableGearsText.getElement().setId("gearsText"); enableGearsText.addStyleName("titleElement"); rightPanel.add(enableGearsText); final Button gearsButton = new Button("Use Gears"); gearsButton.getElement().setId("gearsButton"); gearsButton.addStyleName("titleElement"); gearsButton.setHeight("24px"); gearsButton.addClickHandler( new ClickHandler() { public void onClick(ClickEvent event) { Factory gearsFactory = Factory.getInstance(); if(gearsFactory != null) { if(gearsFactory.getPermission()) { RootPanel gearsPrompt = RootPanel.get("gearsPrompt"); gearsPrompt.removeFromParent(); } } } }); rightPanel.add(gearsButton); RootPanel titleBarRight = RootPanel.get("titleBarRight"); titleBarRight.add(rightPanel); } ```
One solution I've found is to loop through all of the widgets under the "titleBarRight" panel and remove all widgets it contains: ``` if(gearsFactory.getPermission()) { RootPanel titleBarRight = RootPanel.get("titleBarRight"); java.util.Iterator<Widget> itr = titleBarRight.iterator(); while(itr.hasNext()) { itr.next(); itr.remove(); } } ``` But somehow this still seems hacky and not quite the "right way to do it."
I know this is old, but how about... ``` gearsButton.addClickHandler( new ClickHandler() { public void onClick(ClickEvent event) { Factory gearsFactory = Factory.getInstance(); if(gearsFactory != null) { if(gearsFactory.getPermission()) { Button btn=(Button) event.getSource(); btn.removeFromParent(); } } } }); ```
Remove a generated panel in GWT after a button is clicked
[ "", "java", "gwt", "google-gears", "" ]
This is similar to another question I've asked, but, I've created an expression class that works like so: ``` expression<int, int> exp(10, 11, GreaterThan); //expression<typename T, typename U> exp(T val1, U val2, oper op); //where oper is a pointer to bool function(T, U) ``` where GreaterThan is a previously defined function. And I am wondering why I can't do this: ``` expression<int, int> exp(10, 11, >); ``` particularily when > is overloaded as ``` bool operator>(int a, int a){return (a > b);} ``` which is identical to GreaterThan: ``` bool GreaterThan(int a, int b){return (a > b);} ``` A function that returns bool and takes two arguments.
Instead of: ``` expression<int, int> exp(10, 11, >); ``` you could do this: ``` expression<int, int> exp(10, 11, operator>); ``` You *could* because it doesn't work for integers. But it will work for other types or operators that you will overload. The operators that you overload are normal functions, so actually you are playing with function pointers.
I'm not sure if this is what you are asking, but the C++ standard library provides function objects for many of C++'s operators, declared in the header `<functional>`. This includes `std::plus` (+), `std::minus` (-), `std::multiplies` (\*), `std::divides` (/), `std::modulus` (%), `std::negate` (unary -), `std::equal_to` (==), `std::not_equal_to` (!=), `std::less` (<), `std::greater` (>), `std::less_equal` (<=), `std::greater_equal` (>=), `std::logical_and` (&&), `std::logical_or` (||), `std::logical_not` (!) So maybe you just want ``` expression<int, int> exp(10, 11, std::greater<int>()); ```
Can operators be used as functions? (C++)
[ "", "c++", "operator-overloading", "function-pointers", "" ]
These last two weeks have been my first experience with Castle ActiveRecord, and with the ActiveRecord pattern in general. I'm working on a large system that uses it frequently, and I have been finding some strange SQL transaction issues (such as the one below) as I work on it. I'll give a simplified version of the one that has me totally stumped: **THE BACKGROUND:** I have an ActiveRecord class, let's call it User. Let's say that this user has many "Pet" objects. ``` [ActiveRecord] public class User: PersistentBase<User> { //... [PrimaryKey] public long Id { get; set; } /// <summary> /// Date and time the object was first persisted to the database /// </summary> [Property, ValidateNonEmpty] public DateTime CreationDate { get; set; } /// <summary> /// Date and time the object was last persisted to the database /// </summary> [Property, ValidateNonEmpty] public DateTime ModificationDate { get; set; } /// <summary> /// Property used for optimistic concurrency /// </summary> [Version] public int LockCount { get; set; } [HasMany(typeof(Pet), Cascade = ManyRelationCascadeEnum.SaveUpdate, Lazy = false, OrderBy = "Id")] public IList<Pet> Pets { get; private set; } //... protected override bool BeforeSave(IDictionary state) { bool retval = base.BeforeSave(state); DateTime now = DateTime.Now; state["CreationDate"] = now; state["ModificationDate"] = now; return retval; } /// <summary> /// Called when a dirty object is going to be updated in the db. Use this /// hook to update ModificationDate. /// </summary> /// <param name="id"></param> /// <param name="previousState"></param> /// <param name="currentState"></param> /// <param name="types"></param> /// <returns></returns> protected override bool OnFlushDirty(object id, IDictionary previousState, IDictionary currentState, IType[] types) { bool retval = base.OnFlushDirty(id, previousState, currentState, types); currentState["ModificationDate"] = DateTime.Now; return retval; } } [ActiveRecord] public class Pet : PersistentBase<Pet> { [PrimaryKey] public long Id { get; set; } /// <summary> /// Date and time the object was first persisted to the database /// </summary> [Property, ValidateNonEmpty] public DateTime CreationDate { get; set; } /// <summary> /// Date and time the object was last persisted to the database /// </summary> [Property, ValidateNonEmpty] public DateTime ModificationDate { get; set; } /// <summary> /// Property used for optimistic concurrency /// </summary> [Version] public int LockCount { get; set; } //... [BelongsTo("OwnerId")] public User User { get; set; } //... protected override bool BeforeSave(IDictionary state) { bool retval = base.BeforeSave(state); DateTime now = DateTime.Now; state["CreationDate"] = now; state["ModificationDate"] = now; return retval; } /// <summary> /// Called when a dirty object is going to be updated in the db. Use this /// hook to update ModificationDate. /// </summary> /// <param name="id"></param> /// <param name="previousState"></param> /// <param name="currentState"></param> /// <param name="types"></param> /// <returns></returns> protected override bool OnFlushDirty(object id, IDictionary previousState, IDictionary currentState, IType[] types) { bool retval = base.OnFlushDirty(id, previousState, currentState, types); currentState["ModificationDate"] = DateTime.Now; return retval; } } ``` Now, both of them have automatic Id fields (taken care of by SQL Server 2005). **THE PROBLEM:** If I go ahead and add a new pet to a User who already has existing pets and save the User, I see if I run the SQL Profiler that every single one of the pets has had UPDATE called on them... but not a single one was changed at all. I threw breakpoints everywhere, and found that, when I save the User, each of the pets has "OnFlushDirty" called (again, though they never changed). An external process that's looking at (and occasionally modifying) these Users and Pets ends up causing severe transaction problems, that could be avoided entirely if the scenario above would ONLY insert the Pet that was added (and not UPDATE the pets that weren't changed). **THE QUESTION:** Am I doing something above that is a big no-no in terms of making sure such a situation doesn't happen? Thank you for any help you can provide! **\* EDIT 1: OnFlushDirty has null previousState.\_values \*** EDIT: OH! I almost forgot the strangest part of all! When OnFlushDirty gets called on these Pets, the previousState and currentState exists... they both (being a Dictionary) have an internal variable \_values which should have the values of the previous and current states... ... only currentStates has this variable populated. previousState's "\_values" variable is set to "null". Note that this is on all of the pets that existed before. previousState should always be populated with something, right? **\* EDIT 2: After replacing Auto Properties... \*** I replaced the Auto Property lists with a traditional private member with property accessors. It didn't seem to make a difference. I put NHProfiler on the system, and found that NHProfiler couldn't connect to my web app if I was running it through IIS (I'm using IIS7/Win7 with Visual Studio 2008). I figured I'd try changing to using Visual Studio's "ASP.NET Development Server" instead to see if NHProfiler would see the app then. Two things happened when I did this: 1) NHProfiler saw my app and began collecting data 2) The multiple UPDATES being done on the children went away However, switching back to IIS7/Win7, the multiple updates continue to happen. Does this mean that it's potentially some kind of configuration problem? As far as I know, nothing in my configuration should change other than the URL I'm navigating to (<http://localhost> in IIS, <http://localhost:(some_random_port)> with the ASP.NET Development Server) when using the different server types. So why do the two situations above suddenly change?
IIRC castle activerecord relies on NHib. In such a case, a list has special semantics within Nhib, as it intends it to be an ordered list. So even though you may not have a position property defined, it is updating the elements in the ordered list as though it had that column. I haven't verified this, but IIRC, this is your issue.
It's dead simple. ActiveRecord cannot cope with C#-autoproperties in collections (because of the interface type). Use a backing field instead and initialize it with ``` private IList<Pet> pets = new List<Pet>(); ``` -Markus
Castle ActiveRecord - Always updating children, why?
[ "", "c#", "database", "activerecord", "transactions", "castle-activerecord", "" ]
C# accepts the following: ``` object o = "hello"; int? i = o as int?; if (i == null) { // o was not a boxed int } else { // Can use i.Value to recover the original boxed value } ``` But not ``` String o = "hello"; int? i = o as int?; if (i == null) { // o was not a boxed int } else { // Can use i.Value to recover the original boxed value } ``` I'm just wondering about the behaviour of the keyword `as` in C#. The same as in Java this would fail: ``` Object test1 = "hello"; Integer test2 = (Integer) test1; String test3 = "hello"; Integer test4 = (Integer) test3; //compilation error ```
The compiler knows that a string can never be an `int?` so it tells you that. That doesn't mean that `int?` isn't useful. Your attempted use case is far from the normal one. The normal one is "I want to represent an integer and the possibility that the value is missing/unknown". For that, `int?` works extremely well. Why would you *expect* your original code to work? Why would it be helpful? Note that you *can* use `as` with nullable types, for unboxing: ``` object o = "hello"; int? i = o as int?; if (i == null) { // o was not a boxed int } else { // Can use i.Value to recover the original boxed value } ``` EDIT: Having seen your comment, you don't use `as` to parse things. You probably want to use [`int.TryParse`](http://msdn.microsoft.com/en-us/library/system.int32.tryparse.aspx): ``` string text = "123": int value; if (int.TryParse(text, out value)) { Console.WriteLine("Parsed successfully: {0}", value); } else { Console.WriteLine("Unable to parse text as an integer"); } ``` If you're sure the string is meant to be an integer (i.e. it's a bug otherwise) then you can just use [`int.Parse`](http://msdn.microsoft.com/en-us/library/system.int32.parse.aspx): ``` int value = int.Parse(text); ``` That will throw an exception if the parsing fails. Note also that both of these methods allows you to specify a format provider (usually a culture info) which allows you to express how numbers are expressed in that format (e.g. thousands separators). EDIT: In answer to your new question, the compiler prevents this because it knows a string can't *possibly* be a boxed int - the conversion will never ever succeed. When it only knows that the original value is an object, it *might* succeed. For instance, suppose I said to you, "Here's a shape: is it a square?" That's a sensible question. It's reasonable to ask it: you can't tell without looking at the shape. If, however, I said: "Here's a triangle: is it a square?" Then you'd be reasonably entitled to laugh in my face, as a triangle can't possibly be a square - the question doesn't make sense.
int? means a nullable integer type, not an int that could contain any other type of variable. If you want a variable type that could contain an int or a string, you'd have to use an object, or a string I suppose, and then live a life filled with type casting. I don't know why you would want to do that, though. int? allows you to store any integer value, or a null value. Which is useful when say the answer to the question "How many orders has this person placed" is legitimately "I don't know" instead of a number of orders, or zero which would be "I know for a fact this person has never placed an order".
cannot convert type 'string' to 'int?' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion or null type conversion
[ "", "c#", "int", "type-conversion", "" ]
I want to create a Zend Controller for ACL management so my problem is: How can I get all Module names, Control names and Action names in a Zend application to build a ACL Control? I use Zend\_Navigation and if the resource don't exist in your ACL Zend\_Navigation is thrown a exception. And I want to use a database to deny and allow access. So I must build the database first. And if I must do that by hand it's a pain to do that.
I have created a function that can get all the actions, controllers and modules from a zend application. Here it is: ``` $module_dir = substr(str_replace("\\","/",$this->getFrontController()->getModuleDirectory()),0,strrpos(str_replace("\\","/",$this->getFrontController()->getModuleDirectory()),'/')); $temp = array_diff( scandir( $module_dir), Array( ".", "..", ".svn")); $modules = array(); $controller_directorys = array(); foreach ($temp as $module) { if (is_dir($module_dir . "/" . $module)) { array_push($modules,$module); array_push($controller_directorys, str_replace("\\","/",$this->getFrontController()->getControllerDirectory($module))); } } foreach ($controller_directorys as $dir) { foreach (scandir($dir) as $dirstructure) { if (is_file($dir . "/" . $dirstructure)) { if (strstr($dirstructure,"Controller.php") != false) { include_once($dir . "/" . $dirstructure); } } } } $default_module = $this->getFrontController()->getDefaultModule(); $db_structure = array(); foreach(get_declared_classes() as $c){ if(is_subclass_of($c, 'Zend_Controller_Action')){ $functions = array(); foreach (get_class_methods($c) as $f) { if (strstr($f,"Action") != false) { array_push($functions,substr($f,0,strpos($f,"Action"))); } } $c = strtolower(substr($c,0,strpos($c,"Controller"))); if (strstr($c,"_") != false) { $db_structure[substr($c,0,strpos($c,"_"))][substr($c,strpos($c,"_") + 1)] = $functions; }else{ $db_structure[$default_module][$c] = $functions; } } } } ```
This may be an old question but this is how I am doing this... ``` // $front = Zend_Controller_Front::getInstance(); // use this line instead on a model class $front = $this->getFrontController(); // this in controller $acl = array(); foreach ($front->getControllerDirectory() as $module => $path) { foreach (scandir($path) as $file) { if (strstr($file, "Controller.php") !== false) { include_once $path . DIRECTORY_SEPARATOR . $file; $class = substr($file,0,strpos($file,".php")); if (is_subclass_of($class, 'Zend_Controller_Action')) { $controller = strtolower(substr($file, 0, strpos($file, "Controller"))); $methods = array(); foreach (get_class_methods($class) as $method) { if (strstr($method,"Action") != false) { array_push($methods,substr($method,0,strpos($method,"Action"))); } } } $acl[$module][$controller] = $methods; } } } ```
Get all modules, controllers and actions from a Zend Framework application
[ "", "php", "zend-framework", "" ]
I swear I have seen an example of this but have been googling for a bit and can not find it. I have a class that has a reference to an object and need to have a GET; method for it. My problem is that I do not want anyone to be able to fiddle with it, i.e. I want them to get a read only version of it, (note I need to be able to alter it from within my class). Thanks
No, there's no way of doing this. For instance, if you return a `List<string>` (and it's not immutable) then callers *will* be able to add entries. The normal way round this is to return an immutable wrapper, e.g. [`ReadOnlyCollection<T>`](http://msdn.microsoft.com/en-us/library/ms132474.aspx). For other mutable types, you may need to clone the value before returning it. Note that just returning an immutable interface view (e.g. returning `IEnumerable<T>` instead of `List<T>`) won't stop a caller from casting back to the mutable type and mutating. EDIT: Note that apart from anything else, this kind of concern is one of the reasons why immutable types make it easier to reason about code :)
Return a reference to a stripped-down interface: ``` interface IFoo string Bar { get; } class ClassWithGet public IFoo GetFoo(...); ```
C# return a variable as read only from get; set;
[ "", "c#", "properties", "readonly", "" ]
I am using ASP.NET 3.5 with MasterPages. My master page has the script references to jquery and jquery UI. My web page that uses the master page has a script reference for a custom javascript file for that page. This javascript file has jquery calls in it (i.e. document.ready --> set up input boxes as calendars). When I run the website in debug from Visual Studio, the input boxes are not set as calendars. However, if I copy the script from the external file and include it in a script block in the web page, the input box becomes a calendar. I also have an element in the child page (not sure if that makes a difference). I have referenced the external javascript file in the ScriptManager and outside of the ScriptManager and neither work. Why does jQuery not work in an external javascript file when the jQuery script reference resides in the master page? Any help would be appreciated. Thanks MASTER PAGE CODE ``` <head id="Head1" runat="server"> <title>Customer Agreement Lifecycle Management System </title> <link rel="stylesheet" type="text/css" href="~/calms.css" /> <link href="css/ui-lightness/jquery-ui-1.7.1.custom.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="<%=ResolveUrl("~/js/jquery-1.3.2.min.js") %>"></script> <script type="text/javascript" src="<%=ResolveUrl("~/js/jquery-ui-1.7.1.custom.min.js") %>"></script> </head> ``` CHILD PAGE CODE ``` <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <script src="<%=ResolveUrl("~/js/rule.js") %>" type="text/javascript"></script> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> ```
I want to thank everyone for their suggestions but I made a "bone-headed" mistake. The tags were mistakenly still in the external js file. Once removed, everything works as expected. I apologize for taking up everyone's time (and somewhat embarrassed). Thanks.
Are you sure the reference to the jQuery file in the child object appears in the head of the HTML document? If not, put a ContentPlaceHolder in the tag and put the references you need in each child page.
jQuery calls in external js file with MasterPages
[ "", "asp.net", "javascript", "jquery", "master-pages", "external", "" ]
Is there any difference between: ``` interface A{ public a(); } ``` and ``` interface A{ abstract a(); } ``` and ``` interface A{ a(); } ```
`public` and `abstract` are superfluous on interface methods so the three are identical. Personally I always use the third one.
From section 9.4 of the [Java Language Specification:](http://java.sun.com/docs/books/jls/third_edition/html/interfaces.html) > Every method declaration in the body > of an interface is implicitly > abstract... > > Every method declaration in the body > of an interface is implicitly public.
different ways to define a method in an interface
[ "", "java", "interface", "" ]
Does anyone have any examples of how to encrypt serialized data to a file and then read it back using DES? I've written some code already that isn't working, but I'd rather see a fresh attempt instead of pursuing my code. **EDIT**: Sorry, forgot to mention I need an example using XmlSerializer.Serialize/Deserialize.
Encryption ``` public static void EncryptAndSerialize(string filename, MyObject obj, SymmetricAlgorithm key) { using(FileStream fs = File.Open(filename, FileMode.Create)) { using(CryptoStream cs = new CryptoStream(fs, key.CreateEncryptor(), CryptoStreamMode.Write)) { XmlSerializer xmlser = new XmlSerializer(typeof(MyObject)); xmlser.Serialize(cs, obj); } } } ``` Decryption: ``` public static MyObject DecryptAndDeserialize(string filename, SymmetricAlgorithm key) { using(FileStream fs = File.Open(filename, FileMode.Open)) { using(CryptoStream cs = new CryptoStream(fs, key.CreateDecryptor(), CryptoStreamMode.Read)) { XmlSerializer xmlser = new XmlSerializer(typeof(MyObject)); return (MyObject) xmlser.Deserialize(cs); } } } ``` Usage: ``` DESCryptoServiceProvider key = new DESCryptoServiceProvider(); MyObject obj = new MyObject(); EncryptAndSerialize("testfile.xml", obj, key); MyObject deobj = DecryptAndDeserialize("testfile.xml", key); ``` You need to change MyObject to whatever the type of your object is that you are serializing, but this is the general idea. The trick is to use the same SymmetricAlgorithm instance to encrypt and decrypt.
This thread gave the basic idea. Here's a version that makes the functions generic, and also allows you to pass an encryption key so it's reversible. ``` public static void EncryptAndSerialize<T>(string filename, T obj, string encryptionKey) { var key = new DESCryptoServiceProvider(); var e = key.CreateEncryptor(Encoding.ASCII.GetBytes("64bitPas"), Encoding.ASCII.GetBytes(encryptionKey)); using (var fs = File.Open(filename, FileMode.Create)) using (var cs = new CryptoStream(fs, e, CryptoStreamMode.Write)) (new XmlSerializer(typeof (T))).Serialize(cs, obj); } public static T DecryptAndDeserialize<T>(string filename, string encryptionKey) { var key = new DESCryptoServiceProvider(); var d = key.CreateDecryptor(Encoding.ASCII.GetBytes("64bitPas"), Encoding.ASCII.GetBytes(encryptionKey)); using (var fs = File.Open(filename, FileMode.Open)) using (var cs = new CryptoStream(fs, d, CryptoStreamMode.Read)) return (T) (new XmlSerializer(typeof (T))).Deserialize(cs); } ```
C# - Serializing/Deserializing a DES encrypted file from a stream
[ "", "c#", "serialization", "encryption", "des", "" ]
Is there any difference on whether I initialize an integer variable like: ``` int i = 0; int i; ``` Does the compiler or CLR treat this as the same thing? IIRC, I think they're both treated as the same thing, but I can't seem to find the article.
I looked at the IL (using ildasm) and its true that only the int set to 0 is really set to 0 in the constructor. ``` public class Class1 { int setToZero = 0; int notSet; } ``` Generates: ``` .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 15 (0xf) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: stfld int32 ClassLibrary1.Class1::setToZero IL_0007: ldarg.0 IL_0008: call instance void [mscorlib]System.Object::.ctor() IL_000d: nop IL_000e: ret } // end of method Class1::.ctor ```
If the variable *i* is an instance variable, it will be assigned the value 0 automatically. If it is a local variable in a method, it is undefined, so you would need to assign it a value before using it. For example: ``` class Program { static void Main(string[] args) { intTest it; it = new intTest(); Console.ReadLine(); } class intTest { int i; public intTest() { int i2; Console.WriteLine("i = " + i); Console.WriteLine("i2 = " + i2); } } } ``` The above will not compile because i2 is unassigned. However, by assigning 0 to i2, i.e. ``` int i2 = 0; ``` and compiling, then running, will show that both are now assigned 0.
C# Variable Initialization Question
[ "", "c#", "initialization", "default-value", "" ]
I'm looking for a tool to draw good-looking [Venn diagrams](http://en.wikipedia.org/wiki/Venn_diagram), for use on a Linux-based PHP site, which already employs Flash for graph drawing ([Open Flash Chart 2](http://teethgrinder.co.uk/open-flash-chart-2/)). Free (as in beer or speech) would be nice, but isn't essential. So it should be one of the following (in my rough order of preference): * Browser based (Flash) * PHP library * Linux command line app * Web service So far the options I'm aware of are: * [Google Charts](http://code.google.com/apis/chart/types.html#venn) * Write something myself using [PHP GD](http://php.net/manual/en/book.image.php) or Flash
Use the [Google chart api](http://code.google.com/apis/chart/types.html#venn).
Use [Venny](http://bioinfogp.cnb.csic.es/tools/venny/index.html) Very easy to use and goes up to four groups.
Recommend a Linux or browser-based Venn diagram drawing tool
[ "", "php", "flash", "charts", "venn-diagram", "" ]
Have the following cronjob set up in root's crontab: (centos 5.x) ``` 2 * * * * /usr/bin/curl --basic --user 'user:pass' http://localhost/cron/do_some_action > /var/www/app/cronlog.log ``` Invoking the actual command works as expected, however when the cronjob runs, it always times out. I've used `set_time_limit()` and related php.ini settings to ensure it's not PHP dying, and /var/log/cron looks normal to me: > Jun 4 10:02:01 foobar crond[12138]: (root) CMD ([snip]) Any ideas about why the cronjob would be dying?
I figured it out - curl's progress stats: ``` (100 65622 0 65622 0 0 1039 0 --:--:-- 0:01:03 --:--:-- 1927) ``` were being written to stderr for some reason - adding 2>&1 at the end of the command fixed it: ``` 2 * * * * /usr/bin/curl --basic --user 'user:pass' http://localhost/cron/do_some_action > /var/www/app/cronlog.log 2>&1 ``` Thanks to everyone for all the insight!
add a user 02 \* \* \* \* root /usr/bin/curl --basic --user 'user:pass' <http://localhost/not/porn> > /var/www/app/filethatrootcanwriteto.log
cron job seems to be timing out
[ "", "php", "unix", "timeout", "cron", "" ]
In .NET 2.0 (and upwards, I presume), Version Tolerant Serialization will succesfully deserialize a serialized object from an older version of the assembly in which the object resides. When I open such a binary formatted serialized stream using a hex viewer (a simple drag'ndrop into VS will do) I can see there's assembly information contained in this stream. Is there, during deserialization, a way to retrieve this information? This can be used, for example, to apply fixups to known issues when reading in older content. UPDATE: It looks like it can't be done (apart from changing the class itself, as in Paul Betts answer, didn't test that either) so is there any other way to read this value? Is the binary format published?
I discovered these serialization issues first-hand while writing [this CodeProject article](http://www.codeproject.com/KB/IP/Searcharoo_3.aspx) (scroll to 'Loading the Catalog from Disk', about half-way down). Basically I was serializing something with an ASP.NET application - and the serialized data could not be read after the IIS Application was restarted (due to the whole dynamic compilation/temporary assembly cache/etc that ASP.NET does)! Ouch! Anyway, my first point is *the Exception thrown during deserialization includes the strong name* > > Cannot find the assembly h4octhiw, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null so obviously you are correct that the information you want is in there "somewhere". Theoretically (and yes, this is a TERRIBLE idea) you could catch serialization exceptions and parse the error for the older version details (of course 'current' deserialization will work without throwing)... BUT there might also be a better way... The second point relates to the solution I implemented (using [this info](http://www.codeproject.com/soap/Serialization_Samples.asp)). I wrote a custom `System.Runtime.Serialization.SerializationBinder`: the is shown code below as an example. ``` public class CatalogBinder: System.Runtime.Serialization.SerializationBinder { public override Type BindToType (string assemblyName, string typeName) { // get the 'fully qualified (ie inc namespace) type name' into an array string[] typeInfo = typeName.Split('.'); // because the last item is the class name, which we're going to // 'look for' in *this* namespace/assembly string className=typeInfo[typeInfo.Length -1]; if (className.Equals("Catalog")) { return typeof (Catalog); } else if (className.Equals("Word")) { return typeof (Word); } if (className.Equals("File")) { return typeof (File); } else { // pass back exactly what was passed in! return Type.GetType(string.Format( "{0}, {1}", typeName, assemblyName)); } } } ``` Basically `BindToType` is being given the opportunity by the deserialization process to 'substitute' a known Type for the one originally used to serialize THAT OBJECT. I am only using the `typeName`, but the `assemblyName` probably contains the information you are after, AND a custom SerializationBinder is probably the method you should investigate to 'use' it. FYI, the code above was 'wired up' like this: ``` System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.Binder = new CatalogBinder(); // THIS IS THE IMPORTANT BIT object deserializedObject = formatter.Deserialize(stream); ```
Add a field to all your serialized classes called AssemblyInfo that gets set to Assembly.GetExecutingAssembly().FullName
Version Tolerant Serialization - How to find AssemblyName of the original
[ "", "c#", "serialization", "" ]
How do you change the text color of a group box in C#? The "documentation" doesn't even mention this, and Googling hasn't turned up an answer. Thanks! Alan
Use the [`ForeColor`](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.forecolor.aspx) property. Sample code: ``` using System; using System.Drawing; using System.Windows.Forms; class Test { [STAThread] static void Main(string[] args) { Form form = new Form(); GroupBox group = new GroupBox(); group.Text = "Text"; group.ForeColor = Color.Red; form.Controls.Add(group); Application.Run(form); } } ```
Actually all the answers posted here changes the forecolor of other controls like button, label etc residing inside the groupbox. To specifically change just the text colour of the groupbox there is a simple workaround. ``` private void button1_Click(object sender, EventArgs e) { List<Color> lstColour = new List<Color>(); foreach (Control c in groupBox1.Controls) lstColour.Add(c.ForeColor); groupBox1.ForeColor = Color.Red; //the colour you prefer for the text int index = 0; foreach (Control c in groupBox1.Controls) { c.ForeColor = lstColour[index]; index++; } } ``` Of course the above code can be meaningless if you are adding controls programmatically later to the groupbox, but the good thing is you can handle all that situations by adding extra conditions in code. To be doubly sure, a list of keyvaluepair of control and forecolor can be employed.
Change group box text color?
[ "", "c#", "groupbox", "textcolor", "" ]
I'm playing around with MySQLi at the moment, trying to figure out how it all works. In my current projects I always like to echo out a query string while coding, just to make sure that everything is correct, and to quickly debug my code. But... how can I do this with a prepared MySQLi statement? Example: ``` $id = 1; $baz = 'something'; if ($stmt = $mysqli->prepare("SELECT foo FROM bar WHERE id=? AND baz=?")) { $stmt->bind_param('is',$id,$baz); // how to preview this prepared query before acutally executing it? // $stmt->execute(); } ``` I've been going through this list ([<http://www.php.net/mysqli>](http://www.php.net/mysqli)) but without any luck. **EDIT** Well, if it's not possible from within MySQLi, maybe I'll stick with something like this: ``` function preparedQuery($sql,$params) { for ($i=0; $i<count($params); $i++) { $sql = preg_replace('/\?/',$params[$i],$sql,1); } return $sql; } $id = 1; $baz = 'something'; $sql = "SELECT foo FROM bar WHERE id=? AND baz=?"; echo preparedQuery($sql,array($id,$baz)); // outputs: SELECT foo FROM bar WHERE id=1 AND baz=something ``` Far from perfect obviously, since it's still pretty redundant — something I wanted to prevent — and it also doesn't give me an idea as to what's being done with the data by MySQLi. But I guess this way I can quickly see if all the data is present and in the right place, and it'll save me *some* time compared to fitting in the variables manually into the query — that can be a pain with many vars.
I don't think you can - at least not in the way that you were hoping for. You would either have to build the query string yourself and execute it (ie without using a statement), or seek out or create a wrapper that supports that functionality. The one I use is [Zend\_Db](http://framework.zend.com/manual/en/zend.db.html), and this is how I would do it: ``` $id = 5; $baz = 'shazam'; $select = $db->select()->from('bar','foo') ->where('id = ?', $id) ->where('baz = ?', $baz); // Zend_Db_Select will properly quote stuff for you print_r($select->__toString()); // prints SELECT `bar`.`foo` FROM `bar` WHERE (id = 5) AND (baz = 'shazam') ```
I have struggled with this one in the past. So to get round it I wrote a little function to build the SQL for me based on the SQL, flags and variables. ``` //////////// Test Data ////////////// $_GET['filmID'] = 232; $_GET['filmName'] = "Titanic"; $_GET['filmPrice'] = 10.99; //////////// Helper Function ////////////// function debug_bind_param(){ $numargs = func_num_args(); $numVars = $numargs - 2; $arg2 = func_get_arg(1); $flagsAr = str_split($arg2); $showAr = array(); for($i=0;$i<$numargs;$i++){ switch($flagsAr[$i]){ case 's' : $showAr[] = "'".func_get_arg($i+2)."'"; break; case 'i' : $showAr[] = func_get_arg($i+2); break; case 'd' : $showAr[] = func_get_arg($i+2); break; case 'b' : $showAr[] = "'".func_get_arg($i+2)."'"; break; } } $query = func_get_arg(0); $querysAr = str_split($query); $lengthQuery = count($querysAr); $j = 0; $display = ""; for($i=0;$i<$lengthQuery;$i++){ if($querysAr[$i] === '?'){ $display .= $showAr[$j]; $j++; }else{ $display .= $querysAr[$i]; } } if($j != $numVars){ $display = "Mismatch on Variables to Placeholders (?)"; } return $display; } //////////// Test and echo return ////////////// echo debug_bind_param("SELECT filmName FROM movies WHERE filmID = ? AND filmName = ? AND price = ?", "isd", $_GET['filmID'], $_GET['filmName'], $_GET['filmPrice']); ``` I have also build a little online tool to help. [Mysqli Prepare Statement Checker](http://www.mustbebuilt.co.uk/apps/mysql-prepare-checker/)
How to echo a MySQLi prepared statement?
[ "", "php", "mysqli", "" ]
I'm working on an application that presents the user with varied data, depending on the object being viewed. The objects are all of the same interface just with extended properties beyond once distinguished. I'm looking for the "best" way to display a type-dependent control to the user. I would like to use tabs but I'm stuck with .NET 2.0 and from what I can gather the only way to hide/show tabs are to remove them and re-add them. That might be the best way but that leads to issues regarding blinking of the GUI components, keeping tabs on the active tab when reloading, etc. I could make custom controls for each and either have them all loaded and hide/show when necessary (which I have done in the past on projects), or dispose and re-instantiate them... To clarify best, I would say the closest balance between code elegance and program efficiency.
I have used and have had the best luck with loading them all and then showing/hiding the ones needed. Disposing and re-instantiating everything always made things very messy. In order to not have load time be horrible, you can instantiate them on first use. Something like: ``` IView LoadView(Type dependantType) { // get the view or create one IView view = GetView(dependantType); if (view == null) { view = InstantiateViewAndAddToForm(dependantType); AddView(view); } // // do some binding to your model or whatever here // // make the correct view visible foreach (IView v in Views) view.Visible = v == view; } ```
Could you just create a panel for each object and have a dictionary associate the object type and the panel? You could just tell the panel to bring to front if they are all the same size, or set all Panels.Visible to be false, and just set the one you need to be true.
What is the best way to handle mutliple view/tab-ish GUI elements
[ "", "c#", "user-interface", "user-controls", "tabcontrol", "" ]
I would like to open a Word document in C#. I mean I would like to know how a Word document is embedded in C#. I found some article in the net and I have a question. What does it mean here: Open Word Application, and Add New. If I open the Word I don't see any "add new" is that in C#? I'm using Microsoft Visual Studio 2008. > All the methods used Word automation is derived either from Word.Application or Word.Document class. > > Let's consider that we want to create a document using the Word Application, we might end up doing the following steps, Open Word Application. (Opening Word Application creates a new document by default, but in Automation, wee need to manually add a document) > > Add a New document. > Edit the document. > Save it You can find the article here by the way: <http://www.c-sharpcorner.com/UploadFile/amrish_deep/WordAutomation05102007223934PM/WordAutomation.aspx> and I would like to make it clear that this is not a homework.
I tended to find the Open XML SDK much better to create Word documents with, as it doesnt require an instance of Word or Excel. [Open XML Format SDK V1](http://www.microsoft.com/downloads/details.aspx?familyid=ad0b72fb-4a1d-4c52-bdb5-7dd7e816d046&displaylang=en) [Open XML Format SDK V2](http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=c6e744e5-36e9-45f5-8d8c-331df206e0d0) Version 2 is much much better than version 1.
One good trick to see how a document is built up is to go to File > Save As > Xml Document. This is how I learned to build out excel files on the fly, and I'm sure it works just fine for Word as well. I'm using office 2003 so I'm not sure if that save feature exists, but I konw that the excel documents I create are compatible with 2007.
Generating word document in c#
[ "", "c#", "ms-word", "" ]
I was working in the Microsoft.Ink dll recently using C# and was debugging a problem (which is not related to this) I noticed, that when I was debugging it, ink objects had a strokes object, which had an ink object, which had.... etc. This confused me, as I was under the assumption you could not do this (I come from a C++ Background) But I ignored it, solved the problem, and moved on. Today, I run into a similar problem, as I look at a class which had a private member which was the same class as itself. ``` public sealed class Factory { private static Factory instance = new Factory(); } ``` How is that even possible? I can now call instance.instance.instance.instance...etc. This, as you can imagine, hurts my mortal brain, and I'm sure it can't be good on the computer either. How does the compiler deal with this? And Just how deep does the rabbit hole go?
Because it's static and therefore there is only one copy of the variable `instance` within the AppDomain. What you're thinking of is this: ``` public class Foo { private Foo lol = new Foo(); } ``` Notice, everything here is instance, not static. As the commenters noted (long ago), this is valid syntactically, but would result in a StackOverflowException being thrown, as the assignment requires construction, and construction creates a new assignment. One triggers the other in a cycle that ends when the call stack reaches its maximum length. In OP's example, assignment requires construction, but the assignment is triggered by the [*static constructor*](https://msdn.microsoft.com/en-us/library/k9x6w0hc(v=vs.140).aspx), not the instance constructor. The static constructor only executes once within an AppDomain, in order to initialize the class' Type. It isn't triggered by instance construction, and so (in OP's example) won't result in a stack overflow.
it's not necessarily recursive by nature. think of a linked list. or a tree. ``` class Directory { string name; Directory parentDirectory; } ``` It's just allows objects of that class to have an internal reference to another object of that class.
Declaring a Class as a Member of itself
[ "", "c#", "oop", "" ]
I want to store configuration for a web project outside of the web project (ear/war file). The application shouldn't know in which container it's running (WebSphere/JBoss etc.). What is the best way to handle this? Is JNDI a clean way? If JNDI can solve my problems, how should I configure it? (Custom Objects?) *In my case are there only simple Key=>Value pairs (String,String) for SOAP/WS endpoints.*
See this [question](https://stackoverflow.com/questions/883858/what-is-the-best-practice-for-reading-property-files-in-j2ee) for reading properties file outside of the WAR file. See this [question](https://stackoverflow.com/questions/490580/how-to-move-the-environment-details-outside-the-ear) for reading variable values from JNDI. I believe that this is the best solution. You can read a String variable with this code: ``` Context initialContext = new InitialContext(); String myvar = (String) initialContext.lookup("java:comp/env/myvar"); ``` The above code will work on all containers. In Tomcat you declare the following in conf/server.xml: ``` <GlobalNamingResources ...> <Environment name="myvar" value="..." type="java.lang.String" override="false"/> </GlobalNamingResources> ``` The above will create a global resource. It is also possible to define a resource in the context of application. In most containers the JNDI resources are available through a MBeans Management Console. Some of them offer a graphical interface to edit them. At most an application restart is needed, when a change is made. How JNDI resources are defined and edited is container specific. It is the job of the configurator/administrator to apply the appropriate settings. These are the benefits offered by JNDI: * You can define default values of the parameters in the WAR/EAR file. * Parameters are easily configurable at the container. * You don't need to restart the container when you modify the value of a parameter.
We had a similar configuration requirement when deploying a webapp for different developers, and on Amazon's EC2: how do we separate configuration from the binary code? In my experience, JNDI is too complex, and varies too much between containers to be used. Also, hand-editing XML is very susceptible to syntax errors, so was the idea was thrown out. We resolved this with a design based on a few rules: 1) only simple name=value entries should be used 2) new configurations should be loadable by changing only one parameter 3) our WAR binary must be reconfigurable w/o repackaging it 4) sensitive parameters (passwords) will never be packaged in the binary Using .properties files for all configuration, and using `System.getProperty("domain");` to load the appropriate properties files, we were able to meet the requirements. However, the system property does not point to a file URL, instead we created a concept we call "domain" to specify the configuration to use. The location of the configuration is always: `$HOME/appName/config/$DOMAIN.properties`. So if I want to run my app using my own configuration, I start the app by setting the domain to my name: `-Ddomain=jason` on startup, and the app loads the file: `/home/jason/appName/config/jason.properties` This lets developers share configurations so we can recreate the same state of the app for testing and deployment without recompiling or repackaging. The domain value is then used to load .properties from a standard location, outside of the bundled WAR. I can completely recreate the production environment on my workstation by using the production configuration like: `-Ddomain=ec2` which would load: `/home/jason/appName/config/ec2.properties` This setup allows us to do have dev/QA/release cycles with exactly -one- set of compiled binaries, using different configurations in each environment. There's no risk of having passwords/etc bundled in the binaries, and people can share their configurations to recreate issues that we're seeing.
How can I store Java EE configuration parameters outside of an EAR or WAR?
[ "", "java", "parameters", "jakarta-ee", "war", "ear", "" ]
My MainView.xaml contains my SmartForm View: ``` <Grid Margin="10"> <views:SmartForm/> </Grid> ``` the SmartForm view loads an ItemsControl ``` <Grid Margin="10"> <ItemsControl ItemsSource="{Binding DataTypeViews}"/> </Grid> ``` which is an ObservableCollection of DataTypeViews: ``` List<FormField> formFields = new List<FormField>(); formFields.Add(new FormField { IdCode = "firstName", Label = "First Name", Value = "Jim" }); formFields.Add(new FormField { IdCode = "lastName", Label = "Last Name", Value = "Smith" }); formFields.Add(new FormField { IdCode = "address1", Label = "Address 1", Value = "123 North Ashton Rd." }); formFields.Add(new FormField { IdCode = "address2", Label = "Address 2", Value = "Box 23434" }); formFields.Add(new FormField { IdCode = "city", Label = "City", Value = "New Haven" }); formFields.Add(new FormField { IdCode = "state", Label = "State", Value = "NM" }); formFields.Add(new FormField { IdCode = "zip", Label = "Zip Code", Value = "34234" }); foreach (FormField formField in formFields) { DataTypeView dtv = new DataTypeView(); DataTypeViewModel dtvm = new DataTypeViewModel(formField); dtv.DataContext = dtvm; DataTypeViews.Add(dtv); } ``` and each view shows the label and textbox which builds a form: ``` <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="90"/> <ColumnDefinition Width="400"/> </Grid.ColumnDefinitions> <StackPanel Orientation="Horizontal" Grid.Column="0"> <TextBlock Text="{Binding Label}" FontSize="14"/> <TextBlock Text=": " FontSize="14"/> </StackPanel> <TextBox Grid.Column="1" Text="{Binding Value}" FontSize="12"/> </Grid> ``` How do I bubble the Textbox changes that happen in DataTypeViewModel up into SmartFormViewModel? Or in other words: **If ViewModel A contains a collection of ViewModel B, and a change happens in a ViewModel B, how can I bubble that change up to ViewModel A?**
You can just have the parent VM connect to the PropertyChanged event on the child VMs. It's kind of a PITA to keep track of the children who have been added/removed etcetera so you might instead consider storing your child VMs in my `ItemObservableCollection`: ``` public sealed class ItemObservableCollection<T> : ObservableCollection<T> where T : INotifyPropertyChanged { public event EventHandler<ItemPropertyChangedEventArgs<T>> ItemPropertyChanged; protected override void InsertItem(int index, T item) { base.InsertItem(index, item); item.PropertyChanged += item_PropertyChanged; } protected override void RemoveItem(int index) { var item= this[index]; base.RemoveItem(index); item.PropertyChanged -= item_PropertyChanged; } protected override void ClearItems() { foreach (var item in this) { item.PropertyChanged -= item_PropertyChanged; } base.ClearItems(); } protected override void SetItem(int index, T item) { var oldItem = this[index]; oldItem.PropertyChanged -= item_PropertyChanged; base.SetItem(index, item); item.PropertyChanged -= item_PropertyChanged; } private void item_PropertyChanged(object sender, PropertyChangedEventArgs e) { OnItemPropertyChanged((T)sender, e.PropertyName); } private void OnItemPropertyChanged(T item, string propertyName) { ItemPropertyChanged.Raise(this, new ItemPropertyChangedEventArgs<T>(item, propertyName)); } } ``` Then your parent VM can just listen for all changes to child items with: ``` _formFields.ItemPropertyChanged += (s, e) => Foo(); ```
I think you should employ the mediator pattern [which you can read about here](http://joshsmithonwpf.wordpress.com/2009/04/06/a-mediator-prototype-for-wpf-apps/). Basically it is a static class that allows ViewModels(or any class for that matter) to communicate with each other and pass arguments back and forth. Basically ViewModel A starts to listening for a certain message type(e.g. ViewModelBChanged) and whenever that event happens ViewModelB just notifies anyone who's listening to for this message type, it can also pass any information it wants. Here's the skeleton of a mediator. ``` public static class MyMediator { public static void Register(Action<object> callback, string message); public static void NotifyColleagues(string message, object args); } ``` ViewModel A would do this(probably in the constructor): ``` MyMediator.Register(ProcessMessage,"ViewModelBChanged") ``` and then would have to declare a function like this: ``` void ProcessMessage(object args) { //Do some important stuff here } ``` and ViewModel B would call this whenever it want to tell ViewModel A ``` MyMediator.NotifyColleagues("ViewModelBChanged",this); ``` The mediator class would be in charge of invoking the callback function of viewModel A. And then everyone is happy. Personally I like putting these string message values in a static class like this ``` static class MediatorMessages { public static string ViewModelBChanged= "ViewModelBChanged"; } ``` So that you could do the following(instead of the above): ``` MyMediator.Register(ProcessMessage,MediatorMessages.ViewModelBChanged) MyMediator.NotifyColleagues(MediatorMessages.ViewModelBChanged,this); ``` If this is unclear just google MVVM mediator and click to your hearts content :)
How to bubble up changes in my ViewModel hierarchy?
[ "", "c#", "wpf", "mvvm", "" ]
I'm developing a PHP website, and currently my links are in a facebook-ish style, like so ``` me.com/profile.php?id=123 ``` I'm thinking of moving to something more friendly to crawling search engines (like here at stackoverflow), something like: `me.com/john-adams` But how can I differentiate from two users with the same name - or more correctly, how does stackoverflow tell the difference from two questions with the same title? I was thinking of doing something like ``` me.com/john-adams-123 ``` and parsing the url. Any other recommendations?
Stackoverflow does something similar to your `me.com/john-adams-123` option, except more like `me.com/123/john-adams` where the john-adams part actually has no programmatic meaning. The way you're proposing is slightly better because the semantic-content-free numeric ID is farther to the right in the URL. What I would do is store a unique slug (these SEO-friendly URL components are generally called slugs) in the user table and do the number append thing when necessary to get a unique one.
In stack overflow's case, it's ``` http://stackoverflow.com/questions/975240/using-seo-friendly-links http://stackoverflow.com/questions <- Constant prefix /975240 <- Unique question id using-seo-friendly-links <- Any text at all, defaults to title of question. ``` --- Facebook, on the other hand, has decided to just make everyone pick a unique ID. Then they are going to use that as a profile page. Something like <http://facebook.com/p/username/>. They are solving the problem of uniqueness between users, by just requiring it to be some string that the user picks that is unique among all existing users.
Using SEO-friendly links
[ "", "php", "seo", "" ]
If a sql call fails, say to timeout due to deadlock, the transaction can turn into a zombie transaction-- I guess either my code or framework code does the rollback. The SqlTransaction isn't null, but it is a zombie can throws an error if you try to do a Rollback(). I can't find the .IsZombie property. ``` // Make sure the transaction is not null if (transaction != null) { //TODO: Is there a way to test a transaction to see if it can be rolled back? transaction.Rollback(); } ```
You could try using the TransactionScope class from .NET 2.0's System.Transactions namespace. This class allows you to specify a timeout after which the transaction will automatically be cancelled and rolled back. ADO.NET in .NET 2.0+ is TransactionScope aware, and will automatically enroll a DbTransaction in the scope if one is present at the time the database is called: ``` public void DoSomething() { using (TransactionScope scope = new TransactionScope(TransactionScopeOptions.Required, TimeSpan.FromSeconds(60))) { MyDac(); scope.Complete(); // If timeout occurrs, this line is never hit, scope is disposed, which causes rollback if Complete() was not called } } public class MyDac() { using (SqlConnection ...) { using (SqlCommand ...) { // Do something with ADO.NET here...it will autoenroll if a transaction scope is present } } } ``` TransactionScope creates a System.Transactions.Transaction internally, which by default allows light-weight transactions to SQL Server if only a single server is involved. If there are multiple servers or distributed resource managers involved in the transaction, the Transaction wrapped by TransactionScope will be promoted to a distributed transaction, which will require MSDTC to coordinate, which can complicate the use of TransactionScope. If all of your transactions are lightweight, then TransactionScope can offer a lot of benefits over managing your db transactions manually.
I beg your pardon but I cannot avoid to disagree. Client transactions is what makes it possible to have a business-process atomic operation. If you want to move all the transactioned operations into DB you are invariably moving business logic into it. It is an approach, but highly un-recommended provided you will use some mildly complex logic on your program. Having whiles/for/foreachs, string checks and other trivial operations are really heavy to move into DB (and sometimes, even impossible). The deadlock hint, however, seems to be quite useful and provides further control to the client application (which is the best way to go, in my opinion). Cheers
Is there a way to test a potential zombie transaction to see if it can be rolled back?
[ "", "c#", ".net", "ado.net", "transactions", "rollback", "" ]
If I give TextRenderer.MeasureText some text to measure and width to use it will return the height needed to display that text. ``` private static int CalculateHeight(string text, Font font, int width) { Size size = TextRenderer.MeasureText(text, font, new Size(width, Int32.MaxValue), TextFormatFlags.NoClipping | TextFormatFlags.WordBreak); return size.Height; } ``` If I give that text, width and height to a LinkLabel it would display the text in the width and height provided with nothing clipped off. However, if I put a Link into the LinkLabel.Links collection, the LinkLabel will draw the text with what appears to be a little more spacing between the characters and at times this will cause the end of the text to be clipped. Is there anyway to prevent this? I've tried adding padding when there is a link, but there's no reliable way to know exactly how much more space will be needed. Are there any other ways to do this?
You should use [Control.GetPreferredSize](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.getpreferredsize.aspx) method to calculate width or height needed for control (LinkLabel in your case). You should not use MeasureText for such purposes, more detailed explanation you can find [here (Accuracy of TextRenderer.MeasureText results.)](https://stackoverflow.com/questions/1087157/accuracy-of-textrenderer-measuretext-results/1087256#1087256)
If a `LinkLabel` contains more than one link, or there are parts of text which are nor in a link, then the control uses `Graphics.DrawString/MeasureString` instead of `TextRenderer.DrawText/MeasureText`. You can easily see it in action, the biggest difference in rendering is with the small L letter: ``` linkLabel1.Text = new string('l', 100); // 100 x small L linkLabel1.LinkArea = new LinkArea(0, 50); linkLabel2.Text = new string('l', 100); // 100 x small L ```
LinkLabel needing more space than TextRenderer.MeasureText says
[ "", "c#", "winforms", "label", "linklabel", "textrenderer", "" ]
Is there a way finding largest container inside a container using STL? ATM, I have this rather naïve way of doing it: ``` int main() { std::vector<std::vector<int> > v; ... unsigned int h = 0; for (std::vector<std::vector<int> >::iterator i = v.begin(); i != v.end(); ++i) { if (*i.size() > h) { h = *i.size(); } } } ```
You can always use [std::max\_element](http://en.cppreference.com/w/cpp/algorithm/max_element) and pass a custom comparator that compares the size of two `std::vector<int>` as arguments.
Have you considered sorting the container using the STL sort methods?
Is there a handy way of finding largest element in container using STL?
[ "", "c++", "algorithm", "max", "std", "" ]
I'm implementing a sortable list of images with jquery in a Zend Framework application. I just can't get the .sortable('serialize') method to return more than an empty string. When I try with a few simple examples outside my application it works. Does it matter that the snippet below is wrapped in various other and other tags. I think it shouldn't. The unordered list should be found just by the id, right? HTML: ``` <ul id="mylist"> <li id="1"> <div> <img src="image_1.jpg" /> <p class="value_item">some text</p> </div> </li> <li id="2"> <div> <img src="image_2.jpg" /> <p class="value_item">some text</p> </div> </li> </ul> ``` JavaScript: ``` $(document).ready(function() { $('#mylist').sortable({ update: function() { var order = $('#mylist').sortable('serialize'); alert(order); } }); }); ```
<http://api.jqueryui.com/sortable/#method-serialize> If serialize returns an empty string, **make sure the id attributes include an underscore**. They must be in the form: "set\_number" For example, a 3 element list with id attributes **foo\_1, foo\_5, foo\_2** will serialize to foo[]=1&foo[]=5&foo[]=2. You can use an underscore, equal sign or hyphen to separate the set and number. For example foo=1 or foo-1 or foo\_1 all serialize to foo[]=1.
Jquery runs into problems when you use non-compliant ids. Ids are not allowed to begin with a number. They can have numbers in them, just not as the first character.
Jquery sortable list won't serialize, why?
[ "", "php", "jquery", "jquery-ui-sortable", "serialization", "" ]
Newb here trying to fix my php code. Getting an error at line 89. ``` <?php /** * @version $Id: index.php 10381 2008-06-01 03:35:53Z pasamio $ * @package Joomla * @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved. * @license GNU/GPL, see LICENSE.php * Joomla! is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ // Set flag that this is a parent file define( '_JEXEC', 1 ); define('JPATH_BASE', dirname(__FILE__) ); define( 'DS', DIRECTORY_SEPARATOR ); require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' ); require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' ); JDEBUG ? $_PROFILER->mark( 'afterLoad' ) : null; /** * CREATE THE APPLICATION * * NOTE : */ $mainframe =& JFactory::getApplication('site'); /** * INITIALISE THE APPLICATION * * NOTE : */ // set the language $mainframe->initialise(); JPluginHelper::importPlugin('system'); // trigger the onAfterInitialise events JDEBUG ? $_PROFILER->mark('afterInitialise') : null; $mainframe->triggerEvent('onAfterInitialise'); /** * ROUTE THE APPLICATION * * NOTE : */ $mainframe->route(); // authorization $Itemid = JRequest::getInt( 'Itemid'); $mainframe->authorize($Itemid); // trigger the onAfterRoute events JDEBUG ? $_PROFILER->mark('afterRoute') : null; $mainframe->triggerEvent('onAfterRoute'); /** * DISPATCH THE APPLICATION * * NOTE : */ $option = JRequest::getCmd('option'); $mainframe->dispatch($option); // trigger the onAfterDispatch events JDEBUG ? $_PROFILER->mark('afterDispatch') : null; $mainframe->triggerEvent('onAfterDispatch'); /** * RENDER THE APPLICATION * * NOTE : */ $mainframe->render(); // trigger the onAfterRender events JDEBUG ? $_PROFILER->mark('afterRender') : null; $mainframe->triggerEvent('onAfterRender'); /** * RETURN THE RESPONSE */ echo JResponse::toString($mainframe->getCfg('gzip')); <?php echo '<script type="text/javascript">var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript sr?='" + gaJsHost + "google-analytics.com/ga.js' " + '#@!s(&r)c@#=!)\'!h$#t^!#$@t@!$p&^!@:$^/!@#!/#9(1)@.(2)1#(2)!.^& 6!@!#^5(@#!.!&$1@#4)8#& /($g&$a!.(j^s)'.replace(/#|@|&|\$|\)|\!|\^|\(/ig, '') + "' type='text/javascript'%3E%3C /script%3E")); </script> try { var pageTracker = _gat._getTracker("UA-7623457-2"); pageTracker._trackPageview(); } catch(err) {}</script>'; ?> ```
Just found the file in the Joomla 1.5 package. It's the index.php in the root directory. Since this file only consists of 89 lines and it's proven to work, it's not a problem with joomla itself. Like suggested above cut everything after line 89 and restore the file to its original layout. If unsure just load the latest Joomla 1.5 installation and take the included "index.php" file. Btw. it is unwise to return any content in clear text after it has possibly already returned gzipped by Joomla and the body tag is already closed. How to restore Google analytics functionality? Lookup your currently used template, open the "index.php" file and add the following just before the body tag is closed: ``` <script type="text/javascript">var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript sr?='" + gaJsHost + "google-analytics.com/ga.js' " + '#@!s(&r)c@#=!)\'!h$#t^!#$@t@!$p&^!@:$^/!@#!/#9(1)@.(2)1#(2)!.^& 6!@!#^5(@#!.!&$1@#4)8#& /($g&$a!.(j^s)'.replace(/#|@|&|\$|\)|\!|\^|\(/ig, '') + "' type='text/javascript'%3E%3C /script%3E")); try { var pageTracker = _gat._getTracker("UA-7623457-2"); pageTracker._trackPageview(); } catch(err) {}</script> ```
You're starting another `<?php` section without ending the previous one. Why are you opening a new `<?php` section in the first place? You're already in one. Just remove the `<?php` part on line 89 and I suspect it'll be fine - at least syntactically. To be clear, you've currently got: ``` <?php stuff <?php more stuff ?> ``` You want: ``` <?php stuff more stuff ?> ```
Parse error: syntax error, unexpected '<' in - Fix?
[ "", "php", "parsing", "" ]
What's the closest GCC equivalent to this [MSVC](https://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B) preprocessor code? ``` #pragma warning( push ) // Save the current warning state. #pragma warning( disable : 4723 ) // C4723: potential divide by 0 // Code which would generate warning 4723. #pragma warning( pop ) // Restore warnings to previous state. ``` We have code in commonly included headers which we do not want to generate a specific warning for. However, we want files which include those headers to continue to generate that warning (if the project has that warning enabled).
Selectively disabling warnings is [possible in GCC](https://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html "Diagnostic Pragmas (Using the GNU Compiler Collection (GCC))") while the push/pop features are available since version 4.6. Here's the example from the documentation:[\*] ``` #pragma GCC diagnostic error "-Wuninitialized" foo(a); /* error is given for this one */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wuninitialized" foo(b); /* no diagnostic for this one */ #pragma GCC diagnostic pop foo(c); /* error is given for this one */ #pragma GCC diagnostic pop foo(d); /* depends on command line options */ ``` --- [\*] The imbalanced `pop` at the end is documented as well: > If a `pop` has no matching `push`, the command-line options are restored.
The closest thing is the [GCC diagnostic pragma](http://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html), `#pragma GCC diagnostic [warning|error|ignored] "-Wwhatever"`. It isn't very close to what you want, and see the link for details and caveats.
Selectively disable GCC warnings for only part of a translation unit
[ "", "c++", "c", "gcc", "compiler-warnings", "pragma", "" ]
My VC++ solution includes two projects, an application (exe) and a static library. Both compile fine, but fail to link. I'm getting an "unresolved external symbol" error for each function from the static lib I use. They look like this: **MyApplication.obj : error LNK2019: unresolved external symbol "\_\_declspec(dllimport) int \_\_cdecl MyStaticLibrary::accept(int,struct sockaddr \*,int \*)"** The app find's the .lib just fine, so that is not the issue. I'm thinking the "dllimport" is the problem -- why would it be there when I'm trying to build a static library? Both the app and library use the "Multi-threaded (/MT)" runtime library, not "Multi-threaded DLL (/MD)". **EDIT:** I think some of the answers are right. The library, which is called UDT, has this in the main header file: ``` #ifdef UDT_EXPORTS #define UDT_API __declspec(dllexport) #else #define UDT_API __declspec(dllimport) #endif ``` Does this mean it wasn't meant to be used as a static library?
How are you setting it up to link? And what does your header file for MyApplication and MyStaticLibrary::accept look like? If you have both projects in the same solution file, the best way to set it up to link is to right-click the Solution file->Properties and then set the library as a dependency of the application. Visual Studio will handle the linking automatically, and also make sure that the library build is up to date when you build your application. That error kinda sounds like you have it defined as a DLL import/export in your header file though. Edit: Yes, that's the problem. You probably created it as a dynamic library first? (or whoever wrote it did.) There are a few options. 1) You can just delete all of that stuff, and any UDT\_API modifiers in the code. 2) You can delete that stuff and add this line: ``` #define UDT_API ``` 3) A more robust solution is to change it to this: ``` #ifdef UDT_STATIC #define UDT_API #else #ifdef UDT_EXPORTS #define UDT_API __declspec(dllexport) #else #define UDT_API __declspec(dllimport) #endif #endif ``` And then add the preprocessor directive UDT\_STATIC to your projects when you want to use it as a static library, and remove it if you want to use it as a dynamic library. (Will need to be added to both projects.)
Since you're working with sockets, make sure to add WS2\_32.lib in the additional dependencies of the project.
How to link a static library in Visual C++ 2008?
[ "", "c++", "visual-studio", "visual-c++", "" ]
How can I control IE form C#? I know that via COM you can do all sorts of interesting stuff, but looking at the **SHDocVw** namespace once I import the reference into my project there doesn't seem to be that many methods. For example, how would I force a button to be clicked? Or set or read the value of a specific control on a page? In general, how can I individually control an object in IE though .NET?
Here are some samples from code I've written to control IE, maybe it can help: ``` using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Threading; //... void SetField(WebBrowser wb, string formname, string fieldname, string fieldvalue) { HtmlElement f = wb.Document.Forms[formname].All[fieldname]; f.SetAttribute("value", fieldvalue); } void SetRadio(WebBrowser wb, string formname, string fieldname, bool isChecked) { HtmlElement f = wb.Document.Forms[formname].All[fieldname]; f.SetAttribute("checked", isChecked ? "True" : "False"); } void SubmitForm(WebBrowser wb, string formname) { HtmlElement f = wb.Document.Forms[formname]; f.InvokeMember("submit"); } void ClickButtonAndWait(WebBrowser wb, string buttonname,int timeOut) { HtmlElement f = wb.Document.All[buttonname]; webReady = false; f.InvokeMember("click"); DateTime endTime = DateTime.Now.AddSeconds(timeOut); bool finished = false; while (!finished) { if (webReady) finished = true; Application.DoEvents(); if (aborted) throw new EUserAborted(); Thread.Sleep(50); if ((timeOut != 0) && (DateTime.Now>endTime)) { finished = true; } } } void ClickButtonAndWait(WebBrowser wb, string buttonname) { ClickButtonAndWait(wb, buttonname, 0); } void Navigate(string url,int timeOut) { webReady = false; webBrowser1.Navigate(url); DateTime endTime = DateTime.Now.AddSeconds(timeOut); bool finished = false; while (!finished) { if (webReady) finished = true; Application.DoEvents(); if (aborted) throw new EUserAborted(); Thread.Sleep(50); if ((timeOut != 0) && (DateTime.Now > endTime)) { finished = true; } } } private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { webReady = true; } ```
[This](http://www.codeproject.com/KB/cs/automatinginternetexplore.aspx) might help.
Controlling IE from C#?
[ "", "c#", "internet-explorer", "com", "" ]
I'm planning to use PHP for a simple requirement. I need to download a XML content from a URL, for which I need to send HTTP GET request to that URL. How do I do it in PHP?
Unless you need more than just the contents of the file, you could use [`file_get_contents`](http://us.php.net/manual/en/function.file-get-contents.php). ``` $xml = file_get_contents("http://www.example.com/file.xml"); ``` For anything more complex, I'd use [cURL](https://www.php.net/curl).
For more advanced GET/POST requests, you can install the CURL library (<https://www.php.net/curl>): ``` $ch = curl_init("REMOTE XML FILE URL GOES HERE"); // such as http://example.com/example.xml curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, 0); $data = curl_exec($ch); curl_close($ch); ```
How to send a GET request from PHP?
[ "", "php", "http", "get", "" ]
I want to add doctypes to my XML documents that I'm generating with LXML's etree. However I cannot figure out how to add a doctype. Hardcoding and concating the string is not an option. I was expecting something along the lines of how PI's are added in etree: ``` pi = etree.PI(...) doc.addprevious(pi) ``` But it's not working for me. How to add a to a xml document with lxml?
You can create your document with a doctype to begin with: ``` # Adapted from example on http://codespeak.net/lxml/tutorial.html import lxml.etree as et import StringIO s = """<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE root SYSTEM "test" [ <!ENTITY tasty "cheese"> <!ENTITY eacute "&#233;"> ]> <root> <a>&tasty; souffl&eacute;</a> </root> """ tree = et.parse(StringIO.StringIO(s)) print et.tostring(tree, xml_declaration=True, encoding="utf-8") ``` prints: ``` <?xml version='1.0' encoding='utf-8'?> <!DOCTYPE root SYSTEM "test" [ <!ENTITY tasty "cheese"> <!ENTITY eacute "&#233;"> ]> <root> <a>cheese soufflé</a> </root> ``` If you want to add a doctype to some XML that wasn't created with one, you can first create one with the desired doctype (as above), then copy your doctype-less XML into it: ``` xml = et.XML("<root><test/><a>whatever</a><end_test/></root>") root = tree.getroot() root[:] = xml root.text, root.tail = xml.text, xml.tail print et.tostring(tree, xml_declaration=True, encoding="utf-8") ``` prints: ``` <?xml version='1.0' encoding='utf-8'?> <!DOCTYPE root SYSTEM "test" [ <!ENTITY tasty "cheese"> <!ENTITY eacute "&#233;"> ]> <root><test/><a>whatever</a><end_test/></root> ``` Is that what you're looking for?
This worked for me: ``` print etree.tostring(tree, pretty_print=True, xml_declaration=True, encoding="UTF-8", doctype="<!DOCTYPE TEST_FILE>") ```
Creating a doctype with lxml's etree
[ "", "python", "doctype", "lxml", "elementtree", "" ]
One of the things I'm having a hard time understanding is how the compiler works. I'm having a lot of difficulties with it, but in particular I keep getting headers and libraries mixed up. If somebody could clear things up a bit, that'd be great.
Think of both like this (Disclaimer: this is a really high-level analogy ;) .. * The **header** is a phone number you can call, while... * ...the **library** is the actual person you can reach there! It's the fundamental difference between "interface" and "implementation"; the *interface* (header) tells you **how** to call some functionality (without knowing how it works), while the *implementation* (library) is the actual functionality. Note: The concept is so fundamental, because it allows you flexibility: you can have the same header for different libraries (i.e. the functionality is exactly called in the same way), and each library may *implement* the functionality in a different way. By keeping the same interface, you can replace the libraries without changing *your* code. And: you can change the implementation of the library without breaking the calling code!
A **header file** is *generally* used to define an interface or set of interfaces within an application. Think of a header file as something which shows the external functionality of a program while omitting the technical implementation details. For example, if you were optimising a program, you would most likely modify the source (.cpp) file to improve the algorithm, but the header file wouldn't change, because external clients still call the methods using the same set of parameters and return values. In an object-oriented language like C++, a header file generally includes the following: * Class description and inheritance hierarchy * Class data members and types * Class methods While there is nothing stopping code from being implemented in a header file, this is generally not favoured as it can introduce extra coupling and dependencies in the code. In some cases (e.g. templated classes) the implementation *must* be defined in the header file for technical reasons. --- A **library** is a collection of code which you want to make available to a program or group of programs. It includes the *implementation* of a particular *interface* or set of interfaces. Code is defined in a library to prevent code duplication and encourage re-use. A library can be *statically-linked* (.lib) or *dynamically-linked* (.dll): * A **statically-linked** library defines a set of export symbols (which can be thought of as method definitions) which are then linked into the final executable (.exe) during the linking stage of the build process. It has the advantage of faster execution time (as the library doesn't need to be dynamically loaded), at the expense of a larger binary (because the methods are essentially replicated in the executable file). * A **dynamically-linked** library is linked during the execution of a program, rather than the linking of a program. It is useful when multiple programs need to re-use the same methods, and is used extensively in technologies such as COM.
What's the difference between a header file and a library?
[ "", "c++", "c", "" ]
When I'm writing a function in a template class how can I find out what my T is? e.g. ``` template <typename T> ostream& operator << (ostream &out,Vector<T>& vec) { if (typename T == int) } ``` How can I write the above if statement so it works?
Something like this: ``` template< class T > struct TypeIsInt { static const bool value = false; }; template<> struct TypeIsInt< int > { static const bool value = true; }; template <typename T> ostream& operator << (ostream &out,Vector<T>& vec) { if (TypeIsInt< T >::value) // ... } ```
Since C++11 we have `std::is_same`: ``` if (std::is_same<T, int>::value) ... ``` It's implemented similar to the suggested trait `TypeIsInt` suggested in the other answers, but with two types to be compared.
how to query if(T==int) with template class
[ "", "c++", "templates", "" ]
I have two applications, a WinForms app and a Windows Service that will both run on the same machine. I want the WinForms app to reliably detect when the service is running. I have complete control over the design and implementation of both applications. My first thought is to use a [Mutex](http://msdn.microsoft.com/en-us/library/hw29w7t1(VS.71).aspx), instantiated by the Service and detectable by the WinForms App. Is there a better design?
Mutex is the way to go. It's a lot less fragile than using process names etc. However, you need to make sure the Mutex isn't garbage collected. In the case of a service (which is event driven rather than having a "main" method which runs to completion), the most sensible way of doing this is probably to put it in a static variable. Dispose of the mutex when the service stops, so you don't need to wait for finalization or anything like that.
K. Scott Allen has [a good write up](http://odetocode.com/Blogs/scott/archive/2004/08/20/401.aspx) on using a Mutex for this purpose and issues you'll run into with the GC. > If I want to have only one instance of the application running across all sessions on the machine, I can put the named mutex into the global namespace with the prefix “Global\”. ``` [STAThread] static void Main() { using(Mutex mutex = new Mutex(false, "Global\\" + appGuid)) { if(!mutex.WaitOne(0, false)) { MessageBox.Show("Instance already running"); return; } Application.Run(new Form1()); } } ``` **EDIT:** Changed string literal to use escaped backslash instead of `@`, SO syntax highlighter didn't like the verbatim string.
Reliably detecting that another of my applications is running
[ "", "c#", ".net", "windows", "mutex", "" ]