Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm in need of help - I've got two mysql databases on different servers with a web host, and I need to copy a Joomla installation from one to the other. The problem I have is that the only way I can access the data is via php, as direct odbc connections to the database are locked down.
I don't mind doing it table by table, but have no idea of how to code the script :(
My knowledge of php is limited (hence using Joomla), so if anyone has a couple of minutes to point me in the right direction, it'd be appreciated.
Thanks in advance,
PG | Can you install [phpMyAdmin](http://phpmyadmin.net/)? If so, it has a database export/import functionality that would likely be perfect for this. | Look at this post.
[What would be the best way to backup and restore mysql dumps with just php?](https://stackoverflow.com/questions/459796/what-would-be-the-best-way-to-backup-and-restore-mysql-dumps-with-just-php) | Copy MySQL structure across servers via PHP | [
"",
"php",
"mysql",
""
] |
The problem that I am having has to do with the need to keep some urls of a website protected by HTTPS and the rest kicked to HTTP.
Normally, you have `$_SERVER['HTTP_HTTPS']` or `$_SERVER['HTTPS']` (depending on your flavor of Apache). You also can check the port - it's 80 for normal traffic and 443 for HTTPS.
My problem is that the **certificate sits on the loadbalancer**, and all these variables are unavailable, and the webserver sees <http://www.foo.com> on port 80. One way to fix this is to tell the loadbalancer to send the traffic on a different port, but I wonder if there are other ways to detect HTTPS coming from the load balancer? | If the load balancer is the other end of the SSL connection, you cannot get any more info than the load balancer explicitly provides. I would go for adding a http header, it may already be doing that, dump all the HTTP headers and look.
As another solution, you can do the redirection on the load balancer based on URL. | If anybody has the same issue behind an Amazon AWS Elastic Load Balancer, the solution is simple because the `$_SERVER` variable will include:
```
[HTTP_X_FORWARDED_PORT] => 443
[HTTP_X_FORWARDED_PROTO] => https
```
So, to get the protocol, you could use:
```
function getRequestProtocol() {
if(!empty($_SERVER['HTTP_X_FORWARDED_PROTO']))
return $_SERVER['HTTP_X_FORWARDED_PROTO'];
else
return !empty($_SERVER['HTTPS']) ? "https" : "http";
}
``` | Detecting HTTPS requests in PHP | [
"",
"php",
"apache",
"https",
""
] |
When developing a .NET Windows Forms Application we have the choice between those `App.config` tags to store our configuration values. Which one is better?
```
<configuration>
<!-- Choice 1 -->
<appSettings>
<add key="RequestTimeoutInMilliseconds" value="10000"/>
</appSettings>
<!-- Choice 2 -->
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c5612342342" >
<section name="Project1.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c5612342342" requirePermission="false" />
</sectionGroup>
</configSections>
<applicationSettings>
<Project1.Properties.Settings>
<setting name="TABLEA" serializeAs="String">
<value>TABLEA</value>
</setting>
</Project1.Properties.Settings>
</applicationSettings>
</configuration>
``` | The basic `<appSettings>` is easier to deal with - just slap in a `<add key="...." value="..." />` entry and you're done.
The downside is: there's no type-checking, e.g. you cannot safely assume your number that you wanted to configure there really is a number - someone could put a string into that setting..... you just access it as `ConfigurationManager["(key)"]` and then it's up to you to know what you're dealing with.
Also, over time, the `<appSettings>` can get rather convoluted and messy, if lots of parts of your app start putting stuff in there (remember the old windows.ini file? :-)).
If you can, I would prefer and recommend using your own configuration sections - with .NET 2.0, it's really become quite easy, That way, you can:
* a) Define your configuration settings in code and have them type-safe
and checked
* b) You can cleanly separate *YOUR* settings from everyone
else's. And you can reuse your config code, too!
There's a series of really good articles on you to demystify the .NET 2.0 configuration system on CodeProject:
1. [Unraveling the mysteries of .NET 2.0 configuration](http://www.codeproject.com/KB/dotnet/mysteriesofconfiguration.aspx)
2. [Decoding the mysteries of .NET 2.0 configuration](http://www.codeproject.com/KB/dotnet/mysteriesofconfiguration2.aspx)
3. [Cracking the mysteries of .NET 2.0 configuration](http://www.codeproject.com/KB/dotnet/mysteriesofconfiguration3.aspx)
Highly recommended! Jon Rista did a great job explaining the configuration system in .NET 2.0. | Application settings can be controlled from a designer (there is usually a Settings.settings file by default) so its easier to modify and you can access them programmatically through the Settings class where they appear like a strongly typed property. You can also have application and user level settings, as well as default settings for rolling back.
This is available from .NET 2.0 onwards and deprecates the other way of doing it (as far as I can tell).
More detail is given at: [msdn.microsoft.com/en-us/library/k4s6c3a0.aspx](http://msdn.microsoft.com/en-us/library/k4s6c3a0.aspx) | Pros and cons of AppSettings vs applicationSettings (.NET app.config / Web.config) | [
"",
"c#",
".net",
".net-core",
"web-config",
"app-config",
""
] |
Okay this is not a question of "how to get all uniques" or "How to remove duplicates from my array in php". This is a question about the time complexity.
I figured that the `array_unique` is somewhat O(n^2 - n) and here's my implementation:
```
function array_unique2($array)
{
$to_return = array();
$current_index = 0;
for ( $i = 0 ; $i < count($array); $i++ )
{
$current_is_unique = true;
for ( $a = $i+1; $a < count($array); $a++ )
{
if ( $array[$i] == $array[$a] )
{
$current_is_unique = false;
break;
}
}
if ( $current_is_unique )
{
$to_return[$current_index] = $array[$i];
}
}
return $to_return;
}
```
However when benchmarking this against the `array_unique` i got the following result:
Testing (array\_unique2)... Operation took 0.52146291732788 s.
Testing (array\_unique)... Operation took 0.28323101997375 s.
Which makes the array\_unique twice as fast, my question is, why ( Both had the same random data ) ?
And a friend of mine wrote the following:
```
function array_unique2($a)
{
$n = array();
foreach ($a as $k=>$v)
if (!in_array($v,$n))
$n[$k]=$v;
return $n;
}
```
which is twice as fast as the built in one in php.
I'd like to know, why?
What is the time-complexity of array\_unique and in\_array?
**Edit**
I removed the count($array) from both loops and just used a variable in the top of the function, that gained 2 seconds on 100 000 elements! | While I can't speak for the native array\_unique function, I can tell you that your friends algorithm is faster because:
1. He uses a single foreach loop as opposed to your double for() loop.
2. Foreach loops tend to perform faster than for loops in PHP.
3. He used a single if(! ) comparison while you used two if() structures
4. The only additional function call your friend made was in\_array whereas you called count() twice.
5. You made three variable declarations that your friend didn't have to ($a, $current\_is\_unique, $current\_index)
While none of these factors alone is huge, I can see where the cumulative effect would make your algorithm take longer than your friends. | The time complexity of `in_array()` is *O(n)*. To see this, we'll take a look at the [PHP source code](http://www.php.net/get/php-5.2.8.tar.gz/from/a/mirror).
The `in_array()` function is implemented in `ext/standard/array.c`. All it does is call `php_search_array()`, which contains the following loop:
```
while (zend_hash_get_current_data_ex(target_hash, (void **)&entry, &pos) == SUCCESS) {
// checking the value...
zend_hash_move_forward_ex(target_hash, &pos);
}
```
That's where the linear characteristic comes from.
This is the overall characteristic of the algorithm, becaus `zend_hash_move_forward_ex()` has constant behaviour: Looking at `Zend/zend_hash.c`, we see that it's basically just
```
*current = (*current)->pListNext;
```
---
As for the time complexity of `array_unique()`:
* first, a copy of the array will be created, which is an operation with *linear* characteristic
* then, a C array of `struct bucketindex` will be created and pointers into our array's copy will be put into these buckets - *linear* characteristic again
* then, the `bucketindex`-array will be sorted usign quicksort - *n `log` n* on average
* and lastly, the sorted array will be walked and and duplicate entries will be removed from our array's copy - this should be *linear* again, assuming that deletion from our array is a constant time operation
Hope this helps ;) | PHP Arrays - Remove duplicates ( Time complexity ) | [
"",
"php",
"algorithm",
"time-complexity",
""
] |
I have a base class "Foo" that has an Update() function, which I want to be called once per frame for every instance of that class. Given an object instance of this class called "foo", then once per frame I will call foo->Update().
I have a class "Bar" derived from my base class, that also needs to update every frame.
I could give the derived class an Update() function, but then I would have to remember to call its base::Update() function - nothing enforces my requirement that the base::Update() function is called because I have overriden it, and could easily just forget to (or choose not to) call the base:Update function.
So as an alternative I could give the base class a protected OnUpdate() function, which could be made overrideable, and call it from the base::Update() function. This removes the onus on me to remember to call base::Update() from the derived update function because I'm no longer overriding it. A Bar instance called "bar" will have bar->Update() called on it; this will first call the base class' Update() method, which will in turn call the overriden OnUpdate() function, performing the derived class' necessary updates.
Which solves everything. Except. What if I want to derive yet another updatable class, this time from the "Bar" class.
Baz (which derives from Bar) also has update requirements. If I put them in Baz's OnUpdate() function, I'm back to the original problem in that I'd have to remember to tell Baz's OnUpdate() function to call Bar's OnUpdate() function, otherwise Bar's OnUpdate() function wouldn't get called.
So really, I'd want Bar's OnUpdate() function to be non-overridable, and instead for it to call an overridable function after it has done whatever it needed to do, perhaps called OnUpdate2()...
And if I wanted to derive yet another class? OnUpdate3? OnUpdate4? AfterUpdate?
Is there a Better Way?
---
Further Info:
My specific problem domain is a 3d world. I've decided my base class is a "Locator" (an object with a location and orientation).
My first derived class is a "PhysicsObject" - a Locator that also has mass, velocity, collision information, etc.
My next derived class is a "Camera" - which derives from PhysicsObject. As well as position, and velocity, it also has information about the viewport, depth of field, etc.
---
MattK suggests simplifying the hierarchy - if a Locator is never referred to, incorporate it into PhysicsObject.
I'm also thinking about how I would go about turning the layout upside down and using composition instead of inheritance.
Perhaps a Camera HAS physics properties.
Perhaps a PhysicsObject HAS a location.
I'll have to think some more about this problem.
---
I like Uri's approach: "Observe the contract." Here's the rule - please follow it. Uri is right in that whatever kind of safeguards I try to put in, anyone could circumvent them, so perhaps in this case, the simplest solution is best. All my update() functions are going to have the requirement of calling their base::update() function.
Thanks for the help everyone! | That's a great question, I've encountered it many many times.
Unfortunately, there are at present no language mechanisms that I am familiar with for mainstream languages like C++ to do that, though I expect (at least in the future) for Java to have something with annotations.
I've used a variety of techniques including what you've suggested, each with pros and cons. Convulted approaches are not always worth the cost.
My view today is that if you really need to use inheritance (rather than composition), as it sounds here, then it is better to go for the elegant solution and observe the written contract. I admit, it's dangerous, but there are risks to the other approaches as well.
Generally speaking people are more careful reading the documentation of an overridden method than they are of a method they are using. In other words, while you would want to avoid "surprising" the user of your class, and can't count on him reading docs, you can count a little more on that in the case of inheritance, especially if you are the only user.
If you are presenting an API function and you expect many other individuals to override your subclass, you could put all kinds of sanity checks to ensure that the method was called, but in the end, you have to rely on the contract, just as so many standard library classes do. | Sounds like you want composition instead of inheritance. What if there was an interface IUpdateable, and Foo held a collection of IUpdateable objects, and called an Update method on each one every tick? Then Bar and Baz could just implement Update; your only worry would be how best to register them with Foo.
Based on your further info: You might want to consider your main object being analagous to your PhysicsObject, and using composition to include objects that implement specific behaviors, such as those of the Camera object. | Best way to organize a class hierarchy including an overridable "Update" function | [
"",
"c++",
""
] |
I have created a function that takes a SQL command and produces output that can then be used to fill a List of class instances. The code works great. I've included a slightly simplified version without exception handling here just for reference - skip this code if you want to jump right the problem. If you have suggestions here, though, I'm all ears.
```
public List<T> ReturnList<T>() where T : new()
{
List<T> fdList = new List<T>();
myCommand.CommandText = QueryString;
SqlDataReader nwReader = myCommand.ExecuteReader();
Type objectType = typeof (T);
FieldInfo[] typeFields = objectType.GetFields();
while (nwReader.Read())
{
T obj = new T();
foreach (FieldInfo info in typeFields)
{
for (int i = 0; i < nwReader.FieldCount; i++)
{
if (info.Name == nwReader.GetName(i))
{
info.SetValue(obj, nwReader[i]);
break;
}
}
}
fdList.Add(obj);
}
nwReader.Close();
return fdList;
}
```
As I say, this works just fine. However, I'd like to be able to call a similar function with an *anonymous class* for obvious reasons.
Question #1: it appears that I must construct an anonymous class **instance** in my call to my anonymous version of this function - is this right? An example call is:
```
.ReturnList(new { ClientID = 1, FirstName = "", LastName = "", Birthdate = DateTime.Today });
```
Question #2: the anonymous version of my ReturnList function is below. Can anyone tell me why the call to info.SetValue simply does nothing? It doesn't return an error or anything but neither does it change the value of the target field.
```
public List<T> ReturnList<T>(T sample)
{
List<T> fdList = new List<T>();
myCommand.CommandText = QueryString;
SqlDataReader nwReader = myCommand.ExecuteReader();
// Cannot use FieldInfo[] on the type - it finds no fields.
var properties = TypeDescriptor.GetProperties(sample);
while (nwReader.Read())
{
// No way to create a constructor so this call creates the object without calling a ctor. Could this be a source of the problem?
T obj = (T)FormatterServices.GetUninitializedObject(typeof(T));
foreach (PropertyDescriptor info in properties)
{
for (int i = 0; i < nwReader.FieldCount; i++)
{
if (info.Name == nwReader.GetName(i))
{
// This loop runs fine but there is no change to obj!!
info.SetValue(obj, nwReader[i]);
break;
}
}
}
fdList.Add(obj);
}
nwReader.Close();
return fdList;
}
```
Any ideas?
**Note:** when I tried to use the FieldInfo array as I did in the function above, the typeFields array had zero elements (even though the objectType shows the field names - strange). Thus, I use TypeDescriptor.GetProperties instead.
Any other tips and guidance on the use of reflection or anonymous classes are appropriate here - I'm relatively new to this specific nook of the C# language.
UPDATE: I have to thank Jason for the key to solving this. Below is the revised code that will create a list of anonymous class instances, filling the fields of each instance from a query.
```
public List<T> ReturnList<T>(T sample)
{
List<T> fdList = new List<T>();
myCommand.CommandText = QueryString;
SqlDataReader nwReader = myCommand.ExecuteReader();
var properties = TypeDescriptor.GetProperties(sample);
while (nwReader.Read())
{
int objIdx = 0;
object[] objArray = new object[properties.Count];
foreach (PropertyDescriptor info in properties)
objArray[objIdx++] = nwReader[info.Name];
fdList.Add((T)Activator.CreateInstance(sample.GetType(), objArray));
}
nwReader.Close();
return fdList;
}
```
Note that the query has been constructed and the parameters initialized in previous calls to this object's methods. The original code had an inner/outer loop combination so that the user could have fields in their anonymous class that didn't match a field. However, in order to simplify the design, I've decided not to permit this and have instead adopted the db field access recommended by Jason. Also, thanks to Dave Markle as well for helping me understand more about the tradeoffs in using Activator.CreateObject() versus GenUninitializedObject. | Anonymous types encapsulate a set of *read-only* properties. This explains
1. Why `Type.GetFields` returns an empty array when called on your anonymous type: anonymous types do not have public fields.
2. The public properties on an anonymous type are read-only and can not have their value set by a call to `PropertyInfo.SetValue`. If you call `PropertyInfo.GetSetMethod` on a property in an anonymous type, you will receive back `null`.
In fact, if you change
```
var properties = TypeDescriptor.GetProperties(sample);
while (nwReader.Read()) {
// No way to create a constructor so this call creates the object without calling a ctor. Could this be a source of the problem?
T obj = (T)FormatterServices.GetUninitializedObject(typeof(T));
foreach (PropertyDescriptor info in properties) {
for (int i = 0; i < nwReader.FieldCount; i++) {
if (info.Name == nwReader.GetName(i)) {
// This loop runs fine but there is no change to obj!!
info.SetValue(obj, nwReader[i]);
break;
}
}
}
fdList.Add(obj);
}
```
to
```
PropertyInfo[] properties = sample.GetType().GetProperties();
while (nwReader.Read()) {
// No way to create a constructor so this call creates the object without calling a ctor. Could this be a source of the problem?
T obj = (T)FormatterServices.GetUninitializedObject(typeof(T));
foreach (PropertyInfo info in properties) {
for (int i = 0; i < nwReader.FieldCount; i++) {
if (info.Name == nwReader.GetName(i)) {
// This loop will throw an exception as PropertyInfo.GetSetMethod fails
info.SetValue(obj, nwReader[i], null);
break;
}
}
}
fdList.Add(obj);
}
```
you will receive an exception informing you that the property set method can not be found.
Now, to solve your problem, what you can do is use `Activator.CreateInstance`. I'm sorry that I'm too lazy to type out the code for you, but the following will demonstrate how to use it.
```
var car = new { Make = "Honda", Model = "Civic", Year = 2008 };
var anothercar = Activator.CreateInstance(car.GetType(), new object[] { "Ford", "Focus", 2005 });
```
So just run through a loop, as you've done, to fill up the object array that you need to pass to `Activator.CreateInstance` and then call `Activator.CreateInstance` when the loop is done. Property order is important here as two anonymous types are the same if and only if they have the same number of properties with the same type and same name in the same order.
For more, see the [MSDN page](http://msdn.microsoft.com/en-us/library/bb397696.aspx) on anonymous types.
Lastly, and this is really an aside and not germane to your question, but the following code
```
foreach (PropertyDescriptor info in properties) {
for (int i = 0; i < nwReader.FieldCount; i++) {
if (info.Name == nwReader.GetName(i)) {
// This loop runs fine but there is no change to obj!!
info.SetValue(obj, nwReader[i]);
break;
}
}
}
```
could be simplified by
```
foreach (PropertyDescriptor info in properties) {
info.SetValue(obj, nwReader[info.Name]);
}
``` | I had the same problem, I resolved it by creating a new Linq.Expression that's going to do the real job and compiling it into a lambda: here's my code for example:
I want to transform that call:
```
var customers = query.ToList(r => new
{
Id = r.Get<int>("Id"),
Name = r.Get<string>("Name"),
Age = r.Get<int>("Age"),
BirthDate = r.Get<DateTime?>("BirthDate"),
Bio = r.Get<string>("Bio"),
AccountBalance = r.Get<decimal?>("AccountBalance"),
});
```
to that call:
```
var customers = query.ToList(() => new
{
Id = default(int),
Name = default(string),
Age = default(int),
BirthDate = default(DateTime?),
Bio = default(string),
AccountBalance = default(decimal?)
});
```
and do the DataReader.Get things from the new method, the first method is:
```
public List<T> ToList<T>(FluentSelectQuery query, Func<IDataReader, T> mapper)
{
return ToList<T>(mapper, query.ToString(), query.Parameters);
}
```
I had to build an expression in the new method:
```
public List<T> ToList<T>(Expression<Func<T>> type, string sql, params object[] parameters)
{
var expression = (NewExpression)type.Body;
var constructor = expression.Constructor;
var members = expression.Members.ToList();
var dataReaderParam = Expression.Parameter(typeof(IDataReader));
var arguments = members.Select(member =>
{
var memberName = Expression.Constant(member.Name);
return Expression.Call(typeof(Utilities),
"Get",
new Type[] { ((PropertyInfo)member).PropertyType },
dataReaderParam, memberName);
}
).ToArray();
var body = Expression.New(constructor, arguments);
var mapper = Expression.Lambda<Func<IDataReader, T>>(body, dataReaderParam);
return ToList<T>(mapper.Compile(), sql, parameters);
}
```
Doing this that way, i can completely avoid the Activator.CreateInstance or the FormatterServices.GetUninitializedObject stuff, I bet it's a lot faster ;) | How do I create and access a new instance of an Anonymous Class passed as a parameter in C#? | [
"",
"c#",
"reflection",
"anonymous-types",
""
] |
I have some scientific image data that's coming out of a detector device in a 16 bit range which then gets rendered in an image. In order to display this data, I'm using OpenGL, because it should support ushorts as part of the library. I've managed to get this data into textures rendering on an OpenGL 1.4 platform, a limitation that is a requirement of this project.
Unfortunately, the resulting textures look like they're being reduced to 8 bits, rather than 16 bits. I test this by generating a gradient image and displaying it; while the image itself has each pixel different from its neighbors, the displayed texture is showing stripe patterns where all pixels next to one another are showing up as equal values.
I've tried doing this with GlDrawPixels, and the resulting image actually looks like it's really rendering all 16 bits.
How can I force these textures to display properly?
To give more background, the LUT (LookUp Table) is being determined by the following code:
```
String str = "!!ARBfp1.0\n" +
"ATTRIB tex = fragment.texcoord[0];\n" +
"PARAM cbias = program.local[0];\n" +
"PARAM cscale = program.local[1];\n" +
"OUTPUT cout = result.color;\n" +
"TEMP tmp;\n" +
"TXP tmp, tex, texture[0], 2D;\n" +
"SUB tmp, tmp, cbias;\n" +
"MUL cout, tmp, cscale;\n" +
"END";
Gl.glEnable(Gl.GL_FRAGMENT_PROGRAM_ARB);
Gl.glGenProgramsARB(1, out mFragProg);
Gl.glBindProgramARB(Gl.GL_FRAGMENT_PROGRAM_ARB, mFragProg);
System.Text.Encoding ascii = System.Text.Encoding.ASCII;
Byte[] encodedBytes = ascii.GetBytes(str);
Gl.glProgramStringARB(Gl.GL_FRAGMENT_PROGRAM_ARB, Gl.GL_PROGRAM_FORMAT_ASCII_ARB,
count, encodedBytes);
GetGLError("Shader");
Gl.glDisable(Gl.GL_FRAGMENT_PROGRAM_ARB);
```
Where cbias and cScale are between 0 and 1.
Thanks!
EDIT: To answer some of the other questions, the line with glTexImage:
```
Gl.glBindTexture(Gl.GL_TEXTURE_2D, inTexData.TexName);
Gl.glTexImage2D(Gl.GL_TEXTURE_2D, 0, Gl.GL_LUMINANCE, inTexData.TexWidth, inTexData.TexHeight,
0, Gl.GL_LUMINANCE, Gl.GL_UNSIGNED_SHORT, theTexBuffer);
Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MIN_FILTER, Gl.GL_LINEAR); // Linear Filtering
Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MAG_FILTER, Gl.GL_LINEAR); // Linear Filtering
theTexBuffer = null;
GC.Collect();
GC.WaitForPendingFinalizers();
```
The pixel format is set when the context is initialized:
```
Gdi.PIXELFORMATDESCRIPTOR pfd = new Gdi.PIXELFORMATDESCRIPTOR();// The pixel format descriptor
pfd.nSize = (short)Marshal.SizeOf(pfd); // Size of the pixel format descriptor
pfd.nVersion = 1; // Version number (always 1)
pfd.dwFlags = Gdi.PFD_DRAW_TO_WINDOW | // Format must support windowed mode
Gdi.PFD_SUPPORT_OPENGL | // Format must support OpenGL
Gdi.PFD_DOUBLEBUFFER; // Must support double buffering
pfd.iPixelType = (byte)Gdi.PFD_TYPE_RGBA; // Request an RGBA format
pfd.cColorBits = (byte)colorBits; // Select our color depth
pfd.cRedBits = 0; // Individual color bits ignored
pfd.cRedShift = 0;
pfd.cGreenBits = 0;
pfd.cGreenShift = 0;
pfd.cBlueBits = 0;
pfd.cBlueShift = 0;
pfd.cAlphaBits = 0; // No alpha buffer
pfd.cAlphaShift = 0; // Alpha shift bit ignored
pfd.cAccumBits = 0; // Accumulation buffer
pfd.cAccumRedBits = 0; // Individual accumulation bits ignored
pfd.cAccumGreenBits = 0;
pfd.cAccumBlueBits = 0;
pfd.cAccumAlphaBits = 0;
pfd.cDepthBits = 16; // Z-buffer (depth buffer)
pfd.cStencilBits = 0; // No stencil buffer
pfd.cAuxBuffers = 0; // No auxiliary buffer
pfd.iLayerType = (byte)Gdi.PFD_MAIN_PLANE; // Main drawing layer
pfd.bReserved = 0; // Reserved
pfd.dwLayerMask = 0; // Layer masks ignored
pfd.dwVisibleMask = 0;
pfd.dwDamageMask = 0;
pixelFormat = Gdi.ChoosePixelFormat(mDC, ref pfd); // Attempt to find an appropriate pixel format
if (!Gdi.SetPixelFormat(mDC, pixelFormat, ref pfd))
{ // Are we not able to set the pixel format?
BigMessageBox.ShowMessage("Can not set the chosen PixelFormat. Chosen PixelFormat was " + pixelFormat + ".");
Environment.Exit(-1);
}
``` | If you create a texture the 'type' parameter of glTexImage is only the data type your texture data is in before it is converted by OpenGL into its own format. To create a texture with 16 bit per channel you need something like GL\_LUMINANCE16 as format (internal format remains GL\_LUMINANCE). If there's no GL\_LUMINANCE16 for OpenGL 1.4 check if GL\_EXT\_texture is available and try it with GL\_LUMINANCE16\_EXT.
One of these should work. However if it doesn't you can encode your 16 bit values as two 8 bit pairs with GL\_LUMINANCE\_ALPHA and decode it again inside a shader. | You could consider using a single channel floating point texture through one of the `GL_ARB_texture_float`, `GL_ATI_texture_float` or `GL_NV_float_buffer` extensions if the hardware supports it, I can't recall if GL 1.4 has floating point textures or not though. | OpenGl 16 bit display via Tao/C# | [
"",
"c#",
"opengl",
"textures",
"16-bit",
"tao-framework",
""
] |
I am doing the exact same thing in two classes, and in one the compiler is allowing it just fine, but the other one is giving me an error. Why the double standard? There's 15 classes using this same pattern, but only one refuses to compile, saying the following error:
> 'AWWAInvoicingXML.AwwaTransmissionInfo'
> does not implement interface member
> 'AWWAInvoicingXML.IXmlSerializable.fromXML(System.Xml.XmlDocumentFragment)'.
> 'AWWAInvoicingXML.AwwaTransmissionInfo.fromXML(System.Xml.XmlDocumentFragment)'
> is either static, not public, or has
> the wrong return type.
Here is my source code... if I comment out the AwwaTransmissionInfo class, the rest of the file compiles just fine, so I know it's not one of those where the compiler is just dying after the first error. And I know, I know, there's built-in stuff for what I'm trying to do here, but just assume I actually know what I'm doing and skipped the built-in serializers for a reason :)
```
public interface IXmlSerializable {
//if this interface is implemented, the object can be serialized to XML
string toXML();
IXmlSerializable fromXML(XmlDocumentFragment inXml);
}
public class AwwaTransmissionInfo : IXmlSerializable {
public DateTime DateTime = DateTime.Now;
public int ItemCount;
public string toXML() {
throw new Exception("The method or operation is not implemented.");
}
public AwwaTransmissionInfo fromXML(XmlDocumentFragment inXml) {
throw new Exception("The method or operation is not implemented.");
}
}
public class CEmail {
public string Email = "";
public string toXML() {
throw new System.Exception("The method or operation is not implemented.");
}
public CEmail fromXML(XmlDocumentFragment inXml) {
throw new System.Exception("The method or operation is not implemented.");
}
}
``` | The reason the CEmail class was compiling fine is because it was not marked as implementing the interface. When I marked it as such, I got the same error as the other class. The following is how it has to be... I am pretty stupid for not noticing that. We are under a lot of pressure here right now and I can't believe I stared at this code for like an hour before I posted a question, and it was something so simple... it always is I guess :)
```
public interface IXmlSerializable {
//if this interface is implemented, the object can be serialized to XML
string toXML();
IXmlSerializable fromXML(XmlDocumentFragment inXml);
}
public class AwwaTransmissionInfo : IXmlSerializable {
public DateTime DateTime = DateTime.Now;
public int ItemCount;
public string toXML() {
throw new Exception("The method or operation is not implemented.");
}
public IXmlSerializable fromXML(XmlDocumentFragment inXml) {
throw new Exception("The method or operation is not implemented.");
}
}
public class CEmail : **IXmlSerializable** {
public string Email = "";
public string toXML() {
throw new System.Exception("The method or operation is not implemented.");
}
public IXmlSerializable fromXML(XmlDocumentFragment inXml) {
throw new System.Exception("The method or operation is not implemented.");
}
}
``` | The problem is that the method signature must match the interface exactly.
The easiest solution is to change
```
public AwwaTransmissionInfo fromXML(XmlDocumentFragment inXml) {
```
to
```
public IXmlSerializable fromXML(XmlDocumentFragment inXml) {
```
If you are unhappy with that, you can implement the interface explicitly. Add this:
```
public IXmlSerializable IXmlSerializable.fromXML(XmlDocumentFragment inXml) {
return this.fromXML(inXml);
}
```
Then you will have two definitions for fromXML(), one for use when being called as as instance of the class, and one for use when being called through the interface. | C# double standard? | [
"",
"c#",
"interface",
""
] |
This is what I've come up with as a method on a class inherited by many of my other classes. The idea is that it allows the simple comparison between properties of Objects of the same Type.
Now, this does work - but in the interest of improving the quality of my code I thought I'd throw it out for scrutiny. How can it be better/more efficient/etc.?
```
/// <summary>
/// Compare property values (as strings)
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public bool PropertiesEqual(object comparisonObject)
{
Type sourceType = this.GetType();
Type destinationType = comparisonObject.GetType();
if (sourceType == destinationType)
{
PropertyInfo[] sourceProperties = sourceType.GetProperties();
foreach (PropertyInfo pi in sourceProperties)
{
if ((sourceType.GetProperty(pi.Name).GetValue(this, null) == null && destinationType.GetProperty(pi.Name).GetValue(comparisonObject, null) == null))
{
// if both are null, don't try to compare (throws exception)
}
else if (!(sourceType.GetProperty(pi.Name).GetValue(this, null).ToString() == destinationType.GetProperty(pi.Name).GetValue(comparisonObject, null).ToString()))
{
// only need one property to be different to fail Equals.
return false;
}
}
}
else
{
throw new ArgumentException("Comparison object must be of the same type.","comparisonObject");
}
return true;
}
``` | I was looking for a snippet of code that would do something similar to help with writing unit test. Here is what I ended up using.
```
public static bool PublicInstancePropertiesEqual<T>(T self, T to, params string[] ignore) where T : class
{
if (self != null && to != null)
{
Type type = typeof(T);
List<string> ignoreList = new List<string>(ignore);
foreach (System.Reflection.PropertyInfo pi in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
{
if (!ignoreList.Contains(pi.Name))
{
object selfValue = type.GetProperty(pi.Name).GetValue(self, null);
object toValue = type.GetProperty(pi.Name).GetValue(to, null);
if (selfValue != toValue && (selfValue == null || !selfValue.Equals(toValue)))
{
return false;
}
}
}
return true;
}
return self == to;
}
```
*EDIT:*
**Same code as above but uses LINQ and Extension methods :**
```
public static bool PublicInstancePropertiesEqual<T>(this T self, T to, params string[] ignore) where T : class
{
if (self != null && to != null)
{
var type = typeof(T);
var ignoreList = new List<string>(ignore);
var unequalProperties =
from pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
where !ignoreList.Contains(pi.Name) && pi.GetUnderlyingType().IsSimpleType() && pi.GetIndexParameters().Length == 0
let selfValue = type.GetProperty(pi.Name).GetValue(self, null)
let toValue = type.GetProperty(pi.Name).GetValue(to, null)
where selfValue != toValue && (selfValue == null || !selfValue.Equals(toValue))
select selfValue;
return !unequalProperties.Any();
}
return self == to;
}
public static class TypeExtensions
{
/// <summary>
/// Determine whether a type is simple (String, Decimal, DateTime, etc)
/// or complex (i.e. custom class with public properties and methods).
/// </summary>
/// <see cref="http://stackoverflow.com/questions/2442534/how-to-test-if-type-is-primitive"/>
public static bool IsSimpleType(
this Type type)
{
return
type.IsValueType ||
type.IsPrimitive ||
new[]
{
typeof(String),
typeof(Decimal),
typeof(DateTime),
typeof(DateTimeOffset),
typeof(TimeSpan),
typeof(Guid)
}.Contains(type) ||
(Convert.GetTypeCode(type) != TypeCode.Object);
}
public static Type GetUnderlyingType(this MemberInfo member)
{
switch (member.MemberType)
{
case MemberTypes.Event:
return ((EventInfo)member).EventHandlerType;
case MemberTypes.Field:
return ((FieldInfo)member).FieldType;
case MemberTypes.Method:
return ((MethodInfo)member).ReturnType;
case MemberTypes.Property:
return ((PropertyInfo)member).PropertyType;
default:
throw new ArgumentException
(
"Input MemberInfo must be if type EventInfo, FieldInfo, MethodInfo, or PropertyInfo"
);
}
}
}
``` | **UPDATE:** The latest version of Compare-Net-Objects is located on [GitHub](https://github.com/GregFinzer/Compare-Net-Objects) , has [NuGet package](https://www.nuget.org/packages/CompareNETObjects) and [Tutorial](http://www.codeproject.com/Tips/754435/Compare-NET-Objects-Tutorial). It can be called like
```
//This is the comparison class
CompareLogic compareLogic = new CompareLogic();
ComparisonResult result = compareLogic.Compare(person1, person2);
//These will be different, write out the differences
if (!result.AreEqual)
Console.WriteLine(result.DifferencesString);
```
Or if you need to change some configuration, use
```
CompareLogic basicComparison = new CompareLogic()
{ Config = new ComparisonConfig()
{ MaxDifferences = propertyCount
//add other configurations
}
};
```
Full list of configurable parameters is in [ComparisonConfig.cs](https://github.com/GregFinzer/Compare-Net-Objects/blob/master/Compare-NET-Objects/ComparisonConfig.cs)
**Original answer:**
The limitations I see in your code:
* The biggest one is that it doesn't do a deep object comparison.
* It doesn't do an element by element comparison in case properties are lists or contain lists as elements (this can go n-levels).
* It doesn't take into account that some type of properties should not be compared (e.g. a Func property used for filtering purposes, like the one in the PagedCollectionView class).
* It doesn't keep track of what properties actually were different (so you can show in your assertions).
I was looking today for some solution for unit-testing purposes to do property by property deep comparison and I ended up using: <http://comparenetobjects.codeplex.com>.
It is a free library with just one class which you can simply use like this:
```
var compareObjects = new CompareObjects()
{
CompareChildren = true, //this turns deep compare one, otherwise it's shallow
CompareFields = false,
CompareReadOnly = true,
ComparePrivateFields = false,
ComparePrivateProperties = false,
CompareProperties = true,
MaxDifferences = 1,
ElementsToIgnore = new List<string>() { "Filter" }
};
Assert.IsTrue(
compareObjects.Compare(objectA, objectB),
compareObjects.DifferencesString
);
```
Also, it can be easily re-compiled for Silverlight. Just copy the one class into a Silverlight project and remove one or two lines of code for comparisons that are not available in Silverlight, like private members comparison. | Comparing object properties in c# | [
"",
"c#",
"object",
"properties",
"comparison",
""
] |
In Java is there a way to check the condition:
"Does this single character appear at all in string x"
**without** using a loop? | You can use [`string.indexOf('a')`](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf%28int%29).
If the char `a` is present in `string` :
> it returns the the index of the first occurrence of the character in
> the character sequence represented by this object, or -1 if the
> character does not occur. | * [**`String.contains()`**](http://java.sun.com/javase/6/docs/api/java/lang/String.html#contains(java.lang.CharSequence)) which checks if the string contains a specified sequence of char values
* [**`String.indexOf()`**](http://java.sun.com/javase/6/docs/api/java/lang/String.html#indexOf(int)) which returns the index within the string of the first occurence of the specified character or substring (there are 4 variations of this method) | How can I check if a single character appears in a string? | [
"",
"java",
"validation",
"string",
"character",
""
] |
What is the best approach to encapsulate objects and manage their lifetime? Example: I have a class *A*, that contains an object of type *B* and is **solely responsible** for it.
**Solution 1**, clone *b* object to ensure that only *A* is able to clean it up.
```
class A
{
B *b;
public:
A(B &b)
{
this->b = b.clone();
}
~A()
{
delete b; // safe
}
};
```
**Solution 2**, directly use the passed object, we risk a potential double free here.
```
class A
{
B *b;
public:
A(B *b)
{
this->b = b;
}
~A()
{
delete b; // unsafe
}
};
```
In my actual case, solution #2 would fit best. However I wonder if this is considered bad code because someone might not know about the behavior of *A*, even if it's documented. I can think of these scenarios:
```
B *myB = new B();
A *myA = new A(myB);
delete myB; // myA contains a wild pointer now
```
Or,
```
B *myB = new B();
A *firstA = new A(myB);
A *secondA = new A(myB); // bug! double assignment
delete firstA; // deletes myB, secondA contains a wild pointer now
delete secondA; // deletes myB again, double free
```
Can I just ignore these issues if I properly document the behavior of A? Is it enough to declare the responsibility and leave it up to the others to read the docs? How is this managed in your codebase? | You should define your object so that the ownership semantics are, as much as possible, defined by the interface. As David Thornley pointed out, std::auto\_ptr is the smart pointer of choice to indicate *transfer of ownership*. Define your class like so:
```
class A
{
std::auto_ptr<B> b;
public:
A(std::auto_ptr<B> b)
{
this->b = b;
}
// Don't need to define this for this scenario
//~A()
//{
// delete b; // safe
//}
};
```
Since the contract of std::auto\_ptr is that assignment = transfer of ownership, your constructor now states implicitly that an A object has ownership of the pointer to B it's passed. In fact, if a client *tries* to do something with a std::auto\_ptr<B> that they used to construct an A after the construction, the operation will fail, as the pointer they hold will be invalid. | I never delete anything myself unless I really have to. That leads to errors.
Smart pointers are your friend. `std::auto_ptr<>` is your friend when one object owns another and is responsible for deleting it when going out of scope. `boost::shared_ptr<>` (or, now, `std::tr1::shared_ptr<>`) is your friend when there's potentially more than one object attached to another object, and you want the object deleted when there's no more references to it.
So, either use your solution 1 with `auto_ptr`, or your solution 2 with `shared_ptr`. | Lifetime management of encapsulated objects | [
"",
"c++",
"memory-management",
"encapsulation",
""
] |
I have a class in C++ with the following member:
```
map< someEnum, vector<SomeObject*>* > someMap
```
So I have a map that gives me a vector of objects for each enumeration I have. For the life of me, I cannot understand how C++ is initializing these objects. Does it deep initialize them by default? If not, what do I need to do?
I'm getting segmentation faults no matter how I try to do this (and I have tried *everything*), so I'm guessing I'm missing something conceptually.
---
I should note that I tried to use:
```
map< someEnum, vector<SomeObject*> > someMap
```
as well and that didn't work as well. In this case, does C++ deep-initialize the vector? | The rule is: If an STL container contains **pointers to objects**, it it does **not** create objects on heap and assign them to these pointers. If, however, it contains **objects** themselves, it **does** call the default constructor of each contained object and thus initialises them.
What you have here is a map containing pointers (no matter what kind). So do not expect the map to make these pointers to point to memory. | It looks like the map gives you a pointer to a vector of objects. If you try to use the map via
`mymap[MY_ENUM]->push_back(whatever);`
before you initialize, you'll get a segfault. You either need to initialize the vector first
`mymap[MY_ENUM] = new vector<SomeObject*>;`
or, *much* better, just make the map give you a plain ol' vector
`map <someEnum, vector<SomeObject*> > mymap;`
When you first call `mymap[MY_ENUM]`, the vector will be default-initialized (with size zero). Is the problem that you're trying to use the entries of the vector before you enlarge it, e.g.,
`mymap[MY_ENUM][2] = whatever;`
You still need to use `push_back` or `resize`, or something that gives you some space. | Does C++ deep-initialize class members? | [
"",
"c++",
"data-structures",
"oop",
""
] |
I'm trying to load the default HICON that explorer displays for:
* An open folder
* An exe that has no embedded default icon of its own. This can also be seen in 'Add/Remove Programs' or 'Programs and Features' as it's called on Vista.
Do you know where these can be found? I think the folder icon might be in the resources of explorer.exe. But have no idea where the default application icon can be retrieved from.
And additionally, do you have any sample code that could load them into HICONs.
I really need this to work on multiple Windows OSs: 2000, XP, Vista, 2008
---
Thanks for the help so far. I'm on Vista and have looked through Shell32.dll. I don't see an icon in there that looks the same as the default one displayed by an application in explorer. I could be missing it - there are 278 icons to look through - is it definitely in there, or is there some other location I should look? | I think they are in %windir%\system32\SHELL32.dll
Found some code in the internet, try if that works:
```
HINSTANCE hDll;
hDll = LoadLibrary ( "SHELL32.dll" );
wincl.hIcon = LoadIcon (hDll , MAKEINTRESOURCE ( 1 ));
wincl.hIconSm = LoadIcon (hDll, MAKEINTRESOURCE ( 2 ));
```
---
Edit: Windows has a lot more icons in the "moricons.dll", but I think the file and folder icons should all be in the shell32.dll. Remind, that icons in Vista have different resolutions, up to 256x256, so the icon you are looking at a resolution 32x32 might look different then the full resolution version of the same icon. | Use the [SHGetFileInfo](http://msdn.microsoft.com/en-us/library/bb762179(VS.85).aspx) API.
```
SHFILEINFO sfi;
SecureZeroMemory(&sfi, sizeof sfi);
SHGetFileInfo(
_T("Doesn't matter"),
FILE_ATTRIBUTE_DIRECTORY,
&sfi, sizeof sfi,
SHGFI_ICON | SHGFI_SMALLICON | SHGFI_USEFILEATTRIBUTES);
```
will get you the icon handle to the folder icon.
To get the 'open' icon (i.e., the icon where the folder is shown as open), also pass SHGFI\_OPENICON in the last parameter to SHGetFileInfo().
[edit]
ignore all answers which tell you to poke around in the registry! Because that won't work reliably, will show the wrong icons if they're customized/skinned and might not work in future windows versions.
Also, if you extract the icons from system dlls/exes you could get into legal troubles because they're copyrighted. | Where can I find the default icons used for folders and applications? | [
"",
"c++",
"windows",
"winapi",
""
] |
Is there any case where `len(someObj)` does not call someObj's `__len__` function?
I recently replaced the former with the latter in a (sucessful) effort to speed up some code. I want to make sure there's not some edge case somewhere where `len(someObj)` is not the same as `someObj.__len__()`. | If `__len__` returns a length over `sys.maxsize`, `len()` will raise an exception. This isn't true of calling `__len__` directly. (In fact you could return any object from `__len__` which won't be caught unless it goes through `len()`.) | What kind of speedup did you see? I cannot imagine it was noticeable was it?
From <http://mail.python.org/pipermail/python-list/2002-May/147079.html>
> in certain situations there is no
> difference, but using len() is
> preferred for a couple reasons.
>
> first, it's not recommended to go
> calling the `__methods__` yourself, they
> are meant to be used by other parts of
> python.
>
> `len()` will work on any type of
> sequence object (`lists`, `tuples`, and
> all).
> `__len__` will only work on class instances with a `__len__` method.
>
> `len()` will return a more appropriate
> exception on objects without length. | Is there any case where len(someObj) does not call someObj's __len__ function? | [
"",
"python",
"magic-methods",
""
] |
When I run the program from IDE (VS2008) it works perfectly. When I want to launch it from Windows Commander it doesn't work because it needs DLL that wasn't found.
Used both debug and release builds. | Make sure the Qt DLL's are in your `PATH`. Two simple solutions are:
* Copy Qt's DLL's to your `EXE`'s directory.
* Copy Qt's DLL's to `%WINDOWS%\System32` (e.g. `C:\WINDOWS\System32`) (**possibly unsafe, especially if you install another versions of Qt system-wide**. Also, requires administrative privilages). | another solution would be to place path to qt bin subdir in VS tools->options->projects and solutions->VC++ directories. | How can I make the program I wrote with QT4 execute when I launch it not from IDE? | [
"",
"c++",
"qt4",
""
] |
in a CSS like this :
```
...
#big-menu {
background: #fff url(../images/big-menu.jpg) no-repeat;
}
#some-menu {
background: #fff url(../images/some-menu.jpg) no-repeat;
}
#some-other-menu {
background: #fff url(../images/some-other-menu.jpg) no-repeat;
}
...
```
is there a way to delay the loading of `#big-menu`'s background image, so that it loads after everything else, including all of the images in the HTML, and every other CSS background (the `some-menu` and `some-other-menu`).
The reason is, big-menu.jpg is very heavy in size, and I want it to be loaded last. After all, it just serves as an eye-candy, and there are other background images that have a better use than that. (such as the ones used in buttons)
Does the order of putting it in CSS or the occurrences of the markup (`#big-menu`) in HTML got anything to do with what gets loaded first ? or is there a more reliable way to control it ? javascript (jQuery preferred) is fine. | The ordering in css doesn't control which resources are loaded first, but do affect what existing style is being overwritten or inherited.
Try the JavaScript onload event. The event executes only after the page is finish loading.
```
function loadBG(){
document.getElementById("big-menu").style.backgroundImage="url(../images/big-menu.jpg)";
}
window.onload=loadBG();
``` | Another solution is to split your assets over different domains, browsers will only request two assets at time then wait for one to be loaded before starting the next. You can observe this with [Firebug](https://addons.mozilla.org/en-US/firefox/addon/1843) and [YSlow](http://developer.yahoo.com/yslow/), so placing some assets on images.example.com and images1.example.com and see if that makes an impact | delaying the loading of a certain css background image | [
"",
"javascript",
"html",
"css",
"loading",
"background-image",
""
] |
I'm trying to fetch the last inserted row Id of a Sqlite DB in my PHP application. I'm using Zend Framework's PDO Sqlite adapter for database handling. the lastInsertId() method is supposed to give me the results, but it wouldn't. In PDO documentation in php.net I read that the lastInsertId() might not work the same on all databases. but wouldn't it work on sqlite at all?
I tried overwriting the lastInsertId() method of the adapter by this:
```
// Zend_Db_Adapter_Pdo_Sqlite
public function lastInsertId() {
$result = $this->_connection->query('SELECT last_insert_rowid()')->fetch();
return $result[0];
}
```
but it does not work either. just returns 0 everytime I call it. is there any special clean way to find the last inserted Id? | Given an SQLite3 Database with a table `b`, as follows:
```
BEGIN TRANSACTION;
CREATE TABLE b(a integer primary key autoincrement, b varchar(1));
COMMIT;
```
This code gives me a `lastInsertId`:
```
public function lastInsertId() {
$result = $this->_connection->query('SELECT last_insert_rowid() as last_insert_rowid')->fetch();
return $result['last_insert_rowid'];
}
```
That is - if your table is defined correctly, your only problem is likely to be that you tried to fetch key $result[0] - also, whenever you're using a computed column, I recommend aliasing the column using the "AS" keyword as I've demonstrated above. If you don't want to alias the column, in SQLite3 the column should be named "last\_insert\_rowid()". | PDO::lastInserId()
see: <https://www.php.net/manual/en/pdo.lastinsertid.php> | how to get last inserted Id of a Sqlite database using Zend_Db | [
"",
"php",
"sqlite",
"zend-db",
""
] |
I have the 4 sources of IP addresses , I want to store them in SQL Server and allow the ranges, that can be categorised by the originating country code, to be maked in an Exclusion list by country.
For this I have 2 tables.
IPAddressRange
CountryCode
What I need to know is, if this data was returned to the client then cached for quick querying , what is the best way to store the returned data to query a specific IP address within the ranges. I want to know if the supplied IP address is in the list.
The reason the list is in the db is for easy storage.
The reason I want to cache then use the data on the client is that I have heard that searching IP addresses is faster in a trie structure. So , I am think I need to get the list from the db , store in cache in a structure that is very quick to search.
Any help in the A) The SQL stucture to store the addresses and b) Code to search the IP addresses.
I know of a code project solution which has a code algorithm for searching not sure how to mix this with the storage aspect.
Ideally without the use of a third party library. The code must be on our own server. | I've done a filter by country exactly like you describe.
However, after experimenting a while, I found out that it can't be done in a performant way with SQL. That's why IP databases like [this one](http://www.maxmind.com/app/geolitecity) (the one I'm using) offer a binary database, which is **much** faster because it's optimized for this kind of data.
They even say explicitly:
> Note that queries made against the CSV
> data imported into a SQL database can
> take up to a few seconds. If
> performance is an issue, the binary
> format is much faster, and can handle
> thousands of lookups per second.
Plus, they even give you [the code](http://www.maxmind.com/app/csharp) to query this database.
I'm using this in a production website with medium traffic, filtering every request, with no performance problems. | Assuming your IP Addresses are IPV4, you could just store them in an integer field. Create 2 fields, one for the lower bound for the range, and another for the upper bound. Then make sure these to fields are indexed. When searching for values, just search where the value is greater than or equal to the lower bound, and less than or equal to the upper bound. I would experiment with something simple like this before trying to program something more complicated yourself, which doesn't actually give noticeably quicker results. | How to store and search for an IP Address | [
"",
"c#",
"sql-server",
"data-structures",
"ip-address",
""
] |
I have a drop-down list with known values. What I'm trying to do is set the drop down list to a particular value that I know exists using **jQuery**.
Using regular **JavaScript**, I would do something like:
```
ddl = document.getElementById("ID of element goes here");
ddl.value = 2; // 2 being the value I want to set it too.
```
However, I need to do this with **jQuery**, because I'm using a **CSS** class for my selector (stupid [ASP.NET](http://en.wikipedia.org/wiki/ASP.NET) client ids...).
Here are a few things I've tried:
```
$("._statusDDL").val(2); // Doesn't find 2 as a value.
$("._statusDDL").children("option").val(2) // Also failed.
```
> How can I do it with **jQuery**?
---
**Update**
So as it turns out, I had it right the first time with:
```
$("._statusDDL").val(2);
```
When I put an alert just above it works fine, but when I remove the alert and let it run at full speed, I get the error
> Could not set the selected property. Invalid Index
I'm not sure if it's a bug with jQuery or **Internet Explorer 6** (I'm guessing Internet **Explorer 6**), but it's terribly annoying. | [jQuery's documentation](http://docs.jquery.com/Attributes/val#val) states:
> [jQuery.val] checks, or ***selects***, all the radio buttons, checkboxes, and select options that match the set of values.
This behavior is in `jQuery` versions `1.2` and above.
You most likely want this:
```
$("._statusDDL").val('2');
```
Add `.change()` to see the option in the dropdown list frontend:
```
$("._statusDDL").val('2').change();
``` | With hidden field you need to use like this:
```
$("._statusDDL").val(2);
$("._statusDDL").change();
```
or
```
$("._statusDDL").val(2).change();
``` | Change the selected value of a drop-down list with jQuery | [
"",
"javascript",
"jquery",
"asp.net",
"html-select",
""
] |
I'd like to accomplish something like this: Call a method, say "turn", and then have "turn" applied differently to different data types, e.g., calling "turn" with a "screwdriver" object/param uses the "turnScrewdriver" method, calling "turn" with a "steeringWheel" object/param uses the "turnSteeringWheel" method, etc. -- different things are being done, but they're both called "turn."
I'd like to implement this so that the calling code needn't worry about the type(s) involved. In this example, "turn" should suffice to "turn" a "screwdriver", "steeringWheel", or whatever might need to be "turned."
In C++ I'd do this with overloading -- and C++ would sort things out based on the datatype/signature -- but this doesn't work in PHP.
Any suggestions as to where should I begin? A switch statement is obvious, but I'm thinking there must be a (more elegant) OO solution. No?
TIA | I read davethegr8's solution but it seems one could do the same thing with stronger typing:
```
<?php
interface Turnable
{
public function turn();
}
class Screwdriver implements Turnable
{
public function turn() {
print "to turning sir!\n";
}
}
class SteeringWheel implements Turnable
{
public function turn() {
print "to everything, turn, turn turn!\n";
}
}
function turn(Turnable $object) {
$object->turn();
}
$driver = new Screwdriver();
turn($driver);
$wheel = new SteeringWheel();
turn($wheel);
$obj = new Object(); // any object that does not implement Turnable
turn($object); // ERROR!
```
PHP does permit you to use a type hint for the parameter, and the type hint can be an interface name instead of a class name. So you can be sure that if the `$object` implements the `Turnable` interface, then it *must* have the `turn()` method. Each class that implements `Turnable` can do its own thing to accomplish turning. | I think this will work...
```
function turn($object) {
if(method_exists($object, 'turn'.ucwords(get_class($object))) {
$fname = 'turn'.ucwords(get_class($object));
return $object->$fname();
}
return false;
}
``` | Something like overloading in PHP? | [
"",
"php",
"oop",
"overloading",
""
] |
In terms of PC development (excluding Xbox and Zune),
What is the difference between XNA and C# DirectX? Does C# DirectX have a significant advantage over XNA (in terms of speed, royalties, etc)?
How are the two compared to the speed unmanaged C++ DirectX?
Where is the industry moving in terms of game programming? | If you're actually good at writing unmanaged code, then you'll probably be able to write a faster graphics engine on top of DirectX. However, for the hobbyist, XNA has *plenty* of performance, both for 2D and 3D game development.
[Here is a good Channel 9 video](http://channel9.msdn.com/posts/Rory/Looking-at-XNA-Part-Two/) where they run an XNA-built racing game on Xbox 360. It runs well even at full HD. Several of the XBox Live Arcade games have been developed by the XNA community.
As far as C# DirectX, as I recall, Managed DirectX as it was called, is no longer officially supported since XNA basically replaces it. I could be wrong, its been a very long time since I looked at it.
The performance differences are negligible between XNA and Managed DirectX since, in essence they're the same thing; XNA just has a few convenience bits to reduce the amount of boilerplate code you need to write. | The Xna Game Studio stuff is focused around solving game centric problems, though I would question any poster that says the performance of the Xna game studio stuff is any worse than managed direct x without seeing some decent metrics.
An independent group outside of MS have created a project called SlimDx - <http://slimdx.mdxinfo.com/>
If you are writing an application rather than a game (which I expect you are not by the other questions) then that might be worth considering.
The industry still heavily uses C++ for game guts, but there have been successful releases of games written in completely managed code using XNA Game Studio on the community games section of XBox live, and released on the XBox Arcade itself. There should be some interesting stats coming pretty soon about how much people have made on the community games.
Many full price games use C++ for some, but something like Lua for actual game logic... and Lua is not known for the blazing speed!
C# has a good learning curve and is used by tools programmers in the industry - it would be a useful language to have under your belt. C++ would be a great language to have, but it requires more discipline to create functional code - and gives someone new a lot more rope to hang themselves by. C# can dynamically change and do things like unroll loops at runtime rather than compile time - good C# can be as fast or faster than good readable C++ - but you have to know how to use it. In really tight loops, C++ and Assembler might win out in certain circumstances. Often in games using C++, custom allocators are created with their own memory strategies to try and help fragmentation caused by normal allocators... that kind of thing is dealt with by the CLR in .Net/C# and as long as you program to the garbage collectors strengths (the same that you would have to do with your own C++ implementation) then you do not have to concern yourself with such low level implementation detail in .Net.
If you are looking in to getting in to game development and deciding on a language (which, reading between the lines seems to be where you are going with that line of questioning) then the best language to use is the one where you have a finished project to show at the end of it, be it C++, objective C, C#, Flash, Silverlight, etc. As languages change and go in and out of favour, recruiters often look for proven mastery of different languages - which might mitigate not knowing the one they are currently using - and a portfolio of completed work would do that. | Comparison between XNA and DirectX (C#) | [
"",
"c#",
"directx",
"xna",
""
] |
I have some Visual C++ code that receives a pointer to a buffer with data that needs to be processed by my code and the length of that buffer. Due to a bug outside my control, sometimes this pointer comes into my code uninitialized or otherwise unsuitable for reading (i.e. it causes a crash when I try to access the data in the buffer.)
So, I need to verify this pointer before I use it. I don't want to use IsBadReadPtr or IsBadWritePtr because everyone agrees that they're buggy. (Google them for examples.) They're also not thread-safe -- that's probably not a concern in this case, though a thread-safe solution would be nice.
I've seen suggestions on the net of accomplishing this by using VirtualQuery, or by just doing a memcpy inside an exception handler. However, the code where this check needs to be done is time sensitive so I need the most efficient check possible that is also 100% effective. Any ideas would be appreciated.
Just to be clear: I know that the best practice would be to just read the bad pointer, let it cause an exception, then trace that back to the source and fix the actual problem. However, in this case the bad pointers are coming from Microsoft code that I don't have control over so I have to verify them.
Note also that I don't care if the data pointed at is valid. My code is looking for specific data patterns and will ignore the data if it doesn't find them. I'm just trying to prevent the crash that occurs when running memcpy on this data, and handling the exception at the point memcpy is attempted would require changing a dozen places in legacy code (but if I had something like IsBadReadPtr to call I would only have to change code in one place). | > a thread-safe solution would be nice
I'm guessing it's only IsBadWritePtr that isn't thread-safe.
> just doing a memcpy inside an exception handler
This is effectively what IsBadReadPtr is doing ... and if you did it in your code, then your code would have the same bug as the IsBadReadPtr implementation: <http://blogs.msdn.com/oldnewthing/archive/2006/09/27/773741.aspx>
**--Edit:--**
The only problem with IsBadReadPtr that I've read about is that the bad pointer might be pointing to (and so you might accidentally touch) a stack's guard page. Perhaps you could avoid this problem (and therefore use IsBadReadPtr safely), by:
* Know what threads are running in your process
* Know where the threads' stacks are, and how big they are
* Walk down each stack, delberately touching each page of the stack at least once, before you begin to call isBadReadPtr
Also, the some of the comments associated with the URL above also suggest using VirtualQuery. | ```
bool IsBadReadPtr(void* p)
{
MEMORY_BASIC_INFORMATION mbi = {0};
if (::VirtualQuery(p, &mbi, sizeof(mbi)))
{
DWORD mask = (PAGE_READONLY|PAGE_READWRITE|PAGE_WRITECOPY|PAGE_EXECUTE_READ|PAGE_EXECUTE_READWRITE|PAGE_EXECUTE_WRITECOPY);
bool b = !(mbi.Protect & mask);
// check the page is not a guard page
if (mbi.Protect & (PAGE_GUARD|PAGE_NOACCESS)) b = true;
return b;
}
return true;
}
``` | Most efficient replacement for IsBadReadPtr? | [
"",
"c++",
"windows",
"visual-c++",
"memory",
""
] |
People always advised me that if I am doing some application that should use some Windows APIs to do any process level job, I must use VC++ and not any other .net language.
Is there any truth in that?
Can everything that can be done using VC++ be done in other .net languages also?
Are all the .net languages the same when their capabilities are compared? | If you need to work with native code fairly intimately, C++ is likely to make life easier. However, there's nothing inherently wrong with using P/Invoke to call into the Win32 API from C#, VB.NET, F# etc.
Not all .NET languages are the same in terms of capabilities, although C# and VB.NET are *largely* equivalent in functionality. I know there are some things which C++/CLI exposes which aren't exposed by C# or VB.NET - I don't know if the reverse is true. (I've no idea what C++/CLI is like for lambda expressions, extension methods etc.) | For most tasks where the class libraries do not provide help, using P/Invoke is usually fine. There are many "rough" APIs out there that benefit from a simple C++/CLI wrapper. It's usually best to do the bare minimum in the C++/CLI code -- effectively massaging what ever ugliness is below for consumption by C#, VB.NET, etc. | Windows API and .net languages | [
"",
"c#",
".net",
"vb.net",
"winapi",
"visual-c++",
""
] |
I need to test my PHP applications with multiple versions of PHP 5.x, such as PHP 5.0.0 and PHP 5.2.8.
Is there a way that I can configure a development LAMP server so I can quickly test applications with multiple versions of PHP5? | One way to do this is to have your main version of php set up with mod\_php and run all of the others through fast cgi on different ports (i.e. 81, 82, 83 etc). This won't guarantee totally consistent behavior though. | With CentOS, you can do it using a combination of fastcgi for one version of PHP, and php-fpm for the other, as described here:
<https://web.archive.org/web/20130707085630/http://linuxplayer.org/2011/05/intall-multiple-version-of-php-on-one-server>
# Based on CentOS 5.6, for Apache only
## 1. Enable rpmforge and epel yum repository
```
wget http://packages.sw.be/rpmforge-release/rpmforge-release-0.5.2-2.el5.rf.x86_64.rpm
wget http://download.fedora.redhat.com/pub/epel/5/x86_64/epel-release-5-4.noarch.rpm
sudo rpm -ivh rpmforge-release-0.5.2-2.el5.rf.x86_64.rpm
sudo rpm -ivh epel-release-5-4.noarch.rpm
```
## 2. Install php-5.1
CentOS/RHEL 5.x series have php-5.1 in box, simply install it with yum, eg:
```
sudo yum install php php-mysql php-mbstring php-mcrypt
```
## 3. Compile and install php 5.2 and 5.3 from source
For php 5.2 and 5.3, we can find many rpm packages on the Internet. However, they all conflict with the php which comes with CentOS, so, we’d better build and install them from soure, this is not difficult, the point is to install php at different location.
However, when install php as an apache module, we can only use one version of php at the same time. If we need to run different version of php on the same server, at the same time, for example, different virtual host may need different version of php. Fortunately, the cool FastCGI and PHP-FPM can help.
Build and install php-5.2 with fastcgi enabled
### 1) Install required dev packages
```
yum install gcc libxml2-devel bzip2-devel zlib-devel \
curl-devel libmcrypt-devel libjpeg-devel \
libpng-devel gd-devel mysql-devel
```
### 2) Compile and install
```
wget http://cn.php.net/get/php-5.2.17.tar.bz2/from/this/mirror
tar -xjf php-5.2.17.tar.bz2
cd php-5.2.17
./configure --prefix=/usr/local/php52 \
--with-config-file-path=/etc/php52 \
--with-config-file-scan-dir=/etc/php52/php.d \
--with-libdir=lib64 \
--with-mysql \
--with-mysqli \
--enable-fastcgi \
--enable-force-cgi-redirect \
--enable-mbstring \
--disable-debug \
--disable-rpath \
--with-bz2 \
--with-curl \
--with-gettext \
--with-iconv \
--with-openssl \
--with-gd \
--with-mcrypt \
--with-pcre-regex \
--with-zlib
make -j4 > /dev/null
sudo make install
sudo mkdir /etc/php52
sudo cp php.ini-recommended /etc/php52/php.ini
```
### 3) create a fastcgi wrapper script
create file /usr/local/php52/bin/fcgiwrapper.sh
```
#!/bin/bash
PHP_FCGI_MAX_REQUESTS=10000
export PHP_FCGI_MAX_REQUESTS
exec /usr/local/php52/bin/php-cgi
chmod a+x /usr/local/php52/bin/fcgiwrapper.sh
Build and install php-5.3 with fpm enabled
wget http://cn.php.net/get/php-5.3.6.tar.bz2/from/this/mirror
tar -xjf php-5.3.6.tar.bz2
cd php-5.3.6
./configure --prefix=/usr/local/php53 \
--with-config-file-path=/etc/php53 \
--with-config-file-scan-dir=/etc/php53/php.d \
--enable-fpm \
--with-fpm-user=apache \
--with-fpm-group=apache \
--with-libdir=lib64 \
--with-mysql \
--with-mysqli \
--enable-mbstring \
--disable-debug \
--disable-rpath \
--with-bz2 \
--with-curl \
--with-gettext \
--with-iconv \
--with-openssl \
--with-gd \
--with-mcrypt \
--with-pcre-regex \
--with-zlib
make -j4 && sudo make install
sudo mkdir /etc/php53
sudo cp php.ini-production /etc/php53/php.ini
sed -i -e 's#php_fpm_CONF=\${prefix}/etc/php-fpm.conf#php_fpm_CONF=/etc/php53/php-fpm.conf#' \
sapi/fpm/init.d.php-fpm
sudo cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
sudo chmod a+x /etc/init.d/php-fpm
sudo /sbin/chkconfig --add php-fpm
sudo /sbin/chkconfig php-fpm on
sudo cp sapi/fpm/php-fpm.conf /etc/php53/
```
**Configue php-fpm**
Edit /etc/php53/php-fpm.conf, change some settings. This step is mainly to uncomment some settings, you can adjust the value if you like.
```
pid = run/php-fpm.pid
listen = 127.0.0.1:9000
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
```
**Then, start fpm**
```
sudo /etc/init.d/php-fpm start
```
**Install and setup mod\_fastcgi, mod\_fcgid**
```
sudo yum install libtool httpd-devel apr-devel
wget http://www.fastcgi.com/dist/mod_fastcgi-current.tar.gz
tar -xzf mod_fastcgi-current.tar.gz
cd mod_fastcgi-2.4.6
cp Makefile.AP2 Makefile
sudo make top_dir=/usr/lib64/httpd/ install
sudo sh -c "echo 'LoadModule fastcgi_module modules/mod_fastcgi.so' > /etc/httpd/conf.d/mod_fastcgi.conf"
yum install mod_fcgid
```
**Setup and test virtual hosts**
1) Add the following line to /etc/hosts
```
127.0.0.1 web1.example.com web2.example.com web3.example.com
```
2) Create web document root and drop an index.php under it to show phpinfo
switch to user root, run
```
mkdir /var/www/fcgi-bin
for i in {1..3}; do
web_root=/var/www/web$i
mkdir $web_root
echo "<?php phpinfo(); ?>" > $web_root/index.php
done
```
*Note: The empty /var/www/fcgi-bin directory is required, DO NOT REMOVE IT LATER*
3) Create Apache config file(append to httpd.conf)
```
NameVirtualHost *:80
# module settings
# mod_fcgid
<IfModule mod_fcgid.c>
idletimeout 3600
processlifetime 7200
maxprocesscount 17
maxrequestsperprocess 16
ipcconnecttimeout 60
ipccommtimeout 90
</IfModule>
# mod_fastcgi with php-fpm
<IfModule mod_fastcgi.c>
FastCgiExternalServer /var/www/fcgi-bin/php-fpm -host 127.0.0.1:9000
</IfModule>
# virtual hosts...
#################################################################
#1st virtual host, use mod_php, run php-5.1
#################################################################
<VirtualHost *:80>
ServerName web1.example.com
DocumentRoot "/var/www/web1"
<ifmodule mod_php5.c>
<FilesMatch \.php$>
AddHandler php5-script .php
</FilesMatch>
</IfModule>
<Directory "/var/www/web1">
DirectoryIndex index.php index.html index.htm
Options -Indexes FollowSymLinks
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
#################################################################
#2nd virtual host, use mod_fcgid, run php-5.2
#################################################################
<VirtualHost *:80>
ServerName web2.example.com
DocumentRoot "/var/www/web2"
<IfModule mod_fcgid.c>
AddHandler fcgid-script .php
FCGIWrapper /usr/local/php52/bin/fcgiwrapper.sh
</IfModule>
<Directory "/var/www/web2">
DirectoryIndex index.php index.html index.htm
Options -Indexes FollowSymLinks +ExecCGI
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
#################################################################
#3rd virtual host, use mod_fastcgi + php-fpm, run php-5.3
#################################################################
<VirtualHost *:80>
ServerName web3.example.com
DocumentRoot "/var/www/web3"
<IfModule mod_fastcgi.c>
ScriptAlias /fcgi-bin/ /var/www/fcgi-bin/
AddHandler php5-fastcgi .php
Action php5-fastcgi /fcgi-bin/php-fpm
</IfModule>
<Directory "/var/www/web3">
DirectoryIndex index.php index.html index.htm
Options -Indexes FollowSymLinks +ExecCGI
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
```
4) restart apache. visit the 3 sites respectly to view phpinfo and validate the result. ie:
```
http://web1.example.com
http://web2.example.com
http://web3.example.com
```
If all OK, you can use one of the 3 virtual host as template to create new virtual host, with the desired php version. | How can one run multiple versions of PHP 5.x on a development LAMP server? | [
"",
"php",
"lamp",
""
] |
I'm working on an instant messenger client in C++ (Win32) and I'm experimenting with different asynchronous socket models. So far I've been using [WSAAsyncSelect](http://msdn.microsoft.com/en-us/library/ms741540(VS.85).aspx) for receiving notifications via my main window. However, I've been experiencing some unexpected results with Winsock spawning additionally 5-6 threads (in addition to the initial thread created when calling WSAAsyncSelect) for one single socket.
I have plans to revamp the client to support additional protocols via DLL:s, and I'm afraid that my current solution won't be suitable based on my experiences with WSAAsyncSelect in addition to me being negative towards mixing network with UI code (in the message loop).
I'm looking for advice on what a suitable asynchronous socket model could be for a multi-protocol IM client which needs to be able to handle **roughly 10-20+ connections** (depending on amount of protocols and protocol design etc.), while not using an excessive amount of threads -- I am very interested in performance and keeping the resource usage down.
I've been looking on IO Completion Ports, but from what I've gathered, it seems overkill. I'd very much appreciate some input on what a suitable socket solution could be!
Thanks in advance! :-) | There are four basic ways to handle multiple concurrent sockets.
1. Multiplexing, that is using select() to poll the sockets.
2. AsyncSelect which is basically what you're doing with WSAAsyncSelect.
3. Worker Threads, creating a single thread for each connection.
4. IO Completion Ports, or IOCP. dp mentions them above, but basically they are an OS specific way to handle asynchronous I/O, which has very good performance, but it is a little more confusing.
Which you choose often depends on where you plan to go. If you plan to port the application to other platforms, you may want to choose #1 or #3, since select is not terribly different from other models used on other OS's, and most other OS's also have the concept of threads (though they may operate differently). IOCP is typically windows specific (although Linux now has some async I/O functions as well).
If your app is Windows only, then you basically want to choose the best model for what you're doing. This would likely be either #3 or #4. #4 is the most efficient, as it calls back into your application (similar, but with better peformance and fewer issues to WSAsyncSelect).
The big thing you have to deal with when using threads (either IOCP or WorkerThreads) is marshaling the data back to a thread that can update the UI, since you can't call UI functions on worker threads. Ultimately, this will involve some messaging back and forth in most cases.
If you were developing this in Managed code, i'd tell you to look at Jeffrey Richter's AysncEnumerator, but you've chose C++ which has it's pros and cons. Lots of people have written various network libraries for C++, maybe you should spend some time researching some of them. | consider to use the ASIO library you can find in boost (www.boost.org). | Most suitable asynchronous socket model for an instant messenger client? | [
"",
"c++",
"sockets",
""
] |
My javascript gets included multiple times with the script tag, like so:
```
<script src="code.js></script>
<script src="code.js></script>
<script src="code.js></script>
```
Right now I have this code inside **code.js** to make my code run only once without overwriting my namespaces:
```
if(typeof _ow == "undefined" ){
_ow = {};
// code in here will only run once
_ow.Auth = (function(){
})();
_ow.Template = (function(){
})();
}
```
Is there any better structure I could use to make my code only run once? | Are you familiar with Crockford's [Javascript Module Pattern](http://ajaxian.com/archives/a-javascript-module-pattern)?
A slight variation on how to prevent overwriting the namespace:
```
var _ow;
if(!_ow) _ow = {};
``` | ```
var _ow = _ow || { Auth: ... };
```
if its already defined then it wont be defined again. | Javascript idiom for code structure | [
"",
"javascript",
"idioms",
""
] |
I have the following code:
```
<script type="text/javascript">
$(document).ready(function() {
$("#Save").click(function() {
$.post("url", {
"data": "data"
}, function(data) {
alert(data);
});
});
});
</script>
```
I'm testing this script, and one of the tests I'm making is, I just close the asp.net web development server, and click the button.
IE says "access denied" error, I want to catch any error that occurs here, and display a friendly message to the user in this case.
I trying to use try/catch but didn't work...
Any clue? | Use the [`$.ajax()`](http://docs.jquery.com/Ajax/jQuery.ajax) method instead. It has a hook for errors.
[For example](http://www.ibm.com/developerworks/library/x-ajaxjquery.html):
```
$.ajax({
url: 'document.xml',
type: 'GET',
dataType: 'xml',
timeout: 1000,
error: function(){
alert('Error loading XML document');
},
success: function(xml){
// do something with xml
}
});
``` | This is a useful snippet for tracking down any jquery ajax errors in conjunction with [FireBug](http://getfirebug.com/).
```
// Displays any ajax errors in the Firebug console instead of hiding them
$(document).ajaxError(function(){
if (window.console && window.console.error) {
console.error(arguments);
}
});
```
> If you use Ajax with jQuery, you may have noticed that you don't get any error messages when things go wrong. Even if you have major bugs in your callback functions, jQuery just silently fails, sweeping any errors under the rug, and leaving you clueless as to what just happened.
>
> After running this code, you'll start getting error messages in your Firebug console (if anything breaks with your Ajax calls or callbacks). The error messages aren't the greatest, but at least you don't have to stay in the dark any longer.
[Credit goes to Jesse Skinner](http://www.thefutureoftheweb.com/blog/hidden-ajax-errors-in-jquery) | Catch exceptions in jQuery | [
"",
"asp.net",
"javascript",
"jquery",
"ajax",
"error-handling",
""
] |
Should I use decimal or float to store a ratio in a database? Particularly in SQL2005. | That depends on what your need for accuracy is. If you can tolerate the typical errors that come from the IEEE method of storing floating point numbers, then use a float, otherwise, use a decimal if you need an exact representation (and that goes for any numbers that are not integers that you will use in calculations using the percentage as well). | It depends what your ratio is, really.
For interest rates, for instance, in banking, we always use decimal, with a precision and scale determined by the business. If an interest rate is to be calculated and the result is beyond the precision of the column, then there is always a business rule which defines how the result is to be rounded or truncated to fit into the column.
If your ratio is, for example, the ratio between an object's diameter and it's circumference, I would probably use a float. | SQL: What do you use to store a ratio (percentage) in a database? | [
"",
"sql",
"sql-server-2005",
"types",
""
] |
I want to create a file using C++, but I have no idea how to do it. For example I want to create a text file named `Hello.txt`.
Can anyone help me? | One way to do this is to create an instance of the ofstream class, and use it to write to your file. Here's a link to a website that has some example code, and some more information about the standard tools available with most implementations of C++:
[ofstream reference](http://en.cppreference.com/w/cpp/io/basic_ofstream)
For completeness, here's some example code:
```
// using ofstream constructors.
#include <iostream>
#include <fstream>
std::ofstream outfile ("test.txt");
outfile << "my text here!" << std::endl;
outfile.close();
```
You want to use std::endl to end your lines. An alternative is using '\n' character. These two things are different, std::endl flushes the buffer and writes your output immediately while '\n' allows the outfile to put all of your output into a buffer and maybe write it later. | Do this with a file stream. When a `std::ofstream` is closed, the file is created. I prefer the following code, because the OP only asks to create a file, not to write in it:
```
#include <fstream>
int main()
{
std::ofstream { "Hello.txt" };
// Hello.txt has been created here
}
```
The stream is destroyed right after its creation, so the stream is closed inside the destructor and thus the file is created. | Creating files in C++ | [
"",
"c++",
"file-io",
""
] |
My little brother is just getting into programming, and for his Science Fair project, he's doing a simulation of a flock of birds in the sky. He's gotten most of his code written, and it works nicely, but the birds need to move *every moment*.
Tkinter, however, hogs the time for its own event loop, and so his code won't run. Doing `root.mainloop()` runs, runs, and keeps running, and the only thing it runs is the event handlers.
Is there a way to have his code run alongside the mainloop (without multithreading, it's confusing and this should be kept simple), and if so, what is it?
Right now, he came up with an ugly hack, tying his `move()` function to `<b1-motion>`, so that as long as he holds the button down and wiggles the mouse, it works. But there's got to be a better way. | Use the `after` method on the `Tk` object:
```
from tkinter import *
root = Tk()
def task():
print("hello")
root.after(2000, task) # reschedule event in 2 seconds
root.after(2000, task)
root.mainloop()
```
Here's the declaration and documentation for the `after` method:
```
def after(self, ms, func=None, *args):
"""Call function once after given time.
MS specifies the time in milliseconds. FUNC gives the
function which shall be called. Additional parameters
are given as parameters to the function call. Return
identifier to cancel scheduling with after_cancel."""
``` | The [solution posted by Bjorn](https://stackoverflow.com/a/538559/355230) results in a "RuntimeError: Calling Tcl from different appartment" message on my computer (RedHat Enterprise 5, python 2.6.1). Bjorn might not have gotten this message, since, according to [one place I checked](http://www.mail-archive.com/tkinter-discuss@python.org/msg01808.html), mishandling threading with Tkinter is unpredictable and platform-dependent.
The problem seems to be that `app.start()` counts as a reference to Tk, since app contains Tk elements. I fixed this by replacing `app.start()` with a `self.start()` inside `__init__`. I also made it so that all Tk references are either inside the *function that calls `mainloop()`* or are inside *functions that are called by* the function that calls `mainloop()` (this is apparently critical to avoid the "different apartment" error).
Finally, I added a protocol handler with a callback, since without this the program exits with an error when the Tk window is closed by the user.
The revised code is as follows:
```
# Run tkinter code in another thread
import tkinter as tk
import threading
class App(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.start()
def callback(self):
self.root.quit()
def run(self):
self.root = tk.Tk()
self.root.protocol("WM_DELETE_WINDOW", self.callback)
label = tk.Label(self.root, text="Hello World")
label.pack()
self.root.mainloop()
app = App()
print('Now we can continue running code while mainloop runs!')
for i in range(100000):
print(i)
``` | How do you run your own code alongside Tkinter's event loop? | [
"",
"python",
"events",
"tkinter",
""
] |
Is it possible to pass parameters with an `HTTP` get request? If so, how should I then do it? I have found an `HTTP` post requst ([link](http://msdn.microsoft.com/en-us/library/debx8sh9.aspx)). In that example the string `postData` is sent to a webserver. I would like to do the same using *get* instead. Google found this example on `HTTP` get [here](http://support.microsoft.com/kb/307023). However no parameters are sent to the web server. | In a GET request, you pass parameters as part of the query string.
```
string url = "http://somesite.com?var=12345";
``` | My preferred way is this. It handles the escaping and parsing for you.
```
WebClient webClient = new WebClient();
webClient.QueryString.Add("param1", "value1");
webClient.QueryString.Add("param2", "value2");
string result = webClient.DownloadString("http://theurl.com");
``` | How to make an HTTP get request with parameters | [
"",
"c#",
"httpwebrequest",
"get",
""
] |
I'm trying to get access to a form and its elements. The form is within an iframe and the javascript code that is accessing the form is within the main document.
I'm not sure what else I should put into the question, so please let me know if I need to add something else.
(form and main page are in the same domain)
Thanks | ```
var ifr = document.getElementById( yourIframeId );
var ifrDoc = ifr.contentDocument || ifr.contentWindow.document;
var theForm = ifrDoc.getElementById( yourFormId );
```
Or you could have some code in the frame that sets a variable in `parent` to the form, but I wouldn't trust that method. | If your iframe has a `name` attribute, that can be used as a window name. If the frame name is "myframe":
```
myframe.document.getElementById("myform") // gives you the form element
``` | accessing a form that is in an iframe | [
"",
"javascript",
"forms",
"iframe",
""
] |
I'm trying write a query to find records which don't have a matching record in another table.
For example, I have a two tables whose structures looks something like this:
```
Table1
State | Product | Distributor | other fields
CA | P1 | A | xxxx
OR | P1 | A | xxxx
OR | P1 | B | xxxx
OR | P1 | X | xxxx
WA | P1 | X | xxxx
VA | P2 | A | xxxx
Table2
State | Product | Version | other fields
CA | P1 | 1.0 | xxxx
OR | P1 | 1.5 | xxxx
WA | P1 | 1.0 | xxxx
VA | P2 | 1.2 | xxxx
```
(State/Product/Distributor together form the key for Table1. State/Product is the key for Table2)
I want to find all the State/Product/Version combinations which are Not using distributor X. (So the result in this example is CA-P1-1.0, and VA-P2-1.2.)
Any suggestions on a query to do this? | ```
SELECT
*
FROM
Table2 T2
WHERE
NOT EXISTS (SELECT *
FROM
Table1 T1
WHERE
T1.State = T2.State AND
T1.Product = T2.Product AND
T1.Distributor = 'X')
```
This should be ANSI compliant. | In T-SQL:
```
SELECT DISTINCT Table2.State, Table2.Product, Table2.Version
FROM Table2
LEFT JOIN Table1 ON Table1.State = Table2.State AND Table1.Product = Table2.Product AND Table1.Distributor = 'X'
WHERE Table1.Distributor IS NULL
```
No subqueries required.
Edit: As the comments indicate, the DISTINCT is not necessary. Thanks! | Finding unmatched records with SQL | [
"",
"sql",
"select",
""
] |
I have a solution with 10 projects. Many of the projects depend on a third party DLL called `foo.dll`.
The issue is that when I upgrade foo, somehow in Visual Studio when I go to the Object Browser it shows me two versions of `foo.dll`.
How can I find out which project is referencing the old version of foo.dll so I can upgrade it so there is only one dependency across all projects? | This is the kind of thing you only want to do once.
My recommendation to you is to get Notepad. Yes, Notepad.
Open the .csproj file for each of your projects.
There will be a section in the XML outlining the DLL that is being referenced including the path, etc. Even if they are coming out of the GAC, the version, etc. which is used by the .NET linker will be included in the file. The whole line to the reference must match exactly.
Compare these against one project which you know to be correct.
Dealing with references in .NET is one of the worst parts of it. Welcome to DLL hell v2.0 :( | It sounds like you have both versions of Foo.dll installed in the GAC.
Check out [gacutil](http://en.wikipedia.org/wiki/Global_Assembly_Cache#Global_Assembly_Cache_Tool) to remove the old one.
If it is just a file reference, then in each project, open 'References' and right click on 'Foo' and choose properties. It will tell you in the resulting properties window information such as version.
Usually the best approach to dependencies like this is to have a separate folder at project level (but not part of the actual solution) called 'Dependencies' with these kinds of DLLs in them.
I'd also consider some build automation on your server (TFS = Team Build, SVN = Cruise Control, etc.) that will copy the right version of an assembly into the bin folder prior to build.
There are lots of ways to go with assemblies and it's easy to get confused over which one is being used by various applications. It's worth spending some time solving this problem once in a templateable manner that can apply to all future projects. | Solution with mulitple projects dependent on the same binary reference | [
"",
"c#",
"binary",
"dependencies",
"reference",
"projects-and-solutions",
""
] |
I am trying to create a c++ ostream for educational reasons. My test will be creating an ostream that acts like a ofstream would except instead of writing to a file it would write to a deque or vector container. | As it is for education, as you say, i will show you how i would do such a thingy. Otherwise, `stringstream` is really the way to go.
Sounds like you want to create a streambuf implementation that then writes to a vector / deque. Something like this (copying from another answer of me that [targeted a /dev/null stream](http://groups.google.com/group/comp.lang.c++.moderated/browse_thread/thread/82097fd888b76953)):
```
template<typename Ch, typename Traits = std::char_traits<Ch>,
typename Sequence = std::vector<Ch> >
struct basic_seqbuf : std::basic_streambuf<Ch, Traits> {
typedef std::basic_streambuf<Ch, Traits> base_type;
typedef typename base_type::int_type int_type;
typedef typename base_type::traits_type traits_type;
virtual int_type overflow(int_type ch) {
if(traits_type::eq_int_type(ch, traits_type::eof()))
return traits_type::eof();
c.push_back(traits_type::to_char_type(ch));
return ch;
}
Sequence const& get_sequence() const {
return c;
}
protected:
Sequence c;
};
// convenient typedefs
typedef basic_seqbuf<char> seqbuf;
typedef basic_seqbuf<wchar_t> wseqbuf;
```
You can use it like this:
```
seqbuf s;
std::ostream os(&s);
os << "hello, i'm " << 22 << " years old" << std::endl;
std::vector<char> v = s.get_sequence();
```
If you want to have a deque as sequence, you can do so:
```
typedef basic_seqbuf< char, char_traits<char>, std::deque<char> > dseq_buf;
```
Or something similar... Well i haven't tested it. But maybe that's also a good thing - so if it contains still bugs, you can try fixing them. | Use std::stringstream
```
#include <iostream>
#include <sstream>
int main()
{
std::stringstream s;
s << "Plop" << 5;
std::cout << s.str();
}
``` | creating an ostream | [
"",
"c++",
"std",
"ostream",
""
] |
For example, there is this website: www.azet.sk
On the right, there is login and password, I'd like my application to login to this web application and retrieve the data from my own account to C# (.NET) application and work with it. The aim is to keep the "logged in" connection alive and send vars using POST method. Is there any tutorial or easy script with examples to learn this? | ```
string username = "your";
string password = "password";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://moje.azet.sk/prihlasenie.phtml?KDE=www.azet.sk%2Findex.phtml%3F");
using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII))
{
writer.Write("nick=" + username + "&password=" + password);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//Retrieve your cookie that id's your session
//response.Cookies
using (StreamReader reader = new StreamReader(response.GetResponseStream())
{
Console.WriteLine(reader.ReadToEnd());
}
``` | The login part should be relatively easy.
Use `System.Net.WebClient` and the `UploadValues()` method to POST the form data. Look at the HTML source to figure out the field values to POST.
Most forms-based auth mechanisms use an HTTP cookie to keep the user logged in. So, after you POST the values, examine the `WebClient`'s `ResponseHeaders` collection for the 'Set-Cookie:' header.
Store the cookie value for subsequent GETs/POSTs to the website.
You'll probably find that "retrieving the data from your account and working with it" is much more complicated (i.e. screen-scraping, etc).
Here's a link that has some examples:
<http://codebetter.com/blogs/brendan.tompkins/archive/2005/05/18/63329.aspx> | How to login to HTML form using POST vars in C# (.NET)? | [
"",
"c#",
"html",
"logging",
"forms",
"post",
""
] |
It's been a while since I programmed in C++, and after coming from python, I feel soooo in a straight jacket, ok I'm not gonna rant.
I have a couple of functions that act as "pipes", accepting a list as input, returning another list as output (based on the input),
this is in concept, but in practice, I'm using `std::vector` to represent the list, is that acceptable?
further more, I'm not using any pointers, so I'm using `std::vector<SomeType> the_list(some_size);` as the variable, and returning it directly, i.e. `return the_list;`
P.S. So far it's all ok, the project size is small and this doesn't seem to affect performance, but I still want to get some input/advice on this, because I feel like I'm writing python in C++. | The only thing I can see is that your forcing a copy of the list you return. It would be more efficient to do something like:
```
void DoSomething(const std::vector<SomeType>& in, std::vector<SomeType>& out)
{
...
// no need to return anything, just modify out
}
```
Because you pass in the list you want to return, you avoid the extra copy.
Edit: This is an old reply. If you can use a modern C++ compiler with move semantics, you don't need to worry about this. Of course, this answer still applies if the object you are returning DOES NOT have move semantics. | If you really need a new list, I would simply return it. Return value optimization will take care of no needless copies in most cases, and your code stays very clear.
That being said, taking lists and returning other lists is indeed python programming in C++.
A, for C++, more suitable paradigm would be to create functions that take a range of iterators and alter the underlying collection.
e.g.
```
void DoSomething(iterator const & from, iterator const & to);
```
(with iterator possibly being a template, depending on your needs)
Chaining operations is then a matter of calling consecutive methods on begin(), end().
If you don't want to alter the input, you'd make a copy yourself first.
```
std::vector theOutput(inputVector);
```
This all comes from the C++ "don't pay for what you don't need" philosophy, you'd only create copies where you actually want to keep the originals. | Best way to return list of objects in C++? | [
"",
"c++",
"arrays",
"memory-management",
""
] |
I have a sequence of x, y and z -coordinates, which I need to manipulate. They are in one list of three tuples, like {(x1, y1, z1), (x2, y2, z2), ...}.
I need addition, multiplication and logarithm to manipulate my data.
I would like to study a module, which is as powerful as Awk -language. | If you need many array manipulation, then numpy is the best choice in python
```
>>> import numpy
>>> data = numpy.array([(2, 4, 8), (3, 6, 5), (7, 5, 2)])
>>> data
array([[2, 4, 8],
[3, 6, 5],
[7, 5, 2]])
>>> data.sum() # product of all elements
42
>>> data.sum(axis=1) # sum of elements in rows
array([14, 14, 14])
>>> data.sum(axis=0) # sum of elements in columns
array([12, 15, 15])
>>> numpy.product(data, axis=1) # product of elements in rows
array([64, 90, 70])
>>> numpy.product(data, axis=0) # product of elements in columns
array([ 42, 120, 80])
>>> numpy.product(data) # product of all elements
403200
```
or element wise operation with arrays
```
>>> x,y,z = map(numpy.array,[(2, 4, 8), (3, 6, 5), (7, 5, 2)])
>>> x
array([2, 4, 8])
>>> y
array([3, 6, 5])
>>> z
array([7, 5, 2])
>>> x*y
array([ 6, 24, 40])
>>> x*y*z
array([ 42, 120, 80])
>>> x+y+z
array([12, 15, 15])
```
element wise mathematical operations, e.g.
```
>>> numpy.log(data)
array([[ 0.69314718, 1.38629436, 2.07944154],
[ 1.09861229, 1.79175947, 1.60943791],
[ 1.94591015, 1.60943791, 0.69314718]])
>>> numpy.exp(x)
array([ 7.3890561 , 54.59815003, 2980.95798704])
``` | I'm not sure exactly what you're after. You can do a lot with list comprehensions. For example, if you want to turn a list:
```
coords = [(x1, y1, z1), (x2, y2, z2), (x3, y3, z3)] # etc
```
into a tuple `(x1+x2+x3, y1+y2+y3, z1+z2+z3)`, then you can do:
```
sums = (sum(a[0] for a in coords), sum(a[1] for a in coords), sum(a[2] for a in coords))
```
In fact, an experienced python programmer might write that as:
```
sums = map(sum, zip(*coords))
```
though that can look a bit like magic to a beginner.
If you want to multiply across coordinates, then the idea is similar. The only problem is python has no builtin multiplication equivalent to `sum`. We can build our own:
```
import operator
def prod(lst):
return reduce(operator.mul, lst)
```
Then you can multiply your tuples coordinate-wise as:
```
prods = map(prod, zip(*coords))
```
If you want to do something more complex with multiplication (inner product?) that will require a little more work (though it won't be very difficult).
I'm not sure what you want to take the logarithm of. But you can find the log function in the math module:
```
from math import log
```
Hope this helps. | Which Python module is suitable for data manipulation in a list? | [
"",
"python",
"module",
""
] |
The problem is a need to take the arguments into account before choosing the responder. Here is my attempt so far.
```
from responders import A, B, C
class RandomResponder(object)
def init(self, *args, *kwargs):
self.args = args
self.kwargs = kwargs
def __getattr__(self, name):
# pick a responder based on the args the function was called with
# I don't know how to do this part
# for sake of argument lets the args a function was called with lead me to pick responder A
r = A
responder = r(*self.args, **self.kwargs)
return responder.__getattr__(name)
```
The desired effect would be:
```
r = RandomResponder()
r.doSomething(1)
#returns A.doSomething()
r.doSomething(2)
#returns B.doSomething()
r.doSomething(3)
#return C.doSomething()
r.doSomethingElse(1)
#returns A.doSomethingElse()
r.doSomethingElse(2)
#returns B.doSomethingElse()
r.doSomethingElse(3)
#returns C.doSomethingElse()
```
I will not know ahead of time all the functions contained with the responders A, B, and C. | Try this:
```
class RandomResponder(object):
choices = [A, B, C]
@classmethod
def which(cls):
return random.choice(cls.choices)
def __getattr__(self, attr):
return getattr(self.which(), attr)
```
which() randomly selects an option from the choices, and which **getattr** uses to get the attribute.
EDIT: it actually looks like you want something more like this.
```
class RandomResponder(object):
choices = [A, B, C]
def __getattr__(self, attr):
# we define a function that actually gets called
# which takes up the first positional argument,
# the rest are left to args and kwargs
def doCall(which, *args, **kwargs):
# get the attribute of the appropriate one, call with passed args
return getattr(self.choices[which], attr)(*args, **kwargs)
return doCall
```
This could be written using lambda, but I'll just leave it like this so it's clearer. | When you do this
```
r.doSomething(1)
```
what happens is, in order:
* `r.__getattr__` is called, and returns an object
* this object is called with an argument "1"
At the time when `__getattr__` is called, you have no way of knowing what arguments the object you return is *going* to get called with, or even if it's going to be called at all...
So, to get the behavior that you want, `__getattr__` has to return a callable object that makes the decision itself based on the arguments *it's* called with. For example
```
from responders import A, B, C
class RandomResponder(object):
def __getattr__(self, name):
def func(*args, **kwds):
resp = { 1:A, 2:B, 3:C }[args[0]] # Decide which responder to use (example)
return getattr(resp, name)() # Call the function on the responder
return func
``` | Need to route instance calls inside a python class | [
"",
"python",
"class",
"instance",
""
] |
`Html.Encode` seems to simply call `HttpUtility.HtmlEncode` to replace a few html specific characters with their escape sequences.
However this doesn't provide any consideration for how new lines and multiple spaces will be interpretted (markup whitespace). So I provide a text area for the a user to enter a plain text block of information, and then later display that data on another screen (using `Html.Encode`), the new lines and spacing will not be preserved.
I think there are 2 options, but maybe there is a better 3rd someone can suggest.
One option would be to just write a static method that uses HtmlEncode, and then replaces new lines in the resulting string with `<br>` and groups of multiple spaces with ` `
Another option would be to mess about with the `white-space: pre` attribute in my style sheets - however I'm not sure if this would produce side effects when Html helper methods include new lines and tabbing to make the page source pretty.
Is there a third option, like a global flag, event or method override I can use to change how html encoding is done without having to redo the html helper methods? | `HtmlEncode` is only meant to encode characters for display in HTML. It specifically does not encode whitespace characters.
I would go with your first option, and make it an extension method for HtmlHelper. Something like:
```
public static string HtmlEncode(this HtmlHelper htmlHelper,
string text,
bool preserveWhitespace)
{
// ...
}
```
You could use `String.Replace()` to encode the newlines and spaces (or `Regex.Replace` if you need better matching). | Using the `style="white-space:pre-wrap;"` worked for me. Per [this article](http://blog.wolffmyren.com/2009/07/24/dev-tip-preserve-whitespace-in-html-without-using/). | ASP.NET MVC Html.Encode - New lines | [
"",
"c#",
"asp.net-mvc",
"newline",
"html-encode",
""
] |
I want to use Vectors in a C# application I'm writing, sepcifically a Vector3.
What's the best way for me to get a Vector type without writing my own? | I used one in a POC that I found on [CodeProject](http://www.codeproject.com/KB/recipes/VectorType.aspx). It's not ideal, but it worked for our situation. At the time, however, it did not have a method to reflect a Vector3 about a given normal, but that may have changed since then.
If you don't mind using DirectX (some stay away from it for whatever reason), then there is a [Vector3](http://msdn.microsoft.com/en-us/library/microsoft.windowsmobile.directx.vector3.aspx) type in that library as well. | Well, there's a struct called `Microsoft.DirectX.Vector3` if that's what you're looking for. You need to reference `Microsoft.DirectX.dll` to use it. | How can I get a vector type in C#? | [
"",
"c#",
"vector",
"directx",
""
] |
I'm trying to learn [JavaFX](http://www.javafx.com/ "JavaFX") and maybe create a few "learner" games. I always do my development in Eclipse, rather than NetBeans which the JavaFX team is clearly trying to push.
Can anybody point me in the direction of a how-to for building a JavaFX project in Eclipse, or at least building a JavaFX project *without* NetBeans? Everything I've found so far either uses NetBeans, or they're running a one-file project in Eclipse (witch won't work for larger projects). Idealy, I'm looking for somebody who's set up a simple Ant script that builds a JavaFX project, since I assume that's the end-game for this situation.
I was able to find where to download the [Eclipse JavaFX plugin](http://kenai.com/projects/eplugin/pages/Home "Eclipse JavaFX plugin"). It provides syntax highlighting support, plus some "snippets". I can even use it to run simple hello world type JavaFX apps, but I cant seem to get it to automatically build multi-file JavaFX projects. Even if I could, I still can't seem to write a correct ant script to jar up the JavaFX project.
Also, I found [this site](http://jfx.wikia.com/wiki/Ant_task) that talks about what you can do to use a *javafxc* Ant task created by Sun(?), but I'm not having any luck trying to use what they talk about.
Thanks
Ross | After I asked this question, an official (I think?) JavaFX plugin for Eclipse was released. Go to [the JavaFX for Eclipse](http://javafx.com/docs/gettingstarted/eclipse-plugin/index.jsp) page. I installed the plugin and everything automagically worked! | If you create new project in NB there is folder called nbproject. This folder contains `build-impl.xml`. This file contains this target:
```
<target if="src.dir" name="-compile-fx">
<taskdef classname="com.sun.tools.javafx.ant.JavaFxAntTask" classpath="${platform.bootcp}" name="javafxc"/>
<javafxc bootclasspath="${platform.bootcp}" classpath="${build.classes.dir}:${javac.classpath}" compilerclasspath="${platform.bootcp}" debug="${javac.debug}" deprecation="${javac.deprecation}" destdir="${build.classes.dir}" excludes="${excludes}" fork="yes" includeJavaRuntime="false" includeantruntime="false" includes="**/*.fx" source="${javac.source}" sourcepath="" srcdir="${src.dir}" target="${javac.target}">
<compilerarg line="${javac.compilerargs}"/>
</javafxc>
</target>
```
This is good start to create ant for Eclipse. I'm not sure how building works for Eclipse, but there could be limitations. The `com.sun.tools.javafx.ant.JavaFxAntTask` is located in SDK, not in compiler jar. Good luck!. | Build JavaFX project without NetBeans | [
"",
"java",
"eclipse",
"ant",
"javafx",
""
] |
if you create html layout like so
```
<ul>
<li class='a'></li>
<li class='b'></li>
<li class='a'></li>
<li class='b'></li>
<li class='a'></li>
<li class='b'></li>
<li class='a'></li>
<li class='b'></li>
</ul>
```
and try to select odd elements with 'a' class like so $$('.a:odd') you will get empty array, and if you do $$('.a:even') you will get all four li elements with 'a' class.. It really strange.. But im new to mootools, maybe im doing something wrong..
So my question is how to select first and third li elements with a class.
I know that i can do it with function like this
$$('.a').filter(function(item, index) { return index%2; }
but its too complicated for such small task as selecting odd or even elements.. | The problem is that :odd and :even (and their CSS cousins :nth-child(odd) and :nth-child(even)) refer to the order in which the elements appear as children of their parent, not as children with that particular selector.
This worked for me (Prototype, but it looks like MooTools has similar syntax):
```
var odd = $$('.a').filter(function(item, index) {
return index % 2 == 0;
});
var even = $$('.a').filter(function(item, index) {
return index % 2 == 1;
});
```
Edit: it seems you already covered that in the question, boo on me for answering before reading fully. | If you are trying to get the 1st and third, you just need $$('.a').
Are you trying to get the 1st and 5th items? That would be something like $$('a:nth-child(4n+1))
I am assuming mootools uses [css3 Structural pseudo-classes](http://www.w3.org/TR/css3-selectors/) | How to select even or odd elements based on class name | [
"",
"javascript",
"mootools",
""
] |
Im new to programming and I dont know very much about but I'm making a calculator, and i want to use a textbox that only acepts numbers and decimals, and when the user paste text from the clipboard the textbox deletes any literal characters, like the MS calc.
Please take the time to explain each part so I can learn or write it and tell me what to search.
Thanks
EDIT: I'll make it more specific:
How can I make a numeric textbox in C#? I've used the masked textbox but it wont take decimals.
I've read things about overloading the OnKeyPress method so it will correct any wrong characters but I dont know to do it. | The easiest way :)
on Keypress event on your textbox
---
```
if ((e.KeyChar <= 57 && e.KeyChar >= 48) || e.KeyChar == 13 || e.KeyChar == 8)
{
}
else
{
e.Handled = true;
}
```
--- | Add an event handler for the textbox you want to be numeric only, and add the following code:
```
private void textBoxNumbersOnly_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsDigit(e.KeyChar) || e.KeyChar == '\b')
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
```
This allows for numbers 0 to 9, and also backspaces (useful IMHO). Allow through the '.' character if you want to support decimals | Numeric TextBox | [
"",
"c#",
"textbox",
"numeric",
""
] |
Is there a built in method for waiting for a file to be created in c#? How about waiting for a file to be completely written?
I've baked my own by repeatedly attempting File.OpenRead() on a file until it succeeds (and failing on a timeout), but spinning on a file doesn't seem like the right thing to do. I'm guessing there's a baked-in method in .NET to do this, but I can't find it. | What about using the FileSystemWatcher component ?
This class 'watches' a given directory or file, and can raise events when something (you can define what) has happened. | When creating a file with `File.Create` you can just call the `Close` Function.
Like this:
```
File.Create(savePath).Close();
``` | Waiting for a file to be created in C# | [
"",
"c#",
"file-io",
""
] |
The scenario is this. A web page contains:
* some DIVs whose visibility can be toggled with a javascript (fired from an hyperlink)
* a Submit button, whose response takes about 5 seconds
The hyperlink code is
```
<a href="javascript:void null;" onclick="MyFunction()">foo</a>
```
The User:
1. Presses Submit.
2. While he is waiting for the response, he clicks on the hyperlink, and fires the javascript that toggles the DIVs visibility (no other request is performed).
3. In Internet Exporer 6, the browser stops waiting for the first Request.
The problem does not happen in other browsers, even if the user plays with the DIVs, the first request is correctly handled, and we navigate to the next page.
Does anyone know what might be causing this? Is it a known IE6 issue? | Yup, this is the **IE6** issue with **GET** requests *triggered from a Javascript action* on a *hyperlink* (**where the href is set to 'javascript:...'**).
> e.g. if your JavaScript calls
> `someForm.submit()` and the method is
> `GET`, there will be `NO` response (the
> request is definately sent though)
<http://webbugtrack.blogspot.com/2007/09/bug-223-magical-http-get-requests-in.html>
You either need to modify the link, to be like:
```
<a href="#bogushash" onclick="MyFunction()">foo</a>
^^^^^^^^^^
```
or always set the link with return false;
```
<a href="javascript:void null;" onclick="MyFunction();return false;">foo</a>
^^^^^^^^^^^^^
``` | `javascript:void null` should be `javascript:void(0)`, better still is `href="#"`. If MyFunction returns false the `return false` in scunliffe's answer shouldn't be necessary, using `onclick="return MyFunction()"` | Internet Explorer 6 aborts page request when javascript executes | [
"",
"javascript",
"html",
"internet-explorer-6",
""
] |
When I run player.php it's giving this error:
```
Warning: Cannot modify header information - headers already sent by (output started
at /www/110mb.com/m/u/s/i/c/k/i/n/musicking/htdocs/player.php:8) in
/www/110mb.com/m/u/s/i/c/k/i/n/musicking/htdocs/player.php on line 24
```
Can you please help?
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Player</title>
</head>
<body>
<?php
if(isset($_POST["song"])&& $_POST['song'] != "")
{
$song = $_POST["song"];
}
else {$song=array();}
for ($i="0"; $i<count($song); $i++) {
}
//start of new php codep
// create doctype
//$array = array(
// 'song.mp3','song.mp3','song.mp3',
//);
$dom = new DOMDocument("1.0");
// display document in browser as plain text
// for readability purposes
header("Content-Type: text/plain");
// create root element
$root = $dom->createElement("xml");
$dom->appendChild($root);
$i = "1";
foreach ($song as $counter) {
// create child element
$song = $dom->createElement("track");
$root->appendChild($song);
$song1 = $dom->createElement("path");
$song->appendChild($song1);
// create text node
$text = $dom->createTextNode($counter);
$song1->appendChild($text);
$song1 = $dom->createElement("title");
$song->appendChild($song1);
$text = $dom->createTextNode("song ".$i);
$song1->appendChild($text);
$i++;
}
// save and display tree
$dom->save("playlist.xml");
?>
<script type="text/javascript" src="swfobject.js">
</script>
<div id="flashPlayer">
This text will be replaced by the flash music player.
</div>
<script type="text/javascript">
var so = new SWFObject("playerMultipleList.swf", "mymovie", "295", "200", "7", "#FFFFFF");
so.addVariable("autoPlay","yes")
so.addVariable("playlistPath","playlist.xml")
so.write("flashPlayer");
</script>
</body>
</html>
``` | The error message is triggering because of the HTML that appears before your first `<?php` tag. You cannot output anything before `header()` is called. To fix this error start your document with the `<?php` tag and only start outputting HTML after you are done handling the condition that outputs XML for flash.
A cleaner solution would be to separate out the XML generation for flash and the HTML output into different files. | The error message means that the php script has already sent output to the browser before calling the header() function or anything else that requires modifying the http headers.
it is really hard to try and diagnose where the problem is occuring without see the script properly formatted, but this line:
```
header("Content-Type: text/plain");
```
should be at the start of the script in php tags. | Warning: Cannot modify header information - headers already sent by | [
"",
"php",
""
] |
```
function foldersize($path) {
$total_size = 0;
$files = scandir($path);
foreach($files as $t) {
if (is_dir(rtrim($path, '/') . '/' . $t)) {
if ($t<>"." && $t<>"..") {
$size = foldersize(rtrim($path, '/') . '/' . $t);
$total_size += $size;
}
} else {
$size = filesize(rtrim($path, '/') . '/' . $t);
$total_size += $size;
}
}
return $total_size;
}
function format_size($size) {
$mod = 1024;
$units = explode(' ','B KB MB GB TB PB');
for ($i = 0; $size > $mod; $i++) {
$size /= $mod;
}
return round($size, 2) . ' ' . $units[$i];
}
$SIZE_LIMIT = 5368709120; // 5 GB
$sql="select * from users order by id";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)) {
$disk_used = foldersize("C:/xampp/htdocs/freehosting/".$row['name']);
$disk_remaining = $SIZE_LIMIT - $disk_used;
print 'Name: ' . $row['name'] . '<br>';
print 'diskspace used: ' . format_size($disk_used) . '<br>';
print 'diskspace left: ' . format_size($disk_remaining) . '<br><hr>';
}
```
[php disk\_total\_space](https://stackoverflow.com/questions/466140/php-disktotalspace#466268)
Any idea why the processor usage shoot up too high or 100% till the script execution is finish ? Can anything be done to optimize it? or is there any other alternative way to check folder and folders inside it size? | The following are other solutions [offered elsewhere](http://forums.devshed.com/showpost.php?p=1527717&postcount=4):
If on a Windows Host:
```
<?
$f = 'f:/www/docs';
$obj = new COM ( 'scripting.filesystemobject' );
if ( is_object ( $obj ) )
{
$ref = $obj->getfolder ( $f );
echo 'Directory: ' . $f . ' => Size: ' . $ref->size;
$obj = null;
}
else
{
echo 'can not create object';
}
?>
```
Else, if on a Linux Host:
```
<?
$f = './path/directory';
$io = popen ( '/usr/bin/du -sk ' . $f, 'r' );
$size = fgets ( $io, 4096);
$size = substr ( $size, 0, strpos ( $size, "\t" ) );
pclose ( $io );
echo 'Directory: ' . $f . ' => Size: ' . $size;
?>
``` | ```
function GetDirectorySize($path){
$bytestotal = 0;
$path = realpath($path);
if($path!==false && $path!='' && file_exists($path)){
foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)) as $object){
$bytestotal += $object->getSize();
}
}
return $bytestotal;
}
```
The same idea as Janith Chinthana suggested.
With a few fixes:
* Converts `$path` to [realpath](http://www.php.net/manual/en/function.realpath.php)
* Performs iteration only if path is valid and folder exists
* Skips `.` and `..` files
* Optimized for performance | How to get directory size in PHP | [
"",
"php",
"filesystems",
""
] |
Talking about hibernate and others ORMs, the ORMs evangelists talk about SQL like the assembly language for Databases.
I think is soon to assert this, but I guess can be true on a near future, not sure.
**UPDATE:** The analogy I was referring means *SQL* is to *assembly* what *ORM* is to *C/Java/C#*. Of course, an exact analogy is not possible. The question is if in the future, with more powerful computers the developers are going to use only *ORM* (or ORM like) instead of *SQL*. | Absolutely not.
Assembly language is a very low level language where you instruct the processor exactly what to do, including what registers you want to use etc.
SQL is a very high level language where you describe the semantics of what you want, and then a query optimiser decides how to execute it, so you don't even control what gets executed. It's an extremely powerful and flexible language of which any ORM offers at most a (fairly small) subset.
You'll notice that the .NET framework has introduced LINQ recently which is a way to introduce high level SQL-like constructs into languages like C# and VB. Rather than being like assembler, it's pretty easy to argue that SQL works at a higher level of abstraction than most mainstream programming languages. | I have heard a lot of b\*s about impedence mismatch between relational and OO over hte years.
My answer has always been that there is indeed a very big impedence mismatch -- between the niave inflexable "everything is an object and only an object" and the wonderfully flexable and sophisticated "data describes real world things; this data can be combined in different as yet unknown ways to produce mathematicaly provable results".
OO is not the only fruit guys. | Is SQL the assembly for databases? | [
"",
"sql",
"assembly",
""
] |
We are a small team of developers planing to develop a php application. (let's say a CRM system)
Our main goal is to make it a plug-in-enabled application so that clients' developers can write plug-ins add new features to the system without changing the application's core code.
These changes may include:
1) adding new features: more likely adding a new page and creating a new database table and and implementing new operations such as add/edit/display data.
2) editing existing functionality (e.g. we have a list of users, they might need the user name to be a hyperlink and open a light box with user information)
Since this is going to a medium to large-scale application we need to plan it carefully.
At the moment our plan is to write the core application structure and implement the requirements as plug-ins, so that each time a client needs a change we only need to upgrade a specific plug-in.
I just need the gurus here to give us some ideas or links to look at before we start.
The final question is “how to build a plug-in-enabled PHP application?”
Thanks all... | please check the following url
<http://ellislab.com/forums/viewthread/67697/> | I would say try to use an OO framework (zend framework, cakephp, symphony) and create a configuration (xml based) to tell the loader which class should be loaded) that mean you can redifined class when you need to add a functionality to an existing feature or load new class.
Magento for instance use this approach to allow plugins.
But without more informations that's hard to tell. | Modular php application development | [
"",
"php",
"web-applications",
""
] |
What is the best way of converting a multi-dimensional javascript array to JSON? | Most of the popular JavaScript frameworks have JSON utility functions included. For instance, jQuery has a function that directly calls a url and loads the JSON result as an object : <http://docs.jquery.com/Getjson>
However, you can get an open-source JSON parser and stringifier from [the json website](http://www.json.org) :
<https://github.com/douglascrockford/JSON-js>
Then, simply include the code and use the JSON.stringify() method on your array. | The "best" way has been provided by the other posters. If you don't need the full encoding features of the referenced libraries, and only need to encode simple arrays, then try this:
```
<!DOCTYPE html>
<html>
<head>
<title>Simple functions for encoding Javascript arrays into JSON</title>
<script type="text/javascript">
window.onload = function() {
var a = [
[0, 1, '2', 3],
['0', '1', 2],
[],
['mf', 'cb']
],
b = [
0, '1', '2', 3, 'woohoo!'
];
alert(array2dToJson(a, 'a', '\n'));
alert(array1dToJson(b, 'b'));
};
function array2dToJson(a, p, nl) {
var i, j, s = '{"' + p + '":[';
nl = nl || '';
for (i = 0; i < a.length; ++i) {
s += nl + array1dToJson(a[i]);
if (i < a.length - 1) {
s += ',';
}
}
s += nl + ']}';
return s;
}
function array1dToJson(a, p) {
var i, s = '[';
for (i = 0; i < a.length; ++i) {
if (typeof a[i] == 'string') {
s += '"' + a[i] + '"';
}
else { // assume number type
s += a[i];
}
if (i < a.length - 1) {
s += ',';
}
}
s += ']';
if (p) {
return '{"' + p + '":' + s + '}';
}
return s;
}
</script>
</head>
<body>
</body>
</html>
``` | Convert a multidimensional javascript array to JSON? | [
"",
"javascript",
"arrays",
"json",
""
] |
I have a C++ method signature that looks like this:
```
static extern void ImageProcessing(
[MarshalAs(UnmanagedType.LPArray)]ushort[] inImage,
[MarshalAs(UnmanagedType.LPArray)]ushort[] outImage,
int inYSize, int inXSize);
```
I've wrapped the function in timing methods, both internal and external. Internally, the function is running at 0.24s. Externally, the function runs in 2.8s, or about 12 times slower. What's going on? Is marshalling slowing me down that much? If it is, how can I get around that? Should I go to unsafe code and use pointers or something? I'm sort of flummoxed as to where the extra time cost is coming from. | The answer is, sadly, far more mundane than these suggestions, although they do help. Basically, I messed up with how I was doing timing.
The timing code that I was using was this:
```
Ipp32s timer;
ippGetCpuFreqMhz(&timer);
Ipp64u globalStart = ippGetCpuClocks();
globalStart = ippGetCpuClocks() *2 - globalStart; //use this method to get rid of the overhead of getting clock ticks
//do some stuff
Ipp64u globalEnd = ippGetCpuClocks();
globalEnd = ippGetCpuClocks() *2 - globalEnd;
std::cout << "total runtime: " << ((Ipp64f)globalEnd - (Ipp64f)globalStart)/((Ipp64f)timer *1000000.0f) << " seconds" << std::endl;
```
This code is specific to the intel compiler, and is designed to give extremely precise time measurements. Unfortunately, that extreme precision means a cost of roughly 2.5 seconds per run. Removing the timing code removed that time constraint.
There still appears to be a delay of the runtime, though-- the code would report 0.24 s with that timing code on, and is now reporting timing of roughly 0.35s, which means that there's about a 50% speed cost.
Changing the code to this:
```
static extern void ImageProcessing(
IntPtr inImage, //[MarshalAs(UnmanagedType.LPArray)]ushort[] inImage,
IntPtr outImage, //[MarshalAs(UnmanagedType.LPArray)]ushort[] outImage,
int inYSize, int inXSize);
```
and called like:
```
unsafe {
fixed (ushort* inImagePtr = theInputImage.DataArray){
fixed (ushort* outImagePtr = theResult){
ImageProcessing((IntPtr)inImagePtr,//theInputImage.DataArray,
(IntPtr)outImagePtr,//theResult,
ysize,
xsize);
}
}
}
```
drops the executable time to 0.3 s (average of three runs). Still too slow for my tastes, but a 10x speed improvement is certainly within the realm of acceptability for my boss. | Take a look at [this article](http://community.opennetcf.com/articles/cf/archive/2008/01/31/performance-implications-of-crossing-the-p-invoke-boundary.aspx). While it's focus is on the Compact Framework, the general principles apply to the desktop as well. A relevant quote from the analysis section is as follows:
> The managed call doesn't directly call the native method. Instead it calls into a JITted stub method that must perform some overhead routines such as calls to determine GC Preemption status (to determine if a GC is pending and we need to wait). It is also possible that some marshalling code will get JITted into the stub as well. This all takes time.
**Edit**: Also worth a read is [this blog article on perf of JITted code](http://blog.opennetcf.com/ctacke/binary/JITtedCodeSpeed.htm) - again, CF specific, but still relevant. There is also [an article covering call stack depth and its impact on perf](http://blog.opennetcf.com/ctacke/2006/08/25/SpeedOfManagedCodeActII.aspx), though this one is probably CF-specific (not tested on the desktop). | .NET marshalling speed | [
"",
".net",
"c++",
"performance",
"pinvoke",
"marshalling",
""
] |
I have this code:
```
using DC = MV6DataContext;
using MV6; // Business Logic Layer
// ...
public DC.MV6DataContext dc = new DC.MV6DataContext(ConnectionString);
IP ip = new IP(Request.UserHostAddress);
dc.IPs.InsertOnSubmit(ip);
dc.SubmitChanges();
// in Business Logic layer:
public class IP : DC.IP {
public IP(string address) { ... }
}
```
Upon attempting to InsertOnSubmit(ip), I get a NullReferenceException (Object reference not set to an instance of an object). dc is not null; ip and all properties of ip are not null; though some are empty.
VS2008 won't let me step into InsertOnSubmit, so I have no way of knowing what specifically is null when being evaluated. What gives?
Note: I have checked, and all Linq.EntitySets created by FK relationships are present and non-null. | Got it.
Rather than creating a class that inherits from the DataContext's class, I extend the DC class itself with a partial class in the Business Logic layer. From there I can add whatever constructors and methods I wish.
In this case, it is neccessary to copy the code from the existing (auto-generated) constructor:
```
public IP(string address) {
Address = address;
Domain = "";
Notes = "";
FirstAccess = DateTime.Now;
LastAccess = DateTime.Now;
this._Sessions = new EntitySet<Session>(new Action<Session>(this.attach_Sessions), new Action<Session>(this.detach_Sessions));
OnCreated(); }
```
Not sure what's in that OnCreated handler, but it seems to be doing the work that boned me earlier. Works fine now :) | Actually it's better to add a call to your constructor that also calls the generic constructor such as:
```
public IP(string address) : this() {
...
}
``` | LINQ InsertOnSubmit: NullReferenceException | [
"",
"c#",
"asp.net",
"linq",
"linq-to-sql",
"nullreferenceexception",
""
] |
> **Possible Duplicate:**
> [When to choose checked and unchecked exceptions](https://stackoverflow.com/questions/27578/when-to-choose-checked-and-unchecked-exceptions)
When should I create a checked exception, and when should I make a runtime exception?
For example, suppose I created the following class:
```
public class Account {
private float balance;
/* ... constructor, getter, and other fields and methods */
public void transferTo(Account other, float amount) {
if (amount > balance)
throw new NotEnoughBalanceException();
/* ... */
}
}
```
How should I create my `NotEnoughBalanceException`? Should it extend `Exception` or `RuntimeException`? Or should I just use `IllegalArgumentException` instead? | There's a LOT of disagreement on this topic. At my last job, we ran into some real issues with Runtime exceptions being forgotten until they showed up in production (on agedwards.com), so we resolved to use checked exceptions exclusively.
At my current job, I find that there are many who are for Runtime exceptions in many or all cases.
Here's what I think: Using CheckedExceptions, I am forced at compile time to at least acknowledge the exception in the caller. With Runtime exceptions, I am not forced to by the compiler, but can write a unit test that makes me deal with it. Since I still believe that the earlier a bug is caught the cheaper it is to fix it, I prefer CheckedExceptions for this reason.
From a philosophical point of view, a method call is a contract to some degree between the caller and the called. Since the compiler enforces the types of parameters that are passed in, it seems symmetrical to let it enforce the types on the way out. That is, return values or exceptions.
My experience tells me that I get higher quality, that is, code that JUST WORKS, when I'm using checked exceptions. Checked exceptions may clutter code, but there are techniques to deal with this. I like to translate exceptions when passing a layer boundary. For example, if I'm passing up from my persistence layer, I would like to convert an SQL exception to a persistence exception, since the next layer up shouldn't care that I'm persisting to a SQL database, but will want to know if something could not be persisted. Another technique I use is to create a simple hierarchy of exceptions. This lets me write cleaner code one layer up, since I can catch the superclass, and only deal with the individual subclasses when it really matters. | In general, I think the advice by Joshua Bloch in *[Effective Java](https://rads.stackoverflow.com/amzn/click/com/0321356683)* best summarises the answer to your question: **Use checked expections for recoverable conditions and runtime exceptions for programming errors** (Item 58 in 2nd edition).
So in this case, if you really want to use exceptions, it should be a checked one. (Unless the documentation of `transferTo()` made it very clear that the method *must not* be called without checking for sufficient balance first by using some other `Account` method - but this would seem a bit awkward.)
But also note Items 59: *Avoid unnecessary use of checked exceptions* and 57: *Use exceptions only for exceptional conditions*. As others have pointed out, this case may not warrant an exception at all. Consider returning `false` (or perhaps a status object with details about what happened) if there is not enough credit. | In Java, when should I create a checked exception, and when should it be a runtime exception? | [
"",
"java",
"exception",
""
] |
Im trying to improve the Java Html Document a little but i'm running into problems with the `HttpUrlConntion`. One thing is that some servers block a request if the user agent is a Java VM. Another problem is that the `HttpUrlConnection` does not set the `Referrer` or `Location` header field. Since several sites use these fields to verify that the content was accessed from their own site, I'm blocked here as well. As far as I can see the only resolution is to replace the URL handler of the HTTP protocol. Or is there any way to modify the default HTTP Handler? | Open the `URL` with `URL.openConnection`. Optionally cast to `HttpURLConnection`. Call `URLConnection.setRequestProperty`/`addRequestProperty`.
The default User-Agent header value is set from the `"http.agent"` system property. The PlugIn and WebStart allow you to set this property. | If you use [Apache HttpClient](http://hc.apache.org/httpclient-3.x/) to manage your programmatic HTTP connectivity you get an extremely useful API which makes creating connections (and optional automatic re-connecting on fail), setting Headers, posts vs gets, handy methods for retrieving the returned content and much much more. | How to modify the header of a HttpUrlConnection | [
"",
"java",
"http",
"http-headers",
"httpurlconnection",
""
] |
I'm using Java HashMap in MATLAB
```
h = java.util.HashMap;
```
And while strings, arrays and matrices works seemlessly with it
```
h.put(5, 'test');
h.put(7, magic(4));
```
Structs do not
```
h=java.util.HashMap;
st.val = 7;
h.put(7, st);
??? No method 'put' with matching signature found for class 'java.util.HashMap'.
```
**What would be the easiest/most elegant way to make it work for structs?** | You need to ensure that the data passed from MATLAB to Java can be properly converted. See MATLAB's [External Interfaces document](http://www.mathworks.com/help/pdf_doc/matlab/apiext.pdf) for the conversion matrix of which types get converted to which other types.
MATLAB treats most data as pass-by-value (with the exception of classes with handle semantics), and there doesn't appear to be a way to wrap a structure in a Java interface. But you could use another HashMap to act like a structure, and convert MATLAB structures to HashMaps (with an obvious warning for multiple-level structures, function handles, + other beasts that don't play well with the MATLAB/Java data conversion process).
```
function hmap = struct2hashmap(S)
if ((~isstruct(S)) || (numel(S) ~= 1))
error('struct2hashmap:invalid','%s',...
'struct2hashmap only accepts single structures');
end
hmap = java.util.HashMap;
for fn = fieldnames(S)'
% fn iterates through the field names of S
% fn is a 1x1 cell array
fn = fn{1};
hmap.put(fn,getfield(S,fn));
end
```
a possible use case:
```
>> M = java.util.HashMap;
>> M.put(1,'a');
>> M.put(2,33);
>> s = struct('a',37,'b',4,'c','bingo')
s =
a: 37
b: 4
c: 'bingo'
>> M.put(3,struct2hashmap(s));
>> M
M =
{3.0={a=37.0, c=bingo, b=4.0}, 1.0=a, 2.0=33.0}
>>
```
(an exercise for the reader: change this to work recursively for structure members which themselves are structures) | Matlab R2008b and newer have a containers.Map class that provides HashMap-like functionality on native Matlab datatypes, so they'll work with structs, cells, user-defined Matlab objects, and so on.
```
% Must initialize with a dummy value to allow numeric keys
m = containers.Map(0, 0, 'uniformValues',false);
% Remove dummy entry
m.remove(0);
m(5) = 'test';
m(7) = magic(4);
m(9) = struct('foo',42, 'bar',1:3);
m(5), m(7), m(9) % get values back out
``` | Storing MATLAB structs in Java objects | [
"",
"java",
"matlab",
"hashmap",
""
] |
I'm working on a site where I'd like to cycle images, similar to a slideshow, while the user is on the page. I've searched around and haven't been able to find a lead.
Has anyone done this with Rails and the Javascript frameworks it supports? | you could possible use the jquery cycle plugin, here's the link: <http://malsup.com/jquery/cycle/> . It looks like it would do what you want. | FYI, Rails isn't particularly tied to any JS framework, even though it comes with prototype out of the box.
I assume that when you say AJAX, you don't mean AJAX. If you were to rotate the image using AJAX, you would have the rotated image being generated server side and sent to the client, as AJAX = performing requests with javascript. </pedantic>
With that said, you can use pretty much any JS image rotator you can find [on google](http://www.google.com/search?q=javascript+rotate+image).
EDIT: Oh, you meant cycling through images, not rotating it e.g. 90º clockwise etc. (?) | Rotating images, AJAX-like, in Ruby on Rails | [
"",
"javascript",
"ruby-on-rails",
"ajax",
""
] |
I'm interested in building a Texas Hold 'Em AI engine in Java. This is a long term project, one in which I plan to invest at least two years. I'm still at college, haven't build anything ambitious yet and wanting to tackle a problem that will hold my interest in the long term. I'm new to the field of AI. From my data structures class at college, I know basic building blocks like BFS and DFS, backtracking, DP, trees, graphs, etc. I'm learning regex, studying for the SCJP and the SCJD and I'll shortly take a (dense) statistics course.
Questions:
-Where do I get started? What books should I pick? What kind of AI do poker playing programs run on? What open source project can I take a page from? Any good AI resources in Java? I'm interested in learning Lisp as well, is Jatha good? | The following may prove useful:
* [The University of Alberta Computer Poker Research Group](http://poker.cs.ualberta.ca/)
* [OpenHoldem](http://code.google.com/p/openholdembot/)
* [Poker Hand Recognition, Comparison, Enumeration, and Evaluation](http://www.codingthewheel.com/archives/how-i-built-a-working-online-poker-bot-8)
* [The Theory of Poker](https://rads.stackoverflow.com/amzn/click/com/1880685000)
* [The Mathematics of Poker](https://rads.stackoverflow.com/amzn/click/com/1886070253)
* [SpecialKPokerEval](http://code.google.com/p/specialkpokereval/) | Poker AI's are notoriously difficult to get right because humans bet unpredictably. It's usually broken into two parts.
1) Calculate the odds of your hand being the winner.
2) Formulate betting strategy based on 1.
I'd recommend starting with lots of statistics reading for part 1. It seems easy at first blush, but it's actually very complicated (and getting it wrong will doom your AI). Then move on to genetic algorithms for part 2. Betting strategies are mostly genetic algorithms. They adjust themselves based on past success and failures + some randomization so as not to become predictable. | Building a Texas Hold'em playing AI..from scratch | [
"",
"java",
"lisp",
"artificial-intelligence",
"poker",
"jatha",
""
] |
I'm trying to learn TDD by applying it to a simple project of mine. Some details (and an earlier question) are here:
[TDD: Help with writing Testable Class](https://stackoverflow.com/questions/473679/tdd-help-with-writing-testable-class)
The specifics are I have a PurchaseOrderCollection class that has a private List of PurchaseOrders (passed in at constructor), and the PurchaseOrders have a boolean property IsValid. The PurchaseOrderCollection has a property HasErrors that returns a true if any PurchaseOrders in the list have IsValid as false. This is the logic I want to test.
```
[TestMethod]
public void Purchase_Order_Collection_Has_Errors_Is_True_If_Any_Purchase_Order_Has_Is_Valid_False()
{
List<PurchaseOrder> orders = new List<PurchaseOrder>();
orders.Add(new PurchaseOrder(--some values to generate IsValid false--));
orders.Add(new PurchaseOrder(--some values to generate IsValid true--));
PurchaseOrderCollection collection = new PurchaseOrderCollection(orders);
Assert.IsTrue(collection.HasErrors);
}
```
This is similar to my previous question in that this test is too coupled in that I have to know the logic of what makes a PurchaseOrder IsValid false or true to pass the test, when really this test shouldn't care. The question is different (imo) in that the classes themselves aren't the problem.
Essentially I want to be able to declare a PurchaseOrder that has IsValid false or true without knowing anything more about what a PurchaseOrder is.
From my limited TDD knowledge, this is something you use Stubs or Mocks for. My main question, is this correct? Or should I be using a different method for this? Or am I completely flawed and am just writing this test and thinking about it wrong?
My initial thought was to just use some kind of mock framework and create a PurchaseOrder that always returns true or false. From what I've read though, I'd need to declare IsValid virtual. So my second thought was to change it to add IPurchaseOrder as an interface for PurchaseOrder and just create a fake PurchaseOrder that always returns false or true. Are both of these valid ideas?
Thanks! | You are on the right track with either creating a stub or a mock. I prefer using a Mocking framework.
How it would work using a mocking framework is that you would want to mock your PurchaseOrder class therefore abstracting away it's implementation. Then setup expectations that IsValid is called and when it is called return this value.
Example using [Moq](http://code.google.com/p/moq/), if you're using C# 3.0 and .NET Framework 3.5:
```
[TestMethod]
public void Purchase_Order_Collection_Has_Errors_Is_True_If_Any_Purchase_Order_Has_Is_Valid_False()
{
var mockFirstPurchaseOrder = new Mock<IPurchaseOrder>();
var mockSecondPurchaseOrder = new Mock<IPurchaseOrder>();
mockFirstPurchaseOrder.Expect(p => p.IsValid).Returns(false).AtMostOnce();
mockSecondPurchaseOrder.Expect(p => p.IsValid).Returns(true).AtMostOnce();
List<IPurchaseOrder> purchaseOrders = new List<IPurchaseOrder>();
purchaseOrders.Add(mockFirstPurchaseOrder.Object);
purchaseOrders.Add(mockSecondPurchaseOrder.Object);
PurchaseOrderCollection collection = new PurchaseOrderCollection(orders);
Assert.IsTrue(collection.HasErrors);
}
```
Edit:
Here I used an interface to create the mock of PurchaseOrder, but you don't have too. You could mark IsValid as virtual and mock the PurchaseOrder class. My rule of thumb when which way to go is to use virtual first. Just to create an interface, so I can mock an object without any architectual reason is a code smell to me. | > ...this test is too coupled in that I
> have to know the logic of what makes a
> PurchaseOrder IsValid false or true to
> pass the test, when really this test
> shouldn't care...
I'd actually argue the reverse -- that for your test to know that validity is modeled as a boolean within the purchase order means that your test knows too much about the implementation of PurchaseOrder (given that it's actually a test of PurchaseOrderCollection). I don't have a problem with using real-world knowledge (i.e. actual values that would be valid or invalid) to create appropriate test objects. Ultimately, that's really what you're testing (if I give my collection a purchase order with ridiculous values, will it correctly tell me there are errors).
In general I try to avoid writing an interface for an "entity" object such as a PurchaseOrder unless there's some reason to do so other than for testing (e.g. there are multiple kinds of PurchaseOrders in production and an interface is the best way to model that).
It's great when testing reveals that your production code could be better designed. It's not so good, though, to change your production code *just* to make a test possible.
As if I haven't written enough, here's another suggestion -- and this is the way I would actually solve this in real life.
Create a PurchaseOrderValidityChecker that has an interface. Use that when setting the isValid boolean. Now create a test version of the validity checker that lets you specify which answer to give. (Note that this solution probably also requires a PurchaseOrderFactory or the equivalent for creating PurchaseOrders, so that each purchase order can be given a reference to the PurchaseOrderValidityChecker when it is created.) | TDD: Stub, Mock, or None of the Above | [
"",
"c#",
"tdd",
"mocking",
"stub",
""
] |
I have a select control, and in a javascript variable I have a text string.
Using jQuery I want to set the selected element of the select control to be the item with the text description I have (as opposed to the value, which I don't have).
I know setting it by value is pretty trivial. e.g.
```
$("#my-select").val(myVal);
```
But I'm a bit stumped on doing it via the text description. I guess there must be a way of getting the value out from the text description, but my brain is too Friday afternoon-ed to be able to work it out. | ## Select by description for jQuery v1.6+
```
var text1 = 'Two';
$("select option").filter(function() {
//may want to use $.trim in here
return $(this).text() == text1;
}).prop('selected', true);
```
```
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option value="0">One</option>
<option value="1">Two</option>
</select>
```
## [jQuery versions below 1.6 and greater than or equal to 1.4](https://stackoverflow.com/a/3644500/31532)
```
var text1 = 'Two';
$("select option").filter(function() {
//may want to use $.trim in here
return $(this).text() == text1;
}).attr('selected', true);
```
```
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<select>
<option value="0">One</option>
<option value="1">Two</option>
</select>
```
Note that while this approach will work in versions that are above 1.6 but less than 1.9, it has been deprecated since 1.6. It *[will not work](https://stackoverflow.com/questions/14366220/optionselected-not-working-jquery-1-9)* in jQuery 1.9+.
---
## Previous versions
`val()` should handle both cases.
```
$('select').val('1'); // selects "Two"
$('select').val('Two'); // also selects "Two"
```
```
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<select>
<option value="0">One</option>
<option value="1">Two</option>
</select>
``` | I haven't tested this, but this might work for you.
```
$("select#my-select option")
.each(function() { this.selected = (this.text == myVal); });
``` | jQuery - setting the selected value of a select control via its text description | [
"",
"javascript",
"jquery",
""
] |
I have an winform application that creates 5 threads to connect to and retrieve information from a database on a very slow connection (90 seconds for some queries).Each thread has it's own instance of a class for performing sql queries. When the queried data has been retrieved the main thread is notified by an event fired from the class running the query. After receiving the event various components of the main thread are updated such as display items or just a datatable holding data for later use. The queries are repeated at various intervals depending on the type of information that they are querying.
Everything works great...but I am not happy. I feel that it should be done a different way, but I am not sure which way.
Below is how I currently set up each thread:
```
string ConnectionString = @"Data Source=mySrv;Initial Catalog=myTbl;Connect Timeout=30;UID=sa;pwd=mypwd";
//thread #1
SQL_Requests ReasonRequests;
Thread Reason_Thread;
ReasonRequests = new SQL_Requests();
ReasonRequests.ProcessFinished += new SQL_Requests.ProcessFinished(ReasonRequests_Completed);
Reason_Thread = new Thread(ReasonRequests.ExecuteQuery);
ReasonRequests.DBQueryString = "select * from ReasonTable where staralingment = goodalignment"
ReasonRequests.DBConnection = ConnectionString;
//thread #2
SQL_Requests EventRequests;
Thread Event_Thread;
EventRequests = new SQL_Requests();
EventRequests.ProcessFinished += new SQL_Requests.ProcessFinished(EventRequests_Completed);
Event_Thread= new Thread(EventRequests.ExecuteQuery);
EventRequests.DBQueryString = "select * from EventTable where somefield = somevalue"
EventRequests.DBConnection = ConnectionString;
```
each Thread.start are at different intervals.
any recommendations? | Instead of spinning up your own threads you should take a look as the asynchronous methods for executing queries i.e. <http://msdn.microsoft.com/en-ca/library/system.data.sqlclient.sqlcommand.beginexecutereader.aspx>
You mentioned that your connection is slow, is it a low bandwidth connection or a high latency connection? If the data is being returned slowly because of insufficient bandwidth firing off multiple queries will just make things slower. If it is just a latency issue doing multiple queries at once may improve responsiveness.
If you are performing a group of related queries you may also want to consider grouping them into a single command, or grouping them on the server by using a stored procedure. You can get additional result sets by using the NextResult method on the SqlDataReader. | If your threads fetch data from the same server over a very slow connection (meaning that limited bandwidth is the main factor) you will not gain anything by using multiple threads.
OTOH it could actually be better to use a single thread for all data fetch operations:
* You will get a portion of the data after some time, so you can update the UI with that. Fetching in parallel would probably split the bandwidth, and you would get a long time without any data, and in the end the results would arrive shortly after another. Your UI would look less responsive that way.
* If the selects cause a lot of I/O on the server, not having them execute in parallel could actually result in better throughput. Consider that other operations will be executed on the server too.
IMHO you should keep the fetches in a thread for best responsiveness of the UI, but use only one.
**Edit:** You state in the comment that fetches may take different amounts of time. If you can estimate which queries will be the fastest to complete the transfer, execute them first. Still assuming of course that the data transfer takes most of the time, not the query execution on the server.
If you can't estimate how long queries will take, or if bandwidth isn't the only limitation, using multiple threads may of course work best for you. | c# am I handling multiple threads properly | [
"",
"c#",
"multithreading",
""
] |
Both operations create an empty file and return the filename but mkstemp leaves the file open in exclusive mode and gives you the handle. Is there a safety benefit to the C-function? Does this imply that there is a safety hole in the command-line version?
As an aside, it is interesting that there are several related functions in the C api on Linux and most of them say "Don't use this function" (or similar) in their man page. | As you can easily see from `mktemp(1)` source code, it essentially does nothing but calling `mkstemp(3)`.
Exclusive mode in Linux means that function will fail if the file already exists, it does not guarantee locking. Other process can delete this file, create it again and fill it with data, despite the file handle being `open(3)` by your process.
There is no additional safety in C function compared to command line utility. | One trick with temporary files in Unix-like operating systems (including Linux and Mac OS) is as soon as you open the file, delete it. You can still access the file, but nobody else can see it or do anything to it, and it will go away as soon as you close the file, even if your program dies a horrible death. | On Linux, is the command-line program mktemp less safe than the C-function mkstemp? | [
"",
"c++",
"c",
"linux",
"temporary-files",
""
] |
I'm curious to see if you can overload controller methods in ASP.NET MVC. Whenever I try, I get the error below. The two methods accept different arguments. Is this something that cannot be done?
> The current request for action 'MyMethod' on controller type 'MyController' is ambiguous between the following action methods: | You can use the attribute if you want your code to do overloading.
```
[ActionName("MyOverloadedName")]
```
But, you'll have to use a different action name for the same http method (as others have said). So it's just semantics at that point. Would you rather have the name in your code or your attribute?
Phil has an article related to this: <http://haacked.com/archive/2008/08/29/how-a-method-becomes-an-action.aspx> | Yes. I've been able to do this by setting the `HttpGet`/`HttpPost` (or equivalent `AcceptVerbs` attribute) for each controller method to something distinct, i.e., `HttpGet` or `HttpPost`, but not both. That way it can tell based on the type of request which method to use.
```
[HttpGet]
public ActionResult Show()
{
...
}
[HttpPost]
public ActionResult Show( string userName )
{
...
}
```
One suggestion I have is that, for a case like this, would be to have a private implementation that both of your public Action methods rely on to avoid duplicating code. | Can you overload controller methods in ASP.NET MVC? | [
"",
"c#",
"asp.net",
"asp.net-mvc",
"overloading",
""
] |
I tried to install beautifulsoup. I get such an error:
<-- snip -->
```
raise MissingSectionHeaderError(fpname, lineno, line)
ConfigParser.MissingSectionHeaderError: File contains no section headers.
file: /Users/Sam/.pydistutils.cfg, line: 1
'install_lib = ~/Library/Python/$py_version_short/site-packages\n'
```
I get an similar error as I run my Python code in vim by:
:!python % | You can test if a module is installed like so:
```
$ python
>>> import modulename
``` | I'd try the following:
1. Open Python shell
2. Type `import <moduleName>`
3. Parse the results (no error, ImportError or some module loading error)
4. Try to invoke any function from imported module (to see if module is correctly initialized).
Do you need something more sophisticated? | How can I test that I have a Python module successfully installed? | [
"",
"python",
"installation",
"module",
""
] |
Given the following interfaces:
```
interface IFoo
{
void Foo();
}
interface IBar : IFoo
{
void Bar();
}
```
what is the best way to indicate that a given class implements `IBar`?
### Approach A:
```
class Implementation : IBar { ... }
```
This seems simpler and cleaner but it does not indicate that `Implementation` implements `IFoo`.
### Approach B:
```
class Implementation : IBar, IFoo { ... }
```
This seem the most informative but is the extra information really necessary? | Personally I'd go with the former. With the latter, say you're in this situation where you have a bunch of derived classes:
```
class DerivedA : Implementation, IBar, IFoo { ... }
class DerivedB : Implementation, IBar, IFoo { ... }
class DerivedC : Implementation, IBar, IFoo { ... }
class DerivedD : Implementation, IBar, IFoo { ... }
```
And then your requirements for `Implementation` change so that it now needs to implement another interface such as `IBaz` (which it can do without having to affect any of the derived classes as long as it provides a non-abstract implementation) then you have two options:
1. Leave all the derived class definitions without an explicit declaration of the new interface information, in which case the class definition is now incorrect according to the standard, and potentially misleading if people expect the standard to always be followed.
2. Go and find all derived classes, and all their derived classes, and fix up the declarations on them. This takes time, is somewhat error prone and hard to do completely, and turns your single file change into a multi-file check-in.
Neither of these options is attractive, so I'd go with the option that doesn't put you in either situation. Just declare the most derived interface. | The extra information isn't necessary to the compiler, but it may be helpful to the reader of your code as the reader won't have to know that `IBar` extends `IFoo`. An example of this in the framework would be `List<T>` which implements `<IList<T>`, `ICollection<T>`, and `IEnumerable<T>`, even though `IList<T>`; extends both `ICollection<T>` and `IEnumerable<T>`.
**EDIT**: I think, for me at least, the primary reason that I would list both is that you ordinarily don't think of interfaces inheriting from one another. When you derive from a class, you expect that you are inheriting behavior that may itself be inherited. If you are interested, you follow the derivation up the class hierarchy. With an interface it's more unusual that the interface would be derived and thus you'd be less likely to look and more likely to miss the connection. Listing them both solves this problem without too much pain. | What is the best way to show inherited interface implementation in C#? | [
"",
"c#",
"interface",
""
] |
I know of `@staticmethod`, `@classmethod`, and `@property`, but only through scattered documentation. What are all the function decorators that are built into Python? Is that in the docs? Is there an up-to-date list maintained somewhere? | I don't think so. Decorators don't differ from ordinary functions, you only call them in a fancier way.
For finding all of them try searching [Built-in functions](http://docs.python.org/library/functions.html) list, because as you can see in [Python glossary](http://docs.python.org/3.0/glossary.html) the decorator syntax is just a syntactic sugar, as the following two definitions create equal functions (copied this example from glossary):
```
def f(...):
...
f = staticmethod(f)
@staticmethod
def f(...):
```
So any built-in function that returns another function can be used as a decorator. Question is - does it make sense to use it that way? :-)
[functools](http://docs.python.org/library/functools.html) module contains some functions that can be used as decorators, but they aren't built-ins you asked for. | They're not built-in, but [this library](http://wiki.python.org/moin/PythonDecoratorLibrary) of example decorators is very good.
As Abgan [says](https://stackoverflow.com/questions/480178/python-is-there-a-list-of-decorators-somewhere#480266), the built-in function list is probably the best place to look. Although, since decorators can also be implemented as classes, it's not guaranteed to be comprehensive. | Python - what are all the built-in decorators? | [
"",
"python",
"decorator",
""
] |
* Are primitives worth keeping?
* Should all the deprecated stuff be deleted?
* Do we need 2 GUI frameworks?
* ... | As I have [already mentioned](https://stackoverflow.com/questions/314540), even in its [How and When To Deprecate APIs](http://java.sun.com/javase/6/docs/technotes/guides/javadoc/deprecation/deprecation.html), nothing is being said about a policy regarding actually *removing* the deprecated APIs...
The number of applications based on older JVM (1.4 for instance) is still important, in part due to **application servers** which take a long time to validate themselves with new versions of JVM...
The sheer number of applications which are actually running in production means this “backward compatibility” policy may not be broken anytime soon. | There are several types of backwards compatibility:
1. Can old source code compile with the new compiler?
This can be handled with tools that convert old constructs to new ones, or with something like a "source 1.6;" directive at the top of the file.
2. Can old class files run in a new JVM?
In my world this is a complete show-stopper. We use so many third-party libraries that forcing a simultaneous upgrade of all of them would be too costly.
This is also the driver for not removing deprecated classes and methods, but to a lesser extent.
3. Can old class files call code compiled with the new compiler?
This is an important part of #2, because of callbacks.
4. Can newly compiled code call code from old class files?
Another important part of #2.
5. Does the code look substantially similar to developers?
This is important for training, and for working large codebases that have not completely converted. A subtler aspect is how much of the new feature can be used in a mixed codebase. If you break this too far, you've got something like Scala instead of Java++.
Generics were added in such a was as to preserve *all* of these types of compatibility. I think that any incompatible change to Java has to preserve at least 2, 3 and 4 to have any chance of acceptance as *Java*. Tools to handle #1 are also a minimum requirement. | Should Java break backwards compatibility in future versions for the benefit of a cleaner language? | [
"",
"java",
"language-features",
""
] |
I have a carbon C++ application and I would like to programmatically do the equivalent of Command-H (to hide the application) which is available in the Application menu for my app. I have explored the carbon API for TransitionWindow and HideWindow and while these can hide my window, they do not do the equivalent of Command-H. I looked into the AppleEvent reference on the offhand I needed to create an AppleEvent but I didn't see one for hide application. Any thoughts? | Sorry to answer my own question but the ShowHideProcess() API seems to do what I want. If there are better solutions I would love to hear them. | Just a note: hiding a Window is very different to hiding an Application. | Is there a way to programmatically hide an carbon application on osx? | [
"",
"c++",
"macos",
"macos-carbon",
""
] |
I'm trying to connect to an API that uses a self-signed SSL certificate. I'm doing so using .NET's HttpWebRequest and HttpWebResponse objects. And I'm getting an exception that:
> The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
I understand what this means. And I understand *why* .NET feels it should warn me and close the connection. But in this case, I'd like to just connect to the API anyway, man-in-the-middle attacks be damned.
So, how do I go about adding an exception for this self-signed certificate? Or is the approach to tell HttpWebRequest/Response not to validate the certificate at all? How would I do that? | @Domster: that works, but you might want to enforce a bit of security by checking if the certificate hash matches what you expect. So an expanded version looks a bit like this (based on some live code we're using):
```
static readonly byte[] apiCertHash = { 0xZZ, 0xYY, ....};
/// <summary>
/// Somewhere in your application's startup/init sequence...
/// </summary>
void InitPhase()
{
// Override automatic validation of SSL server certificates.
ServicePointManager.ServerCertificateValidationCallback =
ValidateServerCertficate;
}
/// <summary>
/// Validates the SSL server certificate.
/// </summary>
/// <param name="sender">An object that contains state information for this
/// validation.</param>
/// <param name="cert">The certificate used to authenticate the remote party.</param>
/// <param name="chain">The chain of certificate authorities associated with the
/// remote certificate.</param>
/// <param name="sslPolicyErrors">One or more errors associated with the remote
/// certificate.</param>
/// <returns>Returns a boolean value that determines whether the specified
/// certificate is accepted for authentication; true to accept or false to
/// reject.</returns>
private static bool ValidateServerCertficate(
object sender,
X509Certificate cert,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
{
// Good certificate.
return true;
}
log.DebugFormat("SSL certificate error: {0}", sslPolicyErrors);
bool certMatch = false; // Assume failure
byte[] certHash = cert.GetCertHash();
if (certHash.Length == apiCertHash.Length)
{
certMatch = true; // Now assume success.
for (int idx = 0; idx < certHash.Length; idx++)
{
if (certHash[idx] != apiCertHash[idx])
{
certMatch = false; // No match
break;
}
}
}
// Return true => allow unauthenticated server,
// false => disallow unauthenticated server.
return certMatch;
}
``` | Turns out, if you just want to disable certificate validation altogether, you can change the ServerCertificateValidationCallback on the ServicePointManager, like so:
```
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
```
This will validate all certificates (including invalid, expired or self-signed ones). | Using a self-signed certificate with .NET's HttpWebRequest/Response | [
"",
"c#",
"ssl",
"httpwebrequest",
"ssl-certificate",
""
] |
When programming interfaces, I've found I'm doing a lot of casting or object type conversion.
Is there a difference between these two methods of conversion? If so, is there a cost difference or how does this affect my program?
```
public interface IMyInterface
{
void AMethod();
}
public class MyClass : IMyInterface
{
public void AMethod()
{
//Do work
}
// Other helper methods....
}
public class Implementation
{
IMyInterface _MyObj;
MyClass _myCls1;
MyClass _myCls2;
public Implementation()
{
_MyObj = new MyClass();
// What is the difference here:
_myCls1 = (MyClass)_MyObj;
_myCls2 = (_MyObj as MyClass);
}
}
```
Also, what is "in general" the preferred method? | The answer below the line was written in 2008.
C# 7 introduced pattern matching, which has largely replaced the `as` operator, as you can now write:
```
if (randomObject is TargetType tt)
{
// Use tt here
}
```
Note that `tt` is still in scope after this, but not definitely assigned. (It *is* definitely assigned within the `if` body.) That's slightly annoying in some cases, so if you really care about introducing the smallest number of variables possible in every scope, you might still want to use `is` followed by a cast.
---
I don't think any of the answers so far (at the time of starting this answer!) have really explained where it's worth using which.
* Don't do this:
```
// Bad code - checks type twice for no reason
if (randomObject is TargetType)
{
TargetType foo = (TargetType) randomObject;
// Do something with foo
}
```
Not only is this checking twice, but it may be checking different things, if `randomObject` is a field rather than a local variable. It's possible for the "if" to pass but then the cast to fail, if another thread changes the value of `randomObject` between the two.
* If `randomObject` really *should* be an instance of `TargetType`, i.e. if it's not, that means there's a bug, then casting is the right solution. That throws an exception immediately, which means that no more work is done under incorrect assumptions, and the exception correctly shows the type of bug.
```
// This will throw an exception if randomObject is non-null and
// refers to an object of an incompatible type. The cast is
// the best code if that's the behaviour you want.
TargetType convertedRandomObject = (TargetType) randomObject;
```
* If `randomObject` *might* be an instance of `TargetType` and `TargetType` is a reference type, then use code like this:
```
TargetType convertedRandomObject = randomObject as TargetType;
if (convertedRandomObject != null)
{
// Do stuff with convertedRandomObject
}
```
* If `randomObject` *might* be an instance of `TargetType` and `TargetType` is a value type, then we can't use `as` with `TargetType` itself, but we can use a nullable type:
```
TargetType? convertedRandomObject = randomObject as TargetType?;
if (convertedRandomObject != null)
{
// Do stuff with convertedRandomObject.Value
}
```
(Note: currently this is [actually slower than is + cast](https://stackoverflow.com/questions/1583050/performance-surprise-with-as-and-nullable-types). I think it's more elegant and consistent, but there we go.)
* If you really don't need the converted value, but you just need to know whether it *is* an instance of TargetType, then the `is` operator is your friend. In this case it doesn't matter whether TargetType is a reference type or a value type.
* There may be other cases involving generics where `is` is useful (because you may not know whether T is a reference type or not, so you can't use as) but they're relatively obscure.
* I've almost certainly used `is` for the value type case before now, not having thought of using a nullable type and `as` together :)
---
EDIT: Note that none of the above talks about performance, other than the value type case, where I've noted that unboxing to a nullable value type is actually slower - but consistent.
As per naasking's answer, is-and-cast or is-and-as are both as fast as as-and-null-check with modern JITs, as shown by the code below:
```
using System;
using System.Diagnostics;
using System.Linq;
class Test
{
const int Size = 30000000;
static void Main()
{
object[] values = new object[Size];
for (int i = 0; i < Size - 2; i += 3)
{
values[i] = null;
values[i + 1] = "x";
values[i + 2] = new object();
}
FindLengthWithIsAndCast(values);
FindLengthWithIsAndAs(values);
FindLengthWithAsAndNullCheck(values);
}
static void FindLengthWithIsAndCast(object[] values)
{
Stopwatch sw = Stopwatch.StartNew();
int len = 0;
foreach (object o in values)
{
if (o is string)
{
string a = (string) o;
len += a.Length;
}
}
sw.Stop();
Console.WriteLine("Is and Cast: {0} : {1}", len,
(long)sw.ElapsedMilliseconds);
}
static void FindLengthWithIsAndAs(object[] values)
{
Stopwatch sw = Stopwatch.StartNew();
int len = 0;
foreach (object o in values)
{
if (o is string)
{
string a = o as string;
len += a.Length;
}
}
sw.Stop();
Console.WriteLine("Is and As: {0} : {1}", len,
(long)sw.ElapsedMilliseconds);
}
static void FindLengthWithAsAndNullCheck(object[] values)
{
Stopwatch sw = Stopwatch.StartNew();
int len = 0;
foreach (object o in values)
{
string a = o as string;
if (a != null)
{
len += a.Length;
}
}
sw.Stop();
Console.WriteLine("As and null check: {0} : {1}", len,
(long)sw.ElapsedMilliseconds);
}
}
```
On my laptop, these all execute in about 60ms. Two things to note:
* There's no significant difference between them. (In fact, there are situations in which the as-plus-null-check definitely *is* slower. The above code actually makes the type check easy because it's for a sealed class; if you're checking for an interface, the balance tips slightly in favour of as-plus-null-check.)
* They're all *insanely* fast. This simply *will not* be the bottleneck in your code unless you really aren't going to do *anything* with the values afterwards.
So let's not worry about the performance. Let's worry about correctness and consistency.
I maintain that is-and-cast (or is-and-as) are both unsafe when dealing with variables, as the type of the value it refers to may change due to another thread between the test and the cast. That would be a pretty rare situation - but I'd rather have a convention which I can use consistently.
I also maintain that the as-then-null-check gives a better separation of concerns. We have one statement which attempts a conversion, and then one statement which uses the result. The is-and-cast or is-and-as performs a test and *then* another attempt to convert the value.
To put it another way, would anyone *ever* write:
```
int value;
if (int.TryParse(text, out value))
{
value = int.Parse(text);
// Use value
}
```
That's sort of what is-and-cast is doing - although obviously in a rather cheaper way. | **"as"** will return NULL if not possible to cast.
**casting before** will raise an exception.
For the performance, raising an exception is usually more costly in time. | Casting vs using the 'as' keyword in the CLR | [
"",
"c#",
"casting",
"clr",
""
] |
I have a class which represents a shape. The Shape class has a property called Angle. I want the setter for this property to automatically wrap the value into the range [0,359].
Unfortunately, a simple `_Angle = value % 360;` only works for positive numbers. In C#, `-40 % 360 == -40`. Google calc does it [the way I want it](http://www.google.com/search?q=-40+mod+360). The value should be 320.
What's the most elegant solution in C#?
Here's the best way I've got so far:
```
public double Angle {
get { return _Angle; }
set {
if ( value >= 0 ) {
_Angle = value % 360;
}
else {
_Angle = value - (360 * ((int)(value / 360) - 1));
}
}
}
```
**Edit:**
Thanks guys, I now have:
```
public double Angle {
get { return _Angle; }
set {
_Angle = (value % 360) + ((value < 0) ? 360 : 0);
}
}
```
..Which is a lot better :) | Although this is for Java, Java also has the same behavior for modulus. (i.e. `-40 % 360 == -40`).
The below code should return an answer from [0. 360), regardless of the given angle, positive or negative.
```
public class Mod
{
public static int mod(int a, int b)
{
if (a < 0)
return b + (a % b);
else
return a % b;
}
public static void main(String[] args)
{
System.out.println(mod(40, 360)); // 40
System.out.println(mod(-40, 360)); // 320
System.out.println(mod(-400, 360)); // 320
}
}
```
Note that works when the given angle is past -360. | While your solution works for the problem you have the algorithm is actually not identical to the one used by Google. It differs if you use a negative divisor.
```
public double GoogleModulo(double value, double divisor)
{
long q = (long)Math.Floor(value / divisor);
return value - q * divisor;
}
Console.WriteLine(GoogleModulo( 40, 360)); // 40
Console.WriteLine(GoogleModulo( -40, 360)); // 320
Console.WriteLine(GoogleModulo(-400, 360)); // 320
Console.WriteLine(GoogleModulo( 40, -360)); // -320
```
Check google's response to the last calculation [here](http://www.google.com/search?q=40+mod+-360).
The algorithm is explained on [wikipedia](http://en.wikipedia.org/wiki/Modulo_operation) and attributed to Donald Knuth. | In C#, how do I implement modulus like google calc does? | [
"",
"c#",
"modulo",
""
] |
I've never really had the need to use any drag functions until now, so let me fill you in on what I've discovered so far:
* Drag events are events that take place when the user is dragging an object. This is "proper" OS dragging, eg: hiliting some text and dragging it, or even dragging in something from outside of the browser.
* While dragging, as far as I can tell, no other browser events will be fired. (onmouseover is ignored, for example). The only events that work are drag events.
* In all modern browsers, onDragEnter and onDragOver appear to work... but firefox lacks "onDragLeave."
* For dropping, FF uses "onDragDrop" while IE and others use "onDrop" while Safari doesn't appear to support it.
* Events only seem to work on "droppable" elements, like textarea and text. On other elements only *some* events work.
* Various other quirks for each browser that I don't even want to go over.
* There is very little documented about these events.
Yes, I **must** use actual drag+drop, and cannot simulate it.
My questions:
* **Is there a way to detect "ondragleave" or similar in FF?**
* **Is there a way to detect "ondragdrop" or similar in Safari?**
* **Do you have anything to add about Drag + Drop?**
Here's a quick and dirty template demonstrating drag and drop events:
```
<script>
addEvent = function(obj, eventname, fn){
if (document.addEventListener) obj.addEventListener(eventname, fn, false);
else obj.attachEvent('on'+eventname, fn);
}
window.onload = function(){
var logger = document.getElementById("logger");
var log = function(str){ logger.value = str + logger.value; }
//log a variety of drag events for the textarea
var obj = document.getElementById("tarea");
var events = ["dragenter","dragover","dragout","dragleave","dragdrop","drop"];
for (var i=0; i<events.length; i++){
(function(event){//create a closure to remove variable scope
addEvent(obj, event, function(){ log("textarea: " + event + "\n"); });
})(events[i]);
}
//log events on the div
obj = document.getElementById("div");
events = ["mouseover","mouseout","mouseup","mousedown","click","dblclick",
"dragenter","dragover","dragout","dragleave","dragdrop","drop"];
for (var i=0; i<events.length; i++){
(function(event){//create a closure to remove variable scope
addEvent(obj, event, function(){ log("div: " + event + "\n"); });
})(events[i]);
}
}
</script>
Life's a drag when doing cross browser stuff.<br><br>
<div id="div" style="width: 100px; height: 100px; background: green; float: left;">
</div>
<textarea id="tarea" style="width: 100px; height: 100px; float: left; margin: 0px 5px;">
</textarea>
<textarea id="logger" style="width: 200px; height: 400px; float: left;">
</textarea>
``` | I've found a way to handle onDragLeave via event delegation.
Simply add an event to monitor "dragover" on the entire document. When the event source becomes your element in question, set a flag, and once the event source is no longer that element, fire the "dragleave" event.
Note:
* Will need to be modified so that "e.source==obj" is actually "obj.childOf(e.source)" ... since the source element may be a descendant of the object in question.
* Requires the event handling framework to figure out what "source" is based on browser.
Unfortunately it looks like Safari's lack of "ondrop" cannot be fixed... it simply never gets fired.
How to achieve "dragleave" in FF (well, all browsers):
```
var setOnDragLeave = function(obj, fn){
var on=false;
var dragover = function(e){
if (on){
if (e.source!=obj){
on = false;
e.eventname = "dragleave";
fn.call(obj, e);
}
return;
}else{
if (e.source==obj) on = true;
return;
}
}
addEvent(document.documentElement, "dragover", dragover);
}
setOnDragLeave(obj, function(e){ logEvent(e); });
```
I sincerely hope someone else on this planet can use this... | Nice article. I too am looking for an equivalent of ondrop/ondragdrop in Safari. However, there is a possible workaround for "internal" drag-drop case, i.e. the drag source and drop target are in the same document.
IE supports the events ondragstart, ondrag and ondragend on the drag source element. Safari 3 fires these as well. Firefox3 fires ondrag and ondragend, but not ondragstart (though the documentation suggests that it should). Anyway, depending on your scenario, you may be able to use ondragend to detect when the drag-drop operation is completed. | Browser "drag and drop" events: Can anyone fill in the blanks? | [
"",
"javascript",
"firefox",
"events",
"drag-and-drop",
"safari",
""
] |
I'm doing something really simple: slurping an entire text file from disk into a `std::string`. My current code basically does this:
```
std::ifstream f(filename);
return std::string(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>());
```
It's very unlikely that this will ever have any kind of performance impact on the program, but I still got curious whether this is a slow way of doing it.
Is there a risk that the construction of the string will involve a lot of reallocations? Would it be better (that is, faster) to use `seekg()`/`tellg()` to calculate the size of the file and `reserve()` that much space in the string before doing the reading? | I benchmarked your implementation(1), mine(2), and two others(3 and 4) that I found on stackoverflow.
Results (Average of 100 runs; timed using gettimeofday, file was 40 paragraphs of lorem ipsum):
* readFile1: 764
* readFile2: 104
* readFile3: 129
* readFile4: 402
The implementations:
```
string readFile1(const string &fileName)
{
ifstream f(fileName.c_str());
return string(std::istreambuf_iterator<char>(f),
std::istreambuf_iterator<char>());
}
string readFile2(const string &fileName)
{
ifstream ifs(fileName.c_str(), ios::in | ios::binary | ios::ate);
ifstream::pos_type fileSize = ifs.tellg();
ifs.seekg(0, ios::beg);
vector<char> bytes(fileSize);
ifs.read(&bytes[0], fileSize);
return string(&bytes[0], fileSize);
}
string readFile3(const string &fileName)
{
string data;
ifstream in(fileName.c_str());
getline(in, data, string::traits_type::to_char_type(
string::traits_type::eof()));
return data;
}
string readFile4(const std::string& filename)
{
ifstream file(filename.c_str(), ios::in | ios::binary | ios::ate);
string data;
data.reserve(file.tellg());
file.seekg(0, ios::beg);
data.append(istreambuf_iterator<char>(file.rdbuf()),
istreambuf_iterator<char>());
return data;
}
``` | What happens to the performance if you try doing that? Instead of asking "which way is faster?" you can think "hey, I can measure this."
Set up a loop that reads a file of a given size 10000 times or something, and time it. Then do it with the `reserve()` method and time that. Try it with a few different file sizes (from small to enormous) and see what you get. | Performance of creating a C++ std::string from an input iterator | [
"",
"c++",
"string",
"stream",
""
] |
I am running an msi installer in silent mode and caching logs in the specific file. The following is the command i need to execute.
`C:\Program Files\ My Installer\Setup.exe /s /v "/qn /lv %TEMP%\log_silent.log"`
I used:
```
subprocess.Popen(['C:\Program Files\ My Installer\Setup.exe', '/s /v "/qn /lv %TEMP%\log_silent.log"'],stdout=subprocess.PIPE).communicate()[0]
```
to execute the command however it does not recognise the operation and gives error regarding wrong option selected. I have cross-verified and found that the command only works this way. | The problem is very subtle.
You're executing the program directly. It gets:
```
argv[0] = "C:\Program Files\ My Installer\Setup.exe"
argv[1] = /s /v "/qn /lv %TEMP%\log_silent.log"
```
Whereas it should be:
```
argv[1] = "/s"
argv[2] = "/v"
argv[3] = "/qn"
argv[4] = "/lv %TEMP%\log_silent.log"
```
In other words, it should receive 5 arguments, not 2 arguments.
Also, `%TEMP%` is directly unknown to the program!
There are 2 ways to fix this problem:
1. **Calling the shell.**
```
p = subprocess.Popen('C:\Program Files\ My Installer\Setup.exe /s /v "/qn /lv %TEMP%\log_silent.log"', shell=True)
output = p.communicate()[0]
```
2. **Directly call program (more safer)**
```
s = ['C:\Program Files\ My Installer\Setup.exe', '/s /v "/qn /lv %TEMP%\log_silent.log"']
safes = [os.path.expandvars(p) for p in argument_string]
p = subprocess.Popen(safes[0], safes[1:])
output = p.communicate()[0]
``` | The problem is that you effectively supply Setup.exe with only one argument. Don't think in terms of the shell, the string you hand over as an argument does not get splitted on spaces anymore, that's your duty!
So, if you are absolutely sure that "/qn /lv %TEMP%\log\_silent.log" should be one argument, then use this:
```
subprocess.Popen(['C:\Program Files\ My Installer\Setup.exe', '/s', '/v', '/qn /lv %TEMP%\log_silent.log'],stdout=subprocess.PIPE).communicate()[0]
```
Otherwise (I guess this one will be correct), use this:
```
subprocess.Popen(['C:\Program Files\ My Installer\Setup.exe', '/s', '/v', '/qn', '/lv', '%TEMP%\log_silent.log'],stdout=subprocess.PIPE).communicate()[0]
``` | subprocess.Popen error | [
"",
"python",
"subprocess",
"popen",
""
] |
I am developing a simple platform game in Java using BlueJ.
Over the next few weeks I will be posting a few questions asking for help with this project as am not very proficient at programming. So I hope I don't become annoying and I would be very grateful if you can kindly help me.
In my game I have a gameOver method which ends the game and prints a statement to the console. What I would like is to call upon this method when my player sprite "falls off" the screen.
Right now I have a rectangle shape placed at the bottom of the screen to represent some kind of hazard (like water) and when the player collides with it, it calls the gameOver method and the game ends. However, I would still prefer if the game ended if the player fell below a certain height of the screen.
This is my gameOver method (from the 'Game' class)-
```
/** End the game. */
public void gameOver()
{
world.terminate();
isOver = true;
}
```
This is my player sprite (currently drawn using a polygon)-
```
super(Utils.createPolygon(170, 102,
155, 118, 137, 118, 151, 134, 146,
140, 167, 140, 170, 135, 174, 140,
193, 140, 188, 134, 202, 118, 186,
118, 170, 102));
setColor(new Color(254, 167, 184));
```
This is the code (from the 'Enemy' class, similar code is used in a Hazard class also) that ends the game when player collides with an enemy-
```
if (e.contact.involves(player) && (player.getLives() < 1)) {
System.out.println("YOU ARE DEAD!");
game.gameOver();
}
```
I would like a similar, or at least simple solution that will call on my gameOver method when my player sprite falls or goes beyond a certain coordinate of the screen.
I would appreciate it if you could kindly provide a sample/example code, with comments to help me understand it, in order to give an idea of what I should do to achieve this.
Thank you very much and I look forward to your answers. | To get you started:
1. Think about how you might get the player's current position.
2. Think about what makes the player fall (there should be some method/class that implements gravity and falling?)
3. Check the player's position as they fall against the boundries of your world. If they're outside the boundries, it's time to call your GameOver method.
To check the boundries:
1. Your world should have a minimum height that the player has to keep above to stay alive. Remember this value.
2. If you get your player's vertical position and compare to this minimum height, you should get a boolean result (safe vs. dead).
3. Note that screen position starts at the top left and increases as you go right and down, so you're player position probably reflects this. Thus, you're most likely looking for the test (`player.getPosition().Y > world.getMaxAllowedHeight()`);
---
For reference: Please post what you've tried already and where you're having problems. Asking for a spoonfed solution isn't going to help anyone - you're going to have to think about this a bit yourself. If you have no idea where to start, tell us that instead; we can try to steer you in the right direction.
Update: Sounds like you've done a bit of thinking already, which is great! Sorry if I was harsh to jump down your throat, but your original post suggested otherwise. Next time, though, do try to ask a more help-me-help-myself question than a solve-it-for-me one. A simple "Can someone give me an idea of how to start tackling this problem?" will do. | To help you do your homework:
```
// if the player goes out of bounds, the game is over
if (player.getBounds().outside(game.getBounds())
{
System.out.println("YOU WENT OUT!");
game.gameOver();
}
```
assuming that the player has some kind of bounding area and the game itself has some kind of area... | How to call upon a gameOver method in a Java game when sprite "falls off" the screen? | [
"",
"java",
"methods",
"screen",
""
] |
Languages such as Java explicitly use the *interface* keyword to denote [interfaces](https://stackoverflow.com/questions/98867/where-did-the-concept-of-interfaces-come-from). Having used Java, the concept seems useful enough to me to justify a keyword to enforce the concept.
Of course one can use a pure virtual class and label it as an interface. However, this keyword seems to be so useful and differentiated from a pure virtual class as to be useful. Perhaps it is being included in C++ 0x? | The early OO features of C++ have long been neglected because it has since moved in a more interesting direction as a multi-paradigm language. The major focus for over a decade now has been templates and their implications, particularly in the standard library. Yes, programs would be more readable with an `interface` keyword. They would also be easier to maintain if there were `override` and `new` modifiers for methods that have the same name as base class methods (a la C#). But these are not interesting problems to modern C++ users, nor to those who contribute to the language design. The OO features are adequate, but not great, and are hardly used in the "newer" (post 1992) parts of the standard library, which in some ways serves as a guide to good style. | Because C++ allows multiple inheritance, and because an interface is an abstract class which has all of it's members also abstract/virtual, C++ does not need it - a class can simply "extend" multiple other classes, any of which may be purely virtual (abstract).
Java and C#, on the other hand do not permit MI, since the designers of those languages felt that MI creates more problems than it solves. But it is still necessary for an object to "be" many things (the OOP is-a relationship), so interfaces provide a mechanism which allows an object to be many things, without inheriting multiple implementations - keeping the baby, but throwing out the bathwater. | Why is the OO concept interface not represented by a keyword in C++? | [
"",
"c++",
"oop",
""
] |
I need to query the database to get the *column names*, not to be confused with data in the table. For example, if I have a table named `EVENT_LOG` that contains `eventID`, `eventType`, `eventDesc`, and `eventTime`, then I would want to retrieve those field names from the query and nothing else.
I found how to do this in:
* [Microsoft SQL Server](https://stackoverflow.com/q/1054984/419956)
* [MySQL](https://stackoverflow.com/q/193780/419956)
* [PostgreSQL](https://dba.stackexchange.com/q/22362/5089)
But I need to know: **how can this be done in *Oracle*?** | You can query the USER\_TAB\_COLUMNS table for table column metadata.
```
SELECT table_name, column_name, data_type, data_length
FROM USER_TAB_COLUMNS
WHERE table_name = 'MYTABLE'
``` | In SQL Server...
```
SELECT [name] AS [Column Name]
FROM syscolumns
WHERE id = (SELECT id FROM sysobjects WHERE type = 'V' AND [Name] = 'Your table name')
```
Type = 'V' for views
Type = 'U' for tables | How can I get column names from a table in Oracle? | [
"",
"sql",
"database",
"oracle",
""
] |
I'm writing a Windows service and need to make authenticated web requests. The service will not be running under the ownership of the credentials used to make the request; this implies that I need to store the credentials for the request in some way.
What are the best practices here? The credentials will need to be stored in App.config (or an analog); I'd rather not have the password hanging out in plain text. As passwords change frequently, building or otherwise baking in the password to the binary is not an option.
The same question applies for Powershell. I need to make authenticated requests, but I don't want the script to contain in a plain-text form the credentials used for the requests. | Can't take the credit for the answer: But here's a blog post called "Encrypting Passwords in .NET App Config" With full code included.
<http://weblogs.asp.net/jgalloway/archive/2008/04/13/encrypting-passwords-in-a-net-app-config-file.aspx> | I always refer to Keith Brown's "The .NET Developer's Guide to Windows Security" book for stuff like this.
The complete text is online at <http://alt.pluralsight.com/wiki/default.aspx/Keith.GuideBook.HomePage>
The specific section you want (on storing secrets) is at <http://alt.pluralsight.com/wiki/default.aspx/Keith.GuideBook/HowToStoreSecretsOnAMachine.html> | Credential storage best practices | [
"",
"c#",
"powershell",
"windows-services",
""
] |
I have this java string:
```
String bla = "<my:string>invalid_content</my:string>";
```
How can I replace the "invalid\_content" piece?
I know I should use something like this:
```
bla.replaceAll(regex,"new_content");
```
in order to have:
```
"<my:string>new_content</my:string>";
```
but I can't discover how to create the correct regex
help please :) | You could do something like
```
String ResultString = subjectString.replaceAll("(<my:string>)(.*)(</my:string>)", "$1whatever$3");
``` | Mark's answer will work, but can be improved with two simple changes:
* The central parentheses are redundant if you're not using that group.
* Making it non-greedy will help if you have multiple my:string tags to match.
Giving:
```
String ResultString = SubjectString.replaceAll
( "(<my:string>).*?(</my:string>)" , "$1whatever$2" );
```
But that's still not how I'd write it - the replacement can be simplified using lookbehind and lookahead, and you can avoid repeating the tag name, like this:
```
String ResultString = SubjectString.replaceAll
( "(?<=<(my:string)>).*?(?=</\1>)" , "whatever" );
```
Of course, this latter one may not be as friendly to those who don't yet know regex - it is however more maintainable/flexible, so worth using if you might need to match more than just my:string tags. | replacing regex in java string | [
"",
"java",
"regex",
"string",
"replace",
""
] |
When compiling the following code:
```
void DoSomething(int Numbers[])
{
int SomeArray[] = Numbers;
}
```
the VS2005 compiler complains with the error C2440: 'initializing' : cannot convert from 'int []' to 'int []'
I understand that really it's trying to cast a pointer to an array which is not going to work. But how do you explain the error to someone learning C++? | There are three things you need to explain to the person you're trying to help:
1. **Arrays can't be passed by value to a function in C++.** To do what you are trying to do, you need to pass the address of the start of the array to `DoSomething()`, as well as the size of the array in a separate `int` (well, `size_t`, but I wouldn't bother saying that) argument. You can get the address of the start of some array `myArray` with the expression `&(myArray[0])`. Since this is such a common thing to want to do, C++ lets you use just the name of the array -- e.g. `myArray` -- to get the address of its first element. (Which can be helpful or confusing, depending on which way you look at it.) To make things even more confusing, C++ allows you to specify an array type (e.g. `int Numbers[]`) as a parameter to a function, but secretly it treats that parameter as though it was a declared as a pointer (`int *Numbers` in this case) -- you can even do `Numbers += 5` inside `DoSomething()` to make it point to an array starting at the sixth position!
2. **When you declare an array variable such as `SomeArray` in C++, you must either provide an explicit size or an "initialiser list"**, which is a comma-separated list of values between braces. It's not possible for the compiler to infer the size of the array based on another array that you are trying to initialise it with, because...
3. **You can't copy one array into another, or initialise one array from another in C++.** So even if the parameter `Numbers` was really an array (say of size 1000) and not a pointer, and you specified the size of `SomeArray` (again as say 1000), the line `int SomeArray[1000] = Numbers;` would be illegal.
---
To do what you want to do in `DoSomething()`, first ask yourself:
1. Do I need to change any of the values in `Numbers`?
2. If so, do I want to prevent the caller from seeing those changes?
If the answer to either question is "No", you don't in fact need to make a copy of `Numbers` in the first place -- just use it as is, and forget about making a separate `SomeArray` array.
If the answer to both questions is "Yes", you will need to make a copy of `Numbers` in `SomeArray` and work on that instead. In this case, you should really make `SomeArray` a C++ `vector<int>` instead of another array, as this really simplifies things. (Explain the benefits of vectors over manual dynamic memory allocation, including the facts that they *can* be initialised from other arrays or vectors, and they will call element constructors when necessary, unlike a C-style `memcpy()`.) | Say that there are types and incomplete types:
```
struct A;
```
Is an incomplete type of a struct called A. While
```
struct A { };
```
Is a complete type of a struct called A. The size of the first is not yet known, while the size of the second is known.
There are incomplete class types like the above struct. But there are also incomplete array types:
```
typedef int A[];
```
That is an incomplete array type called A. Its size is not yet known. You cannot create an array out of it, because the compiler does not know how big the array is. But you can *use* it to create an array, *only* if you initialize it straight away:
```
A SomeArray = { 1, 2, 3 };
```
Now, the compiler knows the array is an int array with 3 elements. If you try to initialize the array with a pointer, the compiler will not be any more clever than before, and refuse, because that won't give it the size of the array to be created. | How do you make sense of the error: cannot convert from 'int []' to 'int []' | [
"",
"c++",
"arrays",
"visual-studio-2005",
"pointers",
"error-code",
""
] |
I am trying to do a nice SQL statement inside a stored procedure.
I looked at the issue of seeing the number of days that events happened between two dates.
My example is sales orders: for this month, how many days did we have sales orders?
Suppose this setup:
```
CREATE TABLE `sandbox`.`orders` (
`year` int,
`month` int,
`day` int,
`desc` varchar(255)
)
INSERT INTO orders (year, month, day, desc)
VALUES (2009,1,1, 'New Years Resolution 1')
,(2009,1,1, 'Promise lose weight')
,(2009,1,2, 'Bagel')
,(2009,1,12, 'Coffee to go')
```
For this in-data the result should be 3, since there has been three days with sale.
The best solution I found is as below.
However, making a temporary table, counting that then dropping it seemes excess. It "should" be possible in one statement.
Anyone who got a "nicer" solution then me?
/L
```
SELECT [Year], [Month], [Day]
INTO #Some_Days
FROM Quarter
WHERE Start >= '2009-01-01' AND [End] < '2009-01-16'
GROUP BY [Year], [Month], [Day]
SELECT count(*) from #Some_Days
``` | Apologies if I'm misunderstanding the question, but perhaps you could do something like this, as an option:
```
SELECT COUNT(*) FROM
(SELECT DISTINCT(SomeColumn)
FROM MyTable
WHERE Something BETWEEN 100 AND 500
GROUP BY SomeColumn) MyTable
```
... to get around the temp-table creation and disposal? | There are two basic options which I can see. One is to group everything up in a sub query, then count those distinct rows (Christian Nunciato's answer). The second is to combine the multiple fields and count distinct values of that combined value.
In this case, the following formula coverts the three fields into a single datetime.
```
DATEADD(YEAR, [Quarter].Year, DATEADD(MONTH, [Quarter].Month, DATEADD(DAY, [Quarter].DAY, 0), 0), 0)
```
Thus, COUNT(DISTINCT [formula]) will give the answer you need.
```
SELECT
COUNT(DISTINCT DATEADD(YEAR, [Quarter].Year, DATEADD(MONTH, [Quarter].Month, DATEADD(DAY, [Quarter].DAY, 0), 0), 0))
FROM
Quarter
WHERE
[Quarter].Start >= '2009-01-01'
AND [Quarter].End < '2009-01-16'
```
I usually use the sub query route, but depending on what you're doing, indexes, size of table, simplicity of the formula, etc, this Can be faster...
Dems. | Execute count(*) on a group-by result-set | [
"",
"sql",
"t-sql",
""
] |
I am having a qt question. I want the QLineEdit widget to have the focus at application startup. Take the following code for example:
```
#include <QtGui/QApplication>
#include <QtGui/QHBoxLayout>
#include <QtGui/QPushButton>
#include <QtGui/QLineEdit>
#include <QtGui/QFont>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QWidget *window = new QWidget();
window->setWindowIcon(QIcon("qtest16.ico"));
window->setWindowTitle("QtTest");
QHBoxLayout *layout = new QHBoxLayout(window);
// Add some widgets.
QLineEdit *line = new QLineEdit();
QPushButton *hello = new QPushButton(window);
hello->setText("Select all");
hello->resize(150, 25);
hello->setFont(QFont("Droid Sans Mono", 12, QFont::Normal));
// Add the widgets to the layout.
layout->addWidget(line);
layout->addWidget(hello);
line->setFocus();
QObject::connect(hello, SIGNAL(clicked()), line, SLOT(selectAll()));
QObject::connect(line, SIGNAL(returnPressed()), line, SLOT(selectAll()));
window->show();
return app.exec();
}
```
Why does `line->setFocus()` sets the focus on the line widget @app startup only if it is placed after laying out the widgets and if used before it's not working? | [Keyboard focus](https://doc.qt.io/qt-5/focus.html) is related to widget [tab order](https://doc.qt.io/qt-5/qwidget.html#setTabOrder), and the default tab order *is based on the order in which widgets are constructed*. Therefore, creating more widgets changes the keyboard focus. That is why you must make the [`QWidget::setFocus`](https://doc.qt.io/qt-5/qwidget.html#setFocus) call last.
I would consider using a sub-class of `QWidget` for your main window that overrides the [`showEvent`](https://doc.qt.io/qt-5/qwidget.html#showEvent) virtual function and then sets keyboard focus to the `lineEdit`. This will have the effect of always giving the `lineEdit` focus when the window is shown. | Another trick that might work is by using the `singleshot` timer:
```
QTimer::singleShot(0, line, SLOT(setFocus()));
```
Effectively, this invokes the `setFocus()` slot of the `QLineEdit` instance right after the event system is "free" to do so, i.e. sometime after the widget is completely constructed. | Set QLineEdit focus in Qt | [
"",
"c++",
"qt",
"qlineedit",
""
] |
I am using sqlite with python 2.5. I get a sqlite error with the syntax below. I looked around and saw AUTOINCREMENT on this page <http://www.sqlite.org/syntaxdiagrams.html#column-constraint> but that did not work either. Without AUTO\_INCREMENT my table can be created.
```
An error occurred: near "AUTO_INCREMENT": syntax error
CREATE TABLE fileInfo
(
fileId int NOT NULL AUTO_INCREMENT,
name varchar(255),
status int NOT NULL,
PRIMARY KEY (fileId)
);
``` | This is addressed in the [SQLite FAQ](http://www.sqlite.org/faq.html). [Question #1](http://www.sqlite.org/faq.html#q1).
Which states:
> How do I create an AUTOINCREMENT
> field?
>
> Short answer: A column declared
> INTEGER PRIMARY KEY will
> autoincrement.
>
> Here is the long answer: If you
> declare a column of a table to be
> INTEGER PRIMARY KEY, then whenever you
> insert a NULL into that column of the
> table, the NULL is automatically
> converted into an integer which is one
> greater than the largest value of that
> column over all other rows in the
> table, or 1 if the table is empty. (If
> the largest possible integer key,
> 9223372036854775807, then an unused
> key value is chosen at random.) For
> example, suppose you have a table like
> this:
>
> `CREATE TABLE t1( a INTEGER PRIMARY`
> `KEY, b INTEGER );` With this table,
> the statement
>
> `INSERT INTO t1 VALUES(NULL,123);` is
> logically equivalent to saying:
>
> `INSERT INTO t1 VALUES((SELECT max(a)
> FROM t1)+1,123);` There is a function
> named `sqlite3_last_insert_rowid()`
> which will return the integer key for
> the most recent insert operation.
>
> Note that the integer key is one
> greater than the largest key that was
> in the table just prior to the insert.
> The new key will be unique over all
> keys currently in the table, but it
> might overlap with keys that have been
> previously deleted from the table. To
> create keys that are unique over the
> lifetime of the table, add the
> AUTOINCREMENT keyword to the INTEGER
> PRIMARY KEY declaration. Then the key
> chosen will be one more than than the
> largest key that has ever existed in
> that table. If the largest possible
> key has previously existed in that
> table, then the INSERT will fail with
> an SQLITE\_FULL error code. | It looks like AUTO\_INCREMENT should be AUTOINCREMENT see <http://www.sqlite.org/syntaxdiagrams.html#column-constraint> | AUTO_INCREMENT in sqlite problem with python | [
"",
"python",
"sqlite",
""
] |
In C++, I enjoyed having access to a 64 bit unsigned integer, via `unsigned long long int`, or via `uint64_t`. Now, in Java longs are 64 bits, I know. However, they are signed.
Is there an unsigned long (long) available as a Java primitive? How do I use it? | I don't believe so. Once you want to go bigger than a signed long, I think [BigInteger](http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html) is the only (out of the box) way to go. | Starting Java 8, there is support for unsigned long (unsigned 64 bits). The way you can use it is:
```
Long l1 = Long.parseUnsignedLong("17916881237904312345");
```
To print it, you can not simply print l1, but you have to first:
```
String l1Str = Long.toUnsignedString(l1)
```
Then
```
System.out.println(l1Str);
``` | Java equivalent of unsigned long long? | [
"",
"java",
"unsigned",
"primitive",
"unsigned-long-long-int",
""
] |
In a constructor in Java, if you want to call another constructor (or a super constructor), it has to be the first line in the constructor. I assume this is because you shouldn't be allowed to modify any instance variables before the other constructor runs. But why can't you have statements before the constructor delegation, in order to compute the complex value to the other function? I can't think of any good reason, and I have hit some real cases where I have written some ugly code to get around this limitation.
So I'm just wondering:
1. Is there a good reason for this limitation?
2. Are there any plans to allow this in future Java releases? (Or has Sun definitively said this is not going to happen?)
---
For an example of what I'm talking about, consider some code I wrote which I gave in [this StackOverflow answer](https://stackoverflow.com/questions/474535/best-way-to-represent-a-fraction-in-java/474612#474612). In that code, I have a BigFraction class, which has a BigInteger numerator and a BigInteger denominator. The "canonical" constructor is the `BigFraction(BigInteger numerator, BigInteger denominator)` form. For all the other constructors, I just convert the input parameters to BigIntegers, and call the "canonical" constructor, because I don't want to duplicate all the work.
In some cases this is easy; for example, the constructor that takes two `long`s is trivial:
```
public BigFraction(long numerator, long denominator)
{
this(BigInteger.valueOf(numerator), BigInteger.valueOf(denominator));
}
```
But in other cases, it is more difficult. Consider the constructor which takes a BigDecimal:
```
public BigFraction(BigDecimal d)
{
this(d.scale() < 0 ? d.unscaledValue().multiply(BigInteger.TEN.pow(-d.scale())) : d.unscaledValue(),
d.scale() < 0 ? BigInteger.ONE : BigInteger.TEN.pow(d.scale()));
}
```
I find this pretty ugly, but it helps me avoid duplicating code. The following is what I'd like to do, but it is illegal in Java:
```
public BigFraction(BigDecimal d)
{
BigInteger numerator = null;
BigInteger denominator = null;
if(d.scale() < 0)
{
numerator = d.unscaledValue().multiply(BigInteger.TEN.pow(-d.scale()));
denominator = BigInteger.ONE;
}
else
{
numerator = d.unscaledValue();
denominator = BigInteger.TEN.pow(d.scale());
}
this(numerator, denominator);
}
```
---
**Update**
There have been good answers, but thus far, no answers have been provided that I'm completely satisfied with, but I don't care enough to start a bounty, so I'm answering my own question (mainly to get rid of that annoying "have you considered marking an accepted answer" message).
Workarounds that have been suggested are:
1. Static factory.
* I've used the class in a lot of places, so that code would break if I suddenly got rid of the public constructors and went with valueOf() functions.
* It feels like a workaround to a limitation. I wouldn't get any other benefits of a factory because this cannot be subclassed and because common values are not being cached/interned.
2. Private static "constructor helper" methods.
* This leads to lots of code bloat.
* The code gets ugly because in some cases I really need to compute both numerator and denominator at the same time, and I can't return multiple values unless I return a `BigInteger[]` or some kind of private inner class.
The main argument against this functionality is that the compiler would have to check that you didn't use any instance variables or methods before calling the superconstructor, because the object would be in an invalid state. I agree, but I think this would be an easier check than the one which makes sure all final instance variables are always initialized in every constructor, no matter what path through the code is taken. The other argument is that you simply can't execute code beforehand, but this is clearly false because the code to compute the parameters to the superconstructor is getting executed *somewhere*, so it must be allowed at a bytecode level.
Now, what I'd like to see, is some *good* reason why the compiler couldn't let me take this code:
```
public MyClass(String s) {
this(Integer.parseInt(s));
}
public MyClass(int i) {
this.i = i;
}
```
And rewrite it like this (the bytecode would be basically identical, I'd think):
```
public MyClass(String s) {
int tmp = Integer.parseInt(s);
this(tmp);
}
public MyClass(int i) {
this.i = i;
}
```
The only real difference I see between those two examples is that the "`tmp`" variable's scope allows it to be accessed after calling `this(tmp)` in the second example. So maybe a special syntax (similar to `static{}` blocks for class initialization) would need to be introduced:
```
public MyClass(String s) {
//"init{}" is a hypothetical syntax where there is no access to instance
//variables/methods, and which must end with a call to another constructor
//(using either "this(...)" or "super(...)")
init {
int tmp = Integer.parseInt(s);
this(tmp);
}
}
public MyClass(int i) {
this.i = i;
}
``` | > I find this pretty ugly, but it helps
> me avoid duplicating code. The
> following is what I'd like to do, but
> it is illegal in Java ...
You could also work around this limitation by using a static factory method that returns a new object:
```
public static BigFraction valueOf(BigDecimal d)
{
// computate numerator and denominator from d
return new BigFraction(numerator, denominator);
}
```
Alternatively, you could cheat by calling a private static method to do the computations for your constructor:
```
public BigFraction(BigDecimal d)
{
this(computeNumerator(d), computeDenominator(d));
}
private static BigInteger computeNumerator(BigDecimal d) { ... }
private static BigInteger computeDenominator(BigDecimal d) { ... }
``` | I think several of the answers here are wrong because they assume encapsulation is somehow broken when calling super() after invoking some code. The fact is that the super can actually break encapsulation itself, because Java allows overriding methods in the constructor.
Consider these classes:
```
class A {
protected int i;
public void print() { System.out.println("Hello"); }
public A() { i = 13; print(); }
}
class B extends A {
private String msg;
public void print() { System.out.println(msg); }
public B(String msg) { super(); this.msg = msg; }
}
```
If you do
```
new B("Wubba lubba dub dub");
```
the message printed out is "null". That's because the constructor from A is accessing the uninitialized field from B. So frankly it seems that if someone wanted to do this:
```
class C extends A {
public C() {
System.out.println(i); // i not yet initialized
super();
}
}
```
Then that's just as much their problem as if they make class B above. In both cases the programmer has to know how the variables are accessed during construction. And given that you can call `super()` or `this()` with all kinds of expressions in the parameter list, it seems like an artificial restriction that you can't compute any expressions before calling the other constructor. Not to mention that the restriction applies to both `super()` and `this()` when presumably you know how to not break your own encapsulation when calling `this()`.
My verdict: This feature is a bug in the compiler, perhaps originally motivated by a good reason, but in its current form it is an artifical limitation with no purpose. | Why must delegation to a different constructor happen first in a Java constructor? | [
"",
"java",
"syntax",
""
] |
How can I avoid name mangling in C++? | You can't. It's built into compilers to allow you overloading functions and to have functions with the same name in different classes and such stuff. But you can write functions that are mangled like C functions. Those can be called from C code. But those can't be overloaded and can't be called by "normal" C++ function pointers:
```
extern "C" void foo() {
}
```
The above function will be mangled like C functions for your compiler. That may include no change at all to the name, or some changes like a leading "\_" in front of it or so. | Other way:
**Controlling Names Used in Assembler Code** ([gcc spec.](https://gcc.gnu.org/onlinedocs/gcc/Asm-Labels.html))
> You can specify the name to be used in the assembler code for a *C function* or variable by writing the **asm** (or **\_\_asm\_\_**) keyword after the declarator. It is up to you to make sure that the assembler names you choose do not conflict with any other assembler symbols, or reference registers.
>
> To specify the assembler name for functions, write a declaration for the function before its definition and put **asm** there, like this:
```
int func () asm ("MYFUNC");
int func ()
{
```
`g++` will compile it and `nm -D` output will be
```
0000000000001e02 T MYFUNC
```
instead of
```
0000000000001e02 T _Z4funcv
```
Tested on g++ 4.9.2 | How can i avoid name mangling? | [
"",
"c++",
""
] |
For educational purposes I want to create a ostream and stream buffer to do:
1. fix endians when doing << myVar;
2. store in a deque container instead of using std:cout or writing to a file
3. log extra data, such as how many times I did <<, how many times I did .write, the amount of bytes I written and how many times I flush(). But I do not need all the info.
I tried overloading but failed horribly. I tried overloading write by doing
```
ostream& write( const char* s, streamsize n )
```
in my basic\_stringstream2 class (I copied paste basic\_stringstream into my cpp file and modified it) but the code kept using basic\_ostream. I looked through code and it looks like I need to overload xsputn (which isn't mention on this page <http://www.cplusplus.com/reference/iostream/ostream> ) but what else do I need to overload? and how do I construct my class (what does it need to inherit, etc)? | The canonical approach consists in defining your own streambuf.
You should have a look at:
* [Angelika LAnger's articles](http://www.angelikalanger.com/Articles/Topics.html#CPP) on IOStreams derivation
* [James Kanze's articles](http://gabisoft.free.fr/articles-en.html) on filtering streambufs
* [boost.iostream](http://www.boost.org/doc/libs/1_37_0/libs/iostreams/doc/index.html) for examples of application | For A+C) I think you should look at facets, they modify how objects are written as characters. You could store statistics here as well on how many times you streamed your objects.
Check out [How to format my own objects when using STL streams?](https://stackoverflow.com/questions/1096291/how-to-format-my-own-objects-when-using-stl-streams/) for an example.
For B) You need to create your own streambuf and connect your ostream to that buffer (constructor argument). See [Luc's links](https://stackoverflow.com/questions/524641/how-do-i-create-an-ostream-streambuf/528460#528460) + [Deriving new streambuf classes](https://duckduckgo.com/?q=Deriving+new+streambuf+classes&t=ffab&ia=web).
In short you need to implement this for an ostream (minimum):
* overflow (put a single char or flush buffer) ([link](http://uw714doc.sco.com/en/SDK_clib/_overflow.html))
* xsputn (put a char array to buffer)([link](http://www.cplusplus.com/reference/iostream/streambuf/xsputn/))
* sync ([link](http://uw714doc.sco.com/en/SDK_clib/_sync.html)) | How do I create my own ostream/streambuf? | [
"",
"c++",
"ostream",
"streambuf",
""
] |
I'm just starting to learn C++ so you'll have to bear with my ignorance. Is there a way to to declare functions such that they can be referenced without being written before the function that uses them. I'm working with one cpp file (not my decision) and my functions call themselves so there is not really a proper order to place them in. Any way to #define functions before they're used or something to that effect?
Or maybe a way to tag them with a scope operator that doesn't entail them actually being part of a class?
Thanks in advance | You can write function **prototypes** before you implement them. A function prototype names a function, its return type, and the type of its arguments. The only thing that needs to be above the call to your function is the prototype. Here's an example:
```
// prototype
int your_function(int an_argument);
// ...
// here you can write functions that call your_function()
// ...
// implementation of your_function()
int your_function(int an_argument) {
return an_argument + 1;
}
``` | I think what you are referring to is a **function prototype**.
This is where you define the prototype of a function in the **header file**, but define the implementation in a **source (.cpp) file**.
Source code that needs to reference the function simply include the header file, which gives enough information for the compiler to correlate the function call to the arguments and return value of the function you are calling.
Only at the linking stage does the function "symbol" get resolved against the source file -- if the function **implementation** didn't exist at this point, you would get an unresolved symbol.
Here's an example:
Library Header file - library.h
```
// This defines a prototype (or signature) of the function
void libFunction(int a);
```
Library Source (.cpp) file - library.cpp
```
// This defines the implementation (or internals) of the function
void libFunction(int a)
{
// Function does something here...
}
```
Client code
```
#include "library.h"
void applicationFunction()
{
// This function call gets resolved against the symbol at the linking stage
libFunction();
}
``` | Basic C++ question regarding scope of functions | [
"",
"c++",
"function",
"scope",
""
] |
Using YUICompressor I get the following error from my javascript code:
```
[ERROR] 270:201:missing name after . operator
[ERROR] 292:6:missing ; before statement
```
Here's the javascript code at the following lines:
Line 270:
```
new _ow.getScript(_ow.wwwurl+'/widget/save?title='+encodeURIComponent(this.obj.title.value)+'&url='+encodeURIComponent(this.obj.url.value)+'&tags='+this.obj.tags.value+'&private='+this.obj.private.checked+'&c='+this.obj.notes.value+'&service='+services+'&token='+(_ow.token ? encodeURIComponent(_ow.token): ''), function(data) {
```
Line 292:
```
});
```
I can't figure out what the problem is since this Javascript code works fine on all browsers.
---
**EDIT**: I split the line in multiple lines and figured out that the "missing name after . operator" is generated by this code:
```
this.obj.private.checked
```
Is **private** a keyword that makes the YUI compressor go mad? | [`private` is a reserved word.](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Reserved_Words) | First, I'd reformat the code to make it more readable:
```
new _ow.getScript(_ow.wwwurl
+ '/widget/save?title='
+ encodeURIComponent(this.obj.title.value)
+ '&url='
+ encodeURIComponent(this.obj.url.value)
+ '&tags='
+ this.obj.tags.value
+ '&private='
+ this.obj.private.checked
+ '&c='
+ this.obj.notes.value
+ '&service='
+ services
+ '&token='
+ (_ow.token
? encodeURIComponent(_ow.token)
: ''),
function(data) {
});
```
Then, the line # reported by the compressor should help you drill down on what the problem is. | Javascript YUICompressor error | [
"",
"javascript",
"yui",
"yui-compressor",
""
] |
Im searching for a .Net component to read and write xls files from an application in working on. I dont want use automation with Excel.
It should support reading and write Excel 97 and newer versions. And it would be great if its open source or free since its a very low budget project.
I have found this one: [MyXLS](http://myxls.in2bits.org/) that looks very promising.
Do you know of any alternatives? | [This must be one of the most asked questions on SO](https://stackoverflow.com/search?q=excel+c%23+export). | [SpreadsheetGear for .NET](http://www.spreadsheetgear.com/) reads and writes CSV / XLS / XLSX and does more.
You can see live ASP.NET samples with C# and VB source code [here](http://www.spreadsheetgear.com/support/samples/) and download a free trial [here](https://www.spreadsheetgear.com/downloads/register.aspx).
Disclaimer: I own SpreadsheetGear LLC | Reading and writing XLS files | [
"",
"c#",
".net",
"import",
"export",
"xls",
""
] |
I'm working on a simple little swing component, and I'm tearing out my hair trying to figure out why my paint method isn't working.
The idea behind this component is that it's a small JPanel with a label. The background (behind the label) is supposed to be white, with a colored rectangle on the left-hand side indicating the ratio of two measurements: "actual" and "expected".
If you had a bunch of these components aligned vertically, they'd form a bar chart, composed of horizontal bars.
This kind of thing should be super-simple.
Anyhow, here's the code:
```
package com.mycompany.view;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class BarGraphPanel extends JPanel {
private static final Color BACKGROUND = Color.WHITE;
private static final Color FOREGROUND = Color.BLACK;
private static final Color BORDER_COLOR = new Color(229, 172, 0);
private static final Color BAR_GRAPH_COLOR = new Color(255, 255, 165);
private int actual = 0;
private int expected = 1;
private JLabel label;
public BarGraphPanel() {
super();
label = new JLabel();
label.setOpaque(false);
label.setForeground(FOREGROUND);
super.add(label);
super.setOpaque(true);
}
public void setActualAndExpected(int actual, int expected) {
this.actual = actual;
this.expected = expected;
}
@Override
public void paint(Graphics g) {
double proportion = (expected == 0) ? 0 : ((double) actual) / expected;
Rectangle bounds = super.getBounds();
g.setColor(BACKGROUND);
g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
g.setColor(BAR_GRAPH_COLOR);
g.fillRect(bounds.x, bounds.y, (int) (bounds.width * proportion), bounds.height);
g.setColor(BORDER_COLOR);
g.drawRect(bounds.x, bounds.y, bounds.width, bounds.height);
label.setText(String.format("%s of %s (%.1f%%)", actual, expected, proportion * 100));
super.paint(g);
g.dispose();
}
}
```
And here's the simple test harness:
```
package com.mycompany.view;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.UIManager;
public class MyFrame extends JFrame {
public MyFrame() {
super();
super.setLayout(new GridLayout(3, 1));
super.setPreferredSize(new Dimension(300, 200));
BarGraphPanel a = new BarGraphPanel();
BarGraphPanel b = new BarGraphPanel();
BarGraphPanel c = new BarGraphPanel();
a.setActualAndExpected(75, 100);
b.setActualAndExpected(85, 200);
c.setActualAndExpected(20, 300);
super.add(a);
super.add(b);
super.add(c);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Throwable t) { }
MyFrame frame = new MyFrame();
frame.pack();
frame.setVisible(true);
}
}
```
The test harness creates a simple frame and then adds three of these controls.
The labels are all rendered correctly, which indicates to me that the paint() method is actually being called, but the rectangles aren't being drawn to the Graphics object.
What am I doing wrong?
And why does Swing programming suck so much?
---
Here's my final code. Thanks, everyone, for your help!
```
public void paintComponent(Graphics g) {
double proportion = (expected == 0) ? 0 : ((double) actual) / expected;
Rectangle bounds = super.getBounds();
g.setColor(BACKGROUND);
g.fillRect(0, 0, bounds.width, bounds.height);
g.setColor(BAR_GRAPH_COLOR);
g.fillRect(0, 0, (int) (bounds.width * proportion), bounds.height);
g.setColor(BORDER_COLOR);
g.drawRect(0, 0, bounds.width - 1, bounds.height - 1);
FontMetrics metrics = g.getFontMetrics();
String label = String.format("%s of %s (%.1f%%)", actual, expected, proportion * 100);
Rectangle2D textBounds = metrics.getStringBounds(label, g);
g.setColor(FOREGROUND);
g.drawString(label, 5, (int) ((bounds.height + textBounds.getHeight()) / 2));
}
``` | I think you've almost answered your own question in the comments, along with David's answer. Change `paint(Graphics g)` to `paintComponent(Graphics g)` and remove the last two lines of the method, and you should be fine.
**EDIT:** Oddly, this only works for the first bar of the three. More testing in progress...
By the way, you have an off-by-one error in the border-painting code. It should be:
```
g.setColor(BORDER_COLOR);
g.drawRect(bounds.x, bounds.y, bounds.width - 1, bounds.height - 1);
```
**EDIT2:** OK, got it. Your full `paintComponent` method should be as follows:
```
@Override
public void paintComponent(Graphics g) {
double proportion = (expected == 0) ? 0 : ((double) actual) / expected;
Rectangle bounds = super.getBounds();
g.setColor(BACKGROUND);
g.fillRect(0, 0, bounds.width, bounds.height);
g.setColor(BAR_GRAPH_COLOR);
g.fillRect(0, 0, (int) (bounds.width * proportion), bounds.height);
g.setColor(BORDER_COLOR);
g.drawRect(0, 0, bounds.width-1, bounds.height-1);
label.setText(String.format("%s of %s (%.1f%%)", actual, expected, proportion * 100));
}
```
Note that the coordinates given to `g.fillRect()` and `g.drawRect()` are relative to the component, so they must start at (0,0).
And no, I can't help you with your last question, though I feel your pain. :) | In your JPanel, you called super.setOpaque(true). The JPanel is going to completely fill in the background when you call super.paint() and overwrite your retangles. | Java Paint Method Doesn't Paint? | [
"",
"java",
"swing",
"label",
"jpanel",
"paint",
""
] |
I'm trying to add custom fields to an InlineFormset using the following code, but the fields won't show up in the Django Admin. Is the InlineFormset too locked down to allow this? My print "ding" test fires as expected, I can print out the form.fields and see them all there, but the actual fields are never rendered in the admin.
**admin.py**
```
from django.contrib import admin
import models
from django.forms.models import BaseInlineFormSet
from django import forms
from forms import ProgressForm
from django.template.defaultfilters import slugify
class ProgressInlineFormset(BaseInlineFormSet):
def add_fields(self, form, index):
print "ding"
super(ProgressInlineFormset, self).add_fields(form, index)
for criterion in models.Criterion.objects.all():
form.fields[slugify(criterion.name)] = forms.IntegerField(label=criterion.name)
class ProgressInline(admin.TabularInline):
model = models.Progress
extra = 8
formset = ProgressInlineFormset
class ReportAdmin(admin.ModelAdmin):
list_display = ("name", "pdf_column",)
search_fields = ["name",]
inlines = (ProgressInline,)
admin.site.register(models.Report, ReportAdmin)
``` | ```
model = models.Progress
```
In the admin there will be only the fields defined in this *Progress* model. You have no fields/fieldsets option overwriting it.
If you want to add the new ones, there are two options:
* In the model definition, add those new additional fields (make them optional!)
* In the admin model (*admin.TabularInline*), add something something like:
fields = ('newfield1', 'newfield2', 'newfield3')
Take a look at [fields](http://docs.djangoproject.com/en/dev/ref/contrib/admin/#fields), [fieldsets](http://docs.djangoproject.com/en/dev/ref/contrib/admin/#fieldsets). | I did it another way:
forms.py:
```
from django import forms
class ItemAddForm(forms.ModelForm):
my_new_field = forms.IntegerField(initial=1, label='quantity')
class Meta:
model = Item
```
admin.py:
```
from django.contrib import admin
from forms import *
class ItemAddInline(admin.TabularInline):
form = ItemAddForm
fields = (..., 'my_new_field')
```
This works so far, I only need to override somehow the save method to handle this new field. See this: <http://docs.djangoproject.com/en/dev/ref/contrib/admin/#form> . It says that by default Inlines use BaseModelForm, which is send to formset\_factory. It doesn't work for me, tried to subclass BaseModelForm with errors (no attribute '\_meta'). So I use ModelForm instead. | How to add custom fields to InlineFormsets? | [
"",
"python",
"django",
"field",
"formset",
"inline-formset",
""
] |
I started off by drafting a question: "What is the best way to perform unit testing on a constructor (e.g., \_\_construct() in PHP5)", but when reading through the related questions, I saw several comments that seemed to suggest that setting member variables or performing any complicated operations in the constructor are no-nos.
The constructor for the class in question here takes a param, performs some operations on it (making sure it passes a sniff test, and transforming it if necessary), and then stashes it away in a member variable.
I thought the benefits of doing it this way were:
1) that client code would always be
certain to have a value for this
member variable whenever an object
of this class is instantiated, and
2) it saves a step in client code
(one of which could conceivably be
missed), e.g.,
```
$Thing = new Thing;
$Thing->initialize($var);
```
when we could just do this
```
$Thing = new Thing($var);
```
and be done with it.
Is this a no-no? If so why? | This comes up quite a lot in C++ discussions, and the general conclusion I've come to there has been this:
If an object does not acquire any external resources, members *must* be initialized *in* the constructor. This involves doing all work in the constructor.
* (x, y) coordinate (or really any other structure that's just a glorified tuple)
* US state abbreviation lookup table
If an object acquires resources that it can control, they *may* be allocated *in* the constructor:
* open file descriptor
* allocated memory
* handle/pointer into an external library
If the object acquires resources that it can't entirely control, they *must* be allocated *outside* of the constructor:
* TCP connection
* DB connection
* weak reference
There are always exceptions, but this covers most cases. | My rule of thumb is that an object should be ready for use after the constructor has finished. But there are often a number of options that can be tweaked afterwards.
My list of do's and donts:
* Constructors should set up basic options for the object.
* They should maybe create instances of helper objects.
* They should **not** aqquire resources(files, sockets, ...), unless the object clearly is a wrapper around some resource.
Of course, no rules without exceptions. The important thing is that you think about your design and your choises. Make object usage natural - and that includes error reporting. | What things are best not done in a constructor? | [
"",
"php",
"oop",
"constructor",
""
] |
I am working on a winforms application that uses Sybase Datawindow.net. Basically I have a datawindow that retrieves data (dw\_retailer.Retrieve(id)) and what I get back is an object list. The datawindow itself excists of labels and textboxes and I bind the data like this
```
newRetailer.foto1 = ((object[])(dataWindowControl.PrimaryData.Rows[0]))[7].ToString();
newRetailer.foto2 = ((object[])(dataWindowControl.PrimaryData.Rows[0]))[6].ToString();
```
What I want to do now is put a string into the object[] list like this
```
((object[])(_targetForm.dw_retailer.PrimaryData.Rows[0]))[5] = retailer.text;
```
But obviously that doesnt work.
```
((object[])(_targetForm.dw_retailer.PrimaryData.Rows[0])).SetValue(retailer.text,5);
```
That doenst work either (index out of range) altho it has 9 objects
```
_targetForm.dw_retailer.PrimaryData.Rows[0] {object[9]} object {object[]}
```
Tried it like this too
```
Array arrayList = _targetForm.dw_retailer.PrimaryData.Rows.ToArray();
arrayList.SetValue(retailer.text, 0,5);
```
Array is not multidimensional. Because I need the objects in the object so i need arrayList[0][5] but that doenst work either.
I don't even know if it is just a setting I have to select in the DataWindow Designer Application. How do I convert the array to object[] so I can put it back in the \_targetForm.dw\_retailer.PrimaryData.Rows. Is it even possible to edit the datawindows?
---
Still not working Marc
```
IList list = ((IList)(_targetForm.dw_retailer.PrimaryData.Rows[0]));
list[5] = retailer.text;
```
retailer.text has the value "tekst"
list[5] is unchanged.
It's not exactly adding an item, more like editting one. About the index out of range, I know there were only 8 items in the list, that's why I find it strange that the fifth is index out or range. Maybe I just dont understand .SetValue() that well.
Thanks for the IList tho! But how do I convert the IList back to object[]? | ```
_targetForm.dw_retailer.SetColumn(6);
_targetForm.dw_retailer.SetText(retailer.text);
_targetForm.dw_retailer.SetColumn(9);
_targetForm.dw_retailer.SetText(retailer.webname);
```
First you have to activate the control you want to edit with SetColumn and then call SetText.
Now everyone knows! | Re: converting list to object, you could just do it the manual way:
```
object[] objs = new object[list.count];
for (int i=0; i < list.Count; i++) {
objs[i] = list[i];
}
```
It's a bit gauche, but its intent is clear and it will work :-). | Convert an array to object[] | [
"",
"c#",
"sybase",
"datawindow",
""
] |
If I define a local variable instance of a class halfway down my function without using a pointer and new, does the constructor get called on entering the function or where it is defined?
If I define another instance of a class globally within the file does that constructor get called when executable is first loaded? What if multiple threads are accessing the .dll?
Finally is you answer going to be the same in .dll, .so, .exe and linux executables? | > If I define a local variable instance of a class halfway down my function without using a pointer and new, does the constructor get called on entering the function or where it is defined?
Such variables have local scope. Their constructor is called when they're defined. For local statics, the constructor is only called once, since the statics will survive multiple function calls and returns. The order is important, and is the order of definition:
```
void foo() {
....
if(cond) {
...
// called here: first for f, then for b
static Foo f;
static Bar b;
}
...
Foo f; // not static: called here, in every invocation of foo.
}
```
> If I define another instance of a class globally within the file does that constructor get called when executable is first loaded?
Yes, such variable is said to have static storage duration, and namespace scope. Its constructor is called at program start. The order is the order it is defined in the file. That is, a variable defined later will have its ctor called later. The order in which variables defined in different translation units is not defined (look-out for the *static initialization order fiasco*). But they are all called at program start.
> What if multiple threads are accessing the .dll?
All bets are off. The variable is only constructed once. After that, when you start threads and access it, the variable has to be thread safe, or the threads has to do proper locking when accessing the variable. | > If I define a local variable instance of a class halfway down my function without using a pointer and new, does the constructor get called o entering the function or where it is defined?
When it is defined.
> If I define another instance of a class globally within the file does that constructor get called when executable is first loaded?
Yes.
> What if multiple threads are accessing the .dll?
DLLs usually only get loaded once for the whole application – in fact, DLLs also have an entry point which is called by your application's threads but global variable initialization happens before that and only once. | When are constructors called? | [
"",
"c++",
"multithreading",
"locking",
""
] |
What are some good tools for getting a quick start for parsing and analyzing C/C++ code?
In particular, I'm looking for open source tools that handle the C/C++ preprocessor and language. Preferably, these tools would use lex/yacc (or flex/bison) for the grammar, and not be too complicated. They should handle the latest ANSI C/C++ definitions.
Here's what I've found so far, but haven't looked at them in detail (thoughts?):
* [CScope](http://cscope.sourceforge.net/) - Old-school C analyzer. Doesn't seem to do a full parse, though. Described as a glorified 'grep' for finding C functions.
* [GCC](http://gcc.gnu.org/) - Everybody's favorite open source compiler. Very complicated, but seems to do it all. There's a related project for creating GCC extensions called [GEM](http://research.alexeysmirnov.name/index.php?area=sec&proj=gem), but hasn't been updated since GCC 4.1 (2006).
* [PUMA](http://ivs.cs.uni-magdeburg.de/~puma/) - The PUre MAnipulator. (from the page: "The intention of this project is to
provide a library of classes for the analysis and manipulation of C/C++ sources. For this
purpose PUMA provides classes for scanning, parsing and of course manipulating C/C++
sources."). This looks promising, but hasn't been updated since 2001. Apparently PUMA has been incorporated into [AspectC++](http://www.aspectc.org/), but even this project hasn't been updated since 2006.
* Various C/C++ raw grammars. You can get [c-c++-grammars-1.2.tar.gz](http://www.sigala.it/sandro/software.php), but this has been unmaintained since 1997. A little Google searching pulls up other basic lex/yacc grammars that could serve as a starting place.
* Any others?
I'm hoping to use this as a starting point for translating C/C++ source into a new toy language.
Thanks!
-Matt
(Added 2/9): Just a clarification: I want to extract semantic information from the preprocessor in addition to the C/C++ code itself. I don't want "#define foo 42" to disappear into the integer "42", but remain attached to the name "foo". This, unfortunately, excludes several solutions that run the preprocessor first and only deliver the C/C++ parse tree) | Parsing C++ is extremely hard because the grammar is undecidable. To quote [Yossi Kreinin](http://www.yosefk.com/c++fqa/defective.html#defect-2):
> Outstandingly complicated grammar
>
> "Outstandingly" should be interpreted literally, because *all popular languages* have [context-free](http://en.wikipedia.org/wiki/Context-free_grammar) (or "nearly" context-free) grammars, while C++ has [undecidable](http://en.wikipedia.org/wiki/Undecidability) grammar. If you like compilers and parsers, you probably know what this means. If you're not into this kind of thing, there's a [simple example](http://www.yosefk.com/c++fqa/ctors.html#fqa-10.19) showing the problem with parsing C++: is `AA BB(CC);` an object definition or a function declaration? It turns out that the answer depends heavily on the code *before* the statement - the "context". This shows (on an intuitive level) that the C++ grammar is quite context-sensitive. | You can look at [clang](http://clang.llvm.org/StaticAnalysis.html) that uses llvm for parsing.
Support C++ fully now [link](http://clang.llvm.org/cxx_status.html) | Good tools for creating a C/C++ parser/analyzer | [
"",
"c++",
"c",
"parsing",
"yacc",
"lex",
""
] |
I have a little Java problem I want to translate to Python. Therefor I need a multidimensional array. In Java it looks like:
```
double dArray[][][] = new double[x.length()+1][y.length()+1][x.length()+y.length()+3];
dArray[0][0][0] = 0;
dArray[0][0][1] = POSITIVE_INFINITY;
```
Further values will be created bei loops and written into the array.
How do I instantiate the array?
PS: There is no matrix multiplication involved... | You can create it using nested lists:
```
matrix = [[a,b],[c,d],[e,f]]
```
If it has to be dynamic it's more complicated, why not write a small class yourself?
```
class Matrix(object):
def __init__(self, rows, columns, default=0):
self.m = []
for i in range(rows):
self.m.append([default for j in range(columns)])
def __getitem__(self, index):
return self.m[index]
```
This can be used like this:
```
m = Matrix(10,5)
m[3][6] = 7
print m[3][6] // -> 7
```
I'm sure one could implement it much more efficient. :)
If you need multidimensional arrays you can either create an array and calculate the offset or you'd use arrays in arrays in arrays, which can be pretty bad for memory. (Could be faster though…) I've implemented the first idea like this:
```
class Matrix(object):
def __init__(self, *dims):
self._shortcuts = [i for i in self._create_shortcuts(dims)]
self._li = [None] * (self._shortcuts.pop())
self._shortcuts.reverse()
def _create_shortcuts(self, dims):
dimList = list(dims)
dimList.reverse()
number = 1
yield 1
for i in dimList:
number *= i
yield number
def _flat_index(self, index):
if len(index) != len(self._shortcuts):
raise TypeError()
flatIndex = 0
for i, num in enumerate(index):
flatIndex += num * self._shortcuts[i]
return flatIndex
def __getitem__(self, index):
return self._li[self._flat_index(index)]
def __setitem__(self, index, value):
self._li[self._flat_index(index)] = value
```
Can be used like this:
```
m = Matrix(4,5,2,6)
m[2,3,1,3] = 'x'
m[2,3,1,3] // -> 'x'
``` | If you restrict yourself to the Python standard library, then a list of lists is the closest construct:
```
arr = [[1,2],[3,4]]
```
gives a 2d-like array. The rows can be accessed as `arr[i]` for `i` in `{0,..,len(arr}`, but column access is difficult.
If you are willing to add a library dependency, the [NumPy](https://numpy.org) package is what you really want. You can create a fixed-length array from a list of lists using:
```
import numpy
arr = numpy.array([[1,2],[3,4]])
```
Column access is the same as for the list-of-lists, but column access is easy: `arr[:,i]` for `i` in `{0,..,arr.shape[1]}` (the number of columns).
In fact NumPy arrays can be n-dimensional.
Empty arrays can be created with
```
numpy.empty(shape)
```
where `shape` is a tuple of size in each dimension; `shape=(1,3,2)` gives a 3-d array with size 1 in the first dimension, size 3 in the second dimension and 2 in the 3rd dimension.
If you want to store objects in a NumPy array, you can do that as well:
```
arr = numpy.empty((1,), dtype=numpy.object)
arr[0] = 'abc'
```
For more info on the NumPy project, check out the [NumPy homepage](https://numpy.org). | Multidimensional array in Python | [
"",
"python",
"arrays",
""
] |
I'm a bit new to WCF and I don't think I completely understand what the deal is with DataContracts. I have this 'RequestArray' class:
```
[DataContract]
public class RequestArray
{
private int m_TotalRecords;
private RequestRecord[] m_Record;
[System.Xml.Serialization.XmlElement]
[DataMember]
public RequestRecord[] Record
{
get { return m_Record; }
}
[DataMember]
public int TotalRecords
{
get { return m_TotalRecords; }
set {
if (value > 0 && value <= 100) {
m_TotalRecords = value;
m_Record = new RequestRecord[value];
for (int i = 0; i < m_TotalRecords; i++)
m_Record[i] = new RequestRecord();
}
}
}
}
```
The idea is when the client says `requestArray.TotalRecords=6;` the Record array will be allocated and initialized (I realize that I'm hiding an implementation behind an assignment, this is out of my control).
The problem is that when the client does this, the TotalRecord's set code is not called, breakpoints in the service confirm this as well. Rather, some sort of generic setter has been generated that is called instead. How do I get the client to use my setter instead?
EDIT:
It looks like I didn't quite get how the [DataContract] works, but it makes sense that the client wouldn't be executing this code. Like I mentioned in a comment, if I 'manually' do the work of the setter, I see that the set code does get executed right when I call the service function.
The serialization I'm still uncertain on. The contents of the RequestRecord[] array are not getting carried over. The Record class has setters/getters, I feel like I need a helper function somewhere to help it serialize the whole class.
Thanks all for your help! | The premise that the client proxy will execute the same code on the client and on the server is flawed because WCF is based on interfaces. I explain this point in bullet #2 below.
## Rules of Sharing WCF Interfaces & Implementation
If you want to share the implementation of the data contract you will need to factor the RequestArray class into a class library that holds NOTHING BUT the data contract classes, including presumably also the RequestRecord class.
Rules I live by:
1. Group all data contracts by themselves (100%) into one or more assemblies, no exceptions.
2. Group all service contracts into one or more assemblies.
3. Group all service types, i.e., the classes that implement the service contract, into one ore more assemblies.
4. Group all client channel proxies, i.e., the class that invokes the methods defined on the service contract interface, into one or more assemblies.
5. In a generic framework where all client software operates as a WCF service (I avoid duplex connections), it is safe to merge rules 2, 3 & 4 so that service contracts, service types and channel proxies are grouped together into one assembly.
*The main reason for separating the interfaces into a more flexible dependency chain is that it is possible to deploy a limited set of assemblies to the client without exposing unnecessary and potentially proprietary implementation details. Another reason is that it makes refactoring so much easier, especially in cases where you want to implement or extend a generic framework through inheritance or delegation.*
## Examining the Code
There are a few BIG problems with the code for RequestArray...
1. The setter logic will overwrite any of the modified elements of the m\_Record array variable when the DataContract instance is deserialized. This violates deserialization principles.
2. The Record property will not be able to be deserialized because the Record property on the RequestArray class is Read-only (since it lacks a setter). *Generally, I find that for DataContract classes the best approach for read-only properties is simply a method.* It is a bad idea to get into the habit of treating data contracts like they are anything more than bit buckets. What the attributes are basically doing is dynamically creating an interface definition specifically used for data serialization and deserialization. *I believe that it is a mistake to think of the data on the wire as objects. Rather, it is an opt-in way of specifying the relevant data parts of an object that need to persist over the wire.*
3. The TotalRecords property becomes dangerous if it ends up (correctly) just allowing the m\_TotalRecords variable to be set, since it will be totally independent of the internal array. In order for me to get this to work acceptably in my sample code (below), I had to shield the set with `if (m_TotalRecords == 0)`. In the sample code I have saved for future use, I comment out the TotalRecords property altogether, but I leave m\_TotalRecords just to illustrate that the private object is in fact preserved over the wire.
## Fixed Code
I adapted bendewey's sample code (thanks!) and came up with this complete test. Note: I had to define RequestRecord. Also, please see the code comments. If there are any bugs or anything that is unclear, please let me know.
```
#region WCFDataContractTest
[DataContract] // The enclosed type needs to also be attributed for WCF
public class RequestRecord
{
public RequestRecord() { }
[DataMember] // This is CRUCIAL, otherwise the Name property will not be preserved.
public string Name { get; set; }
}
[DataContract] // Encloses the RequestRecord type
public class RequestArray
{
private int m_TotalRecords; // should be for internal bookkeeping only
private RequestRecord[] m_Record;
[System.Xml.Serialization.XmlElement]
[DataMember]
public RequestRecord[] Record
{
get { return m_Record; }
// deserialization will not work without the set
set { m_Record = value; }
}
[DataMember] // is not really needed
public int TotalRecords
{
get { return m_TotalRecords; }
set
{
if (m_TotalRecords == 0)
m_TotalRecords = value;
}
}
// The constructor is not called by the deserialization mechanism,
// therefore this is the right place to specify the array size and to
// perform the array initialization.
public RequestArray(int totalRecords)
{
if (totalRecords > 0 && totalRecords <= 100)
{
m_TotalRecords = totalRecords;
m_Record = new RequestRecord[totalRecords];
for (int i = 0; i < m_TotalRecords; i++)
m_Record[i] = new RequestRecord() { Name = "Record #" + i.ToString() };
m_TotalRecords = totalRecords;
}
else
m_TotalRecords = 0;
}
}
public static void TestWCFDataContract()
{
var serializer = new DataContractSerializer(typeof(RequestArray));
var test = new RequestArray(6);
Trace.WriteLine("Array contents after 'new':");
for (int i = 0; i < test.Record.Length; i++)
Trace.WriteLine("\tRecord #" + i.ToString() + " .Name = " + test.Record[i].Name);
//Modify the record values...
for (int i = 0; i < test.Record.Length; i++)
test.Record[i].Name = "Record (Altered) #" + i.ToString();
Trace.WriteLine("Array contents after modification:");
for (int i = 0; i < test.Record.Length; i++)
Trace.WriteLine("\tRecord #" + i.ToString() + " .Name = " + test.Record[i].Name);
using (var ms = new MemoryStream())
{
serializer.WriteObject(ms, test);
ms.Flush();
ms.Position = 0;
var newE = serializer.ReadObject(ms) as RequestArray;
Trace.WriteLine("Array contents upon deserialization:");
for (int i = 0; i < newE.Record.Length; i++)
Trace.WriteLine("\tRecord #" + i.ToString() + " .Name = " + newE.Record[i].Name);
}
}
#endregion
```
The listing for this sample program, after running TestWCFDataContract is:
Array contents after 'new':
```
Record #0 .Name = Record #0
Record #1 .Name = Record #1
Record #2 .Name = Record #2
Record #3 .Name = Record #3
Record #4 .Name = Record #4
Record #5 .Name = Record #5
```
Array contents after modification:
```
Record #0 .Name = Record (Altered) #0
Record #1 .Name = Record (Altered) #1
Record #2 .Name = Record (Altered) #2
Record #3 .Name = Record (Altered) #3
Record #4 .Name = Record (Altered) #4
Record #5 .Name = Record (Altered) #5
```
Array contents upon deserialization:
```
Record #0 .Name = Record (Altered) #0
Record #1 .Name = Record (Altered) #1
Record #2 .Name = Record (Altered) #2
Record #3 .Name = Record (Altered) #3
Record #4 .Name = Record (Altered) #4
Record #5 .Name = Record (Altered) #5
``` | I just ran a little test and it called the setter. How are you deserializing the objects?
```
class Program
{
static void Main(string[] args)
{
var serializer = new DataContractSerializer(typeof(Employee));
var employee = new Employee() { Name="Joe" };
using (var ms = new MemoryStream())
{
serializer.WriteObject(ms, employee);
ms.Flush();
ms.Position = 0;
var newE = serializer.ReadObject(ms) as Employee;
}
Console.ReadKey();
}
}
[DataContract]
public class Employee
{
private string _name;
[DataMember]
public string Name
{
get { return _name; }
set { _name = value; }
}
}
``` | WCF [DataContract] set/get not getting executed | [
"",
"c#",
"wcf",
""
] |
I don't know much about database optimization, but I'm trying to understand this case.
Say I have the following table:
```
cities
===========
state_id integer
name varchar(32)
slug varchar(32)
```
Now, say I want to perform queries like this:
```
SELECT * FROM cities WHERE state_id = 123 AND slug = 'some_city'
SELECT * FROM cities WHERE state_id = 123
```
If I want the "slug" for a city to be unique within its particular state, I'd add a unique index on state\_id and slug.
Is that index enough? Or should I also add another on state\_id so the second query is optimized? Or does the second query automatically use the unique index?
I'm working on PostgreSQL, but I feel this case is so simple that most DBMS work similarly.
Also, I know this surely doesn't make a difference on small tables, but my example is a simple one. Think of 200k+ rows tables.
Thanks! | A single unique index on (state\_id, slug) should be sufficient. To be sure, of course, you'll need to run EXPLAIN and/or ANALYZE (perhaps with the help of something like <http://explain.depesz.com/>), but ultimately what indexes are appropriate depends very closely on what kind of queries you will be running. Remember, indexes make SELECTs faster and INSERTs, UPDATEs, and DELETEs slower, so you ideally want only as many indexes as are actually necessary.
Also, PostgreSQL has a smart query optimizer: it will use radically different search plans for queries on small tables and huge tables. If the table is small, it will just do a sequential scan and not even bother with *any* indexes, since the overhead of working with them is higher than just brute-force sifting through the table. This changes to a different plan once the table size passes a threshold, and may change again if the table gets larger again, or if you change your SELECT, or....
Summary: you can't trust the results of EXPLAIN and ANALYZE on datasets much smaller or different than your actual data. Make it work, then make it fast later (if you need to). | **[EDIT: Misread the question... Hopefully my answer is more relevant now!]**
In your case, I'd suggest 1 index on `(state_id, slug)`. If you ever need to search just by `slug`, add an index on just that column. If you have those, then adding another index on `state_id` is unnecessary as the first index already covers it.
An index can be used whenever an **initial segment of its columns are used** in a WHERE clause. So e.g. an index on columns A, B and C will optimise queries containing WHERE clauses involving A, B and C, WHERE clauses with just A and B, or WHERE clauses with just A. Note that the order that columns appear in the index definition is very important -- this example index cannot be used for WHERE clauses involving just B and/or C.
(Of course it's up to the query optimiser whether or not a particular index actually gets used, but in your case with 200k rows, you can guarantee that a simple search by `state_id` or `slug` or both will use one of the indices.) | Unique index on two columns plus separate index on each one? | [
"",
"sql",
"optimization",
"indexing",
""
] |
MS SQL Server doesn't have row level triggers, correct? If I needed to insert a row from within a trigger and then insert another row, based on the result of the first insert, would a cursor be the best solution?
For example, is there a better way to do this:
```
CREATE TABLE t1 (foo int)
CREATE TABLE t2 (id int IDENTITY, foo int)
CREATE TABLE t3 (t2_id int)
GO
CREATE TRIGGER t1_insert_trg ON t1 FOR INSERT AS
DECLARE c CURSOR FOR
SELECT foo FROM inserted
DECLARE @foo int
OPEN c
FETCH NEXT FROM c INTO @foo
WHILE @@FETCH_STATUS = 0
BEGIN
INSERT INTO t2 (foo) VALUES (@foo)
INSERT INTO t3 (t2_id) VALUES (@@IDENTITY)
FETCH NEXT FROM c INTO @foo
END
CLOSE c
DEALLOCATE c
``` | I assume you are on 2005 or better? If so, look into the OUTPUT clause, you shouldn't need row-level triggers. For example:
```
USE tempdb;
GO
CREATE TABLE t1 (foo int);
CREATE TABLE t2 (id int IDENTITY, foo int);
CREATE TABLE t3 (t2_id int);
GO
CREATE TRIGGER t1_insert ON t1
FOR INSERT AS
BEGIN
DECLARE @new_rows TABLE(new_id INT, old_foo INT);
INSERT t2(foo)
OUTPUT inserted.id, inserted.foo
INTO @new_rows
SELECT foo
FROM inserted;
INSERT t3 SELECT new_id FROM @new_rows;
END
GO
INSERT t1(foo) SELECT 1 UNION ALL SELECT 5;
SELECT * FROM t1;
SELECT * FROM t2;
SELECT * FROM t3;
GO
DROP TABLE t1,t2,t3;
```
You could also manage this by having a trigger on T1 that inserts into T2, then a trigger on T2 that inserts into T3. This isn't going to be as efficient IMHO, and is not easier to manage, but I will submit that it is easier to follow (and may be your only option if you are stuck on 2000). Both could be set-based and wouldn't need cursors or any other row-by-row processing method.
```
USE tempdb;
GO
CREATE TABLE t1 (foo int);
CREATE TABLE t2 (id int IDENTITY, foo int);
CREATE TABLE t3 (t2_id int);
GO
CREATE TRIGGER t1_insert ON t1
FOR INSERT AS
BEGIN
INSERT t2(foo)
SELECT foo FROM inserted;
END
GO
CREATE TRIGGER t2_insert ON t2
FOR INSERT AS
BEGIN
INSERT t3(t2_id)
SELECT id FROM inserted;
END
GO
INSERT t1(foo) SELECT 1 UNION ALL SELECT 5;
SELECT * FROM t1;
SELECT * FROM t2;
SELECT * FROM t3;
GO
DROP TABLE t1,t2,t3;
```
(BTW, if you are going for identity values, use SCOPE\_IDENTITY(), not @@IDENTITY.) | You might be able to avoid a cursor or the need to know what identity was inserted using the following inserts.
```
Insert INTO t2 (foo) Select foo from inserted
Insert into t3 (t2_id) Select t2.id from t2
inner join inserted i on t2.foo = i.foo
``` | Alternative to row level triggers? | [
"",
"sql",
"sql-server",
"triggers",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.