Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Is it completely against the Java way to create struct like objects?
```
class SomeData1 {
public int x;
public int y;
}
```
I can see a class with accessors and mutators being more Java like.
```
class SomeData2 {
int getX();
void setX(int x);
int getY();
void setY(int y);
private int ... | This is a commonly discussed topic. The drawback of creating public fields in objects is that you have no control over the values that are set to it. In group projects where there are many programmers using the same code, it's important to avoid side effects. Besides, sometimes it's better to return a copy of field's o... | It appears that many Java people are not familiar with the Sun Java Coding Guidelines
which say it is quite appropriate to use public instance variable when the class is
essentially a "Struct", if Java supported "struct" (when there is no behavior).
People tend to think getters and setters are the Java way,
as if they... | Struct like objects in Java | [
"",
"java",
"oop",
"struct",
""
] |
Does anyone know tools which look at a MySQL database, show you all the tables graphically and allow you to create complicated JOIN statements via drag-and-drop? | Before you buy anything, see if the free, official [MySQL's GUI tools](http://dev.mysql.com/downloads/gui-tools/) (specifically the **MySQL Query Browser**) will work for you.
Personally, I'm fairly comfortable interacting with MySQL's command line interface and haven't used their GUI tools very much, but I just downl... | As an update, the MySQL Tools collection is no longer supported, and has been replaced by MySQL Workbench. The documentation can be found here: <http://dev.mysql.com/doc/workbench/en/index.html> and you can download it here: <http://dev.mysql.com/downloads/workbench/>
Edit: stumbled across this today too, a good begin... | MySQL tools which ease creation of SQL JOIN statements? | [
"",
"sql",
"mysql",
""
] |
I have a binary file that I have to parse and I'm using Python. Is there a way to take 4 bytes and convert it to a single precision floating point number? | ```
>>> import struct
>>> struct.pack('f', 3.141592654)
b'\xdb\x0fI@'
>>> struct.unpack('f', b'\xdb\x0fI@')
(3.1415927410125732,)
>>> struct.pack('4f', 1.0, 2.0, 3.0, 4.0)
'\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@'
``` | Just a little addition, if you want a float number as output from the unpack method instead of a tuple just write
```
>>> import struct
>>> [x] = struct.unpack('f', b'\xdb\x0fI@')
>>> x
3.1415927410125732
```
If you have more floats then just write
```
>>> import struct
>>> [x,y] = struct.unpack('ff', b'\xdb\x0fI@\x... | Convert Bytes to Floating Point Numbers? | [
"",
"python",
"floating-point",
""
] |
Knowing an exception code, is there a way to find out more about what the actual exception that was thrown means?
My exception in question:
0x64487347
Exception address: 0x1
The call stack shows no information.
I'm reviewing a .dmp of a crash and not actually debugging in Visual Studio. | Because you're reviewing a crash dump I'll assume it came in from a customer and you cannot easily reproduce the fault with more instrumentation.
I don't have much help to offer save to note that the exception code 0x64487347 is ASCII "dShG", and developers often use the initials of the routine or fault condition when... | A true C++ exception thrown from Microsoft's runtime will have an SEH code of 0xe06d7363 (E0 + 'msc'). You have some other exception.
.NET generates SEH exceptions with the code 0xe0434f4d (E0 + 'COM').
NT's status codes are documented in ntstatus.h, and generally start 0x80 (warnings) or 0xC0 (errors). The most famo... | C++ Exception code lookup | [
"",
"c++",
"exception",
"visual-c++",
"crash",
"memory-dump",
""
] |
I have a old website that generate its own RSS everytime a new post is created. Everything worked when I was on a server with PHP 4 but now that the host change to PHP 5, I always have a "bad formed XML". I was using xml\_parser\_create() and xml\_parse(...) and fwrite(..) to save everything.
Here is the example when ... | At swcombine.com we use [Feedcreator](http://feedcreator.org/). Use that one and your problem will be gone. :)
Here is the PHP code to use it once installed:
```
function feed_simnews() {
$objRSS = new UniversalFeedCreator();
$objRSS->title = 'My News';
$objRSS->link = 'http://link.to/news.php';
$objR... | I would use [simpleXML](http://www.php.net/simplexml) to create the required structure and export the XML. Then I'd cache it to disk with file\_put\_contents(). | PHP - RSS builder | [
"",
"php",
"rss",
""
] |
What SQL can be used to list the tables, and the rows within those tables in an SQLite database file – once I have attached it with the `ATTACH` command on the `sqlite3` command line tool? | The `.tables`, and `.schema` "helper" functions don't look into ATTACHed databases: they just query the `SQLITE_MASTER` table for the "main" database. Consequently, if you used
```
ATTACH some_file.db AS my_db;
```
then you need to do
```
SELECT name FROM my_db.sqlite_master WHERE type='table';
```
Note that tempor... | There are a few steps to see the tables in an SQLite database:
1. List the tables in your database:
```
.tables
```
2. List how the table looks:
```
.schema tablename
```
3. Print the entire table:
```
SELECT * FROM tablename;
```
4. List all of the available SQLite prompt commands:
`... | How can I list the tables in a SQLite database file that was opened with ATTACH? | [
"",
"sql",
"sqlite",
"database-schema",
""
] |
Lets say I have a Dictionary object:
```
Dictionary myDictionary<int, SomeObject> = new Dictionary<string, SomeObject>();
```
Now I want to iterate through the dictionary in reverse order. I can't use a simple for loop because I don't know the keys of the dictionary. A *foreach* is easy:
```
foreach (SomeObject obje... | I'd use a SortedList instead of a dictionary. You can still access it by Key, but you can access it by index as well.
```
SortedList sCol = new SortedList();
sCol.Add("bee", "Some extended string matching bee");
sCol.Add("ay", "value matching ay");
sCol.Add("cee", "Just a standard cee");
// Go through it backwards.
... | A dictionary or any other form of hashtable has no ordering. So what you are trying to do is pointless :) | In C# .NET 2.0, what's an easy way to do a foreach in reverse? | [
"",
"c#",
".net",
"collections",
"iteration",
""
] |
Which is better? Or use and OR mapper with SP's? If you have a system with SP's already, is an OR mapper worth it? | I like ORM's because you don't have to reinvent the wheel. That being said, it completely depends on your application needs, development style and that of the team.
This question has already been covered [Why is parameterized SQL generated by NHibernate just as fast as a stored procedure?](https://stackoverflow.com/qu... | There is nothing good to be said about stored procedures. There were a necessity 10 years ago but every single benefit of using sprocs is no longer valid. The two most common arguments are regarding security and performance. The "sending stuff over the wire" crap doesn't hold either, I can certainly create a query dyna... | Stored procedures or OR mappers? | [
"",
"sql",
"stored-procedures",
""
] |
The following code should find the appropriate project tag and remove it from the XmlDocument, however when I test it, it says:
**The node to be removed is not a child of this node.**
Does anyone know the proper way to do this?
```
public void DeleteProject (string projectName)
{
string ccConfigPath = Configurat... | Instead of
```
configDoc.RemoveChild(projectNodes[i]);
```
try
```
projectNodes[i].parentNode.RemoveChild(projectNodes[i]);
``` | try
```
configDoc.DocumentElement.RemoveChild(projectNodes[i]);
``` | Removing nodes from an XmlDocument | [
"",
"c#",
".net",
"xml",
"xmldocument",
""
] |
I like to use static functions in C++ as a way to categorize them, like C# does.
```
Console::WriteLine("hello")
```
Is this good or bad? If the functions are used often I guess it doesn't matter, but if not do they put pressure on memory?
What about `static const`? | > but is it good or bad
The first adjective that comes to mind is "unnecessary". C++ has free functions and namespaces, so why would you need to make them static functions in a class?
The use of static methods in uninstantiable classes in C# and Java *is a workaround* because those languages don't have free functions... | I'm all for using static **functions**. These just make sense especially when organized into modules (`static class` in C#).
However, *the moment* those functions need some kind of external (non compile-time const) data, then that function should be made an instance method and encapsulated along with its data into a c... | Is using too much static bad or good? | [
"",
"c++",
"static",
""
] |
Okay, I've looked all over the internet for a good solution to get PHP and MySQL working on IIS7.0. It's nearly impossible, I've tried it so many times and given up in vain. Please please help by linking some great step-by-step tutorial to adding PHP and MySQL on IIS7.0 from scratch. PHP and MySQL are essential for ins... | Have you taken a look at this:
<http://learn.iis.net/page.aspx/246/using-fastcgi-to-host-php-applications-on-iis7/>
MySQL should be pretty straight forward.
Let us know what problems you're encountering... | I've been given a PHP / MySQL web site that I'm to host with IIS 7.0 on 64-bit Windows Server 2008.
I'm a .NET / MSSQL developer, and am unfamiliar with either PHP or MySQL.
> **[Kev](https://stackoverflow.com/users/419/kev)** wrote:
>
> Have you taken a look at this…
I don't know if any one implementation of Win64 ... | How do I get PHP and MySQL working on IIS 7.0? | [
"",
"php",
"mysql",
"iis-7",
""
] |
I can get Python to work with Postgresql but I cannot get it to work with MySQL. The main problem is that on the shared hosting account I have I do not have the ability to install things such as Django or PySQL, I generally fail when installing them on my computer so maybe it's good I can't install on the host.
I foun... | MySQLdb is what I have used before.
If you host is using Python version 2.5 or higher, support for sqlite3 databases is built in (sqlite allows you to have a relational database that is simply a file in your filesystem). But buyer beware, sqlite is not suited for production, so it may depend what you are trying to do ... | I don't have any experience with <http://www.SiteGround.com> as a web host personally.
This is just a guess, but it's common for a shared host to support Python and MySQL with the MySQLdb module (e.g., GoDaddy does this). Try the following CGI script to see if MySQLdb is installed.
```
#!/usr/bin/python
module_name ... | Python and MySQL | [
"",
"python",
"mysql",
"postgresql",
"bpgsql",
""
] |
I have one table "orders" with a foreing key "ProductID".
I want to show the orders in a grid with the **product name**, without **LazyLoad** for better performance, but I if use **DataLoadOptions** it retrieves **all** Product fields, which seams like a **overkill**.
Is there a way to retrieve **only** the Product n... | I get the solution in this other question [Which .net ORM can deal with this scenario](https://stackoverflow.com/questions/381049/which-net-orm-can-deal-with-this-scenario#381084), that is related to the **liammclennan** answer but more clear (maybe the question was more clear too) | What you are asking for is a level of optimisation the linq-to-sql does not provide. I think your best bet is to create a query that returns exactly the data you want, possibly as an anonymous type:
```
from order in DB.GetTable<Orders>()
join product in DB.GetTable<Products>()
on order.ProductID = product.ID
select n... | Linq To SQL: Can I eager load only one field in a joined table? | [
"",
".net",
"sql",
"performance",
"linq-to-sql",
""
] |
When I try to `print` a string in a Windows console, sometimes I get an error that says `UnicodeEncodeError: 'charmap' codec can't encode character ....`. I assume this is because the Windows console cannot handle all Unicode characters.
How can I work around this? For example, how can I make the program display a rep... | **Note:** This answer is sort of outdated (from 2008). Please use the solution below with care!!
---
Here is a page that details the problem and a solution (search the page for the text *Wrapping sys.stdout into an instance*):
[PrintFails - Python Wiki](http://wiki.python.org/moin/PrintFails)
Here's a code excerpt ... | **Update:** [Python 3.6](https://docs.python.org/3.6/whatsnew/3.6.html#pep-528-change-windows-console-encoding-to-utf-8) implements [PEP 528: Change Windows console encoding to UTF-8](https://www.python.org/dev/peps/pep-0528/): *the default console on Windows will now accept all Unicode characters.* Internally, it uses... | Python, Unicode, and the Windows console | [
"",
"python",
"unicode",
""
] |
I'm new to MVC (and ASP.Net routing). I'm trying to map `*.aspx` to a controller called `PageController`.
```
routes.MapRoute(
"Page",
"{name}.aspx",
new { controller = "Page", action = "Index", id = "" }
);
```
Wouldn't the code above map \*.aspx to `PageController`? When I run this and type in any .aspx pa... | > I just answered my own question. I had
> the routes backwards (Default was
> above page).
Yeah, you have to put all custom routes above the Default route.
> So this brings up the next question...
> how does the "Default" route match (I
> assume they use regular expressions
> here) the "Page" route?
The Default rou... | I just answered my own question. I had the routes backwards (Default was above page). Below is the correct order. So this brings up the next question... how does the "Default" route match (I assume they use regular expressions here) the "Page" route?
```
routes.MapRoute(
"Page",
"{Name}.aspx",
... | ASP.Net MVC route mapping | [
"",
"c#",
"asp.net",
"asp.net-mvc",
"routes",
""
] |
How can I determine the IP of my router/gateway in Java? I can get my IP easily enough. I can get my internet IP using a service on a website. But how can I determine my gateway's IP?
This is somewhat easy in .NET if you know your way around. But how do you do it in Java? | Java doesn't make this as pleasant as other languages, unfortunately. Here's what I did:
```
import java.io.*;
import java.util.*;
public class ExecTest {
public static void main(String[] args) throws IOException {
Process result = Runtime.getRuntime().exec("traceroute -m 1 www.amazon.com");
Buff... | On Windows, OSX, Linux, etc then Chris Bunch's answer can be much improved by using
```
netstat -rn
```
in place of a `traceroute` command.
Your gateway's IP address will appear in the second field of the line that starts either `default` or `0.0.0.0`.
This gets around a number of problems with trying to use `trace... | How can I determine the IP of my router/gateway in Java? | [
"",
"java",
"sockets",
"ip",
"router",
""
] |
I haven't been able to find an understandable explanation of how to actually use Python's `itertools.groupby()` function. What I'm trying to do is this:
* Take a list - in this case, the children of an objectified `lxml` element
* Divide it into groups based on some criteria
* Then later iterate over each of these gro... | **IMPORTANT NOTE:** You *may* have to **sort your data** first.
---
The part I didn't get is that in the example construction
```
groups = []
uniquekeys = []
for k, g in groupby(data, keyfunc):
groups.append(list(g)) # Store group iterator as a list
uniquekeys.append(k)
```
`k` is the current grouping key,... | `itertools.groupby` is a tool for grouping items.
From [the docs](https://docs.python.org/3/library/itertools.html#itertools.groupby), we glean further what it might do:
> `# [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B`
>
> `# [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D`
`groupby` ob... | How do I use itertools.groupby()? | [
"",
"python",
"python-itertools",
""
] |
I am working on a function to establish the entropy of a distribution. It uses a copula, if any are familiar with that. I need to sum up the values in the array based on which dimensions are "cared about."
Example: Consider the following example...
```
Dimension 0 (across)
_ _ _ _ _ _ _ _ _ _ _ _ _
|_ 0 _|_ 0 _|_ 0 _... | This could have applications. Lets say you implemented a 2D Conway's Game of Life (which defines a 2D plane, 1 for 'alive', 0 for 'dead') and you stored the Games history for every iteration (which then defines a 3D cube). If you wanted to know how many bacteria there was alive over history, you would use the above alg... | @Jeff
I actually think this is an interesting question. I'm not sure how useful it is, but it is a valid question.
@Ed
Can you provide a little more info on this question? You said the dimension of the array is dynamic, but is the number of elements dynamic as well?
EDIT: I'm going to try and answer the question an... | How Does One Sum Dimensions of an Array Specified at Run-Time? | [
"",
"c++",
"c",
"arrays",
"microsoft-dynamics",
""
] |
I'm building an application against some legacy, third party libraries, and having problems with the linking stage. I'm trying to compile with Visual Studio 9. My compile command is:
```
cl -DNT40 -DPOMDLL -DCRTAPI1=_cdecl
-DCRTAPI2=cdecl -D_WIN32 -DWIN32 -DWIN32_LEAN_AND_MEAN -DWNT -DBYPASS_FLEX -D_INTEL=1 -DIPLIB=no... | After trying to get this stuff to compile under VS 2008, I tried earlier versions of VS - 2005 worked with warnings, and 2003 just worked. I double checked the linkages and couldn't find any problems, so either I just couldn't find it, or that wasn't the problem.
So to reiterate, downgrading to VS 2003 fixed it. | These are standard library references. Make sure that all libraries (including the standard library) are using the *same* linkage. E.g. you can't link statically while linking the standard lib dynamically. The same goes for the threading model used. Take special care that you and the 3rd party library use the same link... | C++ linker unresolved external symbols | [
"",
"c++",
""
] |
I've been making a concerted effort to improve my javascript skills lately by reading as much javascript code as I can. In doing this I've sometimes seen the `javascript:` prefix appended to the front of event handler attributes in HTML element tags. What's the purpose of this prefix? Basically, is there any appreciabl... | Probably nothing in your example. My understanding is that `javascript:` is for anchor tags (in place of an actual `href`). You'd use it so that your script can execute when the user clicks the link, but without initiating a navigation back to the page (which a blank `href` coupled with an `onclick` will do).
For exam... | It should not be used in event handlers (though most browsers work defensively, and will not punish you). I would also argue that it should not be used in the href attribute of an anchor. If a browser supports javascript, it will use the properly defined event handler. If a browser does not, a javascript: link will app... | What's the purpose (if any) of "javascript:" in event handler tags? | [
"",
"javascript",
""
] |
I have a PHP application that displays a list of options to a user. The list is generated from a simple query against SQL 2000. What I would like to do is have a specific option at the top of the list, and then have the remaining options sorted alphabetically.
For example, here's the options if sorted alphabetically:
... | ```
SELECT name
FROM locations
ORDER BY
CASE
WHEN name = 'Montreal'
THEN 0
ELSE 1
END, name
``` | ```
SELECT name FROM options ORDER BY name = "Montreal", name;
```
Note: This works with MySQL, not SQL 2000 like the OP requested. | Sort with one option forced to top of list | [
"",
"sql",
"sorting",
""
] |
I am using the function below to match URLs inside a given text and replace them for HTML links. The regular expression is working great, but currently I am only replacing the first match.
How I can replace all the URL? I guess I should be using the *exec* command, but I did not really figure how to do it.
```
functi... | First off, rolling your own regexp to parse URLs is a *terrible idea*. You must imagine this is a common enough problem that someone has written, debugged and [tested](http://benalman.com/code/test/js-linkify/) a library for it, according to [the RFCs](https://metacpan.org/pod/Regexp::Common::URI#REFERENCES). **URIs ar... | ### Replacing URLs with links (Answer to the General Problem)
The regular expression in the question misses *a lot* of edge cases. When detecting URLs, it's always better to use a specialized library that handles international domain names, new TLDs like `.museum`, parentheses and other punctuation within and at the e... | How to replace plain URLs with links? | [
"",
"javascript",
"regex",
""
] |
I build up an array of strings with
```
string[] parts = string.spilt(" ");
```
And get an array with X parts in it, I would like to get a copy of the array of strings starting at element
```
parts[x-2]
```
Other than the obvious brute force approach (make a new array and insert strings), is there a more elegant wa... | How about Array.Copy?
<http://msdn.microsoft.com/en-us/library/aa310864(VS.71).aspx>
> Array.Copy Method (Array, Int32, Array, Int32, Int32)
>
> Copies a range of elements from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index. The length and ... | I remembered answering this question and just learned about a new object that may provide a high performance method of doing what you want.
Take a look at [`ArraySegment<T>`](http://msdn.microsoft.com/en-us/library/1hsbd92d.aspx). It will let you do something like.
```
string[] parts = myString.spilt(" ");
int idx = ... | Pass reference to element in C# Array | [
"",
"c#",
"arrays",
""
] |
What's the best way to allow a user to browse for a file in C#? | ```
using (OpenFileDialog dlg = new OpenFileDialog())
{
dlg.Title = "Select a file";
if (dlg.ShowDialog()== DialogResult.OK)
{
//do something with dlg.FileName
}
}
``` | I would say use the standard "Open File" dialog box ([OpenFileDialog](http://msdn.microsoft.com/en-us/library/system.windows.forms.openfiledialog.aspx)), this makes it less intimidating for new users and helps with a consistant UI. | What's the best way to allow a user to browse for a file in C#? | [
"",
"c#",
""
] |
SQL:
```
SELECT
u.id,
u.name,
isnull(MAX(h.dateCol), '1900-01-01') dateColWithDefault
FROM universe u
LEFT JOIN history h
ON u.id=h.id
AND h.dateCol<GETDATE()-1
GROUP BY u.Id, u.name
``` | A solution, albeit one that defers handling of the null value to the code, could be:
> DateTime yesterday = DateTime.Now.Date.AddDays(-1);
```
var collection=
from u in db.Universe
select new
{
u.id,
u.name,
MaxDate =(DateTime?)
(
from h in db.History
w... | ```
var collection=
from u in db.Universe
select new
{
u.id,
u.name,
MaxDate =(DateTime?)
(
from h in db.History
where u.Id == h.Id
&& h.dateCol < yesterday
select h.dateCol
).Max()
};
```
Just youse the above code and t... | How do I most elegantly express left join with aggregate SQL as LINQ query | [
"",
"c#",
"linq",
"left-join",
""
] |
I was curious about how other people use the **this** keyword. I tend to use it in constructors, but I may also use it throughout the class in other methods. Some examples:
In a constructor:
```
public Light(Vector v)
{
this.dir = new Vector(v);
}
```
Elsewhere
```
public void SomeMethod()
{
Vector vec = ne... | There are several usages of [this](http://msdn.microsoft.com/en-us/library/dk1507sz.aspx) keyword in C#.
1. [To qualify members hidden by similar name](http://msdn.microsoft.com/en-us/library/vstudio/dk1507sz%28v=vs.100%29.aspx)
2. [To have an object pass itself as a parameter to other methods](http://msdn.microsoft.c... | I don't mean this to sound snarky, but it doesn't matter.
Seriously.
Look at the things that are important: your project, your code, your job, your personal life. None of them are going to have their success rest on whether or not you use the "this" keyword to qualify access to fields. The this keyword will not help ... | When do you use the "this" keyword? | [
"",
"c#",
"coding-style",
"this",
""
] |
Suppose I have the following CSS rule in my page:
```
body {
font-family: Calibri, Trebuchet MS, Helvetica, sans-serif;
}
```
How could I detect which one of the defined fonts were used in the user's browser?
For people wondering why I want to do this is because the font I'm detecting contains glyphs that are *n... | I've seen it done in a kind of iffy, but pretty reliable way. Basically, an element is set to use a specific font and a string is set to that element. If the font set for the element does not exist, it takes the font of the parent element. So, what they do is measure the width of the rendered string. If it matches what... | I wrote a simple JavaScript tool that you can use it to check if a font is installed or not.
It uses simple technique and should be correct most of the time.
**[jFont Checker](https://github.com/derek1906/jFont-Checker/)** on github | How to detect which one of the defined font was used in a web page? | [
"",
"javascript",
"html",
"css",
"fonts",
""
] |
Are PHP variables passed by value or by reference? | It's by value according to the [PHP Documentation](http://php.net/manual/en/functions.arguments.php).
> By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments,... | In PHP, by default, objects are passed as reference to a new object.
See this example:
```
class X {
var $abc = 10;
}
class Y {
var $abc = 20;
function changeValue($obj)
{
$obj->abc = 30;
}
}
$x = new X();
$y = new Y();
echo $x->abc; //outputs 10
$y->changeValue($x);
echo $x->abc; //outputs 30
```
... | Are PHP Variables passed by value or by reference? | [
"",
"php",
"variables",
"pass-by-reference",
"pass-by-value",
""
] |
How do you debug **PHP** scripts?
I am aware of basic debugging such as using the Error Reporting. The breakpoint debugging in **PHPEclipse** is also quite useful.
What is the **best** (in terms of fast and easy) way to debug in phpStorm or any other IDE? | Try [Eclipse PDT](https://eclipse.org/pdt/) to setup an Eclipse environment that has debugging features like you mentioned. The ability to step into the code is a much better way to debug then the old method of var\_dump and print at various points to see where your flow goes wrong. When all else fails though and all I... | You can use Firephp an add-on to firebug to debug php in the same environment as javascript.
I also use [Xdebug](http://xdebug.org/) mentioned earlier for profiling php. | How do you debug PHP scripts? | [
"",
"php",
"eclipse",
"debugging",
"phpstorm",
"xdebug",
""
] |
Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this:
```
>>> class Foo:
... bar = 'hello'
... baz = 'world'
...
>>> f = Foo()
>>> props(f)
{ 'bar' : 'hello', 'baz' : 'world' }
```
**NOTE:** It should not include methods. Only fields. | Note that best practice in Python 2.7 is to use *[new-style](https://www.python.org/doc/newstyle/)* classes (not needed with Python 3), i.e.
```
class Foo(object):
...
```
Also, there's a difference between an 'object' and a 'class'. To build a dictionary from an arbitrary *object*, it's sufficient to use `__dict_... | Instead of `x.__dict__`, it's actually more pythonic to use `vars(x)`. | Python dictionary from an object's fields | [
"",
"python",
"dictionary",
"attributes",
"object",
"metaprogramming",
""
] |
Is it possible in c# to initialize an array in, for example, subindex 1?
I'm working with Office interop, and every property is an object array that starts in 1 (I assume it was originally programed in VB.NET), and you cannot modify it, you have to set the entire array for it to accept the changes.
As a workaround I ... | You can use [`Array.CreateInstance`](http://msdn.microsoft.com/en-us/library/system.array.createinstance%28v=vs.110%29.aspx).
See [Array Types in .NET](http://msdn.microsoft.com/en-us/magazine/cc301755.aspx) | It is possible to do as you request see the code below.
```
// Construct an array containing ints that has a length of 10 and a lower bound of 1
Array lowerBoundArray = Array.CreateInstance(typeof(int), new int[1] { 10 }, new int[1] { 1 });
// insert 1 into position 1
lowerBoundArray.SetValue(1, 1);
//insert 2 into ... | Initializing an array on arbitrary starting index in c# | [
"",
"c#",
"arrays",
"interop",
"ms-office",
"initialization",
""
] |
I'm currently working on an internal sales application for the company I work for, and I've got a form that allows the user to change the delivery address.
Now I think it would look much nicer, if the textarea I'm using for the main address details would just take up the area of the text in it, and automatically resiz... | Facebook does it, when you write on people's walls, but only resizes vertically.
Horizontal resize strikes me as being a mess, due to word-wrap, long lines, and so on, but vertical resize seems to be pretty safe and nice.
None of the Facebook-using-newbies I know have ever mentioned anything about it or been confused... | One refinement to some of these answers is to let CSS do more of the work.
The basic route seems to be:
1. Create a container element to hold the `textarea` and a hidden `div`
2. Using Javascript, keep the `textarea`’s contents synced with the `div`’s
3. Let the browser do the work of calculating the height of that d... | How to autosize a textarea using Prototype? | [
"",
"javascript",
"html",
"css",
"textarea",
"prototypejs",
""
] |
[Resharper](http://resharper.blogspot.com/2008/03/varification-using-implicitly-typed.html) certainly thinks so, and out of the box it will nag you to convert
```
Dooberry dooberry = new Dooberry();
```
to
```
var dooberry = new Dooberry();
```
Is that really considered the best style? | It's of course a matter of style, but I agree with Dare: [C# 3.0 Implicit Type Declarations: To var or not to var?](http://www.25hoursaday.com/weblog/2008/05/21/C30ImplicitTypeDeclarationsToVarOrNotToVar.aspx). I think using var instead of an explicit type makes your code less readable.In the following code:
```
var r... | I use it only when it's clearly obvious what var is.
clear to me:
```
XmlNodeList itemList = rssNode.SelectNodes("item");
var rssItems = new RssItem[itemList.Count];
```
not clear to me:
```
var itemList = rssNode.SelectNodes("item");
var rssItems = new RssItem[itemList.Count];
``` | Should I *always* favour implictly typed local variables in C# 3.0? | [
"",
"c#",
"styles",
"resharper",
""
] |
I have defined a Java function:
```
static <T> List<T> createEmptyList() {
return new ArrayList<T>();
}
```
One way to call it is like so:
```
List<Integer> myList = createEmptyList(); // Compiles
```
Why can't I call it by explicitly passing the generic type argument? :
```
Object myObject = createEmtpyList<I... | When the java compiler cannot infer the parameter type by itself for a static method, you can always pass it using the full qualified method name: Class . < Type > method();
```
Object list = Collections.<String> emptyList();
``` | You can, if you pass in the type as a method parameter.
```
static <T> List<T> createEmptyList( Class<T> type ) {
return new ArrayList<T>();
}
@Test
public void createStringList() {
List<String> stringList = createEmptyList( String.class );
}
```
Methods cannot be genericised in the same way that a type can, so ... | Why can't I explicitly pass the type argument to a generic Java method? | [
"",
"java",
"generics",
"syntax",
""
] |
I get a URL from a user. I need to know:
a) is the URL a valid RSS feed?
b) if not is there a valid feed associated with that URL
using PHP/Javascript or something similar
(Ex. <http://techcrunch.com> fails a), but b) would return their RSS feed) | Found something that I wanted:
Google's [AJAX Feed API](http://code.google.com/apis/ajaxfeeds/) has a load feed and lookup feed function (Docs [here](http://code.google.com/apis/ajaxfeeds/documentation/reference.html#_intro_fonje)).
a) [Load feed](http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=http://www.... | The [Zend Feed class](http://framework.zend.com/manual/en/zend.feed.findFeeds.html) of the **Zend-framework** can automatically parse a webpage and list the available feeds.
Example:
```
$feedArray = Zend_Feed::findFeeds('http://www.example.com/news.html');
``` | How To Discover RSS Feeds for a given URL | [
"",
"php",
"rss",
"feed",
"atom-feed",
""
] |
How much less libraries are there for Mono than for Java?
I lack the overview over both alternatives but I have pretty much freedom of choice for my next project. I'm looking for hard technical facts in the areas of
* performance (for example, I'm told Java is good for threading, and I hear the runtime code optimizat... | Well....Java is actually more portable. Mono isn't implemented everywhere, and it lags behind the Microsoft implementation significantly. The Java SDK seems to stay in better sync across platforms (and it works on more platforms).
I'd also say Java has more tool availability across all those platforms, although there ... | Mono does a better job at targeting the platforms I want to support. Other than that, it is all subjective.
I share C# code across the following platforms:
* iOS (iPhone/iPad)
* Android
* The Web (HTML5)
* Mac (OS X)
* Linux
* Windows
I could share it even more places:
* Windows Phone 7
* Wii
* XBox
* PS3
* etc.
T... | Is .NET/Mono or Java the better choice for cross-platform development? | [
"",
"java",
".net",
"linux",
"mono",
"cross-platform",
""
] |
How can I check the existence of an element in jQuery?
The current code that I have is this:
```
if ($(selector).length > 0) {
// Do something
}
```
Is there a more elegant way to approach this? Perhaps a plugin or a function? | In JavaScript, everything is 'truthy' or 'falsy', and for numbers `0` means `false`, everything else `true`. So you could write:
```
if ($(selector).length)
```
You don't need that `>0` part. | Yes!
```
jQuery.fn.exists = function(){ return this.length > 0; }
if ($(selector).exists()) {
// Do something
}
```
This is in response to: [Herding Code podcast with Jeff Atwood](http://herdingcode.com/?p=36) | Is there an "exists" function for jQuery? | [
"",
"javascript",
"jquery",
""
] |
We need to programatically burn files to CD in a C\C++ Windows XP/Vista application we are developing using Borlands Turbo C++.
What is the simplest and best way to do this? We would prefer a native windows API (that doesnt rely on MFC) so as not to rely on any third party software/drivers if one is available. | We used the following:
Store files in the directory returned by GetBurnPath, then write using Burn. GetCDRecordableInfo is used to check when the CD is ready.
```
#include <stdio.h>
#include <imapi.h>
#include <windows.h>
struct MEDIAINFO {
BYTE nSessions;
BYTE nLastTrack;
ULONG nStartAddress;
ULONG ... | To complement the accepted answer, we added this helper function to programatically change the burn directory on the fly as this was a requirement of ours.
```
typedef HMODULE (WINAPI * SHSETFOLDERPATHA)( int , HANDLE , DWORD , LPCTSTR );
int SetBurnPath( char * cpPath )
{
SHSETFOLDERPATHA pSHSetFolderPath;
H... | Windows CD Burning API | [
"",
"c++",
"c",
"windows",
"cd-burning",
""
] |
My path to a 'fulltime'- developer stated as a analyst using VBA with Excel, Access, and then onto C#. I went to college part time once I discovered I had a passion for coding not business.
I do about most of my coding in C#, but being an ASP.NET developer I also write in HTML, JavaScript, SQL etc. . . the usual suspe... | If you want to be one of the best you need to specialise. If you become very good in many skills then you may never become truly excellent in one. I know because I have taken this route myself and have found it difficult to get employment at times. After all, who wants someone who is capable at many languages when ther... | Yeah, the more I get into software, I start to see myself focusing less on the language and more on the design..
Yeah there are framework bits we need to get our head around but most of the time ( *most* not all ) you can look those up as-and-when you need them..
But a good design head? That takes years of experience... | What should I learn to increase my skills? | [
"",
"c#",
".net",
""
] |
In python, you can have a function return multiple values. Here's a contrived example:
```
def divide(x, y):
quotient = x/y
remainder = x % y
return quotient, remainder
(q, r) = divide(22, 7)
```
This seems very useful, but it looks like it can also be abused ("Well..function X already computes what we... | Absolutely (for the example you provided).
### Tuples are first class citizens in Python
There is a builtin function [`divmod()`](https://docs.python.org/3/library/functions.html#divmod) that does exactly that.
```
q, r = divmod(x, y) # ((x - x%y)/y, x%y) Invariant: div*y + mod == x
```
There are other examples: `z... | Firstly, note that Python allows for the following (no need for the parenthesis):
```
q, r = divide(22, 7)
```
Regarding your question, there's no hard and fast rule either way. For simple (and usually contrived) examples, it may seem that it's always possible for a given function to have a single purpose, resulting ... | Is it pythonic for a function to return multiple values? | [
"",
"python",
"function",
"return-value",
"multiple-return-values",
""
] |
How can I replace lone instances of \n with \r\n (LF alone with CRLF) using a regular expression in C#?
I know to do it using plan `String.Replace`, like:
```
myStr.Replace("\n", "\r\n");
myStr.Replace("\r\r\n", "\r\n");
```
However, this is inelegant, and would destroy any "\r+\r\n" already in the text (although th... | Will this do?
```
[^\r]\n
```
Basically it matches a '\n' that is preceded with a character that is not '\r'.
If you want it to detect lines that start with just a single '\n' as well, then try
```
([^\r]|$)\n
```
Which says that it should match a '\n' but only those that is the first character of a line or those ... | It might be faster if you use this.
```
(?<!\r)\n
```
It basically looks for any \n that is not preceded by a \r. This would most likely be faster, because in the other case, almost every letter matches [^\r], so it would capture that, and then look for the \n after that. In the example I gave, it would only stop whe... | Regex (C#): Replace \n with \r\n | [
"",
"c#",
"regex",
""
] |
I didn't see any similar questions asked on this topic, and I had to research this for something I'm working on right now. Thought I would post the answer for it in case anyone else had the same question. | I found the answer here: <http://blog.sqlauthority.com/2007/08/22/sql-server-t-sql-script-to-insert-carriage-return-and-new-line-feed-in-code/>
You just concatenate the string and insert a `CHAR(13)` where you want your line break.
Example:
```
DECLARE @text NVARCHAR(100)
SET @text = 'This is line 1.' + CHAR(13) + '... | `char(13)` is `CR`. For DOS-/Windows-style `CRLF` linebreaks, you want `char(13)+char(10)`, like:
```
'This is line 1.' + CHAR(13)+CHAR(10) + 'This is line 2.'
``` | How to insert a line break in a SQL Server VARCHAR/NVARCHAR string | [
"",
"sql",
"sql-server",
"line-breaks",
""
] |
How do I connect to a remote Oracle database instance from PHP?
I need to query (read only) the remote Oracle database for some information; do I need to have an Oracle Instant Client installed?
Is the OCI extension for PHP enough? | From [PHP Manual](http://php.net/manual/en/oci8.setup.php)
* You will need the Oracle client libraries to use this extension.
* The most convenient way to install all the required files is to use Oracle Instant Client, which is available from [Oracle's site](http://www.oracle.com/technology/software/tech/oci/instantcl... | The best manual for using PHP with Oracle is [Underground PHP Oracle Manual](http://www.oracle.com/technology/tech/php/pdf/underground-php-oracle-manual.pdf). Periodically updated. For example last update describe new cool OCI (Oracle Call Interface) features. I found it by accident and since then has never regretted. ... | Connecting to Oracle using PHP | [
"",
"php",
"oracle",
""
] |
What's the simplest way to connect and query a database for a set of records in C#? | @Goyuix -- that's excellent for something written from memory.
tested it here -- found the connection wasn't opened. Otherwise very nice.
```
using System.Data.OleDb;
...
using (OleDbConnection conn = new OleDbConnection())
{
conn.ConnectionString = "Provider=sqloledb;Data Source=yourServername\\yourInstance;Init... | Very roughly and from memory since I don't have code on this laptop:
```
using (OleDBConnection conn = new OleDbConnection())
{
conn.ConnectionString = "Whatever connection string";
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = conn;
cmd.CommandText = "Select * from CoolTable";
u... | How do I connect to a database and loop over a recordset in C#? | [
"",
"c#",
"database",
"loops",
"connection",
""
] |
The ASP.NET AJAX **ModalPopupExtender** has `OnCancelScript` and `OnOkScript` properties, but it doesn't seem to have an `OnShowScript` property. I'd like to specify a javascript function to run each time the popup is shown.
In past situations, I set the `TargetControlID` to a dummy control and provide my own control ... | hmmm... I'm *pretty sure* that there's a shown event for the MPE... this is off the top of my head, but I think you can add an event handler to the shown event on page\_load
```
function pageLoad()
{
var popup = $find('ModalPopupClientID');
popup.add_shown(SetFocus);
}
function SetFocus()
{
$get('TriggerC... | Here's a simple way to do it in markup:
```
<ajaxToolkit:ModalPopupExtender
ID="ModalPopupExtender2" runat="server"
TargetControlID="lnk_OpenGame"
PopupControlID="Panel1"
BehaviorID="SilverPracticeBehaviorID" >
<Animations>
<OnShown>
<ScriptAction Script="InitializeGame();... | How to specify javascript to run when ModalPopupExtender is shown | [
"",
"asp.net",
"javascript",
"asp.net-ajax",
""
] |
I've found syntax highlighters that highlight pre-existing code, but I'd like to do it as you type with a WYSIWYG-style editor. I don't need auto-completed functions, just the highlighting.
As a follow-up question, what is the WYSIWYG editor that stackoverflow uses?
Edit: Thanks to the answer below, I found two that ... | Here is a really interesting article about how to write one: (Even better, he gives the full source to a JavaScript formatter and colorizer.)
[Implementing a syntax-higlighting JavaScript editor in JavaScript](http://marijn.haverbeke.nl/codemirror/story.html)
or
A brutal odyssey to the dark side of the DOM tree
> How... | The question might be better stated as "What syntax-highlighting editor do you recommended to replace an html textarea in my web app?" (Some of the other answers here deal with desktop apps or pure-syntax highlighters, not client-side editors)
I also recommend [CodeMirror](http://marijn.haverbeke.nl/codemirror/), it's... | Are there any JavaScript live syntax highlighters? | [
"",
"javascript",
"syntax-highlighting",
"wysiwyg",
""
] |
How do I use the profiler in Visual Studio 2008?
I know theres a build option in Config Properties -> Linker -> Advanced -> Profile (/PROFILE), however I can't find anything about actauly using it, only articles I was able to find appear to only apply to older versions of Visual Studio (eg most say to goto Build->Prof... | The profiler is only available in the Team System editions of Visual Studio 2008. The last version that I used that included a profiler was Visual C++ 6.0.
For Visual Studio 2005, you could try [Compuware DevPartner Performance Analysis Community Edition](http://www.compuware.com/media.asp?cid=701000000004ej0). | Microsoft has released stand-alone Profiler for VS 2008 [here](http://www.microsoft.com/downloads/details.aspx?familyid=fd02c7d6-5306-41f2-a1be-b7dcb74c9c0b&displaylang=en) | Profiling in Visual Studio 2008 PRO | [
"",
"c++",
"visual-studio",
"visual-studio-2008",
"profiling",
""
] |
How are you handling the entry of numeric values in WPF applications?
Without a NumericUpDown control, I've been using a TextBox and handling its PreviewKeyDown event with the code below, but it's pretty ugly.
Has anyone found a more graceful way to get numeric data from the user without relying on a third-party cont... | How about:
```
protected override void OnPreviewTextInput(System.Windows.Input.TextCompositionEventArgs e)
{
e.Handled = !AreAllValidNumericChars(e.Text);
base.OnPreviewTextInput(e);
}
private bool AreAllValidNumericChars(string str)
{
foreach(char c in str)
{
if(!Char.IsNumber(c)) return fals... | This is how I do it. It uses a regular expression to check if the text that will be in the box is numeric or not.
```
Regex NumEx = new Regex(@"^-?\d*\.?\d*$");
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (sender is TextBox)
{
string text = (sender as TextBox)... | Numeric Data Entry in WPF | [
"",
"c#",
"wpf",
""
] |
I need to create a 2D int array of size 800x800. But doing so creates a stack overflow (ha ha).
I'm new to C++, so should I do something like a vector of vectors? And just encapsulate the 2d array into a class?
Specifically, this array is my zbuffer in a graphics program. I need to store a z value for every pixel on ... | You need about 2.5 megs, so just using the heap should be fine. You don't need a vector unless you need to resize it. See [C++ FAQ Lite](https://isocpp.org/wiki/faq/freestore-mgmt#multidim-arrays) for an example of using a "2D" heap array.
```
int *array = new int[800*800];
```
(Don't forget to `delete[]` it when you... | Every post so far leaves the memory management for the programmer. This can and should be avoided. ReaperUnreal is darn close to what I'd do, except I'd use a vector rather than an array and also make the dimensions template parameters and change the access functions -- and oh just IMNSHO clean things up a bit:
```
te... | How to work around a very large 2d array in C++ | [
"",
"c++",
"arrays",
"graphics",
"2d",
"zbuffer",
""
] |
I just saw a [comment of suggesting J#](https://stackoverflow.com/questions/5516/what-happened-to-all-of-the-java-developers-how-can-i-get-started-in-net#5522), and it made me wonder... is there a real, beneficial use of J# over Java? So, my feeling is that the only reason you would even consider using J# is that manag... | J# is no longer included in VS2008. Unless you already have J# code, you should probably stay away.
From [j# product page:](http://msdn.microsoft.com/en-us/vjsharp/default.aspx)
> Since customers have told us that the
> existing J# feature set largely meets
> their needs and usage of J# is
> declining, Microsoft is r... | The whole purpose of J# is to ease the transition of Java developers to the .NET environment which didn't work so well (I guessing here) so Microsoft dropped J# from Visual Studio 2008.
For your question, "Is there a real benefit of using J#?"..
in a nutshell... No.. | Is there a real benefit of using J#? | [
"",
"java",
"j#",
""
] |
I am confronted with a new kind of problem which I haven't encountered yet in my very young programming "career" and would like to know your opinion about how to tackle it best.
**The situation**
A research application (php/mysql) gathers stress related health data from users. User gets a an analyses after filling in ... | What you're considering could be done in a number of ways.
1. You could setup a trigger in your DB to recalculate the values whenever a new record is updated. You could store the code needed to update the values in a sproc if necessary.
2. You could write a PHP script and run it regularly via cron.
#1 will slow down ... | PHP set up as a cron job lets you keep it in your source code management system, and if you're using a database abstraction layer it'll be portable to other databases if you ever decide to switch. For those reasons, I tend to go with scripts over stored procedures. | PHP/mySQL - regular recalculation of benchmark values as new users submit their data | [
"",
"php",
"mysql",
"stored-procedures",
"cron",
""
] |
I am sketching the architecture for a set of programs that share various interrelated objects stored in a database. I want one of the programs to act as a service which provides a higher level interface for operations on these objects, and the other programs to access the objects through that service.
I am currently a... | Yes you can. I do it using the pythoncom libraries that come included with [ActivePython](http://www.activestate.com/Products/activepython/index.mhtml) or can be installed with [pywin32](https://sourceforge.net/projects/pywin32/) (Python for Windows extensions).
This is a basic skeleton for a simple service:
```
impo... | The simplest way is to use the: **NSSM - the Non-Sucking Service Manager.** Just download and unzip to a location of your choosing. It's a self-contained utility, around 300KB (much less than installing the entire pywin32 suite just for this purpose) and no "installation" is needed. The zip contains a 64-bit and a 32-b... | How do you run a Python script as a service in Windows? | [
"",
"python",
"windows",
"cross-platform",
""
] |
I have a Java application which I want to shutdown 'nicely' when the user selects Start->Shutdown. I've tried using JVM shutdown listeners via Runtime.addShutdownHook(...) but this doesn't work as I can't use any UI elements from it.
I've also tried using the exit handler on my main application UI window but it has no... | The previously mentioned JNI approach will likely work.
You can use JNA which is basically a wrapper around JNI to make it easier to use. An added bonus is that it (in my opinion at least) generally is faster and more maintainable than raw JNI. You can find JNA at <https://jna.dev.java.net/>
If you're just starting t... | As far as I know you need to start using JNI to set up a message handler for the Windows [WM\_QUERYENDSESSION](http://msdn.microsoft.com/en-us/library/aa376890.aspx) message.
To do this (if you're new to Windows programming like me) you'll need to create a new class of window with a new message handling function (as d... | How do I get my Java application to shutdown nicely in windows? | [
"",
"java",
"windows",
"shutdown",
""
] |
What's the easiest way to convert a percentage to a color ranging from Green (100%) to Red (0%), with Yellow for 50%?
I'm using plain 32bit RGB - so each component is an integer between 0 and 255. I'm doing this in C#, but I guess for a problem like this the language doesn't really matter that much.
Based on Marius a... | I made this function in JavaScript. It returns the color is a css string. It takes the percentage as a variable, with a range from 0 to 100. The algorithm could be made in any language:
```
function setColor(p){
var red = p<50 ? 255 : Math.round(256 - (p-50)*5.12);
var green = p>50 ? 255 : Math.round((p)*5.12)... | What you probably want to do is to assign your 0% to 100% some points in a HSV or HSL color-space. From there you can interpolate colors (and yellow just happens to be between red and green :) and [convert them to RGB](http://en.wikipedia.org/wiki/HSL_color_space). That will give you a nice looking gradient between the... | Conditional formatting -- percentage to color conversion | [
"",
"c#",
"colors",
"rgb",
""
] |
I'm trying to set up an inheritance hierarchy similar to the following:
```
abstract class Vehicle
{
public string Name;
public List<Axle> Axles;
}
class Motorcycle : Vehicle
{
}
class Car : Vehicle
{
}
abstract class Axle
{
public int Length;
public void Turn(int numTurns) { ... }
}
class MotorcycleAxle :... | Use more generics
```
abstract class Vehicle<T> where T : Axle
{
public string Name;
public List<T> Axles;
}
class Motorcycle : Vehicle<MotorcycleAxle>
{
}
class Car : Vehicle<CarAxle>
{
}
abstract class Axle
{
public int Length;
public void Turn(int numTurns) { ... }
}
class MotorcycleAxle : Axle
{
publ... | 2 options spring to mind. 1 is using generics:
```
abstract class Vehicle<TAxle> where TAxle : Axle {
public List<TAxle> Axles;
}
```
The second uses shadowing - and this assumes you have properties:
```
abstract class Vehicle {
public IList<Axle> Axles { get; set; }
}
class Motorcyle : Vehicle {
public ne... | What is the best way to inherit an array that needs to store subclass specific data? | [
"",
"c#",
"oop",
"inheritance",
"covariance",
"contravariance",
""
] |
I have a WCF service from which I want to return a DataTable. I know that this is often a highly-debated topic, as far as whether or not returning DataTables is a good practice. Let's put that aside for a moment.
When I create a DataTable from scratch, as below, there are no problems whatsoever. The table is created, ... | For anyone having similar problems, I have solved my issue. It was several-fold.
* As Darren suggested and Paul backed up, the Max..Size properties in the configuration needed to be enlarged. The SvcTraceViewer utility helped in determining this, but it still does not always give the most helpful error messages.
* It ... | The best way to diagnose these kinds of WCF errors (the ones that really don't tell you much) is to enable tracing. In your web.config file, add the following:
```
<system.diagnostics>
<sources>
<source name="System.ServiceModel"
switchValue="Information"
propagateActivity="tr... | Returning DataTables in WCF/.NET | [
"",
"c#",
".net",
"wcf",
"web-services",
"datatable",
""
] |
Do you know if I can use Visio to forward-engineer a sequence diagram into code (c#)?
Can it be done with Visio alone or do I need a plugin?
What about other diagrams? | You have to get the Visio that for users of Visual Studio. See this link: [Visio for Enterprise Architects](http://msdn.microsoft.com/en-us/library/ms182014.aspx) for more details. The code generation capabilities are fairly weak and you might end up getting Visio into an inconsistent state. I know that Visio will let ... | Looks like the latest version of Sparx Systems Enterprise Architect can forward engineer sequence diagrams
[Sparx Systems Enterprise Architect](http://sparxsystems.com/products/index.html) | Visio and Forward-Engineering | [
"",
"c#",
"visio",
"forward-engineer",
""
] |
Given a URL, what would be the most efficient code to download the contents of that web page? I am only considering the HTML, not associated images, JS and CSS. | ```
public static void DownloadFile(string remoteFilename, string localFilename)
{
WebClient client = new WebClient();
client.DownloadFile(remoteFilename, localFilename);
}
``` | [System.Net.WebClient](http://msdn.microsoft.com/en-us/library/system.net.webclient%28VS.80%29.aspx)
From MSDN:
```
using System;
using System.Net;
using System.IO;
public class Test
{
public static void Main (string[] args)
{
if (args == null || args.Length == 0)
{
throw new Appl... | Fastest C# Code to Download a Web Page | [
"",
"c#",
""
] |
I've got an interesting design question. I'm designing the security side of our project, to allow us to have different versions of the program for different costs and also to allow Manager-type users to grant or deny access to parts of the program to other users. Its going to web-based and hosted on our servers.
I'm u... | If it's only going to be Allow/Deny, then a simple linking table between Users and Resources would work fine. If there is an entry keyed to the User-Resource in the linking table, allow access.
```
UserResources
-------------
UserId FK->Users
ResourceId FK->Resources
```
and the sql would be something like
```
if ex... | I would vote for Option B. If you go with Option A and the assumption that if a user exists, they can get in, then you'll eventually run into the problem that you'll want to deny access to a user, without removing the user record.
There will be lots of cases where you'll want to lock a user out, but won't want to comp... | Is it better to structure an SQL table to have a match, or return no result | [
"",
"sql",
"sql-server",
"optimization",
""
] |
Anything thats as good and as stable and as feature-rich as gigaspaces? | Gigaspaces is top notch as far as a Javaspaces implementation goes for scalability and performance. Are you restricted to a Javaspaces implementation? Blitz Javaspaces is top notch for a free product. | As the first answer says, what are your criteria? There's a number of commercial and open-source tools in the same space (but not Javaspaces-based):
* [Oracle Coherence](http://coherence.oracle.com/display/COH34UG/Coherence+3.4+Home)
* [Gemstone's Gemfire](http://www.gemstone.com/products/gemfire/)
* [Terracotta](http... | Are there any alternatives to Gigaspaces? | [
"",
"java",
"jakarta-ee",
"gigaspaces",
""
] |
I've been doing c# for a long time, and have never come across an easy way to just new up a hash.
I've recently become acquainted with the ruby syntax of hashes and wonder, does anyone know of a simple way to declare a hash as a literal, without doing all the add calls.
```
{ "whatever" => {i => 1}; "and then somethi... | If you're using C# 3.0 (.NET 3.5) then you can use collection initializers. They're not quite as terse as in Ruby but still an improvement.
This example is based on the [MSDN Example](http://msdn.microsoft.com/en-us/library/bb531208.aspx)
```
var students = new Dictionary<int, StudentName>()
{
{ 111, new StudentN... | When I'm not able to use C# 3.0, I use a helper function that translates a set of parameters into a dictionary.
```
public IDictionary<KeyType, ValueType> Dict<KeyType, ValueType>(params object[] data)
{
Dictionary<KeyType, ValueType> dict = new Dictionary<KeyType, ValueType>((data == null ? 0 :data.Length / 2));
... | Literal hashes in c#? | [
"",
"c#",
"ruby",
"hashtable",
"literals",
""
] |
I'm working on a cross platform application in Java which currently works nicely on Windows, Linux and MacOS X. I'm trying to work out a nice way to do detection (and handling) of 'crashes'. Is there an easy, cross-platform way to detect 'crashes' in Java and to do something in response?
I guess by 'crashes' I mean un... | For simple catch-all handling, you can use the following static method in [Thread](http://java.sun.com/javase/6/docs/api/java/lang/Thread.html). From the Javadoc:
> static void [**setDefaultUncaughtExceptionHandler**](http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#setDefaultUncaughtExceptionHandler(java.l... | For handling uncaught exceptions you can provide a new ThreadGroup which provides an implementation of ThreadGroup.uncaughtException(...). You can then catch any uncaught exceptions and handle them appropriately (e.g. send a crash log home).
I can't help you on the JNI front, there's probably a way using a native wrap... | How to capture crash logs in Java | [
"",
"java",
"error-handling",
"crash",
""
] |
Which of the following is better code in c# and why?
```
((DateTime)g[0]["MyUntypedDateField"]).ToShortDateString()
```
or
```
DateTime.Parse(g[0]["MyUntypedDateField"].ToString()).ToShortDateString()
```
Ultimately, is it better to cast or to parse? | If g[0]["MyUntypedDateField"] is really a DateTime object, then the cast is the better choice. If it's not really a DateTime, then you have no choice but to use the Parse (you would get an InvalidCastException if you tried to use the cast) | Casting is the **only** good answer.
You have to remember, that ToString and Parse results are not always exact - there are cases, when you cannot safely roundtrip between those two functions.
The documentation of ToString says, it uses current thread culture settings. The documentation of Parse says, it also uses cu... | C# Casting vs. Parse | [
"",
"c#",
"datetime",
"parsing",
"string",
"casting",
""
] |
I am using a rich text editor on a web page. .NET has feature that prevent one from posting HTML tags, so I added a JavaScript snippet to change the angle brackets to and alias pair of characters before the post. The alias is replaced on the server with the necessary angle bracket and then stored in the database. With ... | There's actually a way to turn that "feature" off. This will allow the user to post whichever characters they want, and there will be no need to convert characters to an alias using Javascript. See this article for [disabling request validation](http://mdid.org/mdidwiki/index.php?title=Disabling_Request_Validation). It... | I think the safest way to go is to NOT allow the user to create tags with your WISYWIG. Maybe using something like a markdown editor like on this site or [available here.](http://wmd-editor.com/) would be another approach.
Also keep the Page directive ValidateRequest=true which should stop markup from being sent in th... | Browser WYSIWYG best practices | [
"",
"asp.net",
"javascript",
"wysiwyg",
""
] |
I need to determine if I'm on a particular view. My use case is that I'd like to decorate navigation elements with an "on" class for the current view. Is there a built in way of doing this? | Here what i am using. I think this is actually generated by the MVC project template in VS:
```
public static bool IsCurrentAction(this HtmlHelper helper, string actionName, string controllerName)
{
string currentControllerName = (string)helper.ViewContext.RouteData.Values["controller"];
string cur... | My current solution is with extension methods:
```
public static class UrlHelperExtensions
{
/// <summary>
/// Determines if the current view equals the specified action
/// </summary>
/// <typeparam name="TController">The type of the controller.</typeparam>
/// <param name="helper">Url Helper</par... | Asp.Net MVC: How to determine if you're currently on a specific view | [
"",
"c#",
"asp.net-mvc",
""
] |
I'm maintaining a .NET 1.1 application and one of the things I've been tasked with is making sure the user doesn't see any unfriendly error notifications.
I've added handlers to `Application.ThreadException` and `AppDomain.CurrentDomain.UnhandledException`, which do get called. My problem is that the standard CLR erro... | Oh, in Windows Forms you definitely should be able to get it to work. The only thing you have to watch out for is things happening on different threads.
I have an old Code Project article here which should help:
*[User Friendly Exception Handling](http://www.codeproject.com/KB/exception/ExceptionHandling.aspx)* | **AppDomain.UnhandledException** is an **event**, not a global exception handler. This means, by the time it is raised, your application is already on its way down the drain, and there is nothing you can do about it, except for doing cleanup and error logging.
What happened behind the scenes is this: The framework det... | Unhandled Exception Handler in .NET 1.1 | [
"",
"c#",
".net",
"exception",
""
] |
What are some standard practices for managing a medium-large JavaScript application? My concerns are both speed for browser download and ease and maintainability of development.
Our JavaScript code is roughly "namespaced" as:
```
var Client = {
var1: '',
var2: '',
accounts: {
/* 100's of functions and... | The approach that I've found works for me is having seperate JS files for each class (just as you would in Java, C# and others). Alternatively you can group your JS into application functional areas if that's easier for you to navigate.
If you put all your JS files into one directory, you can have your server-side env... | Also, I suggest you to use Google's [AJAX Libraries API](http://code.google.com/apis/ajaxlibs/documentation/) in order to load external libraries.
It's a Google developer tool which bundle majors JavaScript libraries and make it easier to deploy, upgrade and make them lighter by always using compressed versions.
Also... | Best practices for managing and deploying large JavaScript apps | [
"",
"javascript",
"web-applications",
"deployment",
""
] |
How would you go about finding out how much memory is being used by an object? I know it is possible to find out how much is used by a block of code, but not by an instantiated object (anytime during its life), which is what I want. | **There's no easy way to find out the memory size of a python object**. One of the problems you may find is that Python objects - like lists and dicts - may have references to other python objects (in this case, what would your size be? The size containing the size of each object or not?). There are some pointers overh... | Try this:
```
sys.getsizeof(object)
```
[getsizeof()](https://docs.python.org/3/library/sys.html#sys.getsizeof) Return the size of an object in bytes. It calls the object’s `__sizeof__` method and adds an additional garbage collector overhead **if** the object is managed by the garbage collector.
[A recursive recipe... | Find out how much memory is being used by an object in Python | [
"",
"python",
"performance",
"memory-profiling",
""
] |
I have a layered application in Java which has a multi thread data access layer which is invoked from different points. A single call to this layer is likely to spawn several threads to parallelize requests to the DB.
What I'm looking for is a logging tool that would allow me to define "activities" that are composed b... | You should also have a look at the [nested diagnostic context](http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/NDC.html) feature of log4j. Pushing different contexts to the logger for different callers might do the trick for you. | You should be able to pass a logger around, so you create a logger based on some "common" for the task data - i.e. username, etc. Then, pass this logger as parameter to all methods you need. That way, you'll be able to set different filters and/or rules in your log4j config file. Or to scrape the output file based on t... | Logging activities in multithreaded applications | [
"",
"java",
"logging",
"log4j",
""
] |
I'm just curious if any project exists that attempts to group all (or most) of PHP's built-in functions into a more object-oriented class hierarchy. For example, grouping all the string functions into a single String class, etc.
I realize this won't actually solve any problems (unless the modifications took place at t... | To Answer your question, Yes there exists several of libraries that do exactly what you are talking about. As far as which one you want to use is an entirely different question. PHPClasses and pear.org are good places to start looking for such libraries.
Update:
As the others have suggested SPL is a good library and w... | Way too many times. As soon as someone discovers that PHP has OO features they want to wrap everything in classes.
The point to the OO stuff in PHP is so that you can architect your solutions in whichever way you want. But wrapping the existing functions in Objects doesn't yield much payoff.
That being said PHP's cor... | Has anyone attempted to make PHP's system functions more Object-Oriented? | [
"",
"php",
"oop",
"wrapper",
""
] |
How do I add a method to an existing object (i.e., not in the class definition) in Python?
I understand that it's not generally considered good practice to do so, except in some cases. | In Python, there is a difference between functions and bound methods.
```
>>> def foo():
... print "foo"
...
>>> class A:
... def bar( self ):
... print "bar"
...
>>> a = A()
>>> foo
<function foo at 0x00A98D70>
>>> a.bar
<bound method A.bar of <__main__.A instance at 0x00A9BC88>>
>>>
```
Bound method... | Preface - a note on compatibility: other answers may only work in Python 2 - this answer should work perfectly well in Python 2 and 3. If writing Python 3 only, you might leave out explicitly inheriting from `object`, but otherwise the code should remain the same.
> # Adding a Method to an Existing Object Instance
>
>... | Adding a method to an existing object instance in Python | [
"",
"python",
"oop",
"methods",
"monkeypatching",
""
] |
Example:
```
select ename from emp where hiredate = todate('01/05/81','dd/mm/yy')
```
and
```
select ename from emp where hiredate = todate('01/05/81','dd/mm/rr')
```
return different results | <http://oracle.ittoolbox.com/groups/technical-functional/oracle-dev-l/difference-between-yyyy-and-rrrr-format-519525>
> YY allows you to retrieve just two digits of a year, for example, the 99 in
> 1999. The other digits (19) are automatically assigned to the current
> century. RR converts two-digit years into four-di... | y2k compatibility. rr assumes 01 to be 2001, yy assumes 01 to be 1901
see: <http://www.oradev.com/oracle_date_format.jsp>
edit: damn! [michael "quickfingers" stum](https://stackoverflow.com/users/91/michael-stum) [beat me to it](https://stackoverflow.com/questions/19058/what-is-the-difference-between-oracles-yy-and-r... | What is the difference between oracle's 'yy' and 'rr' date mask? | [
"",
"sql",
"oracle",
""
] |
I'm looking for a Java profiler that works well with the JVM coming with WebSphere 6.0.2 (IBM JVM 1.4.2). I use yourkit for my usual profiling needs, but it specifically refuses to work with this old jvm (I'm sure the authors had their reasons...).
Can anybody point to a decent profiler that can do the job? Not intere... | Update: I found out that [JProfiler](http://www.ej-technologies.com/products/jprofiler/overview.html) integrates smoothly with WAS 6.0.2 (IBM JDK 1.4). | Old post, but this may help someone. You can use [IBM Health Center](http://www.ibm.com/developerworks/java/jdk/tools/healthcenter/) which is free. It can be downloaded standalone or as part of the [IBM Support Assistant](http://www-01.ibm.com/software/support/isa/). I suggest downloading ISA since it has a ton of othe... | Java profiler for IBM JVM 1.4.2 (WebSphere 6.0.2) | [
"",
"java",
"websphere",
"profiler",
""
] |
I'm trying to find out how much memory my own .Net server process is using (for monitoring and logging purposes).
I'm using:
```
Process.GetCurrentProcess().PrivateMemorySize64
```
However, the Process object has several different properties that let me read the memory space used:
Paged, NonPaged, PagedSystem, NonPa... | If you want to know how much the GC uses try:
```
GC.GetTotalMemory(true)
```
If you want to know what your process uses from Windows (VM Size column in TaskManager) try:
```
Process.GetCurrentProcess().PrivateMemorySize64
```
If you want to know what your process has in RAM (as opposed to in the pagefile) (Mem Usa... | OK, I found through Google the same page that Lars mentioned, and I believe it's a great explanation for people that don't quite know how memory works (like me).
<http://shsc.info/WindowsMemoryManagement>
My short conclusion was:
* Private Bytes = The Memory my process has requested to store data. Some of it may be ... | Process Memory Size - Different Counters | [
"",
"c#",
".net",
"memory",
"process",
"diagnostics",
""
] |
Visual Basic code does not render correctly with [prettify.js](https://code.google.com/archive/p/google-code-prettify) from Google.
on Stack Overflow:
```
Partial Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
... | /EDIT: I've rewritten the whole posting.
Below is a pretty complete solution to the VB highlighting problem. If SO has got nothing better, *please* use it. VB syntax highlighting is definitely wanted.
I've also added a code example with some complex code literals that gets highlighted correctly. However, I haven't ev... | Prettify does support VB comments as of the 8th of January 2009.
To get vb syntax highlighting working correctly you need three things;
```
<script type="text/javascript" src="/External/css/prettify/prettify.js"></script>
<script type="text/javascript" src="/External/css/prettify/lang-vb.js"></script>
```
and a PRE ... | Is there a lang-vb or lang-basic option for prettify.js from Google? | [
"",
"javascript",
"vb.net",
"prettify",
""
] |
Is there an open source library that will help me with reading/parsing PDF documents in .NET/C#? | Since this question was last answered in 2008, iTextSharp has improved their api dramatically. If you download the latest version of their api from <http://sourceforge.net/projects/itextsharp/>, you can use the following snippet of code to extract all text from a pdf into a string.
```
using iTextSharp.text.pdf;
using... | **[iTextSharp](https://github.com/itext/itextsharp)** is the best bet. Used it to make a spider for lucene.Net so that it could crawl PDF.
```
using System;
using System.IO;
using iTextSharp.text.pdf;
using System.Text.RegularExpressions;
namespace Spider.Utils
{
/// <summary>
/// Parses a PDF file and extrac... | Reading PDF documents in .Net | [
"",
"c#",
".net",
"pdf",
""
] |
Why does C#.Net allow the declaration of the string object to be case-insensitive?
```
String sHello = "Hello";
string sHello = "Hello";
```
Both the lower-case and upper-case S of the word String are acceptable and this seems to be the only object that allows this.
Can anyone explain why? | **`string`** is a language keyword while `System.String` is the type it aliases.
Both compile to exactly the same thing, similarly:
* **`int`** is `System.Int32`
* **`long`** is `System.Int64`
* **`float`** is `System.Single`
* **`double`** is `System.Double`
* **`char`** is `System.Char`
* **`byte`** is `System.Byte... | Further to the other answers, it's good practice to use keywords if they exist.
E.g. you should use **string** rather than **System.String**. | C#.Net case-insensitive string | [
"",
"c#",
".net",
""
] |
I've tried several things already,
```
std::stringstream m;
m.empty();
m.clear();
```
both of which don't work. | For all the standard library types the member function `empty()` is a query, not a command, i.e. it means "are you empty?" not "please throw away your contents".
The `clear()` member function is inherited from `ios` and is used to clear the error state of the stream, e.g. if a file stream has the error state set to `e... | You can **clear the error state **and** empty the stringstream** all in one line
```
std::stringstream().swap(m); // swap m with a default constructed stringstream
```
This effectively resets m to a default constructed state, meaning that **it actually deletes the buffers allocated by the string stream and resets the... | How do you clear a stringstream variable? | [
"",
"c++",
"stringstream",
""
] |
Can I return it as an object if I am doing a
```
Select OneItem from Table Where OtherItem = "blah"?
```
Is there a better way to do this?
I am building a constructor to return an object based on its name rather than its ID. | `query.UniqueResult<T>()` returns just one **T** | If there's more than one potential result, then `query.FirstResult()` might be better. | IQuery NHibernate - does it HAVE to be a list? | [
"",
"c#",
".net",
"nhibernate",
""
] |
I have three tables `tag`, `page`, `pagetag`
With the data below
***page***
```
ID NAME
1 page 1
2 page 2
3 page 3
4 page 4
```
***tag***
```
ID NAME
1 tag 1
2 tag 2
3 tag 3
4 tag 4
```
***pagetag***
```
ID PAGEID TAGID
1 2 1
2 2 3
... | > Sergio del Amo:
>
> > However, I am not getting the pages without tags. I guess i need to write my query with left outer joins.
```
SELECT pagetag.id, page.name, group_concat(tag.name)
FROM
(
page LEFT JOIN pagetag ON page.id = pagetag.pageid
)
LEFT JOIN tag ON pagetag.tagid = tag.id
GROUP BY page.id;
```
Not a... | Yep, you can do it across the 3 something like the below:
```
SELECT page_tag.id, page.name, group_concat(tags.name)
FROM tag, page, page_tag
WHERE page_tag.page_id = page.page_id AND page_tag.tag_id = tag.id;
```
Has not been tested, and could be probably be written a tad more efficiently, but should get you started... | Concatenate several fields into one with SQL | [
"",
"sql",
"mysql",
""
] |
I have a view that has a list of jobs in it, with data like who they're assigned to and the stage they are in. I need to write a stored procedure that returns how many jobs each person has at each stage.
So far I have this (simplified):
```
DECLARE @ResultTable table
(
StaffName nvarchar(100),
Stage1Count int,
... | IIRC there is some sort of "On Duplicate" (name might be wrong) syntax that lets you update if a row exists (MySQL)
Alternately some form of:
```
INSERT INTO @ResultTable (StaffName, Stage1Count, Stage2Count)
SELECT StaffName,0,0 FROM ViewJob
GROUP BY StaffName
UPDATE @ResultTable Stage1Count= (
SELECT COUNT(*... | Actually, I think you're making it much harder than it is. Won't this code work for what you're trying to do?
```
SELECT StaffName, SUM(InStage1) AS 'JobsAtStage1', SUM(InStage2) AS 'JobsAtStage2'
FROM ViewJob
GROUP BY StaffName
``` | How do I do an Upsert Into Table? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Is there any easy/general way to clean an XML based data source prior to using it in an XmlReader so that I can gracefully consume XML data that is non-conformant to the hexadecimal character restrictions placed on XML?
Note:
* The solution needs to handle XML
data sources that use character
encodings other than ... | It **may not be perfect** (emphasis added since people missing this disclaimer), but what I've done in that case is below. You can adjust to use with a stream.
```
/// <summary>
/// Removes control characters and other non-UTF-8 characters
/// </summary>
/// <param name="inString">The string to process</param>
/// <re... | I like Eugene's whitelist concept. I needed to do a similar thing as the original poster, but I needed to support all Unicode characters, not just up to 0x00FD. The XML spec is:
Char = #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
In .NET, the internal representation of Unicode characters is ... | How do you remove invalid hexadecimal characters from an XML-based data source prior to constructing an XmlReader or XPathDocument that uses the data? | [
"",
"c#",
"xml",
"validation",
"encoding",
""
] |
I have binary data in a file that I can read into a byte array and process with no problem. Now I need to send parts of the data over a network connection as elements in an XML document. My problem is that when I convert the data from an array of bytes to a String and back to an array of bytes, the data is getting corr... | If you encode it in base64, this will turn any data into ascii safe text, but base64 encoded data is larger than the orignal data | [String(byte[])](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html) treats the data as the default character encoding. So, how bytes get converted from 8-bit values to 16-bit Java Unicode chars will vary not only between operating systems, but can even vary between different users using different codepages... | How do you convert binary data to Strings and back in Java? | [
"",
"java",
"serialization",
""
] |
In what situation would it be more appropriate for me to use a bitset (STL container) to manage a set of flags rather than having them declared as a number of separate (bool) variables?
Will I get a significant performance gain if I used a bitset for 50 flags rather than using 50 separate bool variables? | Well, 50 bools as a bitset will take 7 bytes, while 50 bools as bools will take 50 bytes. These days that's not really a big deal, so using bools is probably fine.
However, one place a bitset might be useful is if you need to pass those bools around a lot, especially if you need to return the set from a function. Usin... | std::bitset will give you extra points when you need to serialize / deserialize it. You can just write it to a stream or read from a stream with it. But certainly, the separate bools are going to be faster. They are optimized for this kind of use after all, while a bitset is optimized for space, and has still function ... | When to use STL bitsets instead of separate variables? | [
"",
"c++",
"performance",
"bitsets",
""
] |
I have a page using `<ul>` lists for navigation (Javascript changes the styling to display or not on mouseover).
This is working fine for me *except* in IE6 and IE7 when I have a Google Map on the page.
In this case the drop-down simply does not work. However, the page continues to work in FireFox 2.
I have done a l... | I don't know if this will fix your problem but you may want to try [this solution at ccsplay.co.uk](http://www.cssplay.co.uk/menus/pro_drop8.html) which fixes the problem of menus appearing underneath drop-down lists. I don't know if it will work for sure, but it's worth a shot. | I fixed a similar issue with drop-downs not appearing over flash movies in IE6/IE7/IE8 using this [jQuery](http://jquery.com/):
```
$(function () {
$("#primary-nav").appendTo("#footer");
});
```
Where `primary-nav` is the `ID` of the drop-down container element and `footer` is the `ID` of the last element on the pa... | Best way to fix CSS/JS drop-down in IE7 when page includes Google Map | [
"",
"javascript",
"css",
"cross-browser",
"browser",
"client-side",
""
] |
Using C# and WPF under .NET (rather than [Windows Forms](http://en.wikipedia.org/wiki/Windows_Forms) or console), what is the correct way to create an application that can only be run as a single instance?
I know it has something to do with some mythical thing called a mutex, rarely can I find someone that bothers to ... | Here is a very good [article](http://sanity-free.org/143/csharp_dotnet_single_instance_application.html) regarding the Mutex solution. The approach described by the article is advantageous for two reasons.
First, it does not require a dependency on the Microsoft.VisualBasic assembly. If my project already had a depend... | You could use the Mutex class, but you will soon find out that you will need to implement the code to pass the arguments and such yourself. Well, I learned a trick when programming in WinForms when I read [Chris Sell's book](http://sellsbrothers.com/wfbook/). This trick uses logic that is already available to us in the... | What is the correct way to create a single-instance WPF application? | [
"",
"c#",
".net",
"wpf",
"mutex",
""
] |
How can I create an [iterator](https://stackoverflow.com/questions/9884132/what-are-iterator-iterable-and-iteration) in Python?
For example, suppose I have a class whose instances logically "contain" some values:
```
class Example:
def __init__(self, values):
self.values = values
```
I want to be able to... | Iterator objects in python conform to the iterator protocol, which basically means they provide two methods: `__iter__()` and `__next__()`.
* The `__iter__` returns the iterator object and is implicitly called
at the start of loops.
* The `__next__()` method returns the next value and is implicitly called at each lo... | There are four ways to build an iterative function:
* create a generator (uses the [yield keyword](http://docs.python.org/py3k/reference/expressions.html#yield-expressions))
* use a generator expression ([genexp](http://docs.python.org/py3k/reference/expressions.html#generator-expressions))
* create an iterator (defin... | How to build a basic iterator? | [
"",
"python",
"object",
"iterator",
""
] |
Could somebody please do a rundown of how to programmatically encrypt a config-file in .NET, preferably in C#.
What I would like to do is do some kind of check on an application's startup to see if a section is unprotected, and if it is, then encrypt it. This for both settings and connection-strings.
Also if anyone c... | To summarize the answers and what I've found so far, here are some good links to answer this question:
* [Encrypting Configuration Information in ASP.NET 2.0 Applications - 4GuysFromRolla.com](https://web.archive.org/web/20211029043331/https://aspnet.4guysfromrolla.com/articles/021506-1.aspx)
* [How To: Encrypt Config... | There is a good article from 4 guys about [Encrypting Configuration Information in ASP.NET 2.0 Applications](https://web.archive.org/web/20211029043331/https://aspnet.4guysfromrolla.com/articles/021506-1.aspx)
Hope this helps | Programmatically encrypting a config-file in .NET | [
"",
"c#",
".net",
"configuration",
"encryption",
"configuration-files",
""
] |
I want to embed a wikipedia article into a page but I don't want all the wrapper (navigation, etc.) that sits around the articles. I saw it done here: <http://www.dayah.com/periodic/>. Click on an element and the iframe is displayed and links to the article only (no wrapper). So how'd they do that? Seems like JavaScrip... | The periodic table example loads the printer-friendly version of the wiki artice into an iframe. <http://en.wikipedia.org/wiki/Potasium>?**printable=yes**
it's done in *function click\_wiki(e)* (line 534, interactivity.js)
> ```
> var article = el.childNodes[0].childNodes[n_name].innerHTML;
> ...
> window.frames["Wik... | @VolkerK is right, they are using the printable version.
Here is an easy way to find out when you know the site is displaying the page in an iframe.
In Firefox right click anywhere inside the iframe, from the context menu select "This Frame" then "View frame info"
You get the info you need including the Address:
> ... | iframe wikipedia article without the wrapper | [
"",
"javascript",
"iframe",
"wikipedia",
""
] |
If you're building an `AJA~Xy` app, are there any downsides to using `JSONP` requests/responses even if you're not planning on any `cross-domain` requests?
The only thing I can think of is that there are a couple extra bytes for the callback wrapper...
**Edit:**
I found [this](http://remysharp.com/2007/10/08/what-is... | Downside? It's fairly limited - you trigger a "GET" request and get back some script that's executed. You don't get error handling if your server throws an error, so you need to wrap all errors in JSON as well. You can't really cancel or retry the request. You're at the mercy of the various browser author opinions of "... | Retrieving errors when a jsonp call fails is possible.
<http://code.google.com/p/jquery-jsonp/>
Hope it helps. | Are there reasons not to use JSONP for AJA~X requests? | [
"",
"javascript",
"ajax",
"json",
"jsonp",
""
] |
If I call `os.stat()` on a broken `symlink`, python throws an `OSError` exception. This makes it useful for finding them. However, there are a few other reasons that `os.stat()` might throw a similar exception. Is there a more precise way of detecting broken `symlinks` with Python under Linux? | A common Python saying is that it's easier to ask forgiveness than permission. While I'm not a fan of this statement in real life, it does apply in a lot of cases. Usually you want to avoid code that chains two system calls on the same file, because you never know what will happen to the file in between your two calls ... | This is not atomic but it works.
`os.path.islink(filename) and not os.path.exists(filename)`
Indeed by [RTFM](https://docs.python.org/2/library/os.path.html)
(reading the fantastic manual) we see
> os.path.exists(path)
>
> Return True if path refers to an existing path. Returns False for broken symbolic links.
It a... | Find broken symlinks with Python | [
"",
"python",
"linux",
"symlink",
""
] |
I've seen this done in a few sites, an example is [artofadambetts.com](http://www.artofadambetts.com/weblog/?p=169). The scroll bar on the page scrolls only an element of the page, not the entire page. I looked at the source and havent't been able to figure it out yet. How is this done? | That's pretty nifty. He uses "position:fixed" on most of the divs, and the one that scrolls is the one that doesn't have it. | In fact it is not the scrolling part that is "doing the job", it is the fixed part of the page.
In order to do this, you should use CSS and add `position: fixed;` property (use it with `top`, `bottom`, `left` and/or `right` properties) to the elements that you wish not to scroll.
And you should not forget to give the... | How to set up the browser scrollbar to scroll part of a page? | [
"",
"javascript",
"html",
"css",
""
] |
I'm looking for a key/value pair object that I can include in a web service.
I tried using .NET's [`System.Collections.Generic.KeyValuePair<>`](http://msdn.microsoft.com/en-us/library/5tbh8a42.aspx) class, but it does not properly serialize in a web service. In a web service, the Key and Value properties are not seria... | Just define a struct/class.
```
[Serializable]
public struct KeyValuePair<K,V>
{
public K Key {get;set;}
public V Value {get;set;}
}
``` | I don't think there is as `Dictionary<>` itself isn't XML serializable, when I had need to send a dictionary object via a web service I ended up wrapping the `Dictionary<>` object myself and adding support for `IXMLSerializable`.
```
/// <summary>
/// Represents an XML serializable collection of keys and values.
/// <... | Is there a serializable generic Key/Value pair class in .NET? | [
"",
"c#",
".net",
""
] |
Let's say I have the following simple enum:
```
enum Response
{
Yes = 1,
No = 2,
Maybe = 3
}
```
How can I bind this enum to a DropDownList control so that the descriptions are displayed in the list as well as retrieve the associated numeric value (1,2,3) once an option has been selected? | I probably wouldn't **bind** the data as it's an enum, and it won't change after compile time (unless I'm having one of those *stoopid* moments).
Better just to iterate through the enum:
```
Dim itemValues As Array = System.Enum.GetValues(GetType(Response))
Dim itemNames As Array = System.Enum.GetNames(GetType(Respon... | Use the following utility class `Enumeration` to get an `IDictionary<int,string>` (Enum value & name pair) from an **Enumeration**; you then bind the **IDictionary** to a bindable Control.
```
public static class Enumeration
{
public static IDictionary<int, string> GetAll<TEnum>() where TEnum: struct
{
... | How do you bind an Enum to a DropDownList control in ASP.NET? | [
"",
"c#",
".net",
"asp.net",
""
] |
I could only find the function `confirm()` that gives OK/Cancel buttons. Is there any way to give Yes/No buttons? | Javascript offers 3 modal boxes. `prompt`, `confirm` and `alert`. None of those satisfy your request.
There are a plethora of js modal popup solutions. Here's an example.
* [ModalBox](https://github.com/okonet/modalbox) | No.
Instead you could use a in browser modal popup. | Code to ask yes/no question in javascript | [
"",
"javascript",
""
] |
Best recommendations for accessing and manipulation of sqlite databases from JavaScript. | Well, if you are working on client side JavaScript, I think you will be out of luck... browsers tend to sandbox the JavaScript environment so you don't have access to the machine in any kind of general capacity like accessing a database.
If you are talking about an SQLite DB on the server end accessed from the client ... | There a project called [`sql.js`](https://github.com/kripken/sql.js) which is a port of SQLite in JavaScript.
> sql.js is a port of SQLite to JavaScript, by compiling the SQLite C code with Emscripten. | JavaScript sqlite | [
"",
"javascript",
"sqlite",
""
] |
I need to grab the `base64-encoded` representation of the `ViewState`. Obviously, this would not be available until fairly late in the request lifecycle, which is OK.
For example, if the output of the page includes:
```
<input type="hidden" name="__VIEWSTATE"
id="__VIEWSTATE" value="/wEPDwUJODU0Njc5MD...==" />
```... | Rex, I suspect a good place to start looking is solutions that **compress the ViewState** -- they're grabbing ViewState on the server before it's sent down to the client and gzipping it. That's exactly where you want to be.
* [Scott Hanselman on ViewState Compression](http://www.hanselman.com/blog/CommentView,guid,feb... | See this [blog post](http://aspguy.wordpress.com/2008/07/09/reducing-the-page-size-by-storing-viewstate-on-server/) where the author describes a method for overriding the default behavior for generating the ViewState and instead shows how to save it on the server Session object.
> In ASP.NET 2.0, ViewState is saved by... | How to get the value of built, encoded ViewState? | [
"",
"c#",
"asp.net",
"viewstate",
""
] |
I have a byte array in memory, read from a file. I would like to split the byte array at a certain point (index) without having to just create a new byte array and copy each byte at a time, increasing the in memory foot print of the operation. What I would like is something like this:
```
byte[] largeBytes = [1,2,3,4,... | This is how I would do that:
```
using System;
using System.Collections;
using System.Collections.Generic;
class ArrayView<T> : IEnumerable<T>
{
private readonly T[] array;
private readonly int offset, count;
public ArrayView(T[] array, int offset, int count)
{
this.array = array;
thi... | In C# with Linq you can do this:
```
smallPortion = largeBytes.Take(4).ToArray();
largeBytes = largeBytes.Skip(4).Take(5).ToArray();
```
;) | How to split a byte array | [
"",
"c#",
"arrays",
"split",
""
] |
I am using the code snippet below, however it's not working quite as I understand it should.
```
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
try {
line = br.readLine();
while(line != null) {
Sys... | > From my understanding of this, readLine should return null the first time no input is entered other than a line termination, like '\r'.
That is not correct. `readLine` will return `null` if the end of the stream is reached. That is, for example, if you are reading a file, and the file ends, or if you're reading from... | No input is not the same as the end of the stream. You can usually simulate the end of the stream in a console by pressing `Ctrl`+`D` (AFAIK some systems use `Ctrl`+`Z` instead). But I guess this is not what you want so better test for empty strings additionally to null strings. | I Am Not Getting the Result I Expect Using readLine() in Java | [
"",
"java",
"java-io",
""
] |
I'm looking for a way to delete a file which is locked by another process using C#. I suspect the method must be able to find which process is locking the file (perhaps by tracking the handles, although I'm not sure how to do this in C#) then close that process before being able to complete the file delete using `File.... | Killing other processes is not a healthy thing to do. If your scenario involves something like uninstallation, you could use the [**`MoveFileEx`** API function](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-movefileexa) to mark the file for deletion upon next reboot.
If it appears that you rea... | The typical method is as follows. You've said you want to do this in C# so here goes...
1. If you don't know which process has the file locked, you'll need to examine each process's handle list, and query each handle to determine if it identifies the locked file. Doing this in C# will likely require P/Invoke or an int... | How do I delete a file which is locked by another process in C#? | [
"",
"c#",
"file-locking",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.