Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I am new with Linq and I would like to sort some data that are in the BindingList. Once I did my Linq query, I need to use back the BindingList collection to bind my data.
```
var orderedList = //Here is linq query
return (BindingList<MyObject>)orderedList;
```
This compiled but fails in execution, what is the tric... | ```
new BindingList<MyObject>(orderedList.ToList())
``` | You can't always cast any collection type into any other collection. In terms of when the the compiler checks casting, check out this post on [Compile-time vs runtime casting](https://stackoverflow.com/a/4499558/1366033)
However, you can easily produce a `BindingList` from an enumerable by doing some of the plumbing y... | BindingList and LINQ? | [
"",
"c#",
".net",
"linq",
".net-3.5",
"c#-3.0",
""
] |
I am developing an .net application which heavely depends on plugins. The application itself contains an connection to a remote server.
Recently I digged into Application domains and see them as the ideal solution for isolating the plugin code from the rest of the application.
However there is one big disadvantage wh... | Have you tried deriving from [MarshalByRefObject](http://msdn.microsoft.com/en-us/library/system.marshalbyrefobject.aspx)? It's a pain in that it screws up your inheritance hierarchy, but I think it's what you want.
From the docs:
> MarshalByRefObject is the base class
> for objects that communicate across
> applicat... | Be aware that clean-up of `MarshalByRefObject` proxies are cleaned up based on a lease. In short if you don't use the object for a specific time it will be reclaimed. You can control this by overriding `InitializeLifetimeService` to return a lease object which matches you needs. If you return `null` you effectively dis... | Workaround .net application domain only passing objects by value | [
"",
"c#",
"appdomain",
"marshalbyrefobject",
""
] |
If i have a complex object, what is the best practice pattern to write code to compare 2 instances to see if they are the same | Implement the IEquatable interface. This defines a generalized method that a value type or class implements to create a type-specific method for determining equality of instances. Don't forget to override Equals(object) as well.
More information here:
<http://msdn.microsoft.com/en-us/library/ms131187.aspx> | I think the answer is highly problem dependent. For example, you may want to consider objects equal only if all of their properties are equivalent. This would perhaps be the case where each object doesn't have a uniquely identifying property. If there is such a property (or properties), say an ID or ID and Version, tha... | Comparing two objects . | [
"",
"c#",
""
] |
I have a Python function in which I am doing some sanitisation of the input parameters:
```
def func(param1, param2, param3):
param1 = param1 or ''
param2 = param2 or ''
param3 = param3 or ''
```
This caters for the arguments being passed as *None* rather than empty strings. Is there an easier/more concis... | This looks like a good job for a decorator. How about this:
```
def sanitized(func):
def sfunc(*args, **kwds):
return func(*[arg or '' for arg in args],
**dict((k, v or '') for k,v in kwds.iteritems()))
sfunc.func_name = func.func_name
sfunc.func_doc = func.func_doc
return s... | You could do some list manipulation:
```
def func(param1, param2, param3):
param1, param2, param3 = map(lambda x: x or '', (param1, param2, param3))
```
but I'm not sure that's better than just writing out the nine lines, since once you get to nine parameters, that's a heinously long line.
You could change the d... | Loop function parameters for sanity check | [
"",
"python",
"function",
"parameters",
"arguments",
"sanitization",
""
] |
I have a non-visual component which manages other visual controls.
I need to have a reference to the form that the component is operating on, but i don't know how to get it.
I am unsure of adding a constructor with the parent specified as control, as i want the component to work by just being dropped into the designe... | [It is important to understand that the ISite technique below only works at design time. Because ContainerControl is public and gets assigned a value VisualStudio will write initialization code that sets it at run-time. Site is set at run-time, but you can't get ContainerControl from it]
[Here's an article](http://www... | I use a recursive call to walk up the control chain. Add this to your control.
```
public Form ParentForm
{
get { return GetParentForm( this.Parent ); }
}
private Form GetParentForm( Control parent )
{
Form form = parent as Form;
if ( form != null )
{
return form;
}
if ( parent != null... | Get Component's Parent Form | [
"",
"c#",
"vb.net",
"winforms",
"components",
""
] |
I have been looking for a quadtree/quadtree node implementation on the net for ages. There is some basic stuff but nothing that I would be able to really use it a game.
My purpose is to store objects in a game for processing things such as collision detection.
I am not 100% certain that a quadtree is the best data str... | Quadtrees are used when you only need to store things that are effectively on a plane. Like units in a classic RTS where they are all on the ground or just a little bit above it. Essentially each node has links to 4 children that divide the node's space up into evenly distributed quarters.
Octrees do the same but in a... | A red-black tree is not a spatial index; it can only sort on a single ordinal key. A quadtree is (for two dimensions) a spatial index that allows fast lookup and elimination of points. An Octree does the same thing for three dimensions. | Quadtree vs Red-Black tree for a game in C++? | [
"",
"c++",
"quadtree",
""
] |
I'm almost finished with the book "Head First Java". The reason I'm studying this is I'm hoping to get a job developing with JavaEE someday. Now I'm thinking, should I go ahead and study EE (moving on to Head First Servlets and JSP) or should I spend more time with SE? Would it help? I'll go on and say directly that I ... | To me its fine to go with JavaEE, as you already did adequate of SE. And certainly hanging out in programming forums will teach you now and then things which are still hidden from you. Believe me there would be many. Anyhow, I am having few advices for you, which will help you down the road.
* Its better to have a ver... | Knowledge is never a bad thing, so more SE is recommended.
But there's nothing wrong with getting your feet wet with EE now. Start with servlets, JSPs, and JDBC. You can do lots of useful things with just these, and it's fair to call it EE.
If you do write JSPs, just make sure that you do it the right way - using JST... | Should I do more JavaSE before jumping to JavaEE? | [
"",
"java",
"jakarta-ee",
""
] |
I am trying to get some `JavaScript` to programmatically adjust a HTML `img` tag's width to display various sized images correctly.
I have a fixed width `img` tag at `800px` to display an image, this is the max width.
If the image is wider then `800px` I want to display it at `800px` wide;
If the image is less than ... | I have never seen a safari in work, but you can try changing your onload event to this:
```
onload="resize_image(self.id);return true"
```
It could be that without a return value, safari thinks that this object should not be loaded. | Use the IE6 css+javascript hack:
```
.dynamic_img {
width: expression(document.body.clientWidth <= 800? "auto" : "800px");
max-width: 800px; //For normal browsers
}
``` | HTML + Javascript: Dynamic Image Resize? | [
"",
"javascript",
"html",
"css",
"resize-image",
""
] |
A coworker asked me to look at indexing on some tables because his query was running very long. Over an hour.
```
select count(1)
from databaseA.dbo.table1
inner join databaseA.dbo.table2 on (table1.key = table2.key)
inner join databaseB.dbo.table3 on (table1.key = table3.key)
```
Note the different databases. This w... | I would suspect the statistics first.
As you are no doubt aware, Join hints should be avoided in 99% of cases and used only when you have proof that they are absolutely required. | Check statistics, and indexing on the table first. Index hints can cause problems. If the data in the tables changes the optimizer will be unable to choose a more efficent plan since you have forced it to always use a hash. | Is this join hint dangerous? | [
"",
"sql",
"join",
"sql-server-2000",
"join-hints",
""
] |
i'm using this example implementation found at <http://tangentsoft.net/wskfaq/examples/basics/select-server.html>
This is doing most of what I need, handles connections without blocking and does all work in its thread (not creating a new thread for each connection as some examples do), but i'm worried since i've been ... | **Alternative library:**
You should consider using [boost asio](http://www.boost.org/doc/libs/1_37_0/doc/html/boost_asio.html). It is a cross platform networking library which simplifies many of the tasks you may have to do.
You can find the [example source code you seek here](http://www.boost.org/doc/libs/1_37_0/doc... | @Brian:
```
if ((gConnections.size() + 1) > 64) {
// For the background on this check, see
// www.tangentsoft.net/wskfaq/advanced.html#64sockets
// The +1 is to account for the listener socket.
cout << "WARNING: More than 6... | alternatives to winsock2 with example server source in c++ | [
"",
"c++",
"winsock",
""
] |
I have a List (Foo) and I want to see if it's equal to another List (foo). What is the fastest way ? | Here are the steps I would do:
1. Do an object.ReferenceEquals() if true, then return true.
2. Check the count, if not the same, return false.
3. Compare the elements one by one.
Here are some suggestions for the method:
1. Base the implementation on ICollection. This gives you the count, but doesn't restrict to spe... | From 3.5 onwards you may use a LINQ function for this:
```
List<string> l1 = new List<string> {"Hello", "World","How","Are","You"};
List<string> l2 = new List<string> {"Hello","World","How","Are","You"};
Console.WriteLine(l1.SequenceEqual(l2));
```
It also knows an overload to provide your own comparer | Fastest way to compare two lists | [
"",
"c#",
"collections",
""
] |
In the application I'm working on porting to the web, we currently dynamically access different tables at runtime from run to run, based on a "template" string that is specified. I would like to move the burden of doing that back to the database now that we are moving to SQL server, so I don't have to mess with a dynam... | ```
CREATE PROCEDURE TemplateSelector
(
@template varchar(40),
@code varchar(80)
)
AS
EXEC('SELECT * FROM ' + @template + ' WHERE ProductionCode = ' + @code)
```
This works, though it's not a UDF. | The only way to do this is with the exec command.
Also, you have to move it out to a stored proc instead of a function. Apparently functions can't execute dynamic sql. | How do I supply the FROM clause of a SELECT statement from a UDF parameter | [
"",
"sql",
"sql-server",
"user-defined-functions",
""
] |
I've got this code in a pair of button click event handlers on a C# form:
```
class frmLogin
{
private const int SHORT_HEIGHT = 120;
private const int LONG_HEIGHT = 220;
private EventHandler ExpandHandler;
private EventHandler ShrinkHandler;
public frmLogin()
{
InitializeComponent();
... | My guess: The DPI or system font size is different on that machine and your form's AutoScaleMode is either "Font" or "Dpi", making your form's MinimumSize or MaximumSize prevent the change. | Check the display mode for the laptop, and in particular check the aspect-ratio setting. Sometimes laptops do weird things to facilitate the wide, short screen. | C# - cannot set form.height | [
"",
"c#",
"winforms",
".net-2.0",
""
] |
I wish to print a `Stack<Integer>` object as nicely as the Eclipse debugger does (i.e. `[1,2,3...]`) but printing it with `out = "output:" + stack` doesn't return this nice result.
Just to clarify, I'm talking about Java's built-in collection so I can't override its `toString()`.
How can I get a nice printable versio... | You could convert it to an array and then print that out with `Arrays.toString(Object[])`:
```
System.out.println(Arrays.toString(stack.toArray()));
``` | ```
String.join(",", yourIterable);
```
(Java 8) | Printing Java Collections Nicely (toString Doesn't Return Pretty Output) | [
"",
"java",
"debugging",
"pretty-print",
""
] |
> **Possible Duplicates:**
> [C++0X when?](https://stackoverflow.com/questions/226061/c0x-when)
> [When will C++0x be finished?](https://stackoverflow.com/questions/5436139/when-will-c0x-be-finished)
When will [C++0x](http://en.wikipedia.org/wiki/C%2B%2B0x) be released? Anyone here know anything? | **Edit**: We have a new standard now : <http://herbsutter.com/2011/08/12/we-have-an-international-standard-c0x-is-unanimously-approved/>
---
**Edit**: The FDIS is done, so officially it should be released in few months. See : <http://herbsutter.com/2011/03/25/we-have-fdis-trip-report-march-2011-c-standards-meeting/>
... | The deadline is **2009**. | When will C++0x be released? | [
"",
"c++",
"c++11",
""
] |
Hi i'v look through the WMI class... but none can help me in getting the partition table information... now i'm having a project which is to display the USB thumbdrive's .MBR how should i go about it? really puzzle... Any help and guide will be very much appreciated!
p.s. the code can only be written in C#
**Edit**
... | If you're prepared to parse the raw information yourself, you can use P/Invoke to call CreateFile. If your user account has enough mojo, you can open the raw disk device by passing it a string, something like `"\\.\PHYSICALDRIVE0"`. See the documentation for CreateFile for more details. | If you want you can use WMI to get information about any drive. To do this you need to query the corresponding WMI classes. With C# you must add these references:
```
System.Management
```
and using statements:
```
using System.Management;
```
To get disk info for which are attached to your computer you can use thi... | How should I using C# to read partition table/boot sector? | [
"",
"c#",
""
] |
At the company I work for, I have created a Error Logging class to handle errors in my ASP.net application. It is a custom class because we are not allowed to install additional software on our servers (nLog, log4net, etc).
I currently use it in two of my projects and have seen some good results from it. Right now I a... | This might not be the exact answer you are looking for, but why develop your own error logging mechanism when there are powerful tools (which you mention) that handle all these key issues for you?
I can appreciate you are not allowed to install additional software but aren't logging libraries just classes like your cu... | I once worked for an agency that would not allow installation of anything that wasn't purely my own code or their (horrid) COM objects. If you have this type of limitation, then see if you can grab the source for log4net and include in your project.
There is nothing better than log4net currently when it comes to loggi... | How much information to log from errors? | [
"",
"c#",
"asp.net",
"error-logging",
""
] |
I recently watched [this youtube tutorial](http://www.youtube.com/watch?v=hp1Y9bhail8) on the Null Object design pattern. Even though there were some errors in it: such as the NullCar that doesn't do anything creates an infinite loop, the concept was well explained. My question is, what do you do when the objects that ... | As far as I've understood it the idea is that the null object's value is as close to "nothing" as possible. That unfortunately means you have to define it yourself. As an example I personally use "" when I can't pass a null String, null object number for me is -1 (mostly because by default most database sequences start... | The objective of a Null Object is to avoid having Null references in the code. The values returned by Null Object getters depend on your domain. Zero or empty string are usually appropriate.
If we transpose the Null Object pattern to real life, what you're asking is similar to ask "*how old is nobody ?*".
Perhaps you... | Null object design pattern question | [
"",
"java",
"design-patterns",
"null-object-pattern",
""
] |
I've made a C# usercontrol with one textbox and one richtextbox.
How can I access the properties of the richtextbox from outside the usercontrol.
For example.. if i put it in a form, how can i use the Text propertie of the richtextbox???
thanks | Cleanest way is to expose the desired properties as properties of your usercontrol, e.g:
```
class MyUserControl
{
// expose the Text of the richtext control (read-only)
public string TextOfRichTextBox
{
get { return richTextBox.Text; }
}
// expose the Checked Property of a checkbox (read/write)
public... | Change the access modifier ("Modifiers") of the RichTextBox in the property grid to Public. | How to access properties of a usercontrol in C# | [
"",
"c#",
"user-controls",
"properties",
"richtextbox",
""
] |
I found several other questions on SO regarding the JavaMail API and sending mail through an SMTP server, but none of them discussed using TLS security. I'm trying to use JavaMail to send status updates to myself through my work SMTP mail server, but it requires TLS, and I can't find any examples online of how to use J... | We actually have some notification code in our product that uses TLS to send mail if it is available.
You will need to set the Java Mail properties. You only need the TLS one but you might need SSL if your SMTP server uses SSL.
```
Properties props = new Properties();
props.put("mail.smtp.starttls.enable","true");
pr... | Good post, the line
```
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
```
is mandatory if the SMTP server uses **SSL Authentication**, like the GMail SMTP server does. However if the server uses **Plaintext Authentication over TLS**, it should not be present, because Java Mail will com... | Using JavaMail with TLS | [
"",
"java",
"smtp",
"jakarta-mail",
"ssl",
""
] |
What is the easiest way to highlight the difference between two strings in PHP?
I'm thinking along the lines of the Stack Overflow edit history page, where new text is in green and removed text is in red. If there are any pre-written functions or classes available, that would be ideal. | You were able to use the PHP Horde\_Text\_Diff package.
However this package is no longer available. | Just wrote a class to compute smallest (not to be taken literally) number of edits to transform one string into another string:
<http://www.raymondhill.net/finediff/>
It has a static function to render a HTML version of the diff.
It's a first version, and likely to be improved, but it works just fine as of now, so I... | Highlight the difference between two strings in PHP | [
"",
"php",
"string",
"diff",
"word-diff",
""
] |
I have now seen 2 methods for determining if an argument has been passed to a JavaScript function. I'm wondering if one method is better than the other or if one is just bad to use?
```
function Test(argument1, argument2) {
if (Test.arguments.length == 1) argument2 = 'blah';
alert(argument2);
}
Test('... | There are several different ways to check if an argument was passed to a function. In addition to the two you mentioned in your (original) question - checking `arguments.length` or using the `||` operator to provide default values - one can also explicitly check the arguments for `undefined` via `argument2 === undefine... | If you are using jQuery, one option that is nice (especially for complicated situations) is to use [jQuery's extend method](http://api.jquery.com/jQuery.extend/).
```
function foo(options) {
default_options = {
timeout : 1000,
callback : function(){},
some_number : 50,
some_text : ... | How best to determine if an argument is not sent to the JavaScript function | [
"",
"javascript",
"arguments",
""
] |
Okay, I have this program and I don't want more than one instance of it running. So what I have right now is it grabs all instances that match it's name, and if there are more than one it quits and lets the user know it's already running in another instance.
However, there is a special case in which the new instance w... | The thing that complicates this is the fact that you want, in certain conditions, to allow a second invocation of the program to do something if another one is running. Using the named mutex will allow you to detect whether the program is already running -- it should be holding the mutex already. You will still need a ... | You can use a shared (named) mutex for this.
See the [Win32 API documentation for Mutex objects](http://msdn.microsoft.com/en-us/library/ms684266(VS.85).aspx) (I assume C# has language bindings for this). | Preventing a second instance from running except in a specific case | [
"",
"c#",
"multithreading",
"process",
""
] |
Does anyone know how to turn this string: "Smith, John R"
Into this string: "jsmith" ?
I need to lowercase everything with lower()
Find where the comma is and track it's integer location value
Get the first character after that comma and put it in front of the string
Then get the entire last name and stick it ... | Start by writing your own INSTR function - call it my\_instr for example. It will start at char 1 and loop until it finds a ','.
Then use as you would INSTR. | The best way to do this is using Oracle Regular Expressions feature, like this:
```
SELECT LOWER(regexp_replace('Smith, John R',
'(.+)(, )([A-Z])(.+)',
'\3\1', 1, 1))
FROM DUAL;
```
That says, 1) when you find the pattern of any set of characters, followed by ", ", followed by an upperc... | Oracle SQL - Parsing a name string and converting it to first initial & last name | [
"",
"sql",
"string",
"parsing",
"informix",
""
] |
Why is ++i is l-value and i++ not? | Well as another answerer pointed out already the reason why `++i` is an lvalue is to pass it to a reference.
```
int v = 0;
int const & rcv = ++v; // would work if ++v is an rvalue too
int & rv = ++v; // would not work if ++v is an rvalue
```
The reason for the second rule is to allow to initialize a reference using ... | Other people have tackled the functional difference between post and pre increment.
As far as being an **lvalue** is concerned, `i++` can't be assigned to because it doesn't refer to a variable. It refers to a calculated value.
In terms of assignment, both of the following make no sense in the same sort of way:
```
... | Why is ++i considered an l-value, but i++ is not? | [
"",
"c++",
"operators",
"increment",
"rvalue",
""
] |
I have an object in C# on which I need to execute a method on a regular basis. I would like this method to be executed only when other people are using my object, as soon as people stop using my object I would like this background operation to stop.
So here is a simple example is this (which is broken):
```
class Fis... | Here is my proposed solution to this problem:
```
class Fish : IDisposable
{
class Swimmer
{
Thread t;
WeakReference fishRef;
public ManualResetEvent terminate = new ManualResetEvent(false);
public Swimmer(Fish3 fish)
{
this.fishRef = new WeakReference(fis... | I think the IDisposable solution is the correct one.
If the users of your class don't follow the guidelines for using classes that implement IDisposable it's their fault - and you can make sure that the documentation explicitly mentions how the class should be used.
Another, much messier, option would be a "KeepAlive... | Automatically terminating non essential threads in C# | [
"",
"c#",
"multithreading",
""
] |
I have a Double which could have a value from around 0.000001 to 1,000,000,000.000
I wish to format this number as a string but conditionally depending on its size. So if it's very small I want to format it with something like:
```
String.Format("{0:.000000000}", number);
```
if it's not that small, say 0.001 then I... | Use Math.Log10 of the absolute value of the double to figure out how many 0's you need either left (if positive) or right (if negative) of the decimal place. Choose the format string based on this value. You'll need handle zero values separately.
```
string s;
double epislon = 0.0000001; // or however near zero you wa... | The first two String.Format in your question can be solved by automatically removing trailing zeros:
```
String.Format("{0:#,##0.########}", number);
```
And the last one you could solve by calling Math.Round(number,1) for values over 1000 and then use the same String.Format.
Something like:
```
String.Format("{0:#... | Formatting double as string in C# | [
"",
"c#",
".net",
"formatting",
""
] |
Hi I've got a DIV section that has only its title visible initially. What I would like to achieve is that when the visitor clicks anywhere on the area of `toggle_section` the `toggle_stuff` div toggles between visible/hidden.
```
<div id="toggle_section"
onclick="javascript: new Effect.toggle('toggle_stuff', 'sl... | The most simple solution is to **add an extra onclick handler to the link** within your DIV which stops event propagation:
```
<div id="toggle_section"
onclick="javascript: new Effect.toggle('toggle_stuff', 'slide');">
<div id="toggle_title">Some title</div>
<div id="toggle_stuff">
some content s... | in script :
```
function overlayvis(blck) {
el = document.getElementById(blck.id);
el.style.visibility = (el.style.visibility == 'visible') ? 'hidden' : 'visible';
}
```
activator link, followed by content (no reason that couldn't be else on the page):
```
<div onclick='overlayvis(showhideme)">show/hide stuff</d... | How to use javascript onclick on a DIV tag to toggle visibility of a section that contains clickable links? | [
"",
"javascript",
"css",
"prototypejs",
"scriptaculous",
""
] |
My webservice provider give me a large WSDL file, but we are going to use only a few function inside.
I believe that the large WSDL have negative impact to the application performance.
We use the webservice in client appliction, **startup time** and **memory usage** are issues.
Large WSDL means that jax-ws will takes... | In short, your answers are "No tool, but you can DIY".
I wish there are simple tool can do it because my WSDL contains too many unused function and schema of data structure.
If I can automate it, WSDL -> trimmed WSDL -> generate client stubs classes. Nothing unused will be generated, no misuse, no maintenances requir... | The size of the WSDL will have zero impact on performance... unless you are downloading it and/or parsing it for every request. And if you are doing the latter, don't. It need only be processed when the service changes, and the service should always change compatibly, with continuing support of old messages (at least f... | Working with large wsdl, can we trim it? | [
"",
"java",
"web-services",
"wsdl",
"jax-ws",
""
] |
I have a CustomAction as part of an MSI.
It MUST run as a domain account that is also a member of the local Administrators account.
It can't use the NoImpersonate flag to run the custom action as NT Authority\System as it will not then get access to network resources.
On Vista/2008 with UAC enabled if NoImpersonate ... | Answering my own question for any other poor s0d looking at this.
* You can't add a manifest to an MSI. You could add a SETUP.EXE or bootstrapper to shell the MSI and manifest that with requireAdministrator but that defeats some of the point of using an MSI.
* Adding a manifest to a CustomAction does not work as it is... | requireAdministrator in the manifest should work.
You can also use a bootloader .exe file which can use ShellExecute with "RUNAS" as the verb (you can use 7-zip to create the bootloader, or there are many other ways). | Mark MSI so it has to be run as elevated Administrator account | [
"",
"c#",
"windows-installer",
"uac",
"custom-action",
""
] |
I am trying to pass a dataString to to an ajax call using JQuery. In the call, I construct the get parameters and then send them to the php page on the receiving end. The trouble is that the data string has ampersands in them and the HTML strict validator is chocking on it.
Here is the code:
```
$(document).ready(fun... | Try putting your javascript inside a CDATA block like this:
```
<script type="text/javascript">
<![CDATA[
// content of your Javascript goes here
]]>
</script>
```
which should make it pass validation. To be extra safe you can add Javascript comments around the CDATA tags to hide them from older browsers who don't un... | "\u0026" works! | How do I escape an ampersand in a javascript string so that the page will validate strict? | [
"",
"javascript",
"jquery",
"ajax",
"w3c-validation",
""
] |
I have the following code:
```
if ($_POST['submit'] == "Next") {
foreach($_POST['info'] as $key => $value) {
echo $value;
}
}
```
How do I get the foreach function to start from the 2nd key in the array? | For reasonably small arrays, use [array\_slice](http://fr.php.net/manual/en/function.array-slice.php) to create a second one:
```
foreach(array_slice($_POST['info'],1) as $key=>$value)
{
echo $value;
}
``` | ```
foreach(array_slice($_POST['info'], 1) as $key=>$value) {
echo $value;
}
```
Alternatively if you don't want to copy the array you could just do:
```
$isFirst = true;
foreach($_POST['info'] as $key=>$value) {
if ($isFirst) {
$isFirst = false;
continue;
}
echo $value;
}
``` | How to skip the 1st key in an array loop? | [
"",
"php",
"arrays",
""
] |
If I have a string with a valid math expression such as:
```
String s = "1 + 2 * 7";
```
Is there a built in library/function in .NET that will parse and evaluate that expression for me and return the result? In this case 15. | You could add a reference to Microsoft Script Control Library (COM) and use code like this to evaluate an expression. (Also works for JScript.)
```
Dim sc As New MSScriptControl.ScriptControl()
sc.Language = "VBScript"
Dim expression As String = "1 + 2 * 7"
Dim result As Double = sc.Eval(expression)
```
**Edit** - C#... | Strange that this famous and old question has not an answer that suggests the builtin [`DataTable.Compute`](http://msdn.microsoft.com/en-us/library/system.data.datatable.compute.aspx)-"trick". Here it is.
```
double result = Convert.ToDouble(new DataTable().Compute("1 + 2 * 7", null));
```
The following arithmetic op... | Is there a string math evaluator in .NET? | [
"",
"c#",
".net",
""
] |
Following on from [this](https://stackoverflow.com/questions/371418/can-you-represent-csv-data-in-googles-protocol-buffer-format) question, what would be the best way to represent a System.Decimal object in a Protocol Buffer? | Well, protobuf-net will simply handle this for you; it runs off the properties of types, and has full support for `decimal`. Since there is no direct way of expressing `decimal` in proto, it won't (currently) generate a `decimal` property from a ".proto" file, but it would be a nice tweak to recognise some common type ... | Marc and I have very vague plans to come up with a "common PB message" library such that you can represent pretty common types (date/time and decimal springing instantly to mind) in a common way, with conversions available in .NET and Java (and anything else anyone wants to contribute).
If you're happy to stick to .NE... | What's the best way to represent System.Decimal in Protocol Buffers? | [
"",
"c#",
".net",
"floating-point",
"protocol-buffers",
""
] |
I'm trying to use the StringEscapeUtils.escapeXML() function from org.apache.commons.lang...
There are two versions of that function, one which expects (Writer, String) and one which just expects (String)....
<http://commons.apache.org/lang/api/org/apache/commons/lang/StringEscapeUtils.html#escapeXml(java.lang.String... | The error message is telling you that you are passing an Object into the method, not a String.
If you are sure that the Object is a String, then you'll need to cast it to a String first.
If this doesn't work, please post the actual code that is giving you trouble. | You should compile the java class with the specify version if you have install the more than one version of java in you system.
You should compile your file using this way.
javac -target -source
E.g H:>javac -target 1.6 -source 1.6 Testt.java
So your target and Source version is tell to the java so it will call the... | How to tell Java which StringEscapeUtils.escapeXML() to use? | [
"",
"java",
"xml",
"jsp",
""
] |
I'm reading some code in the [Ogre3D](http://www.ogre3d.org) implementation and I can't understand what a `void *` type variable means. What does a pointer to `void` mean in C++? | A pointer to void, `void*` can point to any object:
```
int a = 5;
void *p = &a;
double b = 3.14;
p = &b;
```
You can't dereference, increment or decrement that pointer, because you don't know what type you point to. The idea is that `void*` can be used for functions like `memcpy` that just copy memory blocks around... | It's just a generic pointer, used to pass data when you don't know the type. You have to cast it to the correct type in order to use it. | Pointer to void in C++? | [
"",
"c++",
"pointers",
"void",
"void-pointers",
""
] |
What is the main difference between `StringBuffer` and `StringBuilder`?
Is there any performance issues when deciding on any one of these? | [`StringBuffer`](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html) is synchronized, [`StringBuilder`](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html) is not. | [`StringBuilder`](http://docs.oracle.com/javase/9/docs/api/java/lang/StringBuilder.html) is faster than [`StringBuffer`](https://docs.oracle.com/javase/9/docs/api/java/lang/StringBuffer.html) because it's not `synchronized`.
Here's a simple benchmark test:
```
public class Main {
public static void main(String[] ... | Difference between StringBuilder and StringBuffer | [
"",
"java",
"stringbuilder",
"stringbuffer",
""
] |
In a mysqli prepared statement, a NULL gets turned into '' (in the case of a string) or 0 (in the case of an integer). I would like to store it as a true NULL. Is there any way of doing this? | It's possible to bind a true NULL value to the prepared statements (read [this](http://www.php.net/manual/en/mysqli-stmt.bind-param.php#96148)).
> You can, in fact, use mysqli\_bind\_parameter to pass a NULL value to the database. simply create a variable and store the NULL value (see the manpage for it) to the variab... | For anyone coming looking at this because they are having problems binding NULL in their `WHERE` statement, the solution is this:
There is a mysql [NULL safe operator](http://dev.mysql.com/doc/refman/5.5/en/comparison-operators.html#operator_equal-to) that must be used:
`<=>`
Example:
```
<?php
$price = NULL; // NO... | using nulls in a mysqli prepared statement | [
"",
"php",
"mysql",
"null",
"mysqli",
"prepared-statement",
""
] |
After posting [this question](https://stackoverflow.com/questions/410890/how-to-trace-a-nullpointerexception-in-a-chain-of-getters "How to trace a NullPointerException in a chain of getters?") and reading [that one](https://stackoverflow.com/questions/271526/How-to-avoid-null-statements-in-java "how to avoid null state... | A very good follow up question. I consider `null` a truly special value, and if a method may return `null` it must clearly document in the Javadoc when it does (`@return some value ..., or null if ...`). When coding I'm defensive, and assume a method may return `null` unless I'm convinced it can't (e.g., because the Ja... | You can use the [`Option`](http://functionaljava.googlecode.com/svn/artifacts/2.17/javadoc/fj/data/Option.html) type, which is very much like a list that has zero or one element. A return type of `Option<Object>` indicates that the method may return an `Object`, or it may return a special value of type `None`. This typ... | How to show if a method may return null | [
"",
"java",
"null",
"design-by-contract",
""
] |
I know of `python -c '<code>'`, but I'm wondering if there's a more elegant python equivalent to `perl -pi -e '<code>'`. I still use it quite a bit for things like find and replace in a whole directory (`perl -pi -e s/foo/bar/g *` or even `find . | xargs perl -pi -e s/foo/bar/g` for sub-directories).
I actually feel t... | The command line usage from '`python -h`' certainly strongly suggests there is no such equivalent. Perl tends to make extensive use of '`$_`' (your examples make implicit use of it), and I don't think Python supports any similar concept, thereby making Python equivalents of the Perl one-liners much harder. | An equivalent to -pi isn't that hard to write in Python.
1. Write yourself a handy module with the -p and -i features you really like. Let's call it `pypi.py`.
2. Use `python -c 'import pypi; pypi.subs("this","that")'`
You can implement the basic -p loop with the [fileinput](http://docs.python.org/library/fileinput.h... | Is there a Python equivalent to `perl -pi -e`? | [
"",
"python",
"perl",
"command-line",
"language-features",
""
] |
I need to get the image dimensions of a JPEG in C++. I'm looking for either a fairly simple way to do it or a smallish library that provides that functionality. I'm working in C++ on OpenVMS, so any external libraries may have to be adapted to compile on our systems - so please don't post me links to big, closed source... | You have this [C function](http://carnage-melon.tom7.org/stuff/jpegsize.html) which may extract the relevant data for you.
> This is a C routine but should compile fine with C++.
> Pass it a normal FILE pointer (from fopen) to the beginning of a jpeg file and two int pointers to be set with the image height and widt... | libjpeg is reasonably small, open source and available on OpenVMS. It's probably quicker to install it than to handle JPEG yourself. | Get dimensions of JPEG in C++ | [
"",
"c++",
"jpeg",
"openvms",
""
] |
I'm trying to convert an openGL [edit: "card that I drew"(?):) thx unwind]containing a lot of textures (nothing moving) into one PNG file that I can use in another part of the framework I'm working with. Is there a C++ library that does that?
thanks! | If you simply mean "take a scene rendered by OpenGL and save it as an image," then it is fairly straightforward. You need to read the scene with glReadPixels(), and then convert that data to an image format such as PNG (<http://www.opengl.org/resources/faq/technical/miscellaneous.htm>).
There are also more efficient w... | What is an "OpenGL file"? OpenGL is a graphics API, it doesn't specify any file formats. Do you mean a DDS file, or something? | openGL into png | [
"",
"c++",
"opengl",
"png",
"ldf",
""
] |
I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad.
I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, ... | [html2text](https://github.com/Alir3z4/html2text) is a Python program that does a pretty good job at this. | The best piece of code I found for extracting text without getting javascript or not wanted things :
```
from urllib.request import urlopen
from bs4 import BeautifulSoup
url = "http://news.bbc.co.uk/2/hi/health/2284783.stm"
html = urlopen(url).read()
soup = BeautifulSoup(html, features="html.parser")
# kill all scri... | Extracting text from HTML file using Python | [
"",
"python",
"html",
"text",
"html-content-extraction",
""
] |
I have a php file which I will be using as exclusively as an include. Therefore I would like to throw an error instead of executing it when it's accessed directly by typing in the URL instead of being included.
Basically I need to do a check as follows in the php file:
```
if ( $REQUEST_URL == $URL_OF_CURRENT_PAGE ) ... | The easiest way for the generic "PHP app running on an Apache server that you may or may not fully control" situation is to put your includes in a directory and deny access to that directory in your .htaccess file. To save people the trouble of Googling, if you're using Apache, put this in a file called ".htaccess" in ... | Add this to the page that you want to only be included
```
<?php
if(!defined('MyConst')) {
die('Direct access not permitted');
}
?>
```
then on the pages that include it add
```
<?php
define('MyConst', TRUE);
?>
``` | Prevent direct access to a php include file | [
"",
"php",
"include",
"include-guards",
""
] |
I see many, many sites that have URLs for individual pages such as
<http://www.mysite.com/articles/this-is-article-1>
<http://www.mysite.com/galleries/575>
And they don't redirect, they don't run slowly...
I know how to parse URL's, that's easy enough. But in my mind, that seems slow and cumbersome on a dynamic site... | Firstly, when comparing /plain/ URL rewriting at the application level to using /plain/ CGI (CGI can be PHP, ISAPI, ASP.NET, etc.) with serving static pages, serving static files will always, always win. There is simply less work. For example, in Windows and Linux (that I know of) there are even enhancements in the ker... | There are many ways you can handle the above. Generally speaking, there is always at least some form of redirection involved - although that could be at the .htaccess level rather than php. Here's a scenario:
1. Use .htaccess to redirect to your php processing script.
2. Parse the uri ($\_SERVER['REQUEST\_URI']) and a... | Question on dynamic URL parsing | [
"",
"php",
"url",
"url-parsing",
""
] |
I have a script that I'd like to continue using, but it looks like I either have to find some workaround for a bug in Python 3, or downgrade back to 2.6, and thus having to downgrade other scripts as well...
Hopefully someone here have already managed to find a workaround.
The problem is that due to the new changes i... | Direct from the Py3k docs: <http://docs.python.org/dev/py3k/library/urllib.request.html#examples>
```
import urllib.request
# Create an OpenerDirector with support for Basic HTTP Authentication...
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(realm='PDQ Application',
... | My advice would be to maintain your 2.\* branch as your production branch until you can get the 3.0 stuff sorted.
I am going to wait a while before moving over to Python 3.0. There seems a lot of people in a rush, but I just want everything sorted out, and a decent selection of third-party libraries. This may take a y... | How to download a file over http with authorization in python 3.0, working around bugs? | [
"",
"python",
"python-3.x",
"urllib",
""
] |
I've seen a number of people claim that you should specifically name each column you want in your select query.
Assuming I'm going to use all of the columns anyway, why would I not use `SELECT *`?
Even considering the question \*[SQL query - Select \* from view or Select col1, col2, … colN from view](https://stackove... | The essence of the quote of not prematurely optimizing is to go for simple and straightforward code and **then** use a profiler to point out the hot spots, which you can then optimize to be efficient.
When you use select \* you're make it impossible to profile, therefore you're not writing clear & straightforward code... | If your code depends on the columns being in a specific order, your code will break when there are changes to the table. Also, you may be fetching too much from the table when you select \*, especially if there is a binary field in the table.
Just because you are using all the columns now, it doesn't mean someone else... | What is the reason not to use select *? | [
"",
"sql",
""
] |
This particular example relates to Django in Python, but should apply to any language supporting exceptions:
```
try:
object = ModelClass.objects.get(search=value)
except DoesNotExist:
pass
if object:
# do stuff
```
The Django model class provides a simple method *get* which allows me to search for *one ... | The clue is in the name - exceptions should be exceptional.
If you always expect the item will exist then use `get`, but if you expect it not to exist a reasonable proportion of the time (i.e. it not existing is an expected result rather than an exceptional result) then I'd suggest using `filter`.
So, seeing as you i... | Believe it or not, this actually is an issue that is a bit different in each language. In Python, exceptions are regularly thrown for events that aren't exceptional by the language itself. Thus I think that the "you should only throw exceptions under exceptional circumstances" rule doesn't quite apply. I think the resu... | Avoid exceptions? | [
"",
"python",
"django",
"exception",
""
] |
every time i code a gui (in my case with GWT, never touched gui programming before), i notice that my code becomes a big mess, when the applications becomes more complex.
It's really frustrating to look over my code and get a headache of all these setters in object constructors and this messy throwing together of thes... | Martin Fowler wrote interesting article on this topic: [GUI Architectures](http://martinfowler.com/eaaDev/uiArchs.html) | When I'm coding a GUI in GWT I like to create Widgets that do just some small task. This way It becomes much clearer when you then combine those widgets in the final view. On the other hand you can get a widget mess all over. So try to balance what can go in a new widget (to be used on many places) and what in the view... | Patterns and more for clean and easy gui code | [
"",
"java",
"user-interface",
"design-patterns",
"gwt",
""
] |
I have three buttons and need to save some data. I have a idea, I have to set an ID to every button and then let the JS determinate witch button that has been pressed, like:
```
$("#mySpecifikButton").click(function()
{
....some code here...
});
```
but then Im stuck. For example I have 9 users. All they have an ID i... | From what I can see, you can use Ajax to send the value of the button that has been pressed to the php script. Search the [jQuery site](http://jquery.com) for documentation on $.get and $.post. :)
Edit: Now that I'm not on my iPod, it'll be much easier to type. :P
Here's what I mean:
```
<input type="button" value="... | As it sounds like you are making changes to the database, I would recommend using the `$.post( url, [data], [callback], [type] );` [link](http://docs.jquery.com/Ajax/jQuery.post#urldatacallbacktype). You can just post a form to the server and deal with it like you would any other form post. | jquery & php: saving some data without reload | [
"",
"php",
"jquery",
""
] |
It's been a while since I used Java in anger so please forgive me if this is silly.
I have just got started on a Java project where we are using JAXB to de-serializing an incoming XML string (from Jetty Server). The project is only using JAXB for this situation.
What are the alternatives to JAXB?
What are pros/cons... | I've found JAX-B pretty useful and actually like it better than many of the alternatives, especially if I'm starting from scratch and generating a schema from Java objects rather than Java objects from a schema.
In my experience, for whatever reason, I've found good documentation hard to come by from just Google searc... | XML Bean comes to mind (<http://xmlbeans.apache.org/>)
One of the PROS about JAXB is that it now comes bundle in with JDK6. The generate output is really tight and efficient. We are currently converting all our XML Bean implementation to use JAXB 2. The big CONS that we have seen is the lack of XSD related operations. | Java JAXB Pros/Cons and Documentation | [
"",
"java",
"documentation",
"jaxb",
""
] |
I have a simple question and wish to hear others' experiences regarding which is the best way to replicate images across multiple hosts.
I have determined that storing images in the database and then using database replication over multiple hosts would result in maximum availability.
The worry I have with the filesys... | If you store images in the database, you take an extra database hit *plus* you lose the innate caching/file serving optimizations in your web server. Apache will serve a static image much faster than PHP can manage it.
In our large app environments, we use up to 4 clusters:
* App server cluster
* Web service/data ser... | Serving the images from wherever you decide to store them is a trivial problem; I won't discuss how to solve it.
Deciding where to store them is the real decision you need to make. You need to think about what your goals are:
* Redundancy of hardware
* Lots of cheap storage
* Read-scaling
* Write-scaling
The last tw... | File / Image Replication | [
"",
"php",
"mysql",
"sql-server",
"apache",
"image",
""
] |
What is the use of anonymous classes in Java? Can we say that usage of anonymous class is one of the advantages of Java? | By an "anonymous class", I take it you mean [anonymous inner class](http://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html).
An anonymous inner class can come useful when making an instance of an object with certain "extras" such as overriding methods, without having to actually subclass a class.
I tend... | Anonymous inner classes are effectively closures, so they can be used to emulate lambda expressions or "delegates". For example, take this interface:
```
public interface F<A, B> {
B f(A a);
}
```
You can use this anonymously to create a [first-class function](http://en.wikipedia.org/wiki/First-class_function) in ... | How are anonymous inner classes used in Java? | [
"",
"java",
"anonymous-class",
"anonymous-inner-class",
""
] |
I would like to know how I can refer to a list item object if I had for example the following html list
```
<div id="subdiv_2">
<div id="subdiv_3">
<ul>
<li><a href="">Item1</a></li>
<li><a href="">Item2</a></li>
<li><a href="">Item3</a></li>
</ul>
</div>
</div>
```
How is it possible... | You could get all the children elements of `subdiv_3` that are `<li>`. Then iterate through that loop adding the functions as you go.
```
div = document.getElementById('subdiv_3');
els = div.getElementsByTagName('li');
for (var i=0, len=els.length; i<len; i++) {
alert(i); // add your functions here
}
```
Loo... | @Supernovah: You can actually assign a real function to `setTimeot()`. That rids you of the string formatting, which will stand in your way when you want to do more complex things than just setting one property.
This is the code:
```
function attachToList() {
var div = document.getElementById('menu2');
var els = ... | Refer to a html List item object properly in javascript for Event Registration | [
"",
"javascript",
"html",
"dom",
"event-handling",
"html-lists",
""
] |
After I downloaded the [Google Mail](http://mobile.google.com) and [Google Maps](http://mobile.google.com) application into my mobile phone I got an idea about a service that I want to implement.
My problem is that I never did any programming for the mobile platform and I need someone to point me out some resources fo... | Clicking [here](http://developers.sun.com/mobility/midp/articles/wtoolkit/) would be a pretty good place to start, it's where the best J2ME programmers have started before you... | Install [NetBeans with J2ME](http://www.netbeans.org/features/javame/index.html) - you can test your mobile applications on a variety of target device emulators. Easy development model - you can develop GUIs rapidly with the Visual Mobile Designer. | Java Mobile programming for a beginner, where to start? | [
"",
"java",
"mobile",
"mobile-phones",
""
] |
I want to override access to one variable in a class, but return all others normally. How do I accomplish this with `__getattribute__`?
I tried the following (which should also illustrate what I'm trying to do) but I get a recursion error:
```
class D(object):
def __init__(self):
self.test=20
self... | You get a recursion error because your attempt to access the `self.__dict__` attribute inside `__getattribute__` invokes your `__getattribute__` again. If you use `object`'s `__getattribute__` instead, it works:
```
class D(object):
def __init__(self):
self.test=20
self.test2=21
def __getattrib... | Actually, I believe you want to use the [`__getattr__`](https://docs.python.org/3/reference/datamodel.html#object.__getattr__) special method instead.
Quote from the Python docs:
> `__getattr__( self, name)`
>
> Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instanc... | How do I implement __getattribute__ without an infinite recursion error? | [
"",
"python",
"class",
"getattr",
""
] |
I'm learning about DDD, and have come across the statement that "value-objects" should be immutable. I understand that this means that the objects state should not change after it has been created. This is kind of a new way of thinking for me, but it makes sense in many cases.
Ok, so I start creating immutable value-o... | Use a builder:
```
public class Entity
{
public class Builder
{
private int _field1;
private int _field2;
private int _field3;
public Builder WithField1(int value) { _field1 = value; return this; }
public Builder WithField2(int value) { _field2 = value; return this; }
public Builde... | At the moment, you'd have to use a constructor with lots of args, or a builder. In C# 4.0 (VS2010), you can use named/optional arguments to achieve something similar to C# 3.0 object-initializers - see [here](http://marcgravell.blogspot.com/2008/11/immutability-and-optional-parameters.html). The example on the blog is:... | How to design an immutable object with complex initialization | [
"",
"c#",
"domain-driven-design",
"immutability",
""
] |
The setTimeout function always seems to give me trouble. Right now I have a function that is recursive (calls itself through setTimeout) and changes the elements height.
The function is sent two arguments: the element to be altered and that elements maximum height. The purpose of the function is to unfold the element,... | When you do this:
```
var func_call = 'slide_down(' + element + ', ' + max_height + ');';
```
you're converting element to a string, so your timeout will look like
```
slide_down("[Object]", 100);
```
which obviously won't work.
What you should be doing is creating a closure - it's a little complicated but basical... | First of all, this "Right now I have a function that is recursive (calls itself through setTimeout)" screams **[setInterval](http://www.w3schools.com/jsref/met_win_setinterval.asp)** to me if you're not varying the period.
Secondly, this is because the element reference is lost in the string concat as element.toString... | Javascript's setTimeout function not calling | [
"",
"javascript",
"settimeout",
""
] |
I am doing some TTF work for MOSA (the correlating body between all the C# operating systems). Me and Colin Burn are currently working on getting some TTF code working (less me these days :) - he made a lot of progress).
In any case, the TTF spec allows for an arbitrary amount of control points between the 'handles' a... | I did some digging and found some [algorithms](http://www.cs.technion.ac.il/~cs234326/projects/fonts/Methods.htm) for the TTF spec over at [this site over here](http://www.cs.technion.ac.il/~cs234326/projects/fonts/). | From the [Bezier article](http://en.wikipedia.org/wiki/Bezier_curves) in wikipedia, with some practical calculus knowledge, you can translate the formulas to a computer program like the following pseudo C# code listing. I'm doing it with quadratic spline, but it is easy to translate to another.
```
// Quadratic spline... | Turn a N-Ary B-Spline into a sequence of Quadratic or Cubic B-Splines | [
"",
"c#",
"algorithm",
"math",
"spline",
""
] |
After returning to an old Rails project I found none of the destroy/delete links worked and clicking cancel on the confirmation popup would still submit the link.
Example of my code is:
```
<%= link_to 'Delete', admin_user_path(@user), :confirm => 'Are you sure?', :method => :delete %>
``` | This problem occurs if you are using jQuery, and if not, then look for something like that:
In my case, I was using:
javascript\_include\_tag :all %>
And it was not working, but when I put it like:
javascript\_include\_tag :defaults %>
It worked! | Chris, Hi. I had the same problem. I deleted Firebug and the problem persisted. I read from another user that he needed to restart Firefox, that didn't work either. Some said try Safari, that didn't work either.
In the end it was a novice thing:
I have helpers to insert an icon, like edit\_icon, which return a nice i... | method: => :delete not working and :confirm option ignored | [
"",
"javascript",
"ruby-on-rails",
""
] |
I'm looking for a way in .NET (2.0, C# in particular) for source code to trigger a debugging break as if a breakpoint was set at that point, without having to remember to set a specific breakpoint there in the debugger, and without interfering with production runtime.
Our code needs to swallow exceptions in production... | You probably are after something like this:
```
if(System.Diagnostics.Debugger.IsAttached)
System.Diagnostics.Debugger.Break();
```
Of course that will still get compiled in a Release build. If you want it to behave more like the Debug object where the code simply doesn't exist in a Release build, then you could do... | I ran into a situation once where this didn't work
```
System.Diagnostics.Debugger.Break();
```
but this did
```
System.Diagnostics.Debugger.Launch();
``` | Can .NET source code hard-code a debugging breakpoint? | [
"",
"c#",
"visual-studio",
".net-2.0",
"breakpoints",
""
] |
Note: Using MySQL 4.0, which means no subqueries (at present).
I have 2 tables:
* A "user\_details" table
* A "skills" table, which has the user\_id and a "skill\_id", which maps to a predefined set of skills defined elsewhere.
The current query allows an admin to search for users by selecting skills, and the query ... | You don't need a subquery or a join.
```
SELECT user_id
FROM skills
WHERE skill_id IN (51, 52, 53, 54, 55)
GROUP BY user_id
HAVING COUNT(*) = 5;
``` | Just add more single joins.
INNER JOIN skills s ON u.id - us.userid AND skill\_id = $s1
INNER JOIN skills s ON u.id - us.userid AND skill\_id = $s2
INNER JOIN skills s ON u.id - us.userid AND skill\_id = $s3
INNER JOIN skills s ON u.id - us.userid AND skill\_id = $s4
etc.
It will be required to join to them a... | mysql: joining tables + finding records with an AND style query, rather than OR | [
"",
"mysql",
"sql",
"sql-match-all",
""
] |
Ok, all these methods of getting data in a Silverlight control are confusing me.
I've looked at ADO.Net Data Services, Web Service and Silverlight-enabled WCF services.
I'm just not sure when one is appropriate to use over another. What pros/cons do each offer?
I've built a web app, and a Silverlight control. I will ... | From the silverlight perspective, WCF is heavily constrained anyway, so most of the *usual* benefits of WCF don't apply. However, it is still a fairly nice, consistent programming model.
WCF is primarily a SOAP stack, so it is very good at presenting data as rigid operations. ADO.NET Data Services is a REST stack, and... | I know this is old, but I just wanted to add my 2 cents.
I would highly recommend using WCF; and use the WCF Service Library project over the Silverlight-enabled web service. They are both essentially the same, but the Silverlight-enabled web service changes the binding to basic instead of ws\*. It also adds an asp.ne... | Silverlight enabled WCF Service vs Web Service vs ADO.NET Data Service | [
"",
"c#",
".net",
"silverlight",
"wcf",
"web-services",
""
] |
I have a situation where I need to process large (many GB's) amounts of data as such:
1. build a large string by appending many smaller (C char\*) strings
2. trim the string
3. convert the string into a C++ const std::string for processing (read only)
4. repeat
The data in each iteration are independent.
My question... | Is it at all possible to use a C++ string in step 1? If you use `string::reserve(size_t)`, you can allocate a large enough buffer to prevent multiple heap allocations while appending the smaller strings, and then you can just use that same C++ string throughout all of the remaining steps.
See [this link](http://en.cpp... | You can't actually form a std::string without copying the data. A stringstream would probably reuse the memory from pass to pass (though I think the standard is silent on whether it actually has to), but it still wouldn't avoid the copying.
A common approach to this sort of problem is to write the code which processes... | initializing std::string from char* without copy | [
"",
"c++",
"string",
"memory-management",
"stl",
""
] |
Why must class members declared as `const` be initialized in the constructor initializer list rather than in the constructor body?
What is the difference between the two? | In C++, an object is considered fully initialised when execution enters the body of the constructor.
You said:
> "i wanted to know why const must be
> intialized in constructor initializer
> list rather than in it's body ?."
What you are missing is that **initialisation** happens in the initialisation list, and **as... | `const` and reference variables must be initialized on the line they are declared.
```
class Something
{
private:
const int m_nValue;
public:
Something()
{
m_nValue = 5;
}
};
```
would produce code equivalent to;
```
const int nValue; // error, const ... | Why must const members be initialized in the constructor initializer rather than in its body? | [
"",
"c++",
"constructor",
"initialization",
"constants",
""
] |
In using PHP's DOM classes (DOMNode, DOMEElement, etc) I have noticed that they possess truly readonly properties. For example, I can read the $nodeName property of a DOMNode, but I cannot write to it (if I do PHP throws a fatal error).
How can I create readonly properties of my own in PHP? | You can do it like this:
```
class Example {
private $__readOnly = 'hello world';
function __get($name) {
if($name === 'readOnly')
return $this->__readOnly;
user_error("Invalid property: " . __CLASS__ . "->$name");
}
function __set($name, $value) {
user_error("Can't ... | ## Since PHP 8.1 there are implemented native readonly properties
[Documentation](https://www.php.net/manual/en/language.oop5.properties.php#language.oop5.properties.readonly-properties)
You can initialize readonly property only once during the declaration of the property.
```
class Test {
public readonly string... | PHP Readonly Properties? | [
"",
"php",
"programming-languages",
""
] |
Is there an automatic way to add base classes to Linq2Sql entities?
I know I can define a partial and implement that but there has to be an automated way, right? | The LINQ-to-SQL code-generator supports this directly.
The base-class for the data-context can be set in the designer, as the `Base Class` property. Alternatively, edit the dbml directly: right click, "Edit With...", "XML Editor"
To change the base class for the entities, set the type:
```
<Database EntityBase="Some... | EDIT: [Marc's answer](https://stackoverflow.com/questions/411515/way-to-automatically-add-a-linqtosql-base-class-to-entities#411903) is clearly the right way to go in this case, but I'm leaving this answer here for posterity - it's a handy trick to know about in some cases, where you only need a partial class to change... | Way to Automatically Add a LinqToSql base class to Entities? | [
"",
"c#",
"linq-to-sql",
""
] |
I'm working on a java SE 1.5+ swing application, in conjunction with others. I'm wondering what the best way of managing string resources is. I understand the principles behind resource bundles etc. I'd like to avoid having one property file for every class that needs a string, as this seems a bit of overkill. Especial... | What makes you think you have to have a separate properties file for every class? Generally you only need a few (or just one!) properties file (per language, of course).
Just call [`ResourceBundle.getBundle()`](http://java.sun.com/javase/6/docs/api/java/util/ResourceBundle.html) with appropriate parameters - you can u... | JSR 296 Swing Application Framework has support for resource management (and it looks like will be part of Java 7). SAF aims to pre-build parts of a Swing app that many people frequently need while encapsulating best practices. You probably don't want to tie to it directly but its worth taking a look at what they do to... | Management of Java string resources | [
"",
"java",
""
] |
I need to store some data in a Django model. These data are not equal to all instances of the model.
At first I thought about subclassing the model, but I’m trying to keep the application flexible. If I use subclasses, I’ll need to create a whole class each time I need a new kind of object, and that’s no good. I’ll al... | If it's really dictionary like arbitrary data you're looking for you can probably use a two-level setup with one model that's a container and another model that's key-value pairs. You'd create an instance of the container, create each of the key-value instances, and associate the set of key-value instances with the con... | Another clean and fast solution can be found here: <https://github.com/bradjasper/django-jsonfield>
For convenience I copied the simple instructions.
**Install**
```
pip install jsonfield
```
**Usage**
```
from django.db import models
from jsonfield import JSONField
class MyModel(models.Model):
json = JSONFie... | How to store a dictionary on a Django Model? | [
"",
"python",
"django",
"django-models",
"orm",
"persistence",
""
] |
We have a Perl program to validate XML which is invoked from a Java program. It is not able to write to standard error and hanging in the print location.
Perl is writing to STDERR and a java program is reading the STDERR using getErrorStream() function. But the Perl program is hanging to write to STDERR. I suspect Jav... | getErrorStream does not *read* the error stream, it just obtains a handle to it. As it's a pipe, if you never actually read it, it will fill up and force the Perl program to block.
You need something like:
```
Inputstream errors = getErrorStream();
while (errors.read(buffer) > 0) {
SOP buffer;
}
``` | Ideally, I think that to avoid deadlock, in Java you need to spawn separate threads to read the STDERR and the STDOUT. It sounds like Perl is blocking when writing to STDERR because for one reason or another you are never reading from it in Java. | Why can't my Java program read Perl's STDERR? | [
"",
"java",
"perl",
"stderr",
""
] |
Since String implements `IEnumerable<char>`, I was expecting to see the Enumerable extension methods in Intellisense, for example, when typing the period in
```
String s = "asdf";
s.
```
I was expecting to see `.Select<char>(...)`, `.ToList<char>()`, etc.
I was then suprised to see that the extension methods **do** i... | It's by explicit design. The problem is that while String most definitely implements `IEnumerable<T>`, most people don't think of it, or more importantly use it, in that way.
String has a fairly small number of methods. Initially we did not filter extension methods off of String and the result was a lot of negative fe... | For info, this has changed in VS2010 (in beta 2, at least). It looks like this filtering has been removed (presumably it caused too much confusion), and the methods are now visible, along with the extension-method glyph. | Why doesn't VS 2008 display extension methods in Intellisense for String class | [
"",
"c#",
"visual-studio-2008",
"string",
"extension-methods",
"intellisense",
""
] |
How long do you normally test an update for Zend Framework before pushing it out into a productions project. We can break this question up into minor updates 1.6.0 -> 1.6.1 or maybe a major update 1.6.2 -> 1.7.0. Obviously you don't release it if it add bugs to your code.
Also, as with most other server software updat... | It seems like the best method would be to have a comprehensive set of tests that exercised all the functionality in your application. With a good method for testing it seems like you could push it into production pretty quickly.
Another simple thing you can do to help you make your decision would be to simply do a dif... | I'll often jump through update releases (1.7.1 -> 1.7.2) without much hesitation. When the minors roll in, it's another bag of tricks though. For example, there were a lot of changes with Zend's file upload elements, and Zend form in between 1.5, 1.6 and 1.7.
Whether or not I even move on a new release depends on what... | Zend Framework Updates? | [
"",
"php",
"zend-framework",
""
] |
As per c99 standard, size of `long long` should be minimum 64 bits. How is this implemented in a 32 bit machine (eg. addition or multiplication of 2 `long long`s). Also, What is the equivalent of `long long` in C++. | On the IA32 architecture, 64-bit integer are implemented in using two 32-bit registers (eax and edx).
There are platform specific equivalents for C++, and you can use the stdint.h header where available (boost provides you with [one](http://www.boost.org/doc/libs/1_37_0/boost/cstdint.hpp)). | The equivalent in C++ is long long as well. It's not required by the standard, but most compilers support it because it's so usefull.
How is it implemented? Most computer architectures already have built-in support for multi-word additions and subtractions. They don't do 64 bit addititions directly but use the carry f... | long long implementation in 32 bit machine | [
"",
"c++",
"c",
""
] |
I would like to stop images from loading, as in not even get a chance to download, using greasemonkey. Right now I have
```
var images = document.getElementsByTagName('img');
for (var i=0; i<images.length; i++){
images[i].src = "";
}
```
but I don't think this actually stops the images from downloading. Anyone k... | Almost all images are not downloaded. So your script almost working as is.
I've tested the following script:
```
// ==UserScript==
// @name stop downloading images
// @namespace http://stackoverflow.com/questions/387388
// @include http://flickr.com/*
// ==/UserScript==
var images = document.ge... | If you want to disable images downloading for all websites (which I guess you might not be doing) and are using firefox, why not just disable them in preferences? Go to the content tab and switch off "Load images automatically". | Removing images with Greasemonkey? | [
"",
"javascript",
"greasemonkey",
""
] |
Can anyone recommend a good application that could be used to convert VB.NET projects to C#, without having to do too much manual work?
We've used Reflector to do small libraries manually, but some of the larger projects will be too slow and complex to do this manually. | You can use Lutz Roeders Reflector (<http://www.red-gate.com/products/reflector>) which can decompile whole Assemblies into Visual Studio projects. This way you can convert from ANY .NET Langauge into one of the supported languages of this program (C#.VB.NET,MC++,Delphi,Chrome) | [Tangible Software](http://tangiblesoftwaresolutions.com/) do various converters, including VB to C#.
I've played with it a little bit as they're kind enough to give me a copy for free, but I can't say I've stress-tested it. When I've used it it's been fine though - certainly worth a try. | Convert VB.NET --> C# Projects | [
"",
"c#",
".net",
"vb.net",
""
] |
I have a "fat" GUI that it getting fairly complex, and I would like to add links from a place to an other, and add back/forward buttons to ease navigation. It seems to me that this would be easier if my application was addressable: each composite could have its URI, and links would use that URI.
Are there design patte... | In Swing, you might use a [CardLayout](http://java.sun.com/javase/6/docs/api/java/awt/CardLayout.html). You can have each "page" be a card, and the name of the card (chosen when adding cards to the layout) would be equivalent to the URI you want.
Example:
```
String PAGE_1_KEY = "page 1";
String PAGE_2_KEY = "page 2"... | My last approach included global manager and registration of links. Each part of UI was able to name yourself uniquely and register. The global manager knows about each one and then use some dirty work to bring this part visible. The back/forward navigation was made by special undo/redo manager. Each "display" was able... | How do you make a Swing/JFace/SWT GUI addressable? | [
"",
"java",
"user-interface",
"design-patterns",
"swing",
""
] |
is there a way to make the datatextfield property of a dropdownlist in asp.net via c# composed of more than one property of an object?
```
public class MyObject
{
public int Id { get; set; }
public string Name { get; set; }
public string FunkyValue { get; set; }
public int Zip { get; set; }
}
protected void P... | Add another property to the MyObject class and bind to that property :
```
public string DisplayValue
{
get { return string.Format("{0} ({1})", Name, Zip); }
}
```
Or if you can not modify MyObject, create a wrapper object in the presentation layer (just for displaying). This can also be done using some LINQ:
```
L... | I would recommend reading this: <http://martinfowler.com/eaaDev/PresentationModel.html>
Essentially you want to create a class that represents binding to a particular UI. So you would map your Model (My Object in your example) to a ViewModel object, and then bind the drop down list that way. It's a cool way to think a... | dropdownlist DataTextField composed from properties? | [
"",
"c#",
"asp.net",
"data-binding",
"drop-down-menu",
""
] |
This is a complex question, please consider carefully before answering.
Consider this situation. Two threads (a reader and a writer) access a single global `int`. Is this safe? Normally, I would respond without thought, yes!
However, it seems to me that Herb Sutter doesn't think so. In his articles on effective concu... | Your idea of inspecting the assembly is not good enough; the reordering can happen at the hardware level.
To answer your question "is this ever a problem on read hardware:" **Yes!** In fact I've run into that problem myself.
Is it OK to skirt the issue with uniprocessor systems or other special-case situations? I wou... | Yup - use memory barriers to prevent instruction reordering where needed. In some C++ compilers, the volatile keyword has been expanded to insert implicit memory barriers for every read and write - but this isn't a portable solution. (Likewise with the Interlocked\* win32 APIs). Vista even adds some new finer-grained I... | Multithreaded paranoia | [
"",
"c++",
"c",
"multithreading",
"hardware",
""
] |
If I would write:
```
int selectedChannels = selector.select();
Set selectedKeys = selector.selectedKeys();
if ( selectedChannels != selectedKeys.size() ) {
// Selector.select() returned because of a call to Selector.wakeup()
// so do synchronization.
}
// Continue with handling selected channels.
```
would i... | I would guess that the proposed snippet would not work at all in principle, per the contracts of `Selector#select()` and `Selector#selectedKeys()`. From [Selector](http://java.sun.com/javase/6/docs/api/java/nio/channels/Selector.html):
> * The selected-key set is the set of keys such that each key's channel was detect... | If `select()` returns zero, either it timed out or it was woken up. | How to detect a Selector.wakeup call | [
"",
"java",
"nio",
""
] |
Ok, here is my dilemma I have a database set up with about 5 tables all with the exact same data structure. The data is separated in this manner for localization purposes and to split up a total of about 4.5 million records.
A majority of the time only one table is needed and all is well. However, sometimes data is ne... | I think you're looking for the [UNION](http://dev.mysql.com/doc/refman/5.1/en/union.html) clause, a la
```
(SELECT * from us_music where `genre` = 'punk')
UNION
(SELECT * from de_music where `genre` = 'punk')
``` | It sounds like you'd be happer with a single table. The five having the same schema, and sometimes needing to be presented as if they came from one table point to putting it all in one table.
Add a new column which can be used to distinguish among the five languages (I'm assuming it's language that is different among ... | MySQL - Selecting data from multiple tables all with same structure but different data | [
"",
"sql",
"mysql",
"join",
"mysql-error-1052",
""
] |
I have a C# (2008/.NET 3.5) class library assembly that supports WPF (based on [this article](http://dotupdate.wordpress.com/2007/12/05/how-to-add-a-wpf-control-library-template-to-visual-c-express-2008/)).
I've created several windows, and am now attempting to create a common style set for them. However, as it's a ... | Try adding
```
Style={DynamicResource MyStyle}
```
You cannot use a StaticResource in this case. | This sounds like a job for theming.
1. Add a `/themes/generic.xaml` ResourceDictionary to your project.
2. Add the following to AssemblyInfo.cs: `[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]`
3. ?
4. Profit!
Any resources you add to generic will be used by all cont... | Assembly-wide / root-level styles in WPF class library | [
"",
"c#",
".net",
"wpf",
"xaml",
""
] |
Can you recommend a minimalistic python webserver that I can embedded in my Desktop Application. | How minimalistic and for what purpose?
[SimpleHTTPServer](https://docs.python.org/2/library/simplehttpserver.html) comes free as part of the standard Python libraries.
If you need more features, look into [CherryPy](http://cherrypy.org/) or (at the top end) [Twisted](http://twistedmatrix.com/trac/). | I'm becoming a big fan of the newly released [circuits](http://trac.softcircuit.com.au/circuits "circuits") library. It's a component/event framework that comes with a very nice set of packages for creating web servers & apps. Here's the simple web example from the site:
```
from circuits.lib.web import Server, Contro... | Embedded Web Server in Python? | [
"",
"python",
"simplehttpserver",
"embeddedwebserver",
""
] |
I'm a php guy, but I have to do some small project in JSP.
I'm wondering if there's an equivalent to htmlentities function (of php) in JSP. | ```
public static String stringToHTMLString(String string) {
StringBuffer sb = new StringBuffer(string.length());
// true if last char was blank
boolean lastWasBlankChar = false;
int len = string.length();
char c;
for (int i = 0; i < len; i++)
{
c = string.charAt(i);
if ... | > public static String stringToHTMLString(String string) {...
The same thing does utility from [commons-lang](http://commons.apache.org/proper/commons-lang/) library:
```
org.apache.commons.lang.StringEscapeUtils.escapeHtml
```
Just export it in custom tld - and you will get a handy method for jsp. | htmlentities equivalent in JSP? | [
"",
"java",
"jsp",
"html-entities",
""
] |
What to do when after all probing, a reportedly valid object return 'undefined' for any attribute probed? I use jQuery, `$('selector').mouseover(function() { });` Everything returns 'undefined' for `$(this)` inside the function scope. The selector is a 'area' for a map tag and I'm looking for its parent attributes. | Your question is a bit vague, so maybe you can provide more details?
As for finding out about an object and the values of its properties, there are many ways to do it, including using Firebug or some other debug tools, etc. Here is a quick and dirty function that might help get you started until you can provide more d... | Is `selector` the name of the element? If so then you should reference it as:
```
$('area#selector')
```
or
```
$('#selector')
```
otherwise it will attempt to look for the (non-existent) "selector" HTML tag and, obviously, not find it. | How to do JavaScript object introspection? | [
"",
"javascript",
"jquery",
"introspection",
""
] |
I have an datetime object that I want to remove one hour to display the corect time in a different time zone. I am using datetime.addhours(-1) with the -1 being a config value. This works in most cases except when I set the time to 12:59 AM today it displays 11:59 AM today. When it should display 11:59 PM. Is it possib... | How about using the Subtract function:
```
DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
``` | There's a method that can help you with timezones:
```
TimeZoneInfo.ConvertTime(..)
```
[Linkage](http://msdn.microsoft.com/en-us/library/system.timezoneinfo.converttime.aspx) | Update the date of a datetime object when using datetime.addhours(-1) | [
"",
"c#",
""
] |
I have an application that uses DataTables to perform grouping, filtering and aggregation of data. I want to replace datatables with my own data structures so we don't have any unnecessary overhead that we get from using datatables. So my question is if Linq can be used to perform the grouping, filtering and aggregatio... | Unless you go for simple classes (POCO etc), your own implementation is likely to have nearly as much overhead as `DataTable`. Personally, I'd look more at using tools like LINQ-to-SQL, Entity Framework, etc. Then you can use either LINQ-to-Objects against local data, or the provider-specific implementation for complex... | You'd be better off letting your database handle grouping, filtering and aggregation. DataTables are actually relatively good at this sort of thing (their bad reputation seems to come primarily from inappropriate usage), but not as good as an actual database. Moreover, without a *lot* of work on your part, I would put ... | A Better DataTable | [
"",
"c#",
"linq",
""
] |
Given a method `DoSomething` that takes a (parameterless) function and handles it in some way. Is there a better way to create the "overloads" for functions with parameters than the snippet below?
```
public static TResult DoSomething<TResult>(Func<TResult> func)
{
//call func() and do something else
}
public sta... | EDIT: As noted in comments, this is partial application rather than currying. I wrote a [blog post on my understanding of the difference](http://codeblog.jonskeet.uk/2012/01/30/currying-vs-partial-function-application/), which folks may find interesting.
Well, it's not particularly different - but I'd separate out the... | The @Jon Skeet answer is right, but write by hand all possibles overload is something insane, so you can use a lib like [Curryfy](https://github.com/leandromoh/Curryfy) that do this job for you. Curryfy lib particularly exposes Curry, UnCurry and ApplyPartial extension methods, with a lot of overloads. | Proper Currying in C# | [
"",
"c#",
"lambda",
"currying",
""
] |
Given a table such as:
```
CREATE TABLE dbo.MyTestData (testdata varchar(50) NOT NULL)
ALTER TABLE dbo.MyTestData WITH NOCHECK ADD CONSTRAINT [PK_MyTestData] PRIMARY KEY CLUSTERED (testdata)
```
And given that we want a unique list of 'testdata' when we are done gathering items to be added from a list of external ... | I always do it in one statement:
```
INSERT INTO dbo.MyTestData (testdata ) VALUES (@ptestdata)
WHERE NOT EXISTS(SELECT 1 FROM dbo.MyTestData WHERE testdata=@ptestdata)
``` | Your check for errors (i.e. "IF NOT EXISTS ...") may or may not work, because there's a potential race condition (if another transaction inserts the record after your IF NOT EXISTS statement but before your INSERT statement).
Therefore, whether or not you check before, you ought to code your INSERT statement as if it ... | Inserting data into SQL Table with Primary Key. For dupes - allow insert error or Select first? | [
"",
"sql",
"insert",
""
] |
I am trying to write a textbox that will search on 5 DB columns and will return every result of a given search, ex. "Red" would return: red ball, Red Williams, etc. Any examples or similar things people have tried. My example code for the search.
Thanks.
```
ItemMasterDataContext db = new ItemMasterDataContext();... | You can do something like this (syntax may be off )
```
using(var db = new ItemMasterDataContext())
{
var s = txtSearch.Text.Trim();
var result = from p in db.ITMSTs select p;
if( result.Any(p=>p.IMITD1.Contains(s))
lv.DataSource = result.Where(p=>p.IMITD1.Contains(s))
else if ( result.Any(p=... | "q" in your example will be an `IQueryable<ITMST>`. I don't think the Datasource property of WebControl know what to do with that. try writing that line as:
```
lv.DataSource = q.ToList();
``` | LINQ Query to Return multiple results | [
"",
"c#",
"asp.net",
"linq",
"sql-server-2000",
""
] |
I've written this to try and log onto a forum (phpBB3).
```
import urllib2, re
import urllib, re
logindata = urllib.urlencode({'username': 'x', 'password': 'y'})
page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login"[logindata])
output = page.read()
```
However when I run it it comes up with;
```
Trac... | Your line
```
page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login"[logindata])
```
is semantically invalid Python. Presumably you meant
```
page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login", [logindata])
```
which has a comma separating the arguments. However, what you ACTUALLY ... | Your URL string shouldn't be
```
"http://www.woarl.com/board/ucp.php?mode=login"[logindata]
```
But
```
"http://www.woarl.com/board/ucp.php?mode=login", logindata
```
I think, because [] is for array and it require an integer. I might be wrong cause I haven't done a lot of Python. | python logging into a forum | [
"",
"python",
"authentication",
"phpbb3",
"typeerror",
""
] |
Take the method System.Windows.Forms.Control.Invoke(Delegate method)
Why does this give a compile time error:
```
string str = "woop";
Invoke(() => this.Text = str);
// Error: Cannot convert lambda expression to type 'System.Delegate'
// because it is not a delegate type
```
Yet this works fine:
```
string str = "w... | A lambda expression can either be converted to a delegate type or an expression tree - but it has to know *which* delegate type. Just knowing the signature isn't enough. For instance, suppose I have:
```
public delegate void Action1();
public delegate void Action2();
...
Delegate x = () => Console.WriteLine("hi");
`... | Tired of casting lambdas over and over?
```
public sealed class Lambda<T>
{
public static Func<T, T> Cast = x => x;
}
public class Example
{
public void Run()
{
// Declare
var c = Lambda<Func<int, string>>.Cast;
// Use
var f1 = c(x => x.ToString());
var f2 = c(x => ... | Why must a lambda expression be cast when supplied as a plain Delegate parameter | [
"",
"c#",
"c#-3.0",
"delegates",
"lambda",
""
] |
I have an associative array, ie
```
$primes = array(
2=>2,
3=>3,
5=>5,
7=>7,
11=>11,
13=>13,
17=>17,
// ...etc
);
```
then I do
```
// seek to first prime greater than 10000
reset($primes);
while(next($primes) < 10000) {}
prev($primes);
// iterate until target found
while($p = next($primes)) {
... | Don't rely on array pointers. Use iterators instead.
You can replace your outer code with:
```
foreach ($primes as $p) {
if ($p > 10000 && IsPrime(doSomeCalculationsOn($p))) {
return $p;
}
}
``` | You can "save" the state of the array:
```
$state = key($array);
```
And "restore" (not sure if there's a better method):
```
reset($array);
while(key($array) != $state)
next($array);
``` | How to store and reset a PHP array pointer? | [
"",
"php",
"arrays",
"loops",
""
] |
I need help to replace all \n (new line) caracters for
in a String, but not those \n inside [code][/code] tags.
My brain is burning, I can't solve this by my own :(
Example:
```
test test test
test test test
test
test
[code]some
test
code
[/code]
more text
```
Should be:
```
test test test<br />
test test tes... | I would suggest a (simple) parser, and not a regular expression. Something like this (bad pseudocode):
```
stack elementStack;
foreach(char in string) {
if(string-from-char == "[code]") {
elementStack.push("code");
string-from-char = "";
}
if(string-from-char == "[/code]") {
eleme... | You've tagged the question regex, but this may not be the best tool for the job.
You might be better using basic compiler building techniques (i.e. a lexer feeding a simple state machine parser).
Your lexer would identify five tokens: ("[code]", '\n', "[/code]", EOF, :all other strings:) and your state machine looks ... | Regex to replace all \n in a String, but no those inside [code] [/code] tag | [
"",
"java",
"regex",
""
] |
I'm trying to do a Data Binding in the C# code behind rather than the XAML. The XAML binding created in Expression Blend 2 to my CLR object works fine. My C# implementation only updates when the application is started after which subsequent changes to the CLR doesn't update my label content.
Here's the working XAML bi... | Your C# version does not match the XAML version. It should be possible to write a code version of your markup, though I am not familiar with ObjectDataProvider.
Try something like this:
```
Binding displayNameBinding = new Binding( "MyAccountService.Accounts[0].DisplayName" );
displayNameBinding.Source = new ObjectDa... | In the priginal code you have confused the source and path.
```
Binding displayNameBinding = new Binding();
displayNameBinding.Source = PhoneService;
displayNameBinding.Path = "MyAccountService.Accounts[0].DisplayName";
displayNameBinding.Mode = BindingMode.OneWay;
this.DisplayName.SetBinding(... | C# data binding doesn't update WPF | [
"",
"c#",
".net",
"data-binding",
"xaml",
"code-behind",
""
] |
I'm looking at building an API and was considering oauth for managing access to the api, but what I'm doing is more of a b2b system allowing businesses to access data to incorporate into their sites. I won't have any b2c at the beginning.
So oauth doesn't seem like the right tool for me, I've been looking for sources ... | What you need is just something that uniquely identifies the user... Just use a UUID or maybe a hash of a UUID.
Just make sure that this ID is passed over a secure channel, if you are passing it over an insecure channel you may need to implement some method of securing the ID similar to HTTP digest auth. | Take a look at almost any Web 2.0 site/service. They all have varying degrees of doing auth and managing API keys. Flickr, Twitter, Github, etc. | How do you manage api keys | [
"",
"php",
"api",
"oauth",
"key",
""
] |
I'm trying to loop through items of a checkbox list. If it's checked, I want to set a value. If not, I want to set another value. I was using the below, but it only gives me checked items:
```
foreach (DataRowView myRow in clbIncludes.CheckedItems)
{
MarkVehicle(myRow);
}
``` | ```
for (int i = 0; i < clbIncludes.Items.Count; i++)
if (clbIncludes.GetItemChecked(i))
// Do selected stuff
else
// Do unselected stuff
```
If the the check is in indeterminate state, this will still return true. You may want to replace
```
if (clbIncludes.GetItemChecked(i))
```
with
```
if (clbInclud... | This will give a list of selected
```
List<ListItem> items = checkboxlist.Items.Cast<ListItem>().Where(n => n.Selected).ToList();
```
This will give a list of the selected boxes' values (change Value for Text if that is wanted):
```
var values = checkboxlist.Items.Cast<ListItem>().Where(n => n.Selected).Select(n =... | How to loop through a checkboxlist and to find what's checked and not checked? | [
"",
"c#",
".net",
"checkboxlist",
""
] |
I have LINQ statement that looks like this:
```
return ( from c in customers select new ClientEntity() { Name = c.Name, ... });
```
I'd like to be able to abstract out the select into its own method so that I can have different "mapping" option. What does my method need to return?
In essence, I'd like my LINQ query ... | New answer now I've noticed that it's Linq to SQL... :)
If you look at the version of Select that works on `IQueryable<T>` it doesn't take a `Func<In, Out>`. Instead, it takes an `Expression<Func<In, Out>>`. The compiler knows how to generate such a thing from a lambda, which is why your normal code compiles.
So to h... | You might have to use chained methods instead of using LINQ syntax, and then you'll be able to pass in any of a variety of [`Expression`](http://msdn.microsoft.com/en-us/library/bb335710.aspx)`<`[`Func<TSource, TResult>`](http://msdn.microsoft.com/en-us/library/bb549151.aspx)`>` values that you specify:
```
Expression... | Encapsulating LINQ select statement | [
"",
"c#",
"linq",
"linq-to-sql",
""
] |
What is the most efficient way to convert data from nested lists to an object array (which can be used i.e. as data for JTable)?
```
List<List> table = new ArrayList<List>();
for (DATAROW rowData : entries) {
List<String> row = new ArrayList<String>();
for (String col : rowData.getDataColumn())
row.a... | ```
//defined somewhere
List<List<String>> lists = ....
String[][] array = new String[lists.size()][];
String[] blankArray = new String[0];
for(int i=0; i < lists.size(); i++) {
array[i] = lists.get(i).toArray(blankArray);
}
```
I don't know anything about JTable, but converting a list of lists to array can be do... | For `JTable` in particular, I'd suggest subclassing `AbstractTableModel` like so:
```
class MyTableModel extends AbstractTableModel {
private List<List<String>> data;
public MyTableModel(List<List<String>> data) {
this.data = data;
}
@Override
public int getRowCount() {
return data.... | Java nested list to array conversion | [
"",
"java",
"arrays",
"list",
"jtable",
""
] |
I am developing a scientific application used to perform physical simulations. The algorithms used are O(n3), so for a large set of data it takes a very long time to process. The application runs a simulation in around 17 minutes, and I have to run around 25,000 simulations. That is around one year of processing time.
... | I would very highly recommend the Java Parallel Processing Framework especially since your computations are already independant. I did a good bit of work with this undergraduate and it works very well. The work of doing the implementation is already done for you so I think this is a good way to achieve the goal in "num... | Number 3 isn't difficult to do. It requires developing two distinct applications, the client and the supervisor. The client is pretty much what you have already, an application that runs a simulation. However, it needs altering so that it connects to the supervisor using TCP/IP or whatever and requests a set of simulat... | How to create a Linux cluster for running physics simulations in java? | [
"",
"java",
"linux",
"cluster-computing",
"grid-computing",
"playstation",
""
] |
I have a list of booleans where occasionally I reset them all to false. After first writing the reset as:
```
for b in bool_list:
b = False
```
I found it doesn't work. I spent a moment scratching my head, then remembered that of course it won't work since I'm only changing a reference to the bool, not its value.... | ```
bool_list[:] = [False] * len(bool_list)
```
or
```
bool_list[:] = [False for item in bool_list]
``` | If you only have one reference to the list, the following may be easier:
```
bool_list = [False] * len(bool_list)
```
This creates a new list populated with `False` elements.
See my answer to [Python dictionary clear](https://stackoverflow.com/questions/369898/python-dictionary-clear#369925) for a similar example. | Alter elements of a list | [
"",
"python",
"coding-style",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.