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); ... | 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 ... | 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... | 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
*... | 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 i... | 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(){
... | 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... | 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
{
... | 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!");
}
}
pu... | 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... | 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/c... | 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; ... | 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... | 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... | 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 >... | 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 determinin... | 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 expo... | 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 pr... | 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 Interfac... | 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 del... | 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 fragmen... | 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... | 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 fa... | 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) {
/*cod... | ## 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 sho... | 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).... | 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 inte... | 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 =... | 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 k... | `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... | 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 thi... | 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:... | 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 ob... | 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 prop... | 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;... | 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 under... | 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 i... | 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 ... | 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 `TextB... | 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... | 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... | 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 t... | 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... | 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 logg... | 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... | 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/sta... | 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. ... | 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... | 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... | 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, ... | 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... | 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/GN12VariadicTemplatesA... | 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 answe... | 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 chec... | 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 ... | 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 ens... | ```
#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 ... | 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 o... | 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 thing... | 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 = co... | 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 ... | 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="... | 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 n... | 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 runni... | 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 Framewor... | 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/>
... | 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 h... | 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.n... | 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 u... | 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 cour... | 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 ... | 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 thi... | 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) wo... | 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 wit... | 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", ... | 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.... | 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-Typ... | 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 li... | 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 ... | "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.Instanc... | 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,
... | 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()
}
`... | 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 t... | 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 ... | 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.prot... | 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 chan... | 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 ... | 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 instantaneo... | 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 wi... | 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 get... | 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 fo... | 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.
... | 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 da... | 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 proc... | 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/funct... | 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 gre... | 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... | ```
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 framewo... | 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, Rol... | 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 e... | 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"
... | 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 method... | 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 Whee... | 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... | 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.jp... | 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 betwee... | [`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 me... | 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... | 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().StartsWit... | 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:... | 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 whe... | 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>`... | 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 h... | ```
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,... | 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 cr... | 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 fi... | 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 c... | 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 exp... | 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-com... | 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 pr... | 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... | 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 fo... | 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... | 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 go... | 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 repla... | 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 ... | 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"
... | 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, ... | 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 ... | 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 mont... | 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.getEl... | 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 *de... | 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, ins... | 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 ... | 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 th... | [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 ... | 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 b... | > 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
+- tes... | > 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 dupli... | 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 functi... | 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));
$bu... | 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:
... | 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... | 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, shou... | 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... | 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 conce... | 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: BA... | 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 e... | 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... | 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 al... | 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 w... | *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 th... | 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 ... | 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... | 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... | 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 ac... | 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... | 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-cruiks... | 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 ma... | 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 O... | 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... | 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 ... | 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 ... | 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' ... | 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 ... | 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]... | 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,... | 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... | 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 agai... | 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 ... | 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 ge... | 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_d... | 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 ... | 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)
{
TreeNod... | 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,... | 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 h... | 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... | 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... | 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... | 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_jQu... | 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 i... | 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 u... | **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;
Lis... | 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... | 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, s... | 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 cas... | 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 do... | > 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 fo... | 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 t... | 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 joi... | 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... | 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 t... | 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... | 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() i... | 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
definiti... | 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. Manage... | 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 t... | 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 out... | 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-manag... | 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 fo... | 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... | 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... | 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 ca... | 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... | 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:... | 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 Re... | 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 questi... | 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 pro... | 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 ... | 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 por... | 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\_TA... | 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 us... | 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 filt... | 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 t... | 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>
</loa... | 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 practice... | 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 buffer... | 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 ge... | 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... | 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 prob... | 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,... | 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 spec... | 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_nam... | 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.