Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
I am currently developing an approval routing WCF service that will allow an user to create "rules" which determine how an request is routed. The route is determined by comparing the "ObjectToEvaluate" property of the Request class against the "ObjectToEvaluate" property of the "Rule" class. The "UnitOfMeasurement" enum determines how to cast the "ObjectToEvaluate" property for each class.
```
public enum UnitOfMeasurement
{
Currency = 1,
Numeric = 2,
Special = 3,
Text = 4,
}
public class Request
{
public object ObjectToEvaluate { get; set; }
}
public class Rule
{
public object ObjectToEvaluate { get; set; }
public virtual void ExecuteRule()
{
//logic to see if it passes the rule condition
}
}
```
What would be the best way to implement the method to cast the "ObjectToEvaluate" property using the "UnitOfMeasurement" enum?
|
Use an implicit type operator that checks the value of the enum. That way callers can transparently assign the objects to the types you want to represent them. Eg:
```
public class CastableObject {
private UnitOfMeasurement eUnit; // Assign this somehow
public static implicit operator int(CastableObject obj)
{
if (obj.eUnit != UnitOfMeasurement.Numeric)
{
throw new InvalidCastException("Mismatched unit of measurement");
}
// return the numeric value
}
// Create other cast operators for the other unit types
}
```
|
Where are you getting the unit of measurement from? I can see the enum, but I don't see any reference to it elsewhere in the API.
Assuming you do get it from somewhere, the easiest solution may well be a switch statement. It's a bit ugly, but:
* It'll work
* It's easy to understand
* It'll be fast
I'm still not entirely convinced I understand everything about the question though - particularly as you haven't explained what the other objects will be used for after casting.
|
Best way to determine how to cast an object to an appropriate type in C#?
|
[
"",
"c#",
"casting",
""
] |
Is there any way to take a Class and determine if it represents a primitive type (is there a solution that doesn't require specifically enumerating all the primitive types)?
NOTE: I've seen [this question](https://stackoverflow.com/questions/180097/dynamically-find-the-class-that-represents-a-primitive-java-type). I'm asking basically the opposite. I have the Class, I want to know if it's a primitive.
|
There is a method on the Class object called [isPrimitive](http://java.sun.com/javase/6/docs/api/java/lang/Class.html#isPrimitive()).
|
[Class.isPrimitive()](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html#isPrimitive()) will tell you the answer.
|
How can I generically tell if a Java Class is a primitive type?
|
[
"",
"java",
""
] |
I have a generic class in C# with 2 constructors:
```
public Houses(params T[] InitialiseElements)
{}
public Houses(int Num, T DefaultValue)
{}
```
Constructing an object using int as the generic type and passing in two ints as arguments causes the 'incorrect' constructor to be called (from my point of view).
E.g. `Houses<int> houses = new Houses<int>(1,2)` - calls the 2nd construtor. Passing in any other number of ints into the constructor will call the 1st constructor.
Is there any way around this other than removing the params keyword and forcing users to pass an array of T when using the first constructor?
|
A clearer solution would be to have two static factory methods. If you put these into a nongeneric class, you can also benefit from type inference:
```
public static class Houses
{
public static Houses<T> CreateFromElements<T>(params T[] initialElements)
{
return new Houses<T>(initialElements);
}
public Houses<T> CreateFromDefault<T>(int count, T defaultValue)
{
return new Houses<T>(count, defaultValue);
}
}
```
Example of calling:
```
Houses<string> x = Houses.CreateFromDefault(10, "hi");
Houses<int> y = Houses.CreateFromElements(20, 30, 40);
```
Then your generic type's constructor doesn't need the "params" bit, and there'll be no confusion.
|
Perhaps instead of Params you could pass in IEnumerable
```
public Houses(IEnumerable<T> InitialiseElements){}
```
|
Using C# params keyword in a constructor of generic types
|
[
"",
"c#",
".net",
"c#-3.0",
""
] |
When I'm writing a Spring command line application which parses command line arguments, how do I pass them to Spring? Would I want to have my main() structured so that it first parses the command line args and then inits Spring? Even so, how would it pass the object holding the parsed args to Spring?
|
Two possibilities I can think of.
1) Set a static reference. (A static variable, although typically frowned upon, is OK in this case, because there can only be 1 command line invocation).
```
public class MyApp {
public static String[] ARGS;
public static void main(String[] args) {
ARGS = args;
// create context
}
}
```
You can then reference the command line arguments in Spring via:
```
<util:constant static-field="MyApp.ARGS"/>
```
Alternatively (if you are completely opposed to static variables), you can:
2) Programmatically add the args to the application context:
```
public class MyApp2 {
public static void main(String[] args) {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
// Define a bean and register it
BeanDefinition beanDefinition = BeanDefinitionBuilder.
rootBeanDefinition(Arrays.class, "asList")
.addConstructorArgValue(args).getBeanDefinition();
beanFactory.registerBeanDefinition("args", beanDefinition);
GenericApplicationContext cmdArgCxt = new GenericApplicationContext(beanFactory);
// Must call refresh to initialize context
cmdArgCxt.refresh();
// Create application context, passing command line context as parent
ApplicationContext mainContext = new ClassPathXmlApplicationContext(CONFIG_LOCATIONS, cmdArgCxt);
// See if it's in the context
System.out.println("Args: " + mainContext.getBean("args"));
}
private static String[] CONFIG_LOCATIONS = new String[] {
"applicationContext.xml"
};
}
```
Parsing the command line arguments is left as an exercise to the reader.
|
Have a look at my Spring-CLI library - at <http://github.com/sazzer/spring-cli> - as one way of doing this. It gives you a main class that automatically loads spring contexts and has the ability to use Commons-CLI for parsing command line arguments automatically and injecting them into your beans.
|
Dealing with command line arguments and Spring
|
[
"",
"java",
"spring",
"command-line",
""
] |
Consider this case:
```
dll = LoadDLL()
dll->do()
...
void do() {
char *a = malloc(1024);
}
...
UnloadDLL(dll);
```
At this point, will the 1k allocated in the call to malloc() be available to the host process again?
The DLL is statically linking to the CRT.
|
No, you do not leak.
If you mix dll models (static, dynamic) then you can end up with a memory error if you allocate memory in a dll, that you free in a different one (or freed in the exe)
This means that the heap created by the statically-linked CRT is not the same heap as a different dll's CRT.
If you'd linked with the dynamic version of the CRT, then you'd have a leak as the heap is shared amongst all dynamically-linked CRTs. It means you should always design your apps to use the dynamic CRTs, or ensure you never manage memory across a dll boundary (ie if you allocate memory in a dll, always provide a routine to free it in the same dll)
|
1. Memory used by a process as tracked by the OS is applicable to the full process and not specific to a DLL.
2. Memory is given to the program in chunks by the OS, called heaps
3. The heap managers (malloc / new etc) further divide up the chunks and hands it out to requesting code.
4. Only when a new heap is allocated does the OS detect an increase in memory.
5. When a DLL is statically linked to the C Run time library (CRT), a private copy of CRT with the CRT functions that the DLL's code invokes is compiled and put into the DLL's binary. Malloc is also inclued in this.
6. This private copy of malloc will be invoked whenever the code present inside the statically linked DLL tries to allocate memory.
7. Consequently, a private heap visible only to this copy of malloc, is acquired from the OS by this malloc and it allocates the memory requested by the code within this private heap.
8. **When the DLL unloads, it unloads its private heap, and this leak goes unnoticed as the entire heap is returned back to the OS**.
9. However If the DLL is dynamically linked, the memory is allocated by a single shared version of malloc, global to all code that is linked in the shared mode.
10. Memory allocated by this global malloc, comes out of a heap which is also the heap used for all other code that is linked in the dynamic aka shared mode and hence is common. Any leaks from this heap therefore becomes a leak which affects the whole process.
Edit - Added descriptions of the linking scenario.
|
Does a memory leak at unload of a DLL cause a leak in the host process?
|
[
"",
"c++",
"winapi",
"dll",
"memory-management",
"crt",
""
] |
The simple demo below captures what I am trying to do. In the real program, I have to use the object initialiser block since it is reading a list in a LINQ to SQL select expression, and there is a value that that I want to read off the database and store on the object, but the object doesn't have a simple property that I can set for that value. Instead it has an XML data store.
It looks like I can't call an extension method in the object initialiser block, and that I can't attach a property using extension methods.
So am I out of luck with this approach? The only alternative seems to be to persuade the owner of the base class to modify it for this scenario.
I have an existing solution where I subclass BaseDataObject, but this has problems too that don't show up in this simple example. The objects are persisted and restored as BaseDataObject - the casts and tests would get complex.
```
public class BaseDataObject
{
// internal data store
private Dictionary<string, object> attachedData = new Dictionary<string, object>();
public void SetData(string key, object value)
{
attachedData[key] = value;
}
public object GetData(string key)
{
return attachedData[key];
}
public int SomeValue { get; set; }
public int SomeOtherValue { get; set; }
}
public static class Extensions
{
public static void SetBarValue(this BaseDataObject dataObject,
int barValue)
{
/// Cannot attach a property to BaseDataObject?
dataObject.SetData("bar", barValue);
}
}
public class TestDemo
{
public void CreateTest()
{
// this works
BaseDataObject test1 = new BaseDataObject
{ SomeValue = 3, SomeOtherValue = 4 };
// this does not work - it does not compile
// cannot use extension method in the initialiser block
// cannot make an exension property
BaseDataObject test2 = new BaseDataObject { SomeValue = 3, SomeOtherValue = 4, SetBarValue(5) };
}
}
```
One of the answers (from mattlant) suggests using a fluent interface style extension method. e.g.:
```
// fluent interface style
public static BaseDataObject SetBarValueWithReturn(this BaseDataObject dataObject, int barValue)
{
dataObject.SetData("bar", barValue);
return dataObject;
}
// this works
BaseDataObject test3 = (new BaseDataObject { SomeValue = 3, SomeOtherValue = 4 }).SetBarValueWithReturn(5);
```
But will this work in a LINQ query?
|
Even better:
```
public static T SetBarValue<T>(this T dataObject, int barValue)
where T : BaseDataObject
{
dataObject.SetData("bar", barValue);
return dataObject;
}
```
and you can use this extension method for derived types of BaseDataObject to chain methods without casts and preserve the real type when inferred into a var field or anonymous type.
|
Object Initializers are just syntactic sugar that requires a clever compiler, and as of the current implementation you can't call methods in the initializer.
```
var x = new BaseDataObject { SomeValue = 3, SomeOtherValue = 4 };
```
Will get compiler to something like this:
```
BaseDataObject tempObject = new BaseDataObject();
tempObject.SomeValue = 3;
tempObject.SomeOtherValue = 4;
BaseDataObject x = tempObject;
```
The difference is that there can't be any synchronization issues. The variable x get's assigned the fully assigned BaseDataObject at once, you can't mess with the object during it's initialization.
You could just call the extension method after the object creation:
```
var x = new BaseDataObject { SomeValue = 3, SomeOtherValue = 4 };
x.SetBarValue()
```
You could change SetBarValue to be a property with get/set that can be assigned during initialization:
```
public int BarValue
{
set
{
//Value should be ignored
}
}
```
Or, you could subclass / use the facade pattern to add the method onto your object:
```
public class DataObjectWithBarValue : BaseDataObject
{
public void BarValue
{
set
{
SetData("bar", value);
}
get
{
(int) GetData("bar");
}
}
}
```
|
Is there any way to use an extension method in an object initializer block in C#
|
[
"",
"c#",
"linq",
"extension-methods",
"initializer",
""
] |
I'm trying to build a proxy module for .NET, but I'm having trouble copying the Headers from the current request to the new request. I am setting the headers of the new request, because I want the proxy to support SOAP requests. Here is a portion of my code. I can post everything if need, but this is the only part that seems related to the issue I am having:
```
HttpApplication app = (HttpApplication)sender; // sender from context.BeginRequest event
HttpRequest crntReq = app.Request; // set a reference to request object for easier access
HttpWebRequest proxyReq = (HttpWebRequest)HttpWebRequest.Create(crntReq.Url.AbsoluteUri);
// parse headers from current httpcontext.request.headers and add each name->value to the
// new request object
foreach (string header in crntReq.Headers)
{
proxyReq.Headers.Add(header, crntReq.Headers[header]); // throws exception :(
}
```
When my code hits the foreach loop, it throws an exception for the Headers.Add function. I'm assuming the collection has access restrictions, for security purposes. It appears that some of the header values are accessible with properties for the HttpWebRequest object itself. However in this case I'd rather get rid of the abstraction and set the properties manually. The exception that I'm receiving is:
*{"This header must be modified using the appropriate property.\r\nParameter name: name"}*
---
Thanks in advance for your help,
CJAM
|
Some of the headers are actually exposed as properties directly on the HttpWebRequest object. These headers you are not allowed to set directly. e.g HttpWebRequest,ContentType and HttpWebRequest.UserAgent
You will need to update these properties directly and avoid setting them via the Headers property.
|
So I am understanding your response as "It's not possible to set the collection explicitly." I was hoping there was a way to add names and values to the NameValueDictionary, but I guess I'll need to just determine which fields I need to set and use the properties to access specific name/value objects. I guess I could use inheritance and roll my own version of the HttpWebRequest object, but I'm sure the folks at Microsoft had a reason behind encapsulating the collection, so I'll probably just leave things the way they are.
Thanks for your help on this.
|
Need Help With HttpWebRequest object
|
[
"",
"c#",
"asp.net",
""
] |
When creating a class that has internal private methods, usually to reduce code duplication, that don't require the use of any instance fields, are there performance or memory advantages to declaring the method as static?
Example:
```
foreach (XmlElement element in xmlDoc.DocumentElement.SelectNodes("sample"))
{
string first = GetInnerXml(element, ".//first");
string second = GetInnerXml(element, ".//second");
string third = GetInnerXml(element, ".//third");
}
```
...
```
private static string GetInnerXml(XmlElement element, string nodeName)
{
return GetInnerXml(element, nodeName, null);
}
private static string GetInnerXml(XmlElement element, string nodeName, string defaultValue)
{
XmlNode node = element.SelectSingleNode(nodeName);
return node == null ? defaultValue : node.InnerXml;
}
```
Is there any advantage to declaring the GetInnerXml() methods as static? No opinion responses please, I have an opinion.
|
From the [FxCop rule page](http://msdn.microsoft.com/en-us/library/ms245046.aspx) on this:
> After you mark the methods as static, the compiler will emit non-virtual call sites to these members. Emitting non-virtual call sites will prevent a check at runtime for each call that ensures that the current object pointer is non-null. This can result in a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue.
|
When I'm writing a class, most methods fall into two categories:
* Methods that use/change the current instance's state.
* Helper methods that don't use/change the current object's state, but help me compute values I need elsewhere.
Static methods are useful, because just by looking at its signature, you know that the calling it doesn't use or modify the current instance's state.
Take this example:
```
public class Library
{
private static Book findBook(List<Book> books, string title)
{
// code goes here
}
}
```
If an instance of library's state ever gets screwed up, and I'm trying to figure out why, I can rule out findBook as the culprit, just from its signature.
I try to communicate as much as I can with a method or function's signature, and this is an excellent way to do that.
|
Advantages to Using Private Static Methods
|
[
"",
"c#",
"performance",
""
] |
I have these two pieces of code, wich one is more readable?
1. foreach
```
decimal technicalPremium = 0;
foreach (Risk risk in risks)
{
technicalPremium = technicalPremium + risk.TechnicalPremium;
}
return technicalPremium;
```
2. linq
```
return risks.Sum(risk => risk.TechnicalPremium);
```
|
If the team that works on the code knows what the Linq version does and knows its inner workings, then it is more readable.
|
Use whichever you prefer but hide it in a method:
```
return risks.SumTechnicalPremium();
```
|
What is more readable?
|
[
"",
"c#",
"linq",
"lambda",
"readability",
""
] |
I have stfw but I cannot find a simple / standalone way to create a webservice client in java.
Does anyone have a link/sample into this?
|
How about using [Axis2](http://ws.apache.org/axis2/)?
Just follow the [quickstart guide](http://ws.apache.org/axis2/1_4_1/quickstartguide.html) and you should be on your way.
Here is another more descriptive [guide](http://ws.apache.org/axis2/1_0/userguide3.html#Writing_Web_Service_Clients_using_Code_Generation_with_Data_Binding_Support)
|
[soapUI](http://www.soapui.org/) is a great tool to test a Web Service. It is really simple to either create a server stub to test your client or just send client request to any Web Service.
|
java webservice client
|
[
"",
"java",
"webservice-client",
""
] |
I'm working on what I think is a pretty standard django site, but am having trouble getting my admin section to display the proper fields.
Here's my models.py:
```
class Tech(models.Model):
name = models.CharField(max_length = 30)
class Project(models.Model):
title = models.CharField(max_length = 50)
techs = models.ManyToManyField(Tech)
```
In other words, a Project can have different Tech objects and different tech objects can belong to different Projects (Project X was created with Python and Django, Project Y was C# and SQL Server)
However, the admin site doesn't display any UI for the Tech objects. Here's my admin.py:
```
class TechInline(admin.TabularInline):
model = Tech
extra = 5
class ProjectAdmin(admin.ModelAdmin):
fields = ['title']
inlines = []
list_display = ('title')
admin.site.register(Project, ProjectAdmin)
```
I've tried adding the `TechInline` class to the `inlines` list, but that causes a
```
<class 'home.projects.models.Tech'> has no ForeignKey to <class 'home.projects.models.Project'>
```
Error. Also tried adding `techs` to the `fields` list, but that gives a
> no such table: projects\_project\_techs
Error. I verified, and there is no `projects_project_techs` table, but there is a `projects_tech` one. Did something perhaps get screwed up in my syncdb?
I am using Sqlite as my database if that helps.
|
> I've tried adding the TechInline class to the inlines list, but that causes a
>
> 'TechInLine' not defined
Is that a straight copy-paste? It looks like you just made a typo -- try `TechInline` instead of `TechInLine`.
If your syncdb didn't create the proper table, you can do it manually. Execute this command:
```
python manage.py sqlreset <myapp>
```
And look for the definition for the `projects_project_techs` table. Copy and paste it into the client for your database.
|
@John Millikin - Thanks for the sqlreset tip, that put me on the right path. The sqlreset generated code that showed me that the `projects_project_techs` was never actually created. I ended up just deleting my deb.db database and regenerating it. `techs` then showed up as it should.
And just as a sidenote, I had to do an `admin.site.register(Tech)` to be able to create new instances of the class from the Project page too.
I'll probably post another question to see if there is a better way to implement model changes (since I'm pretty sure that is what caused my problem) without wiping the database.
|
Django admin site not displaying ManyToManyField relationship
|
[
"",
"python",
"django",
""
] |
If I have a string (010) and i want to add 1 to it (011) what value type should i use to convert this string into a number for adding and at the same time preserve the whole number and not 10 + 1 = 11.
|
You could use something like this:
```
string initialValue = "010";
int tempValue = Int.Parse(initialValue) + 1;
string newValue = tempValue.ToString("000");
```
You do your math as normal and then just return your string to its previous format using the number formatting feature of the `.ToString()`
|
```
if (int.TryParse(str, out i))
str = (i + 1).ToString("000");
```
HTH.
(**edit**: fixed the problems pointed out by BoltBait and steffenj)
|
What value to use? C# (Adding numbers represented as strings)
|
[
"",
"c#",
"algorithm",
""
] |
I develop a number of desktop Java applications using Swing, and while Swing is quite powerful (once you get the hang of it), there are still a lot of cases where I wish some advanced component was available right out of the box.
For example, I'd really like to see easy-to-use components (without writing them myself, which I could do given enough time) like:
* Multi-line label
* Windows File Explorer-like Icons or Thumbnails view
* Drop-down button (like Firefox's old Back button)
* 5-star rating widget
* Combo box with automatic history (like the text field on Google)
* An Outlook-style accordion-style bar
* and so on
I know of a couple of sources of free Swing components, like [SwingLabs](http://swinglabs.org), home of JXTable, JXDatePicker, and a few others.
**Where do you go for Swing components beyond those included with Java itself?**
|
The following are worth a look:
* [swingX](https://swingx.dev.java.net/)
* [Glazed lists](http://publicobject.com/glazedlists/)
* [Substance look'n'feel](https://substance.dev.java.net/)
* [Flamingo components](https://flamingo.dev.java.net/)
* [Ken Orr's Mac Widgets](http://code.google.com/p/macwidgets/)
* [Jide's open source components](http://www.jidesoft.com/products/oss.htm)
|
As for: "Windows File Explorer-like Icons or Thumbnails view"
They are built in in swing.
File explorer icons are accessed through FileSystemView class ( it is used by JFileChooser ) when the L&F is Windows of course.
```
FileSystemView.getFileSystemView();
Icon driveIcon = fsv.getSystemIcon( new File("C:\\"));
```
And the Thumbnails icon can be retrieved with the sun.com class that are discouraged by Sun
```
sun.awt.shell.ShellFolder getIcon( boolean largeIcon )
```
But this one may not perform very well some times ( due to native resources handling I think ).
|
Open-source improvements or replacements for Swing components
|
[
"",
"java",
"swing",
"components",
""
] |
Is it currently possible to translate C# code into an Abstract Syntax Tree?
Edit: some clarification; I don't necessarily expect the compiler to generate the AST for me - a parser would be fine, although I'd like to use something "official." Lambda expressions are unfortunately not going to be sufficient given they don't allow me to use statement bodies, which is what I'm looking for.
|
The [Roslyn](http://msdn.microsoft.com/en-us/roslyn) project is in Visual Studio 2010 and gives you programmatic access to the [Syntax Tree](https://learn.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/work-with-syntax#syntax-trees), among other things.
```
SyntaxTree tree = SyntaxTree.ParseCompilationUnit(
@" C# code here ");
var root = (CompilationUnitSyntax)tree.Root;
```
|
> Is it currently possible to translate C# code into an Abstract Syntax Tree?
Yes, trivially in special circumstances (= using the new [Expressions framework](http://msdn.microsoft.com/en-us/library/bb397951.aspx)):
```
// Requires 'using System.Linq.Expressions;'
Expression<Func<int, int>> f = x => x * 2;
```
This creates an expression tree for the lambda, i.e. a function taking an `int` and returning the double. You can modify the expression tree by using the Expressions framework (= the classes from in that namespace) and then compile it at run-time:
```
var newBody = Expression.Add(f.Body, Expression.Constant(1));
f = Expression.Lambda<Func<int, int>>(newBody, f.Parameters);
var compiled = f.Compile();
Console.WriteLine(compiled(5)); // Result: 11
```
Notice that all expressions are immutable so they have to be built anew by composition. In this case, I've prepended an addition of 1.
Notice that these expression trees only work on real expressions i.e. content found in a C# function. You can't get syntax trees for higher constructs such as classes this way. Use the CodeDom framework for these.
|
Translate C# code into AST?
|
[
"",
"c#",
"compiler-construction",
"abstract-syntax-tree",
""
] |
I'm having trouble dynamically adding controls inside an update panel with partial postbacks. I've read many articles on dynamic controls and I understand how to add and maintain them with postbacks but most of that information doesn't apply and won't work for partial postbacks. I can't find any useful information about adding and maintaining them with UpdatePanels. I'd like to do this without creating a web service if it's possible. Does anyone have any ideas or references to some helpful information?
|
This is, I think, one of the common pitfalls for asp.net programmers but isn't actually that hard to get it right when you know what is going on (always remember your viewstate!).
the following piece of code explains how things can be done. It's a simple page where a user can click on a menu which will trigger an action that will add a user control to the page inside the updatepanel.
(This code is borrowed [from here](https://web.archive.org/web/20200804033347/http://geekswithblogs.net/rashid/archive/2007/08/11/Loading-UserControl-Dynamically-in-UpdatePanel.aspx), and has lots more of information concerning this topic)
```
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SampleMenu1.aspx.cs" Inherits="SampleMenuPage1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Sample Menu</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Menu ID="Menu1" runat="server" OnMenuItemClick="Menu1_MenuItemClick">
<Items>
<asp:MenuItem Text="File">
<asp:MenuItem Text="Load Control1"></asp:MenuItem>
<asp:MenuItem Text="Load Control2"></asp:MenuItem>
<asp:MenuItem Text="Load Control3"></asp:MenuItem>
</asp:MenuItem>
</Items>
</asp:Menu>
<br />
<br />
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Menu1" />
</Triggers>
</asp:UpdatePanel>
</form>
</body>
</html>
```
and
```
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class PlainSampleMenuPage : System.Web.UI.Page
{
private const string BASE_PATH = "~/DynamicControlLoading/";
private string LastLoadedControl
{
get
{
return ViewState["LastLoaded"] as string;
}
set
{
ViewState["LastLoaded"] = value;
}
}
private void LoadUserControl()
{
string controlPath = LastLoadedControl;
if (!string.IsNullOrEmpty(controlPath))
{
PlaceHolder1.Controls.Clear();
UserControl uc = (UserControl)LoadControl(controlPath);
PlaceHolder1.Controls.Add(uc);
}
}
protected void Page_Load(object sender, EventArgs e)
{
LoadUserControl();
}
protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
{
MenuItem menu = e.Item;
string controlPath = string.Empty;
switch (menu.Text)
{
case "Load Control2":
controlPath = BASE_PATH + "SampleControl2.ascx";
break;
case "Load Control3":
controlPath = BASE_PATH + "SampleControl3.ascx";
break;
default:
controlPath = BASE_PATH + "SampleControl1.ascx";
break;
}
LastLoadedControl = controlPath;
LoadUserControl();
}
}
```
for the code behind.
That's basically it. You can clearly see that the viewstate is being kept with *LastLoadedControl* while the controls themselves are dynamically added to the page (inside the updatePanel (actually inside the placeHolder inside the updatePanel) when the user clicks on a menu item, which will send an asynchronous postback to the server.
More information can also be found here:
* [http://aspnet.4guysfromrolla.com/articles/081402-1.aspx](https://web.archive.org/web/20210707024005/http://aspnet.4guysfromrolla.com/articles/081402-1.aspx)
* [http://aspnet.4guysfromrolla.com/articles/082102-1.aspx](https://web.archive.org/web/20210707024009/http://aspnet.4guysfromrolla.com/articles/082102-1.aspx)
and of course on [the website that holds the example code](https://web.archive.org/web/20200804033347/http://geekswithblogs.net/rashid/archive/2007/08/11/Loading-UserControl-Dynamically-in-UpdatePanel.aspx) I used here.
|
I encountered the problem that using the method mentioned above, LoadUserControl() is called twice when handling an event. I've read through some other articles and would like to show you my modification:
1) Use LoadViewstate instead of Page\_Load to load the user control:
```
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
if (!string.IsNullOrEmpty(CurrentUserControl))
LoadDataTypeEditorControl(CurrentUserControl, panelFVE);
}
```
2) Don't forget to set the control id when loading the usercontrol:
```
private void LoadDataTypeEditorControl(string userControlName, Control containerControl)
{
using (UserControl myControl = (UserControl) LoadControl(userControlName))
{
containerControl.Controls.Clear();
string userControlID = userControlName.Split('.')[0];
myControl.ID = userControlID.Replace("/", "").Replace("~", "");
containerControl.Controls.Add(myControl);
}
this.CurrentUserControl = userControlName;
}
```
|
Programmatically Adding User Controls Inside An UpdatePanel
|
[
"",
"c#",
"asp.net",
"asp.net-ajax",
""
] |
Some text before the code so that the question summary isn't mangled.
```
class Tree
{
public event EventHandler MadeSound;
public void Fall() { MadeSound(this, new EventArgs()); }
static void Main(string[] args)
{
Tree oaky = new Tree();
oaky.Fall();
}
}
```
I haven't used events much in C#, but the fact that this would cause a NullRefEx seems weird. The EventHandler reference is considered null because it currently has no subsribers - but that doesn't mean that the event hasn't occurred, does it?
EventHandlers are differentiated from standard delegates by the **event** keyword. Why didn't the language designers set them up to fire silently in to the void when they have no subscribers? (I gather you can do this manually by explicitly adding an empty delegate).
|
You need to understand what your event declaration is actually doing. It's declaring both an event and a variable, When you refer to it within the class, you're just referring to the variable, which will be null when there are no subscribers.
|
Well, the canonical form is:
```
void OnMadeSound()
{
if (MadeSound != null)
{
MadeSound(this, new EventArgs());
}
}
public void Fall() { OnMadeSound(); }
```
which is *very slightly* faster that calling an empty delegate, so speed won out over programming convenience.
|
Why must someone be subscribed for an event to occur?
|
[
"",
"c#",
"events",
""
] |
My main JavaScript framework is [jQuery](http://jquery.com/), so I would like my unit test and mocking frameworks to be compatible with that. I'd rather not have to introduce another JavaScript framework.
I am currently using [QUnit](http://docs.jquery.com/QUnit) for unit testing and [Jack](https://github.com/keronsen/jack) for mocking, but I am pretty new to the whole unit testing of JavaScript.
Is there a better tool to suggest? What has worked for you?
|
[QUnit](http://docs.jquery.com/QUnit)
[jqUnit](http://code.google.com/p/jqunit/)
[Writing JavaScript tests with QUnit and jqUnit](http://wiki.fluidproject.org/display/fluid/Writing+JavaScript+Unit+Tests)
QUnit is the unit testing framework for the jQuery JavaScript framework. The testing framework itself uses the jQuery library, but the tests can be written for any JavaScript and do not require the code to use jQuery.
jqUnit is a modified version of QUnit that adds in the setup, teardown, and assert functions that are more typical of an xUnit framework, and encapsulates everything in one global variable.
The visual interface of the testrunner page is nice, allowing you to drill down and see each assert in every test method. Writing tests is fairly easy, and you can run the test code directly on the testRunner page [8]. This allows for easy and visible DOM testing.
QUnit: MIT or GPL (choose) jqUnit: MIT License
**Pros**
* Asynchronous support
* Good for DOM testing
* Tests always run sequentially in the order they are added to a suite
* Debug on test page using firebug
* Syntax is similar to JUnit if using jqUnit, but simple to learn if using QUnit
**Cons**
* Automation would be difficult to implement
|
I think that Jack is the best mocking framework for JavaScript as of the time of this writing. The main reason is that what's right for JavaScript is not likely what is right for a strongly typed language such as Java.
Many JavaScript mocking frameworks are inspired by Java mock frameworks (such as the excellent JsMockito, for example). But the problem with these is that they **require** dependency injection, because that's about the only reasonable way to use mocking in Java. But in JavaScript, there are *many* ways to use mocking, and you are not **forced** into using dependency injection everywhere.
For example, with JsMockito, you have to make mocks and then **pass those mocks into** your software-under-test (SUT). The SUT has to directly call the mocks. Therefore, you're forced to code the SUT as a constructor or function that takes in all its dependencies as parameters. (Sometimes, that's a fine way to implement it, but not in every case. The tail is wagging the dog if your mocking framework's design forces your implementation approach.)
In JavaScript, it's very easy to "hijack" any function. Therefore, there are tons of ways to build something such that you can mock parts of it without explicitly injecting its dependencies into it. For example, Jack lets you mock *any* function, whether it is public or on a local object. From there you can spy on it, stub it, or express expectations on it. The key point is this: **once you've mocked a function, *any* calls to that original function will instead be directed to your mock**. In other words, your mocks will still get used even though the original, un-mocked function was called. As a result, you are not forced to inject dependencies, although you certainly can do so in those cases which call for it.
JavaScript is a different language than Java (and C#, etc.). It allows for different implementation idioms. **[Dependency injection](https://en.wikipedia.org/wiki/Dependency_injection) is still one valuable tool in the toolbox in JavaScript, but it is not the only game in town any more.** Your mocking framework needs to know and respect that fact. Jack and a couple of others do, but of the ones that do, Jack appears to be the most mature and feature-rich.
|
What are some JavaScript unit testing and mocking frameworks you have used?
|
[
"",
"javascript",
"jquery",
"unit-testing",
"mocking",
"qunit",
""
] |
I'm working on a Java library and would like to remove some functions from it. My reasons for this is public API and design cleanup. Some objects have setters, but should be immutable, some functionality has been implemented better/cleaner in different methods, etc.
I have marked these methods 'deprecated', and would like to remove them eventually. At the moment I'm thinking about removing these after few sprints (two week development cycles).
Are there any 'best practices' about removing redundant public code?
|
Set a date and publicize it in the @deprecated tag. The amount of time given to the removal depends on the amount of users your code has, how well connected you are with them and the the reason for the change.
If you have thousands of users and you barely talk to them, the time frame should probably be in the decades range :-)
If your users are your 10 coworkers and you see them daily, the time frame can easily be in the weeks range.
```
/**
* @deprecated
* This method will be removed after Halloween!
* @see #newLocationForFunctionality
*/
```
|
Consider it this way, customer A downloads the latest version of you library file or frame work. He hits compile on this machine and suddenly he see thousands of errors because the member file or function does no longer exist. From this point on, you've given the customer a reason why not to upgrade to your new version and to stay with the old version.
Raymond Chen answers this the best with his blog about win32 API,
Though, our experience in our software house has been, once the API has been written we have to carry the API to the end of the product life cycle. To help users to new versions, we provide backwards compatibility with the old commands in the new framework.
|
How to handle functions deprecation in library?
|
[
"",
"java",
""
] |
Boost range library (<http://www.boost.org/doc/libs/1_35_0/libs/range/index.html>) allows us to abstract a pair of iterators into a range. Now I want to combine two ranges into one, viz:
given two ranges r1 and r2, define r which traverses [r1.begin(), r1.end()[ and then [r2.begin(), r2.end()[. Is there some way to define r as a range using r1 and r2?
|
I needed this again so I had a second look. There is a way to concat two ranges using boost/range/join.hpp. Unluckily the output range type is not included in the interface:
```
#include "boost/range/join.hpp"
#include "boost/foreach.hpp"
#include <iostream>
int main() {
int a[] = {1, 2, 3, 4};
int b[] = {7, 2, 3, 4};
boost::iterator_range<int*> ai(&a[0], &a[4]);
boost::iterator_range<int*> bi(&b[0], &b[4]);
boost::iterator_range<
boost::range_detail::
join_iterator<int*, int*, int, int&,
boost::random_access_traversal_tag> > ci = boost::join(ai, bi);
BOOST_FOREACH(int& i, ci) {
std::cout << i; //prints 12347234
}
}
```
I found the output type using the compiler messages. C++0x `auto` will be relevant there as well.
|
* Can't you call the function twice, once for both ranges? Or are there problems with this approach?
* Copy the two ranges into one container and pass that.
* Write your own range class, so it iterates through r1 first and and through r2 second.
|
Boost Range Library: Traversing Two Ranges Sequentially
|
[
"",
"c++",
""
] |
I need to find occurrences of ~ 25 000 words within a text. What is the most suitable algorithm/library for this purpose?
target language is C++
|
build a hashtable with the words, and scan throuhgt the text, for each word lookup in the wordtable and stuff the needed info (increment count, add to a position list, whatever).
|
> I once used the Boyer-Moore algorithm and it was quite fast.
Boyer-Moore isn't apt for efficiently searching many words. There is actually a very efficient algorithm for doing just that, called the Wu-Manber algorithm. I'll post a reference implementation. Notice, however, that I did this some time ago for educational purpose only. Hence, the implementation isn't really apt for direct usage and can also be made more efficient.
It also uses the `stdext::hash_map` from the Dinkumware STL. Subsitute with `std::tr1::unordered_map` or an appropriate implementation.
There's an explanation of the algorithm in a [lecture script](http://www.inf.fu-berlin.de/inst/ag-bio/FILES/ROOT/Teaching/Lectures/SS08//ssa/script-02-HorspoolWuManber.pdf) from a lecture at the Freie Universität Berlin, held by Knut Reinert.
The [original paper](http://webglimpse.net/pubs/TR94-17.pdf) is also online (just found it again) but I don't particularly like the pseudocode presented there.
```
#ifndef FINDER_HPP
#define FINDER_HPP
#include <string>
namespace thru { namespace matching {
class Finder {
public:
virtual bool find() = 0;
virtual std::size_t position() const = 0;
virtual ~Finder() = 0;
protected:
static size_t code_from_chr(char c) {
return static_cast<size_t>(static_cast<unsigned char>(c));
}
};
inline Finder::~Finder() { }
} } // namespace thru::matching
#endif // !defined(FINDER_HPP)
```
---
```
#include <vector>
#include <hash_map>
#include "finder.hpp"
#ifndef WUMANBER_HPP
#define WUMANBER_HPP
namespace thru { namespace matching {
class WuManberFinder : public Finder {
public:
WuManberFinder(std::string const& text, std::vector<std::string> const& patterns);
bool find();
std::size_t position() const;
std::size_t pattern_index() const;
private:
template <typename K, typename V>
struct HashMap {
typedef stdext::hash_map<K, V> Type;
};
typedef HashMap<std::string, std::size_t>::Type shift_type;
typedef HashMap<std::string, std::vector<std::size_t> >::Type hash_type;
std::string const& m_text;
std::vector<std::string> const& m_patterns;
shift_type m_shift;
hash_type m_hash;
std::size_t m_pos;
std::size_t m_find_pos;
std::size_t m_find_pattern_index;
std::size_t m_lmin;
std::size_t m_lmax;
std::size_t m_B;
};
} } // namespace thru::matching
#endif // !defined(WUMANBER_HPP)
```
---
```
#include <cmath>
#include <iostream>
#include "wumanber.hpp"
using namespace std;
namespace thru { namespace matching {
WuManberFinder::WuManberFinder(string const& text, vector<string> const& patterns)
: m_text(text)
, m_patterns(patterns)
, m_shift()
, m_hash()
, m_pos()
, m_find_pos(0)
, m_find_pattern_index(0)
, m_lmin(m_patterns[0].size())
, m_lmax(m_patterns[0].size())
, m_B()
{
for (size_t i = 0; i < m_patterns.size(); ++i) {
if (m_patterns[i].size() < m_lmin)
m_lmin = m_patterns[i].size();
else if (m_patterns[i].size() > m_lmax)
m_lmax = m_patterns[i].size();
}
m_pos = m_lmin;
m_B = static_cast<size_t>(ceil(log(2.0 * m_lmin * m_patterns.size()) / log(256.0)));
for (size_t i = 0; i < m_patterns.size(); ++i)
m_hash[m_patterns[i].substr(m_patterns[i].size() - m_B)].push_back(i);
for (size_t i = 0; i < m_patterns.size(); ++i) {
for (size_t j = 0; j < m_patterns[i].size() - m_B + 1; ++j) {
string bgram = m_patterns[i].substr(j, m_B);
size_t pos = m_patterns[i].size() - j - m_B;
shift_type::iterator old = m_shift.find(bgram);
if (old == m_shift.end())
m_shift[bgram] = pos;
else
old->second = min(old->second, pos);
}
}
}
bool WuManberFinder::find() {
while (m_pos <= m_text.size()) {
string bgram = m_text.substr(m_pos - m_B, m_B);
shift_type::iterator i = m_shift.find(bgram);
if (i == m_shift.end())
m_pos += m_lmin - m_B + 1;
else {
if (i->second == 0) {
vector<size_t>& list = m_hash[bgram];
// Verify all patterns in list against the text.
++m_pos;
for (size_t j = 0; j < list.size(); ++j) {
string const& str = m_patterns[list[j]];
m_find_pos = m_pos - str.size() - 1;
size_t k = 0;
for (; k < str.size(); ++k)
if (str[k] != m_text[m_find_pos + k])
break;
if (k == str.size()) {
m_find_pattern_index = list[j];
return true;
}
}
}
else
m_pos += i->second;
}
}
return false;
}
size_t WuManberFinder::position() const {
return m_find_pos;
}
size_t WuManberFinder::pattern_index() const {
return m_find_pattern_index;
}
} } // namespace thru::matching
```
### Example of usage:
```
vector<string> patterns;
patterns.push_back("announce");
patterns.push_back("annual");
patterns.push_back("annually");
WuManberFinder wmf("CPM_annual_conference_announce", patterns);
while (wmf.find())
cout << "Pattern \"" << patterns[wmf.pattern_index()] <<
"\" found at position " << wmf.position() << endl;
```
|
search 25 000 words within a text
|
[
"",
"c++",
"full-text-search",
""
] |
Is there a standard idiom for comparing version numbers? I can't just use a straight String compareTo because I don't know yet what the maximum number of point releases there will be. I need to compare the versions and have the following hold true:
```
1.0 < 1.1
1.0.1 < 1.1
1.9 < 1.10
```
|
Tokenize the strings with the dot as delimiter and then compare the integer translation side by side, beginning from the left.
|
Another solution for this old post (for those that it might help) :
```
public class Version implements Comparable<Version> {
private String version;
public final String get() {
return this.version;
}
public Version(String version) {
if(version == null)
throw new IllegalArgumentException("Version can not be null");
if(!version.matches("[0-9]+(\\.[0-9]+)*"))
throw new IllegalArgumentException("Invalid version format");
this.version = version;
}
@Override public int compareTo(Version that) {
if(that == null)
return 1;
String[] thisParts = this.get().split("\\.");
String[] thatParts = that.get().split("\\.");
int length = Math.max(thisParts.length, thatParts.length);
for(int i = 0; i < length; i++) {
int thisPart = i < thisParts.length ?
Integer.parseInt(thisParts[i]) : 0;
int thatPart = i < thatParts.length ?
Integer.parseInt(thatParts[i]) : 0;
if(thisPart < thatPart)
return -1;
if(thisPart > thatPart)
return 1;
}
return 0;
}
@Override public boolean equals(Object that) {
if(this == that)
return true;
if(that == null)
return false;
if(this.getClass() != that.getClass())
return false;
return this.compareTo((Version) that) == 0;
}
}
```
---
```
Version a = new Version("1.1");
Version b = new Version("1.1.1");
a.compareTo(b) // return -1 (a<b)
a.equals(b) // return false
Version a = new Version("2.0");
Version b = new Version("1.9.9");
a.compareTo(b) // return 1 (a>b)
a.equals(b) // return false
Version a = new Version("1.0");
Version b = new Version("1");
a.compareTo(b) // return 0 (a=b)
a.equals(b) // return true
Version a = new Version("1");
Version b = null;
a.compareTo(b) // return 1 (a>b)
a.equals(b) // return false
List<Version> versions = new ArrayList<Version>();
versions.add(new Version("2"));
versions.add(new Version("1.0.5"));
versions.add(new Version("1.01.0"));
versions.add(new Version("1.00.1"));
Collections.min(versions).get() // return min version
Collections.max(versions).get() // return max version
// WARNING
Version a = new Version("2.06");
Version b = new Version("2.060");
a.equals(b) // return false
```
---
Edit:
@daiscog: Thank you for your remark, this piece of code has been developed for the Android platform and as recommended by Google, the method "matches" check the entire string unlike Java that uses a regulatory pattern. ([Android documentation](http://developer.android.com/reference/java/lang/String.html#matches%28java.lang.String%29) - [JAVA documentation](http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#matches%28java.lang.String%29))
|
How do you compare two version Strings in Java?
|
[
"",
"java",
"comparison",
"versioning",
""
] |
Is there an efficient way of detecting if a jpeg file is corrupted?
Background info:
solutions needs to work from within a php script
the jpeg files are on disk
manual checking is no option (user uploaded data)
I know that `imagecreatefromjpeg(string $filename);` can do it. But it is quite slow at doing so.
Does anybody know a faster/more efficient solutions?
|
From the command line you can use jpeginfo to find out if a jpeg file is OK or not.
> $ jpeginfo -c test.jpeg
>
> test.jpeg 260 x 264 24bit JFIF N 15332 [OK]
It should be trivial to call jpeginfo from php.
|
My simplest (and fastest) solution:
```
function jpeg_file_is_complete($path) {
if (!is_resource($file = fopen($path, 'rb'))) {
return FALSE;
}
// check for the existence of the EOI segment header at the end of the file
if (0 !== fseek($file, -2, SEEK_END) || "\xFF\xD9" !== fread($file, 2)) {
fclose($file);
return FALSE;
}
fclose($file);
return TRUE;
}
function jpeg_file_is_corrupted($path) {
return !jpeg_file_is_complete($path);
}
```
Note: This only detects a corrupted file structure, but does NOT detect corrupted image data.
|
Efficiently detect corrupted jpeg file?
|
[
"",
"php",
"jpeg",
"corruption",
""
] |
How have you used the Exception.Data property in C# projects that you've worked on?
I'd like answers that suggest a pattern, rather than those that are very specific to your app.
|
The exception logger I use has been tweaked to write out all the items in the Data collection. Then for every exception we encounter that we cannot diagnose from the exception stack, we add in all the data in that function's scope, send out a new build, and wait for it to reoccur.
I guess we're optimists in that we don't put it in every function, but we are pessimists in that we don't take it out once we fix the issue.
|
Since none of the answers include any code. Something that might useful as an addition to this question is how to actually look at the `.Data` dictionary. Since it is not a generic dictionary and only returns `IDictionary`
`foreach(var kvp in exception.Data)` the type of kvp will actually be `object` unhelpfully. However from the [MSDN](https://learn.microsoft.com/en-us/dotnet/api/system.exception.data) there's an easy way to iterate this dictionary:
```
foreach (DictionaryEntry de in e.Data)
Console.WriteLine(" Key: {0,-20} Value: {1}",
"'" + de.Key.ToString() + "'", de.Value);
```
I don't really know what the format argument `, -20` would mean, maybe Take(20)? Digressing... this code can be very helpful in a common error logger to unwind this data. A more complete usage would be similar to:
```
var messageBuilder = new StringBuilder();
do
{
foreach (DictionaryEntry kvp in exception.Data)
messageBuilder.AppendFormat("{0} : {1}\n", kvp.Key, kvp.Value);
messageBuilder.AppendLine(exception.Message);
} while ((exception = exception.InnerException) != null);
return messageBuilder.ToString();
```
|
Using Exception.Data
|
[
"",
"c#",
"exception",
""
] |
<http://developer.yahoo.com/javascript/howto-proxy.html>
Are there disadvantages to this technique? The advantage is obvious, that you can use a proxy to get XML or JavaScript on another domain with XMLHttpRequest without running into same-origin restrictions. However, I do not hear about disadvantages over other methods -- are there, and what might they be?
|
Overhead - things are going to be a bit slower because you're going through an intermediary.
There are security issues if you allow access to any external site via the proxy - be sure to lock it down to the specific site (and probably specific URL) of the resource you're proxying.
|
Overhead -- both for the user (who know hsa to wait for you server to make and receive data from the proxied source) and you (as you're now taking on all the traffic for the other server in addition to your own).
Also security concerns -- if you are using a proxy to bypass browser security checks for displaying untrusted content, you are deliberately sabotaging the browser security model -- potentially allowing the user to be compromised -- so unless you absolutely trust the server you are communicating with (that means no random ads, no user defined content in the page[s] you are proxying) you should not do this.
|
What are the disadvantages to using a PHP proxy to bypass the same-origin policy for XMLHttpRequest?
|
[
"",
"javascript",
"security",
"xmlhttprequest",
""
] |
I have the following code fragment that starts a [Google Earth](http://en.wikipedia.org/wiki/Google_Earth) process using a hardcoded path:
```
var process =
new Process
{
StartInfo =
{
//TODO: Get location of google earth executable from registry
FileName = @"C:\Program Files\Google\Google Earth\googleearth.exe",
Arguments = "\"" + kmlPath + "\""
}
};
process.Start();
```
I want to programmatically fetch the installation location of *googleearth.exe* from somewhere (most likely the registry).
|
Obviously if you're opening a specific file associated with the program then launching it via the file is preferable (for instance, the user might have a program associated with the file type they prefer to use).
Here is a method I've used in the past to launch an application associated with a particular file type, but without actually opening a file. There may be a better way to do it.
```
static Regex pathArgumentsRegex = new Regex(@"(%\d+)|(""%\d+"")", RegexOptions.ExplicitCapture);
static string GetPathAssociatedWithFileExtension(string extension)
{
RegistryKey extensionKey = Registry.ClassesRoot.OpenSubKey(extension);
if (extensionKey != null)
{
object applicationName = extensionKey.GetValue(string.Empty);
if (applicationName != null)
{
RegistryKey commandKey = Registry.ClassesRoot.OpenSubKey(applicationName.ToString() + @"\shell\open\command");
if (commandKey != null)
{
object command = commandKey.GetValue(string.Empty);
if (command != null)
{
return pathArgumentsRegex.Replace(command.ToString(), "");
}
}
}
}
return null;
}
```
Sometimes though there are cases when you want to launch a specific program without opening a file. Usually (hopefully) the program has a registry entry with the install location. Here is an example of how to launch Google Earth in such a manner.
```
private static string GetGoogleEarthExePath()
{
RegistryKey googleEarthRK = Registry.CurrentUser.OpenSubKey(@"Software\Google\Google Earth Plus\");
if (googleEarthRK != null)
{
object rootDir = googleEarthRK.GetValue("InstallLocation");
if (rootDir != null)
{
return Path.Combine(rootDir.ToString(), "googleearth.exe");
}
}
return null;
}
```
|
From the example given you can gauge that I'm actually trying to pass a KML file to Google Earth. Because of this, the simplest way of resolving this problem is relying on the file association of KML with Google Earth and using the following as a replacement for the entire example:
```
Process.Start(kmlPath);
```
This was found by reviewing the answers to [this](https://stackoverflow.com/questions/181719/how-to-start-a-process-from-c-winforms) question.
|
How to find the installation directory of a third-party application, such as Google Earth, using C#?
|
[
"",
"c#",
"google-earth",
""
] |
I have implemented a python webserver. Each http request spawns a new thread.
I have a requirement of caching objects in memory and since its a webserver, I want the cache to be thread safe. Is there a standard implementatin of a thread safe object cache in python? I found the following
<http://freshmeat.net/projects/lrucache/>
This does not look to be thread safe. Can anybody point me to a good implementation of thread safe cache in python?
Thanks!
|
Well a lot of operations in Python are thread-safe by default, so a standard dictionary should be ok (at least in certain respects). This is mostly due to the GIL, which will help avoid some of the more serious threading issues.
There's a list here: <http://coreygoldberg.blogspot.com/2008/09/python-thread-synchronization-and.html> that might be useful.
Though atomic nature of those operation just means that you won't have an entirely inconsistent state if you have two threads accessing a dictionary at the same time. So you wouldn't have a corrupted value. However you would (as with most multi-threading programming) not be able to rely on the specific order of those atomic operations.
So to cut a long story short...
If you have fairly simple requirements and aren't to bothered about the ordering of what get written into the cache then you can use a dictionary and know that you'll always get a consistent/not-corrupted value (it just might be out of date).
If you want to ensure that things are a bit more consistent with regard to reading and writing then you might want to look at Django's local memory cache:
<http://code.djangoproject.com/browser/django/trunk/django/core/cache/backends/locmem.py>
Which uses a read/write lock for locking.
|
Thread per request is often a bad idea. If your server experiences huge spikes in load it will take the box to its knees. Consider using a thread pool that can grow to a limited size during peak usage and shrink to a smaller size when load is light.
|
python threadsafe object cache
|
[
"",
"python",
"multithreading",
"caching",
""
] |
I want to record user states and then be able to report historically based on the record of changes we've kept. I'm trying to do this in SQL (using PostgreSQL) and I have a proposed structure for recording user changes like the following.
```
CREATE TABLE users (
userid SERIAL NOT NULL PRIMARY KEY,
name VARCHAR(40),
status CHAR NOT NULL
);
CREATE TABLE status_log (
logid SERIAL,
userid INTEGER NOT NULL REFERENCES users(userid),
status CHAR NOT NULL,
logcreated TIMESTAMP
);
```
That's my proposed table structure, based on the data.
For the status field 'a' represents an active user and 's' represents a suspended user,
```
INSERT INTO status_log (userid, status, logcreated) VALUES (1, 's', '2008-01-01');
INSERT INTO status_log (userid, status, logcreated) VALUES (1, 'a', '2008-02-01');
```
So this user was suspended on 1st Jan and active again on 1st of February.
If I wanted to get a suspended list of customers on 15th January 2008, then userid 1 should show up. If I get a suspended list of customers on 15th February 2008, then userid 1 should not show up.
1) Is this the best way to structure this data for this kind of query?
2) How do I query the data in either this structure or in your proposed modified structure so that I can simply have a date (say 15th January) and find a list of customers that had an active status on that date in SQL only? Is this a job for SQL?
|
This can be done, but would be a lot more efficient if you stored the end date of each log. With your model you have to do something like:
```
select l1.userid
from status_log l1
where l1.status='s'
and l1.logcreated = (select max(l2.logcreated)
from status_log l2
where l2.userid = l1.userid
and l2.logcreated <= date '2008-02-15'
);
```
With the additional column it woud be more like:
```
select userid
from status_log
where status='s'
and logcreated <= date '2008-02-15'
and logsuperseded >= date '2008-02-15';
```
(Apologies for any syntax errors, I don't know Postgresql.)
To address some further issues raised by Phil:
> A user might get moved from active, to suspended, to cancelled, to active again. This is a simplified version, in reality, there are even more states and people can be moved directly from one state to another.
This would appear in the table like this:
```
userid from to status
FRED 2008-01-01 2008-01-31 s
FRED 2008-02-01 2008-02-07 c
FRED 2008-02-08 a
```
I used a null for the "to" date of the current record. I could have used a future date like 2999-12-31 but null is preferable in some ways.
> Additionally, there would be no "end date" for the current status either, so I think this slightly breaks your query?
Yes, my query would have to be re-written as
```
select userid
from status_log
where status='s'
and logcreated <= date '2008-02-15'
and (logsuperseded is null or logsuperseded >= date '2008-02-15');
```
A downside of this design is that whenever the user's status changes you have to end date their current status\_log as well as create a new one. However, that isn't difficult, and I think the query advantage probably outweighs this.
|
Does Postgres support analytic queries? This would give the active users on 2008-02-15
```
select userid
from
(
select logid,
userid,
status,
logcreated,
max(logcreated) over (partition by userid) max_logcreated_by_user
from status_log
where logcreated <= date '2008-02-15'
)
where logcreated = max_logcreated_by_user
and status = 'a'
/
```
|
SQL - state machine - reporting on historical data based on changeset
|
[
"",
"sql",
"postgresql",
""
] |
HTML (or maybe just XHTML?) is relatively strict when it comes to non-standard attributes on tags. If they aren't part of the spec, then your code is considered non-compliant.
Non-standard attributes can be fairly useful for passing along meta-data to Javascript however. For instance, if a link is suppose to show a popup, you can set the name of the popup in an attribute:
```
<a href="#null" class="popup" title="See the Popup!"
popup_title="Title for My Popup">click me</a>
```
Alternatively, you can store the title for the popup in a hidden element, like a span:
```
<style>
.popup .title { display: none; }
</style>
<a href="#null" title="See the Popup!" class="popup">
click me
<span class="title">Title for My Popup</span>
</a>
```
I am torn however as to which should be a preferred method. The first method is more concise and, I'm guessing, doesn't screw with search engines and screen readers as much. Conversely, the second option makes storing large amounts of data easier and is thus, more versatile. It is also standards compliant.
I am curious what this communities thoughts are. How do you handle a situation like this? Does the simplicity of the first method outweigh the potential downsides (if there are any)?
|
I am a big fan of the proposed HTML 5 solution (`data-` prefixed attributes). Edit: I'd add that there are probably better examples for the use of custom attributes. For instance, data that a custom application will use that have no analogue in standard attributes (eg. customization for event handlers based on something that can't necessarily be expressed in a className or id).
|
Custom attributes provide a convenient way to carry extra data to the client side. Dojo Toolkit is doing this regularly and it has been pointed ([Debunking Dojo Toolkit Myths](http://www.sitepen.com/blog/2008/10/27/debunking-dojo-toolkit-myths/)) out that:
> Custom attributes have always been
> valid HTML, they just don’t validate
> when tested against a DTD. [...] The
> HTML specification states that any
> attribute not recognized is to be
> ignored by the HTML rendering engine
> in user agents, and Dojo optionally
> takes advantage of this to improve
> ease of development.
|
Non-Standard Attributes on HTML Tags. Good Thing? Bad Thing? Your Thoughts?
|
[
"",
"javascript",
"html",
"standards",
""
] |
I have a client who is still using Visual Studio 6 for building production systems. They write multi-threaded systems that use STL and run on mutli-processor machines.
Occasionally when they change the spec of or increase the load on one of their server machines they get 'weird' difficult to reproduce errors...
I know that there are several issues with Visual Studio 6 development and I'd like to convince them to move to Visual Stuio 2005 or 2008 (they have Visual Studio 2005 and use it for some projects).
The purpose of this question is to put together a list of known issues or reasons to upgrade along with links to where these issues are discussed or reported. It would also be useful to have real life 'horror stories' of how these issues have bitten you.
|
Not supported on 64-bit systems, compatibility issues with Vista, and it was moved out of extended support by Microsoft on April 8, 2008
<http://msdn.microsoft.com/en-us/vbrun/ms788708.aspx>
|
Unpatched VC6 STL is not thread safe. See here [<http://www.amanjit-gill.de/articles/vc6_stl.html>](http://www.amanjit-gill.de/articles/vc6_stl.html), the patches aren't included in the service packs and you have to get them from Dinkumware directly (from here [<http://www.dinkumware.com/vc_fixes.html>](http://web.archive.org/web/20081222115435/http://www.dinkumware.com/vc_fixes.html)) and then apply them to each installation...
|
What are some convincing arguments to upgrade from Visual Studio 6?
|
[
"",
"c++",
"visual-studio",
"visual-c++",
"stl",
"visual-c++-6",
""
] |
Is there a maximum length when using window.returnValue (variant) in a modal?
I am calling a modal window using showModalDialog() and returning a comma delimited string. After selecting a group of users, I am putting them into a stringbuilder to display in a literal.
```
Dim strReturn As New StringBuilder
strReturn.Append("<script type=""text/javascript"">window.returnValue='")
Dim strUsers As New StringBuilder
For Each dtRow As DataRow In GetSelectedUserTable.Rows
If strUsers.ToString.Length > 0 Then
strUsers.Append(",")
End If
strUsers.Append(dtRow("UserID"))
Next
strReturn.Append(strUsers.ToString)
strReturn.Append("';window.close();</script>")
litReturnJavascript.Text = strReturn.ToString
```
So would there be a limit on how many characters can be added to the window.returnValue?
|
First, in what browser are you having problems? `window.returnValue` isn't even supported in Firefox, maybe not even other browsers.
Second, have you looked the value of `strUsers` after building it to make sure there are no single or double quotes in that string?
I would guess that the maximum size/length of that property would be determined more by your system's memory than anything else.
---
EDIT: Maybe you should look at using `window.open()` to open a new window and `window.opener` to set the value on the parent form instead - it is supported by more browsers. Just a suggestion...
|
JasonBunting has a good suggestion. You can have the modal dialog update the parent before you close it. This way you can pass objects back and forth between your windows without worrying about the limitation of the return value. For example, you could have a hidden field on the parent that you update with your return values.
|
What is the maximum length allowed for window.returnValue property? (JavaScript)
|
[
"",
"asp.net",
"javascript",
"vb.net",
""
] |
Before you answer, this question is complicated:
1. We are developing in asp.net / asp.net mvc / jQuery but I'm open to solutions on any platform using any framework
2. I think logic like sorting / hiding columns / re-arranging columns / validation (where it makes sense) should be on the client-side
3. I think logic like searching / updating the db / running workflows should be on the server side (just because of security / debugging reasons)
What we are trying to do is **NOT CREATE A MESS** in our UI by writing a bunch of JavaScript to deal with the same feature in different contexts. I understand that I can use a JavaScript file + object oriented JavaScript, I'm looking for the pattern that makes it all easier.
One solution proposed was to have an MVC model on both the client and server side, where we can encapsulate JavaScript functionality in client side controllers, then use them in different parts of the site. However, this means that we have 2 MVC implementations!
Is this overkill? How would you expand on this solution? What other solutions are there?
|
On two; you should always have server side validation as well as client side validation
On three; if you can find a way to manipulate the DB on the client side that would be impressive ;)
I don't know how ASP.net works though, so I am solely speaking from my PHP experience.
I would write controls that are paired by server and client code. Each control needs a form, client side logic and server side logic. The form is written out by your templating engine, the client side logic is attached to the form and written in JS and the server side logic is a controller/action pair somewhere that manipulates the model. Clearly, you would not want to couple your client side logic to a specific action/controller, so be sure to define an interface that can be used to talk to your control instead...
Then for each form I would write a class in javascript that instances your controls. For example; you may have a control:
```
{include file = "list_view.php" id = "ListView1" data = $Data.List}
```
which would print your form out. Then in your page controller class:
```
this.ListView1 = new ListViewController({id : "ListView1", serverCtrl : "Users"});
```
Now you can use "this.ListView1" to manipulate the list view. The list view controller does stuff like makes AJAX queries for new pages if the use presses the next page button - and also handles columns and sorting (which will also delegate to the server).
|
I just googled this so take it with a grain of salt. [JavascriptMVC](http://javascriptmvc.com/) claims to be a MVC framework. Again, I have no experience with it but it may be worth a look.
|
Separating client side logic from server side logic in a reusable way using MVC
|
[
"",
"javascript",
"asp.net-mvc",
"model-view-controller",
""
] |
I need to do a comparaison between an object and NULL. When the object is not NULL I fill it with some data.
Here is the code :
```
if (region != null)
{
....
}
```
This is working but when looping and looping sometime the region object is NOT null (I can see data inside it in debug mode). In step-by-step when debugging, it doesn't go inside the IF statement... When I do a Quick Watch with these following expression : I see the (region == null) return false, AND (region != null) return false too... **why and how?**
**Update**
Someone point out that the object was == and != overloaded:
```
public static bool operator ==(Region r1, Region r2)
{
if (object.ReferenceEquals(r1, null))
{
return false;
}
if (object.ReferenceEquals(r2, null))
{
return false;
}
return (r1.Cmr.CompareTo(r2.Cmr) == 0 && r1.Id == r2.Id);
}
public static bool operator !=(Region r1, Region r2)
{
if (object.ReferenceEquals(r1, null))
{
return false;
}
if (object.ReferenceEquals(r2, null))
{
return false;
}
return (r1.Cmr.CompareTo(r2.Cmr) != 0 || r1.Id != r2.Id);
}
```
|
Is the == and/or != operator overloaded for the region object's class?
Now that you've posted the code for the overloads:
The overloads should probably look like the following (code taken from postings made by [Jon Skeet](https://stackoverflow.com/questions/155458/c-object-is-not-null-but-myobject-null-still-return-false#155488) and [Philip Rieck](https://stackoverflow.com/questions/155458/c-object-is-not-null-but-myobject-null-still-return-false#155508)):
```
public static bool operator ==(Region r1, Region r2)
{
if (object.ReferenceEquals( r1, r2)) {
// handles if both are null as well as object identity
return true;
}
if ((object)r1 == null || (object)r2 == null)
{
return false;
}
return (r1.Cmr.CompareTo(r2.Cmr) == 0 && r1.Id == r2.Id);
}
public static bool operator !=(Region r1, Region r2)
{
return !(r1 == r2);
}
```
|
Those operator overloads are broken.
Firstly, it makes life a lot easier if != is implemented by just calling == and inverting the result.
Secondly, before the nullity checks in == there should be:
```
if (object.ReferenceEquals(r1, r2))
{
return true;
}
```
|
C# object is not null but (myObject != null) still return false
|
[
"",
"c#",
"null",
"compare",
""
] |
I'm working on trying to generate a report from a couple of database tables. The simplified version looks like this
```
Campaign
----------
CampaignID
Source
-----------------------
Source_ID | Campaign_ID
Content
---------------------------------------------------------
Content_ID | Campaign_ID | Content_Row_ID | Content_Value
```
The report needs to read like this:
```
CampaignID - SourceID - ContentRowID(Value(A)) - ContentRowID(Value(B))
```
Where ContentRowID(Value(A)) means "Find a row the has a given CampaignID, and a ContentRowId of "A" and then get the ContentValue for that row"
Essentially, I have to "pivot" (I think that's the correct term) the rows into columns...
It's an Oracle 10g database...
Any suggestions?
|
This is my first stab at it. Refinement coming once I know more about the contents of the Content table.
First, you need a temporary table:
```
CREATE TABLE pivot (count integer);
INSERT INTO pivot VALUES (1);
INSERT INTO pivot VALUES (2);
```
Now we're ready to query.
```
SELECT campaignid, sourceid, a.contentvalue, b.contentvalue
FROM content a, content b, pivot, source
WHERE source.campaignid = content.campaignid
AND pivot = 1 AND a.contentrowid = 'A'
AND pivot = 2 AND b.contentrowid = 'B'
```
|
Bill Karwin mentions this, but I think this deserves to be pointed out very clearly:
**SQL doesn't do what you're asking for, so any "solution" you get is going to be a kludge.**
If you *know*, for sure, it's always going to run on an Oracle 10, then sure, Walter Mitty's crosstabulation might do it. The right way to do it is to work the easiest combination of sort order in the query and application code to lay it out right.
* It works on other database systems,
* it doesn't risk any other layers crapping out (I remember MySQL having a problem with >255 columns for instance. Are you sure you *interface library* copes as well as the db itself?)
* it's (usually) not that much harder.
If you need to, you can just ask for the `Content_Row_ID`s first, then ask for whatever rows you need, ordered by `CampaignID`, `ContentRowID`, which would give you each (populated) cell in left-to-right, line-by-line order.
---
Ps.
There are a bunch of stuff that modern man thinks SQL should have/do that just isn't there. This is one, generated ranges is another, recursive closure, parametric `ORDER BY`, standardised programming language... the list goes on. (though, admittedly, there's a trick for `ORDER BY`)
|
"Pivoting" a Table in SQL (i.e. Cross tabulation / crosstabulation)
|
[
"",
"sql",
"database",
"oracle",
"pivot",
""
] |
How can I bring a console application window to front in C# (especially when running the Visual Studio debugger)?
|
It's hacky, it's horrible, but it works for me (thanks, [pinvoke.net](http://pinvoke.net/)!):
```
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
public class Test
{
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll", EntryPoint="FindWindow", SetLastError = true)]
static extern IntPtr FindWindowByCaption(IntPtr zeroOnly, string lpWindowName);
public static void Main()
{
string originalTitle = Console.Title;
string uniqueTitle = Guid.NewGuid().ToString();
Console.Title = uniqueTitle;
Thread.Sleep(50);
IntPtr handle = FindWindowByCaption(IntPtr.Zero, uniqueTitle);
if (handle == IntPtr.Zero)
{
Console.WriteLine("Oops, cant find main window.");
return;
}
Console.Title = originalTitle;
while (true)
{
Thread.Sleep(3000);
Console.WriteLine(SetForegroundWindow(handle));
}
}
}
```
|
This is what I would do.
```
[DllImport("kernel32.dll", ExactSpelling = true)]
public static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetForegroundWindow(IntPtr hWnd);
public void BringConsoleToFront()
{
SetForegroundWindow(GetConsoleWindow());
}
```
|
bring a console window to front in c#
|
[
"",
"c#",
"console",
"window",
""
] |
I am looking for a python webserver which is multithreaded instead of being multi-process (as in case of mod\_python for apache). I want it to be multithreaded because I want to have an in memory object cache that will be used by various http threads. My webserver does a lot of expensive stuff and computes some large arrays which needs to be cached in memory for future use to avoid recomputing. This is not possible in a multi-process web server environment. Storing this information in memcache is also not a good idea as the arrays are large and storing them in memcache would lead to deserialization of data coming from memcache apart from the additional overhead of IPC.
I implemented a simple webserver using BaseHttpServer, it gives good performance but it gets stuck after a few hours time. I need some more matured webserver. Is it possible to configure apache to use mod\_python under a thread model so that I can do some object caching?
|
[CherryPy](http://cherrypy.org/). Features, as listed from the website:
* A fast, HTTP/1.1-compliant, WSGI thread-pooled webserver. Typically, CherryPy itself takes only 1-2ms per page!
* Support for any other WSGI-enabled webserver or adapter, including Apache, IIS, lighttpd, mod\_python, FastCGI, SCGI, and mod\_wsgi
* Easy to run multiple HTTP servers (e.g. on multiple ports) at once
* A powerful configuration system for developers and deployers alike
* A flexible plugin system
* Built-in tools for caching, encoding, sessions, authorization, static content, and many more
* A native mod\_python adapter
* A complete test suite
* Swappable and customizable...everything.
* Built-in profiling, coverage, and testing support.
|
Consider reconsidering your design. Maintaining that much state in your webserver is probably a bad idea. Multi-process is a much better way to go for stability.
Is there another way to share state between separate processes? What about a service? Database? Index?
It seems unlikely that maintaining a huge array of data in memory and relying on a single multi-threaded process to serve all your requests is the best design or architecture for your app.
|
A good multithreaded python webserver?
|
[
"",
"python",
"apache",
"webserver",
"mod-python",
""
] |
I have a CSV file that holds about 200,000 - 300,000 records. Most of the records can be separated and inserted into a MySQL database with a simple
```
$line = explode("\n", $fileData);
```
and then the values separated with
```
$lineValues = explode(',', $line);
```
and then inserted into the database using the proper data type i.e int, float, string, text, etc.
However, some of the records have a text column that includes a \n in the string. Which breaks when using the $line = explode("\n", $fileData); method. Each line of data that needs to be inserted into the database has approximately 216 columns. not every line has a record with a \n in the string. However, each time a \n is found in the line it is enclosed between a pair of single quotes (')
each line is set up in the following format:
```
id,data,data,data,text,more data
```
example:
```
1,0,0,0,'Hello World,0
2,0,0,0,'Hello
World',0
3,0,0,0,'Hi',0
4,0,0,0,,0
```
As you can see from the example, most records can be easily split with the methods shown above. Its the second record in the example that causes the problem.
New lines are only \n and the file does not include \r in the file at all.
|
If the csv data is in a file, you can just use fgetcsv() as others have pointed out.
fgetcsv handles embedded newlines correctly.
However if your csv data is in a string (like $fileData in your example) the following method may be useful as str\_getcsv() only works on a row at a time and cannot split a whole file into records.
You can detect the embedded newlines by counting the quotes in each line. If there are an odd number of quotes, you have an incomplete line, so concatenate this line with the following line. Once you have an even number of quotes, you have a complete record.
Once you have a complete record, split it at the quotes (again using explode()). Odd-numbered fields are quoted (thus embedded commas are not special), even-numbered fields are not.
Example:
```
# Split file into physical lines (records may span lines)
$lines = explode("\n", $fileData);
# Re-assemble records
$records = array ();
$record = '';
$lineSep = '';
foreach ($lines as $line) {
# Escape @ symbol so we can use it as a marker (as it does not conflict with
# any special CSV character.)
$line = str_replace('@', '@a', $line);
# Escape commas as we don't yet know which ones are separators
$line = str_replace(',', '@c', $line);
# Escape quotes in a form that uses no special characters
$line = str_replace("\\'", '@q', $line);
$line = str_replace('\\', '@b', $line);
$record .= $lineSep . $line;
$lineSep = "\n";
# Must have an even number of quotes in a complete record!
if (substr_count($record, "'") % 2 == 0) {
$records[] = $record;
$record = '';
$lineSep = '';
}
}
if (strlen($record) > 0) {
$records[] = $record;
}
$rows = array ();
foreach ($records as $record) {
$chunks_in = explode("'", $record);
$chunks_out = array ();
# Decode escaped quotes/backslashes.
# Decode field-separating commas (unless quoted)
foreach ($chunks_in as $i => $chunk) {
# Unescape quotes & backslashes
$chunk = str_replace('@q', "'", $chunk);
$chunk = str_replace('@b', '\\', $chunk);
if ($i % 2 == 0) {
# Unescape commas
$chunk = str_replace('@c', ',', $chunk);
}
$chunks_out[] = $chunk;
}
# Join back together, discarding unescaped quotes
$record = join('', $chunks_out);
$chunks_in = explode(',', $record);
$row = array ();
foreach ($chunks_in as $chunk) {
$chunk = str_replace('@c', ',', $chunk);
$chunk = str_replace('@a', '@', $chunk);
$row[] = $chunk;
}
$rows[] = $row;
}
```
|
The other advice here is, of course, valid, especially if you aim to write your own CSV parser, however, if you just want to get the data out, use [fgetcsv()](http://php.net/fgetcsv) function and don't worry about implementation details.
|
Replacing or Removing a new line with something else but only between single or double quotes using PHP on a CSV file
|
[
"",
"php",
"csv",
""
] |
I'm trying to save some XML-Data in my UserSettings (Properties.Settings.Default.UserSettings) in a .NET Winforms Project. Is there a Possibility to do that or would it be better to save this Data in a seperated File?
Thanks for your Answers!
|
You can store an XML document's string representation in a setting of type String. To save the document, load it into an XmlDocument and set the setting to the value of the XmlDocument.OuterXml property. To retrieve it, create a new XmlDocument and use its LoadXml method to parse the string into an XML document.
This is usually a bad idea. Not because there's anything intrinsically wrong with storing an XML document as text within another XML document -- there isn't. But most settings that you access through the UserSettings property are single values. You're introducing a mode of operation where a single setting can now contain an arbitrary number of actual settings. That's not what most people who read your code are going to expect.
As with a lot of things that give code a bad smell, this may be perfectly fine in your specific implementation. I can imagine circumstances in which I'd do it. But in most cases, I wouldn't.
|
In a previous project I had a similar idea but decided to keep the xml files separate.
The xml files can be embedded resources, and their file names can be referenced in the Settings file.
I think this is a cleaner solution.
|
Saving XML-Data in UserSettings
|
[
"",
"c#",
".net",
"xml",
"app-config",
""
] |
I'm trying to call the SQL statement below but get the following error:
> System.Data.SqlClient.SqlException: Conversion failed when converting
> the varchar value '+@buildingIDs+' to data type int.
```
@"SELECT id, startDateTime, endDateTime
FROM tb_bookings
WHERE buildingID IN ('+@buildingIDs+')
AND startDateTime <= @fromDate";
```
`buildingID` is an `int` type column in the db. Will I need to pass the IDs as an array of ints?
|
Bravax's way is a bit dangerous. I'd go with the following so you don't get attacked with SQL Injections:
```
int[] buildingIDs = new int[] { 1, 2, 3 };
/***/ @"SELECT id, startDateTime, endDateTime From tb_bookings WHERE buildingID IN (" +
string.Join(", ", buildingIDs.Select(id => id.ToString()).ToArray())
+ ") AND startDateTime <= @fromDate";
```
|
Note that LINQ can do this via Contains (which maps to IN). With regular TSQL, another option is to pass down the list as a CSV (etc) varchar, and use a table-valued UDF to split the varchar into pieces. This allows you to use a single TSQL query (doing an INNER JOIN to the UDF result).
|
sqlParameter conversion
|
[
"",
".net",
"sql",
"sql-server",
""
] |
What are the basic differences between a semaphore & spin-lock?
When would we use a semaphore over a spin-lock?
|
Spinlock and semaphore differ mainly in four things:
**1. What they are**
A *spinlock* is one possible implementation of a lock, namely one that is implemented by busy waiting ("spinning"). A semaphore is a generalization of a lock (or, the other way around, a lock is a special case of a semaphore). Usually, *but not necessarily*, spinlocks are only valid within one process whereas semaphores can be used to synchronize between different processes, too.
A lock works for mutual exclusion, that is **one** thread at a time can acquire the lock and proceed with a "critical section" of code. Usually, this means code that modifies some data shared by several threads.
A *semaphore* has a counter and will allow itself being acquired by **one or several** threads, depending on what value you post to it, and (in some implementations) depending on what its maximum allowable value is.
Insofar, one can consider a lock a special case of a semaphore with a maximum value of 1.
**2. What they do**
As stated above, a spinlock is a lock, and therefore a mutual exclusion (strictly 1 to 1) mechanism. It works by repeatedly querying and/or modifying a memory location, usually in an atomic manner. This means that acquiring a spinlock is a "busy" operation that possibly burns CPU cycles for a long time (maybe forever!) while it effectively achieves "nothing".
The main incentive for such an approach is the fact that a context switch has an overhead equivalent to spinning a few hundred (or maybe thousand) times, so if a lock can be acquired by burning a few cycles spinning, this may overall very well be more efficient. Also, for realtime applications it may not be acceptable to block and wait for the scheduler to come back to them at some far away time in the future.
A semaphore, by contrast, either does not spin at all, or only spins for a very short time (as an optimization to avoid the syscall overhead). If a semaphore cannot be acquired, it blocks, giving up CPU time to a different thread that is ready to run. This may of course mean that a few milliseconds pass before your thread is scheduled again, but if this is no problem (usually it isn't) then it can be a very efficient, CPU-conservative approach.
**3. How they behave in presence of congestion**
It is a common misconception that spinlocks or lock-free algorithms are "generally faster", or that they are only useful for "very short tasks" (ideally, no synchronization object should be held for longer than absolutely necessary, ever).
The one important difference is how the different approaches behave *in presence of congestion*.
A well-designed system normally has low or no congestion (this means not all threads try to acquire the lock at the exact same time). For example, one would normally *not* write code that acquires a lock, then loads half a megabyte of zip-compressed data from the network, decodes and parses the data, and finally modifies a shared reference (append data to a container, etc.) before releasing the lock. Instead, one would acquire the lock only for the purpose of accessing the *shared resource*.
Since this means that there is considerably more work outside the critical section than inside it, naturally the likelihood for a thread being inside the critical section is relatively low, and thus few threads are contending for the lock at the same time. Of course every now and then two threads will try to acquire the lock at the same time (if this *couldn't* happen you wouldn't need a lock!), but this is rather the exception than the rule in a "healthy" system.
In such a case, a spinlock *greatly* outperforms a semaphore because if there is no lock congestion, the overhead of acquiring the spinlock is a mere dozen cycles as compared to hundreds/thousands of cycles for a context switch or 10-20 million cycles for losing the remainder of a time slice.
On the other hand, given high congestion, or if the lock is being held for lengthy periods (sometimes you just can't help it!), a spinlock will burn insane amounts of CPU cycles for achieving nothing.
A semaphore (or mutex) is a much better choice in this case, as it allows a different thread to run *useful* tasks during that time. Or, if no other thread has something useful to do, it allows the operating system to throttle down the CPU and reduce heat / conserve energy.
Also, on a single-core system, a spinlock will be quite inefficient in presence of lock congestion, as a spinning thread will waste its complete time waiting for a state change that cannot possibly happen (not until the releasing thread is scheduled, which *isn't happening* while the waiting thread is running!). Therefore, given *any* amount of contention, acquiring the lock takes around 1 1/2 time slices in the best case (assuming the releasing thread is the next one being scheduled), which is not very good behaviour.
**4. How they're implemented**
A semaphore will nowadays typically wrap `sys_futex` under Linux (optionally with a spinlock that exits after a few attempts).
A spinlock is typically implemented using atomic operations, and without using anything provided by the operating system. In the past, this meant using either compiler intrinsics or non-portable assembler instructions. Meanwhile both C++11 and C11 have atomic operations as part of the language, so apart from the general difficulty of writing provably correct lock-free code, it is now possible to implement lock-free code in an entirely portable and (almost) painless way.
|
very simply, a semaphore is a "yielding" synchronisation object, a spinlock is a 'busywait' one. (there's a little more to semaphores in that they synchronise several threads, unlike a mutex or guard or monitor or critical section that protects a code region from a single thread)
You'd use a semaphore in more circumstances, but use a spinlock where you are going to lock for a very short time - there is a cost to locking especially if you lock a lot. In such cases it can be more efficient to spinlock for a little while waiting for the protected resource to become unlocked. Obviously there is a performance hit if you spin for too long.
typically if you spin for longer than a thread quantum, then you should use a semaphore.
|
Spinlock versus Semaphore
|
[
"",
"c++",
"c",
"linux",
"unix",
"operating-system",
""
] |
We are currently researching ways of enhancing image quality prior to submission to OCR. The OCR engine we are currently utilizing is the Scansoft API from Nuance (v15). We were researching the [Lead Tools](http://leadtools.com/) but have since decided to look elsewhere. The licensing costs associated with Lead Tools is just too great. To start with we are looking for simple image enhancement features such as: deskewing, despeckling, line removal, punch hole removal, sharpening, etc. We are running a mix of .NET and Java software, but java solution would be preferred.
|
Kofax is good for pre-processing, but for the types of cleanup you are talking about may be overkill unless the images are really bad. Unless your specialty is in image processing, I'd recommend working with a provider that does the image cleanup and the OCR so you can focus on the value you actually add.
We license the OCR development kit from ABBYY ([ABBY SDK](http://www.abbyy.com/sdk/)) and have found it to be superb for both image processing and OCR. The API is quite extensive, and the sample apps, help and support have been beyond impressive. I definitely recommend taking a look.
|
*Disclaimer: I work for Atalasoft*
We have those functions and run-time royalty-free licensing for .NET.
<http://www.atalasoft.com/products/dotimage/>
We also have OCR components including a .NET wrapper for Abbyy, Tesseract and others and Searchable PDF generation (image on top of text in a PDF)
|
What software would you recommend for image enhancement prior to OCR (Optical Character Recognition)?
|
[
"",
"java",
".net",
"image-processing",
"ocr",
"image-enhancement",
""
] |
I get the following warning when using `java.net.URLEncoder.encode`:
```
warning: [deprecation] encode(java.lang.String)
in java.net.URLEncoder has been deprecated
```
What should I be using instead?
|
Use the other `encode` method in [URLEncoder](http://docs.oracle.com/javase/8/docs/api/java/net/URLEncoder.html#encode-java.lang.String-java.lang.String-):
```
URLEncoder.encode(String, String)
```
The first parameter is the text to encode; the second is the name of the character encoding to use (e.g., `UTF-8`). For example:
```
System.out.println(
URLEncoder.encode(
"urlParameterString",
java.nio.charset.StandardCharsets.UTF_8.toString()
)
);
```
|
You should use:
```
URLEncoder.encode("NAME", "UTF-8");
```
|
java.net.URLEncoder.encode(String) is deprecated, what should I use instead?
|
[
"",
"java",
"url",
"network-programming",
"deprecated",
""
] |
Is it possible to pass a App setting "string" in the web.config to a Common C# class?
|
Of course it's possible - but the thing to keep in mind is that a properly designed class (unless it's explicitly designed for ASP.NET) shouldn't know or care where the information comes from. There should be a property (or method, but properties are the more '.NET way' of doing things) that you set with the string value from the application itself, rather than having the class directly grab information from web.config.
|
In any class you can use `ConfigurationManager.AppSettings["KeyToSetting"]` to access any value in the element of web.config (or app.config)
|
Is it possible to pass a App setting in the web.config to a Common C# class
|
[
"",
"c#",
"asp.net",
"web-config",
""
] |
I currently do my textfile manipulation through a bunch of badly remembered AWK, sed, Bash and a tiny bit of Perl.
I've seen mentioned a few places that python is good for this kind of thing. How can I use Python to replace shell scripting, AWK, sed and friends?
|
Any shell has several sets of features.
* The Essential Linux/Unix commands. All of these are available through the [subprocess](https://docs.python.org/3/library/subprocess.html) library. This isn't always the best first choice for doing *all* external commands. Look also at [shutil](https://docs.python.org/3/library/shutil.html) for some commands that are separate Linux commands, but you could probably implement directly in your Python scripts. Another huge batch of Linux commands are in the [os](https://docs.python.org/3/library/os.html) library; you can do these more simply in Python.
And -- bonus! -- more quickly. Each separate Linux command in the shell (with a few exceptions) forks a subprocess. By using Python `shutil` and `os` modules, you don't fork a subprocess.
* The shell environment features. This includes stuff that sets a command's environment (current directory and environment variables and what-not). You can easily manage this from Python directly.
* The shell programming features. This is all the process status code checking, the various logic commands (if, while, for, etc.) the test command and all of it's relatives. The function definition stuff. This is all much, much easier in Python. This is one of the huge victories in getting rid of bash and doing it in Python.
* Interaction features. This includes command history and what-not. You don't need this for writing shell scripts. This is only for human interaction, and not for script-writing.
* The shell file management features. This includes redirection and pipelines. This is trickier. Much of this can be done with subprocess. But some things that are easy in the shell are unpleasant in Python. Specifically stuff like `(a | b; c ) | something >result`. This runs two processes in parallel (with output of `a` as input to `b`), followed by a third process. The output from that sequence is run in parallel with `something` and the output is collected into a file named `result`. That's just complex to express in any other language.
Specific programs (awk, sed, grep, etc.) can often be rewritten as Python modules. Don't go overboard. Replace what you need and evolve your "grep" module. Don't start out writing a Python module that replaces "grep".
The best thing is that you can do this in steps.
1. Replace AWK and PERL with Python. Leave everything else alone.
2. Look at replacing GREP with Python. This can be a bit more complex, but your version of GREP can be tailored to your processing needs.
3. Look at replacing FIND with Python loops that use `os.walk`. This is a big win because you don't spawn as many processes.
4. Look at replacing common shell logic (loops, decisions, etc.) with Python scripts.
|
Yes, of course :)
Take a look at these libraries which help you ***Never write shell scripts again*** (Plumbum's motto).
* [Plumbum](http://plumbum.readthedocs.org/en/latest/)
* [Sarge](https://bitbucket.org/vinay.sajip/sarge/)
* [sh](http://amoffat.github.com/sh/)
Also, if you want to replace awk, sed and grep with something Python based then I recommend [pyp](http://pyvideo.org/video/686/the-pyed-piper-a-modern-python-alternative-to-aw) -
> "The Pyed Piper", or pyp, is a linux command line text manipulation
> tool similar to awk or sed, but which uses standard python string and
> list methods as well as custom functions evolved to generate fast
> results in an intense production environment.
|
How to implement common bash idioms in Python?
|
[
"",
"python",
"bash",
"shell",
""
] |
Whenever I use the signal/slot editor dialog box, I have to choose from the existing list of slots. So the question is how do I create a custom named slot?
|
Unfortunately this is not possible in Qt4.
In Qt3 you could create custom slots which where then implemented in the ui.h file. However, Qt4 does not use this file so custom slots are not supported.
There is some discussion of this issue over on [QtForum](http://www.qtforum.org/article/11096/qt4-custom-slots.html)
|
This does seem to be possible in the version of Qt Designer 4.5.2, but it *can't* be done from the Signal/Slot Editor dock-widget in the main window.
This is what worked for me
1. Switch to [Edit Signals/Slots](http://doc.qt.io/qt-4.8/designer-connection-mode.html) mode (F4)
2. Drag and drop from the widget which is to emit the signal, to the widget which is to receive the signal.
3. A *Configure Connection* dialog appears, showing the signals for the emitting widget, and the slots for the receiving widget. Click *Edit...* below the slots column on the right.
4. A *Signals/Slots of ReceivingWidget* dialog appears. In here its is possible to click the plus icon beneath slots to add a new slot of any name.
5. You can then go back and connect to your new slot in the *Configure Connection* dialog, or indeed in the Signal/Slot Editor dockwidget back in the main window.
Caveat: I'm using PyQt, and I've only tried to use slots added in this way from Python, not from C++, so your mileage may vary...
|
How do I create a custom slot in qt4 designer?
|
[
"",
"c++",
"qt",
"qt4",
"qt-creator",
"qt-designer",
""
] |
I have a Python application in a strange state. I don't want to do live debugging of the process. Can I dump it to a file and examine its state later? I know I've restored corefiles of C programs in gdb later, but I don't know how to examine a Python application in a useful way from gdb.
(This is a variation on my question about [debugging memleaks in a production system](https://stackoverflow.com/questions/141351/how-do-i-find-what-is-using-memory-in-a-python-process-in-a-production-system).)
|
There is no builtin way other than aborting (with os.abort(), causing the coredump if resource limits allow it) -- although you can certainly build your own 'dump' function that dumps relevant information about the data you care about. There are no ready-made tools for it.
As for handling the corefile of a Python process, the [Python source has a gdbinit file](http://svn.python.org/projects/python/trunk/Misc/gdbinit) that contains useful macros. It's still a lot more painful than somehow getting into the process itself (with pdb or the interactive interpreter) but it makes life a little easier.
|
If you only care about storing the traceback object (which is all you need to start a debugging session), you can use [debuglater](https://github.com/ploomber/debuglater) (a fork of [pydump](https://github.com/elifiner/pydump)). It works with recent versions of Python and has a IPython/Jupyter integration.
If you want to store the entire session, look at [dill](https://github.com/uqfoundation/dill). It has a `dump_session`, and `load_session` functions.
Here are two other relevant projects:
* [python-checkpointing2](https://github.com/a-rahimi/python-checkpointing2)
* [pycrunch-trace](https://github.com/gleb-sevruk/pycrunch-trace)
If you're looking for a language agnostic solution, you want to create a core dump file. [Here's an example with Python.](https://pythondev.readthedocs.io/debug_tools.html#create-a-core-dump-file)
|
How do I dump an entire Python process for later debugging inspection?
|
[
"",
"python",
"debugging",
"coredump",
""
] |
There are some updates with .NET 3.0 concerning how to create and use add-ins for your own applications. I read about some "*pipeline*" you have to create for the communication between add-in and host-application but couldn't find further information about it.
How would you made an add-in functionality in an application with .NET 3.0/3.5?
**Additional information if necessary**: The host application is made with WPF and some general functionality. Each add-in should add a own register-tab to a given container with their own content (buttons, textfields, ...) and methods to extend the host-application.
|
Definitely check out the Managed Extensibility Framework at [www.codeplex.com/mef](http://www.codeplex.com/mef). It's a framework that helps with creating extensible applications. It takes care of all the plumbing when creating a pluggable app.
I'm currently writing a series of articles that show the basic functionality of mef at <http://www.jenswinter.com/?tag=/mef>. But the articles are in German though.
Another framework you should give a try is the [CompositeWpf](http://www.codeplex.com/CompositeWpf) (f.k.a. Prism). It let's you create composite WPF applications. Your app will consist of a shell app and several module projects that are wired together and hooked into the shell.
|
In addition to [Daniels](https://stackoverflow.com/questions/179680/how-can-you-make-use-of-the-add-in-framework-in-net-30#179727) codeplex link, Jason He also has a nice wee series on using the System.AddIn namespace when developing Paint.NET starting here -
<http://blogs.msdn.com/zifengh/archive/2007/01/04/addin-model-in-paint-net-1-introduction.aspx>
|
How can you make use of the add-in framework in .NET 3.0?
|
[
"",
"c#",
"add-in",
".net-3.0",
""
] |
Would a C++ [CLI](http://en.wikipedia.org/wiki/Common_Language_Infrastructure) compiler be able to compile some large sets of C++ classes without modifications?
Is C++ CLI a superset of C++?
|
technically no, but depending how standard the C++ code is, you'll probably be just fine. when you get into windows stuff you may run into issues. I compiled the whole game engine we use at work in C++/CLI once and it worked just fine. A colleague did the same for all of mozilla and no such luck.
|
According to [Wikipedia](http://en.wikipedia.org/wiki/C%2B%2B/CLI "Wikipedia"):
> C++/CLI should be thought of as a language of its own (with a new set of keywords, for example), instead of the C++ superset-oriented Managed C++
|
Is C++ CLI a superset of C++?
|
[
"",
"c++",
"c++-cli",
"clr",
""
] |
I know I'll get a thousand "Depends on what you're trying to do" answers, but seriously, there really is no solid information about this online yet. Here are my assumptions - I think they're similar for alot of people right now:
1. It is now October 2008. I want to start writing an application for January 2009. I am willing to use beta code and such but by January, I'd like a site that doesn't have 'strange' problems. With that said, if a language is simply 10% slower than another, I don't care about those things as long as the issue is linear. My main concern is developer productivity.
2. I'll be using Linux, Apache, MySQL for the application.
3. I want the power to do things like run scp and ftp client functions with stable libraries (I only picked those two because they're not web-related but at the same time represent pretty common network protocols that any larger app might use). Technologies like OpenID and Oauth will be used as well.
4. Experienced web developers are readily available (i.e. I don't have to find people from financial companies and such).
5. Whatever the choice is is common and will be around for a while.
6. Here's a kicker. I'd like to be able to use advanced presentation layer tools/languages similar to HAML, SASS. I definitively want to use JQuery.
7. I will be creating a Facebook app and at some point doing things like dealing with SMS messages, iPhone apps, etc...
At this point, the choices for language are PHP (Cake,Symfony,Zend), Python (Django), Ruby (Merb). I'm really between Django and Merb at this point mostly because everybody else seems to be going that way.
Please don't put any technologies in here that aren't made for mainstream. I know Merb is untested mostly, but their stated goal is a solid platform and it has alot of momentum behind it so I'm confident that it's workable. Please don't answer with how great Perl is or .Net.
For Future References - these choices were already made:
* Debian (Lenny) - For converting CPU cycles into something useful. Trac
* 0.11 - For Project Management Gliffy - For wireframes and such
* Google Docs/Apps - For documentation, hosted email, etc...
* Amazon ec2/S3 - For hosting, storage.
Cheers,
Adam
|
it depends.
php - symfony is a great framework. downsides: php, wordy and directory heavy. propel gets annoying to use. upsides: php is everywhere and labor is cheap. well done framework, and good support. lots of plugins to make your life easier
python - django is also a great framework. downsides: python programmers can be harder to find, django even harder. changing your db schema can be somewhat difficult since there are no official migrations. doesn't quite do mvc like you'd expect. upsides: does everything you need and has the great python std library and community behind it.
ruby - i've never used merb, so I'll address rails. upsides: there is a plugin, gem, or recipe for almost anything you could want to do. easy to use. downsides: those plugins, gems, and recipes sometimes fail to work in mysterious ways. monkey patching is often evil. the community is.. vocal. opinionated software, and sometimes those opinions are wrong (*lack of foreign keys*). rails itself seems like a tower of cards waiting to explode and take hours of your life away.
with all of that said, I'm a freelance php/symfony and ruby/rails developer. I've worked on several projects in both languages and frameworks. My latest project is in Rails solely because of ActiveMerchant. I've been looking for a reason to develop a django app for a while. If there were an ActiveMerchant like library for django, I probably would have used it.
|
**Django!**
Look up the DjangoCon talks on Google/Youtube - Especially "Reusable Apps" (www.youtube.com/watch?v=A-S0tqpPga4)
I've been using Django for some time, after starting with Ruby/Rails. I found the Django Community easier to get into (nicer), the language documented with *excellent* examples, and it's modularity is awesome, especially if you're wanting to throw custom components into the mix, and not be forced to use certain things here and there.
I'm sure there are probably ways to be just as flexible with Rails or some such, but I highly encourage you to take a long look at the Django introductions, etc, at <http://www.djangoproject.com/>
Eugene mentioned it's now at 1.0 - and therefore will remain a stable and backward-compatible codebase well through January 2009.
Also, the automatic admin interfaces it builds are *production ready*, and extremely flexible.
|
Framework/Language for new web 2.0 sites (2008 and 2009)
|
[
"",
"python",
"ruby-on-rails",
"django",
"merb",
""
] |
**Note:** This question was asked at a time when C# did not yet support optional parameters (i.e. before C# 4).
We're building a web API that's programmatically generated from a C# class. The class has method `GetFooBar(int a, int b)` and the API has a method `GetFooBar` taking query params like `&a=foo &b=bar`.
The classes needs to support optional parameters, which isn't supported in C# the language. What's the best approach?
|
With C# 4.0 you can use optional parameters that work like this:
```
public void SomeMethod(int a, int b = 0)
{
//some code
}
```
|
Another option is to use the params keyword
```
public void DoSomething(params object[] theObjects)
{
foreach(object o in theObjects)
{
// Something with the Objects…
}
}
```
Called like...
```
DoSomething(this, that, theOther);
```
|
How can you use optional parameters in C#?
|
[
"",
"c#",
"optional-parameters",
""
] |
I'd like to run a script to populate my database. I'd like to access it through the Django database API.
The only problem is that I don't know what I would need to import to gain access to this.
How can this be achieved?
|
Import your settings module too
```
import os
os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings"
from mysite.polls.models import Poll, Choice
```
should do the trick.
|
This is what I have at the top of one my data loading scripts.
```
import string
import sys
try:
import settings # Assumed to be in the same directory.
#settings.DISABLE_TRANSACTION_MANAGEMENT = True
except ImportError:
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
#Setup the django environment with the settings module.
import django
import django.core.management
django.core.management.setup_environ(settings)
from django.db import transaction
```
This should all execute before you do much else in your script.
Another method is to use fixtures and manage.py. Though if you are just trying to accomplish a bulk data load to initialize a database this should work fine.
Also depending on what you are doing you may or may not want to do it all in one transaction. Uncomment the transaction line above and structure your code similar to this.
```
transaction.enter_transaction_management()
try:
#Do some stuff
transaction.commit()
finally:
transaction.rollback()
pass
transaction.leave_transaction_management()
```
|
What do I need to import to gain access to my models?
|
[
"",
"python",
"django",
""
] |
I love Python because it comes batteries included, and I use built-in functions, a lot, to do the dirty job for me.
I have always been using happily the os.path module to deal with file path but recently I ended up with unexpected results on Python 2.5 under Ubuntu linux, while dealing with string that represent windows file paths :
```
filepath = r"c:\ttemp\FILEPA~1.EXE"
print os.path.basename(filepath)
'c:\\ttemp\\FILEPA~1.EXE']
print os.path.splitdrive(filepath)
('', 'c:\ttemp\\FILEPA~1.EXE')
```
WTF ?
It ends up the same way with filepath = u"c:\ttemp\FILEPA~1.EXE" and filepath = "c:\ttemp\FILEPA~1.EXE".
Do you have a clue ? Ubuntu use UTF8 but I don't feel like it has something to do with it. Maybe my Python install is messed up but I did not perform any particular tweak on it that I can remember.
|
If you want to manipulate Windows paths on linux you should use the ntpath module (this is the module that is imported as os.path on windows - posixpath is imported as os.path on linux)
```
>>> import ntpath
>>> filepath = r"c:\ttemp\FILEPA~1.EXE"
>>> print ntpath.basename(filepath)
FILEPA~1.EXE
>>> print ntpath.splitdrive(filepath)
('c:', '\\ttemp\\FILEPA~1.EXE')
```
|
From a `os.path` documentation:
**os.path.splitdrive(path)**
Split the pathname path into a pair (drive, tail) where drive is either a drive specification or the empty string. On systems which do not use drive specifications, drive will always be the empty string. In all cases, drive + tail will be the same as path.
If you running this on unix, it doesnt use drive specifications, hence - drive will be empty string.
If you want to solve windows paths on any platform, you can just use a simple regexp:
```
import re
(drive, tail) = re.compile('([a-zA-Z]\:){0,1}(.*)').match(filepath).groups()
```
`drive` will be a drive letter followed by `:` (eg. `c:`, `u:`) or `None`, and `tail` the whole rest :)
|
Os.path : can you explain this behavior?
|
[
"",
"python",
"path",
""
] |
How do I convert a hex string to an integer?
```
"0xffff" ⟶ 65535
"ffff" ⟶ 65535
```
|
**Without** the `0x` prefix, you need to specify the base explicitly, otherwise there's no way to tell:
```
x = int("deadbeef", 16)
```
**With** the `0x` prefix, Python can distinguish hex and decimal automatically:
```
>>> print(int("0xdeadbeef", 0))
3735928559
>>> print(int("10", 0))
10
```
(You *must* specify `0` as the base in order to invoke this prefix-guessing behavior; if you omit the second parameter, [`int()`](https://docs.python.org/library/functions.html#int) will assume base-10.)
|
`int(hexstring, 16)` does the trick, and works with and without the 0x prefix:
```
>>> int("a", 16)
10
>>> int("0xa", 16)
10
```
|
Convert hex string to integer in Python
|
[
"",
"python",
"string",
"hex",
""
] |
I inherited this gigantic legacy Java web app using Struts 1.2.4. I have a specific question regarding Actions. Most of the pages have exactly one Action, and the processExecute() methods are hideous monsters (very long and tons of nested if statements based on request parameters).
Given that Actions are an implementation of the command pattern, I'm thinking to split these Actions into one Action per user gesture. This will be a large refactoring though, and I'm wondering:
1. Is this the right direction?
2. Is there an intermediate step I could take, a pattern that deals with the mess inside the monolithic actions? Maybe another command pattern inside the Action?
|
My way of dealing with this would be:
* dont do 'everything at once'
* whenever you change anything, leave it better than you found it
+ replacing conditionals with separate Action implementations is one step.
+ Better yet: Make your implementations separate from the Action classes so that you can use it when you change frameworks
+ Keep your new Command implementation *absolutely* without references to Struts, use your new Actions as Wrapper around these implementations.
+ You might need to provide interfaces to your Struts ActionForms in order to pass them around without copying all the data. On the other hand - you might want to pass around other objects than ActionForms that are usually a bunch of Strings (see your other question about [Struts 1.2 ActionForms](https://stackoverflow.com/questions/209493/what-type-should-struts-actionform-properties-be))
* start migrating parts to newer & better technology. Struts 1.2 was great when it came out, but is definitely not what you want to support in eternity. There are some generations of better frameworks now.
There's definitely more - Sorry, I'm running out of time here...
|
Struts Actions, in my mind, shouldn't have very much code in them at all. They should just interact directly with the request and response - take some data from a form or a request parameter, hand that info off to the Service Layer, and then put some stuff in a Response object or maybe save some data in the user's session.
I'd recommend staying away from doing inheritance with action classes. It sounds like a good idea at first but I think sooner or later you realize that you're shoe-horning things more than you're actually making the code base robust. Struts has enough base actions as is, if you're creating new ones you've probably got code in the web layer that shouldn't be there.
That is just my personal experience.
|
How to deal with monstrous Struts Actions?
|
[
"",
"java",
"struts",
"design-patterns",
"anti-patterns",
""
] |
I have embedded a Python interpreter in a C program. Suppose the C program reads some bytes from a file into a char array and learns (somehow) that the bytes represent text with a certain encoding (e.g., ISO 8859-1, Windows-1252, or UTF-8). How do I decode the contents of this char array into a Python string?
The Python string should in general be of type `unicode`—for instance, a `0x93` in Windows-1252 encoded input becomes a `u'\u0201c'`.
I have attempted to use `PyString_Decode`, but it always fails when there are non-ASCII characters in the string. Here is an example that fails:
```
#include <Python.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
char c_string[] = { (char)0x93, 0 };
PyObject *py_string;
Py_Initialize();
py_string = PyString_Decode(c_string, 1, "windows_1252", "replace");
if (!py_string) {
PyErr_Print();
return 1;
}
return 0;
}
```
The error message is `UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 0: ordinal not in range(128)`, which indicates that the `ascii` encoding is used even though we specify `windows_1252` in the call to `PyString_Decode`.
The following code works around the problem by using `PyString_FromString` to create a Python string of the undecoded bytes, then calling its `decode` method:
```
#include <Python.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
char c_string[] = { (char)0x93, 0 };
PyObject *raw, *decoded;
Py_Initialize();
raw = PyString_FromString(c_string);
printf("Undecoded: ");
PyObject_Print(raw, stdout, 0);
printf("\n");
decoded = PyObject_CallMethod(raw, "decode", "s", "windows_1252");
Py_DECREF(raw);
printf("Decoded: ");
PyObject_Print(decoded, stdout, 0);
printf("\n");
return 0;
}
```
|
PyString\_Decode does this:
```
PyObject *PyString_Decode(const char *s,
Py_ssize_t size,
const char *encoding,
const char *errors)
{
PyObject *v, *str;
str = PyString_FromStringAndSize(s, size);
if (str == NULL)
return NULL;
v = PyString_AsDecodedString(str, encoding, errors);
Py_DECREF(str);
return v;
}
```
IOW, it does basically what you're doing in your second example - converts to a string, then decode the string. The problem here arises from PyString\_AsDecodedString, rather than PyString\_AsDecodedObject. PyString\_AsDecodedString does PyString\_AsDecodedObject, but then tries to convert the resulting unicode object into a string object with the default encoding (for you, looks like that's ASCII). That's where it fails.
I believe you'll need to do two calls - but you can use PyString\_AsDecodedObject rather than calling the python "decode" method. Something like:
```
#include <Python.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
char c_string[] = { (char)0x93, 0 };
PyObject *py_string, *py_unicode;
Py_Initialize();
py_string = PyString_FromStringAndSize(c_string, 1);
if (!py_string) {
PyErr_Print();
return 1;
}
py_unicode = PyString_AsDecodedObject(py_string, "windows_1252", "replace");
Py_DECREF(py_string);
return 0;
}
```
I'm not entirely sure what the reasoning behind PyString\_Decode working this way is. A [very old thread on python-dev](http://mail.python.org/pipermail/python-dev/2001-May/014547.html) seems to indicate that it has something to do with chaining the output, but since the Python methods don't do the same, I'm not sure if that's still relevant.
|
You don't want to decode the string into a Unicode representation, you just want to treat it as an array of bytes, right?
Just use `PyString_FromString`:
```
char *cstring;
PyObject *pystring = PyString_FromString(cstring);
```
That's all. Now you have a Python `str()` object. See docs here: <https://docs.python.org/2/c-api/string.html>
I'm a little bit confused about how to specify "str" or "unicode." They are quite different if you have non-ASCII characters. If you want to decode a C string **and** you know exactly what character set it's in, then yes, `PyString_DecodeString` is a good place to start.
|
How to convert a C string (char array) into a Python string when there are non-ASCII characters in the string?
|
[
"",
"python",
"c",
"character-encoding",
"embedding",
""
] |
Is there a way to take a class name and convert it to a string in C#?
As part of the Entity Framework, the .Include method takes in a dot-delimited list of strings to join on when performing a query. I have the class model of what I want to join, and for reasons of refactoring and future code maintenance, I want to be able to have compile-time safety when referencing this class.
Thus, is there a way that I could do this:
```
class Foo
{
}
tblBar.Include ( Foo.GetType().ToString() );
```
I don't think I can do GetType() without an instance. Any ideas?
|
[Include requires a property name](http://msdn.microsoft.com/en-us/library/bb738708.aspx), not a class name. Hence, it's the name of the property you want, not the name of its type. [You can get that with reflection](http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx).
|
You can't use `.GetType()` without an instance because `GetType` is a method.
You can get the name from the type though like this:
```
typeof(Foo).Name
```
And as pointed out by Chris, if you need the assembly qualified name you can use
```
typeof(Foo).AssemblyQualifiedName
```
|
Get the name of a class as a string in C#
|
[
"",
"c#",
"entity-framework",
""
] |
Sometimes I find myself in the situation where I want to execute several sequential commands like such:
```
try:
foo(a, b)
except Exception, e:
baz(e)
try:
bar(c, d)
except Exception, e:
baz(e)
...
```
This same pattern occurs when exceptions simply need to be ignored.
This feels redundant and the excessive syntax causes it to be surprisingly difficult to follow when reading code.
In C, I would have solved this type of problem easily with a macro, but unfortunately, this cannot be done in straight python.
Question: How can I best reduce the code footprint and increase code readability when coming across this pattern?
|
You could use the [`with` statement](https://www.python.org/dev/peps/pep-0343/) if you have python 2.5 or above:
```
from __future__ import with_statement
import contextlib
@contextlib.contextmanager
def handler():
try:
yield
except Exception, e:
baz(e)
```
Your example now becomes:
```
with handler():
foo(a, b)
with handler():
bar(c, d)
```
|
If this is always, *always* the behaviour you want when a particular function raises an exception, you could use a decorator:
```
def handle_exception(handler):
def decorate(func):
def call_function(*args, **kwargs):
try:
func(*args, **kwargs)
except Exception, e:
handler(e)
return call_function
return decorate
def baz(e):
print(e)
@handle_exception(baz)
def foo(a, b):
return a + b
@handle_exception(baz)
def bar(c, d):
return c.index(d)
```
Usage:
```
>>> foo(1, '2')
unsupported operand type(s) for +: 'int' and 'str'
>>> bar('steve', 'cheese')
substring not found
```
|
Generic Exception Handling in Python the "Right Way"
|
[
"",
"python",
"exception",
"readability",
""
] |
Out style:
```
bool result;
if(something.TryParse(val, out result))
{
DoSomething(result);
}
```
Nullable style:
```
bool? result = something.TryParse2(val);
if(result.HasValue)
{
DoSomething(result.Value);
}
```
|
TryParse(val, out result) is a idiom established by the .NET framework in int.TryParse, DateTime.TryParse, etc. It is likely that people that read the code will be familiar with this idiom, so you should stick to it, unless you find a very good reason not to.
|
I don't mean to be unkind. But when you propose a change to a well-established idiom, it undermines confidence if your sample code isn't right.
Your first example should either be:
```
something result;
if (something.TryParse(val, out result))
{
DoSomething(result);
}
```
or:
```
bool result;
if (bool.TryParse(value, out result))
{
DoSomething(result);
}
```
Your second example should either be:
```
Nullable<something> result = something.TryParse2(val);
if(result.HasValue)
{
DoSomething(result.Value);
}
```
or:
```
bool? result = bool.TryParse2(val);
if (result.HasValue)
{
DoSomething(result);
}
```
If I *were* going to implement an extension method for each value type that did what your `TryParse2` seems to do, I wouldn't call it `TryParse2`. Right now, if a method's name begins with `Try`, we expect it to return a `bool` indicating whether or not it succeeded or failed. Creating this new method creates a world where that expectation is no longer valid. And before you dismiss this, think about what was going through your mind when you wrote example code that didn't work, and why you were so sure that `result` needed to be a `bool`.
The other thing about your proposal is that it seems to be trying to solve the wrong problem. If I found myself writing a lot of `TryParse` blocks, the first question I'd ask isn't "How can I do this in fewer lines of code?" I'd ask, "Why do I have parsing code scattered throughout my application?" My first instinct would be to come up with a higher level of abstraction for what I'm really trying to do when I'm duplicating all of that `TryParse` code.
|
TryParse: What is more readable?
|
[
"",
"c#",
""
] |
In ruby the library path is provided in `$:`, in perl it's in `@INC` - how do you get the list of paths that Python searches for modules when you do an import?
|
I think you're looking for [sys.path](https://docs.python.org/3/library/sys.html#sys.path)
```
import sys
print (sys.path)
```
|
You can also make additions to this path with the PYTHONPATH environment variable at runtime, in addition to:
```
import sys
sys.path.append('/home/user/python-libs')
```
|
Python Library Path
|
[
"",
"python",
""
] |
Why or why not?
|
For performance, especially when you're iterating over a large range, `xrange()` is usually better. However, there are still a few cases why you might prefer `range()`:
* In python 3, `range()` does what `xrange()` used to do and `xrange()` does not exist. If you want to write code that will run on both Python 2 and Python 3, you can't use `xrange()`.
* `range()` can actually be faster in some cases - eg. if iterating over the same sequence multiple times. `xrange()` has to reconstruct the integer object every time, but `range()` will have real integer objects. (It will always perform worse in terms of memory however)
* `xrange()` isn't usable in all cases where a real list is needed. For instance, it doesn't support slices, or any list methods.
[Edit] There are a couple of posts mentioning how `range()` will be upgraded by the 2to3 tool. For the record, here's the output of running the tool on some sample usages of `range()` and `xrange()`
```
RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: ws_comma
--- range_test.py (original)
+++ range_test.py (refactored)
@@ -1,7 +1,7 @@
for x in range(20):
- a=range(20)
+ a=list(range(20))
b=list(range(20))
c=[x for x in range(20)]
d=(x for x in range(20))
- e=xrange(20)
+ e=range(20)
```
As you can see, when used in a for loop or comprehension, or where already wrapped with list(), range is left unchanged.
|
No, they both have their uses:
Use `xrange()` when iterating, as it saves memory. Say:
```
for x in xrange(1, one_zillion):
```
rather than:
```
for x in range(1, one_zillion):
```
On the other hand, use `range()` if you actually want a list of numbers.
```
multiples_of_seven = range(7,100,7)
print "Multiples of seven < 100: ", multiples_of_seven
```
|
Should you always favor xrange() over range()?
|
[
"",
"python",
"range",
"xrange",
""
] |
I have a template in word (.docx) format and want to replace some placeholders in this template with my own data, do you know where I can find the right classes for this project? It would be nice for me to know the namespace. Are there any newer classes for handling word documents in the docx format (xml) than the com classes? Thank you for all your answers, I hope someone can help me with my problem.
greets
Sebastian
|
The new office formats (docx, xlsx, etc) are zip files that contain a collection of xml files. With that in mind you have a couple of approaches.
1. You can use the Open XML SDK located at <http://www.microsoft.com/downloads/details.aspx?FamilyId=AD0B72FB-4A1D-4C52-BDB5-7DD7E816D046&displaylang=en>
2. You can unzip the docx file, do a search and replace for your tokens, and zip it back up.
There is a website at [openxmldeveloper.org](http://openxmldeveloper.org) that is just for this kind of thing. Also, bear in mind that they are already shipping a beta version 2 of the SDK.
|
Eric White has touched on exactly this subject in a [blog article detailing a program meant to validate source snippets embedded in DocX files](http://blogs.msdn.com/ericwhite/archive/2008/09/08/openxmlcodetester-validating-code-in-open-xml-documents.aspx). Beyond just that article I highly recommend reading his series on [Office Open XML and C#](http://blogs.msdn.com/ericwhite/archive/2008/09/29/the-flat-opc-format.aspx).
|
Replace Placeholders in word document with c#
|
[
"",
"c#",
".net",
"ms-word",
"placeholder",
""
] |
Why can't I pass the table name to a prepared PDO statement?
```
$stmt = $dbh->prepare('SELECT * FROM :table WHERE 1');
if ($stmt->execute(array(':table' => 'users'))) {
var_dump($stmt->fetchAll());
}
```
Is there another safe way to insert a table name into a SQL query? With safe, I mean that I don't want to do
```
$sql = "SELECT * FROM $table WHERE 1"
```
|
**Table and Column names CANNOT be replaced by parameters in PDO.**
In that case you will simply want to filter and sanitize the data manually. One way to do this is to pass in shorthand parameters to the function that will execute the query dynamically and then use a `switch()` statement to create a white list of valid values to be used for the table name or column name. That way no user input ever goes directly into the query. So for example:
```
function buildQuery( $get_var )
{
switch($get_var)
{
case 1:
$tbl = 'users';
break;
}
$sql = "SELECT * FROM $tbl";
}
```
By leaving no default case or using a default case that returns an error message you ensure that only values that you want used get used.
|
To understand *why* binding a table (or column) name doesn't work, you have to understand how the placeholders in prepared statements work: they are not simply substituted in as (suitably escaped) strings, and the resulting SQL executed. Instead, a DBMS asked to "prepare" a statement comes up with a complete query plan for how it would execute that query, including which tables and indexes it would use, which will be the same regardless of how you fill in the placeholders.
The plan for `SELECT name FROM my_table WHERE id = :value` will be the same whatever you substitute for `:value`, but the seemingly similar `SELECT name FROM :table WHERE id = :value` cannot be planned, because the DBMS has no idea what table you're actually going to select from.
This is not something an abstraction library like PDO can or should work around, either, since it would defeat the 2 key purposes of prepared statements: 1) to allow the database to decide in advance how a query will be run, and use the same plan multiple times; and 2) to prevent security issues by separating the logic of the query from the variable input.
|
Can PHP PDO Statements accept the table or column name as parameter?
|
[
"",
"php",
"pdo",
""
] |
Does anyone know the full list of C# compiler number literal modifiers?
By default declaring '0' makes it an Int32 and '0.0' makes it a 'Double'. I can use the literal modifier 'f' at the end to ensure something is treated as a 'Single' instead. For example like this...
```
var x = 0; // x is Int32
var y = 0f; // y is Single
```
What are the other modifiers I can use? Is there one for forcing to Double, Decimal, UInt32? I tried googling for this but could not find anything. Maybe my terminology is wrong and so that explains why I am coming up blank. Any help much appreciated.
|
```
var y = 0f; // y is single
var z = 0d; // z is double
var r = 0m; // r is decimal
var i = 0U; // i is unsigned int
var j = 0L; // j is long (note capital L for clarity)
var k = 0UL; // k is unsigned long (note capital L for clarity)
```
From the [C# specification](https://stackoverflow.com/questions/127776/where-can-you-find-the-c-language-specifications) 2.4.4.2 Integer literals and 2.4.4.3 Real literals. Take note that L and UL are preferred as opposed to their lowercase variants for clarity as recommended by [Jon Skeet](https://stackoverflow.com/users/22656/jon-skeet).
|
If you don't want to have to remember them, then the compiler also accepts a cast for the same purpose (you can check the IL that the effect is the same - i.e. the compiler, not the runtime, does the cast). To borrow the earlier example:
```
var y = (float)0; // y is single
var z = (double)0; // z is double
var r = (decimal)0; // r is decimal
var i = (uint)0; // i is unsigned int
var j = (long)0; // j is long
var k = (ulong)0; // k is unsigned long
```
And for the record, I agree that "var" is a bad choice here; I'll happily use var for a SortedDictionary<SomeLongType, SomeOtherLongType>, but for "int" it is just lazy...
|
C# compiler number literals
|
[
"",
"c#",
"compiler-construction",
""
] |
I'm not looking for java-web-start, I'm looking for a thick-client application installation toolkit. I've got a stand-alone application that consists of several files (jar files, data files, etc) and would need to do some pretty standard installation tasks, like asking the user for target directories, have them locate some parts of their system - choose some of the per-machine or per-user configuration options and possibly try to detect some of the machine settings for them.
I'm looking for something which is like the MSI or other wizard driven installation applications. What's a good installer for Java? It would be ideal if it were cross-platform capable (Linux, Mac OSX and Windows).
|
Not an MSI-Installer but crossplatform: [izPack](http://izpack.org/)
It's xml-file based with it's own GUI or ant task (whtaever you prefer)
|
Launch4j -- open source -- <http://launch4j.sourceforge.net/>
InstallJammer -- <http://www.installjammer.com/>
|
Java Application Installers
|
[
"",
"java",
"installation",
"toolkit",
""
] |
I had a look in the reference doc, and Spring seems to have pretty good support for sending mail. However, I need to login to a mail account, read the messages, and download any attachments. Is downloading mail attachments supported by the Spring mail API?
I know you can do this with the Java Mail API, but in the past I've found that very verbose and unpleasant to work with.
**EDIT**: I've received several replies pointing towards tutorials that describe how to send mail with attachments, but what I'm asking about is how to **read** attachments from **received** mail.
Cheers,
Don
|
Here's the class that I use for downloading e-mails (with attachment handling). You'll have to glance by some of the stuff it's doing (like ignore the logging classes and database writes). I've also re-named some of the packages for ease of reading.
The general idea is that all attachments are saved as individual files in the filesystem, and each e-mail is saved as a record in the database with a set of child records that point to all of the attachment file paths.
Focus on the doEMailDownload method.
```
/**
* Copyright (c) 2008 Steven M. Cherry
* All rights reserved.
*/
package utils.scheduled;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.Properties;
import java.util.Vector;
import javax.mail.Address;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeBodyPart;
import glob.ActionLogicImplementation;
import glob.IOConn;
import glob.log.Log;
import logic.utils.sql.Settings;
import logic.utils.sqldo.EMail;
import logic.utils.sqldo.EMailAttach;
/**
* This will connect to our incoming e-mail server and download any e-mails
* that are found on the server. The e-mails will be stored for further processing
* in our internal database. Attachments will be written out to separate files
* and then referred to by the database entries. This is intended to be run by
* the scheduler every minute or so.
*
* @author Steven M. Cherry
*/
public class DownloadEMail implements ActionLogicImplementation {
protected String receiving_host;
protected String receiving_user;
protected String receiving_pass;
protected String receiving_protocol;
protected boolean receiving_secure;
protected String receiving_attachments;
/** This will run our logic */
public void ExecuteRequest(IOConn ioc) throws Exception {
Log.Trace("Enter");
Log.Debug("Executing DownloadEMail");
ioc.initializeResponseDocument("DownloadEMail");
// pick up our configuration from the server:
receiving_host = Settings.getValue(ioc, "server.email.receiving.host");
receiving_user = Settings.getValue(ioc, "server.email.receiving.username");
receiving_pass = Settings.getValue(ioc, "server.email.receiving.password");
receiving_protocol = Settings.getValue(ioc, "server.email.receiving.protocol");
String tmp_secure = Settings.getValue(ioc, "server.email.receiving.secure");
receiving_attachments = Settings.getValue(ioc, "server.email.receiving.attachments");
// sanity check on the parameters:
if(receiving_host == null || receiving_host.length() == 0){
ioc.SendReturn();
ioc.Close();
Log.Trace("Exit");
return; // no host defined.
}
if(receiving_user == null || receiving_user.length() == 0){
ioc.SendReturn();
ioc.Close();
Log.Trace("Exit");
return; // no user defined.
}
if(receiving_pass == null || receiving_pass.length() == 0){
ioc.SendReturn();
ioc.Close();
Log.Trace("Exit");
return; // no pass defined.
}
if(receiving_protocol == null || receiving_protocol.length() == 0){
Log.Debug("EMail receiving protocol not defined, defaulting to POP");
receiving_protocol = "POP";
}
if(tmp_secure == null ||
tmp_secure.length() == 0 ||
tmp_secure.compareToIgnoreCase("false") == 0 ||
tmp_secure.compareToIgnoreCase("no") == 0
){
receiving_secure = false;
} else {
receiving_secure = true;
}
if(receiving_attachments == null || receiving_attachments.length() == 0){
Log.Debug("EMail receiving attachments not defined, defaulting to ./email/attachments/");
receiving_attachments = "./email/attachments/";
}
// now do the real work.
doEMailDownload(ioc);
ioc.SendReturn();
ioc.Close();
Log.Trace("Exit");
}
protected void doEMailDownload(IOConn ioc) throws Exception {
// Create empty properties
Properties props = new Properties();
// Get the session
Session session = Session.getInstance(props, null);
// Get the store
Store store = session.getStore(receiving_protocol);
store.connect(receiving_host, receiving_user, receiving_pass);
// Get folder
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
try {
// Get directory listing
Message messages[] = folder.getMessages();
for (int i=0; i < messages.length; i++) {
// get the details of the message:
EMail email = new EMail();
email.fromaddr = messages[i].getFrom()[0].toString();
Address[] to = messages[i].getRecipients(Message.RecipientType.TO);
email.toaddr = "";
for(int j = 0; j < to.length; j++){
email.toaddr += to[j].toString() + "; ";
}
Address[] cc;
try {
cc = messages[i].getRecipients(Message.RecipientType.CC);
} catch (Exception e){
Log.Warn("Exception retrieving CC addrs: %s", e.getLocalizedMessage());
cc = null;
}
email.cc = "";
if(cc != null){
for(int j = 0; j < cc.length; j++){
email.cc += cc[j].toString() + "; ";
}
}
email.subject = messages[i].getSubject();
if(messages[i].getReceivedDate() != null){
email.received_when = new Timestamp(messages[i].getReceivedDate().getTime());
} else {
email.received_when = new Timestamp( (new java.util.Date()).getTime());
}
email.body = "";
Vector<EMailAttach> vema = new Vector<EMailAttach>();
Object content = messages[i].getContent();
if(content instanceof java.lang.String){
email.body = (String)content;
} else if(content instanceof Multipart){
Multipart mp = (Multipart)content;
for (int j=0; j < mp.getCount(); j++) {
Part part = mp.getBodyPart(j);
String disposition = part.getDisposition();
if (disposition == null) {
// Check if plain
MimeBodyPart mbp = (MimeBodyPart)part;
if (mbp.isMimeType("text/plain")) {
Log.Debug("Mime type is plain");
email.body += (String)mbp.getContent();
} else {
Log.Debug("Mime type is not plain");
// Special non-attachment cases here of
// image/gif, text/html, ...
EMailAttach ema = new EMailAttach();
ema.name = decodeName(part.getFileName());
File savedir = new File(receiving_attachments);
savedir.mkdirs();
File savefile = File.createTempFile("emailattach", ".atch", savedir );
ema.path = savefile.getAbsolutePath();
ema.size = part.getSize();
vema.add(ema);
ema.size = saveFile(savefile, part);
}
} else if ((disposition != null) &&
(disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE) )
){
// Check if plain
MimeBodyPart mbp = (MimeBodyPart)part;
if (mbp.isMimeType("text/plain")) {
Log.Debug("Mime type is plain");
email.body += (String)mbp.getContent();
} else {
Log.Debug("Save file (%s)", part.getFileName() );
EMailAttach ema = new EMailAttach();
ema.name = decodeName(part.getFileName());
File savedir = new File(receiving_attachments);
savedir.mkdirs();
File savefile = File.createTempFile("emailattach", ".atch", savedir );
ema.path = savefile.getAbsolutePath();
ema.size = part.getSize();
vema.add(ema);
ema.size = saveFile( savefile, part);
}
}
}
}
// Insert everything into the database:
logic.utils.sql.EMail.insertEMail(ioc, email);
for(int j = 0; j < vema.size(); j++){
vema.get(j).emailid = email.id;
logic.utils.sql.EMail.insertEMailAttach(ioc, vema.get(j) );
}
// commit this message and all of it's attachments
ioc.getDBConnection().commit();
// Finally delete the message from the server.
messages[i].setFlag(Flags.Flag.DELETED, true);
}
// Close connection
folder.close(true); // true tells the mail server to expunge deleted messages.
store.close();
} catch (Exception e){
folder.close(true); // true tells the mail server to expunge deleted messages.
store.close();
throw e;
}
}
protected int saveFile(File saveFile, Part part) throws Exception {
BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(saveFile) );
byte[] buff = new byte[2048];
InputStream is = part.getInputStream();
int ret = 0, count = 0;
while( (ret = is.read(buff)) > 0 ){
bos.write(buff, 0, ret);
count += ret;
}
bos.close();
is.close();
return count;
}
protected String decodeName( String name ) throws Exception {
if(name == null || name.length() == 0){
return "unknown";
}
String ret = java.net.URLDecoder.decode( name, "UTF-8" );
// also check for a few other things in the string:
ret = ret.replaceAll("=\\?utf-8\\?q\\?", "");
ret = ret.replaceAll("\\?=", "");
ret = ret.replaceAll("=20", " ");
return ret;
}
}
```
|
I worked Steven's example a little bit and removed the parts of the code specific to Steven. My code won't read the body of an email if it has attachments. That is fine for my case but you may want to refine it further for yours.
```
package utils;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeBodyPart;
public class IncomingMail {
public static List<Email> downloadPop3(String host, String user, String pass, String downloadDir) throws Exception {
List<Email> emails = new ArrayList<Email>();
// Create empty properties
Properties props = new Properties();
// Get the session
Session session = Session.getInstance(props, null);
// Get the store
Store store = session.getStore("pop3");
store.connect(host, user, pass);
// Get folder
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
try {
// Get directory listing
Message messages[] = folder.getMessages();
for (int i = 0; i < messages.length; i++) {
Email email = new Email();
// from
email.from = messages[i].getFrom()[0].toString();
// to list
Address[] toArray = messages[i] .getRecipients(Message.RecipientType.TO);
for (Address to : toArray) { email.to.add(to.toString()); }
// cc list
Address[] ccArray = null;
try {
ccArray = messages[i] .getRecipients(Message.RecipientType.CC);
} catch (Exception e) { ccArray = null; }
if (ccArray != null) {
for (Address c : ccArray) {
email.cc.add(c.toString());
}
}
// subject
email.subject = messages[i].getSubject();
// received date
if (messages[i].getReceivedDate() != null) {
email.received = messages[i].getReceivedDate();
} else {
email.received = new Date();
}
// body and attachments
email.body = "";
Object content = messages[i].getContent();
if (content instanceof java.lang.String) {
email.body = (String) content;
} else if (content instanceof Multipart) {
Multipart mp = (Multipart) content;
for (int j = 0; j < mp.getCount(); j++) {
Part part = mp.getBodyPart(j);
String disposition = part.getDisposition();
if (disposition == null) {
MimeBodyPart mbp = (MimeBodyPart) part;
if (mbp.isMimeType("text/plain")) {
// Plain
email.body += (String) mbp.getContent();
}
} else if ((disposition != null) && (disposition.equals(Part.ATTACHMENT) || disposition .equals(Part.INLINE))) {
// Check if plain
MimeBodyPart mbp = (MimeBodyPart) part;
if (mbp.isMimeType("text/plain")) {
email.body += (String) mbp.getContent();
} else {
EmailAttachment attachment = new EmailAttachment();
attachment.name = decodeName(part.getFileName());
File savedir = new File(downloadDir);
savedir.mkdirs();
// File savefile = File.createTempFile( "emailattach", ".atch", savedir);
File savefile = new File(downloadDir,attachment.name);
attachment.path = savefile.getAbsolutePath();
attachment.size = saveFile(savefile, part);
email.attachments.add(attachment);
}
}
} // end of multipart for loop
} // end messages for loop
emails.add(email);
// Finally delete the message from the server.
messages[i].setFlag(Flags.Flag.DELETED, true);
}
// Close connection
folder.close(true); // true tells the mail server to expunge deleted messages
store.close();
} catch (Exception e) {
folder.close(true); // true tells the mail server to expunge deleted
store.close();
throw e;
}
return emails;
}
private static String decodeName(String name) throws Exception {
if (name == null || name.length() == 0) {
return "unknown";
}
String ret = java.net.URLDecoder.decode(name, "UTF-8");
// also check for a few other things in the string:
ret = ret.replaceAll("=\\?utf-8\\?q\\?", "");
ret = ret.replaceAll("\\?=", "");
ret = ret.replaceAll("=20", " ");
return ret;
}
private static int saveFile(File saveFile, Part part) throws Exception {
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(saveFile));
byte[] buff = new byte[2048];
InputStream is = part.getInputStream();
int ret = 0, count = 0;
while ((ret = is.read(buff)) > 0) {
bos.write(buff, 0, ret);
count += ret;
}
bos.close();
is.close();
return count;
}
}
```
You also need these two helper classes
```
package utils;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Email {
public Date received;
public String from;
public List<String> to = new ArrayList<String>();
public List<String> cc = new ArrayList<String>();
public String subject;
public String body;
public List<EmailAttachment> attachments = new ArrayList<EmailAttachment>();
}
```
and
```
package utils;
public class EmailAttachment {
public String name;
public String path;
public int size;
}
```
I used this to test the above classes
```
package utils;
import java.util.List;
public class Test {
public static void main(String[] args) {
String host = "some host";
String user = "some user";
String pass = "some pass";
String downloadDir = "/Temp";
try {
List<Email> emails = IncomingMail.downloadPop3(host, user, pass, downloadDir);
for ( Email email : emails ) {
System.out.println(email.from);
System.out.println(email.subject);
System.out.println(email.body);
List<EmailAttachment> attachments = email.attachments;
for ( EmailAttachment attachment : attachments ) {
System.out.println(attachment.path+" "+attachment.name);
}
}
} catch (Exception e) { e.printStackTrace(); }
}
}
```
More info can be found at <http://java.sun.com/developer/onlineTraining/JavaMail/contents.html>
|
download mail attachment with Java
|
[
"",
"java",
"spring",
"email",
"attachment",
""
] |
I'm trying to convert an incoming sting of 1s and 0s from stdin into their respective binary values (where a string such as "11110111" would be converted to 0xF7). This seems pretty trivial but I don't want to reinvent the wheel so I'm wondering if there's anything in the C/C++ standard libs that can already perform such an operation?
|
```
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char * ptr;
long parsed = strtol("11110111", & ptr, 2);
printf("%lX\n", parsed);
return EXIT_SUCCESS;
}
```
For larger numbers, there as a `long long` version, `strtoll`.
|
You can use std::bitset (if then length of your bits is known at compile time)
Though with some program you could break it up into chunks and combine.
```
#include <bitset>
#include <iostream>
int main()
{
std::bitset<5> x(std::string("01011"));
std::cout << x << ":" << x.to_ulong() << std::endl;
}
```
|
Converting string of 1s and 0s into binary value
|
[
"",
"c++",
"c",
"binary",
""
] |
For example if I'm working on Visual Studio 2008, I want the values devenv and 2008 or 9.
The version number is very important...
|
This is going to be PInvoke city...
You'll need to PInvoke the following API's in User32.dll
Win32::GetForegroundWindow() in returns the HWND of the currently active window.
```
/// <summary>
/// The GetForegroundWindow function returns a handle to the foreground window.
/// </summary>
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
```
Win32::GetWindowThreadProcessId(HWND,LPDWORD) returns the PID of a given HWND
```
[DllImport("user32.dll", SetLastError=true)]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
```
In C#
Process.GetProcessByID() takes the PID to create a C# process object
processInstance.MainModule returns a ProcessModule with FileVersionInfo attached.
|
This [project](http://www.codeproject.com/KB/cs/windowhider.aspx) demonstrates the two functions you need: [EnumWindows](http://msdn.microsoft.com/en-us/library/ms633497(VS.85).aspx) and [GetWindowtext](http://msdn.microsoft.com/en-us/library/ms633520(VS.85).aspx)
|
How can I determine the current focused process name and version in C#
|
[
"",
"c#",
"process",
"pinvoke",
"user32",
""
] |
I am writing a dhtml application that creates an interactive simulation of a system. The data for the simulation is generated from another tool, and there is already a very large amount of legacy data.
Some steps in the simulation require that we play "voice-over" clips of audio. I've been unable to find an easy way to accomplish this across multiple browsers.
[Soundmanager2](http://www.schillmania.com/projects/soundmanager2/) comes pretty close to what I need, but it will only play mp3 files, and the legacy data may contain some .wav files as well.
Does anyone have any other libraries that might help?
|
You will have to include a plug-in like Real Audio or QuickTime to handle the .wav file, but this should work...
```
//======================================================================
var soundEmbed = null;
//======================================================================
function soundPlay(which)
{
if (!soundEmbed)
{
soundEmbed = document.createElement("embed");
soundEmbed.setAttribute("src", "/snd/"+which+".wav");
soundEmbed.setAttribute("hidden", true);
soundEmbed.setAttribute("autostart", true);
}
else
{
document.body.removeChild(soundEmbed);
soundEmbed.removed = true;
soundEmbed = null;
soundEmbed = document.createElement("embed");
soundEmbed.setAttribute("src", "/snd/"+which+".wav");
soundEmbed.setAttribute("hidden", true);
soundEmbed.setAttribute("autostart", true);
}
soundEmbed.removed = false;
document.body.appendChild(soundEmbed);
}
//======================================================================
```
|
If you're using Prototype, the Scriptaculous library [has a sound API](http://github.com/madrobby/scriptaculous/wikis/sound). jQuery [appears to have a plugin](http://dev.jquery.com/browser/trunk/plugins/sound/jquery.sound.js?rev=5750), too.
|
Cross-platform, cross-browser way to play sound from Javascript?
|
[
"",
"javascript",
"audio",
"cross-browser",
"cross-platform",
"dhtml",
""
] |
I have an object that needs a test if the object data is valid. The validation itself would be called from the thread that instatiated the object, it looks like this:
```
{
if (_step.Equals(string.Empty)) return false;
if (_type.Equals(string.Empty)) return false;
if (_setup.Equals(string.Empty)) return false;
return true;
}
```
Would it be better to implement this as a property, or as a method, and why? I have read the answers to a [related question](https://stackoverflow.com/questions/164023/what-guidelines-are-appropriate-for-determining-when-to-implement-a-class-membe), but I don't think this specific question is covered there.
|
My personal opinion here would be:
* If the "validate" method mutates the object in any way (which your example doesn't) then make it a method.
* If the object remains un-changed after validation, make it a property.
|
I would say as a Property.
```
if(something.IsValid) { ...
```
looks better then
```
if(something.IsValid()) { ...
```
Also an example from MSDN: <http://msdn.microsoft.com/en-us/library/system.web.ui.page.isvalid(VS.71).aspx>
|
Implement validation as a method or as a property?
|
[
"",
"c#",
""
] |
As it was made clear in my [recent question](https://stackoverflow.com/questions/212009/do-i-have-to-explicitly-call-systemexit-in-a-webstart-application), Swing applications need to explicitly call System.exit() when they are ran using the Sun Webstart launcher (at least as of Java SE 6).
I want to restrict this hack as much as possible and I am looking for a reliable way to detect whether the application is running under Webstart. Right now I am checking that the value of the system property "webstart.version" is not null, but I couldn't find any guarantees in the documentation that this property should be set by future versions/alternative implementations.
Are there any better ways (preferably ones that do not ceate a dependency on the the webstart API?)
|
When your code is launched via javaws, javaws.jar is loaded and the JNLP API classes that you don't want to depend on are available. Instead of testing for a system property that is not guaranteed to exist, you could instead see if a JNLP API class exists:
```
private boolean isRunningJavaWebStart() {
boolean hasJNLP = false;
try {
Class.forName("javax.jnlp.ServiceManager");
hasJNLP = true;
} catch (ClassNotFoundException ex) {
hasJNLP = false;
}
return hasJNLP;
}
```
This also avoids needing to include javaws.jar on your class path when compiling.
Alternatively you could switch to compiling with javaws.jar and catching NoClassDefFoundError instead:
```
private boolean isRunningJavaWebStart() {
try {
ServiceManager.getServiceNames();
return ds != null;
} catch (NoClassDefFoundError e) {
return false;
}
}
```
Using ServiceManager.lookup(String) and UnavailableServiceException is trouble because both are part of the JNLP API. The ServiceManager.getServiceNames() is not documented to throw. We are specifically calling this code to check for a NoClassDefFoundError.
|
Use the javax.jnlp.ServiceManager to retrieve a webstart service.
If it is availabe, you are running under Webstart.
See <http://download.java.net/jdk7/docs/jre/api/javaws/jnlp/index.html>
|
What is the best way to detect whether an application is launched by Webstart
|
[
"",
"java",
"java-web-start",
""
] |
Basically the question is how to get from this:
```
foo_id foo_name
1 A
1 B
2 C
```
to this:
```
foo_id foo_name
1 A B
2 C
```
|
```
SELECT id, GROUP_CONCAT(name SEPARATOR ' ') FROM table GROUP BY id;
```
<https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat>
From the link above, `GROUP_CONCAT`: This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values.
|
```
SELECT id, GROUP_CONCAT( string SEPARATOR ' ') FROM table GROUP BY id
```
More details [here](http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat).
From the link above, `GROUP_CONCAT`: This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values.
|
How to use GROUP BY to concatenate strings in MySQL?
|
[
"",
"sql",
"mysql",
"string",
"aggregate",
"concatenation",
""
] |
I have a modal popup that initially shows some content but expands a div if a checkbox is selected. The modal expands correctly but doesn't recenter unless you scroll up or down. Is there a javascript event I can tack on to my javascript function to recenter the entire modal?
|
Here is what it is:
```
$find('ModalPopupExtenderClientID')._layout();
```
For example:
```
$find('detailsPopUpExtenderId')._layout();
```
and in aspx:
```
<ccl:ModalPopupExtender runat="server" ID="MyPopUpExtender" TargetControlID="pop" PopupControlID="PopUp" BehaviorID="detailsPopUpExtenderId" BackgroundCssClass="ModalBackground" />
```
`BehaviorID` being the property where to set the clientside id.
|
Be careful that this isn't tied to the resize event of the window. If it is, your recentering could trigger a resize event in IE, which would cause an infinte loop.
If it is tied to the resize event, allow 1 or 2 resize events to occur, but then ignore the rest. (I say 2, because in IE, a "restore" event on the window will trigger at least 2 resize events (3 in IE6).
|
Re-center Modal Popup with Javascript
|
[
"",
"asp.net",
"javascript",
""
] |
In a PHP project I'm working on we need to create some DAL extensions to support multiple database platforms. The main pitfall we have with this is that different platforms have different syntaxes - notable MySQL and MSSQL are quite different.
## What would be the best solution to this?
Here are a couple we've discussed:
**Class-based SQL building**
This would involve creating a class that allows you to build SQL querys bit-by-bit. For example:
```
$stmt = new SQL_Stmt('mysql');
$stmt->set_type('select');
$stmt->set_columns('*');
$stmt->set_where(array('id' => 4));
$stmt->set_order('id', 'desc');
$stmt->set_limit(0, 30);
$stmt->exec();
```
It does involve quite a lot of lines for a single query though.
**SQL syntax reformatting**
This option is much cleaner - it would read SQL code and reformat it based on the input and output languages. I can see this being a much slower solution as far as parsing goes however.
|
I'd recommend class-based SQL building and recommend [Doctrine](http://phpdoctrine.org/), [Zend\_Db](http://framework.zend.com/manual/en/zend.db.html) or [MDB2](http://pear.php.net/package/MDB2). And yeah, if it requires more lines to write simple selects but at least you get to rely on a parser and don't need to re-invent the wheel.
Using any DBAL is a trade-off in speed, and not just database execution, but the first time you use either of those it will be more painful than when you are really familiar with it. Also, I'm almost a 100% sure that the code generated is not the fastest SQL query but that's the trade-off I meant earlier.
In the end it's up to you, so even though I wouldn't do it and it sure is not impossible, the question remains if you can actually save time and resources (in the long run) by implementing your own DBAL.
|
A solution could be to have different sets of queries for different platforms with ID's something like
MySql: GET\_USERS = "SELECT \* FROM users"
MsSql: GET\_USERS = ...
PgSql: GET\_USERS = ...
Then on startup you load the needed set of queries and refers then
Db::loadQueries(platform):
$users = $db->query(GET\_USERS)
|
Database Abstraction - supporting multiple syntaxes
|
[
"",
"sql",
"database",
"data-access-layer",
"database-abstraction",
""
] |
I have a trivial console application in .NET. It's just a test part of a larger application. I'd like to specify the "exit code" of my console application. How do I do this?
|
Three options:
* You can return it from `Main` if you declare your `Main` method to return `int`.
* You can call [`Environment.Exit(code)`](https://learn.microsoft.com/en-us/dotnet/api/system.environment.exit).
* You can set the [exit code](https://learn.microsoft.com/en-us/dotnet/api/system.environment.exitcode) using properties: `Environment.ExitCode = -1;`. This will be used if nothing else sets the return code or uses one of the other options above).
Depending on your application (console, service, web application, etc.), different methods can be used.
|
In addition to the answers covering the return int's... a plea for sanity. Please, please define your exit codes in an enum, with Flags if appropriate. It makes debugging and maintenance so much easier (and, as a bonus, you can easily print out the exit codes on your help screen - you do have one of those, right?).
```
enum ExitCode : int {
Success = 0,
InvalidLogin = 1,
InvalidFilename = 2,
UnknownError = 10
}
int Main(string[] args) {
return (int)ExitCode.Success;
}
```
|
How do I specify the exit code of a console application in .NET?
|
[
"",
"c#",
".net",
"exit-code",
""
] |
I understand that server-side validation is an absolute must to prevent malicious users (or simply users who choose to disable javascript) from bypassing client-side validation. But that's mainly to protect your application, not to provide value for those who are running browsers with javascript disabled. Is it reasonable to assume visitors have javascript enabled and simply have an unusable site for those who don't?
|
I browse with NoScript in Firefox, and it always annoys me when I get pages that don't work. That said - know your audience. If you're trying to cater to paranoid computer security professionals - assume they might not have JavaScript enabled. If you're going for a general audience, JavaScript is probably on.
|
Totally depends on who you're aiming at.
If your site or app is for an Intranet, you can make lots of assumptions. If your target audience is bleeding-edge social-networking types, you can assume JavaScript will work. If you anticipate a lot of paranoia sysadmin types, you can assume a bunch of them will be trying to access your site in lynx or have JS turned of for "security reasons."
A good example of this is Amazon -- their approach is driven by their business goals. They are a mass-market site, but for them, locking out users in old/incapable browsers means potential lost sales, so they work hard on non-script fallbacks.
So like lots of these kinds of questions, the answer is not just regurgitating what you've read somewhere about accessibility or progressive enhancement. The real answer is "it depends."
|
Is it reasonable to assume my visitors have javascript enabled?
|
[
"",
"javascript",
""
] |
How can you change the `href` attribute (link target) for a hyperlink using jQuery?
|
Using
```
$("a").attr("href", "http://www.google.com/")
```
will modify the href of all hyperlinks to point to Google. You probably want a somewhat more refined selector though. For instance, if you have a mix of link source (hyperlink) and link target (a.k.a. "anchor") anchor tags:
```
<a name="MyLinks"></a>
<a href="http://www.codeproject.com/">The CodeProject</a>
```
...Then you probably don't want to accidentally add `href` attributes to them. For safety then, we can specify that our selector will only match `<a>` tags with an existing `href` attribute:
```
$("a[href]") //...
```
Of course, you'll probably have something more interesting in mind. If you want to match an anchor with a specific existing `href`, you might use something like this:
```
$("a[href='http://www.google.com/']").attr('href', 'http://www.live.com/')
```
This will find links where the `href` exactly matches the string `http://www.google.com/`. A more involved task might be matching, then updating only part of the `href`:
```
$("a[href^='http://stackoverflow.com']")
.each(function()
{
this.href = this.href.replace(/^http:\/\/beta\.stackoverflow\.com/,
"http://stackoverflow.com");
});
```
The first part selects only links where the href *starts* with `http://stackoverflow.com`. Then, a function is defined that uses a simple regular expression to replace this part of the URL with a new one. Note the flexibility this gives you - any sort of modification to the link could be done here.
|
With jQuery 1.6 and above you should use:
```
$("a").prop("href", "http://www.jakcms.com")
```
The difference between `prop` and `attr` is that `attr` grabs the HTML attribute whereas `prop` grabs the DOM property.
You can find more details in this post: [.prop() vs .attr()](https://stackoverflow.com/questions/5874652/prop-vs-attr)
|
How to change the href attribute for a hyperlink using jQuery
|
[
"",
"javascript",
"html",
"jquery",
"hyperlink",
""
] |
I'd like to how to upgrade the default python installation(2.5.2) supplied with ubuntu 8.04 to python 2.6rc2. I'd like to make 2.6 the default python version on the system and migrate all the other useful installed python libraries installed on 2.5.2 to python 2.6rc2. Please let me know how I can achieve this.
Thanks
Dirk
|
With the warning that I think it's a tremendously bad idea to replace the default Python with an unreleased beta version:
First, install 2.6rc2. You can download the source from the [Python website](http://www.python.org/download/releases/2.6/). Standard `./configure && make && sudo make install` installation style.
Next, remove the `/usr/bin/python` symlink. Do *not* remove `/usr/bin/python2.5`. Add a symlink to 2.6 with `ln -s /usr/local/bin/python2.6 /usr/bin/python`.
Once again, I think this is a terrible idea. There is almost certainly a better way to do whatever you're trying to accomplish.
---
Migrating installed libraries is a much longer process. Look in the `/usr/lib/python2.5/site-packages/` and `/usr/local/lib/python2.5/site-packages/` directories. Any libraries installed to them will need to be re-installed with 2.6. Since you're not using a packaged Python version, you cannot use Ubuntu's packages -- you'll have to manually upgrade all the libraries yourself. Most of them can probably be installed with `sudo easy_install <name>`, but some like PyGTK+ are not so easy. You'll have to follow custom installation procedures for each such library.
|
I have the same issue, and apparently pre-built binaries can be found here:
```
# Python 2.6
deb http://ppa.launchpad.net/doko/ubuntu intrepid main
deb-src http://ppa.launchpad.net/doko/ubuntu intrepid main
```
|
How do I upgrade python 2.5.2 to python 2.6rc2 on ubuntu linux 8.04?
|
[
"",
"python",
"linux",
"ubuntu",
"installation",
""
] |
What's the best way to add the coordinates of a circle to an array in JavaScript? So far I've only been able to do a half circle, but I need a formula that returns the whole circle to two different arrays: `xValues` and `yValues`. (I'm trying to get the coordinates so I can animate an object along a path.)
**Here's what I have so far:**
```
circle: function(radius, steps, centerX, centerY){
var xValues = [centerX];
var yValues = [centerY];
for (var i = 1; i < steps; i++) {
xValues[i] = (centerX + radius * Math.cos(Math.PI * i / steps-Math.PI/2));
yValues[i] = (centerY + radius * Math.sin(Math.PI * i / steps-Math.PI/2));
}
}
```
|
Your loop should be set up like this instead:
```
for (var i = 0; i < steps; i++) {
xValues[i] = (centerX + radius * Math.cos(2 * Math.PI * i / steps));
yValues[i] = (centerY + radius * Math.sin(2 * Math.PI * i / steps));
}
```
* Start your loop at 0
* Step through the entire 2 \* PI range, not just PI.
* You shouldn't have the `var xValues = [centerX]; var yValues = [centerY];` -- the center of the circle is not a part of it.
|
Bresenham's algorithm is way faster. You hear of it in relation to drawing straight lines, but there's a form of the algorithm for circles.
Whether you use that or continue with the trig calculations (which are blazingly fast these days) - you only need to draw 1/8th of the circle. By swapping x,y you can get another 1/8th, and then the negative of x, of y, and of both - swapped and unswapped - gives you points for all the rest of the circle. A speedup of 8x!
|
Circle coordinates to array in Javascript
|
[
"",
"javascript",
"arrays",
"geometry",
"formula",
""
] |
I was just wondering, if by moving complex if else statements and the resulting html markup to the code behind violates some 'MVC' law?
It seems like a great option when faced with inline if else statements that can become extremely unreadable.
|
I prefer not to use the code behind class in my views. This is not because it violates MVC by default, but because I found that the "natural" way (at least for me) is different.
When I face complex HTML markup that relates to purely view concerns, I usually write an extension method for `HtmlHelper` class in order to hide the complexity. Thus I have extensions like `Html.MoneyTextBox()`, `Html.OptionGroup()` and `Html.Pager<T>`.
In other cases when complex conditions arise, usually I missed something from the controller. For example, all issues related to the visibility, readonly or enabled of elements usually stem from something that the controller can provide. In that case instead of passing the model to the view, I create a view model which encapsulates the model and the additional info that the controller can provide in order to simplify the HTML markup. A typical example of view model is the following:
```
public class CustomerInfo
{
public Customer Customer { get; set; }
public bool IsEditable { get; set; } // e.g. based on current user/role
public bool NeedFullAddress { get; set; } // e.g. based on requested action
public bool IsEligibleForSomething { get; set; } // e.g. based on business rule
}
```
That said, the code behind is part of the view, so you can use it freely, if it fits your needs better.
|
It's not horrible to have conditionals in your view. I would keep them in the ASPX not the code behind. However, a conditional often indicates controlling behavior. Consider the following ASPX code:
```
<%if (ViewData["something"] == "foo") {%>
<%=Html.ActionLink("Save", "Save") %>
<%}%>
<%if (ViewData["somethingElse"] == "bar") {%>
<%=Html.ActionLink("Delete", "Delete") %>
<%}%>
```
This set of conditionals represents controlling behavior that is being handled by the view -- i.e., in the wrong place. This behavior is not unit testable. Consider instead:
```
<%foreach (var command in (IList<ICommand>)ViewData["commands"]) {%>
<%=Html.ActionLink(command) %>
<%}%>
```
In this example ActionLink is a custom extension of HtmlHelper that takes our own ICommand specification object. The controller action that renders this view populates ViewData["commands"] based on various conditions. In other words, the controller does the controlling. In the unit tests for this action, we can test that the correct set of commands will be presented under various conditions.
At first this might seem like a hassle compared with quickly throwing a few IFs into the view. The question you have to ask yourself is, "Does this IF represent controlling behavior, and do I want to ensure does not at some point break?"
|
Moving complex conditional statements to code behind
|
[
"",
"c#",
"asp.net-mvc",
"code-behind",
""
] |
I have a very strange problem, when I try to `var_dump` (or `print_r`) a Doctrine Object, my Apache responses with an empty blank page (200 OK header). I can `var_dump` a normal php var like:
```
$dummy = array("a" => 1, "b" =>2);
```
And it works fine. But I can't with any object from any Doctrine class, (like a result from `$connection->query()`, or an instance of a class from my object model with Doctrine).
Anybody knows why this happens?
|
I've had that sometimes when trying to `print_r()` a self-referencing object - it gets into a loop and runs out of memory. Possibly that's what's happening to you.
Try increasing the memory limit (`ini_set('memory_limit', '256M');`) and see if that fixes it.
Edit: I don't think there's an actual fix for this - it's PHP's internal `var_dump` / `print_r` that don't limit depth on recursion (or don't do it properly, at least). If you install the [XDebug](http://xdebug.org/) extension, this can replace the built-in `var_dump` with a version that handles recursion much better.
|
Lazy load proxies always contain an instance of Doctrine’s EntityManager and all its dependencies.
Therefore a `var_dump` will possibly dump a very large recursive structure which is impossible to render and read. You have to use `\Doctrine\Common\Util\Debug::dump()` to restrict the dumping to a human readable level. Note that the default depth for this function is set to 2 (it's the second parameter)
|
Why var_dump a Doctrine Objects kill my Apache?
|
[
"",
"php",
"doctrine",
""
] |
I have a series of datetime objects and would like to calculate the average delta between them.
For example, if the input was `(2008-10-01 12:15:00, 2008-10-01 12:25:00, 2008-10-01 12:35:00)`, then the average delta would be exactly 00:10:00, or 10 minutes.
Any suggestions on how to calculate this using Python?
|
You can subtract each successive date from the one prior (resulting in a timedelta object which represents the difference in days, seconds). You can then average the timedelta objects to find your answer.
|
As far as algorithms go, that's an easy one. Just find the max and min datetimes, take the difference, and divide by the number of datetimes you looked at.
If you have an array a of datetimes, you can do:
```
mx = max(a)
mn = min(a)
avg = (mx-mn)/(len(a)-1)
```
to get back the average difference.
EDIT: fixed the off-by-one error
|
Average difference between dates in Python
|
[
"",
"python",
"algorithm",
"datetime",
""
] |
This may be a matter of style, but there's a bit of a divide in our dev team and I wondered if anyone else had any ideas on the matter...
Basically, we have some debug print statements which we turn off during normal development. Personally I prefer to do the following:
```
//---- SomeSourceFile.cpp ----
#define DEBUG_ENABLED (0)
...
SomeFunction()
{
int someVariable = 5;
#if(DEBUG_ENABLED)
printf("Debugging: someVariable == %d", someVariable);
#endif
}
```
Some of the team prefer the following though:
```
// #define DEBUG_ENABLED
...
SomeFunction()
{
int someVariable = 5;
#ifdef DEBUG_ENABLED
printf("Debugging: someVariable == %d", someVariable);
#endif
}
```
...which of those methods sounds better to you and why? My feeling is that the first is safer because there is always something defined and there's no danger it could destroy other defines elsewhere.
|
My initial reaction was *`#ifdef`, of course*, but I think `#if` actually has some significant advantages for this - here's why:
First, you can use `DEBUG_ENABLED` in preprocessor *and* compiled tests. Example - Often, I want longer timeouts when debug is enabled, so using `#if`, I can write this
```
DoSomethingSlowWithTimeout(DEBUG_ENABLED? 5000 : 1000);
```
... instead of ...
```
#ifdef DEBUG_MODE
DoSomethingSlowWithTimeout(5000);
#else
DoSomethingSlowWithTimeout(1000);
#endif
```
Second, you're in a better position if you want to migrate from a `#define` to a global constant. `#define`s are usually frowned on by most C++ programmers.
And, Third, you say you've a divide in your team. My guess is this means different members have already adopted different approaches, and you need to standardise. Ruling that `#if` is the preferred choice means that code using `#ifdef` will compile -and run- even when `DEBUG_ENABLED` is false. And it's *much* easier to track down and remove debug output that is produced when it shouldn't be than vice-versa.
Oh, and a minor readability point. You should be able to use true/false rather than 0/1 in your `#define`, and because the value is a single lexical token, it's the one time you don't need parentheses around it.
```
#define DEBUG_ENABLED true
```
instead of
```
#define DEBUG_ENABLED (1)
```
|
They're both hideous. Instead, do this:
```
#ifdef DEBUG
#define D(x) do { x } while(0)
#else
#define D(x) do { } while(0)
#endif
```
Then whenever you need debug code, put it inside `D();`. And your program isn't polluted with hideous mazes of `#ifdef`.
|
#ifdef vs #if - which is better/safer as a method for enabling/disabling compilation of particular sections of code?
|
[
"",
"c++",
"c",
"if-statement",
"coding-style",
"c-preprocessor",
""
] |
Here's the problem:
```
split=re.compile('\\W*')
```
This regular expression works fine when dealing with regular words, but there are occasions where I need the expression to include words like `k&auml;ytt&auml;j&aml;auml;`.
What should I add to the regex to include the `&` and `;` characters?
|
You probably want to take the problem reverse, i.e. finding all the character without the spaces:
```
[^ \t\n]*
```
Or you want to add the extra characters:
```
[a-zA-Z0-9&;]*
```
In case you want to match HTML entities, you should try something like:
```
(\w+|&\w+;)*
```
|
I would treat the entities as a unit (since they also can contain numerical character codes), resulting in the following regular expression:
```
(\w|&(#(x[0-9a-fA-F]+|[0-9]+)|[a-z]+);)+
```
This matches
* either a word character (including “`_`”), or
* an HTML entity consisting of
+ the character “`&`”,
- the character “`#`”,
* the character “`x`” followed by at least one hexadecimal digit, or
* at least one decimal digit, or
- at least one letter (= named entity),
+ a semicolon
* at least once.
/EDIT: Thanks to ΤΖΩΤΖΙΟΥ for pointing out an error.
|
Looking for a regular expression including alphanumeric + "&" and ";"
|
[
"",
"python",
"regex",
"encoding",
""
] |
I have saved input from a textarea element to a TEXT column in MySQL. I'm using PHP to pull that data out of the database and want to display it in a p element while still showing the whitespace that the user entered (e.g. multiple spaces and newlines). I've tried a pre tag but it doesn't obey the width set in the containing div element. Other than creating a PHP function to convert spaces to   and new lines to br tags, what are my options? I'd prefer a clean HTML/CSS solution, but any input is welcome! Thanks!
|
You can cause the text inside the `pre` to wrap by using the following CSS
```
pre {
white-space: pre-wrap; /* css-3 */
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}
```
Taken from [this site](http://users.tkk.fi/~tkarvine/pre-wrap-css3-mozilla-opera-ie.html)
It's currently defined in CSS3 (which is not yet a finished standard) but most browsers seem to support it as per the comments.
|
You could just use PHP's [nl2br function](https://www.php.net/nl2br).
|
Displaying whitespace in HTML when pulling from MySQL TEXT column
|
[
"",
"php",
"mysql",
"html",
""
] |
I'm attempting to put together some basic report screens. I've got some fairly complicated SQL queries that I'm feeding into ActiveRecord's find\_by\_sql method. The problem I am having here is that I am losing the order of the columns as given in the original query. I'm assuming that this is because the Hash class does not preserve entry order of its keys.
Is there a way around this problem? Should I be using a different method then find\_by\_sql for my queries?
|
You're correct in that the Ruby Hash does not preserve order. That's part of the point, really - you access it using the key.
I assume your query is written to deliver the columns in the order that you want to output them and you were hoping to output the values via a loop? Seems like a decent enough idea, but I can't think of a way to achieve it without at least some extra work.
What I'd recommend is to explicitly access the columns by key in your template, since you're probably going to end up applying styles, formatting using helper functions like number\_with\_delimiter, that kind of thing.
To get something like the shortcut mentioned above, I suppose you could create an array of symbols in the order required and pull the values out of the hash in a loop. Something like this? (please excuse the potentially dodgy erb: I'm a [haml](http://haml.hamptoncatlin.com/) user!)
```
<% for row in @report.rows %>
<tr>
<% for col in [:a, :b, :c] %>
<td><%= row[col] %></td>
<% end %>
</tr>
<% end %>
```
|
I like to use [Ruport](https://ruport.github.io/) for reporting. It has good ActiveRecord integration and it enables you to control column order and pretty much anything else. And it's sufficiently simple to use that I don't consider it overkill even for "basic" reports.
|
Column order of results from rails ActiveRecord find_by_sql call
|
[
"",
"sql",
"ruby-on-rails",
"ruby",
"activerecord",
""
] |
I've got a web application that is running against Windows Authentication using our Active Directory. I've got a new requirement to pull some personal information through from the Active Directory entry. What would be the easiest way to get access to this information?
|
Accessing the user directly through a DirectoryEntry seems like the most straightforward approach. Here are some AD-related tidbits I learned from my first AD-related project:
* In a URI, write LDAP in lowercase. Otherwise you'll get a mystery error. I spent more than a day on this depressing issue...
* To clear a single-valued property, set it to an empty string, not null. Null causes an exception.
* To clear a multi-valued property, use the *DirectoryEntry.Property.Clear()* method.
* The Active Directory schema reference will say which data type a value will be and whether it is multi-value or single-value.
* You do not need to manually RefreshCache() on a Directoryentry but if you ever use it and specify which properties to cache, know that it will not auto-retrieve any other properties in the future.
* A COMException can be thrown at absolutely any time you use the classes in System.DirectoryServices. Keep an eye on those try blocks. Do not assume anything is safe.
You'll probably need to use DirectorySearcher to get your user's directory entry if you don't know its path (which you wouldn't, just by having him logged in). Using it was fairly easy but beware of the quirks in LDAP syntax; namely, having to encode non-ASCII (and other?) characters. The search string you'd use would probably be something like: *(&(sAMAccountName=whatever)(class=user))*. This is off the top of my head and may be slightly incorrect.
The [Active Directory schema reference](http://msdn.microsoft.com/en-us/library/ms675085(VS.85).aspx) will be useful. Do understand that the schema can be modified and extended (e.g. installing Exchange will add mailbox information to users).
[AD Explorer](http://technet.microsoft.com/en-us/sysinternals/bb963907.aspx) is a useful tool which you can use for debugging and low-level AD data management. I've found it useful when I know which property I want to set but cannot find the right dialog box in the AD management tool.
|
You might find the following snippet useful as a starter.
```
public static bool IsUserInGroup(string lanid, string group)
{
DirectoryEntry entry = new DirectoryEntry("LDAP://" + LDAPPATH);
if(entry != null)
{
entry.Username=@"LDAPUSER";
entry.Password="LDAPPASSWORD";
DirectorySearcher srch = new DirectorySearcher(entry);
srch.Filter = String.Format("(&(objectClass=person)(sAMAccountName={0}))", lanid);
srch.PropertiesToLoad.Add("memberOf");
SearchResult result = srch.FindOne();
if(result != null)
{
if(result.Properties.Contains("memberOf"))
{
string lookfor = String.Format("cn={0},", group.ToLower());
foreach(string memberOf in result.Properties["memberOf"])
{
if(memberOf.ToLower().StartsWith(lookfor))
return true;
}
}
}
return false;
}
throw new Exception(String.Format("Could not get Directory lanid:{0}, group{1}", lanid, group));
}
```
|
Active Directory: Retrieve User information
|
[
"",
"c#",
"active-directory",
""
] |
By that I mean, what do I need to do to have useful assertions in my code?
MFC is quite easy, i just use ASSERT(something).
What's the non-MFC way?
**Edit:** Is it possible to stop assert breaking in assert.c rather than than my file which called assert()?
**Edit:** What's the difference between `<assert.h>` & `<cassert>`?
**Accepted Answer:** Loads of great answers in this post, I wish I could accept more than one answer (or someone would combine them all). So answer gets awarded to Ferruccio (for first answer).
|
```
#include <cassert>
assert(something);
```
and for compile-time checking, Boost's static asserts are pretty useful:
```
#include <boost/static_assert.hpp>
BOOST_STATIC_ASSERT(sizeof(int) == 4); // compile fails if ints aren't 32-bit
```
|
It depends on whether or not you are looking for something that works outside of Visual C++. It also depends on what type of assertion you are looking for.
There are a few types of assertions:
1. **Preprocessor**
These assertions are done using the preprocessor directive `#error`
Preprocessor assertions are only evaluated during the preprocessing phase, and therefore are not useful for things such as templates.
2. **Execute Time**
These assertions are done using the `assert()` function defined in `<cassert>`
Execute time assertions are only evaluated at run-time. And as BoltBait pointed out, are not compiled in if the `NDEBUG` macro has been defined.
3. **Static**
These assertions are done, as you said, by using the `ASSERT()` macro, but only if you are using MFC. I do not know of another way to do static assertions that is part of the C/C++ standard, however, the Boost library offers another solution: `static_assert`.
The `static_assert` function from the Boost library is something that is going to be added in the [C++0x standard](http://en.wikipedia.org/wiki/C++0x).
As an additional warning, the `assert()` function that Ferruccio suggested does not have the same behavior as the MFC `ASSERT()` macro. The former is an execute time assertion, while the later is a static assertion.
I hope this helps!
|
What is the best way of implementing assertion checking in C++?
|
[
"",
"c++",
"debugging",
"assert",
"debugbreak",
""
] |
I've often heard criticism of the lack of thread safety in the Swing libraries. Yet, I am not sure as to what I would be doing in my own code with could cause issues:
In what situations does the fact Swing is not thread safe come into play ?
What should I actively avoid doing ?
|
1. Never do long running tasks in response to a button, event, etc as these are on the event thread. If you block the event thread, the ENTIRE GUI will be completely unresponsive resulting in REALLY pissed off users. This is why Swing seems slow and crusty.
2. Use Threads, Executors, and SwingWorker to run tasks NOT ON THE EDT ( event dispatch thread).
3. Do not update or create widgets outside of the EDT. Just about the only call you can do outside of the EDT is Component.repaint(). Use SwingUtilitis.invokeLater to ensure certain code executes on the EDT.
4. Use [EDT Debug Techniques](http://weblogs.java.net/blog/alexfromsun/archive/2006/02/debugging_swing.html) and a smart look and feel (like [Substance](https://substance.dev.java.net/), which checks for EDT violation)
If you follow these rules, Swing can make some very attractive and RESPONSIVE GUIs
An example of some REALLY awesome Swing UI work: [Palantir Technologies](http://www.palantirtech.com/). Note: I DO NOT work for them, just an example of awesome swing. Shame no public demo... Their [blog](http://blog.palantirtech.com/) is good too, sparse, but good
|
This is one of those questions that makes me glad I purchased [Robinson & Vorobiev's book on Swing](http://www.manning.com/robinson2/).
**Anything that accesses the state of a `java.awt.Component` should be run inside the EDT, with three exceptions:** anything specifically documented as thread-safe, such as `repaint()`, `revalidate()`, and `invalidate()`; any Component in a UI that has not yet been *realized*; and any Component in an Applet before that Applet's `start()` has been called.
Methods specially made thread-safe are so uncommon that it's often sufficient to simply remember the ones that are; you can also usually get away with assuming there are no such methods (it's perfectly safe to wrap a repaint call in a SwingWorker, for example).
*Realized* means that the Component is either a top-level container (like JFrame) on which any of `setVisible(true)`, `show()`, or `pack()` has been called, or it has been added to a realized Component. This means it's perfectly fine to build your UI in the main() method, as many tutorial examples do, since they don't call `setVisible(true)` on the top-level container until every Component has been added to it, fonts and borders configured, etc.
For similar reasons, it's perfectly safe to build your applet UI in its `init()` method, and then call `start()` after it's all built.
Wrapping subsequent Component changes in Runnables to send to `invokeLater()` becomes easy to get right after doing it only a few times. The one thing I find annoying is reading the state of a Component (say, `someTextField.getText()`) from another thread. Technically, this has to be wrapped in `invokeLater()`, too; in practice, it can make the code ugly fast, and I often don't bother, or I'm careful to grab that information at initial event handling time (typically the right time to do it in most cases anyway).
|
Java: Swing Libraries & Thread Safety
|
[
"",
"java",
"multithreading",
"swing",
""
] |
I'm a total newbie, but I was writing a little program that worked on strings in C# and I noticed that if I did a few things differently, the code executed significantly faster.
So it had me wondering, how do you go about clocking your code's execution speed? Are there any (free)utilities? Do you go about it the old-fashioned way with a System.Timer and do it yourself?
|
What you are describing is known as performance profiling. There are many programs you can get to do this such as [Jetbrains profiler](http://www.jetbrains.com/profiler/) or [Ants profiler](http://www.red-gate.com/products/ants_profiler/index.htm), although most will slow down your application whilst in the process of measuring its performance.
To hand-roll your own performance profiling, you can use [System.Diagnostics.Stopwatch](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.stopwatch) and a simple Console.WriteLine, like you described.
Also keep in mind that the C# JIT compiler optimizes code depending on the type and frequency it is called, so play around with loops of differing sizes and methods such as recursive calls to get a feel of what works best.
|
[ANTS Profiler from RedGate](http://www.red-gate.com/products/ants_profiler/index.htm) is a really nice performance profiler. [dotTrace Profiler from JetBrains](http://www.jetbrains.com/profiler/) is also great. These tools will allow you to see performance metrics that can be drilled down the each individual line.
Scree shot of ANTS Profiler:
[ANTS http://www.red-gate.com/products/ants\_profiler/images/app/timeline\_calltree3.gif](http://www.red-gate.com/products/ants_profiler/images/app/timeline_calltree3.gif)
If you want to ensure that a specific method stays within a specific performance threshold during unit testing, I would use the [`Stopwatch` class](http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx) to monitor the execution time of a method one ore many times in a loop and calculate the average and then [`Assert`](http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.assert(VS.80).aspx) against the result.
|
Testing your code for speed?
|
[
"",
"c#",
"performance",
"profiling",
"timing",
""
] |
We're getting ready to translate our PHP website into various languages, and the gettext support in PHP looks like the way to go.
All the tutorials I see recommend using the english text as the message ID, i.e.
gettext("Hi there!")
But is that really a good idea? Let's say someone in marketing wants to change the text to "Hi there, y'all!". Then don't you have to update all the language files because that string -- which is actually the message ID -- has changed?
Is it better to have some kind of generic ID, like "hello.message", and an english translations file?
|
I use meaningful IDs such as "`welcome_back_1`" which would be "`welcome back, %1`" etc. I always have English as my "base" language so in the worst case scenario when a specific language doesn't have a message ID, I fall-back on English.
I don't like to use actual English phrases as message ID's because if the English changes so does the ID. This might not affect you much if you use some automated tools, but it bothers me. I don't like to use simple codes (like msg3975) because they don't mean anything, so reading the code is more difficult unless you litter comments everywhere.
|
Wow, I'm surprised that no one is advocating using the English as a key. I used this style in a couple of software projects, and IMHO it worked out pretty well. The code readability is great, and if you change an English string it becomes obvious that the message needs to be considered for re-translation (which is a good thing).
In the case that you're only correcting spelling or making some other change that definitely doesn't require translation, it's a simple matter to update the IDs for that string in the resource files.
That said, I'm currently evaluating whether or not to carry this way of doing I18N forward to a new project, so it's good to hear some thoughts on why it might not be a good idea.
|
Gettext: Is it a good idea for the message ID to be the english text?
|
[
"",
"php",
"internationalization",
"gettext",
""
] |
Most python frameworks will have a development webserver of some kind that will have a warning that it isn't for use as production servers. How much different do they tend to be from their production equivalents?
I haven't quite decided which framework to go with, much less what production server to use, so it's kinda difficult for me to pin this down to a "compare development server x to production server y." So with that said, let me make the question a little bit more precise: In your past experience with a python framework, how much time did you have to spend getting your application up and running with a production system once its been developed on a development server? Or did you skip the development server and develop your app on a server that's more like what you will use in production?
|
The lower environments should try to match the production environment as closely as possible given the resources available. This applies to all development efforts regardless of whether they are python-based or even web-based. In practical terms, most organizations are not willing to spend that type of money. In this case try to make at least the environment that is directly below production as close to production as possible.
Some of the variable to keep in mind are:
* many times there are multiple machines (app server, database server, web server, load balancers, fire walls, etc) in a production. Keep these all in mind.
* Operating Systems
* number of CPUs. Moving from a one CPU lower environment to a multi core production environment can expose multi-threading issues that were not tested
* load balancing. Many times lower environments are not load balanced. If you are replicating sessions (for instance) across multiple production app servers, you should try to do the same in a lower environment
* Software / library versions
|
Generally, they are same in terms of the settings which are required to run the applications which include the environment setting.
However, the clients genereally have dev systems which are less powerful in terms of the processing power and other h/w resources. I have seen using them virtual servers in dev evironment since they generally have multiple projects going on in parallel an this helps them reducing the cost.
|
How close are development webservers to production webservers?
|
[
"",
"python",
"webserver",
"web-frameworks",
""
] |
I have been looking at a few options for enabling localization and internationalization of a dynamic php application. There appears to be a variety of tools available such as gettext and Yahoo's R3 and I am interested in hearing from both developers and translators about which tools are good to use and what functionality is important in easing the task of implementation and translation.
|
PHP gettext implementation works very smoothly. And po files with po edit and gettext are about as good a way as you can get to deal with localization bearing in mind that no solution of this kind can completely handle the complexities of the various languages. For example, the gettext method is very good on plural forms, but nothing I've seen can handle things like conjugation.
For more info see my post here: [How do you build a multi-language web site?](https://stackoverflow.com/questions/39562/how-do-you-build-a-multi-language-web-site#41379)
|
We've been tinkering with[Zend\_Translate](http://framework.zend.com/manual/en/zend.translate.html), since we use the Zend Framework anyway. It's very well documented and so far extremly solid.
In the past, I've pretty much used my own *home-grown* solution mostly. Which involves language files with constants or variables which hold all text parts and are just echo'ed in the view/template later on.
As for gettext, in the past I've heard references about PHP's gettext implementation being faulty, but I can't really back that up nor do I have any references right now.
|
What are good tools/frameworks for i18n of a php codebase?
|
[
"",
"php",
"internationalization",
""
] |
Trying to create a user account in a test. But getting a Object reference is not set to an instanve of an object error when running it.
Here's my MemberShip provider class, it's in a class library MyCompany.MyApp.Domain.dll:
```
using System;
using System.Collections.Generic;
using System.Web.Security;
namespace MyCompany.MyApp.Domain
{
public class MyMembershipProvider : SqlMembershipProvider
{
const int defaultPasswordLength = 8;
private int resetPasswordLength;
public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
{
resetPasswordLength = defaultPasswordLength;
string resetPasswordLengthConfig = config["resetPasswordLength"];
if (!String.IsNullOrEmpty(resetPasswordLengthConfig))
{
config.Remove("resetPasswordLength");
if (!int.TryParse(resetPasswordLengthConfig, out resetPasswordLength))
{
resetPasswordLength = defaultPasswordLength;
}
}
base.Initialize(name, config);
}
public override string GeneratePassword()
{
return Utils.PasswordGenerator.GeneratePasswordAsWord(resetPasswordLength);
}
}
}
```
Here's my App.Config for my seperate Test Class Library MyCompany.MyApp.Doman.Test.dll that references my business domain library above:
```
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="SqlServer" connectionString="data source=mycomp\SQL2008;Integrated Security=SSPI;Initial Catalog=myDatabase" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<membership defaultProvider="MyMembershipProvider" userIsOnlineTimeWindow="15">
<providers>
<clear/>
<add name="MyMembershipProvider"
type="MyCompany.MyApp.Domain.MyMembershipProvider,MyCompany.MyApp.Domain"
connectionStringName="SqlServer"
applicationName="MyApp"
minRequiredNonalphanumericCharacters="0"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="true"
passwordFormat="Hashed"/>
</providers>
</membership>
</system.web>
</configuration>
```
Here's my method that throws "Object reference is not set to an instanve of an object"
```
public class MemberTest
{
public static void CreateAdminMemberIfNotExists()
{
MembershipCreateStatus status;
status = MembershipCreateStatus.ProviderError;
MyMembershipProvider provider = new MyMembershipProvider();
provider.CreateUser("Admin", "password", "someone@somewhere.co.uk", "Question", "Answer", true, Guid.NewGuid(), out status);
}
}
```
it throws on the provider.CreateUser line
|
I'm quite sure you should call provider.Initialize(...) in your test code before calling CreateUser.
|
Well not quite anyone had the answer. csgero was on the right track though initialize was the problem. But just calling that directly was not a solution. This works:
```
public class MemberTest
{
public static void CreateAdminMemberIfNotExists()
{
MembershipCreateStatus status;
MembershipUser member = Membership.CreateUser("Admin", "password", "email@somewhere.co.uk", "Question", "Answer", true, out status);
}
}
```
I believe instantiating my membership provider directly requires setting the config properties typically stored in the app.config or web.config and then calling initialize. Calling the static CreateUser method on the Mebership class however causes the config to be read, then the type specified in the config is parsed, loaded and initialised.
|
Unit test Custom membership provider with NUnit throws null reference error
|
[
"",
"c#",
".net",
"unit-testing",
"nunit",
"membership",
""
] |
Can I run the python interpreter without generating the compiled .pyc files?
|
From ["What’s New in Python 2.6 - Interpreter Changes"](http://docs.python.org/dev/whatsnew/2.6.html#interpreter-changes):
> Python can now be prevented from
> writing .pyc or .pyo files by
> supplying the [-B](http://docs.python.org/using/cmdline.html#cmdoption-B) switch to the Python
> interpreter, or by setting the
> [PYTHONDONTWRITEBYTECODE](http://docs.python.org/using/cmdline.html#envvar-PYTHONDONTWRITEBYTECODE) environment
> variable before running the
> interpreter. This setting is available
> to Python programs as the
> [`sys.dont_write_bytecode`](http://docs.python.org/library/sys.html#sys.dont_write_bytecode) variable, and
> Python code can change the value to
> modify the interpreter’s behaviour.
So run your program as `python -B prog.py`.
Update 2010-11-27: Python 3.2 addresses the issue of cluttering source folders with `.pyc` files by introducing a special `__pycache__` subfolder, see [What's New in Python 3.2 - PYC Repository Directories](http://docs.python.org/dev/whatsnew/3.2.html#pep-3147-pyc-repository-directories).
#### NOTE: The default behavior is to generate the bytecode and is done for "performance" reasons (for more information see here for [python2](https://www.python.org/dev/peps/pep-0304/) and see here for [python3](https://www.python.org/dev/peps/pep-3147/)).
* The generation of bytecode .pyc files is a form of [caching](https://en.wikipedia.org/wiki/Cache_(computing)) (i.e. greatly improves average performance).
* Configuring python with `PYTHONDONTWRITEBYTECODE=1` can be bad for python performance (for python2 see <https://www.python.org/dev/peps/pep-0304/> and for python3 see <https://www.python.org/dev/peps/pep-3147/> ).
* If you are interested in the performance impact please see here <https://github.com/python/cpython> .
|
```
import sys
sys.dont_write_bytecode = True
```
|
How to avoid .pyc files?
|
[
"",
"python",
""
] |
[This question](https://stackoverflow.com/questions/57168/how-to-copy-a-row-from-one-sql-server-table-to-another) comes close to what I need, but my scenario is slightly different. The source table and destination table are the same and the primary key is a uniqueidentifier (guid). When I try this:
```
insert into MyTable
select * from MyTable where uniqueId = @Id;
```
I obviously get a primary key constraint violation, since I'm attempting to copy over the primary key. Actually, I don't want to copy over the primary key at all. Rather, I want to create a new one. Additionally, I would like to selectively copy over certain fields, and leave the others null. To make matters more complex, I need to take the primary key of the original record, and insert it into another field in the copy (PreviousId field).
I'm sure there is an easy solution to this, I just don't know enough TSQL to know what it is.
|
Try this:
```
insert into MyTable(field1, field2, id_backup)
select field1, field2, uniqueId from MyTable where uniqueId = @Id;
```
Any fields not specified should receive their default value (which is usually NULL when not defined).
|
I like this solution. I only have to specify the identity column(s).
```
SELECT * INTO TempTable FROM MyTable_T WHERE id = 1;
ALTER TABLE TempTable DROP COLUMN id;
INSERT INTO MyTable_T SELECT * FROM TempTable;
DROP TABLE TempTable;
```
The "id"-column is the identity column and that's the only column I have to specify. It's better than the other way around anyway. :-)
I use SQL Server. You may want to use "`CREATE TABLE`" and "`UPDATE TABLE`" at row 1 and 2.
Hmm, I saw that I did not really give the answer that he wanted. He wanted to copy the id to another column also. But this solution is nice for making a copy with a new auto-id.
I edit my solution with the idéas from Michael Dibbets.
```
use MyDatabase;
SELECT * INTO #TempTable FROM [MyTable] WHERE [IndexField] = :id;
ALTER TABLE #TempTable DROP COLUMN [IndexField];
INSERT INTO [MyTable] SELECT * FROM #TempTable;
DROP TABLE #TempTable;
```
You can drop more than one column by separating them with a ",".
The :id should be replaced with the id of the row you want to copy.
MyDatabase, MyTable and IndexField should be replaced with your names (of course).
|
How do you copy a record in a SQL table but swap out the unique id of the new row?
|
[
"",
"sql",
"sql-server",
"sql-server-2005",
"t-sql",
""
] |
I'm trying to serialize objects from a database that have been retrieved with Hibernate, and I'm only interested in the objects' actual data in its entirety (cycles included).
Now I've been working with [XStream](http://xstream.codehaus.org/), which seems powerful. The problem with XStream is that it looks all too blindly on the information. It recognizes Hibernate's PersistentCollections as they are, with all the Hibernate metadata included. I don't want to serialize those.
So, is there a reasonable way to extract the original Collection from within a PersistentCollection, and also initialize all referring data the objects might be pointing to. Or can you recommend me to a better approach?
(The results from [Simple](http://simple.sourceforge.net/) seem perfect, but it can't cope with such basic util classes as Calendar. It also accepts only one annotated object at a time)
|
solution described here worked well for me: <http://jira.codehaus.org/browse/XSTR-226>
the idea is to have custom XStream converter/mapper for hibernate collections, which will extract actual collection from hibernate one and will call corresponding standard converter (for ArrayList, HashMap etc.)
|
I recommend a simpler approach: user dozer: <http://dozer.sf.net>. Dozer is a bean mapper, you can use it to convert, say, a PersonEJB to an object of the same class. Dozer will recursively trigger all proxy fecthes through getter() calls, and will also convert src types to dest types (let's say java.sql.date to java.utilDate).
Here's a snippet:
```
MapperIF mapper = DozerBeanMapperSingletonWrapper.getInstance();
PersonEJB serializablePerson = mapper.map(myPersonInstance, PersonEJB.class);
```
Bear in mind, as dozer walks through your object tree it will trigger the proxy loading one by one, so if your object graph has many proxies you will see many queries, which can be expensive.
|
How to Serialize Hibernate Collections Properly?
|
[
"",
"java",
"hibernate",
"serialization",
"collections",
""
] |
I am trying to save data to a database on a button push, but the variables seem to be private by the nature of where they are defined. I have tried to move where they are defined, but this seems to produce other errors.
Given a fix, why was it fixed that way?
The code follows.
```
namespace enable
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
OleDbConnection favouriteConnection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\\\192.168.123.5\\Share\\Matt\\BugTypes.mdb");
string strSQL = "SELECT CategoryName, Show " + "FROM [Categories] WHERE Show = 'Yes' " + "ORDER BY CategoryName";
OleDbDataAdapter adapter = new OleDbDataAdapter(strSQL, favouriteConnection);
OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(adapter);
DataTable dTable = new DataTable();
adapter.Fill(dTable);
BindingSource bSource = new BindingSource();
bSource.DataSource = dTable;
dataGridView1.DataSource = bSource;
adapter.Update(dTable);
}
private void button1_Click(object sender, EventArgs e)
{
adapter.Update(dTable);//this is the button that needs to do the save, but can't see the variables.
}
}
}
```
|
You're declaring `dTable` and `adapter` in the constructor, so it goes out of scope as soon as the constructor is completed.
You want to move the variable declarations out into the main class, like:
```
public partial class Form1 : Form
{
private DataTable dTable;
private OleDbDataAdapter adapter;
Public Form1()
{
... your setup here ...
dTable = new DataTable();
... etc ...
}
}
```
|
```
namespace enable
{
public partial class Form1 : Form
{
OleDbDataAdapter adapter;
DataTable dTable = new DataTable();
public Form1()
{
InitializeComponent();
OleDbConnection favouriteConnection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\\\192.168.123.5\\Share\\Matt\\BugTypes.mdb");
string strSQL = "SELECT CategoryName, Show " + "FROM [Categories] WHERE Show = 'Yes' " + "ORDER BY CategoryName";
adapter = new OleDbDataAdapter(strSQL, favouriteConnection);
OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(adapter);
adapter.Fill(dTable);
BindingSource bSource = new BindingSource();
bSource.DataSource = dTable;
dataGridView1.DataSource = bSource;
adapter.Update(dTable);
}
private void button1_Click(object sender, EventArgs e)
{
adapter.Update(dTable);//this is the button that needs to do the save, but can't see the variables.
}
}
}
```
You need to change DataAdapter and the dataTable scope to be accesible to the button click method event. If you declare them on the constructor they cannot be acceced on other methods, you need to declare them as object fields to be "global" to your object instance.
You need to find out what scope need each variable, you can have a local scope, that is, declared inside a method or a class scope, declared outside a method.
|
Help someone new to C# variables
|
[
"",
"c#",
"variables",
""
] |
What are the easiest steps to make a small circuit with an LED flash from a C/C++ program?
I would prefer the least number of dependencies and packages needed.
* What port would I connect something into?
* Which compiler would I use?
* How do I send data to that port?
* Do I need to have a micro-processor? If not I don't want to use one for this simple project.
EDIT: Interested in any OS specific solutions.
|
Here's a tutorial on doing it with a [parallel port](http://ashishrd.blogspot.com/2006/11/controlling-leds-with-parallel-port.html).
Though I would recommend an [Arduino](http://www.arduino.cc) which can be purchased very cheaply and would only involve the following code:
```
/* Blinking LED
* ------------
*
* turns on and off a light emitting diode(LED) connected to a digital
* pin, in intervals of 2 seconds. Ideally we use pin 13 on the Arduino
* board because it has a resistor attached to it, needing only an LED
*
* Created 1 June 2005
* copyleft 2005 DojoDave <http://www.0j0.org>
* http://arduino.berlios.de
*
* based on an orginal by H. Barragan for the Wiring i/o board
*/
int ledPin = 13; // LED connected to digital pin 13
void setup()
{
pinMode(ledPin, OUTPUT); // sets the digital pin as output
}
void loop()
{
digitalWrite(ledPin, HIGH); // sets the LED on
delay(1000); // waits for a second
digitalWrite(ledPin, LOW); // sets the LED off
delay(1000); // waits for a second
}
```

<http://www.arduino.cc/en/Tutorial/BlinkingLED>
|
**Which port?** Parallel port is my favorite choice since it outputs +5V (TTL logic level) and is very straightforward to program. Most parallel ports have enough power to drive an LED. It's important to remember that computer ports in general are designed to only output signaling voltages, and not to produce enough current to actually power most devices.
**Which compiler?** Doesn't matter. This kind of hardware hacking is more fun and easy under Linux, though, so GCC is a good choice.
**How do I send data?** Depends on the port and the operating system. USB is frightfully complicated for a simple project, so forget it. Serial and parallel ports can be controlled via a variety of different interfaces. My preference is to use the `ioctl()` system call under Linux to directly control the parallel-port pins. Here's info on how to do that: <http://www.linuxfocus.org/common/src/article205/ppdev.html>
**Do I need a microprocessor?** No, you don't need a microprocessor in the external device (obviously your computer has a microprocessor :-P). If you use the parallel or serial ports, you can just use the LED and a resistor or two and the necessary parts to connect the LED directly.
(Also: The *Linux Device Drivers book*, available for free online, has information on interfacing simple electronic devices to parallel ports and writing kernel drivers for them.)
*EDIT:* There seems to be massive confusion in this thread about what the OP means by, "Do I need a microprocessor?" Emphatically, the parallel port alone can drive an LED based on the software *in the computer*. No microprocessor is needed in the device. However, if you want the device to be able to control itself **without being connected to the computer**, a microprocessor or some other digital logic **is** required.
|
Steps to make a LED blink from a C/C++ program?
|
[
"",
"c++",
"c",
"circuit",
""
] |
I'd like to have comments in my code, but I want them to be removed before deploying.
Yes, it's not hard to write such a thing, but if it already exists…
And how about comments in ASP pages?
|
Sounds like you are looking for a JSMin tool or similar.
There are many tools which you can purchase, but there are also some online tools you can use:
<http://www.askapache.com/tools/online-compression-tool-compares-packer-jsmin-dojo-and-yui-compressor.html>
<http://www.askapache.com/online-tools/js-compress/>
Good Luck!
|
[YUI Compressor](http://developer.yahoo.com/yui/compressor/) in addition to removing comments and white-spaces, obfuscates local variables using the smallest possible variable name...
Besides the utility, there is the [YUI Compressor Library for .NET](http://www.codeplex.com/YUICompressor), this library allows you to programmatically compress JavaScript and CSS, or use it automatically with MsBuild...
|
Is there any tools for automatic removal of comments from JavaScript code?
|
[
"",
"asp.net",
"javascript",
"comments",
""
] |
This is my query:
```
$query = $this->db->query('
SELECT archives.id, archives.signature, type_of_source.description, media_type.description, origin.description
FROM archives, type_of_source, media_type, origin
WHERE archives.type_of_source_id = type_of_source.id
AND type_of_source.media_type_id = media_type.id
AND archives.origin_id = origin.id
ORDER BY archives.id ASC
');
```
But how to output the result? This works, but only gets the last description (origin.description):
```
foreach ($query->result_array() as $row)
{
echo $row['description'];
}
```
This doesn't work:
```
foreach ($query->result_array() as $row)
{
echo $row['type_of_source.description'];
}
```
Or should I rename the columns (e.g. type\_of\_source\_description)?
|
This actually has very little to do with CodeIgniter and a lot with how mysql\_fetch\_assoc provides the query results.
The solution is that you should rename the columns inside the query using `"AS"`, e.g.
```
select type_of_source.description as type_of_source_description, origin.descripotion as origin_descripotion from ....
```
|
Just alias the columns in the SELECT statement. Do not modify your database. The standard practice is to use aliasing in your SQL statements.
From PostgreSQL's docs for `"SELECT"`:
"Using the clause AS output\_name, another name can be specified for an output column."
[PostgreSQL SELECT](http://www.postgresql.org/docs/8.0/interactive/sql-select.html)
|
How to output data from tables with same column names in CodeIgniter?
|
[
"",
"sql",
"database",
"codeigniter",
""
] |
I have a requirement to implement an "Unsaved Changes" prompt in an ASP .Net application. If a user modifies controls on a web form, and attempts to navigate away before saving, a prompt should appear warning them that they have unsaved changes, and give them the option to cancel and stay on the current page. The prompt should not display if the user hasn't touched any of the controls.
Ideally I'd like to implement this in JavaScript, but before I go down the path of rolling my own code, are there any existing frameworks or recommended design patterns for achieving this? Ideally I'd like something that can easily be reused across multiple pages with minimal changes.
|
Using jQuery:
```
var _isDirty = false;
$("input[type='text']").change(function(){
_isDirty = true;
});
// replicate for other input types and selects
```
Combine with `onunload`/`onbeforeunload` methods as required.
From the comments, the following references all input fields, without duplicating code:
```
$(':input').change(function () {
```
Using `$(":input")` refers to all input, textarea, select, and button elements.
|
One piece of the puzzle:
```
/**
* Determines if a form is dirty by comparing the current value of each element
* with its default value.
*
* @param {Form} form the form to be checked.
* @return {Boolean} <code>true</code> if the form is dirty, <code>false</code>
* otherwise.
*/
function formIsDirty(form) {
for (var i = 0; i < form.elements.length; i++) {
var element = form.elements[i];
var type = element.type;
if (type == "checkbox" || type == "radio") {
if (element.checked != element.defaultChecked) {
return true;
}
}
else if (type == "hidden" || type == "password" ||
type == "text" || type == "textarea") {
if (element.value != element.defaultValue) {
return true;
}
}
else if (type == "select-one" || type == "select-multiple") {
for (var j = 0; j < element.options.length; j++) {
if (element.options[j].selected !=
element.options[j].defaultSelected) {
return true;
}
}
}
}
return false;
}
```
[And another](http://developer.mozilla.org/en/DOM/window.onbeforeunload):
```
window.onbeforeunload = function(e) {
e = e || window.event;
if (formIsDirty(document.forms["someForm"])) {
// For IE and Firefox
if (e) {
e.returnValue = "You have unsaved changes.";
}
// For Safari
return "You have unsaved changes.";
}
};
```
Wrap it all up, and what do you get?
```
var confirmExitIfModified = (function() {
function formIsDirty(form) {
// ...as above
}
return function(form, message) {
window.onbeforeunload = function(e) {
e = e || window.event;
if (formIsDirty(document.forms[form])) {
// For IE and Firefox
if (e) {
e.returnValue = message;
}
// For Safari
return message;
}
};
};
})();
confirmExitIfModified("someForm", "You have unsaved changes.");
```
You'll probably also want to change the registration of the `beforeunload` event handler to use `LIBRARY_OF_CHOICE`'s event registration.
|
Detecting Unsaved Changes
|
[
"",
"javascript",
"asp.net",
"prompt",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.