Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a few regular expressions which are run against very long strings. However, the only part of the string which concerns the RE is near the beginning. Most of the REs are similar to:
```
\\s+?(\\w+?).*
```
The REs capture a few groups near the start, and don't care what the rest of the string is. For performance reasons, is there a way to have the RE engine avoid looking at all the characters consumed by the terminating `.*`?
Note: The application with the REs is written using the `java.regex` classes.
**Edit:** For example I have the following RE:
```
.*?id="number"[^>]*?>([^<]+?).*
```
Which is run against large HTML files which are stored as `StringBuilder`s. The tag with `id="number"` is always near the start of the HTML file. | When using the java.util.regex classes, there are a number of ways to match against a given string. `Matcher.matches` always matches against the *whole* input string. `Matcher.find` looks for something matching your regular expression *somewhere within* the input string. Finally, `Matcher.lookingAt` matches your regular expression against the *beginning* of your input string.
If you are using `Matcher.matches` you may require the `.*` at the end to match the whole string. However, you might be better off using one of the other methods instead, which would allow you to leave off the `.*`. It sounds like `Matcher.lookingAt` may be appropriate for your purposes. | Why not just take out **.\***, you dont need it.
```
^\\s+?(\\w+?)
``` | Is it possible to shortcut a regular expression into matching? | [
"",
"java",
"regex",
"performance",
"optimization",
""
] |
I'm trying to create my own class template for Visual Studio called "Public Class".
I followed [the official MSDN instructions on how to manually create an Item Template](http://msdn.microsoft.com/en-us/library/ms247113.aspx) pretty much to the letter, but I'm having no luck getting the template to show up in the "My Templates" section of the "Add New Item" dialog.
I placed PublicClass.zip in the following Windows XP directory:
C:\Documents and Settings\My User Name\My Documents\Visual Studio 2008\Templates\ItemTemplates\Visual C#.
**Public Class.zip contains the following files:**
1. PublicClass.cs
2. PublicClass.ico
3. PublicClass.vstemplate
**PublicClass.cs contains...**
```
using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ == 3.5)using System.Linq;
$endif$using System.Text;
namespace Pse.$projectname$
{
public class $safeitemname$
{
}
}
```
**PublicClass.vstemplate contains...**
```
<?xml version="1.0" encoding="utf-8"?>
<VSTemplate
Type="Item"
Version="1.0.0"
xmlns="http://schemas.microsoft.com/developer/vstemplate/2005">
<TemplateData>
<Name>Public Class</Name>
<Description>An empty class declaration with access modifier = public and namespace = Pse.NameOfProject</Description>
<Icon>PublicClass.ico</Icon>
<ProjectType>CSharp</ProjectType>
<DefaultName>PublicClass.cs</DefaultName>
</TemplateData>
<TemplateContent>
<ProjectItem ReplaceParameters="true">PublicClass.cs</ProjectItem>
</TemplateContent>
</VSTemplate>
```
I started up Studio, tried to add a new item to my project, but my template was nowhere to be found. So, I followed the advice of [this stackoverflow question](https://stackoverflow.com/questions/749979/visual-studio-2008-how-to-install-an-item-template), which was to call...
```
devenv.exe /installvstemplates
```
...from the command line, but all that did was make all the templates (including the built-in ones) disappear. After a few moments of panic, I eventually got them back after running the command several times, but that clearly wasn't the answer for me.
If you see anything wrong with my procedure here, can you please help me out?
Thanks in advance.
**EDIT:**
If I use File/Export Template (as suggested by Preet), the template *does* show up in My Templates, but the parameters are not replacing properly.
If I insert a new "Public Class", this is what I get:
```
using System;
using System.Collections.Generic;
$if$ (3.5 == 3.5)using System.Linq;
$endif$using System.Text;
namespace Pse.$projectname$
{
public class PublicClass1
{
}
}
```
So, only `$projectname$` and `$targetframeworkversion$` are replacing properly. It's not handling the `$if$` statement or `$projectname$` properly. (I also tried using `$safeprojectname$`, but that made no difference.)
This is definitely one of those cases where trying to make my life a little more convenient had had exactly the opposite effect :) | I had this problem :)
And I think I managed to solve it I was doing something very similar what I really wanted was to have a standard template which had headers in for our svn system I ended up extracting the existing Class.zip file in Foo:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033 and then editing it I ended up with this
```
// $Id$
// $Author$
namespace $rootnamespace$
{
using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ == 3.5) using System.Linq;
$endif$ using System.Text;
public class $safeitemrootname$
{
}
}
```
The spacing for the $if$ statement did seem to make a difference If I had tabs or spaced before them they would not evaluate properly or rather they did evaluate as you are seeing but were simply printed in my code.
As for your templates disappearing when you run /installvstemplates, well whats happening is you may notice that cmd takes quite a while to run, what it is infact doing is deleting
Foo:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplatesCache and then rebuilding that folder by extracting the zip files in the original locations as mentioned above. For this command to behave visual studio is best shutdown whilst you run it and you should wait until the command has finished to restart it. (tip I used to actually monitor the folder and watch it build).
Personally allthough this is a flexible system microsoft really could have made this easier for the user, after all R# has this as a simple right click feature, if you have R# this is the easiest way to implement templates outside of the ms system. | If you want it to work in Visual Studio 2008 you have to change `<VSTemplate Version="1.0.0">` to `<VSTemplate Version="3.0.0">` in your .vstemplate file. Then place the .zip file in what you have designated as your *user item templates location*. | What's wrong with my Visual Studio 2008 template? | [
"",
"c#",
"visual-studio",
"templates",
""
] |
I have a 64 bit VB.NET application and want to allocate a buffer > 2GB in size.
In the following code both the "new" and the "ReDim" throw an "OverflowException."
How can I allocate buffers > 2GB when these functions only accept signed 32 bit values?
(Is this possible in C#?)
**Edit** - I am running WinXP 64 with 4GB of RAM.
```
Dim width As Long = 19005
Dim height As Long = 32768
Dim buffer() As Byte = New Byte((width * height * 4) - 1) {}
Dim size As Long = (width * height * 4) - 1
ReDim buffer(size)
``` | Apparently it is not possible to allocate more than 2GB even under 64 bit .net application running on a 64 bit OS.
I find this to be very disappointing and completely without regard for what 64 bit applications and OSs are made for. I am dealing with *gigantic* images and would like to be able to work with the raw bytes all in RAM at once. Now I have to implement paging algorithms to limit the chunks to 2GB.
Hey Microsoft, hows abouts you fix this in the coming .NET release? Yes, I said *fix.* That's because it's broken. How do you expect 64 bit applications to take off when you do *stupid* things like this. (Can you tell that I am *annoyed*.) Thanks for listening.
[Link](http://blogs.msdn.com/joshwil/archive/2005/08/10/450202.aspx)
<http://blogs.msdn.com/joshwil/archive/2005/08/10/450202.aspx> | I think the UnmanagedMemoryStream does what you need. [MSDN doc for UnmanagedMemoryStream](http://msdn.microsoft.com/en-us/library/system.io.unmanagedmemorystream(VS.100).aspx)
I think it's a bad idea, to allocate a huge chunk of memory in a garbage collected environment, since most garbage collectors are optimized for small & short lived object. So using raw memory is generally a better and more performant solution for very large objects. | 64-Bit VB.NET Allocating > 2GB of RAM (.NET bug?) | [
"",
"c#",
".net",
"vb.net",
"memory",
"64-bit",
""
] |
I'm using a third party library which returns a data reader. I would like a simple way and as generic as possible to convert it into a List of objects.
For example, say I have a class 'Employee' with 2 properties EmployeeId and Name, I would like the data reader (which contains a list of employees) to be converted into List< Employee>.
I guess I have no choice but to iterate though the rows of the data reader and for each of them convert them into an Employee object that I will add to the List. Any better solution? I'm using C# 3.5 and ideally I would like it to be as generic as possible so that it works with any classes (the field names in the DataReader match the property names of the various objects). | Do you really need a list, or would IEnumerable be good enough?
I know you want it to be generic, but a much more common pattern is to have a static Factory method on the target object type that accepts a datarow (or IDataRecord). That would look something like this:
```
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public static Employee Create(IDataRecord record)
{
return new Employee
{
Id = record["id"],
Name = record["name"]
};
}
}
```
.
```
public IEnumerable<Employee> GetEmployees()
{
using (var reader = YourLibraryFunction())
{
while (reader.Read())
{
yield return Employee.Create(reader);
}
}
}
```
Then if you *really* need a list rather than an IEnumerable you can call `.ToList()` on the results. I suppose you could also use generics + a delegate to make the code for this pattern more re-usable as well.
**Update:** I saw this again today and felt like writing the generic code:
```
public IEnumerable<T> GetData<T>(IDataReader reader, Func<IDataRecord, T> BuildObject)
{
try
{
while (reader.Read())
{
yield return BuildObject(reader);
}
}
finally
{
reader.Dispose();
}
}
//call it like this:
var result = GetData(YourLibraryFunction(), Employee.Create);
``` | You could build an extension method like:
```
public static List<T> ReadList<T>(this IDataReader reader,
Func<IDataRecord, T> generator) {
var list = new List<T>();
while (reader.Read())
list.Add(generator(reader));
return list;
}
```
and use it like:
```
var employeeList = reader.ReadList(x => new Employee {
Name = x.GetString(0),
Age = x.GetInt32(1)
});
```
Joel's suggestion is a good one. You can choose to return `IEnumerable<T>`. It's easy to transform the above code:
```
public static IEnumerable<T> GetEnumerator<T>(this IDataReader reader,
Func<IDataRecord, T> generator) {
while (reader.Read())
yield return generator(reader);
}
```
If you want to automatically map the columns to properties, the code idea is the same. You can just replace the `generator` function in the above code with a function that interrogates `typeof(T)` and sets the properties on the object using reflection by reading the matched column. However, I personally prefer defining a factory method (like the one mentioned in Joel's answer) and passing a delegate of it into this function:
```
var list = dataReader.GetEnumerator(Employee.Create).ToList();
``` | Convert rows from a data reader into typed results | [
"",
"c#",
"list",
"datareader",
""
] |
Lets say I have the following code.
```
double *return_array(void) {
double foo[2];
foo[0] = 5;
foo[1] = 6;
cout << foo << endl;
cout << foo[0] << endl << foo[1] << endl;
return foo;
}
double *bar = return_array()
cout << bar << endl;
cout << bar[0] << endl << bar[1] << endl;
```
Now, bar and foo are still the same pointer but what was there has changed completely. How can I get around this? Basically, I need to pass 6 or 9 doubles from a function. What should I do? | Typically you would pass in your pre-allocated memory into the function:
```
int barsize = 2;
double *bar = new double[barsize];
fill_array( bar, barsize );
cout << bar << endl;
cout << bar[0] << endl << bar[1] << endl;
delete [] bar;
void fill_array( double *foo, int foosize )
{
if ( foosize < 2 )
return;
foo[0] = 5;
foo[1] = 6;
cout << foo << endl;
cout << foo[0] << endl << foo[1] << endl;
}
```
The rule I use is... always allocate and delete memory in the same spot.
Or use a std::vector. They're nice =) I never use arrays anymore. | Use a vector.
```
std::vector<double> return_array(void) {
std::vector<double> foo;
foo.push_back(5);
foo.push_back(6);
cout << foo[0] << endl << foo[1] << endl;
return foo;
}
```
---
This is a better way, So you avoid copying the vector :
```
void fillVector(std::vector<double>& vec)
{
vec.push_back(5);
vec.push_back(6);
}
int main()
{
std::vector<double> vec;
fillVector(vec);
}
```
---
> Now, bar and foo are still the same
> pointer but what was there has changed
> completely.
Because `foo` is allocated on the stack of the function, it gets deallocatd when the function returns. So, `bar` is actually pointing no where! | Keeping the contents of an array after its function call ends. (C++) | [
"",
"c++",
"arrays",
"memory",
""
] |
I like to organize my Java files a little and would like to know if there is a standard way of doing this. For example:
```
public class Example
{
private int exampleInt;
private String exampleString;
/*------------------------------------------------------------*/
/* I N N E R C L A S S E S */
/*------------------------------------------------------------*/
private someInnerClass
{
someInnerClass()
{
}
}
/*------------------------------------------------------------*/
/**
* This method returns the example int.
*/
public int getExampleInt() {
return exampleInt;
}
}
```
I don't what to call the part where I have a sort of comment break
/*-----------------------------------------------------------------*/
Is there any sort of convention for this sort of thing? Or is this something that I should just not be doing because most IDE's will display everything nicely to you in some sort of outline view? | Refactoring and source cleanup may cause your source files to be reorganized, including comments.
I would suggest you do not do that since that comment may end up somewhere completely unrelated.
Another thing you may want to try instead is to use your IDE to reformat your source. Eclipse allows for doing that every time you save a file. This will give all your code a consistent look allowing for easier reading. | The code explains itself. There is no need to put these ugly long comment lines in. If you really have to, then make them short, like so:
```
// -------------
// Inner Classes
// -------------
```
This is less messy. When I come across these kind of comments that state the obvious, I usually remove them right there and then. | Is there a coding convention for a "line rule" for Java | [
"",
"java",
"coding-style",
""
] |
I have this extract of C# source code:
```
object valueFromDatabase;
decimal result;
valueFromDatabase = DBNull.Value;
result = (decimal)(valueFromDatabase != DBNull.Value ? valueFromDatabase : 0);
result = (valueFromDatabase != DBNull.Value ? (decimal)valueFromDatabase : (decimal)0);
```
The first result evaluation throws an `InvalidCastException` whereas the second one does not.
What is the difference between these two? | UPDATE: This question was [the subject of my blog on May 27th 2010](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/cast-operators-do-not-obey-the-distributive-law). Thanks for the great question!
There are a great many very confusing answers here. Let me try to precisely answer your question. Let's simplify this down:
```
object value = whatever;
bool condition = something;
decimal result = (decimal)(condition ? value : 0);
```
How does the compiler interpret the last line? The problem faced by the compiler is that the **type of the conditional expression must be consistent for both branches**; the language rules do not allow you to return object on one branch and int on the other. The choices are object and int. Every int is convertible to object but not every object is convertible to int, so the compiler chooses object. Therefore this is the same as
```
decimal result = (decimal)(condition ? (object)value : (object)0);
```
Therefore the zero returned is a boxed int.
You then unbox the int to decimal. It is illegal to unbox a boxed int to decimal. For the reasons why, see my blog article on that subject:
[Representation and Identity](https://ericlippert.com/2009/03/03/representation-and-identity/)
Basically, your problem is that you're acting as though the cast to decimal were distributed, like this:
```
decimal result = condition ? (decimal)value : (decimal)0;
```
But as we've seen, that is not what
```
decimal result = (decimal)(condition ? value : 0);
```
means. That means "make both alternatives into objects and then unbox the resulting object". | The difference is that the compiler can not determine a data type that is a good match between `Object` and `Int32`.
You can explicitly cast the `int` value to `object` to get the same data type in the second and third operand so that it compiles, but that of couse means that you are boxing and unboxing the value:
```
result = (decimal)(valueFromDatabase != DBNull.value ? valueFromDatabase : (object)0);
```
That will compile, but not run. You have to box a decimal value to unbox as a decimal value:
```
result = (decimal)(valueFromDatabase != DBNull.value ? valueFromDatabase : (object)0M);
``` | Casting with conditional/ternary ("?:") operator | [
"",
"c#",
"conditional-operator",
""
] |
My Windows mobile application crashes sometimes with an exception that happens in the finalizer of `System.Net.HttpReadStream`.
It only happens sometimes, but then it brings down the whole program. Is there anything I can do to make the program continue when such an internal finalizer throws? Or alternatively, how can I prevent such an error?
Here's the stacktrace of the exception (not complete, since I have to type the whole thing...
```
ObjectDisposedException
at System.Threading.Timer.throwIfDisposed()
at System.Threading.Timer.Change(UInt32 dueTime, UInt32 period)
at ...
at System.Net.ContentLengthReadStream.doClose()
at System.Net.HttpReadStream.Finalize()
```
The calling code is:
```
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(actionUrl);
request.AllowAutoRedirect = true;
request.AllowWriteStreamBuffering = true;
request.Method = "POST";
request.ContentType = "application/json";
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(writer, myRequestObject);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
JsonSerializer serializer = new JsonSerializer();
MyResultObject result = (MyResultObject)serializer.Deserialize(reader, typeof(MyResultObject));
return result;
}
}
```
---
## Update
> The calling code above is fine. The problem was caused by another `HttpWebRequest` where the response was not disposed. So remember, always dispose the response object, but especially in Compact Framework since it can bring down your whole application! | It turned out that it was *another* `HttpWebRequest` causing this. The code in my question was fine, but the dispose of the response was missing in the other place. | This [thread](http://groups.google.com/group/microsoft.public.dotnet.framework.compactframework/browse_thread/thread/44ea29515c5cd2b0?pli=1) describes a similar problem.
The problem could be that you are returning inside the second using block. This way the response object won't get closed. | Windows Mobile: exception in Finalizer terminates program | [
"",
"c#",
".net",
"windows-mobile",
"compact-framework",
""
] |
How do I fetch the email of my friend programmatically in my facebook application? Does facebook provide this functionality? | The answer is no, Facebook does not provide this functionality. Facebook tries to protect the privacy of its users, and therefore user email addresses are explicitly not available.
The only way to email a user is to [prompt them](https://developers.facebook.com/docs/reference/fbml/prompt-permission/) to grant you extended email permissions via a [Facebook prompt](https://developers.facebook.com/docs/reference/fbml/prompt-permission/). If they grant you the permission, you can then use the [notifications.sendEmail](https://developers.facebook.com/docs/reference/fbml/notif-email/) API method, or query the `user` table for the `proxied_email` field, and send them an email via [Facebook's Email Proxy](http://wiki.developers.facebook.com/index.php/Proxied_Email) system. | **edit:** This changed with the newer Graph API's permissions system. Users now have the option to use the proxymail address, but it appears to reveal the true e-mail by default.
Facebook's API calls do not reveal users' e-mail addresses, ever.
Even when a user specifically grants you permission to e-mail them, it's a proxied e-mail address that doesn't reveal their true address - something like `apps+###########.#########.######################@proxymail.facebook.com`.
See <http://wiki.developers.facebook.com/index.php/Proxied_Email> for details. | fetch email of a friend in facebook app | [
"",
"c#",
"facebook",
"facebook-c#-sdk",
""
] |
I'm making a small Python program, which calls the `webbrowser` module to open a URL. Opening the URL works wonderfully.
My problem is that once this line of code is reached, the problem is unresponsive. How do I get the program to proceed past this line of code and continue to execute? Below the problematic line is the problematic line, in context:
```
if viewinbrowser == "y":
print "I can definitely do that. Loading URL now!"
webbrowser.open_new(url)
print "Exiting..."
sys.exit()
```
The program does not get as far as executing the `print "Exiting..."`, which I added because I noticed the program wasn't leaving the if statement for some reason.
I am running this program from the command line, in case that's important. **Edit:** I am running on Kubuntu 9.04 i386, using KDE 4.3 via backports. I use Firefox 3.5 as my default browser, declared in the System Settings for KDE, and it is called correctly by the program. (At least, a new tab opens up in Firefox with the desired URL—I believe that is the desired functionality.) **/Edit**
Also, I assume this problem would happen with pretty much any external call, but I'm very new to Python and don't know the terminology to search for on this site. (Searching for "python webbrowser" didn't yield anything helpful.) So, I apologize if it's already been discussed under a different heading!
Any suggestions? | The easiest thing to do here is probably to fork. I'm pretty sure this doesn't work in Windows unfortunately, since I think their process model might be different from Unix-like operating systems. The process will be similar, though.
```
import os
import sys
pid = os.fork()
if pid:
# we are the parent, continue on
print("This runs in a separate process from the else clause.")
else:
# child runs browser then quits.
webbrowser.open_new(url)
print("Exiting...")
sys.exit()
``` | This looks like it depends on which platform you're running on.
* MacOSX - returns True immediately and opens up browser window. Presumably your desired behavior.
* Linux (no X) - Open up links textmode browser. Once this is closed, returns True.
* Linux (with X) - Opens up Konquerer (in my case). Returns True immediately. Your desired behavior.
I'm guessing you're on Windows, which, as another commentor mentioned doesn't have fork. I'm also guessing that the webbrowser module uses fork internally, which is why it's not working for you on Windows. If so, then using the threading module to create a new thread that opens the webbrowser might be the easiest solution:
```
>>> import webbrowser
>>> import threading
>>> x=lambda: webbrowser.open_new('http://scompt.com')
>>> t=threading.Thread(target=x)
>>> t.start()
``` | How to resume program (or exit) after opening webbrowser? | [
"",
"python",
"browser",
"if-statement",
""
] |
Something which doesn't rely on native libraries would be better. | You could try the dnspython library:
* <http://www.dnspython.org/examples.html>
* <http://www.dnspython.org/docs/1.7.1/html/dns.rdtypes.IN.SRV.SRV-class.html> | Using [dnspython](http://www.dnspython.org/):
```
>>> import dns.resolver
>>> domain='jabberzac.org'
>>> srvInfo = {}
>>> srv_records=dns.resolver.query('_xmpp-client._tcp.'+domain, 'SRV')
>>> for srv in srv_records:
... srvInfo['weight'] = srv.weight
... srvInfo['host'] = str(srv.target).rstrip('.')
... srvInfo['priority'] = srv.priority
... srvInfo['port'] = srv.port
...
>>> print srvInfo
{'priority': 0, 'host': 'xmpp.jabberzac.org', 'port': 5222, 'weight': 0}
``` | How do I resolve an SRV record in Python? | [
"",
"python",
"networking",
"dns",
"srv",
""
] |
So I have been given the task to create a shipping module for a webshop system. It may be a bit overkill, but I would really like to create one that can figure out how to pack parcels in the most optimized way. Having learned programming simply by doing it, this is an area where I have no knowledge - yet! Anyways I can just give short description of the actual problem.
So when users buy stuff at webshops they will have x products in their cart with possibly varying sizes and weight. So I want to give that list of products to the function and let it figure out how these products should be packed in parcel(s).
* max length of parcel: 100
* max width of parcel: 50
* max height of parcel: 50
* max weight of parcel: 20
Every product has a weight, length, width and height as well.
Since parcels and products are basically boxes, I'm guessing this would be rather complex, as there are different ways of putting the products inside the parcel. My goal is not to make the perfect packaging function, but I would like to do something better than just putting products inside the parcel until a limit has been reached.
Now, I don't expect you guys to make this for me, but what I would like to ask is three things.
1. Where can I find good online resources that will teach me the basics needed?
2. Are there some native python tools that would be good to use?
3. Some pointers of what I need to be aware of, pitfalls etc
Like I said, I don't plan for this to be perfect and 100% optimized, but I would like to end up with something that will come close. I would hate if users feel that the sending fee will be a lot higher than it actual is. | The fact that you have height, length and width makes it harder than a simple knapsack problem. Here's an interesting discussion of a [3D knapsack problem](http://www.cirm.univ-mrs.fr/videos/2006/exposes/14/Thursday%20Morning/Diedrich.pdf).
Here's a [paper on the topic](http://books.google.com/books?id=mhrOkx-xyJIC&lpg=PA34&ots=1XEOcysErv&pg=PA34) by the same guys. | That’s your typical [knapsack problem](http://en.wikipedia.org/wiki/Knapsack_problem). Many solutions for different languages can be found at [Rosetta Code](http://www.rosettacode.org/wiki/Knapsack_Problem). | How to create an optimized 3D volume-packing function in python? | [
"",
"python",
"algorithm",
"optimization",
""
] |
I have a poorly designed class in a 3rd-party `JAR` and I need to access one of its **private** fields. For example,
why should I need to choose private field is it necessary?
```
class IWasDesignedPoorly {
private Hashtable stuffIWant;
}
IWasDesignedPoorly obj = ...;
```
How can I use reflection to get the value of `stuffIWant`? | In order to access private fields, you need to get them from the class's *declared* fields and then make them accessible:
```
Field f = obj.getClass().getDeclaredField("stuffIWant"); //NoSuchFieldException
f.setAccessible(true);
Hashtable iWantThis = (Hashtable) f.get(obj); //IllegalAccessException
```
**EDIT**: as has been commented by *aperkins*, both accessing the field, setting it as accessible and retrieving the value can throw `Exception`s, although the only *checked* exceptions you need to be mindful of are commented above.
The `NoSuchFieldException` would be thrown if you asked for a field by a name which did not correspond to a declared field.
```
obj.getClass().getDeclaredField("misspelled"); //will throw NoSuchFieldException
```
The `IllegalAccessException` would be thrown if the field was not accessible (for example, if it is private and has not been made accessible via missing out the `f.setAccessible(true)` line.
The `RuntimeException`s which may be thrown are either `SecurityException`s (if the JVM's `SecurityManager` will not allow you to change a field's accessibility), or `IllegalArgumentException`s, if you try and access the field on an object not of the field's class's type:
```
f.get("BOB"); //will throw IllegalArgumentException, as String is of the wrong type
``` | Try [`FieldUtils`](https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/reflect/FieldUtils.html#readField-java.lang.reflect.Field-java.lang.Object-boolean-) from Apache [commons-lang3](https://commons.apache.org/proper/commons-lang/):
```
FieldUtils.readField(object, fieldName, true);
```
P.S. In my opinion, [reflection is evil](https://www.yegor256.com/2022/06/05/reflection-means-hidden-coupling.html). | How to read the value of a private field from a different class in Java? | [
"",
"java",
"class",
"reflection",
"field",
"private",
""
] |
Given a table name, how do I extract a list of primary key columns and their datatypes from a plpgsql function? | The query above is very bad as it is really slow.
I would recommend this official version:
<http://wiki.postgresql.org/wiki/Retrieve_primary_key_columns>
if schema is needed the query is as follows
```
SELECT
pg_attribute.attname,
format_type(pg_attribute.atttypid, pg_attribute.atttypmod)
FROM pg_index, pg_class, pg_attribute, pg_namespace
WHERE
pg_class.oid = 'foo'::regclass AND
indrelid = pg_class.oid AND
nspname = 'public' AND
pg_class.relnamespace = pg_namespace.oid AND
pg_attribute.attrelid = pg_class.oid AND
pg_attribute.attnum = any(pg_index.indkey)
AND indisprimary
``` | To provide a straight bit of SQL, you can list the primary key columns and their types with:
```
SELECT c.column_name, c.data_type
FROM information_schema.table_constraints tc
JOIN information_schema.constraint_column_usage AS ccu USING (constraint_schema, constraint_name)
JOIN information_schema.columns AS c ON c.table_schema = tc.constraint_schema
AND tc.table_name = c.table_name AND ccu.column_name = c.column_name
WHERE constraint_type = 'PRIMARY KEY' and tc.table_name = 'mytable';
``` | How do I get the primary key(s) of a table from Postgres via plpgsql? | [
"",
"sql",
"postgresql",
"plpgsql",
""
] |
My class contains an object from Interop and calls a method on it which causes it to alloc stuff. It also exposes a method to free that stuff, so I expect I should call this in Dispose():
```
class MyClass : IDisposable
{
private DllName.ComClassName comInstance;
void SomeMethod()
{
comInstance = new DllName.ComClassName();
comInstance.AllocStuff();
}
public void Dispose()
{
comInstance.FreeThatStuff();
}
}
```
Now, I should expand all that to follow the Dispose pattern. I have no other disposable or unmanaged resources to release, so assuming comInstance is managed (isn't that what Interop does, wraps unmanaged into managed?), I think the pattern disolves to:
```
public void Dispose()
{
if (comInstance != null)
{
comInstance.FreeStuff();
comInstance = null;
}
}
```
Which leaks unless I explicitly call Dispose() on instances of MyClass, which would make the Dispose pattern flawed? So does that mean comInstance must be unmanaged, and the pattern disolves to:
```
public void Dispose()
{
DisposeComInstance();
GC.SuppressFinalize(this);
}
~MyClass()
{
DisposeComInstance();
}
private void DisposeComInstance()
{
if (comInstance != null)
{
comInstance.FreeStuff();
comInstance = null;
}
}
```
**EDIT:**
1. To avoid cluttering my class with the full pattern, could I just seal my class?
2. How do I know ComClassName (and in general any class) is unmanaged? | It looks like you've almost got it nailed. I would fall back to the pattern where you have a protected virtual Disposing that takes a boolean parameter indicating if managed items should be disposed of. That way somebody coming behind you will continue to [implement IDisposable properly](http://msdn.microsoft.com/en-us/library/ms244737(VS.80).aspx).
```
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
~MyClass()
{
this.Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
// if (disposing)
// {
// // Managed
// }
if (comInstance != null)
{
comInstance.FreeStuff();
comInstance = null;
}
// base.Dispose(disposing) if required
}
``` | Ultimately you want this kind of pattern:
```
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~MyClass()
{
Dispose(false);
}
private void Dispose(bool disposing)
{
if (disposing)
{
// Dispose of disposable objects here
}
// Other unmanaged cleanup here which will be called by the finalizer
if (comInstance != null)
{
comInstance.FreeStuff();
comInstance = null;
}
// Call base dispose if inheriting from IDisposable class.
base.Dispose(true);
}
```
For a great article on why, check out [Implementing IDisposable and the Dispose pattern properly.](http://www.codeproject.com/KB/cs/idisposable.aspx) | How do I implement the dispose pattern in c# when wrapping an Interop COM Object? | [
"",
"c#",
"interop",
"dispose",
""
] |
I don't understand the nature of Java Beans that well. Well, at least how I see them used in some code-bases that pass through our shop.
I found this question:
[Java Beans: What am I missing?](https://stackoverflow.com/questions/315142/java-beans-what-am-i-missing)
The accepted answer there makes it look like programmers tend to abuse Java Bean (which I really don't doubt), but I see it happen so often and so deliberately, I think I'm still missing something.
I see code that looks like:
```
public class FooBean {
private int a;
private int b;
private int c;
public int getA() { return a; }
public int setA(int x) { a = x; }
// etc...
}
```
No further structure or control than getters and setters. Is there some sort of super awesome compiler trick going on that involves reflection, getters and setters, and the need for some very awkward (but compiler optimized) static associative arrays?
Or maybe I'm *completely* missing the point. :\
Cheers!
**Edit:**
Definitely not promoting the idea of public fields, here. | Actually, yes, there is magic going on.
It's a really dumb pattern, but GUI beans (which all components are) were intended to be reflectively analyzed by a GUI builder. The public set/get fields are intended to be "Properties" that the user can muck with while building his GUI.
Edit: In defense of sun, I should say that although the pattern turned out to be pretty obnoxious because of all the people that copied it and started using it throughout their non-bean code, It did allow people to integrate classes with a GUI builder without using any outside meta-data. You didn't need any XML file or properties file for the editor, it was as easy as extending Button and dropping your new object onto the pallet.
This pattern has been used in other places and, as you noticed, it's pretty much the same as having public fields. I think it's one of the worst patters sun created when setting up java, but there were no other obvious solutions (I think the whole concept was kind of tacked on by the first people trying to build the first GUI builders before java's release).
Now there is a much better solution: using annotations to mark private fields, a reflective tool could still analyze them and bind them to the builder controls. This would be a good deal cleaner and not make all your objects so vulnerable to external state changes. | Java Beans are, as you point out, a fairly trivial coding convention.
The useful part is that they were a convention at all. This allowed auxiliary tools to be built which were based on (at the time) novel ideas like specifying exactly what the name of getters and setters were, and an expectation that specific methods would exist without needing to ascribe to an Interface. This allowed enough flexibility to do whatever you wanted, but still allowed you to use the GUI for assembling beans.
At this point, with full introspection being the norm, and other languages having formalized get/set functionality, and many other ways to do what Beans do, I think they're an idea whose time has passed. | Java Beans: Overglorified Associative Arrays? | [
"",
"java",
"reflection",
"javabeans",
""
] |
I have a static class representing a connection pool that I want to unit test using Visual Studio 2008's built-in unit testing framework. The static class has some constants in it, like for the maximum allowed connections. I want to decrease this value for my unit test so I don't have to have a lot of connections open in order to hit a test condition (specifically, the code for when the maximum allowed connections has been reached). Is there a way I can edit this constant just in the unit test? That doesn't seem possible to me.
One solution I have is to write another method for accessing the code to be tested, one that would take 'maximum allowed connections' as a parameter. That seems slightly dirty in that it modifies the code I want to test, even if only slightly; however, is there a better alternative? Here's some of my code, for reference:
```
internal static class ConnectionPool<T> where T : Connection, new()
{
private const int MAX_OBJECTS = 25;
private static int _totalConnections;
internal static T getConnection(bool testMode)
{
if (_totalConnections >= MAX_OBJECTS)
{
// Here's the code I want to test
}
}
}
``` | It occurred to me that there are two parts to the condition for the code being tested: the constant `MAX_OBJECTS` is one of them, true, but there is also `_totalConnections`. Using an accessor class, which Visual Studio generates for me to have access to private methods and variables within `ConnectionPool`, I can modify the value of `_totalConnections` in order to make the condition `if (_totalConnections >= MAX_OBJECTS)` true. In other words, I'll lie to the static class in my unit test so that I don't have to create `MAX_OBJECTS` connections in order to meet the condition. | No, you can't modify constant, but you can replace it with static readonly field and modify that field using reflection. | adjusting constants in static class for unit tests in C# | [
"",
"c#",
"unit-testing",
"constants",
""
] |
I have a string that contains a value of either TRUE or FALSE or null, this value is read from a text file which is outside of my control. What is the best way to use '|' with 'if'? Keeping in mind strValue could also be null, if strValue is null then I don't want to enter the if statement.
```
if (strValue == "FALSE" | strValue == "TRUE")
{
//do stuff
}
```
Thanks | I would seriously consider using `ToUpper` if it's out of your control - you never know when someone changes it to `"True"` or `"true"`.
```
if (strValue.ToUpper() == "FALSE" || strValue.ToUpper() == "TRUE") {
}
```
Regarding the responses about `ToUpper` and unnecessary defensive programming:
The original question said "read from a text file which is outside of my control", and "TRUE or FALSE or null". As far as I know there is no universal way of indicating NULL in text files. In CSV files, you could treat `,,` as `NULL` or `""` (empty string). In fixed width text files, you could treat all spaces as `NULL`, `""` or `"<some spaces>"`, for example.
So the OP has already done some data conversion/interpretation to get to this point. | ```
if (strValue == "FALSE" || strValue == "TRUE") {
// ...
}
```
to benefit from short circuiting. The second expression will not be tried if the first evaluates to `true`.
If you need case-insensitive comparisons:
```
if ("FALSE".Equals(strValue, StringComparison.InvariantCultureIgnoreCase) ||
"TRUE".Equals(strValue, StringComparison.InvariantCultureIgnoreCase)) {
// ...
}
```
Note that calling `.ToUpper()` or `.ToLower()` on `null` will throw `NullReferenceException`. | C# if (strValue == "FALSE" | strValue == "TRUE") | [
"",
"c#",
""
] |
In the .Net BCL is there a collection data structure similar to list that has a maximum capacity, say configured to 100 items, which when item 101 is added the original first item is popped/removed from the collection thus ensuring the item count never exceeds 100.
I’m using .net 3.5
Thanks in advance | What you are describing is a circular buffer. I use these occasionally and recently ported some older code into a genericised C# class (attached). This code is part of [SharpNeat V2 development](http://sharpneat.sourceforge.net/development.htm).
This has O(1) performance on add and remove oprations whereas the solution posted that encapsulates a List is O(n). This is because removing the 0th item in a list causes all other items to be shuffled down to fill the gap.
```
using System;
using System.Collections.Generic;
using System.Text;
namespace SharpNeat.Utility
{
///
/// This is a generic circular buffer of items of type T. A circular buffer must be assigned
/// a capacity at construction time. Items can be enqueued indefintely, but when the buffer's
/// capacity is reached the oldest values in the buffer are overwritten, thus the buffer is best
/// thought of as a circular array or buffer.
///
public class CircularBuffer
{
///
/// Internal array that stores the circular buffer's values.
///
protected T[] _buff;
///
/// The index of the previously enqueued item. -1 if buffer is empty.
///
protected int _headIdx;
///
/// The index of the next item to be dequeued. -1 if buffer is empty.
///
protected int _tailIdx;
#region Constructors
///
/// Constructs a circular buffer with the specified capacity.
///
///
public CircularBuffer(int capacity)
{
_buff = new T[capacity];
_headIdx = _tailIdx = -1;
}
#endregion
#region Properties
///
/// Gets the number of items in the buffer. Returns the buffer's capacity
/// if it is full.
///
public int Length
{
get
{
if(_headIdx == -1)
return 0;
if(_headIdx > _tailIdx)
return (_headIdx - _tailIdx) + 1;
if(_tailIdx > _headIdx)
return (_buff.Length - _tailIdx) + _headIdx + 1;
return 1;
}
}
#endregion
#region Public Methods
///
/// Clear the buffer.
///
public virtual void Clear()
{
_headIdx = _tailIdx = -1;
}
///
/// Enqueue a new item. This overwrites the oldest item in the buffer if the buffer
/// has reached capacity.
///
///
public virtual void Enqueue(T item)
{
if(_headIdx == -1)
{ // buffer is currently empty.
_headIdx = _tailIdx = 0;
_buff[0] = item;
return;
}
// Determine the index to write to.
if(++_headIdx == _buff.Length)
{ // Wrap around.
_headIdx = 0;
}
if(_headIdx == _tailIdx)
{ // Buffer overflow. Increment tailIdx.
if(++_tailIdx == _buff.Length)
{ // Wrap around.
_tailIdx=0;
}
_buff[_headIdx] = item;
return;
}
_buff[_headIdx] = item;
return;
}
///
/// Remove the oldest item from the back end of the buffer and return it.
///
///
public virtual T Dequeue()
{
if(_tailIdx == -1)
{ // buffer is currently empty.
throw new InvalidOperationException("buffer is empty.");
}
T item = _buff[_tailIdx];
if(_tailIdx == _headIdx)
{ // The buffer is now empty.
_headIdx=_tailIdx=-1;
return item;
}
if(++_tailIdx == _buff.Length)
{ // Wrap around.
_tailIdx = 0;
}
return item;
}
///
/// Pop the most recently added item from the front end of the buffer and return it.
///
///
public virtual T Pop()
{
if(_tailIdx == -1)
{ // buffer is currently empty.
throw new InvalidOperationException("buffer is empty.");
}
T item = _buff[_headIdx];
if(_tailIdx == _headIdx)
{ // The buffer is now empty.
_headIdx = _tailIdx =- 1;
return item;
}
if(--_headIdx==-1)
{ // Wrap around.
_headIdx=_buff.Length-1;
}
return item;
}
#endregion
}
}
``` | There is no such collection available but one is fairly easy to write. The best way to do this is to create a new collection type that encapsulates an existing collection type.
For example
```
public class FixedSizeList<T> : IList<T> {
private List<T> _list = new List<T>();
private int _capacity = 100;
public void Add(T value) {
_list.Add(value);
while ( _list.Count > _capacity ) {
_list.RemoveAt(0);
}
}
// Rest omitted for brevity
}
```
A couple of answers suggested inheritance as a mechanism. This is certainly not a good route especially if you are deriving from one of the generic collections. These collections are not designed to be inherited from and it is very easy to accidentally circumvent any checks you make an capacity as the result of an Add or Remove method.
The primary reason is that these methods are not virtual so they cannot be overridden. You would be forced to either declare an Add method with a different name (thus confusing your users) or re-declare Add with the new syntax. The latter is a very unsafe because as soon as an instance of your class is passed to a reference of the base type, all of your methods will not be called and the list can grow past capacity.
**EDIT**
As the comment section discussion has indicated, implementing `List<T>` is not the best approach here. The reason why is that it violates the substitution principle in several cases. The easiest way to display the problem is imagine if my implementation was passed to the following method. This code should pass for any `IList<T>` implementation but would fail in this case if the list was at capacity.
```
public void Example<T>(IList<T> list, T value) {
var count = list.Count;
list.Add(value);
var addedValue = list[count];
}
```
The only collection interface that can be validly implemented for the specified collection is `IEnumerable<T>`. I've left my implementation up there as an example. But see ShuggyCoUk's answer for an `IEnumerable<T>` implementation:
* [Maximum capacity collection in c#](https://stackoverflow.com/questions/1213317/maximum-capacity-collection-in-c/1213761#1213761) | Maximum capacity collection in c# | [
"",
"c#",
".net",
""
] |
I have a class that has 3 string properties. I want to store these in a list so that when I make changes to the strings of the list they also get updated in the class.
This would be easy to do if I was using class object, but string seems to behave differently. It seems to make a copy of the object for the list rather then have a pointer to the object. How am I supposed to do this is C#? If this is not possible is there a better way? | The problem with `string`s is that they are immutable. In other words, you can never change a `string` once it is created.
Thus, if you want to 'change' a `string`, you must remove the original from the `List`, and store the result back into the list. Example:
```
string a = "abcdefg";
List<String> list = new List<String>();
list.add(a);
a = a.Substring(0, 5);
```
That code does nothing because the `string` `a` is pointing to never changes. It just points to a new `string`. | In .NET, strings are immutable. If you change the string, you are in fact creating a new one and modifying the reference.
I would consider using a [StringBuilder](http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx) object to address your problem. | Store a reference to a string | [
"",
"c#",
"string",
""
] |
I Have something similar to this setup:
```
public class Base {
public String getApple() {return "base apple"};
}
public class Extended extends Base{
public String getApple() {return "extended apple"};
}
```
Somewhere else in the code I have this:
```
{
Base b = info.getForm();
if (b instanceof Extended){
b = (Extended) b;
}
System.out.println(b.getApple()); // returns "base apple" even when if clause is true why??
}
```
How do I accomplish that? | First:
```
if (b instanceof Extended){
b = (Extended) b;
}
```
does absolutely nothing. You are basically saying `b = b`, which says nothing. You are not even changing the reference.
Second, `getApple()` will always be dynamically bound, and the "extended apple" should always be called - given that the subclass is truly extending the base class, and the method is truly overridden.
Basically what you need to do, in order to accomplish correct `getApple()` behavior:
* remove the if clause. it does nothing.
* make sure your class is indeed extending the base class
* make sure the `getApple()` method is overriding the base class method. (use the `@override` annotation if you are not sure) | As written, your code will not compile, which makes me think that your problem is elsewhere. Your return statements don't have semicolons at the end of them. Rather, they appear after the `}`. It's possible you had some other problem (maybe your subclass misspelled getApple()), but you're still using your old class files because your new stuff isn't compiling.
This code works:
```
class Base {
public String getApple() { return "base apple"; }
}
class Extended extends Base {
public String getApple() { return "extended apple"; }
}
public class Test {
public static void main(String[] args) {
Base b = new Extended();
System.out.println(b.getApple());
}
}
```
Console:
```
#javac Test.java
#java Test
extended apple
``` | Java Inheritance Question | [
"",
"java",
"inheritance",
""
] |
I need to create an instance of an object and the type of that object will be determined at run time. The type of the object is pulled from SQL and set to a string value. I also need to pass a number of parameters when instantiating it. The number/type of parameters will be the same every time (for now at least). What do I need to use to accomplish this, Activator.CreateInstance? Any help would be appreciated.
```
private void StartScans(int scan_typeid, SqlDataReader drActiveServers)
{
string sql = "SELECT scan_typeclass from scan_types WHERE scan_typeid = " + scan_typeid.ToString();
sqlconn.Open();
SqlCommand cmd = new SqlCommand(sql, sqlconn);
SqlDataReader drScanClass = cmd.ExecuteReader(CommandBehavior.CloseConnection);
string scan_class = drScanClass["scan_typeclass"].ToString();
//Create object here
}
```
EDIT:
Richard Berg's solution worked in a console app but not in the above example, I've dumped scan\_class and verified its getting a value however I keep getting this error:
System.ArgumentNullException: Value cannot be null.
Parameter name: type
Here's what my updated code looks like:
```
try
{
string sql = "SELECT scan_typeclass from scan_types WHERE scan_typeid = " + scan_typeid.ToString();
sqlconn3.Open();
SqlCommand cmd = new SqlCommand(sql, sqlconn3);
SqlDataReader drScanClass = cmd.ExecuteReader();
drScanClass.Read();
string scan_class = drScanClass["scan_typeclass"].ToString();
var type = Type.GetType(scan_class);
var myObj = Activator.CreateInstance(type, scan_id, scan_name, interval, drActiveServers);
}
catch (Exception e)
{
string sSource = "SharedAuditSVC";
string sLog = "Application";
string sEvent = e.ToString();
if (!EventLog.SourceExists(sSource))
EventLog.CreateEventSource(sSource, sLog);
EventLog.WriteEntry(sSource, sEvent);
EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Warning, 0);
}
```
---
Meh, I think it's scope related though I have had no success calling my custom class through this method. I'll sleep on it.. :)
Works:
```
WindowsServiceAudit WSA = new WindowsServiceAudit(scan_id, scan_name, interval, drActiveServers);
```
Doesn't work:
```
string scan_class = "WindowsServiceAudit";
var type = Type.GetType(scan_class);
var myObj = Activator.CreateInstance(type, scan_id, scan_name, interval, drActiveServers);
``` | Yes, exactly.
```
var type = Type.GetType(scan_class);
var myObject = Activator.CreateInstance(type, constructorArg1, constructorArg2, [...] );
// use myObject - you'll have to reflect on any properties that aren't derived from System.Object
```
**EDIT**
If the constructor is static or non-public, or the parameters you're passing create ambiguity in the constructors' overload resolution, then you'll need to use MethodInfo.Invoke() instead of Activator.CreateInstance().
```
var scan_class = "WindowsServiceAudit";
var bindingFlags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
var constructorArgs = new object[] { scan_id, scan_name, interval, drActiveServers };
var constructorTypes = from p in constructorArgs select p.GetType();
var type = Type.GetType(scan_class);
var method = type.GetMethod(scan_class, bindingFlags, System.Type.DefaultBinder, constructorTypes.ToArray(), null);
var myObject = method.Invoke(null, bindingFlags, System.Type.DefaultBinder, constructorArgs, CultureInfo.CurrentCulture);
```
Also make sure that:
1. The type name is fully qualified. Reflection doesn't know anything about "using" statements.
2. The assembly where the type resides is loaded. Use Assembly.Load() if necessary. | The constructor is not static and is public. I tried Richard's second suggestion with no luck, another null object error.
System.NullReferenceException: Object reference not set to an instance of an object.
at SharedAuditSVC.Scan.StartScans(Int32 scan\_id, String scan\_name, Int32 scan\_typeid, Int32 interval, SqlDataReader drActiveServers) in C:\shared\_audit\SVC\SharedAuditSVC\SharedAuditSVC\Scan.cs:line 84
line 84 is:
```
var method = type.GetMethod(scan_class, bindingFlags, System.Type.DefaultBinder, constructorTypes.ToArray(), null);
```
I'm obviously doing something horribly wrong as it's not getting type of "WindowsServiceAudit". The project is a Windows Service, my question involves 2 of the .cs source files, Scan.cs and WindowsServiceAudit.cs. Scan.cs is where all my code snippets are being pulled from, WindowsServiceAudit is the class I'm trying to instantiate.
```
namespace SharedAuditSVC
{
class Scan
{
namespace SharedAuditSVC
{
public class WindowsServiceAudit
{
```
Both are part of the same namespace so it really has me confused. I also tried referencing it as SharedAuditSVC.WindowsServiceAudit
Again to be clear I can create it just fine by doing the following:
```
WindowsServiceAudit WSA = new WindowsServiceAudit(scan_id, scan_name, interval, drActiveServers);
``` | c# .NET runtime object type | [
"",
"c#",
".net",
"reflection",
""
] |
I'm communicating with a SOAP service created with EJB -- it intermittently fails, and I've found a case where I can reliably reproduce.
I'm getting a funky ass SOAP fault that says "looks like we got not XML," however, when retrieving the last response I get what is listed below (and what looks like valid XML to me).
Any thoughts?
**Soap Fault:**
```
object(SoapFault)#2 (9) {
["message:protected"]=> string(33) "looks like we got no XML document"
["string:private"]=> string(0) ""
["code:protected"]=> int(0)
["file:protected"]=> string(40) "/Users/josh/Sites/blahblahblah/test-update.php"
["line:protected"]=> int(26)
["trace:private"]=> array(2) {
[0]=> array(4) {
["function"]=> string(6) "__call"
["class"]=> string(10) "SoapClient"
["type"]=> string(2) "->"
["args"]=> array(2) {
[0]=> string(24) "UpdateApplicationProfile"
[1]=> array(1) {
[0]=> array(2) {
["suid"]=> string(36) "62eb56ee-45de-4971-9234-54d72bbcd0e4"
["appid"]=> string(36) "6be2f269-4ddc-48af-9d47-30b7cf3d0499"
}
}
}
}
[1]=> array(6) {
["file"]=> string(40) "/Users/josh/Sites/blahblahblah/test-update.php"
["line"]=> int(26)
["function"]=> string(24) "UpdateApplicationProfile"
["class"]=> string(10) "SoapClient"
["type"]=> string(2) "->"
["args"]=> array(1) {
[0]=> array(2) {
["suid"]=> string(36) "62eb56ee-45de-4971-9234-54d72bbcd0e4"
["appid"]=> string(36) "6be2f269-4ddc-48af-9d47-30b7cf3d0499"
}
}
}
}
["faultstring"]=> string(33) "looks like we got no XML document"
["faultcode"]=> string(6) "Client"
["faultcodens"]=> string(41) "http://schemas.xmlsoap.org/soap/envelope/"
}
```
**And the actual raw XML response using client->\_\_getLastResponse():**
```
<env:Envelope xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'>
<env:Header>
</env:Header>
<env:Body>
<ns2:UpdateApplicationProfileResponse xmlns:ns2="blahblahblah">
<paramname>status</paramname>
<paramname>location</paramname>
<paramname>timezone</paramname>
<paramname>homepage</paramname>
<paramname>nickname</paramname>
<paramname>firstName</paramname>
<paramname>languages</paramname>
<paramname>color</paramname>
<paramname>lastName</paramname>
<paramname>gender</paramname>
<paramvalue></paramvalue>
<paramvalue></paramvalue>
<paramvalue></paramvalue>
<paramvalue></paramvalue>
<paramvalue>XXX XXX</paramvalue>
<paramvalue>XXX</paramvalue>
<paramvalue></paramvalue>
<paramvalue>CA0008</paramvalue>
<paramvalue>XXX</paramvalue>
<paramvalue></paramvalue>
</ns2:UpdateApplicationProfileResponse>
</env:Body>
</env:Envelope>
``` | Yeah, so the problem has SOMETHING to do with a piece of bad character data or something being passed in one of the paramvalue children. It DOESN'T appear to be visible, or its stripped, even using the trace and \_\_getLastRequest().
I unfortunately don't have direct access to the server code. Its outputted directly from a WS created using EJB -- the developer has no access to the XML itself, so there is no stray whitespace. Doesn't appear to be any whitespace at all -- certainly is no whitespace using \_\_getLastRequest(), though that was a great place to look for the cause of the error, according to comments on the php page for SoapClient.
I solved the problem by basically ignoring the bad call, and "resetting" each of the paramnames and paramvalues, such that I wipe out the bad data...
Anyway, bummer that I didn't explicitly figure out what was causing it, but disaster averted for the moment.
Edit: Solved this since
A control character was slipping in to xml returned by the EJB framework. It was supposed to be null, so it used a control character to represent it, and php SOAP barfed because its not "valid" xml. I resolved the problem by writing a manual parse of the response using \_\_getLastRequest() in the case of an exception. | Hard to tell here; Couple of things you might check:
* make sure there is no (absolutely none) white space either at the beginning or the end of the XML/SOAP data
* maybe there could be some error that is echoed to the standard output (i.e., before/after the SOAP data?)
What kind of output do you get if you try to call the Webservice's URL from your browser?
*(It would do much, as you won't be using SOAP but it should say something like "Bad request")*
Do you get any kind of trace on the server side, that could indicate there's been an error/a problem/whatever might be useful?
If there is still no way to find anything, last time I worked with web services and got errors I could not find why, I ended up using ethereal (now called Wireshark) to "sniff" what was going on on the network. Sometimes helps, but I hate doing that. | SOAP PHP Parsing Error? | [
"",
"php",
"xml",
"soap",
""
] |
Is there a way to see if a field exists in an IDataReader-based object w/o just checking for an IndexOutOfRangeException?
In essence, I have a method that takes an IDataReader-based object and creates a strongly-typed list of the records. In 1 instance, one data reader has a field that others do not. I don't really want to rewrite all of the queries that feed this method to include some form of this field if I don't have to. The only way I have been able to figure out how to do it so far is to throw the 1 unique field into a try/catch block as shown below.
```
try
{
tmp.OptionalField = reader["optionalfield"].ToString();
}
catch (IndexOutOfRangeException ex)
{
//do nothing
}
```
Is there a cleaner way short of adding the "optional field" to the other queries or copying the loading method so 1 version uses the optional field and the other doesn't?
I'm in the 2.0 framework also. | I ended up finding a solution using the `reader.GetName(int)` method. I created the below method to encompass the logic.
```
public bool ColumnExists(IDataReader reader, string columnName)
{
for (int i = 0; i < reader.FieldCount; i++)
{
if (reader.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
}
return false;
}
``` | The following will give you a list of the column name strings given a data reader.
(Remember the results are based on the last read so it may not be the same depending on what the reader read).
```
var cols = reader.GetSchemaTable()
.Rows
.OfType<DataRow>()
.Select(row => row["ColumnName"]);
```
Or to check if a column exists:
```
public bool ColumnExists(IDataReader reader, string columnName)
{
return reader.GetSchemaTable()
.Rows
.OfType<DataRow>()
.Any(row => row["ColumnName"].ToString() == columnName);
}
``` | Checking to see if a column exists in a data reader | [
"",
"c#",
"idatareader",
""
] |
Suppose that I have class `C`.
I can write `o = C()` to create an instance of `C` and assign it to `o`.
However, what if I want to assign the class itself into a variable and then instantiate it?
For example, suppose that I have two classes, such as `C1` and `C2`, and I want to do something like:
```
if (something):
classToUse = C1
else:
classToUse = C2
o = classToUse.instantiate()
```
What's the syntax for the actual `instantiate()`? Is a call to `__new__()` enough? | ```
o = C2()
```
This will accomplish what you want. Or, in case you meant to use classToUse, simply use:
```
o = classToUse()
```
Hope this helps. | You're almost there. Instead of calling an instantiate() method, just call the variable directly. It's assigned to the class, and classes are callable:
```
if (something):
classToUse = C1
else:
classToUse = C2
o = classToUse()
``` | In Python, what's the correct way to instantiate a class from a variable? | [
"",
"python",
"instantiation",
""
] |
I am refactoring a class so that the code is testable (using NUnit and RhinoMocks as testing and isolations frameworks) and have found that I have found myself with a method is dependent on another (i.e. it depends on something which is created by that other method). Something like the following:
```
public class Impersonator
{
private ImpersonationContext _context;
public void Impersonate()
{
...
_context = GetContext();
...
}
public void UndoImpersonation()
{
if (_context != null)
_someDepend.Undo();
}
}
```
Which means that to test `UndoImpersonation`, I need to set it up by calling `Impersonate` (Impersonate already has several unit tests to verify its behaviour). This smells bad to me but in some sense it makes sense from the point of view of the code that calls into this class:
```
public void ExerciseClassToTest(Impersonator c)
{
try
{
if (NeedImpersonation())
{
c.Impersonate();
}
...
}
finally
{
c.UndoImpersonation();
}
}
```
I wouldn't have worked this out if I didn't try to write a unit test for `UndoImpersonation` and found myself having to set up the test by calling the other public method. So, is this a bad smell and if so how can I work around it? | Code smell has got to be one of the most *vague* terms I have ever encountered in the programming world. For a group of people that pride themselves on engineering principles, it ranks right up there in terms of unmeasurable rubbish, and about as useless a measure, as LOCs per day for programmer efficiency.
Anyway, that's my rant, thanks for listening :-)
To answer your specific question, I don't believe this *is* a problem. If you test something that has pre-conditions, you need to ensure the pre-conditions have been set up first for the given test case.
One of the tests should be what happens when you call it *without* first setting up the pre-conditions - it should either fail gracefully or set up it's own pre-condition if the caller hasn't bothered to do so. | Well, there is a bit too little context to tell, it looks like \_someDepend should be initalized in the constructor.
Initializing fields in an instance method is a big NO for me. A class should be fully usable (i.e. all methods work) as soon as it is constructed; so the constructor(s) should initialize all instance variables. See e.g. the page on [single step construction](http://www.c2.com/cgi/wiki?SingleStepConstructor) in Ward Cunningham's wiki.
The reason initializing fields in an instance method is bad is mainly that it imposes an implicit ordering on how you can call methods. In your case, TheMethodIWantToTest will do different things depending on whether DoStuff was called first. This is generally not something a user of your class would expect, so it's bad :-(.
That said, sometimes this kind of coupling may be unavoidable (e.g. if one method acquires a resource such as a file handle, and another method is needed to release it). But even that should be handled within one method if possible.
What applies to your case is hard to tell without more context. | Is it a code smell for one method to depend on another? | [
"",
"c#",
"unit-testing",
"tdd",
""
] |
Which is the greatest, cheapest application in PHP that I can buy to import Gmail, Yahoo, MSN, Facebook, Twitter contacts from my user's accounts if they wish to invite their friends?
I have gone through:
<http://www.improsys.com/importer.htm>
<http://www.octazen.com/demo.php>
and
<http://www.iplussoft.com/product/iplusinvite_pricing>
Octazen looks awesome but wants excess of $320 for an all in solution. I don't want to spend that much.
All you PHP programmers out there you may have needed to build of integrate a similar app, I need to know which is the best PHP readymade app for this?
Any help would be appreciated and I'll smile with each answer - this should be your biggest incentive to find me something amazing :) | a quick google search gave [openinviter](http://openinviter.com) which should do what you want for free (open source) | open inviter is what you are looking for ... and guess what its free !!! and support almost every thing .... even the dead site hi5 !! | Gmail,Yahoo, Facebook, Twitter contacts importer in PHP | [
"",
"php",
"facebook",
"twitter",
"gmail",
"contacts",
""
] |
I have an AddIn which I want to invoke through Excel interop from a C# winforms application.
I can't get the addin etc. to load unless I uninstall and resinstall it each time (this is apparantly something to do with [Excel not loading addins when you use interop](http://support.microsoft.com/kb/213489) - btw, can't get their example to work in C#). Unfortunately this is slow and annoying to the user so I need to streamline it.
I want to have one instance of Excel but load an already installed addin without forcing this install/reinstall problem.
I've searched and searched but everything I find on google gives the solution to install/reinstall. Is there any other way? The add-in is installed, I just want excel to load it.
This is what I am doing at the moment (taken from google'd advice):
```
// loop over the add-ins and if you find it uninstall it.
foreach (AddIn addIn in excel.AddIns)
if (addIn.Name.Contains("My Addin"))
addin.Installed = false;
// install the addin
var addin = excel.AddIns.Add("my_addin.xll", false);
addin.Installed = true;
``` | After a while I found the answer hidden in strange places in the [MS help](http://support.microsoft.com/default.aspx?scid=kb;en-us;270844): and [this blog post](http://toadcode.blogspot.com/2008/04/excel-xirr-and-c.html).
That isn't all the info you need though. Things to note: you must have at least one workbook open or otherwise Excel barfs. Here's some rudementry code to get started:
```
var excel = new Application();
var workbook = excel.workbooks.Add(Type.Missing);
excel.RegisterXLL(pathToXll);
excel.ShowExcel();
```
If you want you can close the temporary workbook (if you've run some macros etc.) and remember to tidy everything up with plenty of calls to Marshal.ReleaseComObject! | It seems that you have to get the correct Excel process to work with. Use this class to open the Excel document:
```
class ExcelInteropService
{
private const string EXCEL_CLASS_NAME = "EXCEL7";
private const uint DW_OBJECTID = 0xFFFFFFF0;
private static Guid rrid = new Guid("{00020400-0000-0000-C000-000000000046}");
public delegate bool EnumChildCallback(int hwnd, ref int lParam);
[DllImport("Oleacc.dll")]
public static extern int AccessibleObjectFromWindow(int hwnd, uint dwObjectID, byte[] riid, ref Window ptr);
[DllImport("User32.dll")]
public static extern bool EnumChildWindows(int hWndParent, EnumChildCallback lpEnumFunc, ref int lParam);
[DllImport("User32.dll")]
public static extern int GetClassName(int hWnd, StringBuilder lpClassName, int nMaxCount);
public static Application GetExcelInterop(int? processId = null)
{
var p = processId.HasValue ? Process.GetProcessById(processId.Value) : Process.Start("excel.exe");
try
{
Thread.Sleep(5000);
return new ExcelInteropService().SearchExcelInterop(p);
}
catch (Exception)
{
Debug.Assert(p != null, "p != null");
return GetExcelInterop(p.Id);
}
}
private bool EnumChildFunc(int hwndChild, ref int lParam)
{
var buf = new StringBuilder(128);
GetClassName(hwndChild, buf, 128);
if (buf.ToString() == EXCEL_CLASS_NAME) { lParam = hwndChild; return false; }
return true;
}
private Application SearchExcelInterop(Process p)
{
Window ptr = null;
int hwnd = 0;
int hWndParent = (int)p.MainWindowHandle;
if (hWndParent == 0) throw new Exception();
EnumChildWindows(hWndParent, EnumChildFunc, ref hwnd);
if (hwnd == 0) throw new Exception();
int hr = AccessibleObjectFromWindow(hwnd, DW_OBJECTID, rrid.ToByteArray(), ref ptr);
if (hr < 0) throw new Exception();
return ptr.Application;
}
}
```
Use the class in your application like this:
```
static void Main(string[] args)
{
Microsoft.Office.Interop.Excel.Application oExcel = ExcelInteropService.GetExcelInterop();
foreach (AddIn addIn in oExcel.AddIns)
{
addIn.Installed = true;
}
}
``` | How to load an Excel Addin using Interop | [
"",
"c#",
"excel",
"interop",
""
] |
I have this generic list that is being cached in memory. How can I manually during testing release that object from the cache? I cleared cache on the browser but still when I refresh I get the same set of products becuase it's checking my cached object in my database retrieval method. | coffeeaddict you need to implement cache expiration and removal in order for your app to use updated data. If you're using your own caching implementation make sure you invalidate that cached data every time you update the persistent one, so the next time you request it it'll go up full path and cache it in-memory again. | You are confusing the browser's cache (on the client machine) with server-side caching. | How to release objects from memory | [
"",
"c#",
"asp.net",
""
] |
I have a div as such:
```
<div style="overflow-y: scroll; height: 260px">
```
I contains a few hundred records and allows me to select an item to populate a formview control below it.
The problem is that when the page posts-back, the scroller position goes back to the top of the div. I want to try and maintain its position so that the selected record is still visible.
Any ideas? | Place something like:
```
<asp:HiddenField id="hdnScrollPos" runat="server"/> in your aspx.
```
Then, some javascript like:
```
var hdnScroll = document.getElementById(<%=hdnScrollPos.ClientID%>);
var bigDiv = document.getElementById('bigDiv');
bigDiv.onscroll = function() {
hdnScroll.value = bigDiv.scrollTop;
}
window.onload = function () {
bigDiv.scrollTop = hdnScroll.value;
}
``` | Here is a more refined way of FlySwat's solution using JQuery which worked for me:
```
var $ScrollPosition = $('#hfScrollPosition');
var $ScrollingDiv = $('#pnlGroupDataContent');
if ($ScrollPosition.length && $ScrollingDiv.length) {
// Store scrolling value
$ScrollingDiv.scroll(function () {
$ScrollPosition.val($ScrollingDiv.scrollTop());
});
// Set scrolling
$ScrollingDiv.scrollTop($ScrollPosition.val());
}
``` | Maintain scroller position on Div after page postback (ASP.NET) | [
"",
"asp.net",
"javascript",
""
] |
I'm making an edit button which pops up a modal box with a form to edit it. jQuery then sends this form to my server and I get a JSON response back. However, due to my bubbling issue, if I click on, for example, all of the edit buttons and then click on the last one and change a field, it does it across all of them.
```
$('.edit').click(function(event){
//more code...
modal_submit(the_id);
event.stopPropagation();
});
```
and then the submit event:
```
function modal_submit(the_id){
$('#modal form').submit(function(){
//This will alert every time I have EVER clicked on an edit button
alert(the_id);
return false;
});
```
}
finally all of this is inside of a getScript:
```
$.getScript('js/edit.js',function(){
create_edit_btn();
```
});
I've only used this 1 other time, and it worked, but I also had to do this.event.stopPropagation, but if I do "this" now it says this.event is undefined, but like I said, this exact code worked before for another script I did.
Does anyone have any ideas? :\
EDIT:
```
the html is:
<li>
<input id="item1" type="checkbox" value="webhosting|15" title="Web Hosting">
<p>Hosting for your web site</p>
</li>
``` | An event can have multiple event listeners. Each time you use $(element).submit(whateverFunction) you are adding another whateverFunction to the submit event. If you only want only the last listener to be the action that is taken upon envoking the event, try doing this:
```
function modal_submit(the_id){
$('#modal form').unbind(); // this will remove all other event listeners from this element
$('#modal form').submit(function(){
//This will alert every time I have EVER clicked on an edit button
alert(the_id);
return false;
});
``` | I think you event.stoppropagation does its job already. It stopped all the bubbling on the click event of the button (ie, if you try checking the document body, it won't have mouse click event anymore). The reason why codes within submit of the form is still executed, is because this is called by the button's default action.
Together with event.stoppropagation(), I suggest you include this:
```
event.preventDefault();
```
So that the default action will not used and only the codes within your handler is executed. | jQuery / JavaScript Bubbling and stopPropagation doesn't work | [
"",
"javascript",
"jquery",
"debugging",
"events",
"onclick",
""
] |
Is there a way to return the difference between two arrays in JavaScript?
For example:
```
var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];
// need ["c", "d"]
``` | This answer was written in 2009, so it is a bit outdated, also it's rather educational for understanding the problem. Best solution I'd use today would be
```
let difference = arr1.filter(x => !arr2.includes(x));
```
(credits to other author here)
I assume you are comparing a normal array. If not, you need to change the *for* loop to a *for .. in* loop.
```
function arr_diff (a1, a2) {
var a = [], diff = [];
for (var i = 0; i < a1.length; i++) {
a[a1[i]] = true;
}
for (var i = 0; i < a2.length; i++) {
if (a[a2[i]]) {
delete a[a2[i]];
} else {
a[a2[i]] = true;
}
}
for (var k in a) {
diff.push(k);
}
return diff;
}
console.log(arr_diff(['a', 'b'], ['a', 'b', 'c', 'd']));
console.log(arr_diff("abcd", "abcde"));
console.log(arr_diff("zxc", "zxc"));
``` | [`Array.prototype.includes()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) (ES2016/ ES7) comes in handy here.
---
### Intersection
```
let intersection = arr1.filter(x => arr2.includes(x));
```
[](https://i.stack.imgur.com/uasoX.png)
Yields values which are present in both `arr1` and `arr2`.
* `[1,2,3]` and `[2,3]` will yield `[2,3]`
* `[1,2,3]` and `[2,3,5]` will *also* yield `[2,3]`
---
### Difference
(Values in just A.)
```
let difference = arr1.filter(x => !arr2.includes(x));
```
[](https://i.stack.imgur.com/mEtro.png)
Yields values that are present in just `arr1`.
* `[1,2,3]` and `[2,3]` will yield `[1]`
* `[1,2,3]` and `[2,3,5]` will *also* yield `[1]`
---
### Symmetric Difference
```
let symDifference = arr1.filter(x => !arr2.includes(x))
.concat(arr2.filter(x => !arr1.includes(x)));
```
[](https://i.stack.imgur.com/zb1hW.png)
Yields values that are *only* in `arr1` or `arr2`, **but not both** ("exclusive or").
This is what you get if you take the difference of both arrays with each other, and combine the two results (You get an array containing all the elements of `arr1` that are not in `arr2` and vice-versa).
* `[1,2,3]` and `[2,3]` will yield `[1]`
* `[1,2,3]` and `[2,3,5]` will yield `[1,5]`
---
As [@Joshaven Potter pointed out on his answer](https://stackoverflow.com/a/4026828), you can assign this directly to `Array.prototype` so it can be used directly on arrays like this:
```
Array.prototype.diff = function(arr2) {
return this.filter(x => !arr2.includes(x));
}
```
```
[1, 2, 3].diff([2, 3]) // [1]
``` | How to get the difference between two arrays in JavaScript? | [
"",
"javascript",
"arrays",
"array-difference",
""
] |
I have a stored proc (called sprocGetArticles) which returns a list of articles from the articles table. This stored proc does not have any parameters.
Users can leave comments for each article and I store these comments in the comments table linked by the article id.
Is there any way I can do a comment count for each articleid in the returned list from within the sprocGetArticles stored procedure so I only have to make one call to the database?
My problem is that i need the article id to do the count which I seem unable to declare.
Is this the best approach anyway? | One option no one has mentioned so far would be a **computed column** on your article table which would count the number of comments. This is in general much faster than actually computing the number of comments everytime around, and if you really need to query that number frequently, it could save you a lot of processing overhead!
In SQL Server 2005 and up, what you could do in this case is create a small stored function to count the number of comments for each article, and then add this as a computed column to your article table. You could then use that as a normal column and trust me - it's a lot quicker than using subqueries all the time!
```
CREATE FUNCTION dbo.CountComments(@ArticleID INT)
RETURNS INT
WITH SCHEMABINDING
AS BEGIN
DECLARE @ArticleCommentCount INT
SELECT @ArticleCommentCount = COUNT(*)
FROM dbo.ArticleComments
WHERE ArticleID = @ArticleID
RETURN @ArticleCommentCount
END
GO
```
Add this to your article table as a column:
```
ALTER TABLE dbo.Articles
ADD CommentCount AS dbo.CountComments(ArticleID)
```
and from then on, just use it as a normal column:
```
SELECT ArticleID, ArticleTitle, ArticlePostDate, CommentCount
FROM dbo.Articles
```
To make it even faster, you could add this column as a persisted column to your table, and then it really rocks! :-)
```
ALTER TABLE dbo.Articles
ADD CommentCount AS dbo.CountComments(ArticleID) PERSISTED
```
It's a bit more work upfront, but if you need this often and all the time, it could be well worth the trouble! Also works great for e.g. reading out certain bits of information from a XML column stored in your database table and expose it as a regular INT column or whatever.
Highly recommend! It's a feature often overlooked in SQL Server.
Marc | SQL allows entire scalar [subqueries](http://msdn.microsoft.com/en-us/library/ms189575.aspx) to be returned as projected columns. Subqueries can be [correlated](http://msdn.microsoft.com/en-us/library/ms187638.aspx) with the parent query. So is easy to count the comments in a subquery that counts the comments for a given article id:
```
SELECT a.*, (
SELECT COUNT(*)
FROM Comments c
WHERE c.article_id = a.article_id) AS CountComments
FROM Articles a;
```
Note that counting the comments each time can be quite expensive, is better to keep the count as an Article property. | How do a sql count on an additional table inside a sql stored proc? | [
"",
"sql",
""
] |
In reporting tools like Crystal Reports, there are ways to take denormalized data and group it by a particular column in the data, creating row headings for each unique item in the specified column.
If I have this:
```
Category1 Data1
Category1 Data2
Category1 Data3
Category2 Data4
Category2 Data5
Category2 Data6
```
The reporting software will group it like this:
```
Category1
Data1
Data2
Date3
Category2
Data4
Data5
Data6
```
Is there a way to do this in an ASP.NET MVC view, perhaps using a simple linq phrase or linq extension method with a foreach or a nested foreach? | If your view is strongly typed, you can use the LINQ GroupBy extension method with nested foreach:
```
<ul>
<% foreach (var group in Model.GroupBy(item => item.Category)) { %>
<li><%= Html.Encode(group.Key) %>
<ul>
<% foreach (var item in group) { %>
<li><%= Html.Encode(item.Data) %></li>
<% } %>
</ul>
</li>
<% } %>
</ul>
```
This will provide output much like your formatted lists in the original question. It assumes your model looks something like:
```
public class ViewModel
{
public string Category { get; set; }
public string Data { get; set; }
}
``` | ```
<table class="table table-striped table-bordered">
@foreach (var plan in Model.GroupBy(p => p.PlanName))
{
<thead>
<tr>
<th></th>
<th>
@plan.Key
</th>
</tr>
</thead>
<tbody>
@foreach (var plan1 in plan)
{
<tr>
<td>@plan1.PlanDetails</td>
<td>@plan1.PlanOption</td>
</tr>
}
</tbody>
<tfoot>
</tfoot>
}
</table>
``` | How do I group data in an ASP.NET MVC View? | [
"",
"c#",
"asp.net-mvc",
"linq",
"linq-to-sql",
"reporting",
""
] |
I have been trying this for hours
```
<?php
if ($_SERVER['SERVER_NAME']=='http://www.testground.idghosting.com/idi' && $_SERVER['REQUEST_URI'] == 'our-production/') {
echo '<div id="services">
<h1>Our services</h1>
<a href="<?php bloginfo(\'url\'); ?>" id="serv_productions" title="Our Productions"><span>Our Productions</span></a>
<a href="<?php bloginfo(\'url\'); ?>" id="serv_services" title="Production Services"><span>Production Services</span></a>
<a href="<?php bloginfo(\'url\'); ?>" id="serv_equipment" title="Equipment & Facilities"><span>Equipment & Facilities</span></a>
<a href="<?php bloginfo(\'url\'); ?>" id="serv_pr" title="PR & Media"><span>PR & Media</span></a>
</div>';
} else {
echo '<div> do not show</div>';
} ;
?>
```
but no luck... a help would be very much appreciated.. | You also have an extra semi-colon:
```
</div>';
} else {
echo '<div> do not show</div>';
} ;
// ^ remove this semi-colon
``` | That's never going to match because **$\_SERVER['SERVER\_NAME']** is just the domain name of the server, not the url itself.
Some of the items in the $\_SERVER array that may be of use to you:
* **SERVER\_NAME** The full domain name of the server executing the script (eg myserver.foo.com)
* **REQUEST\_URI** The portion of the URL that comes after the server name, including the query string (if any)
* **SCRIPT\_NAME** The portion of the URL after the server name, excluding the query string.
One thing I like to do for handling code that gets executed for development and not on a live site is to create a define based on the hostname.
For example:
```
define('IS_LIVE', (strstr($_SERVER['SERVER_NAME'], 'mytestserver') ? true : false));
```
If I put that define somewhere that gets called for every page, then elsewhere in my code, I can do this:
```
if(!IS_LIVE) {
//Do development-debugging stuff
}
``` | Wordpress PHP If else help | [
"",
"php",
"wordpress",
""
] |
I need to create a storage file format for some simple data in a tabular format, was trying to use HDF5 but have just about given up due to some issues, and I'd like to reexamine the use of embedded databases to see if they are fast enough for my application.
Is there a reputable embedded Java database out there that has the option to store data in one file? The only one I'm aware of is SQLite (Java bindings available). I tried H2 and HSQLDB but out of the box they seem to create several files, and it is highly desirable for me to have a database in one file.
**edit:** reasonably fast performance is important. Object storage is not; for performance concerns I only need to store integers and BLOBs. (+ some strings but nothing performance critical)
**edit 2:** storage data efficiency is important for larger datasets, so XML is out. | I think for now I'm just going to continue to use HDF5 for the persistent data storage, in conjunction with H2 or some other database for in-memory indexing. I can't get SQLite to use BLOBs with the Java driver I have, and I can't get embedded Firebird up and running, and I don't trust H2 with PAGE\_STORE yet. | Nitrite Database <http://www.dizitart.org/nitrite-database.html>
> NOsql Object (NO2 a.k.a Nitrite) database is an open source nosql
> embedded document store written in Java with MongoDB like API. It
> supports both in-memory and single file based persistent store. | java embedded database w/ ability to store as one file | [
"",
"java",
"embedded-database",
""
] |
In ASP.NET C# I have a struct:
```
public struct Data
{
public int item1;
public int item2;
public int category_id;
public string category_name;
}
```
and I have a List of those. I want to select `category_id` and `category_name`, running a `DISTINCT` and finally an `ORDERBY` on `category_name`.
Here's what I have now:
```
List<Data> listObject = getData();
string[] catNames = listObject
.Select(i=> i.category_name)
.Distinct()
.OrderByDescending(s => s)
.ToArray();
```
This obviously just gets the category name. My question is, how do I get multiple fields, and what data structure will I store this in (not a `string[]`)?
EDIT
Using a list of structs is not set in stone. If it would be advisable to change my backing data structure to make selects easier (I'll be writing a lot of these) then I'd gladly take recommendations. | Anonymous types allow you to select arbitrary fields into data structures that are strongly typed later on in your code:
```
var cats = listObject
.Select(i => new { i.category_id, i.category_name })
.Distinct()
.OrderByDescending(i => i.category_name)
.ToArray();
```
Since you (apparently) need to store it for later use, you could use the GroupBy operator:
```
Data[] cats = listObject
.GroupBy(i => new { i.category_id, i.category_name })
.OrderByDescending(g => g.Key.category_name)
.Select(g => g.First())
.ToArray();
``` | You could use an anonymous type:
```
.Select(i => new { i.name, i.category_name })
```
The compiler will generate the code for a class with `name` and `category_name` properties and returns instances of that class. You can also manually specify property names:
```
i => new { Id = i.category_id, Name = i.category_name }
```
You can have arbitrary number of properties. | Select Multiple Fields from List in Linq | [
"",
"c#",
"linq",
"data-structures",
""
] |
I would like to make use of few methods from couple of my old tested classes into my new class that I am building. Unfortunately, C# does not support multiple inheritance. How do I reuse code from these old classes? Do I just create them as member objects? or Do I have any other options? | Generally, using composition instead of inheritance is the way forward, yes. If you could give a concrete example of the kind of thing you mean, that would make it easier to help find the appropriate approach though: it's not always the same. | Using them as member objects should be a good idea. Then you can also expose only the methods of interest, and adapt them if necessary. | How to reuse code when multiple inheritance is not an option? | [
"",
"c#",
"inheritance",
"oop",
"multiple-inheritance",
"reusability",
""
] |
I'm trying to iterate in a JSON object that is returned from a PHP script. The return part is something like:
```
$json = array("result" => -1,
"errors" => array(
"error1" => array("name" => "email","value" => "err1"),
"error2" => array("name" => "pass","value" => "err2")
)
);
$encoded = json_encode($json);
echo $encoded;
```
So, in JavaScript I can do:
```
var resp = eval('(' + transport.responseText + ')');
alert(resp.length);
alert(resp.errors.error1.name);
```
But I can't do:
```
alert(resp.errors.length);
```
I would like to iterate `errors`, that's why I'm trying to get the length. Can somebody give me a hint? Thanks! | To be able to do that, you need `resp.errors` to be a Javascript array, and not a Javascript object.
In PHP, arrays can have named-keys ; that is not possible in Javascript ; so, when using `json_encode`, the `errors` PHP array is "translated" to a JS object : your JSON data looks like this :
```
{"result":-1,"errors":{"error1":{"name":"email","value":"err1"},"error2":{"name":"pass","value":"err2"}}}
```
Instead, you would want it to look like this :
```
{"result":-1,"errors":[{"name":"email","value":"err1"},{"name":"pass","value":"err2"}]}
```
Notice that "`errors`" in an array, without named-keys.
To achieve that, your PHP code would need to be :
```
$json = array(
"result" => -1,
"errors" => array(
array("name" => "email","value" => "err1"),
array("name" => "pass","value" => "err2")
)
);
$encoded = json_encode($json);
echo $encoded;
```
*(Just remove the named-keys on `errors`)* | Have a look at your JSON output. `resp.errors` will be something like this:
```
{"error1": {"name": "email", "value": "err1"}, ...}
```
As you can see, it's an object, not an array (since you passed it an *associative* array and not an numerically indexed array.) If you want to loop through an object in JavaScript, you do it like this:
```
for (var error in resp.errors) {
alert(resp.errors[error].name);
}
```
If you want it to be a JavaScript array, your PHP should look like this:
```
$json = array("result" => -1, "errors" => array(
array("name" => "email","value" => "err1"),
array("name" => "email","value" => "err1")
));
``` | Parsing JSON from PHP | [
"",
"php",
"json",
"parsing",
""
] |
I have a (html)table (sample layout below) that I'd like to hide the last two columns under certain conditions, using the C# codebehind. I'd prefer not to do this by shrinking the width of the columns to 0, though I'm not ruling it out. There aren't any CSS classes really supplied to most of the rows and none of the columns. I've tried using a colgroup to set the display to none as well as the visibility to hidden on the colgroup, but with no luck.
```
_____________
|__|__|__|__|
|__|__|__|__|
|__|__|__|__|
```
to
```
_______
|__|__|
|__|__|
|__|__|
```
Any thoughts? | Assuming your table is static, you could dynamically apply a CSS `class` to any columns you want hidden:
```
<table>
<tr>
<th>
Visible
</th>
<th class="<%= HiddenClassName %>">
Possibly hidden
</th>
</tr>
<tr>
<td>
Visible
</td>
<td class="<%= HiddenClassName %>">
Possibly hidden
</td>
</tr>
</table>
```
In the code file, your property could be:
```
public string HiddenClassName { get; private set; }
```
The `hidden` style itself:
```
<style type="text/css">
.hidden
{
visibility: hidden;
display: none;
}
</style>
``` | In the aspx:
```
<table>
<tr>
<td style="<%= HiddenClassName %>">
my content to be hidden
</td>
</tr>
</table>
```
In the Code:
```
public class OPMRESRVA0 : System.Web.UI.Page
{
public string HiddenClassName { get; private set; }
protected void Page_Load(object sender, EventArgs e)
{
HiddenClassName = "display:none";
}
}
``` | hide column of table with codebehind | [
"",
"c#",
"asp.net",
"html",
""
] |
Consider the following simplified interface inheritence hierarchy:
```
// Starting point:
public interface Base {
void Foo();
}
public interface Derived extends Base {
}
```
It is intended to move the `Foo` method from the `Base` interface to the `Derived` interface:
```
// Desired end-point:
public interface Base {
}
public interface Derived extends Base {
void Foo();
}
```
In order to phase in this breaking change, it is desired to retain backwards compatibility of the `Base` interface for some time.
This can be achieved by marking the method on the `Base` interface as `@Deprecated`:
```
// Intermediate state:
public interface Base {
/**
* @deprecated This method is deprecated as of release X. Derived.Foo should be used instead.
*/
@Deprecated void Foo();
}
public interface Derived extends Base {
void Foo();
}
```
When I compile this code I receive a compiler warning for **`Derived`**:
> [deprecation] Foo() in interface Base has been deprecated
Oddly, if I remove the `@deprecated` from the documentation in `Base` (but leave the @Deprecated) this warning disappears.
Is it correct that I get this warning, and if so, how can I work around this?
---
The warning seems to communicate that `Derived.Foo` is "using" `Base.Foo` (which is deprecated). But the only capacity in which `Derived.Foo` is "using" the deprecated `Base.Foo` is to override it. That seems to say that you are not allowed to override deprecated interface methods in derived methods.
If this is the case, should I then decorate `Derived` with `@SuppressWarnings("deprecation")` to suppress the warning? | I believe your requirement is valid, I have no doubt that overriding the deprecated method is the correct way to go.
I believe the difference between @deprecated and @Deprecated is mainly historical. @Deprecated is the official way in java 5, but is new, so we are expected to double it with @deprecated.
Also note that, sadly enough, @Deprecated doesn't let you specify information .. while information is usually needed, for example to tell what should be used as a replacement, or when the deprecated method is expected to be completely removed.
Not knowing more, and knowing the problem will disappear as soon as you effectively remove the super method, I would use the @SuppressWarnings("deprecation"), possibly with a comment for your successors to understand ... (and another comment on the super method to tell them to remove all that when deleting the method). ;-) | If you add @Deprecated to your derived declaration of Foo() I believe the warning will go away.
```
public interface Derived extends Base {
@Deprecated void Foo();
}
``` | Java: How to avoid deprecated warning in derived interfaces which override deprecated members? | [
"",
"java",
"interface",
"overriding",
"deprecated",
""
] |
I am trying to get my head around applying template programming (and at some future point, template metaprogramming) to real-world scenarios. One problem I am finding is that C++ Templates and Polymorphism don't always play together the way I want.
My question is if the way I'm trying to apply template programming is improper (and I should use plain old OOP) or if I'm still stuck in the OOP mindset.
In this particular case, I am trying to solve a problem using the strategy-pattern. I keep running into the problem where I end up wanting something to behave polymorphically which templates don't seem to support.
OOP Code using composition:
```
class Interpolator {
public:
Interpolator(ICacheStrategy* const c, IDataSource* const d);
Value GetValue(const double);
}
void main(...) {
Interpolator* i;
if (param == 1)
i = new Interpolator(new InMemoryStrategy(...), new TextFileDataSource(...));
else if (param == 2)
i = new Interpolator(new InMemoryStrategy(...), new OdbcDataSource(...));
else if (param == 3)
i = new Interpolator(new NoCachingStrategy(...), new RestDataSource(...));
while (run) {
double input = WaitForRequest();
SendRequest(i->GetValue(input));
}
}
```
Potential Template Version:
```
class Interpolator<class TCacheStrategy, class TDataSource> {
public:
Interpolator();
Value GetValue(const double); // may not be the best way but
void ConfigCache(const& ConfigObject); // just to illustrate Cache/DS
void ConfigDataSource(const& ConfigObject); // need to configured
}
//Possible way of doing main?
void main(...) {
if(param == 1)
DoIt(Interpolator<InMemoryStrategy, TextFileDataSource>(), c, d);
else if(param == 2)
DoIt(Interpolator<InMemoryStrategy, OdbcDataSource>(), c, d)
else if(param == 3)
DoIt(Interpolator<NoCachingStrategy, RestDataSource>(), c, d)
}
template<class T>
void DoIt(const T& t, ConfigObject c, ConfigObject d) {
t.ConfigCache(c);
t.ConfigDataSource(c);
while(run) {
double input = WaitForRequest();
SendRequest(t.GetValue(input));
}
}
```
When I try to convert the OOP implementation to a template-based implementation, the Interpolator code can be translated without a lot of pain. Basically, replace the "interfaces" with Template type parameters, and add a mechanism to either pass in an instance of Strategy/DataSource or configuration parameters.
But when I get down to the "main", it's not clear to me how that should be written to take advantage of templates in the style of template meta programming. I often want to use polymorphism, but it doesn't seem to play well with templates (at times, it feels like I need Java's type-erasure generics... ugh).
When I often find I want to do is have something like `TemplateType<?, ?> x = new TemplateType<X, Y>()` where x doesn't care what X, Y is.
In fact, this is often my problem when using templates.
1. Do I need to apply one more level of
templates?
2. Am I trying to use my shiny new power template wrench to
install a OOP nail into a PCI slot?
3. Or am I just thinking of this all
wrong when it comes to template
programming?
[Edit] A few folks have pointed out this is not actually template metaprogramming so I've reworded the question slightly. Perhaps that's part of the problem--I have yet grok what TMP really is. | Templates provide static polymorphism: you specify a template parameter at compile time implementing the strategy. They don't provide dynamic polymorphism, where you supply an object at runtime with virtual member functions that implement the strategy.
Your example template code will create three different classes, each of which contains all the Interpolator code, compiled using different template parameters and possibly inlining code from them. That probably isn't what you want from the POV of code size, although there's nothing categorically wrong with it. Supposing that you were optimising to avoid function call overhead, then it might be an improvement on dynamic polymorphism. More likely it's overkill. If you want to use the strategy pattern dynamically, then you don't need templates, just make virtual calls where relevant.
You can't have a variable of type `MyTemplate<?>` (except appearing in another template before it's instantiated). `MyTemplate<X>` and `MyTemplate<Y>` are completely unrelated classes (even if X and Y are related), which perhaps just so happen to have similar functions if they're instantiated from the same template (which they needn't be - one might be a specialisation). Even if they are, if the template parameter is involved in the signatures of any of the member functions, then those functions aren't the same, they just have the same names. So from the POV of dynamic polymorphism, instances of the same template are in the same position as any two classes - they can only play if you give them a common base class with some virtual member functions.
So, you could define a common base class:
```
class InterpolatorInterface {
public:
virtual Value GetValue(const double) = 0;
virtual void ConfigCache(const& ConfigObject) = 0;
virtual void ConfigDataSource(const& ConfigObject) = 0;
virtual ~InterpolatorInterface() {}
};
```
Then:
```
template <typename TCacheStrategy, typename TDataSource>
class Interpolator: public InterpolatorInterface {
...
};
```
Now you're using templates to create your different kinds of Interpolator according to what's known at compile time (so calls from the interpolator to the strategies are non-virtual), and you're using dynamic polymorphism to treat them the same even though you don't know until runtime which one you want (so calls from the client to the interpolator are virtual). You just have to remember that the two are pretty much completely independent techniques, and the decisions where to use each are pretty much unrelated.
Btw, this isn't template meta-programming, it's just using templates.
Edit. As for what TMP is, here's the canonical introductory example:
```
#include <iostream>
template<int N>
struct Factorial {
static const int value = N*Factorial<N-1>::value;
};
template<>
struct Factorial<0> {
static const int value = 1;
};
int main() {
std::cout << "12! = " << Factorial<12>::value << "\n";
}
```
Observe that 12! has been calculated *by the compiler*, and is a compile-time constant. This is exciting because it turns out that the C++ template system is a Turing-complete programming language, which the C preprocessor is not. Subject to resource limits, you can do arbitrary computations at compile time, avoiding runtime overhead in situations where you know the inputs at compile time. Templates can manipulate their template parameters like a functional language, and template parameters can be integers or types. Or functions, although those can't be "called" at compile time. Or other templates, although those can't be "returned" as static members of a struct. | I find templates and polymorphism work well toegther. In your example, if the client code doesn't care what template parameters `Interpolator` is using then introduce an abstract base class which the template sub-classes. E.g.:
```
class Interpolator
{
public:
virtual Value GetValue (const double) = 0;
};
template<class TCacheStrategy, class TDataSource>
class InterpolatorImpl : public Interpolator
{
public:
InterpolatorImpl ();
Value GetValue(const double);
};
void main()
{
int param = 1;
Interpolator* interpolator = 0;
if (param==1)
interpolator = new InterpolatorImpl<InMemoryStrategy,TextFileDataSource> ();
else if (param==2)
interpolator = new InterpolatorImpl<InMemoryStrategy,OdbcDataSource> ();
else if (param==3)
interpolator = new InterpolatorImpl<NoCachingStrategy,RestDataSource> ();
while (true)
{
double input = WaitForRequest();
SendRequest( interpolator->GetValue (input));
}
}
```
I use this idiom quite a lot. It quite nicely hides the templatey stuff from client code.
Note, i'm not sure this use of templates really classes as "meta-programming" though. I usually reserve that grandiose term for the use of more sophisticated compile-time template tricks, esp the use of conditionals, recursive defintions etc to effectively compute stuff at compile time. | Can template polymorphism be used in place of OO polymorphism? | [
"",
"c++",
"templates",
"oop",
""
] |
Consider the following Python exception:
```
[...]
f.extractall()
File "C:\Python26\lib\zipfile.py", line 935, in extractall
self.extract(zipinfo, path, pwd)
File "C:\Python26\lib\zipfile.py", line 923, in extract
return self._extract_member(member, path, pwd)
File "C:\Python26\lib\zipfile.py", line 957, in _extract_member
os.makedirs(upperdirs)
File "C:\Python26\lib\os.py", line 157, in makedirs
mkdir(name, mode)
WindowsError: [Error 267] The directory name is invalid: 'C:\\HOME\\as\
\pypm-infinitude\\scratch\\b\\slut-0.9.0.zip.work\\slut-0.9\\aux'
```
I want to handle this particular exception - i.e., WindowsError with error number 267. However, I cannot simply do the following:
```
try:
do()
except WindowsError, e:
...
```
Because that would not work on Unix systems where WindowsError is not even defined in the exceptions module.
Is there an elegant way to handle this error? | Here's my current solution, but I slightly despise using non-trivial code in a except block:
```
try:
f.extractall()
except OSError, e:
# http://bugs.python.org/issue6609
if sys.platform.startswith('win'):
if isinstance(e, WindowsError) and e.winerror == 267:
raise InvalidFile, ('uses Windows special name (%s)' % e)
raise
``` | If you need to catch an exception with a name that might not always exist, then create it:
```
if not getattr(__builtins__, "WindowsError", None):
class WindowsError(OSError): pass
try:
do()
except WindowsError, e:
print "error"
```
If you're on Windows, you'll use the real WindowsError class and catch the exception. If you're not, you'll create a WindowsError class that will never be raised, so the except clause doesn't cause any errors, and the except clause will never be invoked. | Handling Windows-specific exceptions in platform-independent way | [
"",
"python",
"windows",
"exception",
""
] |
This is pure curiosity...
Most 'professionals' will likely never use "Form1" as a valid class name in their Windows Forms projects. I usually end up renaming it to MainForm.
What do you do?
**Edit:** For those of you that use hungarian notation (frmMain) - why? I don't think it would still be considered a standard practice... is it? | `MainForm`. I loathe Hungarian notation, and FxCop complains about it in any case, so `MainForm`, `OkButton`, `AboutDialog`, etc. | {AppName}Form. | What do you rename Form1 to? | [
"",
"c#",
".net",
"winforms",
""
] |
I hate to code what is already available. I can't seem to find in Jakarta commons a method that would to the following:
```
long x= 12345;
int[] digits = toDigitsArray(x); //[1,2,3,4,5]
```
So before I code my own toDigitsArray() method does anyone know if the equivalent exists either in j2se or in commons? | I came up with 4 versions of the method.
1. Uses String.toCharArray and Character.getNumericValue()
2. Uses modulus with an array
3. Uses modulus with an Deque
4. Uses String.split()
When testing with very large values and Long.MAX\_VALUE all four give correct results.
When testing with Long.MIN\_VALUE it turns out that Math.abs(Long.MIN\_VALUE) == Long.MIN\_VALUE so you cannot rely on it to get rid of the minus sign!! So I had to get rid of it so I modified the versions. The modulus versions also give wrong values with Long.MIN\_VALUE, the digits are correct but they have all negative signs.
Now for performance, I did a few tests where I ran each method 10 000 000 times with the same input, this a sample result but it is very representative of the others:
input: -5507235864653430347
1:5110
2:7235
3:7564
4:25487
So it turn out that the winner so far is method 1. 2 and 3 are not reliable and 4 is very slow.
```
public static int[] toIntArray(long x) {
int neg = (x<0)?1:0;
final char[] c = String.valueOf(x).toCharArray();
final int s = c.length-neg;
final int[] d = new int[s];
for (int i = 0; i < s; i++) {
d[i] = Character.getNumericValue(c[i+neg]);
}
if (neg==1) {
d[0] = d[0] * -1;
}
return d;
}
public static int[] toIntArray2(long x) {
int neg = (x<0)?1:0;
final int s = String.valueOf(x).length()-neg;
final int[] d = new int[s];
for(int i =s-1 ; i > -1; i--) {
d[i] = (int) (x%10);
x = x/10;
}
return d;
}
public static Object[] toIntArray3(long x) {
Deque<Integer> d = new ArrayDeque<Integer>(10);
if(x==0){
d.push(0);
return d.toArray();
}
while(x != 0) {
d.push((int) (x%10));
x = x/10;
}
return d.toArray();
}
public static int[] toIntArray4(long x) {
int neg = (x<0)?1:0;
final String[] c = String.valueOf(x).split("");
final int s = c.length-neg;
final int[] d = new int[s-1];
for (int i = 1; i < s; i++) {
d[i-1] = Integer.parseInt(c[i+neg]);
}
if (neg==1) {
d[0] = d[0] * -1;
}
return d;
}
``` | How about x.toString().toCharArray() ? The result will be an array of chars rather than an array of ints as you appear to be looking for in your example, but you could cast the chars to ints as you used them, or depending on what you're trying to do with it, chars could be fine. | Is there something in j2se or Jakarta commons thats converts a number to an array of digits? | [
"",
"java",
""
] |
I've had a good read of the [PHP specs on overloading](http://uk.php.net/manual/en/language.oop5.overloading.php), and most of the examples appear to be intended to simply allow defining of custom fields (similar to stdClass).
But what about the private fields defined in my class? How should these be retrieved/assigned? I could do a switch on possible values and act on certain values:
```
class A
{
private $name;
private $age;
public function __get( $var )
{
switch ( $var )
{
case 'name':
return $this->name;
break;
case 'age':
return $this->age+10; // just to do something different ;)
break;
default:
break;
}
}
}
```
Is this the best method, or is there another generally accepted best practice? (I don't know if it's possible to loop class variables inside a class, but regardless that's not appropriate in most situations since you don't want to return everything.) | This would effectively make them public, and usually this gains you nothing over simply using public properties (but you pay performance penalty and have to write more code, risk bugs).
Use that only if you have existing code that uses public property and you suddenly need getter/setter for it (like your example with `age`).
If you need to execute some code when property is read/written (e.g. make it read-only or lazily fetch from the database), then you should use normal getters/setters (`getAge()`/`setAge()`). | I make extensive use of `__get()` and `__set()` AND I have my properties declared `public`. I wanted the best of both worlds, so my IDE could list public properties for me when I type the name of a class instance. How did I get the PHP interceptor methods to work, even though the properties are public and visible outside the class?
**unset() the properties** I want `__get()` and `__set()` to be used for in the class `__construct()`.
Figuring this method out took a couple evenings of frustration :-) | How do I use PHP's __get() and __set() for defined fields in my class? | [
"",
"php",
"overloading",
"setter",
"getter",
""
] |
Is it better to add functions that return the internal state of an object for unit testing, as opposed to making the testing class a friend? - especially, when there is no use for the functions except for the case of unit testing. | Unit tests should 95% of the time only test the publicly exposed surface of a class. If you're testing something under the covers, that's testing implementation details, which is inherently fragile, because you should be able to easily change implementation and still have the tests work. Not only is it fragile, but you could also be tempted into testing things that aren't actually possible in planned usage scenarios, which is a waste of time.
If the point of the accessors you want to add is just to test whether the function had the desired effect, your class design may violate another principle, which is that a state-machine-like class should always make it clear what state its in, if that affects what happens when people interact with the class. In that case, it'd be right to provide those read-only accessors. If it doesn't affect the class's behavior, refer back to my previous bit about implementation details.
And as you rightly said, cluttering up the public surface of a class with unused stuff is also undesirable for its own reasons.
If I *had* to pick between accessors and friending in your case, I would choose friending, simply because *you* own your test and can change it in a pinch. You may not own the code by the clown who finds a way to use your extra accessors, and then you'll be stuck. | I'll disagree with the accepted answer and instead recommend the use of a friend class.
Part of the state you are testing is probably specific to the implementation of your class; you're testing details that other code normally doesn't know about or care about and shouldn't rely on. Public accessor functions make these implementation details part of the class's interface. If the internal state you are testing is not part of the intended interface, it shouldn't be visible through public functions. From a purist point of view you're stuck between two wrong answers, as friend classes are also technically part of the public interface. In my mind the question becomes, which option is less likely to lead to poor coding choices down the road? Going with a set of implementation-dependent public accessor functions will inadvertantly encourage an implementation-dependent conceptual model of the the class, leading to implementation-dependent use of the class. A single friend class, appropriately named and documented, is less likely to be abused.
While in general I strongly agree with the recommendation to prefer accessor functions over direct access to member variables, I don't agree that this best practice applies to unit testing of implementation-dependent internal state. A reasonable middle ground is to use *private* accessor functions to those pieces of state your unit test will care about, and be disciplined enough to use the accessor functions in your unit tests. Just my opinion. | Using a friend class vs. adding accessors for unit testing in C++? | [
"",
"c++",
"unit-testing",
"friend-class",
""
] |
I have a link within a div:
```
<div>
<a href="#"></a>
</div>
```
This div make's a box, like a button, and when i mouseover it in Internet Explorer 8 works fine showing the hand cursor, but in firefox doesn't.
Can some body help me.
Thanks. | What CSS are you using? The following should work both for IE8 and Firefox:
```
cursor: pointer;
```
More details [here](http://www.learnwebdesignonline.com/css-tutorials/cursor-hand-pointer.htm). | If I understand your problem correctly, the simplest fix to the problem would be to specify that the div cursor your CSS file:
```
div_button_id {
cursor: pointer;
}
```
See: <http://www.w3schools.com/CSS/pr_class_cursor.asp> | Hand cursor over a link not showed in IE but it is in FireFox | [
"",
"javascript",
"html",
"css",
""
] |
I want to truncate some text (loaded from a database or text file), but it contains HTML so as a result the tags are included and less text will be returned. This can then result in tags not being closed, or being partially closed (so Tidy may not work properly and there is still less content). How can I truncate based on the text (and probably stopping when you get to a table as that could cause more complex issues).
```
substr("Hello, my <strong>name</strong> is <em>Sam</em>. I´m a web developer.",0,26)."..."
```
Would result in:
```
Hello, my <strong>name</st...
```
What I would want is:
```
Hello, my <strong>name</strong> is <em>Sam</em>. I´m...
```
How can I do this?
While my question is for how to do it in PHP, it would be good to know how to do it in C#... either should be OK as I think I would be able to port the method over (unless it is a built in method).
Also note that I have included an HTML entity `´` - which would have to be considered as a single character (rather than 7 characters as in this example).
`strip_tags` is a fallback, but I would lose formatting and links and it would still have the problem with HTML entities. | Assuming you are using valid XHTML, it's simple to parse the HTML and make sure tags are handled properly. You simply need to track which tags have been opened so far, and make sure to close them again "on your way out".
```
<?php
header('Content-type: text/plain; charset=utf-8');
function printTruncated($maxLength, $html, $isUtf8=true)
{
$printedLength = 0;
$position = 0;
$tags = array();
// For UTF-8, we need to count multibyte sequences as one character.
$re = $isUtf8
? '{</?([a-z]+)[^>]*>|&#?[a-zA-Z0-9]+;|[\x80-\xFF][\x80-\xBF]*}'
: '{</?([a-z]+)[^>]*>|&#?[a-zA-Z0-9]+;}';
while ($printedLength < $maxLength && preg_match($re, $html, $match, PREG_OFFSET_CAPTURE, $position))
{
list($tag, $tagPosition) = $match[0];
// Print text leading up to the tag.
$str = substr($html, $position, $tagPosition - $position);
if ($printedLength + strlen($str) > $maxLength)
{
print(substr($str, 0, $maxLength - $printedLength));
$printedLength = $maxLength;
break;
}
print($str);
$printedLength += strlen($str);
if ($printedLength >= $maxLength) break;
if ($tag[0] == '&' || ord($tag) >= 0x80)
{
// Pass the entity or UTF-8 multibyte sequence through unchanged.
print($tag);
$printedLength++;
}
else
{
// Handle the tag.
$tagName = $match[1][0];
if ($tag[1] == '/')
{
// This is a closing tag.
$openingTag = array_pop($tags);
assert($openingTag == $tagName); // check that tags are properly nested.
print($tag);
}
else if ($tag[strlen($tag) - 2] == '/')
{
// Self-closing tag.
print($tag);
}
else
{
// Opening tag.
print($tag);
$tags[] = $tagName;
}
}
// Continue after the tag.
$position = $tagPosition + strlen($tag);
}
// Print any remaining text.
if ($printedLength < $maxLength && $position < strlen($html))
print(substr($html, $position, $maxLength - $printedLength));
// Close any open tags.
while (!empty($tags))
printf('</%s>', array_pop($tags));
}
printTruncated(10, '<b><Hello></b> <img src="world.png" alt="" /> world!'); print("\n");
printTruncated(10, '<table><tr><td>Heck, </td><td>throw</td></tr><tr><td>in a</td><td>table</td></tr></table>'); print("\n");
printTruncated(10, "<em><b>Hello</b>w\xC3\xB8rld!</em>"); print("\n");
```
**Encoding note**: The above code assumes the XHTML is [UTF-8](http://en.wikipedia.org/wiki/ISO/IEC_8859-1) encoded. ASCII-compatible single-byte encodings (such as [Latin-1](http://en.wikipedia.org/wiki/UTF-8)) are also supported, just pass `false` as the third argument. Other multibyte encodings are not supported, though you may hack in support by using `mb_convert_encoding` to convert to UTF-8 before calling the function, then converting back again in every `print` statement.
(You should *always* be using UTF-8, though.)
**Edit**: Updated to handle character entities and UTF-8. Fixed bug where the function would print one character too many, if that character was a character entity. | I've written a function that truncates HTML just as yous suggest, but instead of printing it out it puts it just keeps it all in a string variable. handles HTML Entities, as well.
```
/**
* function to truncate and then clean up end of the HTML,
* truncates by counting characters outside of HTML tags
*
* @author alex lockwood, alex dot lockwood at websightdesign
*
* @param string $str the string to truncate
* @param int $len the number of characters
* @param string $end the end string for truncation
* @return string $truncated_html
*
* **/
public static function truncateHTML($str, $len, $end = '…'){
//find all tags
$tagPattern = '/(<\/?)([\w]*)(\s*[^>]*)>?|&[\w#]+;/i'; //match html tags and entities
preg_match_all($tagPattern, $str, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER );
//WSDDebug::dump($matches); exit;
$i =0;
//loop through each found tag that is within the $len, add those characters to the len,
//also track open and closed tags
// $matches[$i][0] = the whole tag string --the only applicable field for html enitities
// IF its not matching an &htmlentity; the following apply
// $matches[$i][1] = the start of the tag either '<' or '</'
// $matches[$i][2] = the tag name
// $matches[$i][3] = the end of the tag
//$matces[$i][$j][0] = the string
//$matces[$i][$j][1] = the str offest
while($matches[$i][0][1] < $len && !empty($matches[$i])){
$len = $len + strlen($matches[$i][0][0]);
if(substr($matches[$i][0][0],0,1) == '&' )
$len = $len-1;
//if $matches[$i][2] is undefined then its an html entity, want to ignore those for tag counting
//ignore empty/singleton tags for tag counting
if(!empty($matches[$i][2][0]) && !in_array($matches[$i][2][0],array('br','img','hr', 'input', 'param', 'link'))){
//double check
if(substr($matches[$i][3][0],-1) !='/' && substr($matches[$i][1][0],-1) !='/')
$openTags[] = $matches[$i][2][0];
elseif(end($openTags) == $matches[$i][2][0]){
array_pop($openTags);
}else{
$warnings[] = "html has some tags mismatched in it: $str";
}
}
$i++;
}
$closeTags = '';
if (!empty($openTags)){
$openTags = array_reverse($openTags);
foreach ($openTags as $t){
$closeTagString .="</".$t . ">";
}
}
if(strlen($str)>$len){
// Finds the last space from the string new length
$lastWord = strpos($str, ' ', $len);
if ($lastWord) {
//truncate with new len last word
$str = substr($str, 0, $lastWord);
//finds last character
$last_character = (substr($str, -1, 1));
//add the end text
$truncated_html = ($last_character == '.' ? $str : ($last_character == ',' ? substr($str, 0, -1) : $str) . $end);
}
//restore any open tags
$truncated_html .= $closeTagString;
}else
$truncated_html = $str;
return $truncated_html;
}
``` | Truncate text containing HTML, ignoring tags | [
"",
"php",
"html",
"string",
"markup",
""
] |
In Python, there are examples of built-in classes with highly constrained instances. For example, "None" is the only instance of its class, and in the bool class there are only two objects, "True" and "False" (I hope I am more-or-less correct so far).
Another good example are integers: if a and b are instances of the int type then a == b implies that a is b.
Two questions:
1. How does one create a class with similarly constrained instances? For example we could ask for a class with exactly 5 instances. Or there could be infinitely many instances, like type int, but these are not arbitrary.
2. if integers form a class, why does int() give the 0 instance? compare this to a user-defined class Cl, where Cl() would give an instance of the class, not *a specific unique instance*, like 0. Shouldn't int() return an unspecified integer object, i.e. an integer without a specified value? | You're talking about giving a class *value semantics*, which is typically done by creating class instances in the normal way, but remembering each one, and if a matching instance would be created, give the already created instance instead. In python, this can be achieved by overloading a classes `__new__` [method](http://docs.python.org/reference/datamodel.html).
Brief example, say we wanted to use pairs of integers to represent coordinates, and have the proper value semantics.
```
class point(object):
memo = {}
def __new__(cls, x, y):
if (x, y) in cls.memo: # if it already exists,
return cls.memo[(x, y)] # return the existing instance
else: # otherwise,
newPoint = object.__new__(cls) # create it,
newPoint.x = x # initialize it, as you would in __init__
newPoint.y = y
cls.memo[(x, y)] = newPoint # memoize it,
return newPoint # and return it!
```
--- | Looks like #1 has been well answered already and I just want to explain a principle, related to #2, which appears to have been missed by all respondents: for most built-in types, calling the type without parameters (the "default constructor") returns an instance of that type *which evaluates as false*. That means an empty container for container types, a number which compares equal to zero for number types.
```
>>> import decimal
>>> decimal.Decimal()
Decimal("0")
>>> set()
set([])
>>> float()
0.0
>>> tuple()
()
>>> dict()
{}
>>> list()
[]
>>> str()
''
>>> bool()
False
```
See? Pretty regular indeed! Moreover, for mutable types, like most containers, calling the type always returns a new instance; for immutable types, like numbers and strings, it doesn't matter (it's a possible internal optimization to return new reference to an existing immutable instance, but the implementation is not required to perform such optimization, and if it does it can and often will perform them quite selectively) since it's never correct to compare immutable type instances with `is` or equivalently by `id()`.
If you design a type of which some instances can evaluate as false (by having `__len__` or `__nonzero__` special methods in the class), it's advisable to follow the same precept (have `__init__` [or `__new__` for immutables], if called without arguments [[beyond `self` for `__init__` and 'cls' for `__new__` of course]], prepare a [[new, if mutable]] "empty" or "zero-like" instance of the class). | How to create Classes in Python with highly constrained instances | [
"",
"python",
"math",
"class",
""
] |
is there an easy way to count uppercase words within a string? | Shooting from the hip, but this (or something like it) should work:
```
function countUppercase($string) {
return preg_match_all(/\b[A-Z][A-Za-z0-9]+\b/, $string)
}
countUppercase("Hello good Sir"); // 2
``` | You could use a regular expression to find all uppercase words and count them:
```
echo preg_match_all('/\b[A-Z]+\b/', $str);
```
The expression `\b` is a [word boundary](http://www.regular-expressions.info/wordboundaries.html) so it will only match whole uppercase words. | PHP: count uppercase words in string | [
"",
"php",
"count",
""
] |
I want to send emails through a web app, for example, reminders of a tasks manager, reminders of birthdays... I want to program a date and an hour, and get the email sent at that moment.
I think I have two options to do this: using cron or sending email with a future timestamp.
Using cron involve to run a command (which will query the database) each one, two o five minutes to check if there are any email to be sent. Or, another way, when I save a new reminder, put a new crontab task (via execute a system command from the web app) at the time indicated. With the first option, I think the server load will be excessive. With second option, I'll have hundreds of crontab tasks, what looks dirty for me.
Perhaps I could send the email at the very moment of creating the reminder, but changing the email timestamp to a date and hour in the future. I know some email servers can manage this (like Mercur for Windows), but, is it a standard? I will use my Gmail account to do this job. And, with this solution, I won't be able to cancel a reminder, because the email has been sent at the moment I created the reminder.
I can use PHP or Ruby (RoR) for server language, so the language isn't important, because both of them can send emails and call system commands. If the solution entails scripting, I can use bash scripts, Perl, Python... (the server is a Linux box).
Which do you think is the best method to accomplish the solution to this problem?
I apologize for my poor english. Thanks in advance. | instead of having a cron job for each reminder (or notification, whatever), you might write everything in a file and periodically (for example every 5 minutes) call a script (e.g. php-script) that reads the file and checks whether to send a notification or not...
you would have the functionality without needing to create a cron-job for every item...
would that be a solution?
regards | I don't know if you've looked into this, but since you use GMail I thought you might be interested. Google Calendar has this feature:
1. Go into GMail.
2. At the top, click on "Calendar".
3. On the left is a list of calendars. Each has a small link called "Settings". Follow this link (you may want to create a new calendar for this project).
4. This brings up a tabbed interface. I think it always brings you to the "Calendars" tab, but if it doesn't, click that tab.
5. Each of the calendars will have a link next to it called, "Notifications". Click the link for the calendar you want to notify you.
This will bring up a list of settings which you can use to set up notifications by sending an email.
Google's API should allow you to access the calendar to sync it with your application. If it's set to send you an email, it will handle all the email for you. | Best method to send programmed emails from web application | [
"",
"php",
"ruby",
"email",
"cron",
""
] |
We have a web application that attempts to use some resources on a Samba mount. If the mount has somehow failed, I need a way to quickly detect and report an error, however File.Exists and Directory.Exists are taking 30 seconds to return false when the mount goes away. What is the best way to quickly determine if a mount is available in C#? | The Win32 Windows Networking Functions are the only way to get this information. You should be able to use either [WNetGetResourceInformation](http://msdn.microsoft.com/en-us/library/aa385461(VS.85).aspx) or [WNetGetConnection](http://msdn.microsoft.com/en-us/library/aa385453(VS.85).aspx). I think WNetGetConnection might be the best option. The return values you would be most interested in are:
**`ERROR_CONNECTION_UNAVAIL`** The device is not currently connected, but it is a persistent connection. For more information, see the following Remarks section.
**`ERROR_NO_NETWORK`** The network is unavailable.
All of that aside, I understand the desire to be proactive in being able to read/write from a backup location, but it seems to me that would be more properly handled on the hardware and/or operating system side rather than the application. The hardware and/or operating system is much more likely to be able to detect that a read/write failed or some other network related event occurred and take the appropriate actions. | If a successful check with File.Exists always completes within 5 seconds (or some shorter time), you could assume that any call that takes longer than that will fail.
Here's a pseudo-code possible solution:
```
const int CUSTOM_TIMEOUT = 5;
bool isMountedVar = false;
bool isMounted ( string path) {
Thread mythread = executeNewThread(&isMountedThread, path);
sleep(CUSTOM_TIMEOUT);
if( mythread.finished() )
return isMountedVar;
// Otherwise
mythread.kill();
return false;
}
void isMountedThread(string path) {
isMountedVar = File(path).Exists;
}
``` | Quickly detect if a file mount is unavailable in Windows | [
"",
"c#",
"asp.net",
"windows",
"iis",
"samba",
""
] |
I'm just learning c++ coming from a Java background.
Just playing around with simple classes now, but for some reason the following won't compile, when the same syntax compiles fine elsewhere:
```
class CardDealer {
private:
string suits[4];
string values[13];
bool cardTaken[4][13];
int getRand(int top);
void getValidSuit(int *suit);
void getValidCard(int suit,int *value);
public:
CardDealer();
string dealCard();
void resetDeck();
};
CardDealer::CardDealer(){
suits = {"hearts", "clubs", "spades", "diamonds"};
values = {"ace","two","three","four","five","six","seven","eight","nine","ten","jack","queen","king"};
cardTaken = {{false,false,false,false,false,false,false,false,false,false,false,false,false},{false,false,false,false,false,false,false,false,false,false,false,false,false},
{false,false,false,false,false,false,false,false,false,false,false,false,false},{false,false,false,false,false,false,false,false,false,false,false,false,false}};
}
```
obviously this is just a part of the class so please don't yell at me for missing '}'s
compiler chucks a wobbly when it hits the instantiations in the constructor, spits out errors like these:
```
1>.\CardDealer.cpp(26) : error C2059: syntax error : '{'
1>.\CardDealer.cpp(26) : error C2143: syntax error : missing ';' before '{'
1>.\CardDealer.cpp(26) : error C2143: syntax error : missing ';' before '}'
1>.\CardDealer.cpp(27) : error C2059: syntax error : '{'
1>.\CardDealer.cpp(27) : error C2143: syntax error : missing ';' before '{'
1>.\CardDealer.cpp(27) : error C2143: syntax error : missing ';' before '}'
1>.\CardDealer.cpp(28) : error C2059: syntax error : '{'
```
line 26 is the one where I've instantiated suits (`suits = {`...)
thanks for taking a look guys, much appreciated | Until C++0x, you can only use the aggregate initializer syntax (ie, braces) when declaring an array.
Note that this program gives a similar error:
```
int thing[4];
int main ()
{
thing = { 0, 1, 2, 3 };
}
```
You'll have to initialize your array with the somewhat tedious bracket syntax, one element at a time. | I have corrected the earlier post:
You could initialise them like this outside the class:
```
namespace CardDealer
{
static const string suits[] = {"hearts", "clubs", "spades", "diamonds"};
static const string values[]={"ace","two","three","four","five","six","seven","eight","nine","ten","jack","queen","king"};
class CardDealer
{
private:
bool cardTaken[4][13];
...
};
...
}
```
In the constructor you could initialise `cardTaken` in a loop. | c ++ String array issue | [
"",
"c++",
"arrays",
"string",
""
] |
How do I convert all elements of my form to a JavaScript object?
I'd like to have some way of automatically building a JavaScript object from my form, without having to loop over each element. I do not want a string, as returned by `$('#formid').serialize();`, nor do I want the map returned by `$('#formid').serializeArray();` | [serializeArray](http://api.jquery.com/serializeArray/) already does exactly that. You just need to massage the data into your required format:
```
function objectifyForm(formArray) {
//serialize data function
var returnArray = {};
for (var i = 0; i < formArray.length; i++){
returnArray[formArray[i]['name']] = formArray[i]['value'];
}
return returnArray;
}
```
Watch out for hidden fields which have the same name as real inputs as they will get overwritten. | # Convert forms to JSON *like a boss*
---
The current source is my [on GitHub](https://github.com/macek/jquery-serialize-object) and [Bower](https://bower.io/).
> $ bower install jquery-serialize-object
---
### The following code is now **deprecated**.
The following code can take work with all sorts of input names; and handle them just as you'd expect.
For example:
```
<!-- All of these will work! -->
<input name="honey[badger]" value="a">
<input name="wombat[]" value="b">
<input name="hello[panda][]" value="c">
<input name="animals[0][name]" value="d">
<input name="animals[0][breed]" value="e">
<input name="crazy[1][][wonky]" value="f">
<input name="dream[as][vividly][as][you][can]" value="g">
```
```
// Output
{
"honey":{
"badger":"a"
},
"wombat":["b"],
"hello":{
"panda":["c"]
},
"animals":[
{
"name":"d",
"breed":"e"
}
],
"crazy":[
null,
[
{"wonky":"f"}
]
],
"dream":{
"as":{
"vividly":{
"as":{
"you":{
"can":"g"
}
}
}
}
}
}
```
## Usage
```
$('#my-form').serializeObject();
```
## The Sorcery (JavaScript)
```
(function($){
$.fn.serializeObject = function(){
var self = this,
json = {},
push_counters = {},
patterns = {
"validate": /^[a-zA-Z][a-zA-Z0-9_]*(?:\[(?:\d*|[a-zA-Z0-9_]+)\])*$/,
"key": /[a-zA-Z0-9_]+|(?=\[\])/g,
"push": /^$/,
"fixed": /^\d+$/,
"named": /^[a-zA-Z0-9_]+$/
};
this.build = function(base, key, value){
base[key] = value;
return base;
};
this.push_counter = function(key){
if(push_counters[key] === undefined){
push_counters[key] = 0;
}
return push_counters[key]++;
};
$.each($(this).serializeArray(), function(){
// Skip invalid keys
if(!patterns.validate.test(this.name)){
return;
}
var k,
keys = this.name.match(patterns.key),
merge = this.value,
reverse_key = this.name;
while((k = keys.pop()) !== undefined){
// Adjust reverse_key
reverse_key = reverse_key.replace(new RegExp("\\[" + k + "\\]$"), '');
// Push
if(k.match(patterns.push)){
merge = self.build([], self.push_counter(reverse_key), merge);
}
// Fixed
else if(k.match(patterns.fixed)){
merge = self.build([], k, merge);
}
// Named
else if(k.match(patterns.named)){
merge = self.build({}, k, merge);
}
}
json = $.extend(true, json, merge);
});
return json;
};
})(jQuery);
``` | Convert form data to JavaScript object with jQuery | [
"",
"javascript",
"jquery",
"json",
"serialization",
""
] |
I am developing with Eclipse + PDT. I've been adding phpdoc comments into my code,
but actually never generated a resulting documentation in Eclipse. How should I do it - is there some functionality in Eclipse, or doc generation should be done externally? | To generate the documentation, you should use [phpDocumentor](http://www.phpdoc.org/), which can be installed as a PEAR package.
Then, you have to call it from command-line ; I've never seen it called from Eclipse PDT, actually.
A great solution is to have a continuous-integration platform (using [phpUnderControl](https://github.com/phpundercontrol), for instance), and integrate to creation of the phpdoc in your build configuration file ; this way, the phpdoc is generated everytime someone commits *(or once a day, or whenever you want ^^ )*.
In Eclipse PDT, you can call "external tools" (see "Run > External Tools" in the menu) ; this would allow you to launch the phpdoc command (like you do from CLI) ; but it definitly is not as user-friendly as what Zend Studio offers -- not the same price either, though ^^ | Another great tool to generate documentation is [ApiGen](http://apigen.org/). It doesn't need installation with PEAR (but includes it) and it can be used like a standalone package. | PHPDoc documentation generator in or out of Eclipse? | [
"",
"php",
"eclipse",
"documentation",
"phpdoc",
""
] |
I have a 16 bit luminance value stored in two bytes, and I want to convert that to R, G, and B values. I have two questions: how do I convert those two bytes to a short, and assuming that the hue and saturation is 0, how do I turn that short into 8 bits per component RGB values?
(The Convert class doesn't have an option to take two bytes and output a short.) | If the 16 bit value is little endian and unsigned, the 2nd byte would be the one you want to repeat 3x to create the RGB value, and you'd drop the other byte. Or if want the RGB in a 32 bit integer, you could either use bit shifts and adds or just multiply that 2nd byte by 0x10101. | Try something like this:
```
byte luminance_upper = 23;
byte luminance_lower = 57;
int luminance = ((int)luminance_upper << 8) | (int)luminance_lower;
```
That will give you a value between 0-65535.
Of course, if you just want to end up with a 32-bit ARGB (greyscale) colour from that, the lower byte isnt going to matter because you're going from a 16-bit luminance to 8-bit R,G,B components.
```
byte luminance_upper = 255;
// assuming ARGB format
uint argb = (255u << 24) // alpha = 255
| ((uint)luminance_upper << 16) // red
| ((uint)luminance_upper << 8) // green
| (uint)luminance_upper; // blue (hope my endianess is correct)
```
Depending on your situation, there may be a better way of going about it. For example, the above code does a linear mapping, however you may get better-looking results by using a logarithmic curve to map the 16-bit values to 8-bit RGB components. | Converting a 16 bit luminance value to 32 bit RGB | [
"",
"c#",
".net",
"image",
""
] |
If the code is the same, there appears to be a difference between:
`include 'external.php';`
and
`eval('?>' . file_get_contents('external.php') . '<?php');`
What is the difference? Does anybody know?
---
I know the two are different because the `include` works fine and the `eval` gives an error. When I originally asked the question, I wasn't sure whether it gave an error on all code or just on mine (and because the code was `eval`ed, it was very hard to find out what the error meant). However, after having researched the answer, it turns out that whether or not you get the error does not depend on the code in the `external.php`, but does depend on your php settings (`short_open_tag` to be precise). | After some more research I found out what was wrong myself. The problem is in the fact that `<?php` is a "short opening tag" and so will only work if `short_open_tag` is set to 1 (in php.ini or something to the same effect). The correct full tag is `<?php`, which has a space after the second p.
As such the proper equivalent of the include is:
```
eval('?>' . file_get_contents('external.php') . '<?php ');
```
Alternatively, you can leave the opening tag out all together (as noted in the comments below):
```
eval('?>' . file_get_contents('external.php'));
```
My original solution was to add a semicolon, which also works, but looks a lot less clean if you ask me:
```
eval('?>' . file_get_contents('external.php') . '<?php;');
``` | AFAIK you can't take advantage of php accelerators if you use eval(). | PHP: Equivalent of include using eval | [
"",
"php",
"include",
"eval",
""
] |
I want to record number of hits to the pages and I'm thinking either plain file-based or SQLite storage.
**File-based option**
A file includes only an integer incremented with each page visit and every page has a unique file name. If I open a file using **a** mode, I can write but is it possible to not to close it in order to save from opening and closing the file each time?
**SQLite option**
A simple table with columns PageName and Hits. Same question again is it possible to not to close it in order to save from opening and closing the db each time? | If you really have to do this in-house, you should go with the sqlite method. While there's a little overhead (due to opening the database file), there can also be notable benefits in storing structured data.
You could for example add a date field, and then get daily/hourly/monthly/whatever data for each page.
You could also add the IP address for each visitor, and then extract visits data. That way you could easily extract data about your site users' behaviours.
You could also store your visitors' user-agent and OS, so you know what browsers you should target or not.
All in all, inserting that kind of data into a database is trivial. You can learn a lot of things from these data, if you take some time to study these. For that reason, databases are usually the way to go, since they're easy to manipulate. | [Google Analytics](http://www.google.com/analytics). Unless you *need* to do it in-house.
Rolling your own solution in PHP can be as simple or complicated as you like. You can create a table to store ip-address (not always reliable), the page location, and a date. This will allow you to track unique hits for each day. You may want to schedule a task to reduce the amount of records to a simple row of `date`, `numOfUnique`.
Another method is parsing your log files. You could do this every 24 hours or so as well. | Best practice for recording page hits using PHP? | [
"",
"php",
"sqlite",
"filesystems",
""
] |
Can we run or develop apps for iPhone in Java?
Have a look to these links and answer:
1. <http://www.iphonefaq.org/archives/9731>
2. <http://www.j2mepolish.org/cms/leftsection/documentation/platforms/iphone.html>
3. <http://www.ibm.com/developerworks/opensource/library/os-eclipse-iphone/> | Currently, there is no JVM running on the iPhone. This means that the only way you have to develop apps for iPhone in Java is to have a compiler that will compile your java code down to Objective-C code.
There are several solutions that do exactly that:
[Codename One](http://www.codenameone.com/) - focuses on building applications using Java with visual tools and simulators. Open source with a SaaS backend that removes the need for a Mac.
XMLVM - a translator to convert Java bytecode to C/Objective-C. Open source, but requires writing iOS specific code at the moment.
There are also several proprietary solutions but I have no experience with them. E.g. Software AG has a tool called web objects. | Sun found they could port Java to the iPhone, but the SDK license prohibits it. So this is not a technical but a political issue. | Can we run Java applications on iPhone? | [
"",
"java",
"iphone",
"java-me",
"j2mepolish",
""
] |
I've a *particularly* long operation that is going to get run when a
user presses a button on an interface and I'm wondering what would be the best
way to indicate this back to the client.
The operation is populating a fact table for a number of years worth of data
which will take roughly 20 minutes so I'm not intending the interface to be
synchronous. Even though it is generating large quantities of data server side,
I'd still like everything to remain responsive since the data for the month the
user is currently viewing will be updated fairly quickly which isn't a problem.
I thought about setting a session variable after the operation has completed
and polling for that session variable. Is this a feasible way to do such a
thing? However, I'm particularly concerned
about the user navigating away/closing their browser and then all status
about the long running job is lost.
Would it be better to perhaps insert a record somewhere lodging the processing record when it has started and finished. Then create some other sort of interface so the user (or users) can monitor the jobs that are currently executing/finished/failed?
Has anyone any resources I could look at?
How'd you do it? | The server side portion of code should spawn or communicate with a process that lives outside the web server. Using web page code to run tasks that should be handled by a daemon is just sloppy work. | You can't expect them to hang around for 20 minutes. Even the most cooperative users in the world are bound to go off and do something else, forget, and close the window. Allowing such long connection times screws up any chance of a sensible HTTP timeout and leaves you open to trivial DOS too.
As Spencer suggests, use the first request to start a process which is independent of the http request, pass an id back in the AJAX response, store the id in the session or in a DB against that user, or whatever you want. The user can then do whatever they want and it won't interrupt the task. The id can be used to poll for status. If you save it to a DB, the user can log off, clear their cookies, and when they log back in you will still be able to retrieve the status of the task. | Dealing with long server-side operations using ajax? | [
"",
"php",
"jquery",
"ajax",
"usability",
""
] |
In C#, is there a benefit or drawback to re-initializing a previously declared variable instead of declaring and initializing a new one? (Ignoring thoughts on conciseness and human readability.)
For example, compare these two samples:
```
DataColumn col = new DataColumn();
col.ColumnName = "Subsite";
dataTable.Columns.Add(col);
col = new DataColumn(); // Re-use the "col" declaration.
col.ColumnName = "Library";
dataTable.Columns.Add(col);
```
vs
```
DataColumn col1 = new DataColumn();
col1.ColumnName = "Subsite";
gridDataTable.Columns.Add(col1);
DataColumn col2 = new DataColumn(); // Declare a new variable instead.
col2.ColumnName = "Library";
gridDataTable.Columns.Add(col2);
```
A similar example involving loops:
```
string str;
for (int i = 0; i < 100; i++)
{
str = "This is string #" + i.ToString(); // Re-initialize the "str" variable.
Console.WriteLine(str);
}
```
vs
```
for (int i = 0; i < 100; i++)
{
string str = "This is string #" + i.ToString(); // Declare a new "str" each iteration.
Console.WriteLine(str);
}
```
**Edit:** Thank you all for your answers so far. After reading them, I thought I'd expand on my question a bit:
Please correct me if I'm wrong.
When I declare and initialize a reference type like a System.String, I have a pointer to that object, which exists on the stack, and the object's contents, which exist on the heap (only accessible through the pointer).
In the first looping example, it seems like we create only one pointer, "str", and we create 100 instances of the String class, each of which exists on the heap. In my mind, as we iterate through the loop, we are merely changing the "str" pointer to point at a new instance of the String class each time. Those "old" strings that no longer have a pointer to them will be garbage collected--although I'm not sure when that would occur.
In the second looping example, it seems like we create 100 pointers in addition to creating 100 instances of the String class.
I'm not sure what happens to items on the stack that are no longer needed, though. I didn't think the garbage collector got rid of those items too; perhaps they are immediately removed from the stack as soon as you exit their scope? Even if that's true, I'd think that creating only one pointer and updating what it points to is more efficient than creating 100 different pointers, each pointing to a unique instance.
I understand the "premature optimization is evil" argument, but I'm only trying to gain a deeper understanding of things, not optimize my programs to death. | Your second example has a much clearer answer, the second example is the better one. The reason why is that the variable str is only used within the for block. Declaring the variable outside the for block means that it's possible for another piece of code to incorrectly bind to this variable and hence cause bugs in your application. You should declare all variables in the most specific scope possible to prevent accidental usage.
For the first sample I believe it's more a matter of preference. For me, I chose to create a new variable because I believe each variable should have a single purpose. If I am reusing variables it's usually a sign that I need to refactor my method. | This sounds suspiciously like a question designed to provide information for premature optimization. I doubt that either scenario is different in any way that matters in 99.9% of software. The memory is being created and used either way. The only difference is the variable references.
To find out if there is a benefit or drawback, you would need a situation where you really care about the size or the performance of the assembly. If you can't meet the size requirements, then measure the assembly size differences between the two choices (although you're more likely to make gains in other areas). If you can't meet the performance requirements, then use a profiler to see which part of your code is working too slowly. | Re-initialize variable or declare new? | [
"",
"c#",
""
] |
I have an class named Foo. This class contains a collection of child objects of type FooChildBase, but I also have a further class of type FooChildTwo which inherits from FooChildBase.
```
Class Foo
Public Children As IList(Of FooChildBase)
End Class
Class FooChildBase
Public Info As String
End Class
Class FooChildTwo
Inherits FooChildBase
Public ExtraInfo As String
End Class
```
This all works fine. Now I need to use a specialisation of my Foo object with extra information.
```
Class FooSpecial
Inherits Foo
Public SpecialInfo As String
End Class
Class FooChildSpecial
Inherits FooChildBase
Public SpecialChildInfo As String
End Class
```
What I would like to do is have my FooSpecial Class treat it's Children collection as if they were FooChildSpecial objects, but still be able to add FooChildTwo objects to it. Is this possible and if so how can it be done?
**EDIT**
I think my original question was incorrect. I need to FooChildSpecial class to wrap any of the objects in the Children collection with the extra values, whether they are FooChildBase or FooChildTwo or XXX.
Hope this makes sense! Please let me know if more clarification is needed.
James | In order for FooSpecialChild to "Wrap" FooChildTwo, it either has to inherit from it or implement the same interface (IFooChildTwo). Unfortunately, you cannot conditionally inherit or implement ... it is either always or never. As such, your FooSpecialChild class *can* inherit from FooChildTwo, but then it will *always* be a FooChildTwo. Same if it implements the same interface as FooChildTwo.
The design pattern you laid out will work correctly. Since both FooChildSpecial and FooChildTwo inherit from the same base class, and the list is of that base class type, it will work out. You'll just have to check the type of the object when you're pulling from the .Children property.
After copy+pasting your code into a sample project, I could successfully do:
```
var foo = new Foo();
foo.Children = new List<FooChildBase>();
var special = new FooChildSpecial();
special.SpecialChildInfo = "special";
foo.Children.Add(special);
var two = new FooChildTwo();
two.ExtraInfo = "two";
foo.Children.Add(two);
```
Which shows that you can add both FooChildSpecial and FooChildTwo to your original list. | What do you mean by "treat as if they were FooChildSpecial" objects? Do you mean access methods that exist only in FooChildSpecial objects?
In this case you will need to cast them to FooChildSpecial.
However, it is better to just let FooSpecial treat them as FooChildBase objects, but have in FooChildSpecial and FooChildTwo that override the base methods to get different behaviors for the two subclasses.
I also have a feeling that you really don't need the FooSpecial class at all, but I could be wrong. I suspect that the extra information and special information could just be combined into "information" and if they need different types of information to initialize the class wtih the different types. | Extending an object and any child collections? | [
"",
"c#",
"vb.net",
"design-patterns",
"architecture",
""
] |
Do I really need to implement it myself?
```
private void shrinkListTo(ArrayList<Result> list, int newSize) {
for (int i = list.size() - 1; i >= newSize; --i)
list.remove(i);
}
``` | Create a [sublist](http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#subList-int-int-) with the range of elements you wish to remove and then call [`clear`](http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#clear--) on the returned list.
```
list.subList(23, 45).clear()
```
This approach is mentioned as an idiom in the documentation for both [List](https://docs.oracle.com/javase/8/docs/api/java/util/List.html#subList-int-int-) and [ArrayList](http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#subList-int-int-).
---
Here's a fully unit tested code example!
```
// limit yourHappyList to ten items
int k = yourHappyList.size();
if ( k > 10 )
yourHappyList.subList(10, k).clear();
// sic k, not k-1
``` | alternatively you can use [subList](http://java.sun.com/javase/6/docs/api/java/util/List.html#subList) method:
```
public static <T> List<T> shrinkTo(List<T> list, int newSize) {
return list.subList(0, newSize - 1);
}
``` | Shrinking an ArrayList to a new size | [
"",
"java",
"arraylist",
""
] |
Hope the title explains it all, but all I'm trying to do is open some .php files in my web-site solution and have Visual studio treat them as if they are html files. I don't need the actual PHJP code highlighted (it's only includes). The HTML syntax should be parse-able, should it not? | You can also install the PHP Tools for Visual Studio add-in. Tools > Extension and Updates and then search for PHP online. Your first result should be this add-in.
If not, you can get it from here:
<http://visualstudiogallery.msdn.microsoft.com/6eb51f05-ef01-4513-ac83-4c5f50c95fb5> | Tools -> Options -> Text Editor -> File Extension
in the Extension box, put .php. For the Editor, you can select HTML Editor. Click Add, then OK | How can I make visual studio highlight .php files | [
"",
"php",
"visual-studio",
""
] |
When I first moved from c to Java I thought that I've finished will all the annoying parameter checks in the begining of every function . (Blessed exceptions)
Lately I've realized that I'm slowly moving back to that practice again , and I'm starting to get really annoyed with all the
```
if (null == a || null == b || null == a.getValue() || ...)
{
return null;
}
```
For example , I have a utility class that analyses web pages and extract specific elements from them. Any call to dom object function with null elements usually results in an exception - So in almost any function I write in this class has countless null checks :
```
private URL extractUrl(Element element) throws Exception {
if (null == element) {
return null;
} ...
public List<Object> getConcreteElements(String xpath) throws Exception {
if (null == xpath) {
return Collections.emptyList();
}...
public String getElementsAsXML(String xpath) throws Exception {
if (null == xpath) {
return null;
}...
```
in the beginning of every function. Is this something I should get used too or is there some coding practice I'm unaware of that can simplify my life? | Yes, they're absolutely annoying. A few small things I've found that at least minimize this:
* Clearly document in internal api's functions that can't return null, or under what conditions you can expect null. If you can trust your documentation, at least, this allows you to avoid null checks in certain places.
* Some idioms minimize null checks - e.g.
if (string!=null && string.equals("A") --> if ("A".equals(string))
* eclipse (as well as findbugs, I think, and probably many other ide's) can be set to flag redundant null checks, or missing null checks. Not perfect, but it helps.
But overall, you're correct. If my code didn't have null checks and logging statements, there wouldn't be anything there at all;) | Returning null means the caller must ALWAYS check the result from your method. Meaning MORE miserable null checks.
Consider using the NullObject pattern instead, where you return a valid object but having empty operations. I.e. an empty list if a collection is returned or similar. | Checking all function parameter in all the functions | [
"",
"java",
"validation",
"parameters",
"function",
""
] |
Consider the query (it runs on both Oracle and MySQL)
```
UPDATE table1
SET something_id = CASE
WHEN table1_id = 1446 THEN 423
WHEN table1_id = 2372 THEN 426
WHEN table1_id = 2402 THEN 428
WHEN table1_id = 2637 THEN 429
WHEN table1_id = 2859 THEN 430
WHEN table1_id = 3659 THEN 433
END
WHERE table1_id IN (1446,2372,2402,2637,2859,3659)
```
This query can get quite large, so I was wondering what is the limit on the number of conditions (WHEN, THEN statements) a single query can hold. Is there a way around it?
**For example:**
I know that the max number of values that can be passed to `IN` is 1000 and to overcome this we can do
```
`WHERE TABLE1_ID IN ([1000 values]) OR TABLE1_ID IN ([more values])`
``` | The docs for [10gR2](http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/expressions004.htm#i1033392) say:
> The maximum number of arguments in a
> CASE expression is 255. All
> expressions count toward this limit,
> including the initial expression of a
> simple CASE expression and the
> optional ELSE expression. Each WHEN
> ... THEN pair counts as two arguments.
> To avoid exceeding this limit, you can
> nest CASE expressions so that the
> return\_expr itself is a CASE
> expression. | Put your correspondences into a helper table:
```
id value
1446 423
2372 426
…
```
and join.
In `Oracle`:
```
UPDATE (
SELECT something_id, value
FROM table1
JOIN helper
ON table1.table1_id = helper.id
)
SET something_id = value
```
(don't forget to make `helper.id` a `PRIMARY KEY` for this to work)
In `MySQL`:
```
UPDATE table1
JOIN helper
ON table1.table1 = helper.id
SET table1.something_id = value
``` | SQL: Limit on CASE (number of WHEN, THEN conditions) | [
"",
"sql",
"mysql",
"oracle",
""
] |
I would like to be able to programmatically emulate the keyboard
navigation for dialog boxes.
I have a custom hardware device with a keypad that I would like to use for
dialog box navigation.
I know about Focus(), but I'd rather do something that automatically
respected the tab order. By emulating the keyboard navigation I don't
have to worry about re-inventing complex behavior for each type of
control.
Does anyone know how to do this?
Thanks! | You could use P/Invoke to call the Windows API function [keybd\_event](http://msdn.microsoft.com/en-us/library/ms646304(VS.85).aspx) to simulate pressing the Tab key.
Bonus: you can use your device to enter tabs into a text editor as well! ;) | For Winforms, you want want the [`Control.GetNextControl()`](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.getnextcontrol.aspx) method
For WPF, you want the [`UIElement.MoveFocus()`](http://msdn.microsoft.com/en-us/library/system.windows.uielement.movefocus.aspx) method | C# How to programmatically tab between controls | [
"",
"c#",
""
] |
I'm working on a C# class library that needs to be able to read settings from the `web.config` or `app.config` file (depending on whether the DLL is referenced from an ASP.NET web application or a Windows Forms application).
I've found that
```
ConfigurationSettings.AppSettings.Get("MySetting")
```
works, but that code has been marked as deprecated by Microsoft.
I've read that I should be using:
```
ConfigurationManager.AppSettings["MySetting"]
```
However, the `System.Configuration.ConfigurationManager` class doesn't seem to be available from a C# Class Library project.
What is the best way to do this? | You'll need to **add a reference** to `System.Configuration` in your project's **references folder**.
You should definitely be using the `ConfigurationManager` over the obsolete `ConfigurationSettings`. | For a sample app.config file like below:
```
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="countoffiles" value="7" />
<add key="logfilelocation" value="abc.txt" />
</appSettings>
</configuration>
```
You read the above application settings using the code shown below:
```
using System.Configuration;
```
You may also need to also add a reference to `System.Configuration` in your project if there isn't one already. You can then access the values like so:
```
string configvalue1 = ConfigurationManager.AppSettings["countoffiles"];
string configvalue2 = ConfigurationManager.AppSettings["logfilelocation"];
``` | Reading settings from app.config or web.config in .NET | [
"",
"c#",
".net",
"configuration",
"appsettings",
""
] |
The way i currently populate business objects is using something similar to the snippet below.
```
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.CDRDatabase))
{
using (SqlCommand comm = new SqlCommand(SELECT, conn))
{
conn.Open();
using (SqlDataReader r = comm.ExecuteReader(CommandBehavior.CloseConnection))
{
while (r.Read())
{
Ailias ailias = PopulateFromReader(r);
tmpList.Add(ailias);
}
}
}
}
private static Ailias PopulateFromReader(IDataReader reader)
{
Ailias ailias = new Ailias();
if (!reader.IsDBNull(reader.GetOrdinal("AiliasId")))
{
ailias.AiliasId = reader.GetInt32(reader.GetOrdinal("AiliasId"));
}
if (!reader.IsDBNull(reader.GetOrdinal("TenantId")))
{
ailias.TenantId = reader.GetInt32(reader.GetOrdinal("TenantId"));
}
if (!reader.IsDBNull(reader.GetOrdinal("Name")))
{
ailias.Name = reader.GetString(reader.GetOrdinal("Name"));
}
if (!reader.IsDBNull(reader.GetOrdinal("Extention")))
{
ailias.Extention = reader.GetString(reader.GetOrdinal("Extention"));
}
return ailias;
}
```
Does anyone have any suggestions of how to improve performance on something like this? Bear in mind that PopulateFromReader, for some types, contains more database look-ups in order to populate the object fully. | One obvious change would be to replace this kind of statement:
ailias.AiliasId = reader.GetInt32(reader.GetOrdinal("AiliasId"));
with
```
ailias.AiliasId = reader.GetInt32(constAiliasId);
```
where constAiliasId is a constant holding the ordinal of the field AiliasId.
This avoids the ordinal lookups in each iteration of the loop. | If the data volume is high, then it can happen that the overhead of building a huge list can be a bottleneck; in which case, it can be more efficient to use a streaming object model; i.e.
```
public IEnumerable<YourType> SomeMethod(...args...) {
using(connection+reader) {
while(reader.Read()) {
YourType item = BuildObj(reader);
yield return item;
}
}
}
```
The consuming code (via `foreach` etc) then only has a single object to deal with (at a time). If they *want* to get a list, they can (with new `List<SomeType>(sequence)`, or in .NET 3.5: `sequence.ToList()`).
This involves a few more method calls (an additional `MoveNext()`/`Current` per sequence item, hidden behind the `foreach`), but you will never notice this when you have out-of-process data such as from a database. | Improving DAL performance | [
"",
"c#",
"performance",
"idatareader",
""
] |
I would like to update all properties from MyObject to another using Reflection. The problem I am coming into is that the particular object is inherited from a base class and those base class property values are not updated.
The below code copies over top level property values.
```
public void Update(MyObject o)
{
MyObject copyObject = ...
FieldInfo[] myObjectFields = o.GetType().GetFields(
BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo fi in myObjectFields)
{
fi.SetValue(copyObject, fi.GetValue(o));
}
}
```
I was looking to see if there were any more BindingFlags attributes I could use to help but to no avail. | Try this:
```
public void Update(MyObject o)
{
MyObject copyObject = ...
Type type = o.GetType();
while (type != null)
{
UpdateForType(type, o, copyObject);
type = type.BaseType;
}
}
private static void UpdateForType(Type type, MyObject source, MyObject destination)
{
FieldInfo[] myObjectFields = type.GetFields(
BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo fi in myObjectFields)
{
fi.SetValue(destination, fi.GetValue(source));
}
}
``` | I wrote this as an extension method that works with different types too. My issue was that I have some models bound to asp mvc forms, and other entities mapped to the database. Ideally I would only have 1 class, but the entity is built in stages and asp mvc models want to validate the entire model at once.
Here is the code:
```
public static class ObjectExt
{
public static T1 CopyFrom<T1, T2>(this T1 obj, T2 otherObject)
where T1: class
where T2: class
{
PropertyInfo[] srcFields = otherObject.GetType().GetProperties(
BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty);
PropertyInfo[] destFields = obj.GetType().GetProperties(
BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty);
foreach (var property in srcFields) {
var dest = destFields.FirstOrDefault(x => x.Name == property.Name);
if (dest != null && dest.CanWrite)
dest.SetValue(obj, property.GetValue(otherObject, null), null);
}
return obj;
}
}
``` | C# Using Reflection to copy base class properties | [
"",
"c#",
"reflection",
"copy",
""
] |
One of my developers working on a trigger-based logging facility in SQL Server 2008 asked me if there was a command to retrieve the *most recently executed SQL command* within T-SQL. I thought there was a system stored procedure for just such a function, but it's possible I'm thinking of another product from a prior decade... online searches yielded us no results.
Does anyone have information on anything of the sort? | sure try this :
```
SELECT
DMExQryStats.last_execution_time AS [Executed At],
DMExSQLTxt.text AS [Query]
FROM
sys.dm_exec_query_stats AS DMExQryStats
CROSS APPLY
sys.dm_exec_sql_text(DMExQryStats.sql_handle) AS DMExSQLTxt
ORDER BY
DMExQryStats.last_execution_time DESC
```
it will returns recently executed queries along with the date and time at which they were executed | Well, the procedure that retrieves the most current SQL batch can safely return itself :)
On a serious note, you can look at [`sys.dm_exec_query_stats`](http://msdn.microsoft.com/en-us/library/ms189741.aspx) and [`sys.dm_exec_procedure_stats`](http://msdn.microsoft.com/en-us/library/cc280701.aspx) to see when a plan was last time executed, based on the `last_execution_time` column. But note that the method **is not reliable** because it does not account for plans that were evicted from the cache after execution. | retrieve most recently executed SQL command (T-SQL) | [
"",
"sql",
"t-sql",
"stored-procedures",
"system-stored-procedures",
""
] |
Hi I want to create my custom collection, I am deriving my custom collection class from CollectionBase class as below:
```
public class MyCollection : System.Collections.CollectionBase
{
MyCollection(){}
public void Add(MyClass item)
{
this.List.Add(item);
}
}
class MyClass
{
public string name;
}
```
Let me ask a few questions:
1. Whether this approach is correct and new, as I working on .NET 3.5 framework.
2. I want to expose this collection from my web service ( WCF) .How can I do that?
3. Do I have to implement GetEnumerator?
4. Whether this will Bind to DataGridView. | Deriving from `List<T>` is somewhat pointless, *especially* now that it has the `IEnumerable<T>` constructor and the availability of extension methods. It has no virtual methods that you can override except `Equals`, `GetHashCode`, and `ToString`. (I suppose you could derive from `List<T>` if your goal was to implement Java's toString() functionality for lists.)
If you want to create your own strongly-typed collection class and possibly customize the collection behavior when items are add/removed, you want to derive from the new (to .NET 2.0) type [`System.Collections.ObjectModel.Collection<T>`](http://msdn.microsoft.com/en-us/library/ms132397.aspx), which has protected virtual methods including `InsertItem` and `RemoveItem` that you can override to perform actions at those times. Be sure to read the documentation - this is a *very easy* class to derive from but you have to realize the difference between the public/non-virtual and protected/virtual methods. :)
```
public class MyCollection : Collection<int>
{
public MyCollection()
{
}
public MyCollection(IList<int> list)
: base(list)
{
}
protected override void ClearItems()
{
// TODO: validate here if necessary
bool canClearItems = ...;
if (!canClearItems)
throw new InvalidOperationException("The collection cannot be cleared while _____.");
base.ClearItems();
}
protected override void RemoveItem(int index)
{
// TODO: validate here if necessary
bool canRemoveItem = ...;
if (!canRemoveItem)
throw new InvalidOperationException("The item cannot be removed while _____.");
base.RemoveItem(index);
}
}
``` | I think you would be better off using one of the container classes defined in System.Collections.Generic
1. Whether this approach is correct and new, as I working on .NET 3.5 framework.
* No. Use List or something instead.
2. I want to expose this collection from my web service ( WCF) .How can I do that?
* pass. haven't used WCF.
3. Do I have to implement GetEnumerator?
* not if you use one of the standard System.Collections.Generic container classes. It's already done for you
4. Whether this will Bind to DataGridView.
* Any of the standard collections that support IEnumerable will bind to controls pretty well. You could look at using IBindingListView if you want sorting and filtering. | How to create a custom collection in .NET 2.0 | [
"",
"c#",
"wcf",
"generics",
"datagridview",
""
] |
I am creating a C++ Win32 dll with some global data. There is a std::map defined globally and there are exported functions in the dll that write data into the map (after acquiring a write lock, ofcourse).
My problem is, when I call the write function from inside the dll DllMain, it works without any problems. But when I load the dll from another program and call the function that writes data into the global map, it gives me this error:
```
WindowsError: exception: access violation reading 0x00000008
```
Is there something that can be done about this? The same function when called from DllMain has access to the global data in the dll, but when called from a different process, it doesn't have access to the global data. Please advice.
I am using the TDM-MinGW gcc 4.4.0 Compiler.
**EDIT:**
Ok, I've figured out what the problem is, and thanks for the help guys, but the problem was not with a constructor issue or inability to have maps in global space, but an issue in the boost::python that I'm using. I had tested it, but since I was calling the dll from within python or maybe something, the urllib2 module wasn't getting loaded into the dll. Now I have to see how to fix it. | Looks like the constructor of `std::map` did not run yet when your code was called. Lifetime of global non-PODs in a Win32 DLL is pretty tricky, and I'm not certain as to how MinGW specifically handles it. But it may be that the way you're compiling the DLL, you've set your own function (`DllMain`?) as an entry point, and thus overrode the CRT initialization routine that calls constructors. | A read error at such a low memory address generally means that you are trying to access a NULL pointer somewhere. Can you show your actual code? | Access to global data in a dll from an exported dll function | [
"",
"c++",
"winapi",
"dll",
"tdm-mingw",
""
] |
Does anyone know of a robust (and bullet proof) is\_JSON function snippet for PHP? I (obviously) have a situation where I need to know if a string is JSON or not.
Hmm, perhaps run it through a [JSONLint](http://www.jsonlint.org) request/response, but that seems a bit overkill. | If you are using the built in [`json_decode`](http://php.net/manual/en/function.json-decode.php) PHP function, [**`json_last_error`**](http://php.net/manual/en/function.json-last-error.php) returns the last error (e.g. [**`JSON_ERROR_SYNTAX`**](http://php.net/manual/en/function.json-last-error.php) when your string wasn't JSON).
Usually [`json_decode`](http://php.net/manual/en/function.json-decode.php) returns `null` anyway. | For my projects I use this function (please read the "**Note**" on the [json\_decode()](http://php.net/manual/en/function.json-decode.php#refsect1-function.json-decode-parameters) docs).
Passing the same arguments you would pass to json\_decode() you can detect specific application "errors" (e.g. depth errors)
With PHP >= 5.6
```
// PHP >= 5.6
function is_JSON(...$args) {
json_decode(...$args);
return (json_last_error()===JSON_ERROR_NONE);
}
```
With PHP >= 5.3
```
// PHP >= 5.3
function is_JSON() {
call_user_func_array('json_decode',func_get_args());
return (json_last_error()===JSON_ERROR_NONE);
}
```
Usage example:
```
$mystring = '{"param":"value"}';
if (is_JSON($mystring)) {
echo "Valid JSON string";
} else {
$error = json_last_error_msg();
echo "Not valid JSON string ($error)";
}
``` | How to determine whether a string is valid JSON? | [
"",
"php",
"json",
"validation",
"code-snippets",
"jsonlint",
""
] |
I am doing Image uploader in Asp.net and I am giving following code under my controls:
```
string st;
st = tt.PostedFile.FileName;
Int32 a;
a = st.LastIndexOf("\\");
string fn;
fn = st.Substring(a + 1);
string fp;
fp = Server.MapPath(" ");
fp = fp + "\\";
fp = fp + fn;
tt.PostedFile.SaveAs("fp");
```
But during uploading or saving image the error message comes that The **SaveAs method is configured to require a rooted path, and the path 'fp' is not rooted.**
So Please help me what is the problem | I suspect the problem is that you're using the string "fp" instead of the variable `fp`. Here's the fixed code, also made (IMO) more readable:
```
string filename = tt.PostedFile.FileName;
int lastSlash = filename.LastIndexOf("\\");
string trailingPath = filename.Substring(lastSlash + 1);
string fullPath = Server.MapPath(" ") + "\\" + trailingPath;
tt.PostedFile.SaveAs(fullPath);
```
You should also consider changing the penultimate line to:
```
string fullPath = Path.Combine(Server.MapPath(" "), trailingPath);
```
You might also want to consider what would happen if the posted file used / instead of \ in the filename... such as if it's being posted from Linux. In fact, you could change the whole of the first three lines to:
```
string trailingPath = Path.GetFileName(tt.PostedFile.FileName));
```
Combining these, we'd get:
```
string trailingPath = Path.GetFileName(tt.PostedFile.FileName));
string fullPath = Path.Combine(Server.MapPath(" "), trailingPath);
tt.PostedFile.SaveAs(fullPath);
```
Much cleaner, IMO :) | Use **`Server.MapPath()`**:
```
fileUploader.SaveAs(Server.MapPath("~/Images/")+"file.jpg");
``` | The SaveAs method is configured to require a rooted path, and the path 'fp' is not rooted | [
"",
"c#",
".net",
"file",
""
] |
I'm looking for a debugging tool that will run my Python app, but display which line is currently being processed -- like an automatically stepping debugger. Basically I want to see what is going on, but be able to jump in if a traceback occurs. | [Winpdb](http://winpdb.org/) is a good python debugger. It is written in Python under the GPL, so adding the automatic stepping functionality you want should not be too complicated. | I think you're looking for the [pdb](http://docs.python.org/library/pdb) module. | "Watching" program being processed line-by-line? | [
"",
"python",
"debugging",
""
] |
I'm after a cross-platform cross-browser way of uploading files such that there is no timeout. Uploads aren't necessarily huge -- some just take a long time to upload because of the uploader's slow connection -- but the server times out anyway.
I hear that there are methods to upload files in chunks so that somehow the server decides not to timeout the upload. After searching around all I can see is proprietary upload helpers and Java and Flash (SWFUpload) widgets that aren't cross-platform, don't upload in chunks, or aren't free.
I'd like a way to do it in any of these platforms (ASP, ASP.NET 2.0 or PHP5), though I am not very clued up on all this .NET class/controller/project/module/visual studio/compile/etc stuff, so some kind of runnable complete project that runs on .NET 2.0 would be helpful. PHP and ASP I can assume will be more straight-forward.
Unless I am completely missing something, which I suspect/hope I am, reasonable web uploads are bloody hard work in any language or platform.
So my question is: how can I perform web browser uploads, cross-platform, so that they don't timeout, using free software? Is it possible at all? | I imagine the solution that you are really looking for is to gain more control over the server. IIS for example has a timeout setting in addition to any setting you provide in web.config or your php.ini. If php is running in fast cgi then you also have fast cgi configuration.
You can then set relevant file size, memory and timeout settings in php.ini / web.config:
php.ini - <http://www.radinks.com/upload/config.php>
web.config -
```
<httpRuntime executionTimeout="1000" maxRequestLength="400000">
```
Asp.net provides the possibility to create html modules which provide some of the slicker (asp.net) upload controls, such as multiple uploads, straight to disk (less server memory usage) and upload progress controls, most of these are commercial though. | No matter what language will deal with the file after the upload is complete, the actual upload is handled by the HTTP server (Apache, IIS, etc.). The way I've seen 'progress bars' or other graphical uploads done in Flash is that there is an AJAX call made to a second script that uploads the file (which locks that thread until the upload is done), and the first script checks the file size of the incoming temporary file for a percentage done.
If you're getting server timeouts while uploading, the issue is likely with your HTTP server (Apache/IIS) configuration, and not holding the connection open log enough. If you tried to set up a PHP file upload system and were getting PHP error messages, likely the '`upload_max_filesize`', '`memory_limit`', or '`post_max_size`' is set incorrectly in your `PHP.ini` (see [PHP's post on file upload pitfals](http://www.php.net/manual/en/features.file-upload.common-pitfalls.php "PHP's tutorial on file uploads")). | Open source file upload with no timeout on IIS6 with ASP, ASP.NET 2.0 or PHP5 | [
"",
"php",
"asp.net",
"asp-classic",
"file-upload",
"timeout",
""
] |
> **Possible Duplicate:**
> [What is the cross-platform way of obtaining the path to the local application data directory?](https://stackoverflow.com/questions/11113974/what-is-the-cross-platform-way-of-obtaining-the-path-to-the-local-application-da)
I'm looking for a way to get the location of the local application data folder, which is a special Windows folder, in Java.
Unfortunately, the following only works for English versions of Windows XP with default settings:
```
System.getProperty("user.home") + "\\Local Settings\\Application Data"
```
What I'd like to have is something like this in .NET:
```
System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
```
Is there a way to do it without having to call [SHGetSpecialFolderLocation](http://msdn.microsoft.com/en-us/library/bb762203(VS.85).aspx) of the Windows Shell API? | Reading the "Shell Folders" registry key is deprecated starting from Windows 95. The registry key contains a note saying "!Do not use this registry key. Use the SHGetFolderPath or SHGetKnownFolderPath instead." I had to find this out the hard way on a Vista system where all the keys were missing except for the warning note.
[This related stackoverflow answer](https://stackoverflow.com/questions/585534/what-is-the-best-way-to-find-the-users-home-directory-in-java) solves this problem on Windows using JNA, which is the solution I'm currently using. | ```
System.getenv("APPDATA")
```
(there seems to be no env variable for the "Local Settings" folder, but this will give you the 'Application Data' folder) | How to get local application data folder in Java? | [
"",
"java",
"windows",
"shell",
""
] |
How can use a dropdown list without the autopostback=true.
The value on the server is not being changed according to the one selected from the client side. As I already stated I do not wish that for each dropdown I have the autopostback will trigger a post back. | Any time I have lost the value of the drop-down it is because I messed up and repopulated the drop down before handling the value change. For me, it has been drop-downs that I need to do something special with like add item attributes for Javascript, etc. This is data that needs to be added on every page load (aka data that is not persisted in the drop down like the names and values of each item). In these cases I have done this work on load, then I try to retrieve the value later in the page lifecycle and DOH!
Here is the page lifecycle:
<http://msdn.microsoft.com/en-us/library/ms178472.aspx>
Dollars to donuts that is what is happening. You are probably just reloading the items before you get to handling whatever postback event you are using to grab the value. If you are doing this and cannot get around this work flow, just save the selected index at the beginning of the logic that populates the drop-down, then set the selected index of the drop down with that value when done. | it'll be saved in the viewstate, so the value will be correct when you do eventually post back, and if you're really desperate to get the current value without a postback, javascript would be the way to do this. | ASP.NET VS2008 C# - dropdown list - postback | [
"",
"c#",
"asp.net",
"drop-down-menu",
"postback",
""
] |
Hi is there a possibility to set time limit only to a command or only to a function eg:
```
function doSomething()
{
//..code here..
function1();
//.. some code here..
}
```
I want to set time limit only to function1.
There exits set\_time\_limit but I think this sets the time limit to whole script.
Anybody any Idea? | set\_time\_limit() does run globally, but it can be reset locally.
> Set the number of seconds a script is allowed to run. If this is reached,
> the script returns a fatal error. The default limit is 30 seconds or, if it
> exists, the max\_execution\_time value defined in the php.ini.
>
> When called, `set_time_limit(`) restarts the timeout counter from zero. In
> other words, if the timeout is the default 30 seconds, and 25 seconds
> into script execution a call such as set\_time\_limit(20) is made, the script
> will run for a total of 45 seconds before timing out.
I've not tested it, but you may be able to set it locally, resetting when you leave the
```
<?php
set_time_limit(0); // global setting
function doStuff()
{
set_time_limit(10); // limit this function
// stuff
set_time_limit(10); // give ourselves another 10 seconds if we want
// stuff
set_time_limit(0); // the rest of the file can run forever
}
// ....
sleep(900);
// ....
doStuff(); // only has 10 secs to run
// ....
sleep(900);
// ....
```
[`set_time_limit`()](http://php.net/manual/en/function.set-time-limit.php) ... *Any time spent on activity that happens outside the execution of the script such as system calls using system(), stream operations, database queries, etc. is not included when determining the maximum time that the script has been running. This is not true on Windows where the measured time is real.* | You would need to code that yourself if you want function1 to return when the time limit is up.
```
function doStuff($seconds)
{
$finish=time()+$seconds;
$done=false;
$timeout=false;
while (!$done && !$timeout)
{
//do stuff here, set $done to true if you complete
//out of time?
$timeout=time() >= $finish;
}
return $done; //let caller know if we completed
}
```
Of course, the "stuff" that you do needs to be iterative so that you can keep checking on your elapsed time and quit if necessary.
If you want timeout execution of an arbitrary function and have control returned to you, that is not supported. If you really need to do this, engineer it as a separate process. Then you can close the process if it seems to be taking too long. | Limit execution time of an function or command PHP | [
"",
"php",
"time",
"runtime",
"limit",
"execution",
""
] |
I want to modify my xml file in PHP based on the following criteria.
my xml structure look like this:
```
<?xml version="1.0" encoding="ISO-8859-1" ?>
<markers>
<marker>
<type></type>
<title></title>
<address></address>
<latitude></latitude>
<longitude></longitude>
<marker>
<marker>
<type></type>
<title></title>
<address></address>
<latitude></latitude>
<longitude></longitude>
<marker>
</markers>
```
Now every time when xml going to modify, with the type attribute.
means, on first time search string == "hotels" then data related to hotels will be stored in xml file as above format.
Now when again search for hotels is done then it will remove the elements which have child element with value hotels.
and search for different query for e.g. schools is done at that time data related to the schools are appended to the xml file. with the data of the hotels.
now again search for schools is done then it will remove the element related to schools.
Thanks in advance. | You can use the **DOMDocument** from **PHP**.
You load your file and than loop trough the **childNodes** of the document.
```
<?php
$dom=new DOMDocument();
$dom->load("file.xml");
$root=$dom->documentElement; // This can differ (I am not sure, it can be only documentElement or documentElement->firstChild or only firstChild)
$nodesToDelete=array();
$markers=$root->getElementsByTagName('marker');
// Loop trough childNodes
foreach ($markers as $marker) {
$type=$marker->getElementsByTagName('type')->item(0)->textContent;
$title=$marker->getElementsByTagName('title')->item(0)->textContent;
$address=$marker->getElementsByTagName('address')->item(0)->textContent;
$latitude=$marker->getElementsByTagName('latitude')->item(0)->textContent;
$longitude=$marker->getElementsByTagName('longitude')->item(0)->textContent;
// Your filters here
// To remove the marker you just add it to a list of nodes to delete
$nodesToDelete[]=$marker;
}
// You delete the nodes
foreach ($nodesToDelete as $node) $node->parentNode->removeChild($node);
echo $dom->saveXML();
?>
```
You can save your output XML like this
```
$dom->saveXML(); // This will return the XML as a string
$dom->save('file.xml'); // This saves the XML to a file
```
To do this parsing in **JavaScript** you should use [jQuery](http://jquery.com/ "jQuery") (a small, but powerful library).
You can include the library directly from Google Code Repository.
```
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
```
*The library is cross-browser and very small. It should be cached in many cases, because some sites use it from Google Code*
```
$(yourXMLStringOrDocument).find("marker").each(function () {
var marker=$(this);
var type=marker.find('type').text();
var title=marker.find('title').text();
var address=marker.find('address').text();
var latitude=marker.find('latitude').text();
var longitude=marker.find('longitude').text();
});
``` | Document Object Model (DOM) is the answer.
```
<?
$dom=new DomDocument();
$dom->Load("file.xml");
$root=$dom->documentElement;
...
$dom->Save("file.xml");
?>
``` | How to modify xml file using PHP | [
"",
"php",
"xml",
""
] |
I want to use RSA public key encryption. What is the best way to store or retrieve private and public keys? Is XML a good idea here?
How to get the keys?
```
RSAParameters privateKey = RSA.ExportParameters(true);
RSAParameters publicKey = RSA.ExportParameters(false);
```
Because RSAParameters have the following members: D, DP, DQ, Exponent, InverseQ, Modulus, P, Q
Which one is the key? | What I have done successfully is to store the keys as XML. There are two methods in RSACryptoServiceProvider: ToXmlString and FromXmlString. The ToXmlString will return an XML string containing either just the public key data or both the public and private key data depending on how you set its parameter. The FromXmlString method will populate the RSACryptoServiceProvider with the appropriate key data when provided an XML string containing either just the public key data or both the public and private key data. | I wanted to point out something as a response to a comment by ala asking if:
> Public Key = modulus + exponent
That is exactly correct. There are a few ways of storing this `exponent` + `modulus`. The first attempt at a standard was in [RFC 3447](https://www.rfc-editor.org/rfc/rfc3447) (*Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography Specifications Version 2.1*), which defines a structure for a public key of called [**`RSAPublicKey`**](https://www.rfc-editor.org/rfc/rfc3447#page-44):
```
RSAPublicKey ::= SEQUENCE {
modulus INTEGER, -- n
publicExponent INTEGER -- e
}
```
The same RFC goes on to declare that you should use the [**DER** flavor of `ASN.1` encoding](http://msdn.microsoft.com/en-us/library/windows/desktop/bb648640(v=vs.85).aspx) to store the public key. i have a sample public key:
* **publicExponent**: 65537 *(it is convention that all RSA public keys use 65537 as their exponent)*
* **modulus**: `0xDC 67 FA F4 9E F2 72 1D 45 2C B4 80 79 06 A0 94 27 50 8209 DD 67 CE 57 B8 6C 4A 4F 40 9F D2 D1 69 FB 995D 85 0C 07 A1 F9 47 1B 56 16 6E F6 7F B9 CF 2A 58 36 37 99 29 AA 4F A8 12 E8 4F C7 82 2B 9D 72 2A 9C DE 6F C2 EE 12 6D CF F0 F2 B8 C4 DD 7C 5C 1A C8 17 51 A9 AC DF 08 22 04 9D 2B D7 F9 4B 09 DE 9A EB 5C 51 1A D8 F8 F9 56 9E F8 FB 37 9B 3F D3 74 65 24 0D FF 34 75 57 A4 F5 BF 55`
The DER ASN.1 encoding of this public key is:
```
30 81 89 ;SEQUENCE (0x89 bytes = 137 bytes)
| 02 81 81 ;INTEGER (0x81 bytes = 129 bytes)
| | 00 ;leading zero of INTEGER
| | DC 67 FA
| | F4 9E F2 72 1D 45 2C B4 80 79 06 A0 94 27 50 82
| | 09 DD 67 CE 57 B8 6C 4A 4F 40 9F D2 D1 69 FB 99
| | 5D 85 0C 07 A1 F9 47 1B 56 16 6E F6 7F B9 CF 2A
| | 58 36 37 99 29 AA 4F A8 12 E8 4F C7 82 2B 9D 72
| | 2A 9C DE 6F C2 EE 12 6D CF F0 F2 B8 C4 DD 7C 5C
| | 1A C8 17 51 A9 AC DF 08 22 04 9D 2B D7 F9 4B 09
| | DE 9A EB 5C 51 1A D8 F8 F9 56 9E F8 FB 37 9B 3F
| | D3 74 65 24 0D FF 34 75 57 A4 F5 BF 55
| 02 03 ;INTEGER (0x03 = 3 bytes)
| | 01 00 01 ;hex for 65537. see it?
```
If you take that entire above DER ASN.1 encoded `modulus`+`exponent`:
> 30 81 89 02 81 81 00 DC 67 FA
> F4 9E F2 72 1D 45 2C B4 80 79 06 A0 94 27 50 82
> 09 DD 67 CE 57 B8 6C 4A 4F 40 9F D2 D1 69 FB 99
> 5D 85 0C 07 A1 F9 47 1B 56 16 6E F6 7F B9 CF 2A
> 58 36 37 99 29 AA 4F A8 12 E8 4F C7 82 2B 9D 72
> 2A 9C DE 6F C2 EE 12 6D CF F0 F2 B8 C4 DD 7C 5C
> 1A C8 17 51 A9 AC DF 08 22 04 9D 2B D7 F9 4B 09
> DE 9A EB 5C 51 1A D8 F8 F9 56 9E F8 FB 37 9B 3F
> D3 74 65 24 0D FF 34 75 57 A4 F5 BF 55 02 03 01
> 00 01
and you **PEM** encode it (i.e. base64):
```
MIGJAoGBANxn+vSe8nIdRSy0gHkGoJQnUIIJ3WfOV7hsSk9An9LRafuZXY
UMB6H5RxtWFm72f7nPKlg2N5kpqk+oEuhPx4IrnXIqnN5vwu4Sbc/w8rjE
3XxcGsgXUams3wgiBJ0r1/lLCd6a61xRGtj4+Vae+Ps3mz/TdGUkDf80dV
ek9b9VAgMBAAE=
```
It's a convention to wrap that base64 encoded data in:
```
-----BEGIN RSA PUBLIC KEY-----
MIGJAoGBANxn+vSe8nIdRSy0gHkGoJQnUIIJ3WfOV7hsSk9An9LRafuZXY
UMB6H5RxtWFm72f7nPKlg2N5kpqk+oEuhPx4IrnXIqnN5vwu4Sbc/w8rjE
3XxcGsgXUams3wgiBJ0r1/lLCd6a61xRGtj4+Vae+Ps3mz/TdGUkDf80dV
ek9b9VAgMBAAE=
-----END RSA PUBLIC KEY-----
```
And that's how you get an have a **PEM DER ASN.1 PKCS#1 RSA Public key**.
---
The next standard was [RFC 4716](https://www.rfc-editor.org/rfc/rfc4716) (*The Secure Shell (SSH) Public Key File Format*). They included an algorithm identifier (`ssh-rsa`), before the exponent and modulus:
```
string "ssh-rsa"
mpint e
mpint n
```
They didn't want to use DER ASN.1 encoding (as it is horrendously complex), and instead opted for *4-byte length prefixing*:
```
00000007 ;7 byte algorithm identifier
73 73 68 2d 72 73 61 ;"ssh-rsa"
00000003 ;3 byte exponent
01 00 01 ;hex for 65,537
00000080 ;128 byte modulus
DC 67 FA F4 9E F2 72 1D 45 2C B4 80 79 06 A0 94
27 50 82 09 DD 67 CE 57 B8 6C 4A 4F 40 9F D2 D1
69 FB 99 5D 85 0C 07 A1 F9 47 1B 56 16 6E F6 7F
B9 CF 2A 58 36 37 99 29 AA 4F A8 12 E8 4F C7 82
2B 9D 72 2A 9C DE 6F C2 EE 12 6D CF F0 F2 B8 C4
DD 7C 5C 1A C8 17 51 A9 AC DF 08 22 04 9D 2B D7
F9 4B 09 DE 9A EB 5C 51 1A D8 F8 F9 56 9E F8 FB
37 9B 3F D3 74 65 24 0D FF 34 75 57 A4 F5 BF 55
```
Take the entire above byte sequence and base-64 encode it:
```
AAAAB3NzaC1yc2EAAAADAQABAAAAgNxn+vSe8nIdRSy0gHkGoJQnUIIJ3WfOV7hs
Sk9An9LRafuZXYUMB6H5RxtWFm72f7nPKlg2N5kpqk+oEuhPx4IrnXIqnN5vwu4S
bc/w8rjE3XxcGsgXUams3wgiBJ0r1/lLCd6a61xRGtj4+Vae+Ps3mz/TdGUkDf80
dVek9b9V
```
And wrap it in the OpenSSH header and trailer:
```
---- BEGIN SSH2 PUBLIC KEY ----
AAAAB3NzaC1yc2EAAAADAQABAAAAgNxn+vSe8nIdRSy0gHkGoJQnUIIJ3WfOV7hs
Sk9An9LRafuZXYUMB6H5RxtWFm72f7nPKlg2N5kpqk+oEuhPx4IrnXIqnN5vwu4S
bc/w8rjE3XxcGsgXUams3wgiBJ0r1/lLCd6a61xRGtj4+Vae+Ps3mz/TdGUkDf80
dVek9b9V
---- END SSH2 PUBLIC KEY ----
```
**Note**: That OpenSSH uses four dashes with a space (`----` ) rather than five dashes and no space (`-----`).
---
The next standard was [RFC 2459](https://www.rfc-editor.org/rfc/rfc2459#page-61) (*Internet X.509 Public Key Infrastructure Certificate and CRL Profile*). They took the PKCS#1 public key format:
```
RSAPublicKey ::= SEQUENCE {
modulus INTEGER, -- n
publicExponent INTEGER -- e
}
```
and extended it to include an algorithm identifier prefix (in case you want to use a public key encryption algorithm **other** than RSA):
```
SubjectPublicKeyInfo ::= SEQUENCE {
algorithm AlgorithmIdentifier,
subjectPublicKey RSAPublicKey }
```
The *"Algorithm Identifier"* for RSA is [`1.2.840.113549.1.1.1`](http://www.alvestrand.no/objectid/1.2.840.113549.1.1.1.html), which comes from:
* `1` - ISO assigned OIDs
+ `1.2` - ISO member body
- `1.2.840` - USA
* `1.2.840.113549` - RSADSI
+ `1.2.840.113549.1` - PKCS
- `1.2.840.113549.1.1` - PKCS-1
The X.509 is an awful standard, that defines a horribly complicated way of encoding an `OID` into hex, but in the end the DER ASN.1 encoding of an X.509 `SubjectPublicKeyInfo` RSA Public key is:
```
30 81 9F ;SEQUENCE (0x9f bytes = 159 bytes)
| 30 0D ;SEQUENCE (0x0d bytes = 13 bytes)
| | 06 09 ;OBJECT_IDENTIFIER (0x09 = 9 bytes)
| | 2A 86 48 86 ;Hex encoding of 1.2.840.113549.1.1
| | F7 0D 01 01 01
| | 05 00 ;NULL (0 bytes)
| 03 81 8D 00 ;BIT STRING (0x8d bytes = 141 bytes)
| | 30 81 89 ;SEQUENCE (0x89 bytes = 137 bytes)
| | | 02 81 81 ;INTEGER (0x81 bytes = 129 bytes)
| | | 00 ;leading zero of INTEGER
| | | DC 67 FA
| | | F4 9E F2 72 1D 45 2C B4 80 79 06 A0 94 27 50 82
| | | 09 DD 67 CE 57 B8 6C 4A 4F 40 9F D2 D1 69 FB 99
| | | 5D 85 0C 07 A1 F9 47 1B 56 16 6E F6 7F B9 CF 2A
| | | 58 36 37 99 29 AA 4F A8 12 E8 4F C7 82 2B 9D 72
| | | 2A 9C DE 6F C2 EE 12 6D CF F0 F2 B8 C4 DD 7C 5C
| | | 1A C8 17 51 A9 AC DF 08 22 04 9D 2B D7 F9 4B 09
| | | DE 9A EB 5C 51 1A D8 F8 F9 56 9E F8 FB 37 9B 3F
| | | D3 74 65 24 0D FF 34 75 57 A4 F5 BF 55
| | 02 03 ;INTEGER (0x03 = 3 bytes)
| | | 01 00 01 ;hex for 65537. see it?
```
You can see in the decoded ASN.1 how they just prefixed the old `RSAPublicKey` with an `OBJECT_IDENTIFIER`.
Taking the above bytes and PEM (i.e. base-64) encoding them:
```
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDcZ/r0nvJyHUUstIB5BqCUJ1CC
Cd1nzle4bEpPQJ/S0Wn7mV2FDAeh+UcbVhZu9n+5zypYNjeZKapPqBLoT8eCK51y
Kpzeb8LuEm3P8PK4xN18XBrIF1GprN8IIgSdK9f5SwnemutcURrY+PlWnvj7N5s/
03RlJA3/NHVXpPW/VQIDAQAB
```
The standard is then to wrap this with a header similar to RSA PKCS#1, but without the "RSA" (since it could be something other than RSA):
```
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDcZ/r0nvJyHUUstIB5BqCUJ1CC
Cd1nzle4bEpPQJ/S0Wn7mV2FDAeh+UcbVhZu9n+5zypYNjeZKapPqBLoT8eCK51y
Kpzeb8LuEm3P8PK4xN18XBrIF1GprN8IIgSdK9f5SwnemutcURrY+PlWnvj7N5s/
03RlJA3/NHVXpPW/VQIDAQAB
-----END PUBLIC KEY-----
```
And that's how you invent an **X.509 SubjectPublicKeyInfo/OpenSSL PEM public key** format.
---
That doesn't stop the list of standard formats for an RSA public key. Next is the proprietary public key format used by OpenSSH:
> ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgNxn+vSe8nIdRSy0gHkGoJQnUIIJ3WfOV7hs Sk9An9LRafuZXYUMB6H5RxtWFm72f7nPKlg2N5kpqk+oEuhPx4IrnXIqnN5vwu4Sbc/w8rjE3XxcGsgXUams3wgiBJ0r1/lLCd6a61xRGtj4+Vae+Ps3mz/TdGUkDf80dVek9b9V
Which is actually the **SSH** public key format above, but prefixed with `ssh-rsa`, rather than wrapped in `---- BEGIN SSH2 PUBLIC KEY ----`/`---- END SSH2 PUBLIC KEY ----`.
---
This is where the ease of the [XML `RSAKeyValue` public key](http://msdn.microsoft.com/en-us/library/windows/apps/hh868328.aspx) comes in:
* **Exponent**: `0x 010001` base64 encoded is `AQAB`
* **Modulus**: `0x 00 dc 67 fa f4 9e f2 72 1d 45 2c b4 80 79 06 a0 94 27 50 82 09 dd 67 ce 57 b8 6c 4a 4f 40 9f d2 d1 69 fb 99 5d 85 0c 07 a1 f9 47 1b 56 16 6e f6 7f b9 cf 2a 58 36 37 99 29 aa 4f a8 12 e8 4f c7 82 2b 9d 72 2a 9c de 6f c2 ee 12 6d cf f0 f2 b8 c4 dd 7c 5c 1a c8 17 51 a9 ac df 08 22 04 9d 2b d7 f9 4b 09 de 9a eb 5c 51 1a d8 f8 f9 56 9e f8 fb 37 9b 3f d3 74 65 24 0d ff 34 75 57 a4 f5 bf 55` base64 encoded is `ANxn+vSe8nIdRSy0gHkGoJQnUIIJ3WfOV7hsSk9An9LRafuZXYUMB6H5RxtWFm72f7nPKlg2N5kpqk+oEuhPx4IrnXIqnN5vwu4Sbc/w8rjE3XxcGsgXUams3wgiBJ0r1/lLCd6a61xRGtj4+Vae+Ps3mz/TdGUkDf80dVek9b9V`.
This means the XML is:
```
<RSAKeyValue>
<Modulus>ANxn+vSe8nIdRSy0gHkGoJQnUIIJ3WfOV7hsSk9An9LRafuZXYUMB6H5RxtWFm72f7nPKlg2N5kpqk+oEuhPx4IrnXIqnN5vwu4Sbc/w8rjE3XxcGsgXUams3wgiBJ0r1/lLCd6a61xRGtj4+Vae+Ps3mz/TdGUkDf80dVek9b9V</Modulus>
<Exponent>AQAB</Exponent>
</RSAKeyValue>
```
Much simpler. A downside is that it doesn't wrap, copy, paste, as nicely as (i.e. Xml is not as user friendly as):
```
-----BEGIN RSA PUBLIC KEY-----
MIGJAoGBANxn+vSe8nIdRSy0gHkGoJQnUIIJ3WfOV7hsSk9An9LRafuZXY
UMB6H5RxtWFm72f7nPKlg2N5kpqk+oEuhPx4IrnXIqnN5vwu4Sbc/w8rjE
3XxcGsgXUams3wgiBJ0r1/lLCd6a61xRGtj4+Vae+Ps3mz/TdGUkDf80dV
ek9b9VAgMBAAE=
-----END RSA PUBLIC KEY-----
```
But it makes a great neutral storage format.
## See also
* [**Translator, Binary**](http://home.paulschou.net/tools/xlate/): Great for decoding and encoding base64 data
* [**ASN.1 JavaScript decoder**](http://lapo.it/asn1js/): Great for decoding ASN.1 encoded hex data (that you get from `Translator, Binary`
* [**Microsoft ASN.1 Documentation**](http://msdn.microsoft.com/en-us/library/windows/desktop/bb648645%28v=vs.85%29.aspx): Describes the Distinguished Encoding Rules (DER) used for ASN.1 structures (you won't find a better set of documentation anywhere else; i would argue Microsoft's is not only real documentation) | How to store/retrieve RSA public/private key | [
"",
"c#",
".net",
"cryptography",
"rsa",
""
] |
I have a code below in my aspx page:
```
<div id="FormContainer">
<div id="leftSection">
<h1>
Contact Us</h1>
<div id="intro">
<p>
Contact PLI</p>
<p>
</p>
</div>
<esp:contactus id="ContactUs" runat="server" />
</div>
</div>
```
And some code which comes from my above usercontrol (**esp:contactus**) is given below
```
<div id="divMain" runat="server">
<div class="leftColumn">
<span id="ContactUs_lblFirstName" class="details">First name:<span class="asterisk" title="This field is mandatory">*</span></span>
<input name="ContactUs$txtFirstname" type="text" maxlength="50" id="ContactUs_txtFirstname" />
<span id="ContactUs_rfvFirstName" style="color:Red;visibility:hidden;">Please type your forename here</span>
<span id="ContactUs_lblFamilyName" class="details">Family name:<span class="asterisk" title="This field is mandatory">*</span></span>
<input name="ContactUs$txtFamilyName" type="text" maxlength="50" id="ContactUs_txtFamilyName" />
<span id="ContactUs_rfvFamilyName" style="color:Red;visibility:hidden;">Please type your family name here</span>
<span id="ContactUs_lblAddress1" class="details">Address 1<span class="asterisk" title="This field is mandatory">*</span></span>
<input name="ContactUs$txtAddress1" type="text" maxlength="50" id="ContactUs_txtAddress1" />
<span id="ContactUs_rfvAddress1" style="color:Red;visibility:hidden;">Please enter the first line of your address</span>
<span id="ContactUs_lblAddress2" class="details">Address 2</span>
<input name="ContactUs$txtAddress2" type="text" maxlength="50" id="ContactUs_txtAddress2" />
<asp:button id="btnSubmit" cssclass="submitBTN" text="Submit"
onclick="Submit_Click" runat="server" />
</div>
</div>
<div id="divThanksmsg" runat="server">
Thank you for your enquiry.
</div>
```
If you see there is submit button in my usercontrol, after validating all above fields its display the thankyou div (divThanksmsg).
when user clicks on submit button it is validating all the form after validating fields my thankyou div (**divThanksmsg**) gets visible. But if you see the above div in my aspx page with id (**intro**) it is visible everytime. I want this div should get hidden when my thankYou div is visible.
Please suggest! | I see that you marked both div (divTanksmsg and divMain) to be ran at server.
You can initialize divThanksmsg to be hidden at first by modifying the markup to
```
<div id="divThanksmsg" visible="false" runat="server">
```
After finishing your validation, you can do something like:
```
divThanksmsg.Visible = true;
divMain.Visible = false;
``` | If I understand you correctly, you want to hide the "intro" div, when you show the "divThanksmsg". For this to work, you need a "runat=server" on the "intro"-div, and then, by this line in your code: `divThanksmsg.Visible = true;` you need to add `intro.Visible = false;`. | Hiding Div on when other div gets visible | [
"",
".net",
"javascript",
"jquery",
""
] |
I thought it would be nice to do something like this (with the lambda doing a yield return):
```
public IList<T> Find<T>(Expression<Func<T, bool>> expression) where T : class, new()
{
IList<T> list = GetList<T>();
var fun = expression.Compile();
var items = () => {
foreach (var item in list)
if (fun.Invoke(item))
yield return item; // This is not allowed by C#
}
return items.ToList();
}
```
However, I found out that I can't use yield in anonymous method. I'm wondering why. The [yield docs](http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx) just say it is not allowed.
Since it wasn't allowed I just created List and added the items to it. | Eric Lippert recently wrote a series of blog posts about why yield is not allowed in some cases.
* [Part 1](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/)
* [Part 2](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/)
* [Part 3](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/)
* [Part 4](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/)
* [Part 5](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/)
* [Part 6](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/)
EDIT2:
* [Part 7](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/iterator-blocks-part-seven-why-no-anonymous-iterators) *(this one was posted later and specifically addresses this question)*
You will probably find the answer there...
---
EDIT1: this is explained in the comments of Part 5, in Eric's answer to Abhijeet Patel's comment:
Q :
> Eric,
>
> Can you also provide some insight into
> why "yields" are not allowed inside an
> anonymous method or lambda expression
A :
> Good question. I would love to have
> anonymous iterator blocks. It would be
> totally awesome to be able to build
> yourself a little sequence generator
> in-place that closed over local
> variables. The reason why not is
> straightforward: the benefits don't
> outweigh the costs. The awesomeness of
> making sequence generators in-place is
> actually pretty small in the grand
> scheme of things and nominal methods
> do the job well enough in most
> scenarios. So the benefits are not
> that compelling.
>
> The costs are large. Iterator
> rewriting is the most complicated
> transformation in the compiler, and
> anonymous method rewriting is the
> second most complicated. Anonymous
> methods can be inside other anonymous
> methods, and anonymous methods can be
> inside iterator blocks. Therefore,
> what we do is first we rewrite all
> anonymous methods so that they become
> methods of a closure class. This is
> the second-last thing the compiler
> does before emitting IL for a method.
> Once that step is done, the iterator
> rewriter can assume that there are no
> anonymous methods in the iterator
> block; they've all be rewritten
> already. Therefore the iterator
> rewriter can just concentrate on
> rewriting the iterator, without
> worrying that there might be an
> unrealized anonymous method in there.
>
> Also, iterator blocks never "nest",
> unlike anonymous methods. The iterator
> rewriter can assume that all iterator
> blocks are "top level".
>
> If anonymous methods are allowed to
> contain iterator blocks, then both
> those assumptions go out the window.
> You can have an iterator block that
> contains an anonymous method that
> contains an anonymous method that
> contains an iterator block that
> contains an anonymous method, and...
> yuck. Now we have to write a rewriting
> pass that can handle nested iterator
> blocks and nested anonymous methods at
> the same time, merging our two most
> complicated algorithms into one far
> more complicated algorithm. It would
> be really hard to design, implement,
> and test. We are smart enough to do
> so, I'm sure. We've got a smart team
> here. But we don't want to take on
> that large burden for a "nice to have
> but not necessary" feature. -- Eric | Eric Lippert has written an excellent series of articles on the limitations (and design decisions influencing those choices) on [iterator blocks](http://blogs.msdn.com/ericlippert/archive/tags/Iterators/default.aspx)
In particular iterator blocks are implemented by some sophisticated compiler code transformations. These transformations would impact with the transformations which happen inside anonymous functions or lambdas such that in certain circumstances they would both try to 'convert' the code into some other construct which was incompatible with the other.
As a result they are forbidden from interaction.
How iterator blocks work under the hood is dealt with well [here](http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx).
As a simple example of an incompatibility:
```
public IList<T> GreaterThan<T>(T t)
{
IList<T> list = GetList<T>();
var items = () => {
foreach (var item in list)
if (fun.Invoke(item))
yield return item; // This is not allowed by C#
}
return items.ToList();
}
```
The compiler is simultaneously wanting to convert this to something like:
```
// inner class
private class Magic
{
private T t;
private IList<T> list;
private Magic(List<T> list, T t) { this.list = list; this.t = t;}
public IEnumerable<T> DoIt()
{
var items = () => {
foreach (var item in list)
if (fun.Invoke(item))
yield return item;
}
}
}
public IList<T> GreaterThan<T>(T t)
{
var magic = new Magic(GetList<T>(), t)
var items = magic.DoIt();
return items.ToList();
}
```
and at the same time the iterator aspect is trying to do it's work to make a little state machine. Certain simple examples might work with a fair amount of sanity checking (first dealing with the (possibly arbitrarily) nested closures) then seeing if the very bottom level resulting classes could be transformed into iterator state machines.
However this would be
1. Quite a lot of work.
2. Couldn't possibly work in all cases without at the very least the iterator block aspect being able to prevent the closure aspect from applying certain transformations for efficiency (like promoting local variables to instance variables rather than a fully fledged closure class).
* If there was even a slight chance of overlap where it was impossible or sufficiently hard to not be implemented then the number of support issues resulting would likely be high since the subtle breaking change would be lost on many users.
3. It can be very easily worked around.
In your example like so:
```
public IList<T> Find<T>(Expression<Func<T, bool>> expression)
where T : class, new()
{
return FindInner(expression).ToList();
}
private IEnumerable<T> FindInner<T>(Expression<Func<T, bool>> expression)
where T : class, new()
{
IList<T> list = GetList<T>();
var fun = expression.Compile();
foreach (var item in list)
if (fun.Invoke(item))
yield return item;
}
``` | In C#, why can't an anonymous method contain a yield statement? | [
"",
"c#",
"yield",
"anonymous-methods",
"yield-return",
""
] |
**1)**
I understand I can call this
```
$memcache_obj = memcache_connect('memcache_host', 11211);
```
in the header files of my site with no impact on pages that don't use memcache
but what about this
```
$memcache->connect('127.0.0.1', 11211);
```
Should this be called on a page to page basis?
---
**2)**
what if the server does not have enough memory to write new caches and memcache tries to store a cache?
---
**3)**
I know keys can have up to a 30 day lifespan,
Is there a way to flush all keys out of memory, especially useful for testing phase?
**4)**
Also this code, the first variable is connecting, so for example if I have 5 sections on a page that add/update/delete from memcache, do I need to run this connection everytime, or is it possible to connect 1 time and do everything per page load?
```
memcache_set($memcache_obj, 'var_key', 'some variable', 0, 30)
```
**5)**
Is there a function or anything to show like how much memory is available and being used on a php page? | 1. yes, no network calls are made until an attempt to fetch, delete, etc..., so it does not hurt to allocate the object in case it is needed. (EDIT: I was thinking of the "memcached" extension here, turns out the "memcache" extension does in fact open a connection to the memcache server, though the hit is negligable at most)
2. memcache will drop least used items to attempt to make space for the new object
3. $memcache\_obj->flush();
4. connect only needs to happen once per script run, easiest to place the connect at the top of your page or in a class constructer
5. $memcache\_obj->getStats() <http://www.php.net/manual/en/function.memcache-getstats.php> | Jason answered your questions very well but I thought that I would add some notes:
2) Note that if you try to store more than 1MB (default) into a key the memcache extension will return a FALSE value. It will also return FALSE if it can't write a key for any reason.
3) Keys *can* have a >30 day lifespan (TTL). Just add the TTL to the current time and use that as the TTL. Using your example call, it might be something like this (coded for clarity):
```
$ttl = 60*60*24*60; // 60 days
$newTTL = time()+$ttl;
memcache_set($memcache_obj, 'cache_key', 'some data', 0, $newTTL)
```
5) If you are talking about PHP memory then `memory_get_usage()` will get you what you want. Memcache memory is a little harder to come by but using the `getStats()` call will start you in the right direction. | A few question about PHP memcache | [
"",
"php",
"memcached",
""
] |
I'm trying to tune the performance of my application. And I'm curious what methods are taking the longest to process, and thus should be looked over for any optimization opportunities.
Are there any existing free tools that will help me visualize the call stack and how long each method is taking to complete? I'm thinking something that displays the call stack as a stacked bar graph or a [treemap](http://en.wikipedia.org/wiki/Treemapping) so it's easy to see that **MethodA()** took 10 second to complete because it called **MethodB()** and **Method(C)** that took 3 and 7 seconds to complete.
Does something like this exist? | Yes, they are called performance profilers. Check out RedGate ANTS and JetBrains' dotTrace, not free but pretty cheap and way better than any free alternative I have seen. | Several profilers are available. I'm only familiar with one (the one included in Visual Studio Team Suite), but it's not free. I must say, it's been powerful/reliable enough that I've had no desire to try switching to another. The other one I've heard about is Red Gate's .NET profiler (also not free). Both of these have feature sets including, but definitely not limited to, what you're after. If this is for commercial application development, definitely check them out. :) | Visualization of the timestamps in a call stack | [
"",
"c#",
".net",
"performance",
"optimization",
"callstack",
""
] |
I am coding my first object factory, and I am wondering if there any any drawbacks to passing one object into another when creating the second object, and then saving the first object within the second for use later?
Example:
```
class main
{
public $connection = array();
// various other useful functions that should be loaded on every page here
// these other functions would be convenient to have avail for
// new objects in different classes
function dbconnect($db) {
if(!isset($this->connection[$db])) {
switch($db) {
case "users":
$connection = @mysql_connect(info,info,info);
$db_select = @mysql_select_db(info,$connection);
$this->connection[$db] = $connection;
break;
case "ads":
$connection = mysql_connect(info,info,info);
$db_select = mysql_select_db(info,$connection);
$this->connection[$db] = $connection;
break;
default:
die($db . " is not a recognized database.");
break;
}
}
return $this->connection[$db];
}
// note how i pass $this into the new object in this function
function create($class,$params=null) {
if(!class_exists($class) && !$this->load($class)) {
die($class . " is not a recognized class.");
}else{
return new $class($this,$params);
}
}
function load($file) {
$file = $_SERVER['DOCUMENT_ROOT'] . "/classes/" . $file . ".class.php";
if(file_exists($file)) {
return require_once($file);
}else{
return false;
}
}
}
class secondary {
private $connection;
private $mainObj;
private $params;
function __construct($mainObj,$params) {
$this->mainObj = $mainObj;
$this->params = $params;
$this->connection = $mainObj->dbconnect('users');
}
}
```
As you see here, any class created by the factory conveniently has the ability to connect to the MySQL db if the class requires it (and other common/useful functions) ... without having to use globals, or pass many things in.
Is this a stable way? I am new, and could use some good theory/schooling on why this is wrong - if it is. | Yes, it is a pretty stable way. But I would like to see [type hinting](https://www.php.net/manual/en/language.oop5.typehinting.php) in the methods taking outer instances as parameters, which would make your classes typed stronger.
Example;
```
class Alob {
public function aMethod(**Blob** $outerObject) {
...
}
}
class Blob {
...
}
```
This will throw a fatal error if Alob::aMethod() is called with another type than Blob.
I would also like to see more accessor keywords for defining visibility, hide your class privates with 'private' and so on. | Definitely nothing wrong with object passing. If you have a ClassB object that needs an instantiated object of ClassA in order to function, then your only options are to create that ClassA object inside ClassB, or to pass ClassA in.
If the ClassA object is likely to be used by multiple ClassB objects, like in your example, then passing the ClassA (ie. Database connection object) around is actually *more* efficient than the alternative, which would involve a lot of duplicate objects being created inside each class.
Since PHP5 automatically passes objects by reference, setting up a reference inside your `secondary` class to `$mainObj` is actually very efficient. | Is it okay to pass a class object to another class? PHP | [
"",
"php",
"class",
"oop",
""
] |
my array is setup as follow:
```
array
'testuri/abc' =>
array
'label' => string 'abc' (length=3)
'weight' => float 5
'testuri/abd' =>
array
'label' => string 'abd' (length=3)
'weight' => float 2
'testuri/dess' =>
array
'label' => string 'dess' (length=4)
'weight' => float 2
'testuri/gdm' =>
array
'label' => string 'gdm' (length=3)
'weight' => float 2
'testuri/abe' =>
array
'label' => string 'abe' (length=3)
'weight' => float 2
'testuri/esy' =>
array
'label' => string 'esy' (length=3)
'weight' => float 2
'testuri/rdx' =>
array
'label' => string 'rdx' (length=3)
'weight' => float 3
'testuri/tfc' =>
array
'label' => string 'tfc' (length=3)
'weight' => float 3
```
I want to get/filter the 5 elements with bigges 'weight'. Is there a php function to make this?
PS. My idea was to use foreach | As far as I know there isn't.
You could use a [heap](http://ch2.php.net/manual/en/class.splmaxheap.php) for this, but for only 5 elements I'm not sure it's faster than just storing the top 5. | Sort the array by the weight value in descending order and then get the first five values:
```
function cmpByWeight($a, $b) {
return $b['weight'] - $a['weight'];
}
uasort($array, 'cmpByWeight');
$firstFive = array_slice($array, 0, 5);
``` | get only 5 elements from array | [
"",
"php",
"arrays",
"filter",
""
] |
Stemming from this [question](https://stackoverflow.com/questions/1180935/how-do-i-use-phps-get-and-set-for-defined-fields-in-my-class) on using `__get()` and `__set()` to access private variables, I'd like to get the input on how they are used in general. I am wondering when or where would be the best time to use a overloading function, and where you have used one (if you have).
Just to be clear, we are talking about these functions: <https://www.php.net/manual/en/language.oop5.magic.php> | ### Lazy Models Getters (using \_\_get())
I don't remember using PHP's magic methods too often in my apps, but I remember one situation where `__get()` was very useful.
Back in the days I was developing an application in CakePHP framework that had a lot of models and all models that are used in specific controller were initialized even if method make use only of one or two of them (that's how Cake was working). So I decided to change that to lazy models to lazy (loading models when they are used for the first time).
All I did is I added a very simple `__get()` function that looked for a model with specific name and loaded it. It was like 3-4 lines of code. I defined that in AppController (all CakePHP classes derives from that controller) and suddenly my app gained speed and used lower memory.
I took it further later on and also made lazy components loading in the same way.
### Dynamic Model Methods (using \_\_call())
Another good example, also from CakePHP, is how Cake searches on models. Basically you have two methods for that: `find()` and `findAll()` in every model, but you can also search using methods `findBy<FieldName>()` and `findAllBy<FieldName>()`.
In example if you have db table
```
notes(id, date, title, body)
```
And create Cake model for that. You can use methods such as `findById()`, `findByTitle()` and so on. You need only CamelCase db field and you can do a search on any field much quicker.
Cake does it by using `__call()` magic method. This method is called if you are trying to execute a method that doesn't exists and then it just runs `find()` or `findAll()` with conditions dynamically created from method name and parameters. This is very simple to implement and can give you really a lot of benefits. | I use \_\_get() and \_\_set() to access elements of a private array, i.e.:
```
class Something {
private $data;
public function __set($key, $value) {
//put validation here
$this->data[$key] = $value;
}
public function __get($key) {
if (!array_key_exists($this->data, $key)) {
throw new Exception("Invalid member $key.");
} else {
return $this->data[$key];
}
}
}
```
So with some validation, something like $person->age = "asdf" would throw an exception immediately (whereas it would be fine if age were a public member.)
Also in the \_\_set() you can limit what keys are valid if you don't want arbitrary 'members' in your class. | Best Practices for __get() and __set() | [
"",
"php",
"oop",
"magic-methods",
""
] |
How do I easily mock out a static method in Java?
I'm using Spring 2.5 and JUnit 4.4
```
@Service
public class SomeServiceImpl implements SomeService {
public Object doSomething() {
Logger.getLogger(this.class); //a static method invoked.
// ...
}
}
```
I don't control the static method that my service needs to invoke so I *cannot* refactor it to be more unit-testable. I've used the [Log4J Logger](http://logging.apache.org/log4j/1.2/apidocs/index.html) as an example, but the real static method is similar. *It is not an option to change the static method.*
Doing Grails work, I'm used to using something like:
```
def mockedControl = mockFor(Logger)
mockControl.demand.static.getLogger{Class clazz-> … }
…
mockControl.verify()
```
How do I do something similar in Java? | Basically, There isn't an easy way to do this in Java + Spring 2.5 & JUnit 4.4 at the moment.
Although it is possible to refactor, and abstract away the static call, Refactoring the code isn't the solution that I was looking for.
JMockit looked like it would work, but is incompatibile with Spring 2.5 and JUnit 4.4. | Do you mean you can't control the calling code? Because if you control the calls *to* the static method but not the implementation itself, you can easily make that testable. Create a dependency interface with a single method with the same signature as the static method. Your production implementation will just call through to the static method, but anything which currently calls the static method will call via the interface instead.
You can then mock out that interface in the normal way. | How can I easily mock out a static method in Java (jUnit4) | [
"",
"java",
"spring",
"static",
"mocking",
""
] |
i wish to interact with my browser window may be IE great if it works on Firefox too, using C#.
I want to make a software which can fill the entries in a webform automatically. In old times there was gator now is roboform, where it can fill in the values automatically.
I actually have users who are comfortable working on an old windows forms application, so i want to make a solution where they can still enter the data in their windows application and it actually fills in the entries at the web form and acts as if the request had generated from the browser itself.
I know i can merge both the databases, since it is a legacy application re writing the database for windows app is a trouble..
Any suggestion? | [WatiN](http://watin.sourceforge.net/) is designed to make testing web applications easy from .NET, and it sounds like it could be handy for what you want to do:
> Following is the Hello world example
> of web test automation; searching
> Google.
>
> ```
> [Test] public void
> SearchForWatiNOnGoogle() { using (IE
> ie = new IE("http://www.google.com"))
> {
> ie.TextField(Find.ByName("q")).TypeText("WatiN");
> ie.Button(Find.ByName("btnG")).Click();
> Assert.IsTrue(ie.ContainsText("WatiN"));
> } }
> ```
>
> WatiN Feature List
>
> * Automates all major HTML elements
> * Find elements by multiple attributes
> * Supports AJAX website testing
> * Supports frames (cross domain) and iframes
> * Supports popup dialogs like alert, confirm, login etc..
> * Supports HTML dialogs (modal and modeless)
> * Works with Internet Explorer 6, 7, 8 and FireFox 2 and 3 | It's billed as a testing application, but [Selenium RC](http://seleniumhq.org/) can be used to fill in forms and is fairly easy to setup. You could also check out [WatiN](http://watin.sourceforge.net/). Don't know anything about what security issues you might see though. | interacting with the browser using C# | [
"",
"c#",
"windows",
""
] |
I have a method that accepts an `Expression<Func<T, bool>>` as a parameter. I would like to use it as a predicate in the List.Find() method, but I can't seem to convert it to a Predicate which List takes. Do you know a simple way to do this?
```
public IList<T> Find<T>(Expression<Func<T, bool>> expression) where T : class, new()
{
var list = GetList<T>();
var predicate = [what goes here to convert expression?];
return list.Find(predicate);
}
```
**Update**
Combining answers from tvanfosson and 280Z28, I am now using this:
```
public IList<T> Find<T>(Expression<Func<T, bool>> expression) where T : class, new()
{
var list = GetList<T>();
return list.Where(expression.Compile()).ToList();
}
``` | ```
Func<T, bool> func = expression.Compile();
Predicate<T> pred = t => func(t);
```
Edit: per the comments we have a better answer for the second line:
```
Predicate<T> pred = func.Invoke;
``` | Another options which hasn't been mentioned:
```
Func<T, bool> func = expression.Compile();
Predicate<T> predicate = new Predicate<T>(func);
```
This generates the same IL as
```
Func<T, bool> func = expression.Compile();
Predicate<T> predicate = func.Invoke;
``` | How to convert an Expression<Func<T, bool>> to a Predicate<T> | [
"",
"c#",
"expression",
"predicate",
""
] |
I am working on a programming exercise that has interested me for some time. The goal of this exercise is to generate a softball schedule for a seasons programatically. What I am looking for is general advice rather than a specific anwser as I am trying to learn something in the process.
The part of the program I am really struggling with is how to generate all of the games that are played in one night. This is the basic functionality I am trying to achieve in the first interation.
Problem:
Given a list of teams, generate a schedule that has every team play 2 games, and no team can play the same team twice in one night. | I went with the implementation that I found on Wikipedia for Round Robin
<http://en.wikipedia.org/wiki/Round-robin_tournament>
The standard algorithm for round-robins is to assign each competitor a number, and pair them off in the first round …
```
1 2 3 4 5 6 7
14 13 12 11 10 9 8
```
… then fix one competitor (number one in this example) and rotate the others clockwise …
```
1 14 2 3 4 5 6
13 12 11 10 9 8 7
1 13 14 2 3 4 5
12 11 10 9 8 7 6
```
… until you end up almost back at the initial position
```
1 3 4 5 6 7 8
2 14 13 12 11 10 9
``` | It seems like you could do this quite simply by just rotating your team list.
e.g. given teams 1..10, do this:
```
Team A: 1 2 3 4 5 6 7 8 9 10
Team B: 2 3 4 5 6 7 8 9 10 1
```
so in game one, team A plays team B. For game two, rotate again:
```
Team A: 1 2 3 4 5 6 7 8 9 10
Team B: 3 4 5 6 7 8 9 10 1 2
```
Nine games will give you a full round-robin, and then you can start at the beginning again. Take the games in pairs for your nightly matchups.
EDIT
Kylotan points out that this doesn't actually work, as it has every team playing twice at once. Oops. If you came up with something that genuinely works, I encourage you to post it and accept it :-) | Help creating a schedule generator | [
"",
"c#",
"algorithm",
""
] |
Is this allowed?
```
Object::Object()
{
new (this) Object(0, NULL);
}
``` | Using `new(this)` will re-construct member variables. This can result in undefined behavior, since they're not destructed first. The usual pattern is to use a helper function instead:
```
class Object {
private:
void init(int, char *);
public:
Object();
Object(int, char *);
};
Object::Object() {
init(0, NULL);
}
Object::Object(int x, char *y) {
init(x, y);
}
void Object::init(int x, char *y) {
/* ... */
}
``` | I believe you want delegate constructors, *like Java for example*, which are not here yet. When C++0x comes you could do it like this :
```
Object::Object() : Object(0, NULL)
{
}
``` | What is wrong with this usage of the new operator? | [
"",
"c++",
""
] |
How can I make an animated mouse move across the screen and click a button?
It would be good for demonstration purposes!
Ideally, it would be in javascript and/or jQuery.
EDIT: there is a gigantic javascript file that the page calls, and that would take me a long time to parse and understand. That is why i am asking | ```
function googleItForThem() {
if ($.getQueryString({ id: "fwd" })) redirect();
$("body").css("cursor", "wait");
fakeMouse.show();
instruct("play.step_1");
fakeMouse.animate({
top: (inputField.position().top + 15).px(),
left: (inputField.position().left + 10).px()
}, 1500, 'swing', function(){
inputField.focus();
fakeMouse.animate({ top: "+=18px", left: "+=10px" }, 'fast', function() { fixSafariRenderGlitch(); });
type(searchString, 0);
});
function type(string, index){
var val = string.substr(0, index + 1);
inputField.attr('value', val);
if (index < string.length) {
setTimeout(function(){ type(string, index + 1); }, Math.random() * 240);
}
else {
doneTyping();
}
}
``` | As it happens, lmgtfy does, in fact, implement this with JavaScript and jQuery. Why not read its source? | How does the "let me google that for you" site make an animated mouse? | [
"",
"javascript",
"jquery",
"user-interface",
""
] |
My website doesn't seem to display any element or content when viewed on IE even though source code is viewable, but on firefox and chrome it loads fine. What is up???
<http://uber-upload.com>
I don't remember ever trying to load my website with IE, so i can't confirm if it ever has worked with IE. Please help me debug =/. WADAFA!??! Thanks for your help | I think your xml prolog syntax might be causing this.
I believe it should be like so:
```
<?xml version="1.0" encoding="iso-8859-1"?>
```
see: <http://www.quirksmode.org/css/quirksmode.html> | Your website is probably confusing the buggery out of IE - the HTML validator found many errors. [Click here](http://validator.w3.org/check?uri=http%3A%2F%2Fuber-upload.com%2F&charset=%28detect+automatically%29&doctype=Inline&group=0).
Start by ensuring your document is valid XHTML (since that's what you're declaring in your doctype). Then we'll go from there. | Website won't display on IE, but source code is viewable | [
"",
"javascript",
"css",
"debugging",
"internet-explorer",
"cross-browser",
""
] |
This program reads strings of numbers from a txt file, converts them to integers, stores them in a vector, and then tries to output them in an organized fashion like so....
If txt file says:
```
7 5 5 7 3 117 5
```
The program outputs:
```
3
5 3
7 2
117
```
so if the number occurs more than once it outputs how many times that happens. Here is the code so far.
```
#include "std_lib_facilities.h"
int str_to_int(string& s)
{
stringstream ss(s);
int num;
ss >> num;
return num;
}
int main()
{
cout << "Enter file name.\n";
string file;
cin >> file;
ifstream f(file.c_str(), ios::in);
string num;
vector<int> numbers;
while(f>>num)
{
int number = str_to_int(num);
numbers.push_back(number);
}
sort(numbers.begin(), numbers.end());
for(int i = 0; i < numbers.size(); ++i)
{
if(i = 0 && numbers[i]!= numbers[i+1]) cout << numbers[i] << endl;
if(i!=0 && numbers[i]!= numbers[i-1])
{
cout << numbers[i] << '\t' << counter << endl;
counter = 0;
}
else ++counter;
}
}
```
Edit: Program is getting stuck. Looking for an infinite loop right now. | How about using a map, where the key is the number you're tracking and the value is the number of occurrences?
If you must use a vector, you've already got it sorted. So just keep track of the number you previously saw. If it is the same as the current number, increment the counter. Every time the number changes: print out the current number and the count, reset the count, set the last\_seen number to the new number. | You could use a map of numbers to counters:
```
typedef map<int,unsigned int> CounterMap;
CounterMap counts;
for (int i = 0; i < numbers.size(); ++i)
{
CounterMap::iterator it(counts.find(numbers[i]));
if (it != counts.end()){
it->second++;
} else {
counts[numbers[i]] = 1;
}
}
```
... then iterate over the map to print results.
EDIT:
As suggested by lazypython: if you have the [TR1 extensions](http://en.wikipedia.org/wiki/C%2B%2B_Technical_Report_1) [wikipedia.org] available, unordered\_map should have better performance...
```
typedef std::tr1::unordered_map<int,unsigned int> CounterMap;
CounterMap counts;
for (int i = 0; i < numbers.size(); ++i)
{
CounterMap::iterator it(counts.find(numbers[i]));
if (it != counts.end()){
it->second++;
} else {
counts[numbers[i]] = 1;
}
}
``` | Counting occurrences in a vector | [
"",
"c++",
""
] |
I am trying to do use `.Select` extension method on `ListView.SelectedItems` which is `SelectedListViewItemCollection`, but `.Select` doesn't show up in intellisense.
I can use `foreach` on `SelectedListViewItemCollection`, so it must have implemented `IEnumerable`. I just checked on MSDN, and it certainly does. Then why can't the LINQ extension methods be used on it? | The reason why is that SelectedItems is typed to a collection which implements IEnumerable. The Select extension method is bound to `IEnumerable<T>`. Hence it won't work with SelectedItems.
The workaround is to use the .Cast extension method to get it to the appropriate type and it should show up
```
ListView.SelectedItems.Cast<SomeType>.Select(...)
``` | It implements IEnumerable, not `IEnumerable<T>` - all LINQ queries are built around the generic `IEnumerable<T>` interface to allow type safety and generic inference - particularly when dealing with anonymous types.
You can use the following instead:
```
myListView.SelectedItems.Cast<ListViewItem>.Select( ... );
``` | Why can't I use LINQ on ListView.SelectedItems? | [
"",
"c#",
".net",
"winforms",
"listview",
""
] |
I am trying to retrieve process information and I'm aware that I can use:
```
Process[] myProcesses = Process.GetProcesses();
```
but how do I retrieve the process description? Is it via some Win32 API call? I'm running Vista and when I click under the Processes tab in Task Manager, I see the description. | What you see in Task Manager is actually the Description field of the executable image.
You can use the `GetFileVersionInfo()` and `VerQueryValue()` WinAPI calls to access various version informations, e.g. CompanyName or FileDescription.
For .Net way, use the `FileDescription` member of `FileVersionInfo`, instantiated with the executable name got via `Process.MainModule.FileName`.
Another way would be through `Assembly`. Load the Assembly from the executable image, then query the `AssemblyDescriptionAttribute` custom attribute. | You just have to go a bit further down the properties.
Suppose you have an instance of notepad running.
```
Process[] proc = Process.GetProcessesByName("notepad");
Console.WriteLine("Process version- " + proc[0].MainModule.FileVersionInfo.FileVersion);
Console.WriteLine("Process description- " + proc[0].MainModule.FileVersionInfo.FileDescription);
```
There you go ! | Retrieving Process Description Information | [
"",
"c#",
".net",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.