instruction stringlengths 0 30k ⌀ |
|---|
I'm looking at sessions in Django, and by default they are stored in the database. What are the benefits of filesystem and cache sessions and when should I use them? |
|python|django|caching|session| |
You can't create an array in .NET (as opposed to declaring a reference to it, which is what you did in your example) without specifying its dimensions, either explicitly, or implicitly by specifying a set of literal values when you initialize it. (e.g. int[,] array4 = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };)
You need to use a variable-size data structure first (a generic list of 22-element 1-d arrays would be the simplest) and then allocate your array and copy your data into it after your read is finished and you know how many rows you need. |
I generally use the nicer collections for this sort of work (List<T>, ArrayList etc.) and then (if really necessary) cast to T[,] when I'm done. |
you would either need to preallocate the array to a Maximum size (float[999,22] ) , or use a different data structure.
i guess you could copy/resize on the fly.. (but i don't think you'd want to)
i think the List<float[]> sounds reasonable. |
One way to handle this would be to use the context menu's Popup event to grab the selected index of the combobox launching the menu. When the dialog form closes reset the selected index. |
I would just use a list, then convert that list into an array.
You will notice here that I used a jagged array (float[][]) instead of a square array (float [,]). Besides being the "standard" way of doing things, it should be much faster. When converting the data from a list to an array you only have to copy [calibrationRow] pointers. Using a square array, you would have to copy [calibrationRow] x [SensorCount] floats.
var tempCalibrationSet = new List<float[]>();
const int SensorCount = 22;
int calibrationRow = 0;
while (recordsToRead())
{
tempCalibrationSet[calibrationRow] = new float[SensorCount];
for (int i = 0; i < SensorCount; i++)
{
tempCalibrationSet[calibrationRow][i] = calibrationArrayView.ReadFloat();
} calibrationRow++;
}
float[][] _calibrationSet = tempCalibrationSet.ToArray(); |
static void Main(string[] args)
{
NorthwindDataContext db = new NorthwindDataContext();
var query = db.Customers;
string json = query.GetJsonTable<Customer>(2, 10, "CustomerID", new string[] {"CustomerID", "CompanyName", "City", "Country", "Orders.Count" });
}
public static class JSonify
{
public static string GetJsonTable<T>(
this IQueryable<T> query, int pageNumber, int pageSize, string IDColumnName, string[] columnNames)
{
string select = string.Format("new ({0} as ID, new ({1}) as cell)", IDColumnName, string.Join(",", columnNames));
var items = new
{
page = pageNumber,
total = query.Count(),
rows = query.Select(select).Skip((pageNumber - 1) * pageSize).Take(pageSize)
};
return JavaScriptConvert.SerializeObject(items);
}
}
|
davidg was on the right track, and I am crediting him with the answer.
But the WMI query necessary was a little less than straightfoward, since I needed not just a list of users for the whole machine, but the subset of users *and groups*, whether local or domain, that were members of the local Administrators group. For the record, that WMI query was:
SELECT PartComponent FROM Win32_GroupUser WHERE GroupComponent = "Win32_Group.Domain='thehostname',Name='thegroupname'"
Here's the full code snippet:
public string GroupMembers(string targethost, string groupname, string targetusername, string targetpassword)
{
StringBuilder result = new StringBuilder();
try
{
ConnectionOptions Conn = new ConnectionOptions();
if (targethost != Environment.MachineName) //WMI errors if creds given for localhost
{
Conn.Username = targetusername; //can be null
Conn.Password = targetpassword; //can be null
}
Conn.Timeout = TimeSpan.FromSeconds(2);
ManagementScope scope = new ManagementScope("\\\\" + targethost + "\\root\\cimv2", Conn);
scope.Connect();
StringBuilder qs = new StringBuilder();
qs.Append("SELECT PartComponent FROM Win32_GroupUser WHERE GroupComponent = \"Win32_Group.Domain='");
qs.Append(targethost);
qs.Append("',Name='");
qs.Append(groupname);
qs.AppendLine("'\"");
ObjectQuery query = new ObjectQuery(qs.ToString());
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection queryCollection = searcher.Get();
foreach (ManagementObject m in queryCollection)
{
ManagementPath path = new ManagementPath(m["PartComponent"].ToString());
{
String[] names = path.RelativePath.Split(',');
result.Append(names[0].Substring(names[0].IndexOf("=") + 1).Replace("\"", " ").Trim() + "\\");
result.AppendLine(names[1].Substring(names[1].IndexOf("=") + 1).Replace("\"", " ").Trim());
}
}
return result.ToString();
}
catch (Exception e)
{
Console.WriteLine("Error. Message: " + e.Message);
return "fail";
}
}
So, if I invoke Groupmembers("Server1", "Administrators", "myusername", "mypassword"); I get a single string returned with:
SERVER1\Administrator
MYDOMAIN\Domain Admins
The actual WMI return is more like this:
\\\SERVER1\root\cimv2:Win32_UserAccount.Domain="SERVER1",Name="Administrator"
... so as you can see, I had to do a little string manipulation to pretty it up. |
@[Jared](#24024):
> Non-overloaded, non-inherited static methods (like Class.b(a,c)) that take an instance as the first variable are semantically equivalent to a method call (like a.b(c))
No, they aren't.
> (Assuming it compiles to the same CIL, which it should.)
That's your mistake. The CIL produced is different. The distinction is that member methods can't be invoked on `null` values so the CIL inserts a check against `null` values. This obviously isn't done in the static variant.
However, `String.Format` does *not* allow `null` values so the developers had to insert a check manually. From this point of view, the member method variant would be technically superior. |
I've been building a few sites with the framework since the first preview came out, and it has certainly come a long way already. It feels like a very light-weight and tidy framework.
There are a couple of areas where I think it really excels over "vanilla" asp.net:
- Enables a much cleaner separation of concerns/loose coupling
- makes test-driven development actually possible.
- And it's *much* more friendly towards javascript (ajax) heavy sites.
That said, there are some areas where it has some way to go yet:
- Validation
- Data binding
- Tag soup, as mentioned earlier (although this can be avoided to some extent; user controls, helper methods&codebehind is still allowed!)
The framework is still in beta though, so I expect these things to improve over time. Scott Hanselman has hinted that the Dynamic Data framework will be available for ASP.NET MVC at some point too, for example.
|
"Reflection" is a language's ability to inspect and dynamically call classes, methods, attributes, etc. at runtime. For example, all objects in Java has the method <b>getClass</b>, which lets you determine its class even if you don't know it at compile time (like if you declared it as <b>Object</b>) - this might seem trivial, but such reflection is not by default possible in less dynamic languages such as C++.
More advanced uses lets you list and call methods, constructors, etc.
Reflection is important since it lets you write program that does not have to "know" everything at compile time, making them more dynamic, since they can be tied together at runtime. The code can be written against known interfaces, but the actual classes to be used can be instantiated using reflection from configuration files.
Lots of modern frameworks uses reflection extensively for this very reason.
Most other modern languages uses reflection as well, and in script languages like Python can be said to be even more tightly integrated, since it matches more naturally with the general programming model for those languages. |
"Reflection" is a language's ability to inspect and dynamically call classes, methods, attributes, etc. at runtime. For example, all objects in Java has the method <b>getClass</b>, which lets you determine its class even if you don't know it at compile time (like if you declared it as <b>Object</b>) - this might seem trivial, but such reflection is not by default possible in less dynamic languages such as C++.
More advanced uses lets you list and call methods, constructors, etc.
Reflection is important since it lets you write programs that does not have to "know" everything at compile time, making them more dynamic, since they can be tied together at runtime. The code can be written against known interfaces, but the actual classes to be used can be instantiated using reflection from configuration files.
Lots of modern frameworks uses reflection extensively for this very reason.
Most other modern languages uses reflection as well, and in script languages like Python can be said to be even more tightly integrated, since it matches more naturally with the general programming model for those languages. |
> Johannes:
>
>> @PConroy: This was my initial thougt also. the interesting part on this is to find good transformation rules for the different parts of the address! Any good suggestions?
When we were working on this type of project before, our approach was to take our existing corpus of addresses (150k or so), then apply the most common transformations for our domain (Ireland, so "Dr"->"Drive", "Rd"->"Road", etc). I'm afraid there was no comprehensive online resource for such things at the time, so we ended up basically coming up with a list ourselves, checking things like the phone book (pressed for space there, addresses are abbreviated in all manner of ways!). As I mentioned earlier, you'd be amazed how many "duplicates" you'll detect with the addition of only a few common rules!
I've recently stumbled across a page with a fairly comprehensive [list of address abbreviations](http://www.semaphorecorp.com/cgi/abbrev.html), although it's american english, so I'm not sure how useful it'd be in Germany! A quick google turned up a couple of sites, but they seemed like spammy newsletter sign-up traps. Although that was me googling in english, so you may have more look with "german address abbreviations" in german :) |
*@Dillie-O: Your answer put me in the right direction (I should have expected it to just be a registry change) and I got this working. But I'm going to mark this as the answer because I'm going to put some additional information that I found while working on this.*
***Edit:** So I can't mark this as the answer, probably because I don't have enough reputation. So if people see this, at least upmod it, and if you upmodded another answer here, please un-upmod it. That way people will actually be able to see this answer.*
The solution to this question really doesn't matter what programming language you're using, as long as there's some way to modify Windows registry settings.
- To associate a program with the mailto protocol for **all users** on a computer, change the HKEY_CLASSES_ROOT\mailto\shell\open\command Default value to:
"*Your program's executable*" "%1"
- To [associate a program with the mailto protocol for the **current user**](http://windowsxp.mvps.org/permail.htm), change the HKEY_CURRENT_USER\Software\Classes\mailto\shell\open\command Default value to:
"*Your program's executable*" "%1"
The %1 will be replaced with the entire mailto URL. For example, given the link:
<a href="mailto:user@example.com">Email me</a>
The following will be executed:
"*Your program's executable*" "mailto:user@example.com"
Note: [The mailto syntax allows for more than just the email address](http://www.ianr.unl.edu/internet/mailto.html). |
*@Dillie-O: Your answer put me in the right direction (I should have expected it to just be a registry change) and I got this working. But I'm going to mark this as the answer because I'm going to put some additional information that I found while working on this.*
***Edit:** So I can't mark this as the answer, probably because I don't have enough reputation. So if people see this, at least upmod it, and if you upmodded another answer here, please un-upmod it. That way people will actually be able to see this answer.*
The solution to this question really doesn't matter what programming language you're using, as long as there's some way to modify Windows registry settings.
Finally, here's the answer:
- To associate a program with the mailto protocol for **all users** on a computer, change the HKEY_CLASSES_ROOT\mailto\shell\open\command Default value to:
"*Your program's executable*" "%1"
- To [associate a program with the mailto protocol for the **current user**](http://windowsxp.mvps.org/permail.htm), change the HKEY_CURRENT_USER\Software\Classes\mailto\shell\open\command Default value to:
"*Your program's executable*" "%1"
The %1 will be replaced with the entire mailto URL. For example, given the link:
<a href="mailto:user@example.com">Email me</a>
The following will be executed:
"*Your program's executable*" "mailto:user@example.com"
Note: [The mailto syntax allows for more than just the email address](http://www.ianr.unl.edu/internet/mailto.html). |
This one's not specifically about development, but [Security Now][1] from Steve Gibson and Leo Laporte is an excellent discussion of security issues. I think it's a must-listen for just about any computer user who's concerned about security, and especially for web developers who are responsible both for the security of their site and at least partially responsible for their users' security.
[1]: http://www.grc.com/securitynow.htm |
Is your customer using Exchange 2007? If so, I'd have a look at [Exchange Web Services][1]. If not, as hairy as it can be, I think WebDAV is your best bet.
Personally I don't like using the Outlook.Application COM object route, as its security prompts ("An application is attempting to access your contacts. Allow this?", etc.) can cause problems on a server. I also think it would be difficult to accomplish your impersonation-like tasks using Outlook, such as sending mail as a given user.
[1]: http://msdn.microsoft.com/en-us/library/bb204119(EXCHG.80).aspx |
The responses to this question have got more than a little confused.
The title asks about disposal, but then says that they want memory back immediately.
.Net is *managed*, which means that when you write .Net apps you don't need to worry about memory directly, the cost is that you don't have direct control over memory either.
.Net decides when it's best to clean up and free memory, not you as the .Net coder.
The `Dispose` is a way to tell .Net that you're done with something, but it won't actually free up the memory until it's the best time to do so.
Basically .Net will actually collect the memory back when it's easiest for it to do so - it's very good at deciding when. Unless you're writing something very memory intensive you normally don't need to overrule it (this is part of the reason games aren't often written in .Net yet - they need complete control)
In .Net you can use `GC.Collect()` to force it to immediately, but that is almost always bad practise. If .Net hasn't cleaned it up yet that means it isn't a particularly good time for it to do so.
`GC.Collect()` picks up the objects that .Net identifies as done with. If you haven't disposed an object that needs it .Net may decide to keep that object. This means that `GC.Collect()` is only effective if you correctly implement your disposable instances.
`GC.Collect()` is **not** a replacement for correctly using IDisposable.
So Dispose and memory are not directly related, but they don't need to be. Correctly disposing will make your .Net apps more efficient and therefore use less memory though.
----------
99% of the time in .Net the following is best practice:
**Rule 1:** If you don't deal with anything *unmanaged* or that implements `IDisposable` then don't worry about Dispose.
**Rule 2:** If you have a local variable that implements IDisposable make sure that you get rid of it in the current scope:
//using is best practice
using( SqlConnection con = new SqlConnection("my con str" )
{
//do stuff
}
//this is what 'using' actually compiles to:
SqlConnection con = new SqlConnection("my con str" ) ;
try
{
//do stuff
}
finally
{
con.Dispose();
}
**Rule 3:** If a class has a property or member variable that implements IDisposable then that class should implement IDisposable too. In that class's Dispose method you can also dispose of your IDisposable properties:
//rather basic example
public sealed MyClass :
IDisposable
{
//this connection is disposable
public SqlConnection MyConnection { get; set; }
//make sure this gets rid of it too
public Dispose()
{
//if we still have a connection dispose it
if( MyConnection != null )
MyConnection.Dispose();
//note that the connection might have already been disposed
//always write disposals so that they can be called again
}
}
This isn't really complete, which is why the example is sealed. Inheriting classes may need to observe the next rule...
**Rule 4:** If a class uses an *unmanaged* resource then implement IDispose *and* add a finaliser.
.Net can't do anything with the *unmanaged* resource, so now we are talking about memory. If you don't clean it up you can get a memory leak.
The Dispose method needs to deal with both *managed* and *unmanaged* resources.
The finaliser is a safety catch - it ensures that if someone else creates and instance of your class and fails to dispose it the 'dangerous' *unmanaged* resources can still be cleaned up by .Net.
~MyClass()
{
//calls a protected method
//the false tells this method
//not to bother with managed
//resources
this.Dispose(false);
}
public void Dispose()
{
//calls the same method
//passed true to tell it to
//clean up managed and unmanaged
this.Dispose(true);
//as dispose has been correctly
//called we don't need the
//'backup' finaliser
GC.SuppressFinalize(this);
}
Finally this overload of Dispose that takes a boolean flag:
protected virtual void Dispose(bool disposing)
{
//check this hasn't been called already
//remember that Dispose can be called again
if (!disposed)
{
//this is passed true in the regular Dispose
if (disposing)
{
// Dispose managed resources here.
}
//both regular Dispose and the finaliser
//will hit this code
// Dispose unmanaged resources here.
}
disposed = true;
}
Note that once this is all in place other managed code creating an instance of your class can just treat it like any other IDisposable (Rules 2 and 3).
|
The responses to this question have got more than a little confused.
The title asks about disposal, but then says that they want memory back immediately.
.Net is *managed*, which means that when you write .Net apps you don't need to worry about memory directly, the cost is that you don't have direct control over memory either.
.Net decides when it's best to clean up and free memory, not you as the .Net coder.
The `Dispose` is a way to tell .Net that you're done with something, but it won't actually free up the memory until it's the best time to do so.
Basically .Net will actually collect the memory back when it's easiest for it to do so - it's very good at deciding when. Unless you're writing something very memory intensive you normally don't need to overrule it (this is part of the reason games aren't often written in .Net yet - they need complete control)
In .Net you can use `GC.Collect()` to force it to immediately, but that is almost always bad practise. If .Net hasn't cleaned it up yet that means it isn't a particularly good time for it to do so.
`GC.Collect()` picks up the objects that .Net identifies as done with. If you haven't disposed an object that needs it .Net may decide to keep that object. This means that `GC.Collect()` is only effective if you correctly implement your disposable instances.
`GC.Collect()` is **not** a replacement for correctly using IDisposable.
So Dispose and memory are not directly related, but they don't need to be. Correctly disposing will make your .Net apps more efficient and therefore use less memory though.
----------
99% of the time in .Net the following is best practice:
**Rule 1:** If you don't deal with anything *unmanaged* or that implements `IDisposable` then don't worry about Dispose.
**Rule 2:** If you have a local variable that implements IDisposable make sure that you get rid of it in the current scope:
//using is best practice
using( SqlConnection con = new SqlConnection("my con str" ) )
{
//do stuff
}
//this is what 'using' actually compiles to:
SqlConnection con = new SqlConnection("my con str" ) ;
try
{
//do stuff
}
finally
{
con.Dispose();
}
**Rule 3:** If a class has a property or member variable that implements IDisposable then that class should implement IDisposable too. In that class's Dispose method you can also dispose of your IDisposable properties:
//rather basic example
public sealed MyClass :
IDisposable
{
//this connection is disposable
public SqlConnection MyConnection { get; set; }
//make sure this gets rid of it too
public Dispose()
{
//if we still have a connection dispose it
if( MyConnection != null )
MyConnection.Dispose();
//note that the connection might have already been disposed
//always write disposals so that they can be called again
}
}
This isn't really complete, which is why the example is sealed. Inheriting classes may need to observe the next rule...
**Rule 4:** If a class uses an *unmanaged* resource then implement IDispose *and* add a finaliser.
.Net can't do anything with the *unmanaged* resource, so now we are talking about memory. If you don't clean it up you can get a memory leak.
The Dispose method needs to deal with both *managed* and *unmanaged* resources.
The finaliser is a safety catch - it ensures that if someone else creates and instance of your class and fails to dispose it the 'dangerous' *unmanaged* resources can still be cleaned up by .Net.
~MyClass()
{
//calls a protected method
//the false tells this method
//not to bother with managed
//resources
this.Dispose(false);
}
public void Dispose()
{
//calls the same method
//passed true to tell it to
//clean up managed and unmanaged
this.Dispose(true);
//as dispose has been correctly
//called we don't need the
//'backup' finaliser
GC.SuppressFinalize(this);
}
Finally this overload of Dispose that takes a boolean flag:
protected virtual void Dispose(bool disposing)
{
//check this hasn't been called already
//remember that Dispose can be called again
if (!disposed)
{
//this is passed true in the regular Dispose
if (disposing)
{
// Dispose managed resources here.
}
//both regular Dispose and the finaliser
//will hit this code
// Dispose unmanaged resources here.
}
disposed = true;
}
Note that once this is all in place other managed code creating an instance of your class can just treat it like any other IDisposable (Rules 2 and 3).
|
Reflection |
|reflection|java| |
What is reflection, and why is it useful?
I'm particularly interested in Java, but I assume the principles are the same in any language(?). |
What is reflection, and why is it useful? |
|java|reflection| |
What is reflection, and why is it useful?
I'm particularly interested in Java, but I assume the principles are the same in any language(?). |
Examining Berkeley DB files from the CLI |
|linux|command-line-interface|berkeley-db| |
I have a set of Berkeley DB files on my Linux file system that I'd like to examine.
What useful tools exist for getting a quick overview of the contents? I can write Perl scripts that use BDB modules for examining them, but I'm looking for some CLI utility to be able to take a look inside without having to start writing scripts. |
I have found these two links useful:
Using CLR and single audit table.<br />
[http://www.sqljunkies.ddj.com/Article/4CD01686-5178-490C-A90A-5AEEF5E35915.scuk][1]
Using triggers and seperate audit table for each table being audited.<br />
[http://sqlserver2000.databases.aspfaq.com/how-do-i-audit-changes-to-sql-server-data.html][2]
[1]: http://www.sqljunkies.ddj.com/Article/4CD01686-5178-490C-A90A-5AEEF5E35915.scuk
[2]: http://sqlserver2000.databases.aspfaq.com/how-do-i-audit-changes-to-sql-server-data.html |
# Visual Basic: Linq
<Extension()> _
Public Function Product(ByVal xs As IEnumerable(Of Integer)) As Integer
Return xs.Aggregate(1, Function(a, b) a * b)
End Function
Public Function Fact(ByVal n As Integer) As Integer
Return Aggregate x In Enumerable.Range(1, n) Into Product()
End Function
This shows how to use the `Aggregate` keyword in VB. **C# can't do this** (although C# can of course call the extension method directly). |
Follow-up to my previous posting.
Templates are one of the main reasons why C++ fails so abysmally at intellisense, regardless of the IDE used. Because of template specialization, the IDE can never be really sure if a given member exists or not. Consider:
template <typename T>
struct X {
void foo() { }
};
template <>
struct X<int> { };
typedef int my_int_type;
X<my_int_type> a;
a.|
Not, the cursor is at the indicated position and it's damn hard for the IDE to say at that point if, and what, members `a` has. For other languages the parsing would be straightforward but for C++, quite a bit of evaluation is needed beforehand.
It gets worse. What if `my_int_type` were defined inside a class template as well? Now its type would depend on another type argument. And here, even compilers fail.
template <typename T>
struct Y {
typedef T my_type;
};
X<Y<int>::my_type> b;
After a bit of thinking, a programmer would conclude that this code is the same as the above: `Y<int>::my_type` resolves to `int`, therefore `b` should be the same type as `a`, right?
Wrong. At the point where the compiler tries to resolve this statement, it doesn't actually know `Y<int>::my_type` yet! Therefore, it doesn't know that this is a type. It could be something else, e.g. a member function or a field. This might give rise to ambiguities (though not in the present case), therefore the compiler fails. We have to tell it explicitly that we refer to a type name:
X<typename Y<int>::my_type> b;
Now, the code compiles. To see how ambiguities arise from this situation, consider the following code:
Y<int>::my_type(123);
This code statement is perfectly valid and tells C++ to execute the function call to `Y<int>::my_type`. However, if `my_type` is not a function but rather a type, this statement would still be valid and perform a special cast (the function-style cast) which is often a constructor invocation. The compiler can't tell which we mean so we have to disambiguate here. |
I believe JWebPane is going to be the official way to embed a browser into a java app. Its based on the open sourced engine - WebKit, which is used in Apples Safari and Googles Chrome browsers.See [this blog][1] for details.
[1]: http://weblogs.java.net/blog/ixmal/archive/2008/05/introducing_jwe.html |
How to use webclient in a secure site? |
|screen-scraping| |
I need to automate a process involving a website that is using a login form. I need to capture some data in the pages following the login page.
I know how to screen-scrape normal pages, but not those behind a secure site.
1. Can this be done with the WebClient class?
- How would I automatically login?
- How would I keep logged in for the other pages? |
|.net|screen-scraping| |
I need to automate a process involving a website that is using a login form. I need to capture some data in the pages following the login page.
I know how to screen-scrape normal pages, but not those behind a secure site.
1. Can this be done with the .NET WebClient class?
- How would I automatically login?
- How would I keep logged in for the other pages? |
Composite is used extensively in UI. Components can be leaf components e.g. buttons and labels or composites e.g. panels, that can contain other leaf or composite components. From the point of view of the client, all components are treated the same, which greatly simplifies the client code.
|
Setting DataGridView.DefaultCellStyle.NullValue to null at designtime raises error at adding rows runtime. |
|c#|datagridview|null| |
In Visual Studio 2008
- add a new DataGridView to a form
- Edit Columns
- Add a a new DataGridViewImageColumn
- Open the CellStyle Builder of this column (DefaultCellStyle property)
- Change the NullValue from System.Drawing.Bitmap to null
- Try to add a new Row to the DataGridView at runtime
(dataGridView1.Rows.Add();)
- You get this error: System.FormatException: Formatted
value of the cell has a wrong type.
If you change back the NullValue to System.Drawing.Bitmap (as it was) you still get the same error at adding a row.
If you set the NullValue at runtime instead of designtime you don't get anny error.
(dataGridView1.Columns[0].DefaultCellStyle.NullValue = null;)
Could you tell me why is that? |
I think you should base your server class on the [SocketServer][1] class from the standard library. You'll need to write a `RequestHandler` to read and echo input but a lot of the heavy lifting is already done for you.
You can use the [ThreadingMixIn][2] to make the server multi-threaded very easily.
[1]: http://www.python.org/doc/lib/module-SocketServer.html
[2]: http://docs.python.org/lib/node632.html |
I think you should base your server class on the [`SocketServer`][1] class from the standard library. You'll need to write a `RequestHandler` to read and echo input but a lot of the heavy lifting is already done for you.
You can use the [`ThreadingMixIn`][2] to make the server multi-threaded very easily.
[1]: http://www.python.org/doc/lib/module-SocketServer.html
[2]: http://docs.python.org/lib/node632.html |
Carlton : Alfresco seems to be a Java based solution.
Ta: I've looked into the plugin folders but none was really good for asp.net mvc.
What I'm now testing is a mix between Tiny with the image uploader of FCKEditor:
this is the pho version but I think it is pretty easy to convert to .net [Tinyfck][1]
[1]: this: http://p4a2.crealabsfoundation.org/tinyfck |
Mark-up is a term from print editing - the editor would go through the text and add annotations (i.e. this in italic, that in bold) for the printers to use when producing the final version. This was called marking up the text.
A computer mark-up language is just a standardised short-hand for these sorts of annotations.
HTML is basically the web's standard mark-up language, but it's rather verbose.
A list in HTML:
<ul>
<li>Item one</li>
<li>Item two</li>
</ul>
Markdown has its own simpler syntax.
A list in Markdown:
* Item one
* Item two
Both of these will work in your stackoverflow posts.
Markdown can't do everything HTML can, but both are mark-up languages. |
>Isn't it a security flaw of the site to let hackers throw everything in their arsenal against the site?
Well, you should focus on closing holes, rather than trying to thwart scanners (which is a futile battle). Consider running such tests yourself. |
It's good that you block bad request after a couple of trials, but you should let it continue.
If you block it after 5 bad requests you won't know if the 6th request wouldn't crash your site.
EDIT:
I meant that some attacker might send only one request but similar to one of those 1495 that You didn't test because you blocked., and this one request might chrash your site. |
According to [wikipedia][1] Fib(0) should be 0 but it does not matter.
Here is simple C# solution with for cycle:
ulong Fib(int n)
{
ulong fib = 1; // value of fib(i)
ulong fib1 = 1; // value of fib(i-1)
ulong fib2 = 0; // value of fib(i-2)
for (int i = 0; i < n; i++)
{
fib = fib1 + fib2;
fib2 = fib1;
fib1 = fib;
}
return fib;
}
It is pretty common trick to convert recursion to [tail recursion][2] and then to loop. For more detail see any for example this [lecture][3] (ppt).
[1]: http://en.wikipedia.org/wiki/Fibonacci_number
[2]: http://c2.com/cgi/wiki?TailRecursion
[3]: http://www.isle.uiuc.edu/~akantor/teaching/discussionSessions/Accumulator%20Recursion.ppt |
According to [wikipedia][1] Fib(0) should be 0 but it does not matter.
Here is simple C# solution with for cycle:
ulong Fib(int n)
{
ulong fib = 1; // value of fib(i)
ulong fib1 = 1; // value of fib(i-1)
ulong fib2 = 0; // value of fib(i-2)
for (int i = 0; i < n; i++)
{
fib = fib1 + fib2;
fib2 = fib1;
fib1 = fib;
}
return fib;
}
It is pretty common trick to convert recursion to [tail recursion][2] and then to loop. For more detail see for example this [lecture][3] (ppt).
[1]: http://en.wikipedia.org/wiki/Fibonacci_number
[2]: http://c2.com/cgi/wiki?TailRecursion
[3]: http://www.isle.uiuc.edu/~akantor/teaching/discussionSessions/Accumulator%20Recursion.ppt |
If you're referring to simply accessing your IIS server from a remote location, remote desktop generally solves that problem. Assuming your server has a static IP address or a host name you can access from the internet, remote desktop is a simple and relatively secure solution. |
If you're referring to simply accessing your IIS server from a remote location, remote desktop generally solves that problem. Assuming your server has a static IP address or a host name you can access from the internet, remote desktop is a simple and relatively secure solution.
Is there a problem with this answer? Now I have negative reputation... |
Something like this should work. ( though, you **will** want to change the interval )
public Form1()
{
InitializeComponent();
Timer Every4Minutes = new Timer();
Every4Minutes.Interval = 10;
Every4Minutes.Tick += new EventHandler(MoveNow);
Every4Minutes.Start();
}
void MoveNow(object sender, EventArgs e)
{
Cursor.Position = new Point(Cursor.Position.X - 1, Cursor.Position.Y - 1);
} |
Python - How do I tell what OS I'm running on? |
|python| |
What do I need to look at to see if I'm on Windows, Unix, etc? |
This is an active area of research. There are literally oodles of academic papers on the subject. It's going to be difficult to give you assistance especially w/o more deatails. Are you looking for specific types of text? Fonts? English-only? Are you familiar with the academic literature?
"Text detection" is a standard problem in any OCR (optical character recognition) system and consequently there are lots of bits of code on the interwebs that deal with it.
I could start listing piles of links from google but I suggest you just do a search for "text detection" and start reading :). There is ample example code available as well. |
>>> import os
>>> print os.name
posix
>>> import platform
>>> platform.system()
'Linux'
>>> platform.release()
'2.6.22-15-generic'
See: <http://docs.python.org/lib/node441.html> |
How can I programmatically determine if my workstation is locked? |
|c#|productivity| |
I'm writing up some productivity/metrics tools for myself to help monitor my focus throughout the day. Recently, I've noticed that I tend to get off track more than usual and feel the need to get up and go for walks/drinks/etc and I'm concerned that I'm "wasting" too much time.
Since I always lock my computer when I go anywhere, and I unlock it as soon as I return (even if I'm just reading at my desk, etc), I was wondering how I can determine, in code, how long the machine is locked.
I'm writing this in C# if that helps, but I'm open to other ideas. |
I'm writing up some productivity/metrics tools for myself to help monitor my focus throughout the day. Recently, I've noticed that I tend to get off track more than usual and feel the need to get up and go for walks/drinks/etc and I'm concerned that I'm "wasting" too much time.
Since I always lock my computer when I go anywhere, and I unlock it as soon as I return (even if I'm just reading at my desk, etc), I was wondering how I can determine, in code, how long the machine is locked.
I'm writing this in C# if that helps, but I'm open to other ideas.
<hr />
I like the windows service idea (and have accepted it) for simplicity and cleanliness, but unfortunately I don't think it will work for me in this particular case. I wanted to run this on my workstation at work rather than home (or in addition to home, I suppose), but it's locked down pretty hard courtesy of the DoD. That's part of the reason I'm rolling my own, actually.
I'll write it up anyway and see if it works. Thanks everyone! |
You could also use a two-dimensional ArrayList (from System.Collections) -- you create an ArrayList, then put another ArrayList inside it. This will give you the dynamic resizing you need, but at the expense of a bit of overhead.
|
Without native code, you can only tell whether the current thread holds the lock. You can't tell what thread, if any, holds it if it isn't the current thread. |
You can only tell whether the current thread holds a normal lock (`Thread.holdsLock(Object)`). You can't get a reference to the thread that has the lock without native code.
However, if you're doing anything complicated with threading, you probably want to familiarize yourself with the java.util.concurrent packages. The `ReentrantLock` does allow you to get its owner (but its a protected method, so you'd have to extend this). Depending on your application, it may well be that by using the concurrency packages, you'll find that you don't need to get the lock's owner after all.
There are non-programmatic methods to find the lock owners, such as signaling the JVM to issue a thread dump to stderr, that are useful to determine the cause of deadlocks. |
That's what I would like to avoid if properly, but this seems to be much more complicated than excepted.
Normally, everyone advises using the AsyncPostBackError of the ScriptManager, but this does not work if called on the Global.asax. Unfortunately, as the HttpRequestValidationException is emitted by the runtime, it never enters my code and I cannot do much within the Application_Error.
So yes, it needs to be indeed done in the JavaScript, I just hope there is a way to add a "hook" like the BeginRequestHandler-Function so that I don't have to "hack" Microsoft code. If I find a solution before someone else, i'll put it up here :-) |
That's what I would like to avoid if possible, but this seems to be much more complicated than expected.
Normally, everyone advises using the AsyncPostBackError of the ScriptManager, but this does not work if called on the Global.asax. Unfortunately, as the HttpRequestValidationException is emitted by the runtime, it never enters my code and I cannot do much within the Application_Error.
So yes, it needs to be indeed done in the JavaScript, I just hope there is a way to add a "hook" like the BeginRequestHandler-Function so that I don't have to "hack" Microsoft code. If I find a solution before someone else, i'll put it up here :-) |
Have a look at [EasyListBox][1]. I used on a project and while a bit quirky at first, got the job done.
[1]: http://www.easylistbox.com/home.aspx |
I would just use Red Gate's ANTS Profiler. It will tell you a lot about what's going on in memory without you having to learn the profiling API yourself. |
In general, the problem is one of using two different "constants" for form layout, and then changing one of those constants without changing the other.
You are using pixels for your form entities, and points (basically inches) to specify font size. Pixels and points are related by DPI, so you change the DPI and suddenly your pixel fixed values don't line up with your point fixed values.
There are packages and classes for this, but at the end of the day you must choose one unit or the other, or scale one of the units according to the changing constant.
Personally, I'd changing the entities on the form into inches. I'm not a C# person, so I don't know if this is supported natively, or if you have to perform some dynamic form sizing on app startup.
If you have to do this in your software, then go ahead and size everything normally (say, to your usual 95 dpi).
When your app starts, verify the system is at 95dpi before you show your forms. If it is, great. If not, then set a variable with the correction factor, and scale and translate (modify both the location and size) of each entity before you show the form.
The ultimate, though, would be to specify everything in inches or points (a point is 1/72 of an inch) and let the OS deal with it. You might have to deal with corner cases (an outdoor screen with a correctly set DPI would show your app in a few pixels...)
-Adam |
In all versions of MySQL, simply alias the aggregate in the SELECT list, and order by the alias:
SELECT COUNT(id) AS theCount, `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY theCount DESC
LIMIT 20 |
programmatically retrieve Visual Studio install directory |
|visual-studio| |
I know there is a registry key indcating the install directory, but don't remember what it is off-hand.
Currently interested in VS2008 install directory, though it wouldn't hurt to list others for future reference.
|
Well, since you only have a four element array you may just want ot unroll the recursion to save time. Passing arrays as arguments will eat up memory and leave a mess for the GC to clean up later. |
UK Government Data Standards Catalogue suggests 35 characters for each of Given Name and Family Name, or 70 characters for a single field to hold the Full Name:
[http://www.govtalk.gov.uk/gdsc/html/noframes/PersonName-1-1-Release.htm][1]
[1]: http://www.govtalk.gov.uk/gdsc/html/noframes/PersonName-1-1-Release.htm |
Use the [Version](http://msdn.microsoft.com/en-us/library/system.version.aspx) class.
Version a = new Version("1.0.0.0");
Version b = new Version("2.0.0.0");
Console.WriteLine(string.Format("Newer: {0}", (a > b) ? "a" : "b"));
// prints b |
I'm sure there's a registry entry as well but I couldn't easily locate it. There is the VS90COMNTOOLS environment variable that you could use as well. |
If you can assume that each place in the version string will only be one number (or at least the last 3, you can just remove the commas or periods and compare...which would be a lot faster...not as robust, but you don't always need that.
public static int CompareVersions(string strA, string strB)
{
char[] splitTokens = new char[] {'.', ','};
string[] strAsplit = strA.Split(splitTokens, StringSplitOptions.RemoveEmptyEntries);
string[] strBsplit = strB.Split(splitTokens, StringSplitOptions.RemoveEmptyEntries);
int versionA = 0;
int versionB = 0;
string vA = string.Empty;
string vB = string.Empty;
for (int i = 0; i < 4; i++)
{
vA += strAsplit[i];
vB += strBsplit[i];
versionA[i] = Convert.ToInt32(strAsplit[i]);
versionB[i] = Convert.ToInt32(strBsplit[i]);
}
versionA = Convert.ToInt32(vA);
versionB = Convert.ToInt32(vB);
if(vA > vB)
return 1;
else if(vA < vB)
return -1;
else
return 0; //they are equal
}
And yes, I'm also assuming 4 version places here... |
I kept digging around some of the "major" frameworks and it seems that Django does exactly what I was talking about. Or so it seems from this [screencast][1].
Does anyone have any remark to make about this? Does it work well?
[1]: http://www2.lamptraining.com/screencast/1/ |
[Jboss clustering][1] was very easy to get up and running.
It seems to work well for us.
[1]: http://docs.jboss.org/jbossas/jboss4guide/r4/html/cluster.chapt.html |
For non developer tools try Microsoft Action Pack
https://partner.microsoft.com/40016455
Then use Visual Studio Professional (in some exibitions you will get this for free)
For the versioning use svn and not TeamSystem
|
I'm no expert, but from what I learned so far the golden rule is not to trust any user data (GET, POST, COOKIE). Common attack types and how to save yourself:
1. [SQL Injection Attack][1]: Use prepared queries
2. [Cross Site Scripting][2]: Send no user data to browser without filtering/escaping first. This also includes user data stored in database, which originally came from users.
[2]: http://en.wikipedia.org/wiki/Cross-site_scripting
[1]: http://en.wikipedia.org/wiki/SQL_injection |
I my applications I usually have `setup.php` file that includes all core classes (i.e. framework and accompanying libraries). My custom classes are loaded using autoloader aided by directory layout map.
Each time new class is added I run command line builder script that scans whole directory tree in search for model classes then builds associative array with class names as keys and paths as values. Then, __autoload function looks up class name in that array and gets include path. Here's the code:
**autobuild.php**
define('MAP', 'var/cache/autoload.map');
error_reporting(E_ALL);
require 'setup.php';
print(buildAutoloaderMap() . " classes mapped\n");
function buildAutoloaderMap() {
$dirs = array('lib', 'view', 'model');
$cache = array();
$n = 0;
foreach ($dirs as $dir) {
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $entry) {
$fn = $entry->getFilename();
if (!preg_match('/\.class\.php$/', $fn))
continue;
$c = str_replace('.class.php', '', $fn);
if (!class_exists($c)) {
$cache[$c] = ($pn = $entry->getPathname());
++$n;
}
}
}
ksort($cache);
file_put_contents(MAP, serialize($cache));
return $n;
}
**autoload.php**
define('MAP', 'var/cache/autoload.map');
function __autoload($className) {
static $map;
$map or ($map = unserialize(file_get_contents(MAP)));
$fn = array_key_exists($className, $map) ? $map[$className] : null;
if ($fn and file_exists($fn)) {
include $fn;
unset($map[$className]);
}
}
Note that file naming convention must be [class_name].class.php. Alter the directories classes will be looked in `autobuild.php`. You can also run autobuilder from autoload function when class not found, but that may get your program into infinite loop.
Serialized arrays are darn fast.
@JasonMichael: PHP 4 is dead. Get over it. |
Checkout Netbeans, it's written in Java so you'll have the same environment regardless of your OS, and it supports a lot more than just C++.
I'm not going to try to convince you, because I think IDEs can be a very personal choice. For me it improves my productivity by being fast, supporting the languages I code in and has the standard features you'd expect from an IDE. |
Outlook Add-in using .NET |
|.net|outlook|add-in| |
Follow-up to my previous posting.
Templates are one of the main reasons why C++ fails so abysmally at intellisense, regardless of the IDE used. Because of template specialization, the IDE can never be really sure if a given member exists or not. Consider:
template <typename T>
struct X {
void foo() { }
};
template <>
struct X<int> { };
typedef int my_int_type;
X<my_int_type> a;
a.|
Now, the cursor is at the indicated position and it's damn hard for the IDE to say at that point if, and what, members `a` has. For other languages the parsing would be straightforward but for C++, quite a bit of evaluation is needed beforehand.
It gets worse. What if `my_int_type` were defined inside a class template as well? Now its type would depend on another type argument. And here, even compilers fail.
template <typename T>
struct Y {
typedef T my_type;
};
X<Y<int>::my_type> b;
After a bit of thinking, a programmer would conclude that this code is the same as the above: `Y<int>::my_type` resolves to `int`, therefore `b` should be the same type as `a`, right?
Wrong. At the point where the compiler tries to resolve this statement, it doesn't actually know `Y<int>::my_type` yet! Therefore, it doesn't know that this is a type. It could be something else, e.g. a member function or a field. This might give rise to ambiguities (though not in the present case), therefore the compiler fails. We have to tell it explicitly that we refer to a type name:
X<typename Y<int>::my_type> b;
Now, the code compiles. To see how ambiguities arise from this situation, consider the following code:
Y<int>::my_type(123);
This code statement is perfectly valid and tells C++ to execute the function call to `Y<int>::my_type`. However, if `my_type` is not a function but rather a type, this statement would still be valid and perform a special cast (the function-style cast) which is often a constructor invocation. The compiler can't tell which we mean so we have to disambiguate here. |
Two alternatives
1. Use a temporary table
2. Investigate
the [XOR algorithm][1]
[1]: http://en.wikipedia.org/wiki/XOR_swap_algorithm |
To add an answer to my own question:
A different way of doing it is ask users for their mobile phone number, send them a text msg for verification. This stops most people messing with duplicate addresses.
I'm talking from personal experience. (thanks [pigsback][1] !) They introduced confirmation through mobile phone. That stopped me having 2 accounts! :-)
[1]: http://www.pigsback.ie |
Reflection is a key mechanism to allow an application or framework to work with code that might not have even been written yet!
Take for example your typical web.xml file. This will contain a list of servlet elements, which contain nested servlet-class elements. The servlet container will process the web.xml file, and create new a new instance of each servlet class through reflection.
Another example would be the Java API for XML Parsing [(JAXP)](http://en.wikipedia.org/wiki/Java_API_for_XML_Processing). Where an XML parser provider is 'plugged-in' via well-known system properties, which are used to construct new instances through reflection.
And finally, the most comprehensive example is [Spring](http://www.springframework.org/) which uses reflection to create its beans, and for its heavy use of proxies |
I heard lot of good about [Django Schema Evolution Branch](http://code.google.com/p/deseb/) and those were opions of actual users. It mostely works out of the box and do what it should do. |
As [kronoz said](#47776) in .Net 3.5 you can use `Distinct()`.
In .Net 2 you could mimic it:
public IEnumerable<T> DedupCollection<T> ( IEnumerable<T> input ) {
List<T> passedValues = new List<T>();
//relatively simple dupe check alg used as example
foreach( T item in input)
if( passedValues.Contains(item) )
continue;
else {
passedValues.Add(item)
yield return item;
}
}
This could be used to dedupe any collection, but you could return the passedValues variable if you wanted a list instead.
It's normally much quicker to filter a collection (as both `Distinct()` and this sample does) than it would be to remove items from it. |
I agree, it gives me the *it works but it feels like a hack* feeling. I try to avoid reflection whenever possible. I have been burned many times after refactoring code which had reflection in it. Code compiles fine, tests even run, but under special circumstances (which the tests didn't cover) the program blows up run-time because of my refactoring in one of the objects the reflection code poked into.
**Example 1:** Reflection in OR mapper, you change the name or the type of the property in your object model: Blows up run-time.
**Example 2:** You are in a SOA shop. Web Services are complete decoupled (or so you think). They have their own set of generated proxy classes, but in the mapping you decide to save some time and you do this:
ExternalColor c = (ExternalColor)Enum.Parse(typeof(ExternalColor), internalColor.ToString());
Under the covers this is also reflection but done by the .net framework itself. Now what happens if you decide to rename **InternalColor.Grey** to **InternalColor.Gray**? Everything looks ok, it builds fine, and even runs fine.. until the day some stupid user decides to use the color Gray... at which point the mapper will blow up. |
I agree, it gives me the *it works but it feels like a hack* feeling. I try to avoid reflection whenever possible. I have been burned many times after refactoring code which had reflection in it. Code compiles fine, tests even run, but under special circumstances (which the tests didn't cover) the program blows up run-time because of my refactoring in one of the objects the reflection code poked into.
**Example 1:** Reflection in OR mapper, you change the name or the type of the property in your object model: Blows up run-time.
**Example 2:** You are in a SOA shop. Web Services are complete decoupled (or so you think). They have their own set of generated proxy classes, but in the mapping you decide to save some time and you do this:
ExternalColor c = (ExternalColor)Enum.Parse(typeof(ExternalColor),
internalColor.ToString());
Under the covers this is also reflection but done by the .net framework itself. Now what happens if you decide to rename **InternalColor.Grey** to **InternalColor.Gray**? Everything looks ok, it builds fine, and even runs fine.. until the day some stupid user decides to use the color Gray... at which point the mapper will blow up. |
PHP callbacks are structures that "point" to global functions, object methods, or static methods of a class. This allows some level of functional programming in PHP before 5.3. The 3 flavors are:
$cb1 = 'someGlobalFunction';
$cb2 = array(&$obj, 'somePublicMethod');
$cb3 = array('ClassName', 'someStaticMethod');
Here's how you should call a callback function:
if (is_callable($cb3)) {
// $cb3 is a valid callback, the class "ClassName" is loaded and has
// a public method "someStaticMethod"
$ret = call_user_func($cb3, $arg1, $arg2);
// $ret has the return value of the $cb3.
}
Only the string form can be called directly by PHP, but this limits the utility of your code:
$cb1($arg1, $arg2);
See: http://php.net/callback |
PHP callbacks are structures that "point" to global functions, object methods, or static methods of a class. This allows some level of functional programming in PHP before 5.3. The 3 flavors are:
$cb1 = 'someGlobalFunction';
$cb2 = array(&$obj, 'somePublicMethod');
$cb3 = array('ClassName', 'someStaticMethod');
Here's how you should call a callback function:
if (is_callable($cb3)) {
// $cb3 is a valid callback, the class "ClassName" is loaded and has
// a public method "someStaticMethod"
$ret = call_user_func($cb3, $arg1, $arg2);
// $ret has the return value of the $cb3.
}
Only the string form can be called by appending parenthesis, but this limits the utility and readability of code:
$ret = $cb1($arg1, $arg2); // OK
$ret = $cb2($arg1, $arg2); // will cause error
$ret = $cb3($arg1, $arg2); // will cause error
See: http://php.net/callback |
I am very happy with RedGate ANTS. The only other one I tried was the one that comes with Visual Studio Team, and it sucks. |
signed to unsigned conversion in C - is it always safe? |
|c| |