Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm trying to find a way to make a list of everything between `<a>` and `</a>` tags. So I have a list of links and I want to get the names of the links (not where the links go, but what they're called on the page). Would be really helpful to me.
Currently I have this:
```
$lines = preg_split("/\r?\n|\r/", $content); // content is the given page
foreach ($lines as $val) {
if (preg_match("/(<A(.*)>)(<\/A>)/", $val, $alink)) {
$newurl = $alink[1];
// put in array of found links
$links[$index] = $newurl;
$index++;
$is_href = true;
}
}
``` | The standard disclaimer applies: Parsing HTML with regular expressions is not ideal. Success depends on the well-formedness of the input on a character-by-character level. If you cannot guarantee this, the regex will fail to do the Right Thing at some point.
Having said that:
```
<a\b[^>]*>(.*?)</a> // match group one will contain the link text
``` | I'm a big fan of regexes, but this is not the right place to use them.
Use a real HTML parser.
* Your code will be clearer
* It will be more likely to work
I Googled for a PHP HTML parser, and found [this one](http://sourceforge.net/projects/simplehtmldom/).
If you know you're working with XHTML, then you could use PHP's standard XML parser. | regexp for finding everything between <a> and </a> tags | [
"",
"php",
"regex",
""
] |
I have a directory on a linux box that I want to make publicly readable using Tomcat (5.5). I think this is easy to set up but can't find the appropriate documentation. Is there a simple way to accomplish this? | Although Tomcat is a good web server, it's not particularly made to list directories.
You might want to look at a web server like the [Apache](http://www.apache.org/) web server instead, it's more designed for this type of thing. | It is possible by defining that directory as an web application, but it's not really what Tomcat is designed to do, other servers are far better at serving static content.
The way to define a directory as a webapp is to either
* put it into `$TOMCAT_HOME/webapps`,
* configure it in `$TOMCAT_HOME/conf/server.xml` or
* provide a context `.xml` file and put it in `$TOMCAT_HOME/conf/Catalina/localhost` (by default, depends on your configuration). | Use Tomcat to serve a directory? | [
"",
"java",
"tomcat",
"file",
""
] |
I have a page with a `document.onkeydown` event handler, and I'm loading it inside an iframe in another page. I have to click inside the iframe to get the content page to start "listening".
Is there some way I can use JavaScript in the outer page to set the focus to the inner page so I don't have to click inside the iframe?
EDIT: response to comment:
The context is the main window is a light-box-like system, except instead of pictures, it shows iframes, and each iframe is an interactive page with keydown/mousemove handlers. these handlers don't fire until I click in the iframe after showing the light-box-thing.
I'm not actually looking to "setFocus" in the traditional sense as much as "enable event handlers on the iframe contentDocument" | I had a similar problem with the jQuery Thickbox (a lightbox-style dialog widget). The way I fixed my problem is as follows:
```
function setFocusThickboxIframe() {
var iframe = $("#TB_iframeContent")[0];
iframe.contentWindow.focus();
}
$(document).ready(function(){
$("#id_cmd_open").click(function(){
/*
run thickbox code here to open lightbox,
like tb_show("google this!", "http://www.google.com");
*/
setTimeout(setFocusThickboxIframe, 100);
return false;
});
});
```
The code doesn't seem to work without the setTimeout(). Based on my testing, it works in Firefox3.5, Safari4, Chrome4, IE7 and IE6. | Using the contentWindow.focus() method, the timeout is probably necessary to wait for the iframe to be completely loaded.
For me, also using attribute `onload="this.contentWindow.focus()"` works, with firefox, into the iframe tag | Setting focus to iframe contents | [
"",
"javascript",
"dom",
"iframe",
"setfocus",
""
] |
Ok, bear with me guys and girls as I'm learning. Here's my question.
I can't figure out why I can't override a method from a parent class. Here's the code from the base class (yes, I pilfered the java code from an OOP book and am trying to rewrite it in C#).
```
using System;
public class MoodyObject
{
protected String getMood()
{
return "moody";
}
public void queryMood()
{
Console.WriteLine("I feel " + getMood() + " today!");
}
}
```
and here are my other 2 objects that inherit the base class (MoodyObject):
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class SadObject: MoodyObject
{
protected String getMood()
{
return "sad";
}
//specialization
public void cry()
{
Console.WriteLine("wah...boohoo");
}
}
}
```
And:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class HappyObject: MoodyObject
{
protected String getMood()
{
return "happy";
}
public void laugh()
{
Console.WriteLine("hehehehehehe.");
}
}
}
```
and here is my main:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
MoodyObject moodyObject = new MoodyObject();
SadObject sadObject = new SadObject();
HappyObject happyObject = new HappyObject();
Console.WriteLine("How does the moody object feel today?");
moodyObject.queryMood();
Console.WriteLine("");
Console.WriteLine("How does the sad object feel today?");
sadObject.queryMood();
sadObject.cry();
Console.WriteLine("");
Console.WriteLine("How does the happy object feel today?");
happyObject.queryMood();
happyObject.laugh();
}
}
}
```
As you can see, pretty basic stuff, but here's the output:
> How does the moody object feel today?
> I feel moody today!
>
> How does the sad object feel today? I
> feel moody today! wah...boohoo
>
> How does the happy object feel today?
> I feel moody today! hehehehehehe.
> Press any key to continue . . .
Not as I expected. I've tried to make the base method virtual and calling override when trying to override it and that just gets me this error "cannot override inherited member 'MoodyObject.getMood()' because it is not marked virtual, abstract, or override". I also tried it without the virtual and override and it thinks I'm trying to hide the base method. Again, I'm new to OOP and would appreciate any guidance.
**EDITED TO ADD: I found it! The MoodyObject.cs was only a "solution item" in the solution explorer as opposed to a "ConsoleApplication1" item. I dragged it down to where it belonged in the solution explorer and voila! It works now. I marked Luc's answer below as the answer because he offered the help I needed to get to where I have it resolved... I'm learning so much here. It's amazing and you guys and girls are crazy smart!** | In C# methods are not virtual by default, so if you design some method as overridable, you should specify it as virtual:
```
class Base
{
protected virtual string GetMood() {...}
}
```
Second, you have to specify that you are going to override method from base class in derived class.
```
class Derived : Base
{
protected override string GetMood() {...}
}
```
If you don't specify "override" keyword, you will get method that hides base type (and warning from compiler to put "new" keyword for the method to explicitly state so).
If you want to stop inheritance chain and disallow further overrides of the method, you should mark method as sealed, like this:
```
protected sealed override string GetMood() {...}
``` | You need to use the override keyword to override any virtual or implement any abstract methods.
```
public class MoodyObject
{
protected virtual String getMood()
{
return "moody";
}
public void queryMood()
{
Console.WriteLine("I feel " + getMood() + " today!");
}
}
public class HappyObject : MoodyObject
{
protected override string getMood()
{
return "happy";
}
}
```
What I would recommend here is that you probally meant for MoodyObject to be an abstract class. (You'd have to change your main method if you do this but you should explore it) Does it really make sense to be in a moody mode? The problem with what we have above is that your HappyObject is not required to provide an implementation for getMood.By making a class abstract it does several things:
1. You cannot new up an instance of an abstract class. You have to use a child class.
2. You can force derived children to implement certain methods.
So to do this you end up:
```
public abstract class MoodyObject
{
protected abstract String getMood();
public void queryMood()
{
Console.WriteLine("I feel " + getMood() + " today!");
}
}
```
Note how you no longer provide an implementation for getMood. | Overriding and Inheritance in C# | [
"",
"c#",
"inheritance",
"overriding",
""
] |
I was wondering if something exists (in Java world) able to take an snapshot of the JVM current state with the following features:
* Do it while an exception is being thrown.
* Capture local variables, method's arguments, etc.
* Put it in a handy file which can be used to extract or reproduce in a IDE the situation in your source code.
The two first features are required (third would be awesome). And it must be suitable for production use (so, there is no way about debuggers).
Before asking this I've searched through the WWW (as long as possible) and I found some pointers:
* [Cajoon Interceptor](http://www.cajoon.com): As said in [Dzone post](http://www.dzone.com/links/java_production_errors_rapid_resolution.html), it's a passive JVM agent which fulfill the three requirements! But, it has two downsides: you must pay for it and the site is down (maybe there is no chance to pay anything).
* [AviCode Intercept Studio](http://www.avicode.com/): Cajoon's .NET equivalent. Just to give some insight about.
* [JavaFrame](http://twitter.com/thobe/status/1012650896): Ok, it's a tweet, but it points to a available SVN repo which have the source code (under MIT license) of a JVM agent which looks fine (I'm going to give a try to it).
So, maybe I'm looking for a non existent solution? It's not urgent, but I had this idea for a project and it would be great to explore this "unknown" (?) path and get something real.
It seems to be clear that it would be a JVM agent (exception event from JVMTI, for [example](http://java.sun.com/developer/technicalArticles/Programming/jvmti/)).
At last, I would highlight the followin paragraph from [Wikipedia's Exception Handling article](http://en.wikipedia.org/wiki/Exception_handling):
> In runtime engine environments such as
> Java or .NET, there exist tools that
> attach to the runtime engine and every
> time that an exception of interest
> occurs, they record debugging
> information that existed in memory at
> the time the exception was thrown
> (call stack and heap values). These
> tools are called Automated Exception
> Handling or Error Interception tools
> and provide 'root-cause' information
> for exceptions.
That's the idea. I hope somebody can give me some insight or maybe, in the future, somebody get inspired by this humble post :)
Thanks! | I give a look to [JavaFrame](http://kenai.com/projects/jvm-frame-introspect) and it seems a good starting point. Just install Apache Ant, do `ant` in the javaframe directory and launch the test suite (inside test directory) with:
```
LD_LIBRARY_PATH=../build/native/ java -agentlib:frameintrospect -classpath ../build/classes/:. org.thobe.frame.Test
```
It does not get any local variable but it tries. So, as I said, it can be an starting point. I hope to get further about its usage, but no time and no documentation (there are lots of projects named JavaFrame) are bad circumstances.
Maybe some day it can be done again. Yes, again. There was Cajoon, it looked promising and shiny but its website is down and there is no trace of any downloadable jar to try.
Thanks to everybody!
PD.: Just for reference, some links I found while researching:
* [How VM Agents Work](http://blogs.oracle.com/kto/entry/using_vm_agents)
* [JVM options](http://blogs.oracle.com/watt/resource/jvm-options-list.html) | You may want to look into the work that NetBeans has done regarding automated use logging: <http://wiki.netbeans.org/UsageLoggingSpecification>.
As for dumping out local variables, I would imagine that you could simply use a debugger, such as the one that bajafresh4life mentioned. | Automated Exception Handling | [
"",
"java",
"exception",
"jvm",
"agent",
""
] |
I know this maybe a very basic question but I'm having a bit of a mind blank at the moment. Should I be unit testing this class.
```
public class MapinfoWindowHandle : IWin32Window
{
IntPtr handle;
public MapinfoWindowHandle(IntPtr mapinfoHandle)
{
this.handle = mapinfoHandle;
}
#region IWin32Window Members
IntPtr IWin32Window.Handle
{
get { return this.handle; }
}
#endregion
}
```
If I should be what should I be testing for?
I use it like this:
```
IntPtr handle = new IntPtr(100);
myform.show(new MapinfoWindowHandle(handle));
``` | The only thing that I can see is making sure you get out the handle that you put in via your constructor. I know that it's obvious that you implemented it this way, but a test would assure you that it stays this way. I would test this only because you are injecting it via the constructor. If it was just { get; set; } I probably wouldn't.
```
[TestMethod]
public void ConstructorTest()
{
IntPtr handle = new IntPtr(100);
MapinfoWindowHandle winHandle = new MapinfoWindowHandle(handle);
Assert.AreEqual( handle, ((IWin32Window)winHandle).Handle );
}
``` | I'd certainly test for trying to construct it with a NULL (0) or INVALID\_HANDLE\_VALUE (-1) and probably have it throw on either/both if appropriate (it's unclear if it's ok to initialize the class with an IntPtr.Zero, but it's almost certain that a -1 would be invalid. | Should I be unit testing this class? | [
"",
"c#",
"unit-testing",
"testing",
""
] |
I'm using a `DateTime` in C# to display times. What date portion does everyone use when constructing a time?
E.g. the following is not valid because there is no zero-th month or zero-th day:
```
// 4:37:58 PM
DateTime time = new DateTime(0, 0, 0, 16, 47, 58);
```
Do I use COM's zero date?
```
// 4:37:58 PM
DateTime time = new DateTime(1899, 12, 30, 16, 47, 58);
```
Or perhaps SQL Server's?
```
//4:37:58 PM
DateTime time = new DateTime(1900, 1, 1, 16, 47, 58);
```
I realize it's arbitrary, since I'll be ignoring the date portions in code, but it would still be nice to be able to use:
```
DateTime duration = time2 - time1;
```
---
# Answer
I think I like **MinValue**
```
DateTime time = DateTime.MinValue.Date.Add(new TimeSpan(16, 47, 58));
```
---
**Note:** I can't use a `TimeSpan`, because that doesn't store times of the day. And the reason I know that is because there's no way to display its contents as a time.
Which is to say that `TimeSpan` records a *span of time*, not a *time of day*, e.g.:
```
TimeSpan t = new TimeSpan(16, 47, 58);
t.ToString();
```
returns a span of time in the format *hours*:*minutes*:*seconds*, e.g.:
```
16:47:58
```
rather than a time:
```
4:47:58 PM (United States)
04:47:58 nm (South Africa)
4:47:58.MD (Albania)
16:47:58 (Algeria)
04:47:58 م (Bahrain)
PM 4:47:58 (Singapore)
下午 04:47:58 (Taiwan)
04:47:58 PM (Belize)
4:47:58 p.m. (New Zealand)
4:47:58 μμ (Greece)
16.47.58 (Italy)
오후 4:47:58 (Korea)
04:47:58 ب.ظ (Iran)
ਸ਼ਾਮ 04:47:58 (India)
04:47:58 p.m. (Argentina)
etc
```
In other words, there is a difference between a timespan, and a time. And also realize that `TimeSpan` doesn't provide a mechanism to convert a span of time into a time of day - and there is a reason for that. | what about DateTime.MinValue? | Let's help out the guys who want a Time structure:
```
/// <summary>
/// Time structure
/// </summary>
public struct Time : IComparable
{
private int minuteOfDay;
public static Time Midnight = "0:00";
private static int MIN_OF_DAY = 60 * 24;
public Time(int minuteOfDay)
{
if (minuteOfDay >= (60 * 24) || minuteOfDay < 0)
throw new ArgumentException("Must be in the range 0-1439", "minuteOfDay");
this.minuteOfDay = minuteOfDay;
}
public Time(int hour, int minutes)
{
if (hour < 0 || hour > 23)
throw new ArgumentException("Must be in the range 0-23", "hour");
if (minutes < 0 || minutes > 59)
throw new ArgumentException("Must be in the range 0-59", "minutes");
minuteOfDay = (hour * 60) + minutes;
}
#region Operators
public static implicit operator Time(string s)
{
var parts = s.Split(':');
if (parts.Length != 2)
throw new ArgumentException("Time must be specified on the form tt:mm");
return new Time(int.Parse(parts[0]), int.Parse(parts[1]));
}
public static bool operator >(Time t1, Time t2)
{
return t1.MinuteOfDay > t2.MinuteOfDay;
}
public static bool operator <(Time t1, Time t2)
{
return t1.MinuteOfDay < t2.MinuteOfDay;
}
public static bool operator >=(Time t1, Time t2)
{
return t1.MinuteOfDay >= t2.MinuteOfDay;
}
public static bool operator <=(Time t1, Time t2)
{
return t1.MinuteOfDay <= t2.MinuteOfDay;
}
public static bool operator ==(Time t1, Time t2)
{
return t1.GetHashCode() == t2.GetHashCode();
}
public static bool operator !=(Time t1, Time t2)
{
return t1.GetHashCode() != t2.GetHashCode();
}
/// Time
/// Minutes that remain to
/// Time conferred minutes
public static Time operator +(Time t, int min)
{
if (t.minuteOfDay + min < (24 * 60))
{
t.minuteOfDay += min;
return t;
}
else
{
t.minuteOfDay = (t.minuteOfDay + min) % MIN_OF_DAY;
return t;
}
}
public static Time operator -(Time t, int min)
{
if (t.minuteOfDay - min > -1)
{
t.minuteOfDay -= min;
return t;
}
else
{
t.minuteOfDay = MIN_OF_DAY + (t.minuteOfDay - min);
return t;
}
}
public static TimeSpan operator -(Time t1, Time t2)
{
return TimeSpan.FromMinutes(Time.Span(t2, t1));
}
#endregion
public int Hour
{
get
{
return (int)(minuteOfDay / 60);
}
}
public int Minutes
{
get
{
return minuteOfDay % 60;
}
}
public int MinuteOfDay
{
get { return minuteOfDay; }
}
public Time AddHours(int hours)
{
return this + (hours * 60);
}
public int CompareTo(Time other)
{
return this.minuteOfDay.CompareTo(other.minuteOfDay);
}
#region Overrides
public override int GetHashCode()
{
return minuteOfDay.GetHashCode();
}
public override string ToString()
{
return string.Format("{0}:{1:00}", Hour, Minutes);
}
#endregion
///
/// Safe enumerering - whatever interval applied max days
///
/// Start time
/// Spring in minutes
///
public static IEnumerable Range(Time start, int step)
{
return Range(start, start, step);
}
///
/// Safe enumeration - whatever interval applied max days
///
public static IEnumerable Range(Time start, Time stop, int step)
{
int offset = start.MinuteOfDay;
for (var i = 0; i < Time.Span(start, stop); i += step)
{
yield return Time.Midnight + (i + offset);
}
}
///
/// Calculates the number of minutes between t1 and t2
///
public static int Span(Time t1, Time t2)
{
if (t1 < t2) // same day
return t2.MinuteOfDay - t1.MinuteOfDay;
else // over midnight
return MIN_OF_DAY - t1.MinuteOfDay + t2.MinuteOfDay;
}
}
``` | C# DateTime: What "date" to use when I'm using just the "time"? | [
"",
"c#",
"datetime",
"time",
""
] |
I hate to have to ask, but I'm pretty stuck here.
I need to test a sequence of numbers to find the first which has over 500 factors:
<http://projecteuler.net/index.php?section=problems&id=12>
-At first I attempted to brute force the answer (finding a number with 480 after a LONG time)
-I am now looking at determining the prime factors of a number and then use them to find all other factors.
I am currently at the stage where I can get an array of prime factors for any number I input - i.e 300 has the prime factors 2 2 3 5 5
Using this array of prime factors I need to be able to calculate the remaining factors - This is the part I am stuck on. Basically, as I understand it, I need to calculate ALL possible combinations of the numbers in the array...
i.e
2 \* 2
2 \* 2 \* 3
2 \* 2 \* 3 \* 5
2 \* 3
2 \* 3 \* 3
...and so forth - But where it gets interesting is with things like...
2 \* 5
2 \* 3 \* 5
...i.e Numbers which are not adjacent to each other in the array
I can't think of a way to code this in a generic fashion for any length array...
I need help! P.S - I am working in Java
EDIT: My brute force code - As it has been suggested brute forcing the problem will work and so there may be an error in my code :(
```
package euler.problem12;
public class Solution {
public static void main(String[] args) {
int next = 1;
int triangle = 0;
int maxFactors = 0;
while(true) {
triangle = triangle + next;
int factors = 1;
int max = (int) triangle / 2;
for(int i = 1; i <= max; ++i) {
if(triangle % i == 0) {
factors ++;
}
}
if(factors > maxFactors) {
maxFactors = factors;
System.out.println(triangle + "\t" + factors);
}
next++;
}
}
}
``` | As far as I can tell, question 12 doesn't mention anything about prime numbers? Is this the one you're looking at?
> The sequence of triangle numbers is generated by adding the natural numbers...
If so, then perhaps not thinking about primes will help? ;) | OK, second attempt as I was making things far too difficult.
Answer is given here: [Link](https://web.archive.org/web/20171117010511/http://mathforum.org/library/drmath/view/57151.html)
> If you factor a number into its prime
> power factors, then the total number
> of factors is found by adding one to
> all the exponents and multiplying
> those results together. Example: 108 =
> 2^2 \* 3^3, so the total number of
> factors is (2+1) \* (3+1) = 3 \* 4 = 12.
> Sure enough, the factors of 108 are 1,
> 2, 3, 4, 6, 9, 12, 18, 27, 36, 54, and
> 108. This happens because to be a factor, a number must have the same
> primes, and raised to the same or lower powers.
So if you know the prime factors, you just need to count the repeated ones and use the above calculation to work out the number of factors. | Euler Project Help (Problem 12) - Prime Factors and the like | [
"",
"java",
""
] |
I have inherited a application framework from the previous developer where I now work. This framework utilizes multiple parent/child relationships. In many instances parent/parent/child occur. I asked why he WASN'T using MDI and he stated that years ago, when he had started, MDI had major shortcomings concerning the previously stated relationship scenarios. Particularly with the multiple Parents.
My actual questions are; Does MDI still have these shortcomings? & Those of you who have worked with MDI, what problems did you have and how did you overcome them?
Thank You! | One problem with MDI interfaces is that you can't register unlimited Window's within your MDI Containers anyway (see [This Microsoft KB item](http://support.microsoft.com/kb/126962)). Thought i posted that up because i've seen many MDI applications hit that error when its heavily used.
I generally like an SDI Interface and make it share the same controls and windows over multiple instances of 'something' instead of spawning a new Window for each instance of 'something'.
I dont know the specifics of the programs interface but i've yet to find something that couldnt be reworked to an SDI interface and some modal dialogs (if really needed). | I really think it's a shortcoming of the app you've inherited that it requires the multiple parents (hello tightly coupled app!).
I once worked on an app (knock on wood that I won't have to go back to supporting it anytime soon) that was coupled probably a lot like yours is now. Had the original author simply used delegates instead of "this.Parent.Parent.Parent.functionX" we may have been able to make greater strides in fixing that app's shortcomings (and delegates may not have even been the way to go...).
As for MDI, I prefer it personally but I can't speak for the shortcomings your original developer found because I try to design around having the relationships he/she needed. | MDI Pros & Cons | [
"",
"c#",
".net",
"winforms",
"mdi",
""
] |
I am curious to know where the "Don't Fragment" [DF] Bit of the IP Flags is used. As fragmentation is invisible to higher layers and they don't care too.
I am also looking for an example.
Thanks a lot in advance. | Fragmentation is not always invisible to all upper layers. Some early (and probably even current) micro-controller TCP/IP stacks did not implement the full capabilities such as fragmentation handling. Use of the flag in that situation would ensure that the packet arrived in its original form instead of a lot of fragments which the other end couldn't handle.
In addition, when using UDP, it's not necessary for all the fragments to arrive at the destination so, preventing fragmentation means the message either arrives or doesn't arrive - there is no possibility that only a bit of the UDP datagram will reach the destination. I can't recall how long the TCP/IP stack held on to unassembled IP packets waiting for missing fragments, but use of the DF flag meant there were no unnecessary resources tied up during that time.
Finally, you can use it for testing behavior of network infrastructure, such as what happens when you get a packet that's bigger than the maximum transmission unit (DF will prevent that packet from being fragmented to 'squeeze through' the hole). | In addition to [@Pax's answer](https://stackoverflow.com/questions/351806/where-is-the-dont-fragment-bit-of-the-ip-flags-used/351894#351894) (or perhaps as part of the testing he mentioned), the DP flag is also used in [path MTU discovery](http://www.netheaven.com/pmtu.html). This is when you try to figure out what the largest packet that can be sent without being fragmented is, for a given link.
It is often useful to avoid fragmentation, even though higher-level protocols are in theory isolated from the mechanics of it, they can still "feel" the consequences. If a single application-level `write()` to the network socket ends up being fragmented because it is too large, and one of the fragments is lost in the network, the entire IP packet will be lost. This of course affects throughput.
For this reason, it is often desirable to know the *maximum transmission unit*, i.e. the largest packet that can be sent to a destination without being fragmented. Path MTU discovery is used to find this size, by simply setting the DF bit and sending successively larger packets until the network reports (over [ICMP](http://en.wikipedia.org/wiki/Internet_Control_Message_Protocol)) a failure. | Where is the Don't Fragment Bit of the IP Flags used? | [
"",
"c++",
"c",
"networking",
"network-programming",
"network-protocols",
""
] |
What are your favorite C++ coding style idioms? I'm asking about style or coding typography such as where you put curly braces, are there spaces after keywords, the size of indents, etc. This is opposed to best-practices or requirements such as always deleting arrays with `delete[]`.
Here is an example of one of my favorites: In C++ Class initializers, we put the separators at the front of the line, rather than the back. This makes it easier to keep this up to date. It also means that source code control diffs between versions are cleaner.
```
TextFileProcessor::
TextFileProcessor( class ConstStringFinder& theConstStringFinder )
: TextFileProcessor_Base( theConstStringFinder )
, m_ThreadHandle ( NULL )
, m_startNLSearch ( 0 )
, m_endNLSearch ( 0 )
, m_LineEndGetIdx ( 0 )
, m_LineEndPutIdx ( 0 )
, m_LineEnds ( new const void*[ sc_LineEndSize ] )
{
;
}
``` | When creating enumerations, put them in a namespace so that you can access them with a meaningful name:
```
namespace EntityType {
enum Enum {
Ground = 0,
Human,
Aerial,
Total
};
}
void foo(EntityType::Enum entityType)
{
if (entityType == EntityType::Ground) {
/*code*/
}
}
```
**EDIT**: However, this technique has become obsolete in C++11. *Scoped enumeration* (declared with `enum class` or `enum struct`) should be used instead: it is more type-safe, concise, and flexible. With old-style enumerations the values are placed in the outer scope. With new-style enumeration they are placed within the scope of the `enum class` name.
Previous example rewritten using scoped enumeration (also known as *strongly typed enumeration*):
```
enum class EntityType {
Ground = 0,
Human,
Aerial,
Total
};
void foo(EntityType entityType)
{
if (entityType == EntityType::Ground) {
/*code*/
}
}
```
There are other significant benefits from using scoped enumerations: absence of implicit cast, possible forward declaration, and ability to use custom underlying type (not the default `int`). | ## RAII: Resource Acquisition Is Initialization
RAII may be the most important idiom. It is the idea that resources should be mapped to objects, so that their lifetimes are managed automatically according to the scope in which those objects are declared.
For example, if a file handle was declared on the stack, it should be implicitly closed once we return from the function (or loop, or whichever scope it was declared inside). If a dynamic memory allocation was allocated as a member of a class, it should be implicitly freed when that class instance is destroyed. And so on. Every kind of resource—memory allocations, file handles, database connections, sockets, and any other kind of resource that has to be acquired and released—should be wrapped inside such a RAII class, whose lifetime is determined by the scope in which it was declared.
One major advantage of this is that C++ guarantees that destructors are called when an object goes out of scope, *regardless of how control is leaving that scope*. Even if an exception is thrown, all local objects will go out of scope, and so their associated resources will get cleaned up.
```
void foo() {
std::fstream file("bar.txt"); // open a file "bar.txt"
if (rand() % 2) {
// if this exception is thrown, we leave the function, and so
// file's destructor is called, which closes the file handle.
throw std::exception();
}
// if the exception is not called, we leave the function normally, and so
// again, file's destructor is called, which closes the file handle.
}
```
Regardless of how we leave the function, and of what happens after the file is opened, we don't need to explicitly close the file, or handle exceptions (e.g. try-finally) within that function. Instead, the file gets cleaned up because it is tied to a local object that gets destroyed when it goes out of scope.
RAII is also less-commonly known as SBRM (Scope-Bound Resource Management).
See also:
* [ScopeGuard](http://www.ddj.com/cpp/184403758) allows code to "automatically invoke an 'undo' operation .. in the event that an exception is thrown." | What are your favorite C++ Coding Style idioms | [
"",
"c++",
"coding-style",
""
] |
Are there any libraries or resources available for parsing/reading an archived eventlogs? | There is this article [Parsing event log(\*.evt) file.](http://www.codeproject.com/KB/string/EventLogParser.aspx?fid=334874&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2018071#xx2018071xx)
Then there is the Microsoft [Event Log file format documentation](http://msdn.microsoft.com/en-us/library/bb309026(VS.85).aspx) (evt used on xp win 2003). So far the only information I can find for the new format is a pdf from some [forensic conference.](http://www.dfrws.org/2007/proceedings/p65-schuster.pdf)
And [how to convert evt to evtx](http://blogs.technet.com/askperf/archive/2007/10/12/windows-vista-and-exported-event-log-files.aspx) | If the file is .evt, you can just run eventvwr, click Action->Open Log File and select the archived file and the file type.
For programmatic access, there is a .NET class System.Diagnostics.EventLog which would have everything you need. | How do you read an archived eventlog file? | [
"",
"c#",
".net",
"vb.net",
""
] |
I have a configuration file where a developer can specify a text color by passing in a string:
```
<text value="Hello, World" color="Red"/>
```
Rather than have a gigantic switch statement look for all of the possible colors, it'd be nice to just use the properties in the class System.Drawing.Brushes instead so internally I can say something like:
```
Brush color = Brushes.Black; // Default
// later on...
this.color = (Brush)Enum.Parse(typeof(Brush), prasedValue("color"));
```
Except that the values in Brush/Brushes aren't enums. So Enum.Parse gives me no joy. Suggestions? | Recap of all previous answers, different ways to convert a string to a Color or Brush:
```
// best, using Color's static method
Color red1 = Color.FromName("Red");
// using a ColorConverter
TypeConverter tc1 = TypeDescriptor.GetConverter(typeof(Color)); // ..or..
TypeConverter tc2 = new ColorConverter();
Color red2 = (Color)tc.ConvertFromString("Red");
// using Reflection on Color or Brush
Color red3 = (Color)typeof(Color).GetProperty("Red").GetValue(null, null);
// in WPF you can use a BrushConverter
SolidColorBrush redBrush = (SolidColorBrush)new BrushConverter().ConvertFromString("Red");
``` | String to brush:
```
myTextBlock.Foreground = new BrushConverter().ConvertFromString("#FFFFFF") as SolidColorBrush;
```
That's my case here! | Convert string to Brushes/Brush color name in C# | [
"",
"c#",
".net",
"graphics",
"colors",
"brush",
""
] |
Does anyone know if there's a de-facto standard (i.e., TR1 or Boost) C++ function object for accessing the elements of a std::pair? Twice in the past 24 hours I've wished I had something like the `keys` function for Perl hashes. For example, it would be nice to run std::transform on a std::map object and dump all the keys (or values) to another container. I could certainly write such a function object but I'd prefer to reuse something that's had a lot of eyeballs on it. | `boost::bind` is what you look for.
```
boost::bind(&std::pair::second, _1); // returns the value of a pair
```
Example:
```
typedef std::map<std::string, int> map_type;
std::vector<int> values; // will contain all values
map_type map;
std::transform(map.begin(),
map.end(),
std::back_inserter(values),
boost::bind(&map_type::value_type::second, _1));
``` | From the way you worded your question, I'm not sure this is a proper response, but try `boost::tie` (part of the Boost::tuple library). It works on `std::pair`s too. | Is there a standard C++ function object for taking apart a std::pair? | [
"",
"c++",
"boost",
"std",
"tr1",
"std-pair",
""
] |
I have an abstract base class called Shape from which both Circle and Rectangle are derived, but when I execute the following code in VS 2005 I get the error Debug assertion failed. At the same time I have not overloaded == operator in any class
Expression:Vector iterator not dereferencable, what is the reason for this.
```
vector<Shape*> s1;
s1.push_back(new Circle(point(1,2),3));
s1.push_back(new Circle(point(4,3),5));
s1.push_back(new Rectangle(point(1,1),4,5));
vector<Shape*> s2(s1);
reverse(s1.begin(),s1.end());
(*find(s1.begin(),s1.end(),new Circle(point(1,2),3)))->move(point(10,20));
``` | Simple :
* find fails since your newly created Circle can't be found in the vector with comparing Shape \*
* a failed find returns the end iterator which is not deferencable as caught by a Debug assertion
For it to work like you want, you do need to compare Shape, not Shape\*
As pointed out in other answers, [boost::ptr\_vector](http://www.boost.org/doc/libs/1_37_0/libs/ptr_container/doc/ptr_vector.html) is an easy way to achieve this. | Like @David Pierre suggests: find is value-based: it looks in the range of iterators for a pointer (e.g. 0x0F234420) that equals the pointer to the `new Circle(point(1,2),3)` you just created. Since that's a new object, it won't be there.
You can get around this by using `find_if` with an operator that compares the objects referenced to by the pointer.
However, the Criterium should be able to differentiate between shape types.
```
class Shape {
public:
//amongst other functions
virtual bool equal( const Shape* ) const = 0;
};
class Circle : public Shape {
public:
bool equal( const Shape* pOther ) const {
const Circle* pOtherCircle = dynamic_cast<const Circle*>( pOther );
if( pOtherCircle == NULL ) return false;
// compare circle members
}
};
class Rectangle : public Shape {
public:
bool equal( const Shape* pOther ) const {
const Rectangle* pOtherR = dynamic_cast<const Rectangle*>( pOther );
if( pOtherR == NULL ) return false;
// compare rectangle members
}
};
Shape* pFindThis = new Circle(point(1,2),3);
vector<Shape*>::const_iterator itFound = find_if(s1.begin(),s1.end(),
bind1st( mem_fun( &Shape::equal ), pFindThis) ) );
delete pFindThis; //leak resolved by Mark Ransom - tx!
if( itFound != s1.end() ) {
(*itFound)->move(point(10,20));
}
``` | Vector iterator not dereferencable | [
"",
"c++",
"stl",
""
] |
I am trying to write a function that will pull the name of a property and the type using syntax like below:
```
private class SomeClass
{
Public string Col1;
}
PropertyMapper<Somewhere> propertyMapper = new PropertyMapper<Somewhere>();
propertyMapper.MapProperty(x => x.Col1)
```
Is there any way to pass the property through to the function without any major changes to this syntax?
I would like to get the property name and the property type.
So in the example below i would want to retrieve
`Name = "Col1"` and `Type = "System.String"`
Can anyone help? | Here's enough of an example of using [Expressions](http://msdn.microsoft.com/en-us/library/system.linq.expressions.aspx) to get the name of a property or field to get you started:
```
public static MemberInfo GetMemberInfo<T, U>(Expression<Func<T, U>> expression)
{
var member = expression.Body as MemberExpression;
if (member != null)
return member.Member;
throw new ArgumentException("Expression is not a member access", "expression");
}
```
Calling code would look like this:
```
public class Program
{
public string Name
{
get { return "My Program"; }
}
static void Main()
{
MemberInfo member = ReflectionUtility.GetMemberInfo((Program p) => p.Name);
Console.WriteLine(member.Name);
}
}
```
A word of caution, though: the simple statment of `(Program p) => p.Name` actually involves quite a bit of work (and can take measurable amounts of time). Consider caching the result rather than calling the method frequently. | This can be easily done in C# 6. To get the name of property use nameof operator.
```
nameof(User.UserId)
```
and to get type of property use typeof operator.
```
typeof(User.UserId)
``` | Get property name and type using lambda expression | [
"",
"c#",
"reflection",
"lambda",
""
] |
Presuming I have a class named `A`, and I want to use the decorator design pattern. Correct me if I'm wrong, but for that to work , we'll need to create a decorator class, say `ADecorator`, which will hold a reference to an `A` instance, and all the other decorators will extend this to add functionality.
I don't understand why do we have to create a decorator class, instead of using an `A` instance? | The decorator pattern is used to add capabilities to objects dynamically (that is, at run time). Normally the object will have its capabilities fixed when you write the class. But an important point is that the functionality of the object is extended in a way that is transparent to the client of the object because it implements the same interface as the original object delegates responsibility to the decorated object.
The decorator pattern works in scenarios where there are many optional functionality that an object may have. Without the decorator pattern you will have to create a different class for each object-option configuration. One example that is pretty useful comes from the ***Head First Design Patterns*** book by O'Reilly. It uses a coffee shop example that sounds just like StarBucks.
So you have the basic coffee with a method like cost.
```
public double cost(){
return 3.45;
}
```
Then the customer can add cream which costs 0.35 so you now create a CoffeeCream class with the cost method:
```
public double cost(){
return 3.80;
}
```
Then the customer may want Mocha which costs 0.5, and they may want Mocha with Cream or Mocha without Cream. So you create classes CoffeeMochaCream and CoffeeMocha. Then a customer wants double cream so you create a class CoffeeCreamCream… etc. What you end up with is class explosion. Please excuse the poor example used. It's a bit late and I know it's trivial but it does express the point.
Instead you can create an Item abstract class with an abstract cost method:
```
public abstract class Item{
public abstract double cost();
}
```
And you can create a concrete Coffee class that extends Item:
```
public class Coffee extends Item{
public double cost(){
return 3.45;
}
}
```
Then you create a CoffeeDecorator that extend the same interface and contain an Item.
```
public abstract class CoffeeDecorator extends Item{
private Item item;
...
}
```
Then you can create concrete decorators for each option:
```
public class Mocha extends CoffeeDecorator{
public double cost(){
return item.cost() + 0.5;
}
}
```
Notice how the decorator does not care what type of object it is wrapping just as long as it's an Item? It uses the cost() of the item object and simply adds its own cost.
```
public class Cream extends CoffeeDecorator{
public double cost(){
return item.cost() + 0.35;
}
}
```
Now it is possible for a large number of configurations with these few classes:
e.g.
```
Item drink = new Cream(new Mocha(new Coffee))); //Mocha with cream
```
or
```
Item drink = new Cream(new Mocha(new Cream(new Coffee))));//Mocha with double cream
```
And so on. | In some languages (like Ruby or JavaScript) you could just add new functionality to an A instance. I notice that your question is tagged Java, so I assume that you are asking why you can't do this in Java. The reason is that Java is statically typed. An A instance can only ever have the methods that class A defines or inherits. Therefore, if you want at run time to give an A instance a method that A does not define, then this new method must be defined in a different class. | Why do we need the decorator in the decorator design pattern? | [
"",
"java",
"design-patterns",
"decorator",
""
] |
Does anyone know which property sets the text color for disabled control?
I have to display some text in a disabled `TextBox` and I want to set its color to black. | **NOTE:** see Cheetah's answer below as it identifies a prerequisite to get this solution to work. Setting the `BackColor` of the `TextBox`.
---
I think what you really want to do is enable the `TextBox` and set the `ReadOnly` property to `true`.
It's a bit tricky to change the color of the text in a disabled `TextBox`. I think you'd probably have to subclass and override the `OnPaint` event.
`ReadOnly` though should give you the same result as `!Enabled` and allow you to maintain control of the color and formatting of the `TextBox`. I think it will also still support selecting and copying text from the `TextBox` which is not possible with a disabled `TextBox`.
Another simple alternative is to use a `Label` instead of a `TextBox`. | Additionally, in order for ForeColor to be obeyed on a TextBox marked ReadOnly, you must explicitly set the BackColor. If you want to have it still use the default BackColor, you have to make the set explicit, as the designer is too smart for its own good here. It is sufficient to set the BackColor to its current value. I do this in the Load event for the form, like so:
```
private void FormFoo_Load(...) {
txtFoo.BackColor = txtFoo.BackColor;
}
``` | How to change the font color of a disabled TextBox? | [
"",
"c#",
"winforms",
""
] |
Is there any example code of a [cpython](http://www.python.org/) (not IronPython) client which can call Windows Communication Foundation (WCF) service? | WCF needs to expose functionality through a communication protocol. I think the most commonly used protocol is probably SOAP over HTTP. Let's assume that's
what you're using then.
Take a look at [this chapter in Dive Into Python](https://linux.die.net/diveintopython/html/soap_web_services/index.html). It will show you how to
make SOAP calls.
I know of no unified way of calling a WCF service in Python, regardless of communication
protocol. | I used [suds](/questions/tagged/suds "show questions tagged 'suds'").
```
from suds.client import Client
print "Connecting to Service..."
wsdl = "http://serviceurl.com/service.svc?WSDL"
client = Client(wsdl)
result = client.service.Method(variable1, variable2)
print result
```
That should get you started. I'm able to connect to exposed services from WCF and a RESTful layer. There needs to be some data massaging to help do what you need, especially if you need to bind to several namespaces. | WCF and Python | [
"",
"python",
"wcf",
""
] |
This is my first crack at a method that is run periodically during the lifetime of my ASP.NET application to clean up expired sessions stored in my database. It seems to work pretty well, but the software engineer in me doesn't feel "right" about this code. I've been working with LINQ to SQL for a few months now, but I'm not very confident in the following code. I'm worried about a few things:
1. Is the following code safe to run in a situation where the database is being accessed by different threads in my application? I have a decent understanding of the idea of transactions, but I want to make sure I'm using them properly.
2. Is my query going to cause performance issues? Or is it appropriate in this case to select all of the records in this particular table? This method only runs every 15 minutes, so it's not like that query will be made over and over again in a short period of time.
3. Is there a better way that I could do this? I have a nagging feeling that there is.
Code:
```
/// <summary>
/// Method, run periodically, to remove all sign in records that correspond to expired sessions.
/// </summary>
/// <param name="connectionString">Database connection string</param>
/// <returns>Number of expired sign in records removed</returns>
public static int Clean(String connectionString)
{
MyDatabaseDataContext db = new MyDatabaseDataContext(connectionString);
var signIns = db.SignIns.Select(x => x);
int removeCount = 0;
using (TransactionScope scope = new TransactionScope())
{
foreach (SignIn signIn in signIns)
{
DateTime currentTime = DateTime.Now;
TimeSpan span = currentTime.Subtract(signIn.LastActivityTime);
if (span.Minutes > 10)
{
db.SignIns.DeleteOnSubmit(signIn);
++removeCount;
}
}
db.SubmitChanges();
scope.Complete();
}
return removeCount;
}
``` | This sounds like something you could easily do in a sproc. SQLServer gives you a GETDATE() method that returns the current time... I don't see why you can't just
```
DELETE * FROM tblSignIns
WHERE LastActivityTime < DATEADD("minute", -10, GETDATE());
```
Wouldn't that do the same thing? | One comment: you don't want [`TimeSpan.Minutes`](http://msdn.microsoft.com/en-us/library/system.timespan.minutes.aspx), you want [`TimeSpan.TotalMinutes`](http://msdn.microsoft.com/en-us/library/system.timespan.totalminutes.aspx). It may well be irrelevant *most* of the time, but it's a logical bug at least :) | Best way to periodically remove a set of records with LINQ to SQL | [
"",
"c#",
"performance",
"linq-to-sql",
"t-sql",
"transactions",
""
] |
I would like to store log4net config data in my application.config file. Based on my understanding of the documentation, I did the following:
1. Add a reference to log4net.dll
2. Add the following line in AssemblyInfo.cs:
```
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
```
3. Initialize the logger as follows:
```
private static readonly ILog log = LogManager.GetLogger(typeof(frmWizard));
```
4. I have the following code in my app.config:
```
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="ConsoleAppender" />
</root>
</log4net>
```
However, when I run the application, I get the following error on the console:
> No appender named [Consoleappender] could be found.
How can I get log4net to read settings from the config file?
Thanks! | Add a line to your app.config in the configSections element
```
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net, Version=1.2.10.0,
Culture=neutral, PublicKeyToken=1b44e1d426115821" />
</configSections>
```
Then later add the log4Net section, but delegate to the actual log4Net config file elsewhere...
```
<log4net configSource="Config\Log4Net.config" />
```
In your application code, when you create the log, write
```
private static ILog GetLog(string logName)
{
ILog log = LogManager.GetLogger(logName);
return log;
}
``` | From the config shown in the question there is but one appender configured and it is named "EventLogAppender". But in the config for root, the author references an appender named "ConsoleAppender", hence the error message. | Have log4net use application config file for configuration data | [
"",
"c#",
"logging",
"log4net",
""
] |
Is there an obvious way to do this that I'm missing? I'm just trying to make thumbnails. | Define a maximum size.
Then, compute a resize ratio by taking `min(maxwidth/width, maxheight/height)`.
The proper size is `oldsize*ratio`.
There is of course also a library method to do this: the method `Image.thumbnail`.
Below is an (edited) example from the [PIL documentation](https://pillow.readthedocs.io/en/stable/reference/Image.html?highlight=thumbnail#PIL.Image.Image.thumbnail).
```
import os, sys
import Image
size = 128, 128
for infile in sys.argv[1:]:
outfile = os.path.splitext(infile)[0] + ".thumbnail"
if infile != outfile:
try:
im = Image.open(infile)
im.thumbnail(size, Image.Resampling.LANCZOS)
im.save(outfile, "JPEG")
except IOError:
print "cannot create thumbnail for '%s'" % infile
``` | This script will resize an image (somepic.jpg) using PIL (Python Imaging Library) to a width of 300 pixels and a height proportional to the new width. It does this by determining what percentage 300 pixels is of the original width `img.size[0]` and then multiplying the original height `img.size[1]` by that percentage. Change `base_width` to any other number to change the default width of your images.
```
from PIL import Image
base_width= 300
img = Image.open('somepic.jpg')
wpercent = (base_width / float(img.size[0]))
hsize = int((float(img.size[1]) * float(wpercent)))
img = img.resize((basewidth, hsize), Image.Resampling.LANCZOS)
img.save('somepic.jpg')
``` | How do I resize an image using PIL and maintain its aspect ratio? | [
"",
"python",
"image",
"python-imaging-library",
"thumbnails",
""
] |
For some reason I'm not getting this. (Example model below) If I write:
```
var property = typeof(sedan).GetProperty("TurningRadius");
Attribute.GetCustomAttributes(property,typeof(MyAttribute), false)
```
the call will return MyAttribute(2) despite indicating I don't want to search the inheritance chain. Does anyone know what code I can write so that calling
```
MagicAttributeSearcher(typeof(Sedan).GetProperty("TurningRadius"))
```
returns nothing while calling
```
MagicAttributeSearcher(typeof(Vehicle).GetProperty("TurningRadius"))
```
returns MyAttribute(1)?
---
Example Model:
```
public class Sedan : Car
{
// ...
}
public class Car : Vehicle
{
[MyAttribute(2)]
public override int TurningRadius { get; set; }
}
public abstract class Vehicle
{
[MyAttribute(1)]
public virtual int TurningRadius { get; set; }
}
``` | Okay, given the extra information - I believe the problem is that `GetProperty` is going up the inheritance change.
If you change your call to `GetProperty` to:
```
PropertyInfo prop = type.GetProperty("TurningRadius",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
```
then `prop` will be null if the property isn't overridden. For instance:
```
static bool MagicAttributeSearcher(Type type)
{
PropertyInfo prop = type.GetProperty("TurningRadius", BindingFlags.Instance |
BindingFlags.Public | BindingFlags.DeclaredOnly);
if (prop == null)
{
return false;
}
var attr = Attribute.GetCustomAttribute(prop, typeof(MyAttribute), false);
return attr != null;
}
```
This returns `true` and only if:
* The specified type overrides the `TurningRadius` property (or declares a new one)
* The property has the `MyAttribute` attribute. | I believe the problem is that when you obtain the property TurningRadius from the Sedan object in the first line
```
var property = typeof(sedan).GetProperty("TurningRadius");
```
what you are actually getting is the TurningRadius property declared at Car level, since Sedan doesn't have its own overload.
Therefore, when you request its attributes, you are getting the ones defined at car even if you requested not to go up in the inheritance chain, as the property you are querying is the one defined in Car.
You should change the GetProperty to add the necessary flags to obtain only declaring members. I believe [DeclaredOnly](http://msdn.microsoft.com/en-us/library/system.reflection.bindingflags.declaredonly.aspx) should do.
Edit: Note that this change will have the first line return null, so watch out for NullPointerExceptions. | How do I ignore the inheritance chain when getting attributes? | [
"",
"c#",
"reflection",
"attributes",
""
] |
C++0x will allow template to take an arbitrary number of arguments. What is the best use of this feature other than implementing tuples ? | 1. **Type-safe printf**
2. Forwarding of arbitrary many constructor arguments in **factory methods**
3. Having **arbitrary** base-classes allows for putting and removing useful **policies**.
4. Initializing by moving **heterogenous typed objects** directly into a container by having a variadic template'd constructor.
5. Having a **literal operator** that can calculate a value for a user defined literal (like "10110b").
Sample to 3:
```
template<typename... T> struct flexible : T... { flexible(): T()... { } };
```
Sample to 4:
```
struct my_container { template<typename... T> my_container(T&&... t) { } };
my_container c = { a, b, c };
```
Sample to 5:
```
template<char... digits>
int operator "" b() { return convert<digits...>::value; }
```
See this example code: [here](https://stackoverflow.com/questions/537303/binary-literals/538101#538101) | Maybe the talk by Andrei Alexandrescu on the Going Native 2012 event, will be of your interest:
[Here](http://video.ch9.ms/ch9/5174/7feb4b38-591d-478f-8341-9fd4012d5174/GN12AndreiAlexandrescuVariadicTemplates_high_ch9.mp4) is the video and [Here](http://ecn.channel9.msdn.com/events/GoingNative12/GN12VariadicTemplatesAreFunadic.pdf) the documentation. | Variadic templates | [
"",
"c++",
"templates",
"c++11",
""
] |
So if I have:
```
public class ChildClass : BaseClass
{
public new virtual string TempProperty { get; set; }
}
public class BaseClass
{
public virtual string TempProperty { get; set; }
}
```
How can I use reflection to see that ChildClass is hiding the Base implementation of TempProperty?
I'd like the answer to be agnostic between c# and vb.net | We'll have to deal in terms of the methods of the property here rather than the property itself, because it is the get/set methods of the property that actually get overridden rather than the property itself. I'll use the get method as you should never have a property without one, though a complete solution should check for the lack of one.
Looking at the IL emitted in a number of cases, the 'get' method of the base property will have the metadata tokens (this is from the C# compiler; others may not emit the `hidebysig` depending on their method hiding semantics, in which case the method would be hide-by-name):
```
non-virtual : .method public hidebysig specialname instance
virtual : .method public hidebysig specialname newslot virtual instance
```
The derived one will have the following tokens:
```
override : .method public hidebysig specialname virtual instance
new : .method public hidebysig specialname instance
new virtual : .method public hidebysig specialname newslot virtual instance
```
So we can see from this that it isn't possible to tell purely from the method's metadata tokens whether it is `new` because the non-virtual base method has the same tokens as the non-virtual `new` method, and the virtual base method has the same tokens as the `new virtual` method.
What we *can* say is that if the method has the `virtual` token but not the `newslot` token then it overrides a base method rather than shadows it, i.e.
```
var prop = typeof(ChildClass).GetProperty("TempProperty");
var getMethod = prop.GetGetMethod();
if ((getMethod.Attributes & MethodAttributes.Virtual) != 0 &&
(getMethod.Attributes & MethodAttributes.NewSlot) == 0)
{
// the property's 'get' method is an override
}
```
Assuming, then, that we find the 'get' method is not an override, we want to know whether there is a property in the base class that it is shadowing. The problem is that because the method is in a different method table slot, it doesn't actually have any direct relationship to the method it is shadowing. So what we're actually saying is "does the base type have any method which meets the criteria for shadowing", which varies depending on whether the method is `hidebysig` or hide-by-name.
For the former we need to check whether the base class has any method which matches the signature exactly, whereas for the latter we need to check whether it has any method with the same name, so continuing the code from above:
```
else
{
if (getMethod.IsHideBySig)
{
var flags = getMethod.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic;
flags |= getMethod.IsStatic ? BindingFlags.Static : BindingFlags.Instance;
var paramTypes = getMethod.GetParameters().Select(p => p.ParameterType).ToArray();
if (getMethod.DeclaringType.BaseType.GetMethod(getMethod.Name, flags, null, paramTypes, null) != null)
{
// the property's 'get' method shadows by signature
}
}
else
{
var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance;
if (getMethod.DeclaringType.BaseType.GetMethods(flags).Any(m => m.Name == getMethod.Name))
{
// the property's 'get' method shadows by name
}
}
}
```
I think this is most of the way there, but I still don't think it's exactly right. For a start I'm not totally familiar with hiding by name as C# doesn't support it and that's pretty much all I use, so I may be wrong in the code here that indicates an instance method could shadow a static one. I also don't know about the case sensitivity issue (e.g. in VB could a method called `Foo` shadow a method called `foo` if they both had the same signature and were both `hidebysig` - in C# the answer is no but if the answer is yes in VB then it means the answer to this question is actually nondeterministic).
Well, I'm not sure how much help all this is, other than to illustrate that it's actually a much harder problem than I thought it would be (or I've missed something really obvious in which case I'd like to know!). But hopefully it's got sufficient content that it helps you achieve what you're trying to do. | Doesn't look like reflection will give this to you by default so you'll have to roll your own:
```
public static bool IsHidingMember( this PropertyInfo self )
{
Type baseType = self.DeclaringType.BaseType;
PropertyInfo baseProperty = baseType.GetProperty( self.Name, self.PropertyType );
if ( baseProperty == null )
{
return false;
}
if ( baseProperty.DeclaringType == self.DeclaringType )
{
return false;
}
var baseMethodDefinition = baseProperty.GetGetMethod().GetBaseDefinition();
var thisMethodDefinition = self.GetGetMethod().GetBaseDefinition();
return baseMethodDefinition.DeclaringType != thisMethodDefinition.DeclaringType;
}
```
Not sure how this will work with indexed properties, however! | How does reflection tell me when a property is hiding an inherited member with the 'new' keyword? | [
"",
"c#",
"vb.net",
"reflection",
"inheritance",
"overriding",
""
] |
So I have this code for these Constructors of the Weapon class:
```
Weapon(const WeaponsDB * wepDB);
Weapon(const WeaponsDB * wepDB_, int * weaponlist);
~Weapon(void);
```
And I keep getting an error:
```
1>c:\users\owner\desktop\bosconian\code\bosconian\weapon.h(20) : error C2062: type 'int' unexpected
```
and ensuing errors (more than listed):
```
1>c:\users\owner\desktop\bosconian\code\bosconian\weapon.h(21) : error C2059: syntax error : '('
1>c:\users\owner\desktop\bosconian\code\bosconian\weapon.h(21) : error C2238: unexpected token(s) preceding ';'
1>c:\users\owner\desktop\bosconian\code\bosconian\weapon.h(33) : error C2327: '<unnamed-tag>::maxWeapons' : is not a type name, static, or enumerator
1>c:\users\owner\desktop\bosconian\code\bosconian\weapon.h(33) : error C2065: 'maxWeapons' : undeclared identifier
1>c:\users\owner\desktop\bosconian\code\bosconian\weapon.h(38) : warning C4094: untagged 'class' declared no symbols
```
I'm a semi-newbie and I haven't been able to figure it out.
Line 21 is the second constructor, the first one doesn't cause an error.
Also, if I comment out this constructor I still get all the errors listed after that constructors. Any idea what the problem might be?
Here is the preceding code for reference:
```
#ifndef Weapon
#define Weapon
#include <allegro.h>
#include <stdio.h>
#include <iostream>
using namespace std;
class WeaponsDB;
class MenuDriver;
class Ammo;
class Weapon
{
public:
.....
``` | ```
#ifndef Weapon
#define Weapon
```
This is almost certainly going to cause weirdness; call the constant WEAPON\_H instead. | So you named your class the same as a preprocessor directive? That is something I would avoid.
Try changing your preprocessor Weapon or making a different class name. I think it will work better. | Problem with a constructor c++ | [
"",
"c++",
""
] |
I want to prevent the user from maximizing the Windows Form to full screen so I have disabled the Maximize button. However, I want to be able to have the user 'restore' the Form. When they click the Restore button I want it to show a different, smaller, minified, form, which will show them a maximize button which will return the use to the original form.
Is there a way to do this?
Thanks.
edit:
You don't understand, I'm not preventing the user from resizing the form. Whats happening is when the click the restore button, it will hide the form and open a new one with less controls on it. When they click maximize on the smaller form, it will return to the original form. | I looked at a similar problem to this at work and the only solutions I could find involved setting undocumented window styles, which I was not inclined to do.
Therefore the best solution to your problem I would think would be to hide the current minimize/maximize/restore buttons and add your own using some ownerdraw or other commands.
Looking at this from a user interaction perspective I would want the minimize/maximize/restore buttons to do exactly the same thing for your application as they do for all others. Overriding that functionality would create confusion for your users, hence why I would recommend creating different buttons either on the title bar or somewhere else on your interface that perform this function. | You can set the MaximumSize and MinimumSize and enable the maximize button to get this kind of effect. | Showing the Restore Button without a Maximize button | [
"",
"c#",
"winforms",
"restore",
"maximize",
""
] |
I have been bitten by a poorly architected solution. It is not thread safe!
I have several shared classes and members in the solution, and during development all was cool...
BizTalk has sunk my battle ship.
We are using a custom BizTalk Adapter to call my assemblies. The Adapter is calling my code and running things in parallel, so I assume it is using multiple threads all under the same AppDomain.
What I would like to do is make my code run under its own AppDomain so the shared problems I have will not muck with each other.
I have a very simple class that the BizTalk adapter is instantiating then running a Process() method.
I would like to create a new AppDomain inside my Process() method, so each time BizTalk spins another thread, it will have its own version of the static classes and methods.
BizTalkAdapter Code:
```
// this is inside the BizTalkAdapter and it is calling the Loader class //
private void SendMessage(IBaseMessage message, TransactionalTransmitProperties properties)
{
Stream strm = message.BodyPart.GetOriginalDataStream();
string connectionString = properties.ConnectionString;
string msgFileName = message.Context.Read("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties") as string;
Loader loader = new Loader(strm, msgFileName, connectionString);
loader.Process();
EventLog.WriteEntry("Loader", "Successfully processed: " + msgFileName);
}
```
This is the class BizTalk Calls:
```
public class Loader
{
private string connectionString;
private string fileName;
private Stream stream;
private DataFile dataFile;
public Loader(Stream stream, string fileName, string connectionString)
{
this.connectionString = connectionString;
this.fileName = fileName;
this.stream = stream;
}
public void Process()
{
//***** Create AppDomain HERE *****
// run following code entirely under that domain
dataFile = new DataFile(aredStream, fileName, connectionString);
dataFile.ParseFile();
dataFile.Save();
// get rid of the AppDomain here...
}
}
```
FYI: The Loader class is in a seperate DLL from the dataFile class.
Any help would be appreciated. I will continue to working on making the code Thread-Safe, but I feel like this could be the "simple" answer.
If anyone has any other thought, please throw in.
Thank you,
Keith
> Just for completeness.
>
> I did find that if I marked the send adapter as "Ordered Delivery" in
> the "Transport Advanced Options" dialog I was able to avoid the
> multi-thread issues I was having.
>
> I figure this is another possible answer to my problem, but not
> necessarily to the question. | Using app domains you could do something like this:
```
public class Loader
{
private string connectionString;
private string fileName;
private Stream stream;
private DataFile dataFile;
public Loader(Stream stream, string fileName, string connectionString)
{
this.connectionString = connectionString;
this.fileName = fileName;
this.stream = stream;
}
public void Process()
{
//***** Create AppDomain HERE *****
string threadID = Thread.CurrentThread.ManagedThreadId.ToString();
AppDomain appDomain = AppDomain.CreateDomain(threadID);
DataFile dataFile =
(DataFile) appDomain.CreateInstanceAndUnwrap(
"<DataFile AssemblyName>",
"DataFile",
true,
BindingFlags.Default,
null,
new object[]
{
aredstream,
filename,
connectionString
},
null,
null,
null);
dataFile.ParseFile();
dataFile.Save();
appDomain.Unload(threadID);
}
}
``` | Which bit, exactly, is being a pain in terms of thread safety? I can't see any static state nor singletons - and there seems to be appropriate "new" objects... am I being blind?
So what is the symptom you are seeing...
An AppDomain answer will be (relatively) slow. As part of a middleware-backed system this might be OK (i.e. the "relatively" is in the same ball-park).
If you *do* have some static state somewhere, another option that sometimes works is [ThreadStatic] - which the runtime interprets as "this static field is unique per thread". You need to be careful with initialization, though - the static constructor on thread A might assign a field, but then thread B would see a null/0/etc. | How to use an AppDomain to limit a static class' scope for thread-safe use? | [
"",
"c#",
"thread-safety",
"biztalk",
"appdomain",
""
] |
I am trying to get intellisense in VS2008 in a js file, foo.js, from another js library/file I've written but cannot figure out the reference path ?syntax?/?string?
The library is in a file called common.js which is in the same folder as foo.js I'm working on.
Here's the paths I've tried...
```
/// <reference path="../../scripts/common.js"/>
/// <reference path="/../scripts/common.js"/>
/// <reference path="../scripts/common.js"/>
/// <reference path="/scripts/common.js"/>
/// <reference path="scripts/common.js"/>
/// <reference path="/common.js"/>
/// <reference path="../common.js"/>
/// <reference path="/common.js"/>
/// <reference path="common.js"/>
```
What's the secret path syntax/string that I'm missing?
FWIW the top path is what is set in the master page of this MVC app...like so
`<script type="text/javascript" src="../../scripts/common.js"></script>`
Thanks Greg | First, make sure "common.js" is in your web project. Then drag "common.js" from the solution explorer into the editor window for the file you want to reference it from. | Finally...finally got jQuery intellisense to work...
From here <http://blogs.msdn.com/webdevtools/archive/2007/11/06/jscript-intellisense-a-reference-for-the-reference-tag.aspx>
the author says
> Here are a few other subtle tips:
>
> * Remember, reference statements must precede all other content in the file-even normal comments.
And that was what fixed the issue for me...placed the reference statements at the very top and... voila!... intellisense works!
So just for grins here's what the first lines of my file look like
```
/// <reference path="common.js" />
/// <reference path="jquery-1.2.6.js" />
/// <reference path="jquery.formatCurrency.js" />
/*
* Foo Scripts/foo Script: foo.js
* Version 1.0
* Copyright(c) 2008 FUBAR Management, LLC. All Rights Reserved.
*/
```
Originally I had the reference statements below the Foo Scripts comments arghhhh! | reference path re javascript intellisense | [
"",
"javascript",
"visual-studio-2008",
"intellisense",
""
] |
I am a Web developer who spends 99% of his time in Linux, but I need to develop a super simple application with VB or possibly C# (.Net). The only version of Visual Studio I have is the most current free ones. There MIGHT be a copy of 2001 lying around somewhere. Anyways, the machine I need to develop this for is running Windows NT4. I cannot change this because another piece of software runs on that requires it.
Is there a way to develop an app with the new VS and keep it compatible with such an old version of the .Net framework (1.1)?
If nothing else I could install Perl on the machine and write a command line type script, but given the people that will be using it GUI would be better. | I don't believe you can target .Net 1.1 in Visual Studio 2008. Here's one of the developer's explanations, from a comment in [this blog entry](http://blogs.msdn.com/lukeh/archive/2007/06/29/net-framework-multitargeting-in-visual-studio-2008-aka-orcas.aspx):
> Visual Studio 2008 will not support targeting .Net Framework 1.1. This is something we really wanted to be able to support - since we know there are a lot of .NET developers working on .NET 1.1 applications. However, it would have been significantly more difficult to go back and support .NET 1.1 which was a substantially different runtime.
>
> Thus, to fit in this release, the
> decision ended up being either to not
> support multitargeting at all - or to
> support only targeting .NET2.0 and
> greater. Because we really wanted
> Visual Studio 2008 to be a great tool
> for at least both .NET 3.0 and .NET
> 3.5 - we decided to put in the most multitargeting support we could fit in
> this release. | You can use vs.net 2008 to write code that is able to run on .net v1.1 but the IDE won't give you any hints on what will work etc.
You will be stuck using inline asp.net for a model.
(or compile using the commandline tools)
There are a lot of examples using this method here:
<http://www.learnasp.com/freebook/learn/>
This code is all v1.1 except for the explicit naming of the v2 examples. | Can I write an app in the new version of Visual Studio and make it compatible with .NET Framework 1.1 | [
"",
"c#",
".net",
"vb.net",
".net-1.1",
"version-compatibility",
""
] |
After an upgrade to XP and Java 1.6 one of our intranet apps is experiencing a problem when running a java applet in the browser. The java applet is a document editor and accepts a parameter to where the document is located. I assume it copies this file to the users machine for editing. I wish I knew more but I don't have the source...dam!
we are getting a java.io.IOException on a machine running XP-IE6-Java 1.6. This problem doesn't happen on our older Win2K-IE6-Java 1.3 so we are certain its isolated to the desktop and not the server (99% sure anyway).
A little info: If you try to run the applet twice in a row, it works the second time. The first time it fails. Also, the error message box appears BEFORE the orange java loading logo appears embedded in the browser.
I have also entered in the following information into the policy file and reloaded the policy file via the console.
```
grant codeBase "http://intranetserver/*" {
permission java.security.AllPermission;
};
```
here is a dump of the stack trace. Thanks for your time :-)
```
java.io.IOException: Write error
at java.io.FileOutputStream.writeBytes(Native Method)
at java.io.FileOutputStream.write(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.close(Unknown Source)
at com.docscience.dlstools.browser.editor.HTMLDocumentLoader.loadDocument(HTMLDocumentLoader.java:94)
at com.docscience.dlstools.browser.editor.HTMLDocumentLoader.loadDocument(HTMLDocumentLoader.java:113)
at com.docscience.dlstools.browser.editor.HTMLDocumentLoader.loadDocument(HTMLDocumentLoader.java:126)
at com.docscience.dlstools.browser.editor.dsBrowserEditor.loadPage(dsBrowserEditor.java:1623)
at com.docscience.dlstools.browser.editor.dsBrowserEditor.loadFile(dsBrowserEditor.java:1873)
at com.docscience.dlstools.browser.editor.dsBrowserEditor.(dsBrowserEditor.java:201)
at com.docscience.dlstools.browser.editor.DLSBrowserEditor.init(DLSBrowserEditor.java:38)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
``` | I worked out the problem. Turn off temporary files in the java control panel. | You say you went from Java v1.3 directly to Java 1.6, have you had a chance to test it at all with Java 1.4 or 1.5? A bit more contextual information would be helpful here. | Java IOException only when running new Java 1.6 - someone please | [
"",
"java",
"windows-xp",
"ioexception",
""
] |
We have to accept large file uploads (video content) and want to do that in a way that works well across all standards-compliant browsers and plug-ins. Our current setup looks like this:
* [SWFUpload](http://swfupload.org)
* input type="file" for graceful degradation
On the server-side, we have [nginx](http://nginx.net/) and the [upload module](http://www.grid.net.ru/nginx/upload.en.html) streaming the uploaded files into the server, then handing the requests off to a merb app.
Unfortunately, it looks like the recently released Adobe Flash Player 10 broke every single free/open uploading flash component out there (and then, some other sites which have their own proprietary versions as well), but some other sites, such as [Flickr](http://flickr.com) and [Vimeo](http://vimeo.com), seem to work just fine.
I've been poking around looking for other ways of doing this, but since compatibility with both Flash 9 and 10 is mandatory, I couldn't find a suitable solution. Any ideas? | File uploading is always a pain.
I tried a few flash uploaders a while ago and it seems all of them had the limitation of not being to display a progress bar on Macs. Not to mention the upgrade to flash 10 broke most flash uploaders so users of our company app went from multiselecting a whole folder with 50 files to upload at once to uploading 50 files one at a time.
Java uploaders work fine (even through Java updates) but if you don't have small user base that you can explain why they need to download java and allow an applet to run in their browser, most will not use it.
I think the middle ground is to just use ftp. It's old but effective, works with extremely large files and multiple files. | I've been using [JumpLoader](http://www.jumploader.com/) with good results. Support is great, free version available, even includes some basic image processing functions (crop, resize, etc).
According to my google analytics data (non-tech website), 99% of visitors have Java installed, so that's not a problem.
Of course, always provide a simple `input type="file"` alternative, just in case. | What's the most bullet-proof way to upload large files in a web app? | [
"",
"javascript",
"html",
"flash",
"upload",
""
] |
anyone have any experience of using them together? How well does it work? or is it just too much grief? | You don't want to do that. Both ReSharper and CodeRush want the keyboard. Specifically, CodeRush remaps the escape key (ESC) for its own purposes. ReSharper does not like that (note: ReSharper doens't do anything special with the escape key, but it still doesn't like it).
As for choosing between them...they both have their points. CodeRush has better templating and more refactorings. ReSharper has built in unit testing for NUnit, and a healthy set of plugings. ReSharper also has Templates, and a slew of Keyboard short-cuts. | I use both tools succesfully. Yes, both wants the keyboard, but they want it in different manner. You can configure them to work together without too much problems. All is about configuration and the learning curve.
Main issues I've faced are: managing parentheses and brackets (just choose which one is going to do this), templates (not a real problem: use tab for one and space for the other), suggestions (configure different keys for each tool).
CodeRush plugins and Resharper plugins works well together and the result is a true delight. There are no conflicts between the tools. Just take two weeks to use it with easy. | Coderush and resharper, do they work together? | [
"",
"c#",
"visual-studio-2008",
"resharper",
"coderush",
""
] |
This is related to a question I asked the other day on [how to send email](https://stackoverflow.com/questions/366629/how-do-i-send-an-email-message-from-my-c-application).
My new, related question is this... what if the user of my application is behind a firewall or some other reason why the line client.Send(mail) won't work...
After the lines:
```
SmtpClient client = new SmtpClient("mysmtpserver.com", myportID);
client.Credentials = new System.Net.NetworkCredential("myusername.com", "mypassword");
```
is there something I can do to test client before I try sending?
I thought about putting this in a try/catch loop, but I'd rather do a test and then pop up a dialog saying: can't access smtp or something like that.
(I'm presuming that neither I, nor potentially my application user, has the ability to adjust their firewall settings. For example... they install the app at work and don't have control over their internet at work)
-Adeena | I think this is a case where exception handling would be the preferred solution. You really don't know that it will work until you try, and failure is an exception.
Edit:
You'll want to handle SmtpException. This has a StatusCode property, which is an enum that will tell you why the Send() failed. | I think that if you are looking to test the SMTP it's that you are looking for a way to validate your configuration and network availability without actually sending an email. Any way that's what I needed since there were no dummy email that would of made sense.
With the suggestion of my fellow developer I came up with this solution. A small helper class with the usage below. I used it at the OnStart event of a service that sends out emails.
Note: the credit for the TCP socket stuff goes to Peter A. Bromberg at <http://www.eggheadcafe.com/articles/20030316.asp> and the config read stuff to the guys here: [Access system.net settings from app.config programmatically in C#](https://stackoverflow.com/questions/625262/c-access-programatically-system-net-settings-from-app-config)
**Helper:**
```
public static class SmtpHelper
{
/// <summary>
/// test the smtp connection by sending a HELO command
/// </summary>
/// <param name="config"></param>
/// <returns></returns>
public static bool TestConnection(Configuration config)
{
MailSettingsSectionGroup mailSettings = config.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
if (mailSettings == null)
{
throw new ConfigurationErrorsException("The system.net/mailSettings configuration section group could not be read.");
}
return TestConnection(mailSettings.Smtp.Network.Host, mailSettings.Smtp.Network.Port);
}
/// <summary>
/// test the smtp connection by sending a HELO command
/// </summary>
/// <param name="smtpServerAddress"></param>
/// <param name="port"></param>
public static bool TestConnection(string smtpServerAddress, int port)
{
IPHostEntry hostEntry = Dns.GetHostEntry(smtpServerAddress);
IPEndPoint endPoint = new IPEndPoint(hostEntry.AddressList[0], port);
using (Socket tcpSocket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
//try to connect and test the rsponse for code 220 = success
tcpSocket.Connect(endPoint);
if (!CheckResponse(tcpSocket, 220))
{
return false;
}
// send HELO and test the response for code 250 = proper response
SendData(tcpSocket, string.Format("HELO {0}\r\n", Dns.GetHostName()));
if (!CheckResponse(tcpSocket, 250))
{
return false;
}
// if we got here it's that we can connect to the smtp server
return true;
}
}
private static void SendData(Socket socket, string data)
{
byte[] dataArray = Encoding.ASCII.GetBytes(data);
socket.Send(dataArray, 0, dataArray.Length, SocketFlags.None);
}
private static bool CheckResponse(Socket socket, int expectedCode)
{
while (socket.Available == 0)
{
System.Threading.Thread.Sleep(100);
}
byte[] responseArray = new byte[1024];
socket.Receive(responseArray, 0, socket.Available, SocketFlags.None);
string responseData = Encoding.ASCII.GetString(responseArray);
int responseCode = Convert.ToInt32(responseData.Substring(0, 3));
if (responseCode == expectedCode)
{
return true;
}
return false;
}
}
```
**Usage:**
```
if (!SmtpHelper.TestConnection(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)))
{
throw new ApplicationException("The smtp connection test failed");
}
``` | Can I test SmtpClient before calling client.Send()? | [
"",
"c#",
"email",
"smtpclient",
""
] |
I'm trying to send an email in html format using JavaMail but it always seems to only display as a text email in Outlook.
Here is my code:
```
try
{
Properties props = System.getProperties();
props.put("mail.smtp.host", mailserver);
props.put("mail.smtp.from", fromEmail);
props.put("mail.smtp.auth", authentication);
props.put("mail.smtp.port", port);
Session session = Session.getDefaultInstance(props, null);
// -- Create a new message --
MimeMessage message = new MimeMessage(session);
// -- Set the FROM and TO fields --
message.setFrom(new InternetAddress(fromEmail, displayName));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
MimeMultipart content = new MimeMultipart();
MimeBodyPart text = new MimeBodyPart();
MimeBodyPart html = new MimeBodyPart();
text.setText(textBody);
text.setHeader("MIME-Version" , "1.0" );
text.setHeader("Content-Type" , text.getContentType() );
html.setContent(htmlBody, "text/html");
html.setHeader("MIME-Version" , "1.0" );
html.setHeader("Content-Type" , html.getContentType() );
content.addBodyPart(text);
content.addBodyPart(html);
message.setContent( content );
message.setHeader("MIME-Version" , "1.0" );
message.setHeader("Content-Type" , content.getContentType() );
message.setHeader("X-Mailer", "My own custom mailer");
// -- Set the subject --
message.setSubject(subject);
// -- Set some other header information --
message.setSentDate(new Date());
// INFO: only SMTP protocol is supported for now...
Transport transport = session.getTransport("smtp");
transport.connect(mailserver, username, password);
message.saveChanges();
// -- Send the message --
transport.sendMessage(message, message.getAllRecipients());
transport.close();
return true;
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
throw e;
}
```
Any ideas why the html version of the email won't display in Outlook? | After a lot of investigation, I've been able to make some significant progress.
Firstly, instead of using JavaMail directly, I recommend using the [Jakarta Commons Email](http://commons.apache.org/email/) library. This really simplifies the issue a lot!
The code is now:
```
HtmlEmail email = new HtmlEmail();
email.setHostName(mailserver);
email.setAuthentication(username, password);
email.setSmtpPort(port);
email.setFrom(fromEmail);
email.addTo(to);
email.setSubject(subject);
email.setTextMsg(textBody);
email.setHtmlMsg(htmlBody);
email.setDebug(true);
email.send();
```
Talk about simple.
However, there is still an issue. The html version of the email works great in Gmail, Hotmail, etc. But it still won't correctly display in Outlook. It always wants to display the text version and I'm not sure why. I suspect it's a setting in Outlook, but I can't find it... | In addition to removing the `html.setHeader("Content-Type", html.getContentType())`
call as suggest already, I'd replace the line:
```
MimeMultipart content = new MimeMultipart();
```
…with:
```
MimeMultipart content = new MimeMultiPart("alternative");
```
…and removing the line:
```
message.setHeader("Content-Type" , content.getContentType() );
```
The default MimeMultiPart constructor could be causing problems with a "multipart/mixed" content-type.
When using multipart/alternative, the alternatives are ordered by how faithful they are to the original, with the best rendition last. However, clients usually give users an option to display plain text, even when HTML is present. Are you sure that this option is not enabled in Outlook? How do other user agents, like Thunderbird, or GMail, treat your messages?
Also, ensure that the HTML is well-formed. I'd validate the HTML content with the [W3 validation service](http://validator.w3.org/#validate_by_input+with_options), and possibly save it into a file and view it with different versions of IE too. Maybe there's a flaw there causing Outlook to fall back to plain text. | How to send html email to outlook from Java | [
"",
"java",
"email",
"jakarta-mail",
""
] |
Is there a simple process in SQL 2005 for spitting all of my stored procedures out to individual .sql files. I'd like to move them into VSS, but am not too excited by the prospect of clicking on each one to get the source, dumping it into a text file and so on.. | In SQL Management Studio right click on the database, go to tasks -> Generate Scripts, walkthrough the wizard. One of the pages will let you script each object to its own file. | You can run this select:
```
select
O.name, M.definition
from
sys.objects as O
left join
sys.sql_modules as M
on O.object_id = M.object_id
where
type = 'P'
```
and you get the name and source code for stored procedures.
Propably most easy way, how to put it in files is in some "classic" languge like c#, java, etc ... | Stored Procedures to .sql files | [
"",
"sql",
"sql-server",
"sql-server-2005",
"stored-procedures",
""
] |
Suppose I have two classes with the same interface:
```
interface ISomeInterface
{
int foo{get; set;}
int bar{get; set;}
}
class SomeClass : ISomeInterface {}
class SomeOtherClass : ISomeInterface {}
```
Suppose I have an instance of ISomeInterface that represents a SomeClass. Is there an easy way to copy that into a new instance of SomeOtherClass without copying each member by hand?
**UPDATE:** For the record, I'm *not* trying to cast the instance of SomeClass into the instance of SomeOtherClass. What I'd like to do is something like this:
```
ISomeInterface sc = new SomeClass() as ISomeInterface;
SomeOtherClass soc = new SomeOtherClass();
soc.foo = sc.foo;
soc.bar = soc.bar;
```
I just don't want to have to do that for each by hand as these objects have lots of properties. | "Would you be able to give me an example of how I can do that (or at least point me towards the right methods to be using)? I don't seem to be able to find them on MSDN" – Jason Baker
Jason, something like the following:
```
var props = typeof(Foo)
.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo p in props)
{
// p.Name gives name of property
}
```
I'd suggest writing a tool to spit out the code you need for a copy constructor, as opposed to doing it reflectively at runtime - which would be less performant. | You can create implicit operators in each class to do the conversion for you:
```
public class SomeClass
{
public static implicit operator SomeOtherClass(SomeClass sc)
{
//replace with whatever conversion logic is necessary
return new SomeOtherClass()
{
foo = sc.foo,
bar = sc.bar
}
}
public static implicit operator SomeClass(SomeOtherClass soc)
{
return new SomeClass()
{
foo = soc.foo,
bar = soc.bar
}
}
//rest of class here
}
```
and then `SomeOtherClass soc = sc;` and vice versa would work. | Using an interface to convert an object from one type to another? | [
"",
"c#",
".net",
".net-3.5",
"interface",
"copying",
""
] |
I'm trying to write a macro that would allow me to do something like: `FORMAT(a << "b" << c << d)`, and the result would be a string -- the same as creating an ostringstream, inserting `a...d`, and returning `.str()`. Something like:
```
string f(){
ostringstream o;
o << a << "b" << c << d;
return o.str()
}
```
Essentially, `FORMAT(a << "b" << c << d) == f()`.
First, I tried:
```
1: #define FORMAT(items) \
((std::ostringstream&)(std::ostringstream() << items)).str()
```
If the very first item is a C string (`const char *`), it will print the address of the string in hex, and the next items will print fine. If the very first item is an `std::string`, it will fail to compile (no matching operator `<<`).
This:
```
2: #define FORMAT(items) \
((std::ostringstream&)(std::ostringstream() << 0 << '\b' << items)).str()
```
gives what seems like the right output, but the `0` and `\b` are present in the string of course.
The following seems to work, but compiles with warnings (taking address of temporary):
```
3: #define FORMAT(items) \
((std::ostringstream&)(*((std::ostream*)(&std::ostringstream())) << items)).str()
```
Does anyone know why 1 prints the address of the c-string and fails to compile with the `std::string`? Aren't 1 and 3 essentially the same?
I suspect that C++0x variadic templates will make `format(a, "b", c, d)` possible. But is there a way to solve this now? | You've all pretty much nailed this already. But it's a little challenging to follow. So let me take a stab at summarizing what you've said...
---
That difficulties here are that:
* We are playing with a temporary `ostringstream` object, so taking addresses is contra-indicated.
* Because it's a temporary, we cannot trivially convert to an `ostream` object through casting.
* Both the constructor [obviously] and `str()` are class `ostringstream` methods.
(Yes, we need to use `.str()`. Using the `ostringstream` object directly would wind up invoking `ios::operator void*()`, returning a pointer-like good/bad value and not a string object.)
* `operator<<(...)` exists as both inherited `ostream` methods and global functions. In all cases it returns an `ostream&` reference.
* The choices here for `ostringstream()<<"foo"` are the inherited method `ostream::operator<<(void* )` and the global function `operator<<(ostream&,const char* )`. The inherited `ostream::operator<<(void* )` wins out because we can't convert to an `ostream` object reference to invoke the global function. [Kudos to *coppro*!]
---
So, to pull this off, we need to:
* Allocate a temporary `ostringstream`.
* Convert it to an `ostream`.
* Append data.
* Convert it back to an `ostringstream`.
* And invoke `str()`.
---
***Allocating:*** `ostringstream()`.
***Converting:*** There are several choices. Others have suggested:
* `ostringstream() << std::string() // Kudos to *David Norman*`
* `ostringstream() << std::dec // Kudos to *cadabra*`
***Or we could use:***
* `ostringstream() . seekp( 0, ios_base::cur )`
* `ostringstream() . write( "", 0 )`
* `ostringstream() . flush()`
* `ostringstream() << flush`
* `ostringstream() << nounitbuf`
* `ostringstream() << unitbuf`
* `ostringstream() << noshowpos`
* Or any other standard manipulator. [`#include <iomanip>`] [Reference: See *"Insert data with format"* 1/3 of the way down on this webpage.](http://www.cplusplus.com/reference/iostream/ostream/operator%3C%3C.html)
***We cannot use:***
* `operator<<( ostringstream(), "" )`
* `(ostream &) ostringstream()`
***Appending:*** Straightforward now.
***Converting back:*** We could just use `(ostringstream&)`. But a `dynamic_cast` would be safer. In the unlikely event `dynamic_cast` returned `NULL` (it shouldn't), the following `.str()` will trigger a coredump.
***Invoking `str()`:*** Guess.
---
Putting it all together.
```
#define FORMAT(ITEMS) \
( ( dynamic_cast<ostringstream &> ( \
ostringstream() . seekp( 0, ios_base::cur ) << ITEMS ) \
) . str() )
```
---
References:
* [IOstream Library](http://www.cplusplus.com/reference/iostream/)
* [`ostringstream`](http://www.cplusplus.com/reference/iostream/ostringstream/)
* [`ostream::operator<<()`](http://www.cplusplus.com/reference/iostream/ostream/operator%3C%3C/)
* [Type Casting Tutorial](http://www.cplusplus.com/doc/tutorial/typecasting.html)
* [Wiki: Type Casting](http://en.wikibooks.org/wiki/C%2B%2B_Programming/Type_Casting)
. | Here is what I use. It all fits into one tidy class definition in a header file.
**update:** major improvement to the code thanks to [litb](https://stackoverflow.com/users/34509/litb).
```
// makestring.h:
class MakeString
{
public:
std::stringstream stream;
operator std::string() const { return stream.str(); }
template<class T>
MakeString& operator<<(T const& VAR) { stream << VAR; return *this; }
};
```
Here is how it is used:
```
string myString = MakeString() << a << "b" << c << d;
``` | C++ format macro / inline ostringstream | [
"",
"c++",
"format",
"printing",
"macros",
"ostringstream",
""
] |
```
[hannel,192.168.0.46:40014] 15:08:03,642 - ERROR - org.jgroups.protocols.UDP - failed sending message to null (61 bytes)
java.lang.Exception: dest=/225.1.2.46:30446 (64 bytes)
at org.jgroups.protocols.UDP._send(UDP.java:333)
at org.jgroups.protocols.UDP.sendToAllMembers(UDP.java:283)
at org.jgroups.protocols.TP.doSend(TP.java:1327)
at org.jgroups.protocols.TP.send(TP.java:1317)
at org.jgroups.protocols.TP.down(TP.java:1038)
at org.jgroups.protocols.PING.sendMcastDiscoveryRequest(PING.java:220)
at org.jgroups.protocols.PING.sendGetMembersRequest(PING.java:214)
at org.jgroups.protocols.Discovery$PingSenderTask$1.run(Discovery.java:385)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:417)
at java.util.concurrent.FutureTask$Sync.innerRunAndReset(FutureTask.java:280)
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:135)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$101(ScheduledThreadPoolExecutor.java:65)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.runPeriodic(ScheduledThreadPoolExecutor.java:142)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:166)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:650)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:675)
at java.lang.Thread.run(Thread.java:595)
Caused by: java.io.InterruptedIOException: operation interrupted
at java.net.PlainDatagramSocketImpl.send(Native Method)
at java.net.DatagramSocket.send(DatagramSocket.java:612)
at org.jgroups.protocols.UDP._send(UDP.java:324)
... 16 more
```
This is happening during load testing on the server. Should I worry about it. Aside from getting that message in the log, everything seem to work OK. | In response to matt b, the "failed sending message to null" message is misleading. The true problem is the InterruptedIOException. This means that someone called interrupt() on the Thread that was sending UDP. Most likely, the interrupt is generated within JGroups. (Unless you started, and then stopped the JGroups channel.)
Looking at the stack trace, the interrupted I/O was from a Discovery protocol. It was trying to discover other cluster members. Thus, no message of yours was lost from this Exception.
We would have to know more to really figure this one out. | Sending to "null" means sending to the entire cluster, versus sending a message to a single member. I agree, this is a bit misleading, so I changed this in later version: IIRC "null" was replaced to with "cluster" or "group".
"null" here referred to the destination: a null destination address means send to the entire cluster.
The InterruptedIOException comes from the sender thread being stopped by JGroups; this happens for example when we already have enough responses in the discovery phase to return, and so the send task is stopped (ie., interrupted).
This was also fixed in later versions of JGroups.
Bela | org.jgroups.protocols.UDP - failed sending message to null | [
"",
"java",
"networking",
"jgroups",
""
] |
We have a pretty big ASP.NET WebForm (web application) project with a lot of references to other libraries, other projects etc and most of the time after a compilation, the first time we load a page it takes a LONG time before rendering anything... Disk IO is the main problem. For small projects it's nearly instantaneous, but once your project gets large, it can really slow development and remove fun from programming.
My question:
Is first page load time after a compilation as long in ASP.NET MVC as it is in ASP.NET Webforms for big projects? | MVC still uses the same ASP.NET framework as Web Forms, so you are probably going to see similar behavior, regardless.
The long first load time is because your project's build output is still just IL code that needs to be compiled into native code by the JIT compiler before executing. Any code changes that you make will cause the previously cached native code for your app to be discarded, so the JIT has to recompile. Naturally, the larger your project, the longer it's going to take for the JIT to process it. | You will see similar load times in both environments.
In both environments, if your site gets large you should pre-compile your site before deployment. This will eliminate the performance drag on first page load. | ASP.NET MVC vs WebForms for First Page Load Speed for Big Projects | [
"",
"c#",
"asp.net-mvc",
"performance",
"webforms",
""
] |
I have a table in a database that represents dates textually (i.e. "2008-11-09") and I would like to replace them with the UNIX timestamp. However, I don't think that MySQL is capable of doing the conversion on its own, so I'd like to write a little script to do the conversion. The way I can think to do it involves getting all the records in the table, iterating through them, and updating the database records. However, with no primary key, I can't easily get the exact record I need to update.
Is there a way to get MySQL to assign temporary IDs to records during a SELECT so that I refer back to them when doing UPDATEs? | Does this not do it?
```
UPDATE
MyTable
SET
MyTimeStamp = UNIX_TIMESTAMP(MyDateTime);
``` | If for some reason you do have to iterate (the other answers cover the situation where you don't), I can think of two ways to do it (these aren't MySQL-specific):
1. Add a column to the table that's an auto-assigned number. Use that as the PK for your updates, then drop the column afterwards (or just keep it around for future use).
2. In a table with no defined PK, as long as there are no exact duplicate rows, you can use the entire row as a composite PK; just use every column in the row as your distinguishing characteristic. i.e., if the table has 3 columns, "name", "address", and "updated", do the following:
UPDATE mytable SET updated = [timestamp value] WHERE name = [name] AND address = [address] AND timestamp = [old timestamp]
Many data access frameworks use this exact strategy to implement optimistic concurrency. | Change each record in a table with no primary key? | [
"",
"sql",
"mysql",
"primary-key",
""
] |
My problem is that I want a grid that is populated with a set of times spent on tasks. It needs to have the days of the week at the top (these would preferably be fixed - i.e. Sun, Mon... Sat) and task names down the left column. The contents of the grid will have the individual hours spent for that day on that task.
What would the best approach to take to achieve this? Option one would be to try and put it all in SQL statements in the database. Option two is a collection of LINQ queries that pull raw data from a Tasks and TimeEntries and structure it correctly. Option three is to use LINQ and pull the results into a class (or collection), which is then bound to the control (probably a gridview).
How would you do this? | I'll take a rough hack at it not knowing your structure but guessing you have a task table and a tasktime table that stores the actual times and dates that are charged to each task. This isn't tested but:
select t.taskname, sum(case when datepart(d,tt.taskdate)= 1, tt.taskhours) else 0 end) as Sunday,
sum(case when datepart(d,tt.taskdate)= 2, t.taskhours) else 0 end) as Monday
from tasktable t
join tasktime tt on t.taskid = tt.taskid
where tt.taskdate >= @begindate and tt.taskdate<= @enddate
The where clause is important because you probably only want to display a week at time (usually the current week) on your grid. This also assumes you have properly stored the ddates of your hours charged as datetime data type. (if you haven't fix that now - you will thank me later.) The variables would be submitted from the user interface in some fashion. I personally would do that as a stored proc. I left Tues through Saturday for you to do. | You seem to imply that the data currently resides in a database. The optimal solution depends on the amount of internal processing of the data and the existing infrastructure of the project.
I would either use a big SQL query to pull all the data together and bind the `ResultSet` directy to the Grid (little to no processing or infrastructure) or use LINQ to populate a kind of `TimeSheetModel` class, using existing infrastructure and enabling further processing. | Timesheets: Retrieve data using SQL, LINQ or class? | [
"",
"c#",
"asp.net",
"sql-server",
"linq",
"design-patterns",
""
] |
I am running C# framework 2.0 and I would like to get some of the data from a list? The list is a List<>. How can I do that without looping and doing comparaison manually on each element of the List<>? | You can try Predicate. Here is a code I wrote to illustrate the point. Of course, as you can see in this example, you can move the Predicate outside the calling class and have a control on it. This is useful if you need to have more option with it. Inside the predicate you can do many comparison with all property/function of your object.
```
static void Main()
{
List<SimpleObject> list = new List<SimpleObject>();
list.Add(new SimpleObject(1,"Jon"));
list.Add(new SimpleObject( 2, "Mr Skeet" ));
list.Add(new SimpleObject( 3,"Miss Skeet" ));
Predicate<SimpleObject> yourFilterCriteria = delegate(SimpleObject simpleObject)
{
return simpleObject.Name.Contains("Skeet");
};
list = list.FindAll(yourFilterCriteria);//Get only name that has Skeet : Here is the magic
foreach (SimpleObject o in list)
{
Console.WriteLine(o);
}
Console.Read();
}
public class SimpleObject
{
public int Id;
public string Name;
public SimpleObject(int id, string name)
{
this.Id=id;
this.Name=name;
}
public override string ToString()
{
return string.Format("{0} : {1}",Id, Name);
}
}
``` | If I follow your question correctly, you can just call the `Find()` or `FindAll()` methods to get data items out of the list. For example:
```
List<string> myList = ..;
List<string> startingWithA = myList.FindAll(delegate(string s) { return s.StartsWith("A"); });
``` | How do get some of the object from a list without Linq? | [
"",
"c#",
".net",
".net-2.0",
"c#-2.0",
""
] |
I have an owner-drawn UserControl where I've implemented double-buffering. In order to get double-buffering to work without flicker, I have to override the OnPaintBackground event like so:
```
protected override void OnPaintBackground(PaintEventArgs e)
{
// don't even have to do anything else
}
```
This works great at runtime. The problem is that when I have an instance of the control on a form at design time, it becomes a black hole that shows trails of whatever windows are dragged over it (because the override of the OnPaintBackground event also governs design-time appearance). It's just a cosmetic problem, but it's visually jarring and it always leads new developers on the project to assume something has gone horribly wrong.
Is there any way to have an overridden method like this not be overridden at design time, or is there another solution? | Steven Lowe's solution unfortunately cover all scenarios, espcially when user controls come into the picture.
The this.DesignMode flag is very deceptive. Its only scope is to check if the direct parent is within the designer.
For instance, if you have a Form A, and a UserControl B, in the designer:
* A.DesignMode is true when viewed in designer
* B.DesignMode is false when viewing A, but true when looking directly at B in the designer.
The solution to this is a special flag to check (sorry for the ugly C++ code):
```
if(this->DesignMode ||
LicenseManager::UsageMode == LicenseUsageMode::Designtime)
return;
```
This variable will always show the proper design boolean. | ```
if (this.DesignMode)
{
return; //or call base.OnPaintBackground()
}
``` | Controlling designer appearance of double-buffered owner-drawn UserControl in C#/.NET 2.0 | [
"",
"c#",
".net",
"user-controls",
".net-2.0",
""
] |
I'm a C# developer. I develop both Windows & Web Applications. I would like to build an Winforms application that has a role-based system. All users must in role/group(s). Then we assign permissions like "View, Add, Update,.." to role/group. The role/group is dynamic, so we let users to define it.
Is there any frameworks and good sample projects to implement it? | I usually roll my own, since the .NET Framework is pretty full-featured in this regard, but you might try the [MS Authorization and Profile Application Block](http://www.microsoft.com/downloads/details.aspx?familyid=ba983ad5-e74f-4be9-b146-9d2d2c6f8e81&displaylang=en). | For the grungy implementation details, have you looked at "principals"? See my reply [here](https://stackoverflow.com/questions/351415/how-do-you-find-the-users-nameidentity-in-c#351876). With this approach, you can use roles-based security in the code - such as:
```
[PrincipalPermission(SecurityAction.Demand, Role="ADMIN")]
static void SomeMethod()
{...}
```
The runtime itself will now verify that the user has to have your "ADMIN" role to get into that method (obviously you could also disable the option in the UI by checking `IsInRole(...)`). Very powerful. | Any frameworks on Authentication & Authorization for Windows Form Application? | [
"",
"c#",
".net",
"winforms",
"authentication",
"authorization",
""
] |
I have the following Transact-Sql that I am trying to convert to LINQ ... and struggling.
```
SELECT * FROM Project
WHERE Project.ProjectId IN (SELECT ProjectId FROM ProjectMember Where MemberId = 'a45bd16d-9be0-421b-b5bf-143d334c8155')
```
Any help would be greatly appreciated ... I would like to do it with Lambda expressions, if possible.
Thanks in advance! | GFrizzle beat me to it. But here is a C# version
```
var projectsMemberWorkedOn = from p in Projects
join projectMember in ProjectMembers on
p.ProjectId equals projectMember.ProjectId
where projectMember.MemberId == "a45bd16d-9be0-421b-b5bf-143d334c8155"
select p;
```
And as a bonus a purely LINQ method chain version as well:
```
var projectsMemberWorkedOn =
Projects.Join( ProjectMembers, p => p.ProjectId, projectMember => projectMember.ProjectId,
( p, projectMember ) => new { p, projectMember } )
.Where( @t => @t.projectMember.MemberId == "a45bd16d-9be0-421b-b5bf-143d334c8155" )
.Select(@t => @t.p );
``` | In this context, you can just use .Contains(), something like this:
```
var projects =
from p in db.Projects
where db.ProjectMembers.Where(m => m.MemberId == "a45bd16d-9be0-421b-b5bf-143d334c8155").Select(pp => pp.ProjectID).Contains(p.ProjectID)
select p;
``` | How do you do an IN or CONTAINS in LINQ using LAMBDA expressions? | [
"",
"sql",
"linq-to-sql",
"lambda",
""
] |
I'm an old (but not too old) Java programmer, that decided to learn C++. But I have seen that much of C++ programming style, is... well, just damn ugly!
All that stuff of putting the class definition in a header file, and the methods in a different source file- Calling functions out of nowhere, instead of using methods **inside classes**. All that just seems... wrong!
So finally, is there any reason for me to continue with this massacre to the OOP, and anything that is good and righteous in programming, or can I just ignore that old-fashioned C++ conventions, and use my good Java programing style?
By the way I'm learning C++, because I want to do game programing.
Here is an example:
In an C++ website I found a Windows implementation:
```
class WinClass
{
public:
WinClass (WNDPROC wndProc, char const * className, HINSTANCE hInst);
void Register ()
{
::RegisterClass (&_class);
}
private:
WNDCLASS _class;
};
```
That class is located in a header file and the constructor:
```
WinClass::WinClass (WNDPROC wndProc, char const * className, HINSTANCE hInst)
{
_class.style = 0;
_class.lpfnWndProc = wndProc; // Window Procedure: mandatory
_class.cbClsExtra = 0;
_class.cbWndExtra = 0;
_class.hInstance = hInst; // Owner of the class: mandatory
_class.hIcon = 0;
_class.hCursor = ::LoadCursor (0, IDC_ARROW); // Optional
_class.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1); // Optional
_class.lpszMenuName = 0;
_class.lpszClassName = className; // Mandatory
}
```
Is located at a .cpp source file.
What I could just do is:
```
class WinClass
{
public:
WinClass (WNDPROC wndProc, char const * className, HINSTANCE hInst)
{
_class.style = 0;
_class.lpfnWndProc = wndProc; // Window Procedure: mandatory
_class.cbClsExtra = 0;
_class.cbWndExtra = 0;
_class.hInstance = hInst; // Owner of the class: mandatory
_class.hIcon = 0;
_class.hCursor = ::LoadCursor (0, IDC_ARROW); // Optional
_class.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1); // Optional
_class.lpszMenuName = 0;
_class.lpszClassName = className; // Mandatory
}
void Register ()
{
::RegisterClass (&_class);
}
private:
WNDCLASS _class;
};
```
And now the constructor is inside its class. | In addition to what others have said here, there are even more important problems:
1) Large translation units lead to longer compile times and larger
object file sizes.
2) Circular dependencies! And this is the big one. And it can almost
always be fixed by splitting up headers and source:
```
// Vehicle.h
class Wheel {
private:
Car& m_parent;
public:
Wheel( Car& p ) : m_parent( p ) {
std::cout << "Car has " << m_parent.numWheels() << " wheels." << std::endl;
}
};
class Car {
private:
std::vector< Wheel > m_wheels;
public:
Car() {
for( int i=0; i<4; ++i )
m_wheels.push_back( Wheel( *this ) );
}
int numWheels() {
return m_wheels.size();
}
}
```
No matter what order you put these in, one will always be lacking the definition of the other, even using forward declarations it won't work, since in the function bodies are using specifics about each class's symbol.
But if you split them up into proper .h and .cpp files and use forward declarations it will satisfy the compiler:
```
//Wheel.h
//-------
class Car;
class Wheel {
private:
Car& m_parent;
public:
Wheel( Car& p );
};
//Wheel.cpp
//---------
#include "Wheel.h"
#include "Car.h"
Wheel::Wheel( Car& p ) : m_parent( p ) {
std::cout << "Car has " << m_parent.numWheels() << " wheels." << std::endl;
}
//Car.h
//-----
class Wheel;
class Car {
private:
std::vector< Wheel > m_wheels;
public:
Car();
int numWheels();
}
//Car.cpp
//-------
#include "Car.h"
#include "Wheel.h"
Car::Car() {
for( int i=0; i<4; ++i )
m_wheels.push_back( Wheel( *this ) );
}
int Car::numWheels() {
return m_wheels.size();
}
```
Now the code that actually has to know specifics about the second class can just include the header file which doesn't need to know specifics about the first class.
Headers just provide the *declarations* while source files provide the *definitions*. Or another way to say it: Headers tell you what is there (*what symbols are valid to use*) and source tells the compiler what the symbols actually do. In C++ you don't need anything more than a valid symbol to begin using whatever it is.
Trust that C++ has a reason for this idiom, because if you don't you will make a lot of headaches for yourself down the line. I know :/ | When the code builds, the C++ preprocessor builds a translation unit. It starts with a .cpp file, parses the #includes grabbing the text from the headers, and generates one great big text file with all the headers and the .cpp code. Then this translation unit gets compiled into code that will run on the platform you're targeting. Each translation unit ends up as one object file.
So, .h files get included in multiple translation units, and a .cpp file just gets included in one.
If .h files contain lots of stuff (including implementation), then the translation units would be correspondingly bigger. Compile times would increase, and when you change anything in a header... every translation unit that uses it would need to be recompiled.
So.. minimizing stuff in .h files drastically improves compile time. You can edit a .cpp file to change a function, and only that one translation unit needs to be rebuilt.
To complete the story on compiling...
Once all the translation units are build into object files (native binary code for you platform). The linker does its job, and stitches them together into you .exe, .dll or .lib file. A .lib file can be linked into another build so it can be reused in more than one .exe or .dll.
I suppose the Java compilation model is more advanced, and the implications of where you put your code have less meaning. | C++ programming style | [
"",
"c++",
"windows",
"oop",
""
] |
[Path.Combine](https://msdn.microsoft.com/en-us/library/system.io.path.combine%28v=vs.110%29.aspx) is handy, but is there a similar function in the .NET framework for [URLs](http://en.wikipedia.org/wiki/Uniform_resource_locator)?
I'm looking for syntax like this:
```
Url.Combine("http://MyUrl.com/", "/Images/Image.jpg")
```
which would return:
`"http://MyUrl.com/Images/Image.jpg"` | There [is a Todd Menier's comment above](https://stackoverflow.com/questions/372865/path-combine-for-urls/43582421#comment33212350_372865) that [Flurl](https://flurl.dev/) includes a `Url.Combine`.
More details:
> Url.Combine is basically a Path.Combine for URLs, ensuring one
> and only one separator character between parts:
```
var url = Url.Combine(
"http://MyUrl.com/",
"/too/", "/many/", "/slashes/",
"too", "few?",
"x=1", "y=2"
// result: "http://www.MyUrl.com/too/many/slashes/too/few?x=1&y=2"
```
Get [Flurl.Http on NuGet](https://www.nuget.org/packages/Flurl.Http/):
PM> Install-Package Flurl.Http
Or [get the stand-alone URL builder](https://www.nuget.org/packages/Flurl/) without the HTTP features:
PM> Install-Package Flurl | [`Uri`](https://learn.microsoft.com/en-us/dotnet/api/system.uri) has a constructor that should do this for you: `new Uri(Uri baseUri, string relativeUri)`
Here's an example:
```
Uri baseUri = new Uri("http://www.contoso.com");
Uri myUri = new Uri(baseUri, "catalog/shownew.htm");
```
Note from editor: Beware, this method does not work as expected. It can cut part of baseUri in some cases. See comments and other answers. | Path.Combine for URLs? | [
"",
"c#",
".net",
"asp.net",
"url",
"path",
""
] |
I found the following code to create a tinyurl.com url:
```
http://tinyurl.com/api-create.php?url=http://myurl.com
```
This will automatically create a tinyurl url. Is there a way to do this using code, specifically C# in ASP.NET? | You should probably add some error checking, etc, but this is probably the easiest way to do it:
```
System.Uri address = new System.Uri("http://tinyurl.com/api-create.php?url=" + YOUR ADDRESS GOES HERE);
System.Net.WebClient client = new System.Net.WebClient();
string tinyUrl = client.DownloadString(address);
Console.WriteLine(tinyUrl);
``` | After doing some more research ... I stumbled upon the following code:
```
public static string MakeTinyUrl(string url)
{
try
{
if (url.Length <= 30)
{
return url;
}
if (!url.ToLower().StartsWith("http") && !Url.ToLower().StartsWith("ftp"))
{
url = "http://" + url;
}
var request = WebRequest.Create("http://tinyurl.com/api-create.php?url=" + url);
var res = request.GetResponse();
string text;
using (var reader = new StreamReader(res.GetResponseStream()))
{
text = reader.ReadToEnd();
}
return text;
}
catch (Exception)
{
return url;
}
}
```
Looks like it may do the trick. | Using tinyurl.com in a .Net application ... possible? | [
"",
"c#",
".net",
"asp.net",
"api",
"tinyurl",
""
] |
I'm having a little bit of trouble making a sticky form that will remember what is entered in it on form submission if the value has double quotes. The problem is that the HTML is supposed to read something like:
```
<input type="text" name="something" value="Whatever value you entered" />
```
However, if the phrase: "How do I do this?" is typed in with quotes, the resulting HTML is similar to:
```
<input type="text" this?="" do="" i="" how="" value="" name="something"/>
```
How would I have to filter the double quotes? I've tried it with magic quotes on and off, I've used stripslashes and addslashes, but so far I haven't come across the right solution. What's the best way to get around this problem for PHP? | You want [htmlentities()](http://www.php.net/htmlentities).
`<input type="text" value="<?php echo htmlentities($myValue); ?>">` | The above will encode all sorts of characters that have html entity code. I prefer to use:
```
htmlspecialchars($myValue, ENT_QUOTES, 'utf-8');
```
This will only encode:
```
'&' (ampersand) becomes '&'
'"' (double quote) becomes '"' when ENT_NOQUOTES is not set.
''' (single quote) becomes ''' only when ENT_QUOTES is set.
'<' (less than) becomes '<'
'>' (greater than) becomes '>'
```
You could also do a strip\_tags on the $myValue to remove html and php tags. | Escaping double quotes in a value for a sticky form in PHP | [
"",
"php",
"validation",
"forms",
"filtering",
""
] |
How do I maintain the scroll position of the parent page when I open new window using window.open()? The parent page returns to the top of the page.
Here is my current code:
```
<a href="#" onclick="javascript: window.open('myPage.aspx');">
Open New Window
</a>
``` | ```
<a href="#" onclick="window.open('myPage.aspx');return false;">Open New Window</a>
```
* `javascript:` is not required in event attributes.
* You were not returning false from the event handler, so the link was being following, it was equivilent to `<a href="#">Scroll to top</a>`. | ```
<a href="javascript:void()" onclick="window.open('myPage.aspx');">Open New Window</a>
```
Ought to do it. As others have mentioned, the # is trying to go to a non-existent anchor, which will cause the browser to scroll to the top. You don't want to remove the href attribute, because some browsers don't treat `<a>` tags without href attributes as links for styling purposes, and you would have to define additional CSS rules to ge thte link to look like other links on your site.
Also, why have an href attribute and then try to block the event by always returning false from your handler. In my opinion, this way is cleaner than the others proposed here. | Maintain scroll position in Javascript window.open() | [
"",
"javascript",
""
] |
I have a paragraph of text in a javascript variable called 'input\_content' and that text contains multiple anchor tags/links. I would like to match all of the anchor tags and extract anchor text and URL, and put it into an array like (or similar to) this:
```
Array
(
[0] => Array
(
[0] => <a href="http://yahoo.com">Yahoo</a>
[1] => http://yahoo.com
[2] => Yahoo
)
[1] => Array
(
[0] => <a href="http://google.com">Google</a>
[1] => http://google.com
[2] => Google
)
)
```
I've taken a crack at it ([<http://pastie.org/339755>](http://pastie.org/339755)), but I am stumped beyond this point. Thanks for the help! | ```
var matches = [];
input_content.replace(/[^<]*(<a href="([^"]+)">([^<]+)<\/a>)/g, function () {
matches.push(Array.prototype.slice.call(arguments, 1, 4))
});
```
This assumes that your anchors will always be in the form `<a href="...">...</a>` i.e. it won't work if there are any other attributes (for example, `target`). The regular expression can be improved to accommodate this.
To break down the regular expression:
```
/ -> start regular expression
[^<]* -> skip all characters until the first <
( -> start capturing first token
<a href=" -> capture first bit of anchor
( -> start capturing second token
[^"]+ -> capture all characters until a "
) -> end capturing second token
"> -> capture more of the anchor
( -> start capturing third token
[^<]+ -> capture all characters until a <
) -> end capturing third token
<\/a> -> capture last bit of anchor
) -> end capturing first token
/g -> end regular expression, add global flag to match all anchors in string
```
Each call to our anonymous function will receive three tokens as the second, third and fourth arguments, namely arguments[1], arguments[2], arguments[3]:
* arguments[1] is the entire anchor
* arguments[2] is the href part
* arguments[3] is the text inside
We'll use a hack to push these three arguments as a new array into our main `matches` array. The `arguments` built-in variable is not a true JavaScript Array, so we'll have to apply the `split` Array method on it to extract the items we want:
```
Array.prototype.slice.call(arguments, 1, 4)
```
This will extract items from `arguments` starting at index 1 and ending (not inclusive) at index 4.
```
var input_content = "blah \
<a href=\"http://yahoo.com\">Yahoo</a> \
blah \
<a href=\"http://google.com\">Google</a> \
blah";
var matches = [];
input_content.replace(/[^<]*(<a href="([^"]+)">([^<]+)<\/a>)/g, function () {
matches.push(Array.prototype.slice.call(arguments, 1, 4));
});
alert(matches.join("\n"));
```
Gives:
```
<a href="http://yahoo.com">Yahoo</a>,http://yahoo.com,Yahoo
<a href="http://google.com">Google</a>,http://google.com,Google
``` | Since you're presumably running the javascript in a web browser, regex seems like a bad idea for this. If the paragraph came from the page in the first place, get a handle for the container, call `.getElementsByTagName()` to get the anchors, and then extract the values you want that way.
If that's not possible then create a new html element object, assign your text to it's .innerHTML property, and then call `.getElementsByTagName()`. | javascript regex to extract anchor text and URL from anchor tags | [
"",
"javascript",
"regex",
"anchor",
""
] |
I have a class A and another class that inherits from it, B. I am overriding a function that accepts an object of type A as a parameter, so I have to accept an A. However, I later call functions that only B has, so I want to return false and not proceed if the object passed is not of type B.
What is the best way to find out which type the object passed to my function is? | dynamic\_cast should do the trick
```
TYPE& dynamic_cast<TYPE&> (object);
TYPE* dynamic_cast<TYPE*> (object);
```
The [`dynamic_cast`](http://en.cppreference.com/w/cpp/language/dynamic_cast) keyword casts a datum from one pointer or reference type to another, performing a runtime check to ensure the validity of the cast.
If you attempt to cast to pointer to a type that is not a type of actual object, the result of the cast will be NULL. If you attempt to cast to reference to a type that is not a type of actual object, the cast will throw a [`bad_cast`](http://en.cppreference.com/w/cpp/types/bad_cast) exception.
**Make sure there is at least one virtual function in Base class to make dynamic\_cast work.**
Wikipedia topic [Run-time type information](https://en.wikipedia.org/wiki/Run-time_type_information)
> RTTI is available only for classes that are polymorphic, which means
> they have at least one virtual method. In practice, this is not a
> limitation because base classes must have a virtual destructor to
> allow objects of derived classes to perform proper cleanup if they are
> deleted from a base pointer. | Dynamic cast is the best for your description of problem,
but I just want to add that you can find the class type with:
```
#include <typeinfo>
...
string s = typeid(YourClass).name()
``` | Finding the type of an object in C++ | [
"",
"c++",
"types",
""
] |
I want to port few C/C++ libraries to Android, how feasible it would be
e.g. OpenSSL can it be ported
or suppose an application which depends on OpenSSL, what is the best way to port it to Android when Android I think itself has libssl.so
what are the tools available e.g. Scratchbox, any alternatives?
Has anybody experience with it? | The [android internals wiki](http://groups.google.com/group/android-internals) is a good starting point, and includes [a link](http://benno.id.au/blog/2007/11/13/android-native-apps) explaining how to compile simple native applications.
[Scratchbox](http://www.macrobug.com/blog/2007/11/25/using-scratchbox-to-build-complex-arm-binaries-for-android/) does seem to be the way to go for compiling more complex apps & libraries, as you probably know already. I would suggest contacting those folks to get a bearing on your OpenSSL project. | This should be very doable now with the release of the [Android NDK](http://developer.android.com/sdk/ndk/index.html). From their website:
> The Android NDK is a companion tool to the Android SDK that lets Android application developers build performance-critical portions of their apps in native code...
>
> The NDK provides:
>
> * A set of tools and build files used to generate native code libraries from C and C++ sources
> * A way to embed the corresponding native libraries into application package files (.apks) that can be deployed on Android devices
> * A set of native system headers and libraries that will be supported in all future versions of the Android platform, starting from Android 1.5
> * Documentation, samples, and tutorials | Porting C++ lib/app on android | [
"",
"c++",
"c",
"android",
"linux",
"embedded",
""
] |
What's the easiest way to play a sound file (.wav) in Python? By easiest I mean both most platform independent and requiring the least dependencies. pygame is certainly an option, but it seems overkill for just sound. | [The Snack Sound Toolkit](http://www.speech.kth.se/snack/) can play wav, au and mp3 files.
```
s = Sound()
s.read('sound.wav')
s.play()
``` | For Windows, you can use winsound. It's built in
```
import winsound
winsound.PlaySound('sound.wav', winsound.SND_FILENAME)
```
You should be able to use ossaudiodev for linux:
```
from wave import open as waveOpen
from ossaudiodev import open as ossOpen
s = waveOpen('tada.wav','rb')
(nc,sw,fr,nf,comptype, compname) = s.getparams( )
dsp = ossOpen('/dev/dsp','w')
try:
from ossaudiodev import AFMT_S16_NE
except ImportError:
from sys import byteorder
if byteorder == "little":
AFMT_S16_NE = ossaudiodev.AFMT_S16_LE
else:
AFMT_S16_NE = ossaudiodev.AFMT_S16_BE
dsp.setparameters(AFMT_S16_NE, nc, fr)
data = s.readframes(nf)
s.close()
dsp.write(data)
dsp.close()
```
(Credit for ossaudiodev: Bill Dandreta <http://mail.python.org/pipermail/python-list/2004-October/288905.html>) | Play a Sound with Python | [
"",
"python",
"audio",
"platform-independent",
""
] |
Right now we've got web pages that show UI elements, and web pages that just process form submissions, and then redirect back to the UI pages. They do this using PHP's header() function:
```
header("Location: /other_page.php");
```
This causes a 302 Found response to be sent; according to the HTTP 1.1 spec, 302 is for cases where "The requested resource resides temporarily under a different URI." [[HTTP 1.1 spec]](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.3)
Functionally, this is fine, but it doens't seem like this is the proper status code for what we're doing. It looks like 303 ("See Other") is the appropriate status here, so I'm wondering if there's any reason not to use it. We'd have to be more explicit in our use of header(), since we'd have to specify that status line rather than just a Location: field. Thoughts? | You can use either, but the proper statuscode to use for redirect-after-post is 303.
The confusion has a historical explanation. Originally, 302 specified that the browser mustn't change the method of the redirected request. This makes it unfit for redirect-after-post, where you want the browser to issue a GET request. However, all browsers seems to misinterpret the specs and always issue a GET request. In order to clear up the ambiguity HTTP/1.1 specified two new codes: 303 and 307. 303 essentially specifies the de-facto interpretation of 302, while 307 specifies the original specification of 302. So in practice 302 and 303 are interchangeable, and in theory 302 and 307 are.
If you *really* care about compatibility, 302 is a safer bet than 303, since HTTP/1.0 agents may not understand 303, but all modern browsers speak HTTP/1.1, so it isn't a real issue. I would recommend using 303, since that's the most correct thing to do.
On a side-note; The `Location` field should be a full URL. In practice it doesn't matter - browsers are forgiving - but if you care about the specs, that's the proper thing to do. | I've never used it myself... as it says in your link:
> Note: Many pre-HTTP/1.1 user agents do
> not understand the 303
> status. When interoperability with such clients is a concern, the
> 302 status code may be used instead, since most user agents react
> to a 302 response as described here for 303.
This seems a good enough reason to me to stick with 302.
FYI [header()](http://www.php.net/header) takes extra parameters in which you can set the status code:
`header('Location: /foo.php', true, 303);` | HTTP status for functional redirect | [
"",
"php",
"http",
"post",
"redirect",
"http-status-code-302",
""
] |
Do any of the existing JavaScript frameworks have a non-regex `replace()` function,
or has this already been posted on the web somewhere as a one-off function?
For example I want to replace `"@!#$123=%"` and I don't want to worry about which characters to escape. Most languages seem to have both methods of doing replacements. I would like to see this simple thing added. | i may be misunderstanding your question, but javascript does have a [`replace()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)
```
var string = '@!#$123=%';
var newstring = string.replace('@!#$123=%', 'hi');
```
**edit**: (see comments) the 5th edition does seem to have this info in it, although it doesn't show up when i [link directly](http://safari.informit.com/0596101996/jscript5-CHP-11-SECT-2) to it. here's the relevant part:
> The replace( ) method performs a search-and-replace operation. It takes a regular expression as its first argument and a replacement string as its second argument. It searches the string on which it is called for matches with the specified pattern. If the regular expression has the g flag set, the replace( ) method replaces all matches in the string with the replacement string; otherwise, it replaces only the first match it finds. **If the first argument to replace( ) is a string rather than a regular expression, the method searches for that string literally rather than converting it to a regular expression with the RegExp( ) constructor, as search( ) does.** | I had exactly the same problem searching for a non-regex javascript string replace() method. My solution was to use a combination of split() and join():
```
"some text containing regex interpreted characters: $1.00".split("$").join("£");
```
which gives:
> "some text containing regex interpreted characters: £1.00"
compare with replace():
```
"some text containing regex interpreted characters: $1.00".replace(new RegExp("$"),"£")
```
which bizarrely gives:
> "some text containing regex interpreted characters: $1.00£" | JavaScript Non-regex Replace | [
"",
"javascript",
""
] |
## What I'm trying to accomplish
* My app generates some tabular data
* I want the user to be able to launch Excel and click "paste" to place the data as cells in Excel
* Windows accepts a format called "CommaSeparatedValue" that is used with it's APIs so this seems possible
* Putting raw text on the clipboard works, but trying to use this format does not
* NOTE: I can correctly retrieve CSV data from the clipboard, my problem is about pasting CSV data to the clipboard.
## What I have tried that isn't working
Clipboard.SetText()
```
System.Windows.Forms.Clipboard.SetText(
"1,2,3,4\n5,6,7,8",
System.Windows.Forms.TextDataFormat.CommaSeparatedValue
);
```
Clipboard.SetData()
```
System.Windows.Forms.Clipboard.SetData(
System.Windows.Forms.DataFormats.CommaSeparatedValue,
"1,2,3,4\n5,6,7,8",
);
```
In both cases something is placed on the clipboard, but when pasted into Excel it shows up as one cell of garbarge text: "–§žý;pC¦yVk²ˆû"
## Update 1: Workaround using SetText()
As BFree's answer shows **SetText** with **TextDataFormat** serves as a workaround
```
System.Windows.Forms.Clipboard.SetText(
"1\t2\t3\t4\n5\t6\t7\t8",
System.Windows.Forms.TextDataFormat.Text
);
```
I have tried this and confirm that now pasting into Excel and Word works correctly. In each case it pastes as a table with cells instead of plaintext.
Still curious why CommaSeparatedValue is *not* working. | The .NET Framework places `DataFormats.CommaSeparatedValue` on the clipboard as Unicode text. But as mentioned at <http://www.syncfusion.com/faq/windowsforms/faq_c98c.aspx#q899q>, Excel expects CSV data to be a UTF-8 memory stream (it is difficult to say whether .NET or Excel is at fault for the incompatibility).
The solution I've come up with in my own application is to place two versions of the tabular data on the clipboard simultaneously as tab-delimited text and as a CSV memory stream. This allows the destination application to acquire the data in its preferred format. Notepad and Excel prefer the tab-delimited text, but you can force Excel to grab the CSV data via the Paste Special... command for testing purposes.
Here is some example code (note that WinForms-equivalents from the WPF namespaces are used here):
```
// Generate both tab-delimited and CSV strings.
string tabbedText = //...
string csvText = //...
// Create the container object that will hold both versions of the data.
var dataObject = new System.Windows.DataObject();
// Add tab-delimited text to the container object as is.
dataObject.SetText(tabbedText);
// Convert the CSV text to a UTF-8 byte stream before adding it to the container object.
var bytes = System.Text.Encoding.UTF8.GetBytes(csvText);
var stream = new System.IO.MemoryStream(bytes);
dataObject.SetData(System.Windows.DataFormats.CommaSeparatedValue, stream);
// Copy the container object to the clipboard.
System.Windows.Clipboard.SetDataObject(dataObject, true);
``` | Use tabs instead of commas. ie:
```
Clipboard.SetText("1\t2\t3\t4\t3\t2\t3\t4", TextDataFormat.Text);
```
Just tested this myself, and it worked for me. | How to paste CSV data to Windows Clipboard with C# | [
"",
"c#",
"windows",
"csv",
"clipboard",
"paste",
""
] |
I've created two functions to load expanded views of a month in the archive section of my blog when it's link is clicked:
```
// Load open view of a month in the Archive section
function loadMonth(date) {
// Remove other open month
removeMonth();
// Hide opening month's link
// Define variable to hold month anchor tag
var monthLink = document.getElementById(date);
monthLink.style.display = "none"; // Hide month anchor
// Define new open month node and its attributes
var openMonth = document.createElement("div");
openMonth.setAttribute("id", "openMonth");
openMonth.innerHTML = "Testing one, two, three.";
// Insert open month
// Define a variable to hold the archive Div node
var archive = document.getElementById("archive");
// Insert the open month in the archive node before it's link
archive.insertBefore(openMonth,monthLink);
return;
}
// Close full view of a month and replace with respective link
function removeMonth() {
// Define global function vars
var archive = document.getElementById("archive"); // Define a var to hold the archive Div node
var openMonth = document.getElementById("openMonth"); // Define var to hold the open month Div node
// Get date of full view month for replacement anchor tag where ID = date
var month = openMonth.getElementsByTagName("span")[0].innerHTML; // Define var to hold the name of the open month
var date = (new Date(month + " 15, 2008").getMonth() + 1); // Define var to hold the numerical equivalent of the month
var year = archive.getElementsByTagName("h3")[0].innerHTML.split(" "); // Define var to hold the year being displayed in the archive
date = year[1] + "" + date; // Change date var to string and insert year
// Remove the open month
archive.removeChild(openMonth);
// Show Link for that month
document.getElementById(date).className = "big"; // Fixes display error when anchor has class firstLink
document.getElementById(date).style.display = "inline"; // Returns link from display "none" state
return;
}
```
The functions work when run on the original static content, but when a second link is clicked in the archive, they do nothing. I am wondering if maybe because the elements that were created by my functions cannot be called by document.getElementById. Perhaps a different method of accessing those nodes should be used, or maybe replacing "document" with something that works on javascript created elements too?
Any advice would be greatly appreciated. Thanks. | To answer your main question: `document.getElementById` **does** work with dynamically added elements.
In your sample code you are creating the openMonth div and setting its innerHTML. Then in the remove tag you are doing this:
```
var month = openMonth.getElementsByTagName("span")[0].innerHTML;
```
`openMonth.getElementsByTagName("span")` will not exist and will get an error because there are no span elements. I don't know if this is a mistake in the code or if it is just a incomplete sample in the post. | You should be fine with:
```
openMonth.id = "openMonth";
```
`getElementById()` can only work if the element is part of the DOM, but since you already use `insertBefore()` this is merely a side note.
There is a common source of confusion involved here: An attribute *named* "id" is not necessarily the one that is *defined* as the element ID in the underlying DTD. In declarative HTML, they are linked automatically. When you use `setAttribute()`, you are not more than creating an attribute *named* "id". The element ID itself is accessible via the `.id` property.
*Edit*
The following works for me:
```
function test()
{
// create element, set ID
var p = document.createElement("P");
p.innerHTML = "Look ma, this is a new paragraph!";
p.id = "newParagraph";
// make element part of the DOM
document.getElementsByTagName("BODY")[0].appendChild(p);
// get element by ID
var test = document.getElementById("newParagraph");
alert(test.innerHTML);
}
``` | Does getElementById work on elements created by javascript? | [
"",
"javascript",
"html",
"dom",
""
] |
I'm building an application where I should capture several values and build a text with them: `Name`, `Age`, etc.
The output will be a plain text into a `TextBox`.
I am trying to make those information appear in kind of `columns`, therefore I am trying to separate them with `tab` to make it clearer.
For example, instead of having:
```
Ann 26
Sarah 29
Paul 45
```
I would like it to show as:
```
Ann 26
Sarah 29
Paul 45
```
Any tip on how to `insert` the tabs into my text? | Try using the `\t` character in your strings | Hazar is right with his `\t`. Here's the full list of escape characters for C#:
`\'` for a single quote.
`\"` for a double quote.
`\\` for a backslash.
`\0` for a null character.
`\a` for an alert character.
`\b` for a backspace.
`\f` for a form feed.
`\n` for a new line.
`\r` for a carriage return.
`\t` for a horizontal tab.
`\v` for a vertical tab.
`\uxxxx` for a unicode character hex value (e.g. `\u0020`).
`\x` is the same as `\u`, but you don't need leading zeroes (e.g. `\x20`).
`\Uxxxxxxxx` for a unicode character hex value (longer form needed for generating surrogates). | Inserting a tab character into text using C# | [
"",
"c#",
".net",
"vb.net",
""
] |
I need to debug JavaScript in Internet Explorer 7.
Unfortunately, its default debugger doesn't provide me with much information. It tells me the page that the error showed up on (not the specific script) and gives me a line number. I don't know if that is related to my problem.
It'd be nice if it could narrow down the error to a line number on a specific script (like Firebug can).
Is there an addon to debug JavaScript in IE7 like Firebug does in Firefox?
Thank you!
### See also:
[Does IE7 have a “developer mode” or plugin like Firefox/Chrome/Safari?](https://stackoverflow.com/questions/56615/does-ie7-have-a-developer-mode-or-plugin-like-firefoxchromesafari) | [Web Development Helper](http://web-development-helper.software.informer.com) is very good.
The [IE Dev Toolbar](http://www.microsoft.com/downloads/en/details.aspx?familyid=95E06CBE-4940-4218-B75D-B8856FCED535&displaylang=en) is often helpful, but unfortunately doesn't do script debugging | The hard truth is: the only good debugger for IE is Visual Studio.
If you don't have money for the real deal, download free ~~Visual Web Developer 2008 Express Edition~~[Visual Web Developer 2010 Express Edition](http://www.microsoft.com/web/gallery/install.aspx?appid=VWD2010SP1AzurePack). While the former allows you to attach debugger to already running IE, the latter doesn't (at least previous versions I used didn't allow that). If this is still the case, the trick is to create a simple project with one empty web page, "run" it (it starts the browser), now navigate to whatever page you want to debug, and start debugging.
Microsoft gives away full Visual Studio on different events, usually with license restrictions, but they allow tinkering at home. Check their schedule and the list of freebies.
Another hint: try to debug your web application with other browsers first. I had a great success with Opera. Somehow Opera's emulation of IE and its bugs was pretty close, but the debugger is much better. | Debugging JavaScript in IE7 | [
"",
"javascript",
"internet-explorer-7",
""
] |
I am currently working on converting an existing web application to support an additional language (namely Welsh). My proposed approach is to extract all displayed text into property files and then access the text using JSTL fmt tags.
My question is: how should these property files be structured? I know they need to be on the classpath for the web application, but rather than storing them directly in WEB-INF/classes I would prefer to copy them there during the build step. This leaves me a lot of flexibility in how to store the files in subversion. Since they are closely aligned with the jsps is it a good idea to create a new top-level directory (e.g. resources) and mirror the jsp structure under this folder? This would give me a structure like
```
resources/jsp/index.properties
resources/jsp/index_cy.properties
```
This seems like a reasonable approach and it is extensible to property files for classes too, if they should be required:
```
resources/com/mycompany/myapp/CustomObject.properties
resources/com/mycompany/myapp/CustomObject_cy.properties
```
The build process could then copy all of these files into WEB-INF/classes ready for packaging into the war file.
Is this approach in line with industry standards? This is the first multilingual application for my current company, so it is likely to be used as a blueprint for all others.
Edit: It has been pointed out that this approach could lead to a lot of duplicated strings in the various property files. While this is true, it would only be as many duplicated strings as currently exist in the jsps. Is it better to have a clear mapping from jsp to property files, at the cost of some duplication in the property files? | > Is this approach in line with industry standards? This is the first multilingual application for my current company, so it is likely to be used as a blueprint for all others.
Yes, I think it is.
I believe Maven creates the following directory structure:
```
src
+- main
| |- java
| |- resources
+- test
|- java
|- resources
```
Which gives you a nice clean separation between your code and unit tests, and then between java code and resources such as property files etc. | > It has been pointed out that this
> approach could lead to a lot of
> duplicated strings in the various
> property files. While this is true, it
> would only be as many duplicated
> strings as currently exist in the
> jsps. Is it better to have a clear
> mapping from jsp to property files, at
> the cost of some duplication in the
> property files?
Yes, this is always better. While it is possible to 'reuse' a string at different places / JSPs in English, it still might not be possible in other languages. Reuse of localized strings could also create unwanted and tricky dependencies between components that are otherwise unrelated.
The translators also need to be aware of use of texts they translate in your application. | How should I structure resource bundle property files which are used by jsps? | [
"",
"java",
"jsp",
"jakarta-ee",
"internationalization",
""
] |
A program that I work on assumes that the UUID generated by the Windows RPC API call UuidCreateSequential() contains the MAC address of the primary ethernet adapter. Is this assumption correct or should I use a different method to get the MAC address? | I wouldn't rely on this - the only reason that UuidCreateSequential has the MAC address is it's trying to guarantee that the UUID is unique across the network. Plus, why would you use such a weird way to get a MAC address? Use WMI and *actually* ask for the MAC address instead of a side-effect of a UUID creation function. | This appears to be a valid assumption. The documentation on [MSDN](http://msdn.microsoft.com/en-us/library/aa379322.aspx) specifically says this will contain the address of the ethernet card on the machine. It doesn't mention anything about a mult-card scenario but picking the primary card appears to be a logical leap. | Extracting MAC addresses from UUIDs | [
"",
"c++",
"windows",
"uuid",
""
] |
```
<?php
function data_info($data)
{
if ($data) {
while (!feof($data)) {
$buffer = fgets($data);
if (file_exists($buffer)) {
$bufferArray[$buffer]['Exists'] = (file_exists($buffer));
$bufferArray[$buffer]['Readable'] = (is_readable($buffer));
$bufferArray[$buffer]['Writable'] = (is_writable($buffer));
$bufferArray[$buffer]['Size'] = (filesize($buffer));
} else {
$bufferArray[$buffer]['Exists'] = "No";
}
}
print_r($bufferArray);
} else {
echo "The file could not be opened";
}
}
$data = fopen("D:/xampp/htdocs/Practice/ficheros.txt", "r");
data_info($data);
?>
```
If I have this:
ficheros.txt:
ExistingFile.txt
ExistingFile2.txt
ExistingFile3.txt...
...
It works, but If I have at least 1 NON EXISTING FILE then It will take every file as a non existing one too.
What's wrong? I believe someting in the inner if condition.
---
I mean, what is wrong with the entire code.
I just need to make an array with arrays in it, a good result would be:
```
array
(
'text.txt' => array
(
'exists' => true,
'readable' => true,
'writable' => true,
'Size' => 64
),
'document.doc' => array
(
'exists' => false
),
'photo.jpg' => array
(
'exists' => true,
'readable' => true,
'writable' => false,
'size' => 354915
)
)
``` | Hmm, well that works in Linux (though I have to trim the filename `$buffer` first). | Yeah, It works for me too if I have in ficheros.txt
```
Existingfile.txt
AnotherExistingfile.txt
```
Or
```
FakeFile.txt
FakeFile2.txt
```
But If I combine both of them:
```
Fakefile.txt
Existingfile.txt
```
It won't work, the script in the last case takes both files as non existing ones. | File exists php code | [
"",
"php",
""
] |
I have written a function that gets a given number of random records from a list. Currently I can do something like:
```
IEnumerable<City> cities = db.Cites.GetRandom(5);
```
(where db is my DataContext connecting to a SQL Server DB)
Currently, I have a function like this in every entity I need random records from:
```
public partial class City
{
public static IEnumerable<City> GetRandom(int count)
{
Random random = new Random();
IEnumerable<City> cities = DB.Context.Cities.OrderBy( c => random.Next() ).Take(count);
return cities;
}
}
```
It works fine, but I'd like it to be generic, so it can work for any table, or even any list of items. I have tried an extension method like:
```
public static IEnumerable<T> GetRandom<T>( this Table<T> table, int count)
{
Random random = new Random();
IEnumerable<T> records = table.OrderBy(r => random.Next()).Take(count);
return records;
}
```
but I get:
```
Error 1 The type 'T' must be a reference type in order to use it as parameter 'TEntity' in the generic type or method 'System.Data.Linq.Table'
```
which highlights `GetRandom<T>`.
I don't understand what the problem is here. Can someone clear up the proper syntax? | JaredPar, I don't think you can do that with the :class inside the generic definition.
I think this is the proper way to define type constraints:
```
public static IEnumerable<T> GetRandom<T>( this Table<T> table, int count) where T : class {
...
}
```
More info on type constraints [here](http://msdn.microsoft.com/en-us/library/d5x73970.aspx) | I like the idea of a random order function, and it can be applied to any IEnumerable like so:
```
public static IEnumerable<T> Randomize<T>(this IEnumerable<T> source)
{
Random rnd = new Random();
return source.OrderBy(t => rnd.Next());
}
...
IEnumerable<City> cities = db.Cites.Randomize().Take(5);
``` | Custom Linq Extension Syntax | [
"",
"c#",
"linq",
"generics",
"extension-methods",
""
] |
On a site where 90% of the pages use the same libraries, should you just load the libraries all the time or only load them when needed? The other pages would be ajax or simple pages that don't have any real functionality.
Also, should you only load the code when needed? If part way down a page you need a library, should you load it then or just load it at the top. Maybe it's possible it may never get there before of an error or wrong data. (Loading at the top makes it somewhat easier to understand, but may result in extra code not needed.)
I'm also wondering if I should make the libraries more specific so I'm not say loading the code to edit at the same time as viewing?
Basically, how much should I worry about loading code or not loading code? | I would always try to give a file, class, and method a [single responsibility](http://en.wikipedia.org/wiki/Single_responsibility_principle "Single responsibility principle - Wikipedia, the free encyclopedia"). Because of that, separating the displaying from the editing code could be a good idea in either case.
As for loading libraries, I believe that the performance loss of including non required libraries could be quite irrelevant in a lot of cases. However, `include`, `require`, `include_once`, and `require_once` are relatively slow as they (obviously) access the file system. If the libraries you do not use on each occasion are quite big and usually include a lot of different files themselves, removing unnecessary includes could help reducing the time spent there. Nonetheless, this cost could also be reduced drastically by using an efficient caching system.
Given you are on PHP5 and your libraries are nicely split up into classes, you could leverage PHP's [auto loading functionality](http://php.net/autoload "PHP: Autoloading - Manual") which includes required classes as the PHP script needs them. That would pretty effectively avoid a lot of non used code to be included.
Finally, if you make any of those changes which could affect your website's performance, run some benchmarks and profile the gain or loss in performance. That way, you do not run into the risk of doing some possibly cool optimization which just costs too much time to fully implement or even degrades performance. | Bear in mind that each script that is loaded gets parsed as PHP is compiled at run-time, so there is a penalty for loading unneeded scripts. This might be minor depending on your application structure and requirements, but there are cases which this is not the case.
There are two things you can do to negate such concerns:
1. Use [\_\_autoload](http://www.php.net/autoload) to load your scripts as they are needed. This removes the need to maintain a long 'require' list of scripts and only loads what's needed for the current run.
2. Use [APC](http://www.php.net/apc) as a byte-code cache to lower the cost of loading scripts. APC caches scripts in their compiled state and will do wonders for your application performance. | How important is to not load unused scripts in PHP? | [
"",
"php",
"optimization",
""
] |
I just ran into an issue with Python's imaplib and Gmail's authentication mechanism:
```
>>> import imaplib
>>> imap = imaplib.IMAP4_SSL('imap.gmail.com', 993)
>>> imap.authenticate('bobdole@gmail.com', 'Bob Dole likes your style!')
Traceback (most recent call last):
...
imaplib.error: AUTHENTICATE command error: BAD ['TODO (not supported yet) 31if3458825wff.5']
```
If authentication is unsupported, how does one log in? | Instead of
```
>>> imap.authenticate('bobdole@gmail.com', 'Bob Dole likes your style!')
```
use
```
>>> imap.login('bobdole@gmail.com', 'Bob Dole likes your style!')
``` | The following works for me:
```
srv = imaplib.IMAP4_SSL("imap.gmail.com")
srv.login(account, password)
```
I think using `login()` is required. | Python imaplib Gmail authenticate failure | [
"",
"python",
"gmail",
"imap",
""
] |
I am trying to find a way to get the source code for (user defined) PHP functions in a string.
For normal code this is easy, using reflection I can find the file and line numbers where the function is defined; then I can open the file and read the function source code.
This will not work if a function is defined in eval'd code. I do not want to keep record of all eval'd code.
Is this possible? If yes, then how?
**Example code:**
```
function myfunction() {
echo "Test";
}
eval('
function myevalfunction() {
echo "Test";
}
');
$a = new ReflectionFunction('myfunction');
echo $a;
$b = new ReflectionFunction('myevalfunction');
echo $b;
```
**Output:**
```
Function [ <user> <visibility error> function myfunction ] {
@@ test.php 3 - 5
}
Function [ <user> <visibility error> function myevalfunction ] {
@@ test.php(11) : eval()'d code 2 - 4
}
``` | How about you define your own eval-function, and do the tracking there?
```
function myeval($code) {
my_eval_tracking($code, ...); # use traceback to get more info if necessary
# (...)
return eval($code);
}
```
That said, I do share a lot of Kent Fredric's feelings on eval in this case. | My initial response is to say there's virtually 0 good reason to create a function in eval.
You can create functions conditionally, ie:
```
if ( $cond ){
function foo(){
}
}
```
If you want **closure** like behaviour I guess eval is the only way to do it until PHP5.3, but its *EPIC* bad stuff and you should avoid it all cost.
Here is why:
```
01 <?php
02
03 function foo ()
04 {
05 eval( '
06 function baz()
07 {
08 eval("throw new Exception();");
09 }
10 ');
11 baz();
12 }
13
14
15
16 try{
17 foo();
18 }catch( Exception $e ){
19 var_dump($e);
20 }
21 try{
22 foo();
23 }
24 catch( Exception $e ){
25 var_dump($e);
26 }
```
Which Emits this:
```
object(Exception)#1 (6) {
["message:protected"]=>
string(0) ""
["string:private"]=>
string(0) ""
["code:protected"]=>
int(0)
["file:protected"]=>
string(50) "/tmp/xx.php(10) : eval()'d code(4) : eval()'d code"
["line:protected"]=>
int(1)
["trace:private"]=>
array(3) {
[0]=>
array(3) {
["file"]=>
string(31) "/tmp/xx.php(10) : eval()'d code"
["line"]=>
int(4)
["function"]=>
string(4) "eval"
}
[1]=>
array(4) {
["file"]=>
string(11) "/tmp/xx.php"
["line"]=>
int(11)
["function"]=>
string(3) "baz"
["args"]=>
array(0) {
}
}
[2]=>
array(4) {
["file"]=>
string(11) "/tmp/xx.php"
["line"]=>
int(17)
["function"]=>
string(3) "foo"
["args"]=>
array(0) {
}
}
}
}
Fatal error: Cannot redeclare baz() (previously declared in /tmp/xx.php(10) : eval()'d code:2) in /tmp/xx.php(10) : eval()'d code on line 5
Call Stack:
0.0002 115672 1. {main}() /tmp/xx.php:0
0.0006 122304 2. foo() /tmp/xx.php:22
```
So much badness, so little effort. | How find the source code for an eval'd function in PHP? | [
"",
"php",
"function",
"reflection",
""
] |
My main experience is with C && C++, so I'd prefer to remain with them. I don't want to use anything like QT, GTK, or wxWidgets or any tool kits. I'd like to learn native programming and this sort of defeats the purpose. With that in mind I'd also like to avoid Java.
I understand gnome and xfce and KDE and such are all Desktop Environments for Linux, and the base installed typically is X (Xorg). When coding for Linux, do you code for X, or for the desktop environment? Is there a standard Linux header for this (like win32 has windows.h) for Linux? or is it different coding methods for every desktop environment?
any help is greatly appreciated. | X is a hideous layer to program for and, despite your intent to avoid Java, QT or any of the excellent UI abstraction layers, you'll be doing yourself a disservice by coding to that level. I've done it (a long time ago when Motif was in its infancy on the platform we were using) and I would *not* do it again if there was an easier way.
Your use of the phrase "native programming" confuses me a little. If you want to learn native programming, it's to the APIs that you choose to call. Using similar reasoning, you shouldn't be coding in C either, instead opting for assembler (or direct machine code) since C provides an abstraction to the hardware.
If you want to learn X programming, that's fine. You'll end up with a lot more control over your interface but almost everyone else will be out-performing you in terms of delivery of software. Myself, I'd prefer to code to a higher-level API that I can use on many platforms - it gives me both faster delivery times and more market potential.
You don't build a house out of atoms, you build it out of bricks. My suggestion is to use the tools, that's what they're there for. | *I don't want to use anything like QT, GTK, or wxWidgets or any tool kits. I'd like to learn native programming and this sort of defeats the purpose.*
No you don't. Back in an early version of X11, like R1 or R2, I coded a complete "Hello, world" program in Xlib alone.
Roughly 700 lines of C.
You don't want to go there. | How do you make linux GUI's? | [
"",
"c++",
"c",
"linux",
"native",
""
] |
I have this form:
```
<form name="customize">
Only show results within
<select name="distance" id="slct_distance">
<option>25</option>
<option>50</option>
<option>100</option>
<option value="10000" selected="selected">Any</option>
</select> miles of zip code
<input type="text" class="text" name="zip_code" id="txt_zip_code" />
<span id="customize_validation_msg"></span>
</form>
```
How can I select the `input` and `select` with one jQuery selector?
I tried this but it selected all of the selects and inputs on the page:
```
$("form[name='customize'] select,input")
``` | The comma in the selector string separates completely separate expressions, just like in CSS, so the selector you've given gets the select elements within the form named "customize" and all inputs on the form (as you've described). It sounds like you want something like this:
```
$("form[name='customize'] select, form[name='customize'] input")
```
or if you're not into repitition, this:
```
$("form[name='customize']").children("select, input")
``` | A shorter syntax $(selector,parentselector) is also possible.
Example on this page :
```
// all spans
$("span").css("background-color","#ff0");
// spans below a post-text class
$("span", ".post-text").css("background-color","#f00");
```
Edit -- I forgot the particular case of several kind of children !
```
// spans and p's below a post-text class
$("span,p", ".post-text").css("background-color","#f00");
``` | Select multiple descendants with jQuery? | [
"",
"javascript",
"jquery",
"forms",
"jquery-selectors",
""
] |
I try to write to a large file, but it seems like it does not work for files larger than 2GB.
I have tried with boost::iostreams::file\_sink. Is this just a limit with the boost stream? Is there some other way I can write a large file on Win64 and win32? | This depends on:
* The file system which you're using. Old file systems like FAT allow only files up to 2GB. Use NTFS.
* Your library must be compiled to allow large files (64bit seek offsets). If they use 32bit ints to seek in file (check the arguments and results of the calls "seek" and "tell"), you can only ever access 2GB (2^31bits, the 32th is the sign +/-)
This might also help: <http://www.boost.org/doc/libs/1_37_0/libs/iostreams/doc/faq.html#offsets> | In Win32/64 the ReadFile & WriteFile can write files larger than 4gb. The positioning is done via a 64bit \_LARGE\_INTEGER value in [SetFilePointerEx](http://msdn.microsoft.com/en-us/library/aa365542(VS.85).aspx). Likewise to get the file size you need [GetFileSizeEx](http://msdn.microsoft.com/en-us/library/aa364957(VS.85).aspx) and not the basic GetFileSize. | Write large file | [
"",
"c++",
"file-io",
"win64",
""
] |
I'm trying to inverse a matrix with version Boost boost\_1\_37\_0 and MTL mtl4-alpha-1-r6418. I can't seem to locate the matrix inversion code. I've googled for examples and they seem to reference lu.h that seems to be missing in the above release(s). Any hints?
[@Matt](https://stackoverflow.com/users/8643/matt-cruikshank) suggested copying lu.h, but that seems to be from MTL2 rather than MTL4. I'm having trouble compiling with MTL2 with VS05 or higher.
So, any idea how to do a matrix inversion in MTL4?
Update: I think I understand Matt better and I'm heading down [this ITL path](http://www.osl.iu.edu/research/itl/). | Looks like you use `lu_factor`, and then `lu_inverse`. I don't remember what you have to do with the pivots, though. From the [documentation](http://www.osl.iu.edu/research/mtl/reference/html/index.html).
And yeah, like you said, it looks like their documentations says you need lu.h, somehow:
> **How do I invert a matrix?**
>
> The first question you should ask
> yourself is whether you want to really
> compute the inverse of a matrix or if
> you really want to solve a linear
> system. For solving a linear system of
> equations, it is not necessary to
> explicitly compute the matrix inverse.
> Rather, it is more efficient to
> compute triangular factors of the
> matrix and then perform forward and
> backward triangular solves with the
> factors. More about solving linear
> systems is given below. If you really
> want to invert a matrix, there is a
> function `lu_inverse()` in mtl/lu.h.
If nothing else, you can look at [lu.h on their site](http://www.osl.iu.edu/research/mtl/mtl/lu.h). | I've never used boost or MTL for matrix math but I have used JAMA/[TNT](http://math.nist.gov/tnt/).
This page <http://wiki.cs.princeton.edu/index.php/TNT> shows how to take a matrix inverse. The basic method is library-independent:
1. factor matrix M into XY where X and Y are appropriate factorizations (LU would be OK but for numerical stability I would think you would want to use QR or maybe SVD).
2. solve I = MN = (XY)N for N with the prerequisite that M has been factored; the library should have a routine for this. | Matrix Template Library matrix inversion | [
"",
"c++",
"math",
"stl",
"boost",
"linear-algebra",
""
] |
I've got a node struct
```
struct Node{CString text, int id;};
```
in a sorted vector.
I'm wondering if there's a function in algorithm that will do a binary search of the vector and find an element. | `std::binary_search()` will tell you if a value exists in the container.
`std::lower_bound()/std::upper_bound()` will return an iterator to the first/last occurrence of a value.
Your objects need to implement `operator<` for these algorithms to work. | Yes, there's a function called "binary\_search" std::binary\_search
You give it first, last and a value or a predicate.
See [here](http://www.java2s.com/Tutorial/Cpp/0520__STL-Algorithms-Binary-search/Usebinarysearchtolocateavalueinavector.htm) for a sample
Combine that with [Martin York's](https://stackoverflow.com/questions/369211/is-there-a-search-in-algorithm-ive-got-a-sorted-vector-and-im-looking-for-speci#369237) operator== and you should be OK (alternatively you can write a predicate functor | What function in the std library is there to binary search a vector and find an element? | [
"",
"c++",
"vector",
"std",
"binary-search",
""
] |
I am writing a addressbook module for my software right now. I have the database set up so far that it supports a very flexible address-book configuration.
I can create n-entries for every type I want. Type means here data like 'email', 'address', 'telephone' etc.
I have a table named 'contact\_profiles'.
This only has two columns:
```
id Primary key
date_created DATETIME
```
And then there is a table called contact\_attributes. This one is a little more complex:
```
id PK
#profile (Foreign key to contact_profiles.id)
type VARCHAR describing the type of the entry (name, email, phone, fax, website, ...) I should probably change this to a SET later.
value Text (containing the value for the attribute).
```
I can now link to these profiles, for example from my user's table. But from here I run into problems.
At the moment I would have to create a JOIN for each value that I want to retrieve.
Is there a possibility to somehow create a View, that gives me a result with the type's as columns?
So right now I would get something like
```
#profile type value
1 email name@domain.tld
1 name Sebastian Hoitz
1 website domain.tld
```
But it would be nice to get a result like this:
```
#profile email name website
1 name@domain.tld Sebastian Hoitz domain.tld
```
The reason I do not want to create the table layout like this initially is, that there might always be things to add and I want to be able to have multiple attributes of the same type.
So do you know if there is any possibility to convert this dynamically?
If you need a better description please let me know. | You have reinvented a database design called [Entity-Attribute-Value](http://en.wikipedia.org/wiki/Entity-attribute-value_model). This design has a lot of weaknesses, including the weakness you've discovered: it's very hard to reproduce a query result in a conventional format, with one column per attribute.
Here's an example of what you must do:
```
SELECT c.id, c.date_created,
c1.value AS name,
c2.value AS email,
c3.value AS phone,
c4.value AS fax,
c5.value AS website
FROM contact_profiles c
LEFT OUTER JOIN contact_attributes c1
ON (c.id = c1.profile AND c1.type = 'name')
LEFT OUTER JOIN contact_attributes c1
ON (c.id = c1.profile AND c1.type = 'email')
LEFT OUTER JOIN contact_attributes c1
ON (c.id = c1.profile AND c1.type = 'phone')
LEFT OUTER JOIN contact_attributes c1
ON (c.id = c1.profile AND c1.type = 'fax')
LEFT OUTER JOIN contact_attributes c1
ON (c.id = c1.profile AND c1.type = 'website');
```
You must add another `LEFT OUTER JOIN` for every attribute. You must know the attributes at the time you write the query. You must use `LEFT OUTER JOIN` and not `INNER JOIN` because there's no way to make an attribute mandatory (the equivalent of simply declaring a column `NOT NULL`).
It's far more efficient to retrieve the attributes as they are stored, and then write application code to loop through the result set, building an object or associative array with an entry for each attribute. You don't need to know all the attributes this way, and you don't have to execute an `n`-way join.
```
SELECT * FROM contact_profiles c
LEFT OUTER JOIN contact_attributes ca ON (c.id = ca.profile);
```
You asked in a comment what to do if you need this level of flexibility, if not use the EAV design? SQL is not the correct solution if you truly need unlimited metadata flexibility. Here are some alternatives:
* Store a `TEXT` BLOB, containing all the attributes structured in XML or YAML format.
* Use a semantic data modeling solution like [Sesame](http://openrdf.org/), in which any entity can have dynamic attributes.
* Abandon databases and use flat files.
EAV and any of these alternative solutions is a lot of work. You should consider very carefully if you truly need this degree of flexibility in your data model, because it's hugely more simple if you can treat the metadata structure as relatively unchanging. | If you are limiting yourself to displaying a single email, name, website, etc. for each person in this query, I'd use subqueries:
```
SELECT cp.ID profile
,cp.Name
,(SELECT value FROM contact_attributes WHERE type = 'email' and profile = cp.id) email
,(SELECT value FROM contact_attributes WHERE type = 'website' and profile = cp.id) website
,(SELECT value FROM contact_attributes WHERE type = 'phone' and profile = cp.id) phone
FROM contact_profiles cp
```
If you're using SQL Server, you could also look at [PIVOT](http://msdn.microsoft.com/en-us/library/ms177410.aspx).
If you want to show multiple emails, phones, etc., then consider that each profile must have the same number of them or you'll have blanks.
I'd also factor out the type column. Create a table called `contact_attribute_types` which would hold "email", "website", etc. Then you'd store the `contact_attribute_types.id` integer value in the `contact_attributes` table. | SQL database problems with addressbook table design | [
"",
"sql",
"data-structures",
"entity-attribute-value",
"database-relations",
""
] |
C#: How do you pass an object in a function parameter?
```
public void MyFunction(TextBox txtField)
{
txtField.Text = "Hi.";
}
```
Would the above be valid? Or? | So long as you're not in a different thread, yes the code sample is valid. A textbox (or other windows forms items) are still objects that can be passed to and manipulated by methods. | Yup, that will work. You're not actually passing an object - you're passing in a *reference* to the object.
See ["Parameter passing in C#"](http://pobox.com/~skeet/csharp/parameters.html) for details when it comes to pass-by-ref vs pass-by-value. | C#: How do you pass an object in a function parameter? | [
"",
"c#",
""
] |
I have a window (derived from JFrame) and I want to disable the close button during certain operations which are not interruptible. I know I can make the button not do anything (or call a handler in a WindowListener) by calling
```
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
```
but I would like to make it clear visually that it is pointless to click it. | If I understand it correctly, [this bug report](https://bugs.java.com/bugdatabase/view_bug?bug_id=6199687) indicates that this is currently not possible. | This is probably the best you are going to get:
```
setUndecorated(true);
getRootPane().setWindowDecorationStyle(JRootPane.NONE);
```
This will remove the entire titlebar, java doesn't really specify a way to remove individual components of the titlebar
edit:
There may be a way, check out these threads:
* [link 1](http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=2&t=015407)
* [link 2](http://forums.sun.com/thread.jspa?messageID=10255068) | How to disable (or hide) the close (x) button on a JFrame? | [
"",
"java",
"windows",
"swing",
""
] |
I really love the way Ajax makes a web app perform more like a desktop app, but I'm worried about the hits on a high volume site. I'm developing a database app right now that's intranet based, that no more then 2-4 people are going to be accessing at one time. I'm Ajaxing the hell out of it, but it got me to wondering, how much Ajax is too much?
At what point does the volume of hits, outweigh the benefits seen by using Ajax? It doesn't really seem like it would, versus a whole page refresh, since you are, in theory, only updating the parts that need updating.
I'm curious if any of you have used Ajax on high volume sites and in what capacity did you use it? Does it create scaling issues? | On my current project, we do use Ajax and we have had scaling problems. Since my current project is a J2EE site that does timekeeping for the employees of a large urban city, we've found that it's best if the browser side can cache data that won't change for the duration of a user session. Fortunately we're moving to a model where we have a single admin process the timekeeping for as many employees as possible. This would be akin to how an ERP application might work (or an email application). Consequently our business need is that the browser-side can hold a lot of data, but we don't expect the volume of hits to be a serious problem. So we've kept an XML data island on the browser-side. In addition, we load data only on an as-needed basis.
I highly recommend the book *Ajax Design Patterns* or their [site](http://ajaxpatterns.org/). | Ajax should help your bandwidth on a high volume site if that is your concern as you are, like you said, only updating the parts that need updating. My problem with Ajax is that your site can be rendered useless if the visitors do not have javascript enabled, and most of the time I do not feel like coding the site again for non-javascript users. | To Ajaxify Or Not? | [
"",
"javascript",
"ajax",
"asynchronous",
"scaling",
""
] |
I'm wondering if this is possible in SQL. Say you have two tables A and B, and you do a select on table A and join on table B:
```
SELECT a.*, b.* FROM TABLE_A a JOIN TABLE_B b USING (some_id);
```
If table A has columns 'a\_id', 'name', and 'some\_id', and table B has 'b\_id', 'name', and 'some\_id', the query will return columns 'a\_id', 'name', 'some\_id', 'b\_id', 'name', 'some\_id'. Is there any way to prefix the column names of table B without listing every column individually? The equivalent of this:
```
SELECT a.*, b.b_id as 'b.b_id', b.name as 'b.name', b.some_id as 'b.some_id'
FROM TABLE_A a JOIN TABLE_B b USING (some_id);
```
But, as mentioned, without listing every column, so something like:
```
SELECT a.*, b.* as 'b.*'
FROM TABLE_A a JOIN TABLE_B b USING (some_id);
```
Basically something to say, "prefix every column returned by b.\* with 'something'". Is this possible or am I out of luck?
### EDITS
Advice on not using `SELECT *` and so on is valid advice but not relevant in my context, so please stick to the problem at hand -- is it possible to add a prefix (a constant specified in the SQL query) to all the column names of a table in a join?
My ultimate goal is to be able to do a `SELECT *` on two tables with a join, and be able to tell, from the names of the columns I get in my result set, which columns came from table A and which columns came from table B. Again, I don't want to have to list columns individually, I need to be able to do a `SELECT *`. | I see two possible situations here. First, you want to know if there is a SQL standard for this, that you can use in general regardless of the database. No, there is not. Second, you want to know with regard to a specific dbms product. Then you need to identify it. But I imagine the most likely answer is that you'll get back something like "a.id, b.id" since that's how you'd need to identify the columns in your SQL expression. And the easiest way to find out what the default is, is just to submit such a query and see what you get back. If you want to specify what prefix comes before the dot, you can use "SELECT \* FROM a AS my\_alias", for instance. | It seems the answer to your question is no, however one hack you can use is to assign a dummy column to separate each new table. This works especially well if you're looping through a result set for a list of columns in a scripting language such as Python or PHP.
```
SELECT '' as table1_dummy, table1.*, '' as table2_dummy, table2.*, '' as table3_dummy, table3.* FROM table1
JOIN table2 ON table2.table1id = table1.id
JOIN table3 ON table3.table1id = table1.id
```
I realize this doesn't answer your question exactly, but if you're a coder this is a great way to separate tables with duplicate column names. | SQL select join: is it possible to prefix all columns as 'prefix.*'? | [
"",
"sql",
"join",
""
] |
I have a database table (named Topics) which includes these fields :
1. topicId
2. name
3. parentId
and by using them I wanna populate a TreeView in c#. How can I do that ?
Thanks in advance... | It will probably be something like this. Give some more detail as to what exactly you want to do if you need more.
```
//In Page load
foreach (DataRow row in topics.Rows)
{
TreeNode node = new TreeNode(dr["name"], dr["topicId"])
node.PopulateOnDemand = true;
TreeView1.Nodes.Add(node);
}
///
protected void PopulateNode(Object sender, TreeNodeEventArgs e)
{
string topicId = e.Node.Value;
//select from topic where parentId = topicId.
foreach (DataRow row in topics.Rows)
{
TreeNode node = new TreeNode(dr["name"], dr["topicId"])
node.PopulateOnDemand = true;
e.Node.ChildNodes.Add(node);
}
}
``` | Not quite.
Trees are usually handled best by not loading everything you can at once. So you need to get the root node (or topic) which has no parentIDs. Then add them to the trees root node and then for each node you add you need to get its children.
```
foreach (DataRow row in topicsWithOutParents.Rows)
{
TreeNode node = New TreeNode(... whatever);
DataSet childNodes = GetRowsWhereParentIDEquals(row["topicId"]);
foreach (DataRow child in childNodes.Rows)
{
Treenode childNode = new TreeNode(..Whatever);
node.Nodes.add(childNode);
}
Tree.Nodes.Add(node);
}
``` | Populate TreeView from DataBase | [
"",
"c#",
"asp.net",
"database",
"webforms",
"treeview",
""
] |
Let's say I have some code like this:
```
<html>
<head><title>Title</title></head>
<body>
<?php
if (!$someCondition){
die();
}
else{
#Do something
}
?>
</body>
<html>
```
I hope the purpose of this code is straightforward. If a certain condition is met (ie can't connect to database), then the program should die, but otherwise it should execute. My problem arises when the die() function is executed. It stops **right** there, and sends only the first three lines to the browser, but not the last two lines.
Is there a funciton that I can use instead of die() so that the php chunks will stop executing, but the static HTML text is still sent through? | You should be separating out your header and footer into an separate files and functions. This makes the UI much easier to maintain and keeps things consistent for rendering the view. Couple that with using [Exception handling](http://us.php.net/Exceptions) and you're golden.
```
<?php
printHeader(); // outputs the html header
try
{
if (some condition)
{
throw new Exception("It Died...");
}
// More processing here that should not execute if the above condition is true
// ...
}
catch (Exception e)
{
echo $e->getMessage();
}
printFooter(); // outputs the html footer
?>
``` | Decouple your program logic from presentation. Read about MVC, templates.
In simplest form it goes like that:
```
<?php
function logic() {
if (!$someCondition) {
return 'display_empty_page';
} else {
return 'display_other_stuff';
}
}
presentation(logic());
```
---
For other cases, where `die()` or such is unavoidable (e.g. fatal error or 3rd party code dying), there's hack involving output handler:
```
ob_start('myhandler');
function myhandler($page) {return $page.' extra markup';}
die();
```
Although I recommend using that only for diagnostic/debugging purposes. | How Can I Display Static HTML After I've Used die() in a PHP Block? | [
"",
"php",
"die",
""
] |
I have from the backend a time on the format 00:12:54 and I display it to the screen. But, I would like to have this time to continue to go down. I have though to create a variable in javascript that will old the time and with `setTimeout` to loop to display with document.getElementById the new value. I think it can be problematic if I have many time to go down in same time. I might require an array?
How would you do that? If I have no other suggestion, I will try my way, but I am curious to know if it does have a more secure way to do it. | General algorithm:
1. Read time from server.
2. Read the current time.
3. Call a function.
4. In your function, read the current time, get the delta from the initial time you read in step 2.
5. Subtract the delta from the initial time you read from the server in step 1 and display the remainder.
6. The function should call `window.setTimeout` to call itself in 1000ms (or adjust according to time elapsed within the function), if you want to continue counting down.
Here's a rough cut:
```
window.onload = function () {
var countdown_start_in_ms = 6000; // from server
function tick() {
var now = new Date().getTime();
var disp = start - now;
if (disp < 0) {
disp = 0;
}
var el = document.getElementById("countdown");
el.innerHTML =
// quick hack to format time
/(\d\d:\d\d:\d\d) ...$/.exec(new Date(disp).toUTCString())[1];
if (disp > 1000) {
var elapsed = new Date().getTime() - now;
window.setTimeout(tick, 1000 - elapsed);
} else {
// stop countdown and set color to light grey
el.style.color = "#ccc";
}
}
var start = new Date().getTime() + countdown_start_in_ms;
tick();
}
``` | Do you know jQuery Framework? It's a Javascript framework that have a lot of utilities methods and functions that let you do Javascript stuff more easily.
Here is a [count down plugin](http://keith-wood.name/countdown.html) (haven't tested it).
I suggest you to [download JQuery](http://docs.jquery.com/Downloading_jQuery) than [download the plugin](http://keith-wood.name/countdown.html) . Check the sample of code from the "relative" tab on the website. You can have something like :
```
$('#until2d4h').countdown({until: '+12M +54S'});
```
\*The only drawback with what I suggest you is that you will require 2 .js to be added. Try to add them only when needed and you will be find. | Counting down for x to 0 in Javascript? | [
"",
"javascript",
""
] |
Range intersection is a simple, but non-trivial problem.
Its has been answered twice already:
* [Find number range intersection](https://stackoverflow.com/questions/224878/find-number-range-intersection)
* [Comparing date ranges](https://stackoverflow.com/questions/143552/comparing-date-ranges)
The first solutions is O(n) and the second solution is for a database (which is less than O(n) of course).
I have the same problem, but for a large n and I am not within a database.
This problem seems to be very similar to [Store 2D points for quick retrieval of those inside a rectangle](https://stackoverflow.com/questions/303243/store-2d-points-for-quick-retrieval-of-those-inside-a-rectangle) but I don't see how it maps.
So what data structure would you store the set of ranges in, such that a search on a range costs less than O(n)? (Extra credit for using libraries available for Java)
**EDIT:**
I want to get a subset of all intersecting ranges, meaning the search range could intersect multiple ranges.
The method that needs to be less than O(n) in Java is:
```
public class RangeSet {
....
public Set<Range> intersects(Range range);
....
}
```
Where Range is just a class containing a pair of int start and end.
This is not an impossible question, I already have the solution, I just wanted to see if there was a more standard/simpler way of doing it | The standard approach is to use an [interval tree](http://en.wikipedia.org/wiki/Interval_tree#With_an_Interval).
> In computer science, an interval tree is a tree data structure to hold intervals. Specifically, it allows one to efficiently find all intervals that overlap with any given interval or point. It is often used for windowing queries, for instance, to find all roads on a computerized map inside a rectangular viewport, or to find all visible elements inside a three-dimensional scene. A similar data structure is the segment tree.
>
> The trivial solution is to visit each interval and test whether it intersects the given point or interval, which requires O(n) time, where n is the number of intervals in the collection. Since a query may return all intervals, for example if the query is a large interval intersecting all intervals in the collection, this is asymptotically optimal; however, we can do better by considering output-sensitive algorithms, where the runtime is expressed in terms of m, the number of intervals produced by the query. Interval trees have a query time of O(log n + m) and an initial creation time of O(n log n), while limiting memory consumption to O(n). After creation, interval trees may be dynamic, allowing efficient insertion and deletion of an interval in O(log n). If the endpoints of intervals are within a small integer range (e.g., in the range [1,...,O(n)]), faster data structures exist[1] with preprocessing time O(n) and query time O(1+m) for reporting m intervals containing a given query point. | **Edit:**
It sounds like this solution is more or less [an Interval Tree](http://en.wikipedia.org/wiki/Interval_tree#With_an_Interval). A more complete implementation of an Interval Tree can be found [here](http://www.mit.edu/~emin/source_code/cpp_trees/index.html).
```
class TreeNode
{
public:
long pivot;
List<Range> leaves; //Any ranges that intersect the pivot
TreeNode left; //Tree nodes that fall to the left of the pivot
TreeNode right; //Tree nodes that fall to the right of the pivot
};
```
Prep O(n log n):
1. Create the list of ranges
2. Pick the pivot points (possibly by using a sorted list of the end dates.) ??
3. Build your tree.
Search:
1. Use binary search to find the first pivot that is >= TestRange.End
2. Traverse the tree until the pivot > TestRange.Start
2a. Add the leaves to your result.
---
Example:
Ranges:
* 0 - 2
* 1 - 2
* 2 - 3
* 1 - 4
* 2 - 4
* 0 - 5
* 4 - 5
* 2 - 6
* 3 - 7
Tree:
```
4
--------------+------------------
3 | 7
| 1-4 |
| 2-4 |
| 0-5 |
| 4-5 |
---------+------ --------+--------
2 | null 6 | null
-----+---- 2-3 ----+---- 3-7
null | null null | null
0-2 2-6
1-2
``` | A range intersection algorithm better than O(n)? | [
"",
"java",
"algorithm",
"search",
"big-o",
"interval-intersection",
""
] |
I am trying to create a simple dialog in MFC using Visual C++. My problem is that when I get the dialog on the screen and try to type in an Edit Box field, if I type the letter 'a' once, it appears in the edit box as 'aaaaaaaaaaa' (that's 12 a's). Furthermore, if I try to navigate around in the box using the arrow keys, the carat moves 12 characters at a time.
It's not just a display error, as the output from the editbox is still "aaaaaaaaaaaa".
I'd post code, but there's really none to post. I added the edit box using the Toolbox in Visual Studio and assigned a variable to it in my class so this isn't any sort of special edit box.
If anyone has any thoughts as to what might be happening it would be greatly appreciated. Unfortunately, I don't know where to begin.
Thank as always. | Are you capturing any events such as WM\_KEYUP in your PreTranslateMessage() function or anywhere else in your app ?
If you have overridden the default handling for keyboard events, it might cause the symptoms you are seeing. | To debug this, add PreTranslateMessage function to your dialog, and see exactly how many times the keydown is being processed.
```
BOOL DialogName::PreTranslateMessage(MSG* pMsg)
{
if(pMsg->message==WM_KEYDOWN)
{
// TODO: see what is going on here
return TRUE; //do not dispatch this message, so keydown will have no effect
}
return CDialog::PreTranslateMessage(pMsg);
}
``` | MFC Edit Box - Multiple Characters per Keystroke? | [
"",
"c++",
"mfc",
"editcontrol",
""
] |
Is there a way to find the application name of the current active window at a given time on Mac OS X using Python? | This should work:
```
#!/usr/bin/python
from AppKit import NSWorkspace
activeAppName = NSWorkspace.sharedWorkspace().activeApplication()['NSApplicationName']
print activeAppName
```
Only works on Leopard, or on Tiger if you have PyObjC installed and happen to point at the right python binary in line one (not the case if you've installed universal MacPython, which you'd probably want to do on Tiger). But Peter's answer with the Carbon way of doing this will probably be quite a bit faster, since importing anything from AppKit in Python takes a while, or more accurately, importing something from AppKit for the first time in a Python process takes a while.
If you need this inside a PyObjC app, what I describe will work great and fast, since you only experience the lag of importing AppKit once. If you need this to work as a command-line tool, you'll notice the performance hit. If that's relevant to you, you're probably better off building a 10 line Foundation command line tool in Xcode using Peter's code as a starting point. | The method in the accepted answer was deprecated in OS X 10.7+. The current recommended version would be the following:
```
from AppKit import NSWorkspace
active_app_name = NSWorkspace.sharedWorkspace().frontmostApplication().localizedName()
print(active_app_name)
``` | Finding the Current Active Window in Mac OS X using Python | [
"",
"python",
"objective-c",
"cocoa",
"macos",
""
] |
I am migrating a 1.1 winforms app to 2.0. what are the main things i should immediately change because of generics. Here what i have so far:
1. Replace all hashtables with generic dictionaries
2. Replace all arraylists with List<>
3. Replace all CollectionBase derive classes with : List<>
Any others that should be done immediately?
thks,
ak | > Any others that should be done immediately?
Generally, change any mention of `IEnumerable` to `IEnumerable<T>`, where possible. Migration can be greatly helped by switching the whole namespace, i.e. un-`import`ing `System.Collections` in every file and instead importing `System.Collections.Generic`.
Also, search for mentions of `object` and/or usage of boxing in your code and consider whether this is still appropriate or should be replaced by generics.
As **jalf** reminded me in the comments, another important change is the switch to the generic version of `IComparable` where applicable. | I don't think anything should be done immediately! The 1.1 code works, right? What's the business case for the wholesale swap to generics? Compile the app under 2.0, get it running and tested. And then, as new features are needed that would let you exploit generics well, implement those features as generics. | Moving to generics . | [
"",
"c#",
"winforms",
"generics",
""
] |
I want to send some strings in a list in a POST call. eg:
```
www.example.com/?post_data = A list of strings
```
The python code receives the data as a single string (Instead of a list of strings). How do I post it as a list of strings? | There's no such thing as a "list of strings" in a URL (or in practically anything in HTTP - if you specify multiple values for the same header, they come out as a single delimited value in most web app frameworks IME). It's just a single string. I suggest you delimit the strings in some way (e.g. comma-separated) and then parse them out again at the other end. | TRY JSON(JavaScript Object Notation) it's available in the python package.
Find out here: <http://docs.python.org/library/json.html>
You can Encode your list to an array represented in JSON and append to the post argument. Later decode it back to list... | How do I pass a python list in the post query? | [
"",
"python",
"web-services",
""
] |
I have two tables with the following columns:
table1:
```
id, agent_name, ticket_id, category, date_logged
```
table2:
```
id, agent_name, department, admin_status
```
What I'm trying to achieve is to Select all rows from table1 where an agents department is equal to that of table2.
I've tried a few different join statements but I'm either getting the syntax wrong or it just won't work with this table setup. I'm a beginner when it comes to MySQL and from what I've read JOIN's are at the complex end of the spectrum!
One other option I've considered is duplicating the column "department" into table1 but that will require a little bit more coding on the frontend and I'm trying to see if I can achieve the desired result without doing that.
Any assistance greatly appreciated. | I don't quite understand your question...
Only table2 have a department, the only thing they have in common is agent\_name.
I do suspect what you really mean is: that you want all rows from Table1 where the agent is from a certain department, is that what you want? In that case, something like this should do it (haven't tested it though):
```
SELECT * FROM Table1
INNER JOIN Table2
ON Table1.agent_name = Table2.agent_name
WHERE Table2.department = 'somespecific value';
```
BTW: (Inspired by what someone else said) `agent_name` sounds like it's a string value, you really should consider using the id from table2 as a key in table1 (let's call it `agent_id` perhaps) to link them together. The foreign keys (the link between tables) should be a real unique id. The department should pobably allso be a id key. Then it would be:
```
SELECT * FROM Table1
INNER JOIN Table2
ON Table1.agent_id = Table2.id
WHERE Table2.department = 'somespecific value';
``` | Although I cannot exactly understand, what you need and how are tables related, I'd try someting similar:
```
select
a.id, a.agent_name, a.ticket_id,
a.category, a.date_logged, b.department
from
table1 a inner join table2 b on b.agent_name=a.agent_name
```
Currently I'm assuming that you need to link tables on agent\_name.
BTW, joins are the simplest end of the SQL spectrum :) | mysql join question | [
"",
"php",
"mysql",
"join",
""
] |
I'm creating a simple API that creates typed classes based on JSON data that has a mandatory 'type' field defined in it. It uses this string to define a new type, add the fields in the JSON object, instantiate it, and then populate the fields on the instance.
What I want to be able to do is allow for these types to be optionally pre-defined in whatever application is using my module. This is so methods and other application-specific attributes not found in the JSON object can be added. I'd like to have my module check if a type already exists, and if it does, use that instead of dynamically creating the type. It would still add attributes from the JSON object, but it would be recycling the existing type.
My JSON data is:
```
{
"type": "Person",
"firstName": "John",
"lastName": "Smith",
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
},
"phoneNumbers": [
"212 555-1234",
"646 555-4567"
]
}
```
My code so far (assume json\_object is a dict at this point):
```
if not json_object.has_key('type'):
raise TypeError('JSON stream is missing a "type" attribute.')
##### THIS IS WHERE I WANT TO CHECK IF THE TYPE BY THAT NAME EXISTS ALREADY ####
# create a type definition and add attributes to it
definition = type(json_object['type'], (object,), {})
for key in json_object.keys():
setattr(definition, key, None)
# instantiate and populate a test object
tester = definition()
for key, value in json_object.iteritems():
setattr(tester, key, value)
``` | You can use `dir()` to get a list of all the names of all objects in the current environment, and you can use `globals()` to a get a dictionary mapping those names to their values. Thus, to get just the list of objects which are classes, you can do:
```
import types
listOfClasses = [cls for cls in globals().values() if type(cls) == types.ClassType]
``` | If you want to reuse types that you created earlier, it's best to cache them yourself:
```
json_types = {}
def get_json_type(name):
try:
return json_types[name]
except KeyError:
json_types[name] = t = type(json_object['type'], (object,), {})
# any further initialization of t here
return t
definition = get_json_type(json_object['type'])
tester = definition()
# or: tester = get_json_type(json_object['type'])()
```
If you want to have them added to the module namespace, do
```
json_types = globals()
```
instead. | List all the classes that currently exist | [
"",
"python",
""
] |
So I have an object graph, let's just say it's an order. You have the order class, line item class, tracking number class, payment class. You get the idea.
Now the business requirement is any user can change the order, but order changes must be approved by the manager. Until the manger approves nothing changes. Managers can change anything, at any time, without approval.
What are the best practices for dealing with situations like this? Saving the many (possible) different states of the order object and eventually approving or rejecting the changes.
i'm using C# and Nhibernate.
Thanks, Kyle. | I would create a transaction table. It would have a record for each pending change. It would reference the order table.
So an order would get created but have a pending change; a record would be inserted into the orders table, with a status column of pending, and a record would be insterted into the OrderTransaction table.
For every change another record would get inserted into the OrderTransaction table.
I would also set up a RequestedChanges table with all the possible requested changes. | Similar to Sam WIlliamson's idea about a transaction table, I would use a temporary table.
Changes made by someone who is not a manager, go to new Order objects in the temp table. The manager will have an interface to review these orders pending approval, and the system will have all the changes saved already, but outside of the standard position.
This might be an issue for the user's interface as well, they will have to see both the official version of an order and the pending-revision version side by side to make sense of the state of the object.
Anyway I think your best bet is to store the objects as normal, but in a separate table from the official records, pending review by the manager. This temp table should never grow very large, as it represents the backlog of approvals the manager has to get to. | How to save objects when approval is needed to actually make changes? | [
"",
"c#",
"nhibernate",
""
] |
I use jQuery to make an AJAX POST request to my server, which can return HTTP response with status 302. Then JavaScript just sends GET request to this URL, while I'd like to redirect user to URL in this response. Is this possible? | The accepted answer does not work for the reasons given. I posted a comment with a link to a question that described a hack to get round the problem of the 302 being transparently handled by the browser:
[How to manage a redirect request after a jQuery Ajax call](https://stackoverflow.com/questions/199099/how-to-manage-a-redirect-request-after-a-jquery-ajax-call)
However, it is a bit of a dirty hack and after much digging around I found what I think is a better solution - use [JSON](http://en.wikipedia.org/wiki/JSON). In this case, you can make all responses to ajax requests have the code 200 and, in the body of the response, you add some sort of JSON object which your ajax response handler can then use in the appropriate manner. | I don't think so. The [W3C](http://www.w3.org/TR/2006/WD-XMLHttpRequest-20060405/#xmlhttprequest) says that HTTP redirects with certain status codes, including 302, must be transparently followed. Quoted below:
> If the response is an HTTP redirect (status code 301, 302, 303 or
> 307), then it MUST be transparently followed (unless it violates
> security or infinite loop precautions). Any other error (including a
> 401) MUST cause the object to use that error page as the response.
As an experiment, I tried doing Ajax requests from various browsers (Firefox 3.5, Chrome, IE8, IE7, IE6) to a server giving a 302 status code, and showing the status in the browser's request object. In every case, it showed up as 200. | Catching 302 FOUND in JavaScript | [
"",
"javascript",
"jquery",
"ajax",
"http-status-code-302",
""
] |
Is it possible to forward declare an standard container in a header file? For example, take the following code:
```
#include <vector>
class Foo
{
private:
std::vector<int> container_;
...
};
```
I want to be able to do something like this:
```
namespace std
{
template <typename T> class vector;
}
class Foo
{
private:
std::vector<int> container_;
...
};
```
Can this be done? | Declaring `vector` in the `std` namespace is **undefined behavior**. So, your code might work, but it also might not, and the compiler is under no obligation to tell you when your attempt won't work. That's a gamble, and I don't know that avoiding the inclusion of a standard C++ header is worth that.
See the following comp.std.c++.moderated discussion:
[forward declaring std::vector. Works, but is it legal and standard compliant?](http://groups.google.com/group/comp.lang.c++.moderated/browse_thread/thread/5c12858c636ab833/6cd57590509ad6b4) | I don't think so because the compiler would have no way of knowing how much space to allocate for the `container_` object. At best you could do:
```
std::vector<int> *container_;
```
and new it in the constructor, since the compiler knows the size of a pointer. | Forward declare a standard container? | [
"",
"c++",
"header",
"std",
""
] |
PHP provides a mechanism to register a shutdown function:
```
register_shutdown_function('shutdown_func');
```
The problem is that in the recent versions of PHP, this function is still executed DURING the request.
I have a platform (in Zend Framework if that matters) where any piece of code throughout the request can register an entry to be logged into the database. Rather than have tons of individual insert statements throughout the request, slowing the page down, I queue them up to be insert at the end of the request. I would like to be able to do this after the HTTP request is complete with the user so the length of time to log or do any other cleanup tasks doesn't affect the user's perceived load time of the page.
Is there a built in method in PHP to do this? Or do I need to configure some kind of shared memory space scheme with an external process and signal that process to do the logging? | If you're really concerned about the insert times of MySQL, you're probably addressing the symptoms and not the cause.
For instance, if your PHP/Apache process is executing after the user gets their HTML, your PHP/Apache process is still locked into that request. Since it's busy, if another request comes along, Apache has to fork another thread, dedicate more memory to it, open additional database connections, etc.
If you're running into performance problems, you need to remove heavy lifting from your PHP/Apache execution. If you have a lot of cleanup tasks going on, you're burning precious Apache processes.
I would consider logging your entries to a file and have a crontab load these into your database out of band. If you have other heavy duty tasks, use a queuing/job processing system to do the work out of band. | Aside from register\_shutdown\_function() there aren't built in methods for determining when a script has exited. However, the Zend Framework has several hooks for running code at specific points in the dispatch process.
For your requirements the most relevant would be the action controller's [post-dispatch hook](http://framework.zend.com/manual/en/zend.controller.action.html#zend.controller.action.prepostdispatch) which takes place just after an action has been dispatched, and the [dispatchLoopShutdown event](http://framework.zend.com/manual/en/zend.controller.plugins.html#zend.controller.plugins.introduction) for the controller plugin broker.
You should read the manual to determine which will be a better fit for you.
EDIT: I guess I didn't understand completely. From those hooks you could fork the current process in some form or another.
PHP has several ways to fork processes as you can read in the manual under [program execution](http://www.php.net/manual/en/refs.fileprocess.process.php). I would suggest going over the pcntl extension - read [this blog post](http://www.welldonesoft.com/technology/articles/php/forking/) to see an example of forking child processes to run in the background. | Execute code after HTTP request is complete in PHP? | [
"",
"php",
"zend-framework",
""
] |
I have a string of test like this:
```
<customtag>hey</customtag>
```
I want to use a RegEx to modify the text between the "customtag" tags so that it might look like this:
```
<customtag>hey, this is changed!</customtag>
```
I know that I can use a MatchEvaluator to modify the text, but I'm unsure of the proper RegEx syntax to use. Any help would be much appreciated. | I wouldn't use regex either for this, but if you must this expression should work:
`<customtag>(.+?)</customtag>` | I'd chew my own leg off before using a regular expression to parse and alter HTML.
Use [XSL](http://www.w3schools.com/xsl/xsl_languages.asp) or [DOM](http://www.w3schools.com/dom/default.asp).
---
Two comments have asked me to clarify. The regular expression substitution works in the specific case in the OP's question, but in general regular expressions are not a good solution. Regular expressions can match [regular languages](http://en.wikipedia.org/wiki/Regular_language), i.e. a sequence of input which can be accepted by a finite state machine. HTML can contain nested tags to any arbitrary depth, so it's not a regular language.
What does this have to do with the question? Using a regular expression for the OP's question as it is written works, but what if the content between the `<customtag>` tags contains other tags? What if a literal `<` character occurs in the text? It has been 11 months since Jon Tackabury asked the question, and I'd guess that in that time, the complexity of his problem may have increased.
Regular expressions are great tools and I do use them all the time. But using them in lieu of a real parser for input that needs one is going to work in only very simple cases. It's practically inevitable that these cases grow beyond what regular expressions can handle. When that happens, you'll be tempted to write a more complex regular expression, but these quickly become very laborious to develop and debug. Be ready to scrap the regular expression solution when the parsing requirements expand.
XSL and DOM are two standard technologies designed to work with XML or XHTML markup. Both technologies know how to parse structured markup files, keep track of nested tags, and allow you to transform tags attributes or content.
Here are a couple of articles on how to use XSL with C#:
* <http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63>
* <http://www.csharphelp.com/archives/archive78.html>
Here are a couple of articles on how to use DOM with C#:
* <http://msdn.microsoft.com/en-us/library/aa290341%28VS.71%29.aspx>
* <http://blogs.msdn.com/tims/archive/2007/06/13/programming-html-with-c.aspx>
Here's a .NET library that assists DOM and XSL operations on HTML:
* <http://www.codeplex.com/Wiki/View.aspx?ProjectName=htmlagilitypack> | RegEx matching HTML tags and extracting text | [
"",
"c#",
"regex",
""
] |
The one that ships with IDEA is nothing more than a GWT project creation tool. Is there a better plugin? Is there a standalone GUI editor for GWT? | To answer your question directly, there is no such thing as a Intellij IDEA GUI WYSIWYG editor for GWT for the moment.
The most popular/feature complete WYSIWYG editor for GWT is [Instantiations GWT Designer](http://www.instantiations.com/windowbuilder/). It is available only for Eclipse though.
The GWT team also provide a [list of tools and libraries.](http://code.google.com/intl/nn/webtoolkit/tools.html). It seem rather incomplete though as it does not list Ext-GWT and GWT-Ext libraries (the most popular widget libraries).
Be warned however that most WYSIWYG editor only support the basic widgets of GWT. If you have custom widget, you may not be able to use them in the editor.
---
[Edit] As of August 2010, Instanciation has been acquired Google | I've never used these personally but a few things I've found include:
* <http://www.gdevelop.com/> (extension to JDeveloper so it might not be appropriate for you if you're using IDEA and not wanting to download and use JDeveloper for your GWT project)
* <http://code.google.com/p/gwt-html-editor/> | GWT - What's a good GUI editor for GWT in Intellij IDEA? | [
"",
"java",
"gwt",
"intellij-idea",
""
] |
(Note: I realize this is close to [How do you document your database structure?](https://stackoverflow.com/questions/186392/how-do-you-document-your-database-structure) , but I don't think it's identical.)
I've started work at a place with a database with literally hundreds of tables and views, all with cryptic names with very few vowels, and no documentation. They also don't allow gratuitous changes to the database schema, nor can I touch any database except the test one on my own machine (which gets blown away and recreated regularly), so I can't add comments that would help anybody.
I tried using "Toad" to create an ER diagram, but after leaving it running for 48 hours straight it still hadn't produced anything visible and I needed my computer back. I was talking to some other recent hires and we all suggested that whenever we've puzzled out what a particular table or what some of its columns means, we should update it in the developers wiki.
So what's a good way to do this? Just list tables/views and their columns and fill them in as we go? The basic tools I've got to hand are Toad, Oracle's "SQL Developer", MS Office, and Visio. | In my experience, ER (or UML) diagrams aren't the most useful artifact - with a large number of tables, diagrams (especially reverse engineered ones) are often a big convoluted mess that nobody learns anything from.
For my money, some good human-readable documentation (perhaps supplemented with diagrams of smaller portions of the system) will give you the most mileage. This will include, for each table:
* Descriptions of what the table means and how it's functionally used (in the UI, etc.)
* Descriptions of what each attribute means, if it isn't obvious
* Explanations of the relationships (foreign keys) from this table to others, and vice-versa
* Explanations of additional constraints and / or triggers
* Additional explanation of major views & procs that touch the table, if they're not well documented already
With all of the above, don't document for the sake of documenting - documentation that restates the obvious just gets in people's way. Instead, focus on the stuff that confused you at first, and spend a few minutes writing really clear, concise explanations. That'll help you think it through, and it'll *massively* help other developers who run into these tables for the first time.
As others have mentioned, there are a wide variety of tools to help you manage this, like [Enterprise Architect](http://www.sparxsystems.com.au/), [Red Gate SQL Doc](http://www.red-gate.com/products/SQL_Doc/index.htm), and the built-in tools from various vendors. But while tool support is helpful (and even critical, in bigger databases), doing the hard work of *understanding* and *explaining* the conceptual model of the database is the real win. From that perspective, you can even do it in a text file (though doing it in Wiki form would allow several people to collaborate on adding to that documentation incrementally - so, every time someone figures out something, they can add it to the growing body of documentation instantly). | One thing to consider is the COMMENT facility built into the DBMS. If you put comments on all of the tables and all of the columns in the DBMS itself, then your documentation will be inside the database system.
Using the COMMENT facility does not make any changes to the schema itself, it only adds data to the USER\_TAB\_COMMENTS catalog table. | How to document a database | [
"",
"sql",
"oracle",
"documentation",
""
] |
We have an HttpHandler that deals directly with binary posts over HTTP from custom client software. The client software occasionally sends data which results in IIS 7 responding with a 400 - Bad Request. Since the "400 Bad Request" is special in that HTTP.SYS transparently handles it in kernel mode without notifying user mode of anything, no errors are raised to be handled in ASP.NET. Is it possible to catch this http 400 in ASP.NET, so that I can write specific data to the Response stream in these scenarios? A redirect to another page isn't an option as it needs to be in the current Request/Response. | If you know what is causing the 400, then you may be able to customise the behaviour of http.sys via the registry to deal with it:
<http://support.microsoft.com/kb/820129>
However, you should be aware that there are potential security and performance ramifications of doing this.
Another option would be to use a filtering proxy before IIS, thereby capturing the request before it goes any further. | I would instead ask them to fix the custom client software. Give them a report showing the failed requests. If you are able to, run a sniffer such as Wireshark and send them the packets if they do not believe the problem is with their software. | Can an ASP.NET HttpHandler handle an http 400 - Bad Request? | [
"",
"c#",
"asp.net",
"http",
"iis-7",
"httphandler",
""
] |
I need to read the value of a property from a file in an Ant script and strip off the first few characters. The property in question is
```
path=file:C:/tmp/templates
```
This property is store in a file that I can access within the ant script via
```
<property file="${web.inf.dir}/config.properties"/>
```
I have two questions:
1. How do I read the single 'path' property from the loaded property file?
2. How do I remove the leading 'file:' from the property value?
Ultimately, I'd like to have access to the following name-value pair within the Ant script:
```
path=C:/tmp/templates
```
Cheers,
Don | I used the [propertyregex task](http://ant-contrib.sourceforge.net/tasks/tasks/propertyregex.html) from [Ant Contrib](http://ant-contrib.sourceforge.net/) to do something similar. | In Ant 1.6 or later you can use `LoadProperties` with a nested `FilterChain`
```
<loadproperties srcFile="${property.file.name}">
<filterchain>
<tokenfilter>
<containsstring contains="path=file:"/>
<replaceregex pattern="path=file:" replace="path=" flags=""/>
</tokenfilter>
</filterchain>
</loadproperties>
```
This should result in a `path` property being loaded with the string "file:" stripped.
Not tested, caveat emptor... | read property value in Ant | [
"",
"java",
"ant",
""
] |
I just finished reading this post: <https://developer.yahoo.com/performance/rules.html#flush> and have already implemented a flush after the top portion of my page loads (head, css, top banner/search/nav).
Is there any performance hit in flushing? Is there such a thing as doing it too often? What are the best practices?
If I am going to hit an external API for data, would it make sense to flush before hand so that the user isn't waiting on that data to come back, and can at least get some data before hand? | The technique described looks nice, but has several pitfalls:
1) the time between PHP script start and end is small compared to transmission time; also, this saves the user about 0.5 seconds, according to your source. Is that a significant amount of time for you?
2) this technique doesn't work with gzip output buffering
3) if you flush too often, you'll be sending an almost-empty packet on flush, which might actually increase loading time (on slow, noisy connections).
4) once you flush, you can't send any more headers
5) (minor issue) the server response will come in chunked encoding, which means the client won't know the size in advance (therefore won't display "x% done" when downloading a file).
On the other hand, if you expect your script to run for a loooong time (20+ seconds), it may be needed to send some data (spaces, for example) to keep the browser from timing out the connection. | Down side is that you can't gzip the content as well as flushing it afaik, so I've always preferred to gzip rather than flush.
> [Some versions of Microsoft Internet Explorer will only start to display the page after they have received 256 bytes of output, so you may need to send extra whitespace before flushing to get those browsers to display the page.](http://php.net/flush)
This makes this not idea, as it seems padding more data isn't very useful. | PHP Flush: How Often and Best Practices | [
"",
"php",
"optimization",
"flush",
""
] |
I'm using a 3rd party DLL written in unmanaged C++ that controls some hardware we have.
Unfortunately this DLL crashes now and then and I've been tasked to make it "reload" automagically. I'm not too sure about how to proceed to get best results.
My project uses C++.Net 2.0 (2005). I'm wrapping the 3rd party stuff in a separate DLL. I've been trying to FreeLibrary() and LoadLibrary(). However when I FreeLibrary(), some internal DLL dependencies remain allocated and LoadLibrary() will make it crash because of corrupted memory.
Another approach that was suggested was to refactor the whole project using .NET remoting interfaces. It would make it easier to kill another process and restart it but it will be a lot of work.
Any suggestions? Pointers? Hints? | The most effective approach will be to not load that DLL in your application's process at all. Instead, create a second process whose only job is to use that DLL on behalf of your application. You can use a shared memory region, local socket, or other IPC mechanism to control the proxy process.
This way, when the problematic DLL crashes, you can simply allow the proxy process to die without worrying about the (nearly impossible) task of trying to make sure the DLL didn't corrupt anything important on its way down. Your main process need only start a new instance of the proxy process and carry on. | I'm not a windows expert, but I think the general idea should hold.
LoadLibrary, FreeLibrary deal with mapping a DLL onto the process memory space. The corruption you are seeing is due presumably to some code inside the DLL doing something "bad" and almost certainly corrupting the process memory. Now If it's crashing, it's almost certainly killed the thread it was running in - if not the whole process.
I would take an educated guess that the only way to reliably recover and ensure non-corrupted memory is to run a sacrificial process as a wrapper round the rogue DLL. I assume the remoting interfaces are one way of doing this. There may be others. | How to reload a 3rd party DLL that crashes often | [
"",
".net",
"c++",
"winapi",
"dll",
""
] |
I am trying to so something like [Database Design for Tagging](https://stackoverflow.com/questions/48475/database-design-for-tagging), except each of my tags are grouped into categories.
For example, let's say I have a database about vehicles. Let's say we actually don't know very much about vehicles, so we can't specify the columns all vehicles will have. Therefore we shall "tag" vehicles with information.
```
1. manufacture: Mercedes
model: SLK32 AMG
convertible: hardtop
2. manufacture: Ford
model: GT90
production phase: prototype
3. manufacture: Mazda
model: MX-5
convertible: softtop
```
Now as you can see all cars are tagged with their manufacture and model, but the other categories don't all match. Note that a car can only have one of each category. IE. A car can only have one manufacturer.
I want to design a database to support a search for all Mercedes, or to be able to list all manufactures.
My current design is something like this:
```
vehicles
int vid
String vin
vehicleTags
int vid
int tid
tags
int tid
String tag
int cid
categories
int cid
String category
```
I have all the right primary and foreign keys in place, except I can't handle the case where each car can only have one manufacturer. Or can I?
Can I add a foreign key constraint to the composite primary key in vehicleTags? IE. Could I add a constraint such that the composite primary key (vid, tid) can only be added to vehicleTags only if there isn't already a row in vehicleTags such that for the same vid, there isn't already a tid in the with the same cid?
My guess is no. I think the solution to this problem is add a cid column to vehicleTags, and make the new composite primary key (vid, cid). It would look like:
```
vehicleTags
int vid
int cid
int tid
```
This would prevent a car from having two manufacturers, but now I have duplicated the information that tid is in cid.
What should my schema be?
Tom noticed this problem in my database schema in my previous question, [How do you do many to many table outer joins?](https://stackoverflow.com/questions/372399/how-do-you-do-many-to-many-table-outer-joins)
**EDIT**
I know that in the example manufacture should really be a column in the vehicle table, but let's say you can't do that. The example is just an example. | This is yet another variation on the [Entity-Attribute-Value](http://en.wikipedia.org/wiki/Entity-attribute-value_model) design.
A more recognizable EAV table looks like the following:
```
CREATE TABLE vehicleEAV (
vid INTEGER,
attr_name VARCHAR(20),
attr_value VARCHAR(100),
PRIMARY KEY (vid, attr_name),
FOREIGN KEY (vid) REFERENCES vehicles (vid)
);
```
Some people force `attr_name` to reference a lookup table of predefined attribute names, to limit the chaos.
What you've done is simply spread an EAV table over three tables, but without improving the order of your metadata:
```
CREATE TABLE vehicleTag (
vid INTEGER,
cid INTEGER,
tid INTEGER,
PRIMARY KEY (vid, cid),
FOREIGN KEY (vid) REFERENCES vehicles(vid),
FOREIGN KEY (cid) REFERENCES categories(cid),
FOREIGN KEY (tid) REFERENCES tags(tid)
);
CREATE TABLE categories (
cid INTEGER PRIMARY KEY,
category VARCHAR(20) -- "attr_name"
);
CREATE TABLE tags (
tid INTEGER PRIMARY KEY,
tag VARCHAR(100) -- "attr_value"
);
```
If you're going to use the EAV design, you only need the `vehicleTags` and `categories` tables.
```
CREATE TABLE vehicleTag (
vid INTEGER,
cid INTEGER, -- reference to "attr_name" lookup table
tag VARCHAR(100, -- "attr_value"
PRIMARY KEY (vid, cid),
FOREIGN KEY (vid) REFERENCES vehicles(vid),
FOREIGN KEY (cid) REFERENCES categories(cid)
);
```
But keep in mind that you're *mixing data with metadata*. You lose the ability to apply certain constraints to your data model.
* How can you make one of the categories mandatory (a conventional column uses a `NOT NULL` constraint)?
* How can you use SQL data types to validate some of your tag values? You can't, because you're using a long string for every tag value. Is this string long enough for every tag you'll need in the future? You can't tell.
* How can you constrain some of your tags to a set of permitted values (a conventional table uses a foreign key to a lookup table)? This is your "softtop" vs. "soft top" example. But you can't make a constraint on the `tag` column because that constraint would apply to all other tag values for other categories. You'd effectively restrict engine size and paint color to "soft top" as well.
SQL databases don't work well with this model. It's extremely difficult to get right, and querying it becomes very complex. If you do continue to use SQL, you will be better off modeling the tables conventionally, with one column per attribute. If you have need to have "subtypes" then define a subordinate table per subtype ([Class-Table Inheritance](http://www.martinfowler.com/eaaCatalog/classTableInheritance.html)), or else use [Single-Table Inheritance](http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html). If you have an unlimited variation in the attributes per entity, then use [Serialized LOB](http://www.martinfowler.com/eaaCatalog/serializedLOB.html).
Another technology that is designed for these kinds of fluid, non-relational data models is a Semantic Database, storing data in [RDF](http://en.wikipedia.org/wiki/Resource_Description_Framework) and queried with [SPARQL](http://en.wikipedia.org/wiki/SPARQL). One free solution is [RDF4J](https://rdf4j.org) (formerly Sesame). | I needed to solve this exact problem (same general domain and everything — auto parts). I found that the best solution to the problem was to use Lucene/Xapian/Ferret/Sphinx or whichever full-text indexer you prefer. Much better performance than what SQL can offer. | How to design a database schema to support tagging with categories? | [
"",
"sql",
"schema",
"tags",
"foreign-keys",
"entity-attribute-value",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.