Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
None of the guides/notes/articles that discuss `IDisposable` pattern suggest that one should set the internal members to `null` in the `Dispose(bool)` method (especially if they are memory hogging beasts).
I've come to realize the importance of it while debugging an internal benchmark tool. What used to happen was tha... | Releasing any additional references during `Dispose` is certainly something I try to do, for two reasons:
* it allows the inner objects to be garbage collected even if the disposed object is still in scope
* if the inner objects are disposable, it means we only dispose them once even if `Dispose()` is called repeatedl... | Maybe I'm missing your point, but once your object is disposed, the root or 'sub-root' it represented relative to it's members has been detached. It seems like you are thinking of garbage collection like a ref count system (which can be done, but ... usually isn't).
Instead, think of it as a many-rooted tree, where ev... | In the Dispose(bool) method implementation, Shouldn't one set members to null? | [
"",
"c#",
".net",
"memory-management",
"garbage-collection",
"dispose",
""
] |
Is there a way, in C# code, to send an email without having to know the SMTP server configuration, etc on the server, or have any of that stuff set up?
The code I'm developing will be deployed to a live server, but I know nothing about the configuration, so I can't predict what the SMTP server will be. | The best answer is if you know nothing until live, can you move all the settings into web.config? This will allow configuration up until the last minute. Below is some code to dump into your web.config file. I would question as to why you don't have access to this information though
```
<system.net>
<mailSettings>... | Add this to your web.config ([MSDN reference here](http://msdn.microsoft.com/en-us/library/ms164240.aspx)):
```
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="jdoe@example.com">
<network host="localhost" port="25" />
</smtp>
</mailSettings>
</system.net>
```
Using... | C# code for sending an email without knowing much about the server configuration? | [
"",
"c#",
"email",
"configuration",
"smtp",
""
] |
I am using HTML, and I'd like to hide the `script` tag from the user's view. When the user views the page source, the definitions should not appear. How do I accomplish this?
### Example
```
<script type="text/javascript" src="My1.js"></script>
<script type="text/javascript" src="My2.js"></script>
<script type="text/... | You cannot hide HTML. If you want a closed-source solution, use a proprietary format, such as [Flash](http://en.wikipedia.org/wiki/Adobe_Flash) or [Flex](http://en.wikipedia.org/wiki/Adobe_Flex).
You can, however, obfuscate your JavaScript code (you should shrinkwrap or minify it anyhow) which makes reading it harder. | You can limit it to one script tag by making an include file that references the other scripts..
Other than that, no. | How to hide the 'script' HTML tag? | [
"",
"javascript",
"jquery",
"html",
""
] |
I have a MySql database with three tables I need to combine in a query: schedule, enrolled and waitlist. They are implementing a basic class enrollment system.
Schedule contains the scheduled classes. When a user enrolls in a class, their user account id and the id of the scheduled class are stored in enrolled. If a c... | I would do it with another left join and two inline count(distincts)
```
select s.id, s.classDate, s.instructor ,
count(distinct e.id) as enrolled,
count(distinct w.id) as waiting
from schedule as s
left outer join enrolled as e
on s.id = e.scheduleID
left outer join waitlist as w
on s.id = w.scheduleID
group by s.id
... | Use nested SELECT queries. Assuming a bit about your schema, how about something like this (might not work on some flavors of SQL):
```
select s.id, s.classDate, s.instructor,
(select COUNT(e.id) from enrolled e where e.scheduleId = s.id) as enrolled,
(select COUNT(w.id) from waitlist w where w.schedule... | How do I include filtered rowcounts from two other tables in a query of a third? | [
"",
"sql",
"mysql",
"rowcount",
""
] |
I am doing something like this:
```
class Class(object):
def __init__(self):
self.var=#new instance name string#
```
How do I make the \_\_ init \_\_ method of my instance to use the instance name string for 'c'? Say in case:
```
c=Class()
```
I want c.var equal to 'c'.
Thanks for your replies, I am im... | To persist data objects you need to use the database record's unique ID.
**pesudo code because I don't know what database module you're using**
```
import db # assume this is your db module
class Class(object):
def __init__(self):
self.id = None
self.name = None
def get_by_id(self, id):
... | Python doesn't have variables, it has [objects and names](http://effbot.org/zone/python-objects.htm). When you do
```
c = Class()
```
you're doing two things:
1. Creating a new object of type `Class`
2. Binding the object to the name `c` in the current scope.
The object you created doesn't have any concept of a "va... | Addressing instance name string in __init__(self) in Python | [
"",
"python",
"instance",
"instantiation",
""
] |
We have a hosted site that has a CMS we built running on a LAMP stack. We noticed that when you save HTML that has a tag embedded in the HTML the request immediately dies. This does not occur on the staging or local development instances of the CMS, so I'm assuming its a server configuration issue. Any ideas what might... | I've had similar problems caused by apaches mod\_security. If you have mod\_security enabled on the server, you can try something like this (in a .htaccess file):
```
<IfModule mod_security.c>
SecFilterEngine Off
</IfModule>
``` | Since you have system where this error does not appear it is a configuration error.
Find the difference between the failing and the other systems.
If you have too many files to compare. Start reducing the complexity of the system as far as possible. | Submitting form fails when the form data contains a <script> tag LAMP | [
"",
"php",
"apache",
"forms",
"scripting",
"lamp",
""
] |
Is there an elegant way to handle exceptions that are thrown in `finally` block?
For example:
```
try {
// Use the resource.
}
catch( Exception ex ) {
// Problem with the resource.
}
finally {
try{
resource.close();
}
catch( Exception ex ) {
// Could not close the resource?
}
}
```
How do y... | I usually do it like this:
```
try {
// Use the resource.
} catch( Exception ex ) {
// Problem with the resource.
} finally {
// Put away the resource.
closeQuietly( resource );
}
```
Elsewhere:
```
protected void closeQuietly( Resource resource ) {
try {
if (resource != null) {
resource.close();... | I typically use one of the `closeQuietly` methods in `org.apache.commons.io.IOUtils`:
```
public static void closeQuietly(OutputStream output) {
try {
if (output != null) {
output.close();
}
} catch (IOException ioe) {
// ignore
}
}
``` | throws Exception in finally blocks | [
"",
"java",
"exception",
"try-catch",
"finally",
""
] |
I've got an empty DIV element in which I append images by using function createElement("img") and append them with appendChild. So now I've got DIV element full of images.
I would like to use one button to clean this DIV and add new images in it simultaneously.
Thanks for your help | Are you just looking for method `replaceChild? Or you could remove all child elements before adding new images:`
```
// assuming yor div is in variable divelement
while (divelement.firstChild)
divelement.removeChild(divelement.firstChild);
``` | what do you mean by clean? If you just want to empty it, you can do
```
document.getElementById('mydiv').innerHTML = '';
```
And then add on whatever new images you want. | How do I "refresh" element in DOM? | [
"",
"javascript",
"dom",
""
] |
i have a tiny little problem with xslt, js and html entities, eg. within a template:
```
<script type="text/javascript">
<xsl:value-of select="/some/node"/>
for (var i = 0; i < 5; i++) {
// ^^^ js error
}
</script>
<script type="text/javascript">
<xsl:value-of select="/some/node"... | ok. long story, short answer:
it seems that with **some libxslt versions** the xslt processor leaves the content of a <script/> element unescaped when using the html output method, **with others
not** ... therefore the following is recommended:
```
<script type="text/javascript">
<xsl:value-of select="/some/node"... | > i always thought the xslt processor would leave the content of a script element unescaped when using the html output method
You are correct: <http://www.w3.org/TR/xslt#section-HTML-Output-Method>
```
The html output method should not perform escaping for the content of the script and style elements.
For example, a ... | xslt, javascript and unescaped html entities | [
"",
"javascript",
"xslt",
"html-entities",
""
] |
How do I get the current GLOBAL mouse cursor type (hourglass/arrow/..)? In Windows.
Global - I need it **even if the mouse is ouside of my application** or even if my program is windlowless.
In C#, Delphi or pure winapi, nevermind...
Thank you very much in advance!! | After thee years its time to answer my own question. Here's how you check if the current global cursor is hourglass in C# (extend the code for you own needs if you need):
```
private static bool IsWaitCursor()
{
var h = Cursors.WaitCursor.Handle;
CURSORINFO pci;
pci.cbSize = Marshal.SizeOf(typeof(CURSORIN... | To get the information on global cursor, use [GetCursorInfo](http://msdn.microsoft.com/en-us/library/ms648389.aspx "GetCursorInfo on MSDN"). | get current mouse cursor type | [
"",
"c#",
"delphi",
"winapi",
"vb6",
""
] |
I am using `<a>` tags for links on a web page. How do I disable the `Tab` key from selecting either of them? | **EDIT:** Hi, original author of this answer here. Don't use this one. Scroll down. StackOverflow won't let me remove this answer since it was accepted.
---
You could do something like this for those links:
```
<a href="http://foo.bar" onfocus="this.blur()">Can't focus on this!</a>
```
You should use the answer be... | Alternatively you could go for plain HTML solution.
```
<a href="http://foo.bar" tabindex="-1">inaccessible by tab link</a>
```
The [HTML5 spec says](http://www.w3.org/TR/html5/editing.html#attr-tabindex):
> **If the value is a negative integer**
> The user agent must set the element's tabindex focus flag, but sho... | How do I disable tabs for <a> tag | [
"",
"javascript",
"html",
"dom-events",
""
] |
How can I ignore an output parameter of a stored procedure? I'm calling the procedure from another procedure, e.g.:
```
DECLARE @param1 integer
EXEC mystoredprocedure
@in_param_1,
@in_param2_,
@param1 OUTPUT,
-- what do I type here to ignore the second output param??
```
I'm using T-SQL (MS SQL 2... | You can just use NULL as the last parameter, and it should work fine - as long as that parameter isn't expected for input logic in the proc as well.
In your case, you'd call the proc as
```
exec mystoredproc @in_param_1, @in_param2_, @param1 OUTPUT, null
```
Here's another example that for the same scenario...
```
... | The output parameter has to have a default in order for you to not pass it. See below
```
create proc x (@in int = null, @out int = null OUTPUT)
as
Begin
Select @in
End
exec x 1
```
**EDIT**
To clarify a little, the error is being returned because the stored procedure that is being called has a parameter defin... | Is it possible to ignore an output param of a stored procedure? | [
"",
"sql",
"sql-server-2005",
"t-sql",
"stored-procedures",
""
] |
I am not familiar with PHP at all and had a quick question.
I have 2 variables `pricePerUnit` and `InvoicedUnits`. Here's the code that is setting these to values:
```
$InvoicedUnits = ((string) $InvoiceLineItem->InvoicedUnits);
$pricePerUnit = ((string) $InvoiceLineItem->PricePerUnit);
```
If I output this, I get t... | ```
$rootbeer = (float) $InvoicedUnits;
```
Should do it for you. Check out [Type-Juggling](https://www.php.net/language.types.type-juggling). You should also read [String conversion to Numbers](https://www.php.net/manual/en/language.types.string.php#language.types.string.conversion). | You want the [non-locale-aware `floatval` function](http://php.net/function.floatval):
> float floatval ( mixed $var ) - Gets the float value of a string.
Example:
```
$string = '122.34343The';
$float = floatval($string);
echo $float; // 122.34343
``` | PHP String to Float | [
"",
"php",
"string",
"casting",
"floating-point",
""
] |
I encountered a, at least to my expectations, strange behavior in the binary serialization of .NET.
All items of a `Dictionary` that are loaded are added to their parent AFTER the `OnDeserialization` callback. In contrast `List` does the other way. This can be really annoying in real world repository code, for example... | I can reproduce the problem. Had a look around Google and found this: <http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=94265> although I'm not sure it's the exact same problem, it seems pretty similar.
EDIT:
I think that adding this code may have fixed the problem?
```
public void... | Yes, you've discovered an annoying quirk in `Dictionary<TKey, TValue>` deserialization. You can get around it by manually calling the dictionary's `OnDeserialization()` method:
```
public void OnDeserialization(object sender)
{
Dictionary.OnDeserialization(this);
TestsLengthsOfDataStructures(this);
}
```
Inci... | Strange behaviour of .NET binary serialization on Dictionary<Key, Value> | [
"",
"c#",
".net",
"serialization",
"dictionary",
"binary",
""
] |
I'm generating code dynamically, currently using String.Format and embedding placeholders - but reformatting the C# code for use as a template is a pain, and I think using a T4 template would be better.
However, the code generation will be happening on a running system, so I need to know that I can safely and legally ... | It looks like there may soon be another option.
Yesterday, Miguel de Icaza posted about T4 integration in MonoDevelop, so I'm expecting there to be a mono equivalent T4 toolset any time now.
See: <http://tirania.org/blog/archive/2009/Mar-10.html> | You can redistribute T4 as part of [DSLToolsRedist](http://www.microsoft.com/downloads/details.aspx?familyid=693EE22D-4BB1-450D-835C-59EEBCB9F2AE&displaylang=en), however, it requires Visual Studio 2005 standard edition or higher to be already installed. I don't believe that T4 can be legally redistributed without Visu... | Can I redistribute the Microsoft T4 Engine with my product? | [
"",
"c#",
"t4",
""
] |
Switch statements are typically faster than equivalent if-else-if statements (as e.g. descibed in this [article](http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx)) due to compiler optimizations.
How does this optimization actually work? Does anyone have a good explanation? | The compiler can build jump tables where applicable. For example, when you use the reflector to look at the code produced, you will see that for huge switches on strings, the compiler will actually generate code that uses a hash table to dispatch these. The hash table uses the strings as keys and delegates to the `case... | This is a slight simplification as typically any modern compiler that encounters a `if..else if ..` sequence that could trivially be converted into a switch statement by a person, the compiler will as well. But just to add extra fun the compiler is not restricted by syntax so can generate "switch" like statements inter... | If vs. Switch Speed | [
"",
"c#",
"performance",
"switch-statement",
"if-statement",
""
] |
For my university assignment I have to make a networkable version of pacman. I thought I would best approach this problem with making a local copy of pacman first and then extend this functionality for network play.
I would have to say that I am relatively new to java GUI development and utilizing such features within... | It looks like your call to Thread.sleep doesn't do what you intended, but I don't think it's the source of your trouble. You have:
`Thread.sleep(Math.max(0, startTime - System.currentTimeMillis()));`
startTime will always be less than System.currentTimeMillis(), so startTime - System.currentTimeMillis() will always b... | First off, I'd recommend that you use named constants rather than having random magic numbers in your code and consider using enums for your cell types. While it won't make your code run any faster, it certainly will make it easier to understand. Also, 'i' is normally used as a counter, not for a return value. You shou... | Pacman in Java questions | [
"",
"java",
"network-programming",
"pacman",
""
] |
I have a method which takes String argument. In some cases I want to pass int value to that method. For invoking that method I want to convert int into String. For that I am doing the following:
```
aMethod(""+100);
```
One more option is:
```
aMethod(String.valueOf(100));
```
Both are correct. I don't know... | Since you're mostly using it in GWT, I'd go with the ""+ method, since it's the neatest looking, and it's going to end up converted to javascript anyway, where there is no such thing as a StringBuilder.
Please don't hurt me Skeet Fanboys ;) | Using `+` on strings creates multiple string instances, so using `valueOf` is probably a bit more performant. | String conversions in Java | [
"",
"java",
"string",
""
] |
I'm speaking of this module:
<http://docs.python.org/library/operator.html>
From the article:
> The operator module exports a set of
> functions implemented in C
> corresponding to the intrinsic
> operators of Python. For example,
> operator.add(x, y) is equivalent to
> the expression x+y. The function names
> are th... | Possibly the most popular usage is operator.itemgetter. Given a list `lst` of tuples, you can sort by the ith element by: `lst.sort(key=operator.itemgetter(i))`
Certainly, you could do the same thing without operator by defining your own key function, but the operator module makes it slightly neater.
As to the rest, ... | One example is in the use of the `reduce()` function:
```
>>> import operator
>>> a = [2, 3, 4, 5]
>>> reduce(lambda x, y: x + y, a)
14
>>> reduce(operator.add, a)
14
``` | In what situation should the built-in 'operator' module be used in python? | [
"",
"python",
"operators",
""
] |
My question is best phrase as:
[Remove a child with a specific attribute, in SimpleXML for PHP](https://stackoverflow.com/questions/262351/remove-a-child-with-a-specific-attribute-in-simplexml-for-php)
except I'm not using simpleXML.
I'm new to XML for PHP so I may not be doing the best way
I have a xml created usin... | Ok, let’s try this complete example of use:
```
function CatRemove($myXML, $id) {
$xmlDoc = new DOMDocument();
$xmlDoc->load($myXML);
$xpath = new DOMXpath($xmlDoc);
$nodeList = $xpath->query('//category[@id="'.(int)$id.'"]');
if ($nodeList->length) {
$node = $nodeList->item(0);
$no... | So you want to remove the `category` node with a specific `id`?
```
$node = $xmlDoc->getElementById("12345");
if ($node) {
$node->parentNode->removeChild($node);
}
```
You could also use XPath to get the node, for example:
```
$xpath = new DOMXpath($xmlDoc);
$nodeList = $xpath->query('//category[@id="12345"]');
... | How do I remove a specific node using its attribute value in PHP XML Dom? | [
"",
"php",
"xml",
"dom",
"xml-attribute",
""
] |
I've seen a couple .net applications that allow you to select a C# .cs source file and the program itself will compile this code and run it.
How is this done? | It probably uses the CSharpCodeProvider class in the Microsoft.CSharp namespace. You would want to look at the following methods to compile code:
```
CompileAssemblyFromDom
CompileAssemblyFromFile
CompileAssemblyFromSource
``` | [CodeDOM](http://msdn.microsoft.com/en-us/library/650ax5cx.aspx) is your friend | How do I allow my .net program to compile C# code while running? | [
"",
"c#",
".net",
"compiler-construction",
"runtime",
""
] |
Is it possible that using jQuery, I **cancel/abort an Ajax request** that I have not yet received the response from? | Most of the jQuery Ajax methods return an XMLHttpRequest (or the equivalent) object, so you can just use `abort()`.
See the documentation:
* [abort Method](http://msdn.microsoft.com/en-us/library/ms535920%28VS.85%29.aspx) ([MSDN](http://en.wikipedia.org/wiki/Microsoft_Developer_Network)). Cancels the current HTTP req... | You can't recall the request but you can set a timeout value after which the response will be ignored. See this [page](http://docs.jquery.com/Ajax/jQuery.ajax#options) for jquery AJAX options. I believe that your error callback will be called if the timeout period is exceeded. There is already a default timeout on ever... | Abort Ajax requests using jQuery | [
"",
"javascript",
"jquery",
"ajax",
""
] |
Many of the standard c library (fwrite, memset, malloc) functions have direct equivalents in the Windows Api (WriteFile, FillMemory/ ZeroMemory, GlobalAlloc).
Apart from portability issues, what should be used, the CLIB or Windows API functions?
Will the C functions call the Windows Api functions or is it the other w... | There's nothing magical about the C library. It's just a standardized API for accessing common services from the OS. That means it's implemented on top of the OS, using the API's provided by the OS.
Use whichever makes sense in your situation. The C library is portable, Win32 isn't. On the other hand, Win32 is often m... | It's probably more information than you're looking for (and maybe not exactly what you asked) but Catch22.net has an article entitled "[Techniques for reducing Executable size](http://catch22.net/tuts/minexe)" that may help point out the differences in Win32 api calls and c runtime calls. | C library vs WinApi | [
"",
"c++",
"c",
"winapi",
"visual-c++",
""
] |
My main window has spawned a child window that's positioned on top to look like part of the main. I would like to move the child window in sync with the main but I'm not sure how.
My main window has my own title bar which event MouseLeftButtonDown calls this function:
```
public void DragWindow(object sender, MouseBu... | AH HAH!
My Main window has an event LocationChanged which I've tied to my UpdateChildWindowPosition(). LocationChange fires when (duh) the location changes so it's continuously firing as I move the window when DragMove() is being executed in my DragWindow posted above. | You can use the window's Left and Top properties to place the secondary window. Here's a rough bit of code as an example:
In the MainWindow code:
```
mDebugWindow.Left = this.Left + this.ActualWidth;
mDebugWindow.Top = this.Top;
```
In this case mDebugWindow is my child window. This code tells it to ... | Move two WPF windows at once? | [
"",
"c#",
".net",
"wpf",
""
] |
I have a list/queue of 200 commands that I need to run in a shell on a Linux server.
I only want to have a maximum of 10 processes running (from the queue) at once. Some processes will take a few seconds to complete, other processes will take much longer.
When a process finishes I want the next command to be "popped"... | I would imagine you could do this using make and the make -j xx command.
Perhaps a makefile like this
```
all : usera userb userc....
usera:
imapsync usera
userb:
imapsync userb
....
```
make -j 10 -f makefile | On the shell, `xargs` can be used to queue parallel command processing. For example, for having always 3 sleeps in parallel, sleeping for 1 second each, and executing 10 sleeps in total do
```
echo {1..10} | xargs -d ' ' -n1 -P3 sh -c 'sleep 1s' _
```
And it would sleep for 4 seconds in total. If you have a list of n... | Parallel processing from a command queue on Linux (bash, python, ruby... whatever) | [
"",
"python",
"ruby",
"bash",
"shell",
"parallel-processing",
""
] |
I was wondering if anyone had any experience in working programmatically with .pdf files. I have a .pdf file and I need to crop every page down to a certain size.
After a quick Google search I found the pyPdf library for python but my experiments with it failed. When I changed the cropBox and trimBox attributes on a p... | [pyPdf](https://pypi.org/project/pyPdf/) does what I expect in this area. Using the following script:
```
#!/usr/bin/python
#
from pyPdf import PdfFileWriter, PdfFileReader
with open("in.pdf", "rb") as in_f:
input1 = PdfFileReader(in_f)
output = PdfFileWriter()
numPages = input1.getNumPages()
print ... | Use this to get the dimension of pdf
```
from PyPDF2 import PdfWriter, PdfReader, PdfMerger
reader = PdfReader("/Users/user.name/Downloads/sample.pdf")
page = reader.pages[0]
print(page.cropbox.lower_left)
print(page.cropbox.lower_right)
print(page.cropbox.upper_left)
print(page.cropbox.upper_right)
```
After this g... | Cropping pages of a .pdf file | [
"",
"python",
"pdf",
"pypdf",
""
] |
I would like to have a function that modifies some variable list of parameters but they are all value types (int, string). There is a way to make the params keyword work with ref keyword or something close to that?
```
public void funcParams(params object[] list)
{
/* Make something here to change 'a', 'b' and 'c' ... | Yes. It is possible.
However, the resulting code is "unsafe" which makes it unverifiable.
That may or may not be an issue depending on your requirements.
In any case, here is the code:
```
using System;
namespace unsafeTest
{
class MainClass
{
public static void Main(string[] args)
{
... | Well, you could declare a few overloads, i.e.
```
public void FuncParams(ref int a) {...}
public void FuncParams(ref int a, ref int b) {...}
```
etc
Otherwise, you'll have to read back from the array (as `params` really means "implicit array"):
```
object[] args = {1,2,3};
funcParams(args);
Console.WriteLine(args[0... | There is a way to pass-by-reference using variable parameters in C#? | [
"",
"c#",
"reference",
"parameters",
""
] |
```
this.String = {
Get : function (val) {
return function() {
return val;
}
}
};
```
What is the ':' doing? | Others have already explained what this code does. It creates an object (called `this.String`) that contains a single function (called `Get`). I'd like to explain when you could use this function.
This function can be useful in cases where you need a higher order function (that is a function that expects another funct... | `this.String = {}` specifies an object. `Get` is a property of that object. In javascript, object properties and their values are separated by a colon ':'.
So, per the example, you would call the function like this
```
this.String.Get('some string');
```
More examples:
```
var foo = {
bar : 'foobar',
other : {
... | What is this javascript code doing? | [
"",
"javascript",
""
] |
If I have sequence of sequences (maybe a list of tuples) I can use itertools.chain() to flatten it. But sometimes I feel like I would rather write it as a comprehension. I just can't figure out how to do it. Here's a very construed case:
Let's say I want to swap the elements of every pair in a sequence. I use a string... | With a comprehension? Well...
```
>>> seq = '012345'
>>> swapped_pairs = zip(seq[1::2], seq[::2])
>>> ''.join(item for pair in swapped_pairs for item in pair)
'103254'
``` | Quickest I've found is to start with an empty array and extend it:
```
In [1]: a = [['abc', 'def'], ['ghi'],['xzy']]
In [2]: result = []
In [3]: extend = result.extend
In [4]: for l in a:
...: extend(l)
...:
In [5]: result
Out[5]: ['abc', 'def', 'ghi', 'xzy']
```
This is over twice as fast for the exam... | Comprehension for flattening a sequence of sequences? | [
"",
"python",
"sequences",
"list-comprehension",
""
] |
Are there any free libraries that would "print" to a PDF without actually having to install a PDF printer on the system. I want something that can be completely self contained in my application. The reason I say I want it to "print" is that I've tried and tried to find a solution for directly converting from HTML with ... | [PDFsharp](http://pdfsharp.com/) | Does it have to be free? Last time I looked at [ABCpdf](http://www.websupergoo.com/abcpdf-1.htm) it looked quite good, and claims to support css ([here](http://www.websupergoo.com/helppdf5net/source/3-concepts/g-htmlrender.htm)).
[HTMLDOC](http://www.easysw.com/htmldoc/) should support css at some point, but last time... | C# PDF Printing Library | [
"",
"c#",
"html",
"pdf",
"pdf-generation",
""
] |
I have a cache which has soft references to the cached objects. I am trying to write a functional test for behavior of classes which use the cache specifically for what happens when the cached objects are cleared.
The problem is: I can't seem to reliably get the soft references to be cleared. Simply using up a bunch o... | > The problem is: I can't seem to
> reliably get the soft references to be
> cleared.
This is not unique to SoftReferences. Due to the nature of garbage collection in Java, there is no guarantee that anything that is garbage-collectable will actually be collected at any point in time. Even with a simple bit of code:
... | There is also the following JVM parameter for tuning how soft references are handled:
```
-XX:SoftRefLRUPolicyMSPerMB=<value>
```
Where 'value' is the number of milliseconds a soft reference will remain for every free Mb of memory. The default is 1s/Mb, so if an object is only soft reachable it will last 1s if only 1... | How to cause soft references to be cleared in Java? | [
"",
"java",
"garbage-collection",
"soft-references",
""
] |
For a typical J2EE web application, the datasource connection settings are stored as part of the application server configuration.
Is there a way to version control these configuration details? I want more control on the datasource and other application server config changes.
What is the standard practice for doing t... | Tracking configuration changes to your application server through version control is a good thing to ask for. However, It does imply that all changes are done via scripting, instead of the administrative web interface. I recommend
<http://www.ibm.com/developerworks/java/library/j-ap01139/index.html?ca=drs->
as a good... | Websphere canbe tricky as the directory structure is a mess of files - often there appears to be duplicates and it's hard to figure which is the magic file you need to backup / restore . The question of how to go about this should not detract from the need to do it. - which is a definite yes. | Should I implement source control for j2ee application server configuration files? | [
"",
"java",
"version-control",
"jakarta-ee",
"configuration-management",
""
] |
How do I do this in linq?
```
var p = new pmaker();
foreach (var item in itemlist)
{
var dlist = new List<Dummy>();
foreach (var example in item.examples)
{
dlist.Add(example.GetDummy());
}
p.AddStuff(item.X,item.Y,dlist);
}
// .. do stuff with p
``` | How about:
```
var qry = from item in itemlist
select new {item.X, item.Y,
Dummies = item.examples.Select(
ex => ex.GetDummy())
};
foreach (var item in qry)
{
p.AddStuff(item.X, item.Y, item.Dummies.ToList());
}
```
Not sure it is much clearer like this, though...... | if `itemlist` is a `List<T>` collection you could do:
```
var p = new pmaker();
itemlist.ForEach(item =>
p.AddStuff(item.X, item.Y,
(from ex in item.examples
select ex.GetDummy()).ToList())
);
```
but if it's clearer this way? I think not, you should not use LINQ and delegates just because you like t... | foreach to linq tip wanted | [
"",
"c#",
"linq",
""
] |
I've been struggling with this one SQL query requirement today that I was wondering if someone could help me with.
I have a table of sports questions. One of the columns is the team related to the question. My requirement is to return a set number of random questions where the teams are unique.
So lets say we have th... | for sql 2005 you can do this:
```
select top 5 *
from (
select ROW_NUMBER() over(partition by team order by team) as RN, *
from @t
) t
where RN = 1
order by NEWID()
``` | This should do what you need, in oracle; for a different database you'll need to use their random number source, obviously. There's probably a better way; lets hope someone else will point it out to us :p
```
select question, answer, team
from
(
select question, answer, team, r
from
(
select
question,
answer... | How to select a set number of random records where one column is unique? | [
"",
"sql",
"random",
""
] |
How do I create test suites with JUnit 4?
All the documentation I've seen doesn't seem to be working for me. And if I use the Eclipse wizard it doesn't give me an option to select any of the test classes I have created. | ```
import org.junit.runners.Suite;
import org.junit.runner.RunWith;
@RunWith(Suite.class)
@Suite.SuiteClasses({TestClass1.class, TestClass2.class})
public class TestSuite {
//nothing
}
``` | You can create a suite like so. For example an `AllTest` suite would look something like this.
```
package my.package.tests;
@RunWith(Suite.class)
@SuiteClasses({
testMyService.class,
testMyBackend.class,
...
})
public class AllTests {}
```
Now you can run this in a couple different ways:
1. right-clic... | JUnit 4 Test Suites | [
"",
"java",
"junit",
"test-suite",
""
] |
I am using the Asp.net OutputCache on a page containing a usercontrol that in certain circumstances when the usercontrol is edited i want to be able to expire the page cache and reload the page with fresh data.
Is there any way i can do this from within the usercontrol?
If not, what are some other methods of caching ... | After some more research I found a method that seems to work well.
```
Dim cachekey As String = String.Format("Calendar-{0}", calendarID)
HttpContext.Current.Cache.Insert(cachekey, DateTime.Now, Nothing, System.DateTime.MaxValue, System.TimeSpan.Zero, System.Web.Caching.CacheItemPriority.NotRemovable, Nothing)
Respons... | You could try this:
```
private void RemoveButton_Click(object sender, System.EventArgs e)
{
HttpResponse.RemoveOutputCacheItem("/caching/CacheForever.aspx");
}
```
From: <http://aspalliance.com/668>
Thanks. | Asp.Net OutputCache and Expiration | [
"",
"c#",
"asp.net",
"vb.net",
"caching",
"outputcache",
""
] |
I have two expressions of type `Expression<Func<T, bool>>` and I want to take to OR, AND or NOT of these and get a new expression of the same type
```
Expression<Func<T, bool>> expr1;
Expression<Func<T, bool>> expr2;
...
//how to do this (the code below will obviously not work)
Expression<Func<T, bool>> andExpressio... | Well, you can use `Expression.AndAlso` / `OrElse` etc to combine logical expressions, but the problem is the parameters; are you working with the same `ParameterExpression` in expr1 and expr2? If so, it is easier:
```
var body = Expression.AndAlso(expr1.Body, expr2.Body);
var lambda = Expression.Lambda<Func<T,bool>>(b... | You can use Expression.AndAlso / OrElse to combine logical expressions, but you have to make sure the ParameterExpressions are the same.
I was having trouble with EF and the [PredicateBuilder](http://www.albahari.com/nutshell/predicatebuilder.aspx) so I made my own without resorting to Invoke, that I could use like th... | Combining two expressions (Expression<Func<T, bool>>) | [
"",
"c#",
"linq",
"lambda",
"expression",
""
] |
Sorry if this is a comp-sci 101 question. I'm just unsure if I'm missing something obvious.
So let's say some user input throws an error, and I want to catch it and return some feedback. The error will be a number, 0 - 8. 0 means "No Error". I want to give the user very specific feedback if the error is 3 (No numbers ... | logically the following are identical ( excuse my pseudo code )
```
(! expression_one || ! expression_two) /** this is the same as the one below **/
! (expression_one && expression_two)
```
Functionally which one is more optimal? They are both as optimal as each other. Both ways (&& and ||) allow short circuiting if ... | It will be much more readable if you use a switch statement:
```
switch ($_error) {
case 0;
nothing happens;
break;
case 3:
bunch of stuff happens;
break;
default:
bunch of other stuff;
break;
}
``` | Logical Operators: is AND better than OR? | [
"",
"php",
"error-handling",
"logic",
""
] |
I have a struct like this:
```
class Items
{
private:
struct item
{
unsigned int a, b, c;
};
item* items[MAX_ITEMS];
}
```
Say I wanted to 'delete' an item, like so:
```
items[5] = NULL;
```
And I created a new item on that same spot later:
```
items[5] = new item;
```
Would I still need ... | You need to call `delete` before setting it to NULL. (Setting it to NULL isn't required, it just helps reduce bugs if you accidentally try to dereference the pointer after deleting it.)
Remember that every time you use `new`, you will need to use `delete` later on the same pointer. Never use one without the other.
Al... | As Kluge pointed out, you'd leak the object at index 5 like that. But this one really sounds like you shouldn't do this manually but use a container class inside `Item`. If you don't actually need to store these `item` objects as pointers, use `std::vector<item>` instead of that array of `MAX_ITEMS` pointers. You can a... | Array of structs and new / delete | [
"",
"c++",
"arrays",
"memory-management",
"struct",
"new-operator",
""
] |
I have been programming in C# and Java for a little over a year and have a decent grasp of object oriented programming, but my new side project requires a database-driven model. I'm using C# and Linq which seems to be a very powerful tool but I'm having trouble with designing a database around my object oriented approa... | Linq to SQL using a table per class solution:
<http://blogs.microsoft.co.il/blogs/bursteg/archive/2007/10/01/linq-to-sql-inheritance.aspx>
Other solutions (such as my favorite, LLBLGen) allow other models. Personally, I like the single table solution with a discriminator column, but that is probably because we often ... | I had the opposite problem: how to get my head around OO after years of database design. Come to that, a decade earlier I had the problem of getting my head around SQL after years of "structured" flat-file programming. There are jsut enough similarities betwwen class and data entity decomposition to mislead you into th... | How can an object-oriented programmer get his/her head around database-driven programming? | [
"",
"sql",
"linq",
"database-design",
"oop",
""
] |
I'm looking to connect or glue together two shapes or objects with a Line. These shapes will be generated dynamically, meaning I'll be calling a Web service on the backend to determine how many objects/shapes need to be created. Once this is determined, I'll need to have the objects/shapes connected together.
The meth... | 1. Use a Path or a Line below the shapes in stacking order or z index
2. Use instance.TransformToVisual() to get the transform of each shape
3. Use the transform to transform the centerpoint of each shape
4. Draw a line between the two centerpoints.
---
```
var transform1 = shape1.TransformToVisual(shape1.Parent as U... | I am trying much the same, but instead of the line going from one centre to the other I want the lines to stop at the edge of the two shapes.
In particular I have arrows at the end of the lines, and the arrows need to stop at the bounds of the shapes instead of going inside/behind the shape to its centre.
My shape is ... | Connecting two shapes together, Silverlight 2 | [
"",
"c#",
"wpf",
"silverlight",
"expression",
""
] |
```
public class WrapperTest {
static {
print(10);
}
static void print(int x) {
System.out.println(x);
System.exit(0);
}
}
```
In the above code `System.exit(0)` is used to stop the program. What argument does that method take? Why do we gave it as `0`. Can anyone explain the c... | From the [JAVA Documentation](http://java.sun.com/javase/6/docs/api/java/lang/System.html#exit(int)):
> The argument serves as a status code;
> by convention, a nonzero status code
> indicates abnormal termination.
And [Wikipedia](http://en.wikipedia.org/wiki/Exitcode) adds additional information. | It's the return value that the Java process will report to the calling process.
It hasn't really got a precise definition, but the usual convention is that `0` means success and any non-zero value represents a failure. | Use of System.exit(0) | [
"",
"java",
"exit-code",
""
] |
I hope you know, because I don't see it. Bonus points for whoever figures out how one can achieve what this test is trying to achieve.
```
using NUnit.Framework;
using Moq;
[TestFixture]
public class MoqHuh
{
public class A {}
public class B : A {}
public interface IHelper
{
void DoIt(A a);
... | Turns out this was sort of pilot error. I incorrectly assumed Moq working fine on Mono.
(which it looks like it does just fine). This issue only happens when compiled with mono's gmcs, not when compiled with Microsofts csc.
I have reported the appropriate bugs with the mono team, and will continue towards making sure ... | This test works fine.
Since there is no system under test, you are testing that moq works as expected. | Why does this NUnit+Moq test fail? | [
"",
"c#",
"nunit",
"moq",
""
] |
I'm trying to iterate through an array of elements. jQuery's documentation says:
[jquery.Each() documentation](http://docs.jquery.com/Utilities/jQuery.each#objectcallback)
> Returning non-false is the same as a continue statement in a for loop, it will skip immediately to the next iteration.
I've tried calling 'retu... | What they mean by non-false is:
```
return true;
```
So this code:
```
var arr = ["one", "two", "three", "four", "five"];
$.each(arr, function(i) {
if (arr[i] == 'three') {
return true;
}
console.log(arr[i]);
});
```
```
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"... | By 'return non-false', they mean to return any value which would not work out to boolean false. So you could return `true`, `1`, `'non-false'`, or whatever else you can think up. | How to skip to next iteration in jQuery.each() util? | [
"",
"javascript",
"jquery",
"iteration",
""
] |
Given a `List<T>` in c# is there a way to extend it (within its capacity) and set the new elements to `null`? I'd like something that works like a `memset`. I'm not looking for sugar here, I want fast code. I known that in C the operation could be done in something like 1-3 asm ops per entry.
The best solution I've fo... | The simplest way is probably by creating a temporary array:
```
list.AddRange(new T[size - count]);
```
Where `size` is the required new size, and `count` is the count of items in the list. ~~However, for relatively large values of `size - count`, this can have bad performance, since it can cause the list to realloca... | ```
static IEnumerable<T> GetValues<T>(T value, int count) {
for (int i = 0; i < count; ++i)
yield return value;
}
list.AddRange(GetValues<object>(null, number_of_nulls_to_add));
```
This will work with 2.0+ | Set/extend List<T> length in c# | [
"",
"c#",
"list",
""
] |
I want to suppress the web browser's default tooltip display when a user hovers over certain links and elements. I know it's possible but I don't know how. Can anyone help?
The reason for this is to suppress the tooltip for microformatted date-times. The BBC dropped support for hCalendar because the appearane of the m... | **As far as I know it is not possible to actually *suppress* showing the title tag.**
There are some workarounds however.
Assuming you mean you want to preserve the title property on your links and elements, you could use Javascript to remove the title property at `onmouseover()` and set it again at `onmouseout()`.
... | Add this element to your html
```
onmouseover="title='';"
```
For example i have a asp.net checkbox I store a hidden variable but do not want the user to see on as the tooltip. | Disabling browser tooltips on links and <abbr>s | [
"",
"javascript",
"jquery",
"accessibility",
"microformats",
""
] |
How can I convert a BITMAP in byte array format to JPEG format using .net 2.0? | What type of `byte[]` do you mean? The raw file-stream data? In which case, how about something like (using `System.Drawing.dll` in a client application):
```
using(Image img = Image.FromFile("foo.bmp"))
{
img.Save("foo.jpg", ImageFormat.Jpeg);
}
```
Or use `FromStream` with a `new MemoryStream(ar... | If it is just a buffer of raw pixel data, and not a complete image file(including headers etc., such as a JPEG) then you can't use Image.FromStream.
I think what you might be looking for is System.Drawing.Bitmap.LockBits, returning a System.Drawing.Imaging.ImageData; this provides access to reading and writing the ima... | C#: How to convert BITMAP byte array to JPEG format? | [
"",
"c#",
".net",
"jpeg",
"bmp",
""
] |
I can implement the error function, erf, myself, but I'd prefer not to. Is there a python package with no external dependencies that contains an implementation of this function? I have found [this](http://pylab.sourceforge.net/packages/included_functions.html) but this seems to be part of some much larger package (and ... | Since v.2.7. the standard *math* module contains *erf* function. This should be the easiest way.
<http://docs.python.org/2/library/math.html#math.erf> | I recommend SciPy for numerical functions in Python, but if you want something with no dependencies, here is a function with an error error is less than 1.5 \* 10-7 for all inputs.
```
def erf(x):
# save the sign of x
sign = 1 if x >= 0 else -1
x = abs(x)
# constants
a1 = 0.254829592
a2 = -0.... | Is there an easily available implementation of erf() for Python? | [
"",
"python",
"math",
""
] |
A related post [here](https://stackoverflow.com/questions/435553/java-reflection-performance) pretty much established reflection in Java as a performance hog. Does that apply to the CLR as well? (C#, VB.NET, etc).
***EDIT***: How does the CLR compare to Java when it comes to reflection? Was that ever benchmarked? | I wouldn't really care about the instantiation performance of the object using reflection itself but the actual performance of methods and such since those are after all what I'll be using from the class anyway.
Surely the instantiation takes a lot of time as can be seen in the linked post but since you're most likely... | Yeah, reflection in .NET is a performance intensive operation too as it requires querying metadata tables in assemblies. | Reflection runtime performance - Java vs CLR | [
"",
"java",
"reflection",
"clr",
"performance",
""
] |
I want to use java.util.ConcurrentLinkedQueue as a non-durable queue for a Servlet.
Here's the blurb from the javadoc for the class.
> An unbounded thread-safe queue based on linked nodes. A ConcurrentLinkedQueue is an appropriate choice when many threads will share access to a common collection. This queue does not p... | You're essentially asking three different questions (two of them explicitly and one implicitly.) Here they are, with my answers:
**1. Do I need to do my own synchronization if I use `java.util.ConcurrentLinkedQueue`?**
Atomic operations on the concurrent collections are synchronized for you. In other words, each indi... | Remember that the queue is only threadsafe for calls to a single member. Don't write code like this and expect it to work:
```
if (queue.Count!=0)
queue.Dequeue().DoSomething();
```
In between these two operations, another thread may have dequeued the last element. I'm not intimate with Java collections, but I gu... | java.util.ConcurrentLinkedQueue | [
"",
"java",
"tomcat",
"servlets",
"concurrency",
"queue",
""
] |
I hope this question is not a RTFM one.
I am trying to write a Python script that extracts links from a standard HTML webpage (the `<link href...` tags).
I have searched the web for matching regexen and found many different patterns. Is there any agreed, standard regex to match links?
Adam
**UPDATE:**
I am actually l... | As others have suggested, if real-time-like performance isn't necessary, BeautifulSoup is a good solution:
```
import urllib2
from BeautifulSoup import BeautifulSoup
html = urllib2.urlopen("http://www.google.com").read()
soup = BeautifulSoup(html)
all_links = soup.findAll("a")
```
As for the second question, yes, HT... | Regexes with HTML get messy. Just use a DOM parser like Beautiful Soup. | Regex for links in html text | [
"",
"python",
"html",
"regex",
"hyperlink",
"href",
""
] |
I'm currently working on a project that contains many different Eclipse projects referencing each other to make up one large project. Is there a point where a developer should ask themselves if they should rethink the way their development project is structured?
**NOTE:** My project currently contains 25+ different Ec... | My general rule of thumb is I would create a new project for every reusable component. So for example if I have some isolated functionality that can be packaged say as a jar, I would create a new project so I can build,package and distribute the component independently.
Also, if there are certain projects that you do ... | If your project has *that* many sub-projects, or modules, needed to actually compose your final artifact then it is time to look at having something like Maven and setting up a multi-module project. It will a) allow you to work on each module independently without ide worries and allow easy setup in your ide (and other... | How many multiple "Eclipse Projects" is considered too excessive for one actual development project? | [
"",
"java",
"eclipse",
""
] |
I need to be able to list the command line arguments (if any) passed to other running processes. I have the PIDs already of the running processes on the system, so basically I need to determine the arguments passed to process with given PID *XXX*.
I'm working on a core piece of a [Python module for managing processes]... | To answer my own question, I finally found a CodeProject solution that does exactly what I'm looking for:
<http://www.codeproject.com/KB/threads/GetNtProcessInfo.aspx>
As @Reuben already pointed out, you can use [NtQueryProcessInformation](http://msdn.microsoft.com/en-us/library/ms684280(VS.85).aspx) to retrieve this... | The cached solution:
<http://74.125.45.132/search?q=cache:-wPkE2PbsGwJ:windowsxp.mvps.org/listproc.htm+running+process+command+line&hl=es&ct=clnk&cd=1&gl=ar&client=firefox-a>
```
in CMD
WMIC /OUTPUT:C:\ProcessList.txt PROCESS get Caption,Commandline,Processid
or
WMIC /OUTPUT:C:\ProcessList.txt path win32_process get... | Reading Command Line Arguments of Another Process (Win32 C code) | [
"",
"python",
"c",
"winapi",
""
] |
I have two models, `Room` and `Image`. `Image` is a generic model that can tack onto any other model. I want to give users a form to upload an image when they post information about a room. I've written code that works, but I'm afraid I've done it the hard way, and specifically in a way that violates DRY.
Was hoping s... | You don't have to use the Image class. As [DZPM](https://stackoverflow.com/users/30300/dzpm) suggested, convert the image field to an ImageField. You also need to make some changes to the view.
Instead of using an upload handler, you can create a Image object with the uploaded data and attach the Image object to the R... | Why don't you just use `ImageField`? I don't see the need for the `Image` class.
```
# model
class Room(models.Model):
name = models.CharField(max_length=50)
image = models.ImageField(upload_to="uploads/images/")
# form
from django import forms
class UploadFileForm(forms.Form):
name = forms.CharField(max... | Adding a generic image field onto a ModelForm in django | [
"",
"python",
"django",
"django-forms",
""
] |
EIMI being an explicit interface member implementation. So instead of:
```
public int SomeValue{get;}
```
you have
```
int SomeInterface.SomeValue {get;}
```
I'm currently considering using one as i'm using an internal interface (to decouple, yet restrict) and I don't want to make the methods on the implementing ob... | Yep, that's a good use case. According to [C# Language Specification](http://msdn.microsoft.com/en-us/library/aa664591(VS.71).aspx) on MSDN:
> Explicit interface member implementations serve two primary purposes:
>
> * Because explicit interface member implementations are not accessible through class or struct instanc... | A very good example is in the .Net generic collections classes.
For example, `List<T>` implements 'IList' implicitly and `IList` (non generic interface) explicitly. That means when you use the class directly you'll only see the specialized methods and not the ones that work with Object.
Let's say you instantiate a `L... | Whats a good use case for an EIMI? | [
"",
"c#",
".net",
"interface",
""
] |
Previously I've asked about [inserting a column into a dataset](https://stackoverflow.com/questions/351557/how-does-one-insert-a-column-into-a-dataset-between-two-existing-columns). I now have a similar question...namely merging two or more columns into a single column.
Lets say I have the following data set:
```
Dat... | it seems to me that this should happen in the data layer and not the logic layer. presumably the dataset consumer knows what data it needs and could request it from the datastore explicitly, without having to manipulate datasets.
in a database scenario, i'm essentially proponing a multiple stored procedure approach an... | ```
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DataSet ds = new DataSet();
ds.Tables.Add(new DataTable());
ds.Tables[0].Columns.Add("id", typeof(int));
ds.Tables[0].Columns.Add("firstname", typeof(string));
ds.Tables[0].Columns.A... | How do I merge two columns in a DataSet? | [
"",
"c#",
"merge",
"dataset",
""
] |
I'm trying to generate a sales reports which lists each product + total sales in a given month. Its a little tricky because the prices of products can change throughout the month. For example:
* Between Jan-01 and Jan-15, my company sells 50 Widgets at a cost of $10 each
* Between Jan-15 and Jan-31, my company sells 5... | If you start storing start and end dates, or create a view that includes the start and end dates (you can even create an indexed view) then you can heavily simplify your query. (provided you are certain there are no range overlaps)
```
SELECT
Sale_ID,
Product_ID,
Sale_Date,
Price
FROM Sales
JOIN Prices... | It's well to avoid these types of correlated subqueries. Here's a classic technique for such cases.
```
SELECT
Sale_ID,
Product_ID,
Sale_Date,
p1.Price
FROM Sales AS s
LEFT JOIN Prices AS p1 ON s.ProductID = p1.ProductID
AND s.Sale_Date >= p1.Sale_Date
LEFT JOIN Prices AS p2 ON s.Pro... | Optimizing Query With Subselect | [
"",
"sql",
"sql-server",
"optimization",
""
] |
Suppose assembly Assembly1.dll contains 3 classes: Class C1, C2, C3.
I want to expose only class C1 to the outside world. Classes C2 and C3 will not be accessible. How to acheive this?
Note: Making classes C2 and C3 private is not an option as this will make them unaccessible inside the assembly itself. | Make classes C2 and C3 internal, as in:
```
internal class C2
{
//...
}
``` | As others have said, you use `internal` visibility. A couple more points though:
* For non-nested types, internal is actually the default in C#, so you don't *have* to specify it. Whether or not you explicitly specify the default access is a matter of personal taste. (I'm currently on the fence, leaning towards being ... | How to expose only one particular class from an assembly? | [
"",
"c#",
"oop",
"assemblies",
""
] |
I've managed to find the Regex to get almost the result I want here i.e.
```
Regex r1 = new Regex(@"\[(.*?)\]");
string row = HEADERNAMES[COL1,COL2,COL3,COL4];
Match match = r1.Match(row);
string result = match.ToString();
```
Outputs: "[COL1,COL2,COL3,COL4]";
I know I can then use:
```
result.Replace("[", "");
res... | ```
Regex r1 = new Regex(@"\[(.+)\]");
string row = "HEADERNAMES[COL1, COL2, COL3, COL4]";
// Regex puts capture groups (i.e. things captured between ( and ) )
// in Groups collection
string match = r1.Match(row).Groups[1].Value;
//match = "COL1, COL2, COL3, COL4"
``` | There's one major point to observe in the solution presented by "Aku" (I don't yet have the rep to comment)
You should note that the 2nd item in the Groups collection provides the value you need. The first item (Groups(0)) is equivalent to the entire matched string (Match.ToString() or Match.Value) | Regex to match a substring within 2 brackets, e.g. [i want this text] BUT leave out the brackets? | [
"",
"c#",
".net",
"regex",
""
] |
Are there any tools that can take a fully-constructed/wired Spring application context and export a visualization of it? I'm talking about a live context that shows the order in which aspects were applied, what beans were auto-wired into other beans, etc.
I know it can be done with the context files themselves (re: Sp... | I am looking for the same tool. Unfortunately, I do not see any other possibility than to wait for Spring 3.2 where should be that feature. See <https://jira.springsource.org/browse/SPR-9662> | I have written an ApplicationContextDumper to dump live spring application context into log. It shows autowired beans and beans loaded by component scan, but can't show which aspect is applied.
Source code and example in <https://gist.github.com/aleung/1347171> | Is there tooling to visualize a live Spring application context? | [
"",
"java",
"spring",
"spring-ide",
""
] |
We have a bit of a messy database situation.
Our main back-office system is written in Visual Fox Pro with local data (yes, I know!)
In order to effectively work with the data in our websites, we have chosen to regularly export data to a SQL database. However the process that does this basically clears out the tables... | There are a lot of ways to skin this cat.
I would attack the locking issues first. It is extremely rare that I would use CURSORS, and I think improving the performance and locking behavior there might resolve a lot of your issues.
I expect that I would solve it by using two separate staging tables. One for the FoxPro... | You should be able to maintain one db for the website and just replicate to that table from the other sql db table.
This is assuming that you do not update any data from the website itself. | Effectively transforming data from one SQL database to another in live environment | [
"",
"sql",
"sql-server-2005",
"visual-foxpro",
"foxpro",
""
] |
I want to repeatedly execute a function in Python every 60 seconds forever (just like an [NSTimer](http://web.archive.org/web/20090823012700/http://developer.apple.com:80/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html) in Objective C or setTimeout in JS). This code will run as a d... | If your program doesn't have a event loop already, use the [sched](http://docs.python.org/library/sched.html) module, which implements a general purpose event scheduler.
```
import sched, time
def do_something(scheduler):
# schedule the next call first
scheduler.enter(60, 1, do_something, (scheduler,))
p... | Lock your time loop to the system clock like this:
```
import time
starttime = time.monotonic()
while True:
print("tick")
time.sleep(60.0 - ((time.monotonic() - starttime) % 60.0))
```
Use a 'monotonic' clock to work properly; time() is adjusted by solar/legal time changes, ntp synchronization, etc... | How to repeatedly execute a function every x seconds? | [
"",
"python",
"timer",
""
] |
I create a plugin which includes the following folder structure:
* src
* native/so/libsystemcommand.so
* META-INF/MANIFEST.MF
The manifest include the command
```
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Commands Plug-in
Bundle-SymbolicName: de.system.commands;singleton:=true
Bundle-Version: 1.0.... | I think i found the solution.
We only build the plugin which was not working and copy it to the destination platform directory. After this we start the application as wtach the log files whether the library was foud or not.
What we miss, was to **delete the configurations folder**. The new plugin was not unzipp and t... | I wonder if the library needs to be specified without the lib prefix? E.g.,
```
System.loadLibrary("systemcommand");
```
Since that is how the library would be passed on a gcc link line. | Use Bundle-NativeCode on Linux does not work | [
"",
"java",
"linux",
"eclipse-plugin",
"shared-libraries",
"bundle",
""
] |
Is it possible to use If Else conditional in a LINQ query?
Something like
```
from p in db.products
if p.price>0
select new
{
Owner=from q in db.Users
select q.Name
}
else
select new
{
Owner = from r in db.ExternalUsers
select r.Name
}
``` | This might work...
```
from p in db.products
select new
{
Owner = (p.price > 0 ?
from q in db.Users select q.Name :
from r in db.ExternalUsers select r.Name)
}
``` | I assume from `db` that this is LINQ-to-SQL / Entity Framework / similar (not LINQ-to-Objects);
Generally, you do better with the conditional syntax ( a ? b : c) - however, I don't know if it will work with your different queries like that (after all, how would your write the TSQL?).
For a trivial example of the type... | If Else in LINQ | [
"",
"c#",
"linq",
"linq-to-sql",
""
] |
I have a date input field that allows the user to enter in a date and I need to validate this input (I already have server side validation), but the trick is that the format is locale dependent. I already have a system for translating the strptime format string to the the user's preference and I would like to use this ... | After a few days of googling I found [this implementation](https://web.archive.org/web/20210726055034/http://www.logilab.org/blogentry/6731) which, although not complete, seems to handle all of the cases I have right now. | I've just added our php.js implementation of [strptime()](http://github.com/kvz/phpjs/blob/master/functions/datetime/strptime.js); I've tested it a bit, but it needs further unit testing. Anyhow, feel free to give it a shot; it should cover everything that PHP does (except for not yet supporting the undocumented %E... ... | strptime in Javascript | [
"",
"javascript",
"strptime",
"phpjs",
""
] |
A regular function can contain a call to itself in its definition, no problem. I can't figure out how to do it with a lambda function though for the simple reason that the lambda function has no name to refer back to. Is there a way to do it? How? | The only way I can think of to do this amounts to giving the function a name:
```
fact = lambda x: 1 if x == 0 else x * fact(x-1)
```
or alternately, for earlier versions of python:
```
fact = lambda x: x == 0 and 1 or x * fact(x-1)
```
**Update**: using the ideas from the other answers, I was able to wedge the fac... | without reduce, map, named lambdas or python internals:
```
(lambda a:lambda v:a(a,v))(lambda s,x:1 if x==0 else x*s(s,x-1))(10)
``` | Can a lambda function call itself recursively in Python? | [
"",
"python",
"recursion",
"lambda",
"y-combinator",
""
] |
I'm trying to work with [fractions](http://en.wikipedia.org/wiki/Fraction_%28mathematics%29#Vulgar.2C_proper.2C_and_improper_fractions) in Java.
I want to implement arithmetic functions. For this, I will first require a way to normalize the functions. I know I can't add 1/6 and 1/2 until I have a common denominator. I... | It just so happens that I wrote a BigFraction class not too long ago, for [Project Euler problems](http://projecteuler.net). It keeps a BigInteger numerator and denominator, so it'll never overflow. But it'll be a tad slow for a lot of operations that you know will never overflow.. anyway, use it if you want it. I've b... | * Make it [immutable](http://en.wikipedia.org/wiki/Immutable_object);
* Make it [canonical](http://en.wikipedia.org/wiki/Canonical#Mathematics), meaning 6/4 becomes 3/2 ([greatest common divisor](http://en.wikipedia.org/wiki/Greatest_common_divisor) algorithm is useful for this);
* Call it Rational, since what you're r... | Best way to represent a fraction in Java? | [
"",
"java",
"math",
"fractions",
""
] |
AFAIK ROWID in Oracle represents physical location of a record in appropriate datafile.
In which cases ROWID of a record may change ?
The one known to me is UPDATE on partitioned table that "moves" the record to another partition.
Are there another cases ? Most of our DBs are Oracle 10. | As you have said, it occurs anytime the row is physically moved on disk, such as:
* Export/import of the table
* ALTER TABLE XXXX MOVE
* ALTER TABLE XXXX SHRINK SPACE
* FLASHBACK TABLE XXXX
* Splitting a partition
* Updating a value so that it moves to a new partition
* Combining two partitions
If is in an index orga... | Another +1 to WW, but just to add a little extra...
If the driving question is whether you can store ROWIDs for later use, I would say "don't do it".
You are fine to use ROWIDs within a transaction - for example collecting a set of ROWIDs on which to carry out a subsequent operations - but you should *never* store th... | What can cause an Oracle ROWID to change? | [
"",
"sql",
"database",
"oracle",
"rowid",
""
] |
I'm planning to start on a new project and am looking at the current state-of-the-art Java web frameworks. I decided to build my application around Guice, and am likely to use a very lightweight ORM like Squill/JEQUEL/JaQu or similar, but I can't decide on the web framework. Which one would fit best in such a lightweig... | I have gathered some experience on this topic, as I started to program on a new project in November. The project is in a late stage now.
For me, the following design guidelines were important:
* Use a modern technology stack that is both fun to use and will be in general use in future.
* Reduce the number of project ... | [Wicket has a Guice module built in](http://herebebeasties.com/2007-06-20/wicket-gets-guicy/), which I haven't used (but I have used [Wicket](http://en.wikipedia.org/wiki/Apache_Wicket) quite a bit, and liked it). | Which Java Web Framework fits best with Google Guice? | [
"",
"java",
"dependency-injection",
"guice",
""
] |
I've found a few articles & discussions on how to import data from Access to SQL Server or SQL Server Express, but not to SQL Server CE. I can access both the the Access data and CE data in the VS database explorer with seperate connections, but don't know how to move the data from one to the other. (I'm using c#.) Any... | You might look at [PrimeWorks' DataPort Wizard](http://www.primeworks-mobile.com/Products/DataPortWizard.html). | You can do it using [SSIS](http://en.wikipedia.org/wiki/SQL_Server_Integration_Services), or even in SQL Server Explorer if you are not looking to do it programmatically. | Import Access data into SQL Server CE (.mdb to .sdf) | [
"",
"c#",
".net",
"sql-server-ce",
""
] |
I know VB.Net and am trying to brush up on my C#. Is there a `With` block equivalent in C#? | This is what Visual C# program manager has to say:
[Why doesn't C# have a 'with' statement?](https://learn.microsoft.com/en-us/archive/blogs/csharpfaq/why-doesnt-c-have-vb-nets-with-operator)
> Many people, including the C# language designers, believe that 'with'
> often harms readability, and is more of a curse than ... | Although C# doesn't have any direct equivalent for the general case, C# 3 gain object initializer syntax for constructor calls:
```
var foo = new Foo { Property1 = value1, Property2 = value2, etc };
```
See chapter 8 of C# in Depth for more details - you can download it for free from [Manning's web site](http://manni... | With block equivalent in C#? | [
"",
"c#",
".net",
"vb.net",
""
] |
I am working on a script that will process user uploads to the server, and as an added layer of security I'd like to know:
Is there a way to detect a file's true extension/file type, and ensure that it is not another file type masked with a different extension?
Is there a byte stamp or some unique identifier for each... | Not really, no.
You will need to read the first few bytes of each file and interpret it as a header for a finite set of known filetypes. Most files have distinct file headers, some sort of metadata in the first few bytes or first few kilobytes in the case of MP3.
Your program will have to simply try parsing the file ... | PHP has a couple of ways of reading file contents to determine its MIME type, depending on which version of PHP you are using:
Have a look at the [Fileinfo functions](http://php.net/manual/en/ref.fileinfo.php) if you're running PHP 5.3+
```
$finfo = finfo_open(FILEINFO_MIME);
$type = finfo_file($finfo, $filepath);
f... | How can I determine a file's true extension/type programmatically? | [
"",
"php",
"security",
"file-upload",
"file-type",
""
] |
## I challenge you :)
I have a process that someone already implemented. I will try to describe the requirements, and I was hoping I could get some input to the "best way" to do this.
---
It's for a financial institution.
I have a routing framework that will allow me to recieve files and send requests to other syst... | Simplify as much as possible.
The batches (trying to process them as units, and their various sizes) appear to be discardable in terms of the simplest process. It sounds like the rows are atomic, not the batches.
Feed all the lines as separate atomic transactions through an asynchronous FIFO message queue, with a goo... | When you receive the file, parse it and put the information in the database.
Make one table with a record per line that will need a getPerson request.
Have one or more threads get records from this table, perform the request and put the completed record back in the table.
Once all records are processed, generate the... | Designing a process | [
"",
"java",
""
] |
I have a windows forms app with a textbox control that I want to only accept integer values. In the past I've done this kind of validation by overloading the KeyPress event and just removing characters which didn't fit the specification. I've looked at the MaskedTextBox control but I'd like a more general solution that... | Two options:
1. Use a [`NumericUpDown`](http://msdn.microsoft.com/en-us/library/system.windows.forms.numericupdown(v=vs.110).aspx) instead. NumericUpDown does the filtering for you, which is nice. Of course it also gives your users the ability to hit the up and down arrows on the keyboard to increment and decrement th... | And just because it's always more fun to do stuff in one line...
```
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
}
```
NOTE: This DOES NOT prevent a user from Copy / Paste into this textbox. It's not a fai... | How do I make a textbox that only accepts numbers? | [
"",
"c#",
".net",
"winforms",
"textbox",
""
] |
I've been trying to develop a linq query that returns the ItemNumber column of all my tables in the database, but so far I haven't been able to do it successfully.
Basically I have a table for each kind of hardware component in a computer, and each table has a ItemNumber column. I need to query all of the tables in on... | What you are describing is a union:
SELECT ItemNumber FROM tbl1 UNION SELECT ItemNumber FROM tbl2
In LINQ:
```
var itemCounts = (from hhd in dc.HHD select hhd.ItemNumber)
.Union((from hkb in dc.HKB select hkb.ItemNumber)
.Union(from hmm in dc.HMM select hmm.ItemNumber))
... | Don't use Union - instead use [Concat](http://msdn.microsoft.com/en-us/library/bb351755.aspx)!
* LinqToSql's *Union* is mapped to T-Sql's *Union*.
* LinqToSql's **Concat** is mapped to T-Sql's **Union All**.
The difference is that *Union* requires that the lists be checked against each other and have duplicates remov... | Linq to SQl, select same column from multiple tables | [
"",
"c#",
".net",
"linq",
"linq-to-sql",
""
] |
Is there an online Java book like *Dive into Python* for learning Python?
Other resources online besides the standard Java documentation (which is awesome but almost too technical)
. | Definitely "[Thinking in Java](http://www.mindview.net/Books/TIJ/)" by Bruce Eckel. | Hard to tell if you meant this by "standard online documentation" but the [Java Tutorial](http://java.sun.com/docs/books/tutorial/) is excellent and what many of us old-timers started with. | Online Java Book | [
"",
"java",
""
] |
I've been searching for a way to get all the strings that map to function names in a dll.
I mean by this all the strings for which you can call GetProcAddress. If you do a hex dump of a dll the symbols (strings) are there but I figure there must me a system call to acquire those names. | It takes a bit of work, but you can do this programmaticly using the [DbgHelp](http://msdn.microsoft.com/en-us/library/ms679291(VS.85).aspx "MSDN: DbgHelp Debugging Libraries") library from Microsoft.
[Debugging Applications for Microsoft .Net and Microsoft Windows, by John Robbins](https://rads.stackoverflow.com/amzn... | If you have MS Visual Studio, there is a command line tool called DUMPBIN.
```
dumpbin /exports <nameofdll>
``` | Is there a way to find all the functions exposed by a dll | [
"",
"c++",
"c",
"winapi",
"dll",
""
] |
I have this factory method in java:
```
public static Properties getConfigFactory() throws ClassNotFoundException, IOException {
if (config == null) {
InputStream in = Class.forName(PACKAGE_NAME).getResourceAsStream(CONFIG_PROP);
config = new Properties();
config.load(in);
}
return ... | A `RuntimeException` should be used only when the client cannot recover from whatever the problem is. It is occasionally appropriate to do what you are talking about, but more often it is not appropriate.
If you are using a JDK >= 1.4, then you can do something like:
```
try {
// Code that might throw an exception
... | Two points regarding exception handling best practices:
* **Caller code cannot do anything** about the exception -> Make it an **unchecked exception**
* **Caller code will take some useful recovery action** based on information in exception -> Make it a **checked exception**
And you may throw the RuntimeException wit... | Wrapping a checked exception into an unchecked exception in Java? | [
"",
"java",
"exception",
"checked-exceptions",
""
] |
I'm currently doing something like this in some code I'm working on right now:
```
public CommandType GetCommandTypeFromCommandString(String command)
{
if(command.StartsWith(CommandConstants.Acknowledge))
return CommandType.Acknowledge;
else if (command.StartsWith(CommandConstants.Status))
return Com... | One optimization would be to use the StringComparison enum to specify that you only want ordinal comparison. Like this:
```
if(command.StartsWith(CommandConstants.Acknowledge, StringComparison.Ordinal))
return CommandType.Acknowledge;
```
If you don't specify a string comparison method the current culture will be... | Similar in concept to the FSM answer by Vojislav, you could try putting the constants into a [trie](http://en.wikipedia.org/wiki/Trie). You can then replace your sequence of comparisons with a single traversal of the trie.
There is a C# trie implementation described [here](http://www.kerrywong.com/2006/04/01/implement... | More efficient way to determine if a string starts with a token from a set of tokens? | [
"",
"c#",
"optimization",
""
] |
In my C# application, I use a regular expression to validate the basic format of a US phone number to make sure that the user isn't just entering bogus data. Then, I strip out everything except numbers, so this:
> (123) 456-7890 x1234
becomes
> 12345678901234
in the database. In various parts of my application, how... | ```
String.Format("{0:(###) ###-#### x ###}", double.Parse("1234567890123"))
```
Will result in (123) 456-7890 x 123 | Using a regex you can replace:
```
(\d{3})(\d{3})(\d{4})(\d{4})
```
with:
```
(\1) \2-\3 x\4
```
(Though I'm not familiar with US phone numbers so maybe there's more to it.) | Converting a normalized phone number to a user-friendly version | [
"",
"c#",
"regex",
"formatting",
"phone-number",
""
] |
In javascript I have an array as follows:
```
var foo = [2, 2, 4, 4, 128, 2, 2, 1, 4, 18, 27, 16, 2, 1, 18, 21, 5, 1, 128, 1, 2, 2, 1, 18, 12, 60, 2, 28, 1, 17, 2, 3, 4, 2, 2, 2, 1, 27, 2, 17, 7, 2, 2, 2, 5, 1, 2, 4, 7, 1, 2, 1, 1, 1, 2, 1, 5, 7, 2, 7, 6, 1, 7, 1, 5, 8, 4];
```
And I am interested in finding a way (w... | My previous answer used a reverse index table, but contained some bugs - which are now fixed - and was harder to understand than the following code.
This is actually the slowest of all solutions given in the answers - for maximum performance, check my other answer.
```
var foo = [2, 2, 4, 4, 128, 2, 2, 1, 4, 18, 27, ... | Here's the de-bugged version of my previous answer using an index table. I did a little benchmarking and for the input given in the question, this solition will be faster than anything else which has been suggested in this thread till now:
```
var foo = [2, 2, 4, 4, 128, 2, 2, 1, 4, 18, 27, 16, 2, 1, 18, 21, 5, 1, 128... | Easiest way to derive subset array of highest 10 values? | [
"",
"javascript",
""
] |
I am writing a web service in Java, and I am **trying to figure out the best way to define error codes and their associated error strings**. I need to have a numerical error code and an error string grouped together. Both the error code and error string will be sent to the client accessing the web service. For example,... | Well there's certainly a better implementation of the enum solution (which is generally quite nice):
```
public enum Error {
DATABASE(0, "A database error has occurred."),
DUPLICATE_USER(1, "This user already exists.");
private final int code;
private final String description;
private Error(int code, Strin... | As far as I am concerned, I prefer to externalize the error messages in a properties files.
This will be really helpful in case of internationalization of your application (one properties file per language). It is also easier to modify an error message, and it won't need any re-compilation of the Java sources.
On my p... | Best way to define error codes/strings in Java? | [
"",
"java",
"enums",
""
] |
I know that there are many free and not so free compression libraries out there, but for the project i am working on, i need to be able to take file data from a stream and put it into some kind zip or pack file, but without compression, because i will need to access these files quickly without having to wait for them t... | You can use Zip for this. You would use a compression level of something like "none" or "store", which just combines the files without compression. [This site](http://help.globalscape.com/help/cutezip2/Compression_levels__effects.htm) enumerates some of them:
> * Maximum - The slowest of the
> compression options, b... | Have a look at [System.IO.Packaging](http://msdn.microsoft.com/en-us/library/system.io.packaging.aspx) namespace.
Quote from MSDN:
> System.IO.Packaging
>
> Provides classes that support storage
> of multiple data objects in a single
> container.
>
> Package is an abstract class that can
> be used to organize objects... | Create zip style file without compression | [
"",
"c#",
""
] |
I have to use a smart pointer and I found "shared\_ptr" from boost looks good. I downloaded the boost library and I can see many files and libraries there. Is there any way to use only the shared\_ptr ? | [`boost bcp`](http://www.boost.org/doc/libs/1_37_0/tools/bcp/bcp.html) is your friend. It allows extracting individual boost libraries out of its tree. I used it with success in the past. shared\_ptr consists only of headers, so that will be especially good for you. | You can use bcp as litb suggested, but if you're worried about dragging in extra library code, you shouldn't be. Boost, in general, follows the C++ philosophy of "you only pay for what you use". So, if you include only the shared\_ptr headers, that's all that your code will use. | Using boost shared_ptr | [
"",
"c++",
"boost",
""
] |
```
public class WrapperTest {
public static void main(String[] args) {
Integer i = 100;
Integer j = 100;
if(i == j)
System.out.println("same");
else
System.out.println("not same");
}
}
```
The above code gives the output of `same` when run, howe... | In Java, Integers between -128 and 127 (inclusive) are generally represented by the same Integer object instance. This is handled by the use of a inner class called IntegerCache (contained inside the Integer class, and used e.g. when Integer.valueOf() is called, or during autoboxing):
```
private static class IntegerC... | Basically Integers between -127 and 127 are 'cached' in such a way that when you use those numbers you always refer to the same number in memory, which is why your `==` works.
Any Integer outside of that range are not cached, thus the references are not the same. | Java Wrapper equality test | [
"",
"java",
"wrapper",
""
] |
I'm using Zend Framework 1.7.2, MySQL and the MySQLi PDO adapter. I would like to call multiple stored procedures during a given action. I've found that on Windows there is a problem calling multiple stored procedures. If you try it you get the following error message:
> SQLSTATE[HY000]: General error: 2014
> Cannot e... | I has same errors when called queries like this(variables to use in next query)
```
$db->query("SET @curr = 0.0;");
```
To fix this I've changed my config file to
```
'database' => array(
'adapter' => 'mysqli',
``` | This pattern of preparing, executing and then closing each $sql statement that calls a stored procedure does work.
```
public function processTeams($leagueid,$raceid,$gender)
{
$db = Zend_Db_Table::getDefaultAdapter();
$sql = $db->prepare(sprintf("CALL addScoringTeams(%d,%d,'%s')",$leagueid,$raceid,$gender));
... | Call Multiple Stored Procedures with the Zend Framework | [
"",
"php",
"mysql",
"zend-framework",
"stored-procedures",
""
] |
I have a list of Python objects that I want to sort by a specific attribute of each object:
```
[Tag(name="toe", count=10), Tag(name="leg", count=2), ...]
```
How do I sort the list by `.count` in descending order? | To sort the list in place:
```
orig_list.sort(key=lambda x: x.count, reverse=True)
```
To return a new list, use `sorted`:
```
new_list = sorted(orig_list, key=lambda x: x.count, reverse=True)
```
Explanation:
* `key=lambda x: x.count` sorts by count.
* `reverse=True` sorts in descending order.
More on [sorting b... | A way that can be fastest, especially if your list has a lot of records, is to use `operator.attrgetter("count")`. However, this might run on an pre-operator version of Python, so it would be nice to have a fallback mechanism. You might want to do the following, then:
```
try: import operator
except ImportError: keyfu... | How do I sort a list of objects based on an attribute of the objects? | [
"",
"python",
"list",
"sorting",
"reverse",
""
] |
I'm using levenshtein algorithm to meet these requirements:
When finding a word of N characters, the words to suggest as correction in my dictionary database are:
Every dictionary word of N characters that has 1 character of difference with the found word.
Example:
found word:bearn, dictionary word: bears
Every dict... | You may also want to add [Norvig's excellent article on spelling correction](http://norvig.com/spell-correct.html) to your reading.
It's been a while since I've read it but I remember it being very similar to what your writing about. | As I've said elsewhere, Boyer-Moore isn't really apt for this. Since you want to search for multiple stings simultanously, the algorithm of Wu and Manber should be more to your liking.
I've posted a proof of concept C++ code in answer to [another question](https://stackoverflow.com/questions/154365/search-25-000-words... | Levenshtein algorithm: How do I meet this text editing requirements? | [
"",
"c++",
"algorithm",
"pattern-matching",
"levenshtein-distance",
""
] |
Edit--@Uri correctly pointed out that this was an abuse of annotations; trying to actually create the menu data itself in annotations is just silly.
They are good for binding however, I think I'll stick with using them to link the text data to the methods (the @Menu ("File") portion) since it's more explicit and flexi... | The way I've seen multiple annotations attached is to use a container annotation, and then specify the items as an array.
```
@Retention(RetentionPolicy.RUNTIME)
public @interface Menu {
String name();
String[] children();
}
@Retention(RetentionPolicy.RUNTIME)
public @interface MenuBar {
Menu[] value();
}... | I know I'll get downvoted for this, but I really think people are starting to overabuse the annotation mechanism in Java.
All it was designed for was to be a mechanism for providing metainformation about classes and methods for the purpose of the compiler or of programming-support tools (e.g., testing infrastructure, ... | Help with annotations | [
"",
"java",
"user-interface",
"swing",
"reflection",
"annotations",
""
] |
I'm implementing `compareTo()` method for a simple class such as this (to be able to use `Collections.sort()` and other goodies offered by the Java platform):
```
public class Metadata implements Comparable<Metadata> {
private String name;
private String value;
// Imagine basic constructor and accessors here
... | Using **Java 8**:
```
private static Comparator<String> nullSafeStringComparator = Comparator
.nullsFirst(String::compareToIgnoreCase);
private static Comparator<Metadata> metadataComparator = Comparator
.comparing(Metadata::getName, nullSafeStringComparator)
.thenComparing(Metadata::getValue... | You can simply use [Apache Commons Lang](http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/ObjectUtils.html#compare(T,%20T)):
```
result = ObjectUtils.compare(firstComparable, secondComparable)
``` | How to simplify a null-safe compareTo() implementation? | [
"",
"java",
"refactoring",
"comparison",
"null",
"compareto",
""
] |
Given an instance of some class in Python, it would be useful to be able to determine which line of source code *defined* each method and property (e.g. to implement [1](https://stackoverflow.com/questions/465605/how-do-i-make-ipython-organize-tab-completion-possibilities-by-class)). For example, given a module ab.py
... | You are looking for the undocumented function `inspect.classify_class_attrs(cls)`. Pass it a class and it will return a list of tuples `('name', 'kind' e.g. 'method' or 'data', defining class, property)`. If you need information on absolutely everything in a specific instance you'll have to do additional work.
Example... | This is more-or-less impossible without static analysis, and even then, it won't always work. You can get the line where a function was defined and in which file by examining its code object, but beyond that, there's not much you can do. The `inspect` module can help with this. So:
```
import ab
a = ab.A()
meth = a.x
... | How would you determine where each property and method of a Python class is defined? | [
"",
"python",
"introspection",
"plone",
"python-datamodel",
""
] |
I want to write a piece of software which is essentially a regex data scrubber. I am going to take a contact list in CSV and remove all non-word characters and such from the person's name.
This project has Perl written all over it but my client base is largely non-technical and installing Perl on Windows would not be ... | You can use [Perl Archive Toolkit](http://search.cpan.org/perldoc?PAR) to bring a minimal perl core + needed modules + your Perl program with you.
And you can even convert it using [PAR Packer](http://search.cpan.org/perldoc?pp) to a windows exe file that will run just like any other program, from an end user's perspe... | You can get Windows executables in all three languages.
* As usual with Perl, there's more than one way to do it:
+ [PAR Packer](http://search.cpan.org/perldoc?pp) (free/open-source)
+ [perl2exe](http://www.indigostar.com/perl2exe.htm) (shareware)
+ [PerlApp](http://community.activestate.com/products/PerlDevKit)... | How can I deploy a Perl/Python/Ruby script without installing an interpreter? | [
"",
"python",
"ruby",
"perl",
""
] |
When I design classes and have to choose between inheritance and composition, I usually use the rule of thumb: if the relationship is "is-a" - use inheritance, and if the relationship is "has-a" - use composition.
Is it always right?
Thank you. | No - "is a" does not always lead to inheritence. A well cited example is the relationship between a square and a rectangle. A square is a rectangle, but it will be bad to design code that inherits a Square class off a Rectangle class.
My suggestion is to enhance your "is a / has a" heuristic with the [Liskov Substitut... | Yes and no.
The line can be blurred. This hasn't been helped by some pretty terrible examples of OO programming from the early days of OO like: Manager is an Employee is a Person.
The thing you have to remember about inheritance is: inheritance breaks encapsulation. Inheritance is an implementation detail. There's al... | Inheritance or composition: Rely on "is-a" and "has-a"? | [
"",
"c++",
"inheritance",
"oop",
""
] |
I have an application that uses simple sockets to pass some characters between two systems. I have my java application running as a server. I establish a connection fine, and even pass one message. However, after one message has been sent my connection closes.
From what I can tell it appears as if on closing the `prin... | Yes, closing any Writer/Reader will close all other Writers and Readers that they wrap. Don't close it until you are ready to close the underlying socket. | As @Eddie [said](https://stackoverflow.com/questions/484925/does-closing-the-bufferedreader-printwriter-close-the-socket-connection#484939) (seconds before me! :) ), closing the writer and/or the reader will close the underlying socket streams [and the socket itself](http://docs.oracle.com/javase/8/docs/api/java/net/So... | Does closing the BufferedReader/PrintWriter close the socket connection? | [
"",
"java",
"sockets",
""
] |
Assume we have a method like this:
```
public IEnumerable<T> FirstMethod()
{
var entities = from t in context.Products
where {some conditions}
select t;
foreach( var entity in entities )
{
entity.SomeProperty = {SomeValue};
yield return entity;
... | The latter (deferred); `FirstMethod` is an iterator block (because of `yield return`); this means that you have a chain of iterators. Nothing is read until the **final caller** starts iterating the data; then each record is read in turn during the **final caller's** `foreach` (between which the connection/command is op... | In short, it doesn't load until SecondMethod performs the iteration...
Read [here](http://rapidapplicationdevelopment.blogspot.com/2008/03/how-systemlinqwhere-really-works.html) for more... | Does it load the data from database? | [
"",
"c#",
".net",
"linq-to-sql",
""
] |
I have a simple form on a view page, implemented as a user control, that looks something like this:
```
<%=Html.BeginForm("List", "Building", FormMethod.Post) %>
//several fields go here
<%Html.EndForm(); %>
```
There are two problems I would like resolved, the first is that I would like the controller method that ... | 1) Use FormCollection as the argument:
```
public ActionResult List(FormCollection searchQuery)
```
Now you can iterate the FormCollection and get key/value search terms from your search form.
2) Remove the "=" from BeginForm:
```
<% Html.BeginForm("List", "Building", FormMethod.Post) %>
```
That said, you [should... | If I'm understanding your question properly, you use the html helper and create inputs named:
```
<%=Html.TextBox("building.FieldNumber1")%>
<%=Html.TextBox("building.FieldNumber2")%>
```
You should be able to access the data using:
```
public ActionResult List(Building building)
{
...
var1 = building.FieldNum... | Implementing Forms in ASP.net MVC | [
"",
"c#",
".net",
"asp.net-mvc",
"forms",
"view",
""
] |
In C#/ASP.NET 3.5, I have a DataTable which pulls rows from the database.
I want to dynamically apply a sort filter to the datatable (could be a dataview), and then do a loop through the "rows" of the sorted data to use each row for some metrics.
I would greatly prefer not to hit the database each time to do custom so... | The DataTable.Select() function does exactly what you seem to be wanting. Its second String parameter is a sorting string whose syntax is the same as SQL's: *[Column Name]* ASC, *[Other column name]* DESC, etc. | ```
DataTable table = ...
DataView view = table.DefaultView;
view.Sort = ...
view.RowFilter = ...
```
* MSDN: [DataView.Sort](http://msdn.microsoft.com/en-us/library/system.data.dataview.sort.aspx)
* MSDN: [DataView.RowFilter](http://msdn.microsoft.com/en-us/library/system.data.dataview... | .NET/C# - Sort DataTable, then manually process the rows | [
"",
"c#",
".net",
""
] |
I need to read some large files (from 50k to 100k lines), structured in groups separated by empty lines. Each group start at the same pattern "No.999999999 dd/mm/yyyy ZZZ". Here´s some sample data.
> No.813829461 16/09/1987 270
> Tit.SUZANO PAPEL E CELULOSE S.A. (BR/BA)
> C.N.P.J./C.I.C./N INPI : 16404287000155
... | That is pretty good. Below some suggestions, let me know if you like'em:
```
import re
import pprint
import sys
class Despacho(object):
"""
Class to parse each line, applying the regexp and storing the results
for future use
"""
#used a dict with the keys instead of functions.
regexp = {
... | It would be easier to help if you had a specific concern. Performance will depend greatly on the efficiency of the particular regex engine you are using. 100K lines in a single file doesn't sound that big, but again it all depends on your environment.
I use [Expresso](http://www.ultrapico.com/Expresso.htm) in my .NET ... | Extracting info from large structured text files | [
"",
"python",
"text-processing",
""
] |
I want to write a regex that matches if a string contains XYZ but doesn't contain ABC somewhere before it. So "blah XYZ blah" should match, but "blah ABC blah XYZ blah " should not.
Any ideas? In particular I'm writing the regex in c#, in case there's anything specific to that syntax.
I guess I can use negative lookb... | No need for lookbehind:
```
^(?:(?!ABC).)*XYZ
``` | ```
^(?:(?<!ABC).)*XYZ
```
was fine for my little testset. | How do i write a Regular Expression to match text containing XYZ but not ABC? | [
"",
"c#",
"regex",
""
] |
Is it possible to determine the type of a local variable at runtime in TSQL?
For example, say I wanted to do something along these lines:
```
IF ( @value IS INTEGER )
```
Or
```
IF ( TYPEOF(@value) = <whatever> )
```
Does anyone know of any way to accomplish this?
EDIT: This is not for a specific task, this is mo... | run this
```
declare @d int
select @d = 500
if cast(sql_variant_property(@d,'BaseType') as varchar(20)) = 'int'
print 'yes'
else
print 'no'
``` | using SQL 2019 , below code still working
```
DECLARE @MyVar int;SET @MyVar = 99;
DECLARE @MyVarDataType varchar(50);
SET @MyVarDataType = cast(SQL_VARIANT_PROPERTY(@MyVar,'BaseType') AS varchar);
PRINT @MyVarDataType
``` | SQL Server 2005: Determine datatype of variable | [
"",
"sql",
"sql-server-2005",
"t-sql",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.