Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Regarding the "standard" way to put comments inside Python source code:
```
def func():
"Func doc"
... <code>
'TODO: fix this'
#badFunc()
... <more code>
def func():
"Func doc"
... <code>
#TODO: fix this
#badFunc()
... <more code>
```
I prefer to write general comments as strings instead of prefixing #'s.
The official Python style guide doesn't mention using strings as comments (If I didn't miss it while reading it).
I like it that way mainly because I think the `#` character looks ugly with comment blocks. As far as I know these strings don't do anything.
Are there disadvantages in doing this? | Don't misuse strings (no-op statements) as comments. Docstrings, e.g. the first string in a module, class or function, are special and definitely recommended.
Note that **docstrings are documentation**, and documentation and comments are two different things!
* Documentation is important to understand *what* the code does.
* Comments explain *how* the code does it.
Documentation is read by people who *use* your code, comments by people who want to *understand* your code, e.g. to maintain it.
Using strings for commentation has the following (potential) disadvantages:
* It confuses people who don't know that the string does nothing.
* Comments and string literals are highlighted differently in code editors, so your style may make your code harder to read.
* It might affect performance and/or memory usage (if the strings are not removed during bytecode compilation, removing comments is done on the scanner level so it's definitively cheaper)
Most important for Python programmers: It is not pythonic:
> There should be one—and preferably only one—obvious way to do it.
Stick to the standards, use comments. | I think that only the first string literal in a definition (or class) is "special", i.e. gets stored by the interpreter into the defined object's (or class') [docstring](http://www.python.org/dev/peps/pep-0257/).
Any other string literals you place in the code will, at the worst, mean the interpreter will build the string value at run-time, and then just throw it away. This means that doing "comments" by littering the code with string constants might cost, performance-wise.
Of course, I have not benchmarked this, and also don't know the Python interpreter well enough to say for sure. | Python comments: # vs. strings | [
"",
"python",
""
] |
I am using visual studio 2008 SP1.
And I am creating a desktop application using MFC.
I have a library I want to link with my application. However, the library was written in WIN32 visual studio 2005.
I am been having a trouble linking:
```
fatal error LNK1104: cannot open file 'AgentLib.lib'
```
I am wondering if it is because I am using MFC 2008 and the library was written and compiled with 2005?
Many thanks for any advice, | Make sure you have added the path where your lib files are under project settings in Linker>General>Additional Library Directories | There should be no problem to do that.
You can either
* Add the directory where AgentLib.lib is to the library directories of your project.
* Add AgentLib.lib to your project (you may get a message box from Visual Studio asking for a rule, but there is no need for one, and it works) | can you create a lib or dll in VS 2005 and link with VS 2008 | [
"",
"c++",
"visual-c++-2005",
""
] |
Regardless of whether or not this is a good idea, is it possible to implement an interface where the executing function is aware of the calling object's type?
```
class A
{
private C;
public int doC(int input)
{
return C.DoSomething(input);
}
}
class B
{
private C;
public int doC(int input)
{
return C.DoSomething(input);
}
}
class C
{
public int DoSomething(int input)
{
if(GetType(CallingObject) == A)
{
return input + 1;
}
else if(GetType(CallingObject) == B)
{
return input + 2;
}
else
{
return input + 3;
}
}
}
```
It seems to me like this is a bad coding practice (because the parameters don't change, but the output would) but aside from that is it possible?
I'm in a situation were I want a few specific types to be able to call a certain function, but I can't exclude access to the function.
I thought about having a "type" parameter
```
DoSomething(int input, Type callingobject)
```
But there's no guarantee that the calling object would use GetType(this), as opposed to GetType(B) to spoof a B regardless of their own type.
Would this be as simple (relatively simple) as examining the callstack? | First, yes, it's a terrible idea to do this and breaks all kinds of solid design principles. You should definitely consider an alternative approach if that's open, like simply using polymorphism—this seems like it can be refactored to a pretty clear case of single dispatch.
Secondly, yes, it's possible. Use [`System.Diagnostics.StackTrace`](http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx) to walk the stack; then get the appropriate `StackFrame` one level up. Then determine which method was the caller by using [`GetMethod()`](http://msdn.microsoft.com/en-us/library/system.diagnostics.stackframe.getmethod.aspx) on that `StackFrame`. Note that building a stack trace is a potentially expensive operation, and it's possible for callers of your method to obscure where things are really coming from.
---
**Edit:** This comment from the OP makes it pretty clear that this could probably be a generic or polymorphic method. **@devinb**, you might want to consider making a new question that provides more detail about what you're trying to do, and we can see if it lends itself well to a good solution.
> The short version is that I would end up
> have 30 or 40 identical functions that were
> simply off by one or two lines. – devinb (12 secs ago) | As an alternative approach, have you ever considered offering up a different class based on the type of the object that is asking for the class. Say the following
```
public interface IC {
int DoSomething();
}
public static CFactory {
public IC GetC(Type requestingType) {
if ( requestingType == typeof(BadType1) ) {
return new CForBadType1();
} else if ( requestingType == typeof(OtherType) {
return new CForOtherType();
}
...
}
}
```
This would be a much cleaner approach than have each method change it's behavior based on the calling object. It would cleanly separate out the concerns to the different implementations of IC. Additionally, they could all proxy back to the real C implementation.
**EDIT** Examining the callstack
As several other people pointed out you can examine the callstack to determine what object is immediately calling the function. However this is not a foolproof way to determine if one of the objects you want to special case is calling you. For instance I could do the following to call you from SomeBadObject but make it very difficult for you to determine that I did so.
```
public class SomeBadObject {
public void CallCIndirectly(C obj) {
var ret = Helper.CallDoSomething(c);
}
}
public static class Helper {
public int CallDoSomething(C obj) {
return obj.DoSomething();
}
}
```
You could of course walk further back on the call stack. But that's even more fragile because it may be a completely legal path for `SomeBadObject` to be on the stack when a different object calls `DoSomething()`. | Determine Calling Object Type in C# | [
"",
"c#",
"types",
""
] |
I'm trying to narrow down some weirdness going on with my AJAX calls. My PHP scripts have this at the start:
```
ob_start("ob_gzhandler");
```
Works great with HTML. But are there any problems with doing it with application/json data? Any browser issues anyone is aware of? | I don't think so... I've used static files stored as gzipped JSON before, and it worked fine with AJAX.
**edit:** I checked my php script and the only thing special I did was to include these headers:
```
Content-Encoding: gzip
Content-Type: text/plain
```
If I remember right, whenever I tried to change the Content-Type to something that would indicate JSON, the client had trouble. | Some older browsers, like certain versions of IE6, screw up gzipped content, especially js content.
Just check that your server sends proper content-encoding header, that is
```
Content-Encoding: gzip
```
You should also check the headers sent by the browser for proper accept-encoding header before sending gzipped content... that is,
```
Accept-Encoding: gzip,deflate
``` | Is gzip encoding compatible with JSON? | [
"",
"php",
"json",
"encoding",
"gzip",
""
] |
This regular expression:
```
<IMG\s([^"'>]+|'[^']*'|"[^"]*")+>
```
seems to process endlessly when given this text
```
<img src=http://www.blahblahblah.com/houses/Images/
single_and_multi/roof/feb09/01_img_trrnjks_vol2009.jpg' />
```
I would expect it to - not find a match (quickly) - because there is only one single quote in the text. I have had this happen in C# and also using the Expresso regex tool. If the text is a lot shorter it seems to work. | Other commenters have mentioned the complexity being the likely cause for the perfo problem. I'd add that if you're trying to match something resembling an IMG tag, I think you want a regex more like this:
```
<IMG(\s+[a-z]+=('[^']*'|"[^"]*"|[^\s'">]+))+>
```
Of course, there are still valid HTML variations that this regex won't catch. Like a closing `/` (required in xhtml), or whitespace before the closing bracket. And it will pass some invalid cases, like unsupported attribute names. | ```
<IMG\s([^"'>]+|'[^']*'|"[^"]*")+>
```
Taking out a couple of branches, the start and the end:
```
([^"'>]+)+
```
How many ways can this match "hello"?
```
(hell)(o)
(hel)(lo)
(hel)(l)(o)
(he)(llo)
(he)(l)(lo)
(he)(l)(l)(o)
... and so on
``` | Regular expression to match img tag's url | [
"",
"c#",
".net",
"regex",
""
] |
Everywhere else in Java, anything with an index starts at 0. Is there a reason for the change here or is this just bad design? | Historically, databases have used 1-based indexing for bound parameters. This probably reflects the origins of relational databases in set theory and mathematics, which index elements starting with one, and use zero to represent a null or empty set.
In shell scripts and regular expressions, the zero index usually means something "special". For example, in the case of shell scripts, the zeroth "argument" is actually the command that was invoked.
The choice for JDBC was deliberate but, ultimately, probably causes more confusion and difficulty than it solves. | This was part of a plot by the original language designers to weed out the weak. In the original spec, arrays were numbered from -1, and lists with 1 element returned length =0.
Today, only the java Calendar API remains from this diabolical plot. | In JDBC, why do parameter indexes for prepared statements begin at 1 instead of 0? | [
"",
"java",
"jdbc",
"indexing",
"prepared-statement",
""
] |
[Binary tree http://img9.imageshack.us/img9/9981/binarytree.jpg](http://img9.imageshack.us/img9/9981/binarytree.jpg)
What would be the best way to serialize a given binary tree and inturn evaluate a unique id for each serialized binary tree?
For example, I need to serialize the sub-tree (2,7,(5,6,11)) and generate a unique id '**x**' representing that sub-tree so that whenever I come across a similar sub-tree (2,7,(5,6,11)) it would serialize to the same value '**x**' and hence I can deduce that I've found a match.
Here we assume that each node has properties that are unique. In the above example, it would be the numbers assigned to each node and hence they would always generate the same ids for similar sub-trees. I'm trying to do this in C++.
Do algorithms already exist to perform such serialized tree matching? | Do you want to to be able match any arbitrary part of the tree or a subtree running upto some leaf node(s)? IIUC, you are looking at suffix matching.
You can also look at Compact Directed Acyclic Word Graph for ideas. | I would make a hash value (in some Rabin-Karp fashion) based on the nodes' IDs and position in the tree, ie:
```
long h = 0
for each node in sub tree:
h ^= node.id << (node.depth % 30)
```
in pseudo code. The downside is that different subtrees may yield the same hash value. But the advantage is that it is fast to compare hash values, and when match is found you can further investige the actual sub tree for equality. | Tree matching using serialization of tree and unique id generation for each subtree | [
"",
"c++",
"binary-tree",
""
] |
```
int fn();
void whatever()
{
(void) fn();
}
```
Is there any reason for casting an unused return value to void, or am I right in thinking it's a complete waste of time? | David's [answer](https://stackoverflow.com/questions/689677/casting-unused-return-values-to-void/689688#689688) pretty much covers the motivation for this, to explicitly show other "developers" that you know this function returns but you're explicitly ignoring it.
This is a way to ensure that where necessary error codes are always handled.
I think for C++ this is probably the only place that I prefer to use C-style casts too, since using the full static cast notation just feels like overkill here. Finally, if you're reviewing a coding standard or writing one, then it's also a good idea to explicitly state that calls to overloaded operators (not using function call notation) should be exempt from this too:
```
class A {};
A operator+(A const &, A const &);
int main () {
A a;
a + a; // Not a problem
(void)operator+(a,a); // Using function call notation - so add the cast.
``` | At work we use that to acknowledge that the function has a return value but the developer has asserted that it is safe to ignore it. Since you tagged the question as C++ you should be using *static\_cast*:
```
static_cast<void>(fn());
```
As far as the compiler goes casting the return value to void has little meaning. | Why cast unused return values to void? | [
"",
"c++",
"c",
"void",
""
] |
Is there any way to get `HttpContext.Current.Request.Url.Host` and `HttpContext.Current.Request.ApplicationPath` in one call?
Something like "full application url"?
EDIT: Clarification - what I need is this the part within []:
```
http://[www.mysite.com/mywebapp]/Pages/Default.aspx
```
I ask simply out of curiosity.
EDIT 2: Thanks for all the replies, but none of them were exactly what I was looking for.
FYI, I solved the problem this way (but am still interested in knowing if there's a smoother way):
```
public string GetWebAppRoot()
{
if(HttpContext.Current.Request.ApplicationPath == "/")
return "http://" + HttpContext.Current.Request.Url.Host;
else
return "http://" + HttpContext.Current.Request.Url.Host + HttpContext.Current.Request.ApplicationPath;
}
``` | ```
public static string GetSiteRoot()
{
string port = System.Web.HttpContext.Current.Request.ServerVariables["SERVER_PORT"];
if (port == null || port == "80" || port == "443")
port = "";
else
port = ":" + port;
string protocol = System.Web.HttpContext.Current.Request.ServerVariables["SERVER_PORT_SECURE"];
if (protocol == null || protocol == "0")
protocol = "http://";
else
protocol = "https://";
string sOut = protocol + System.Web.HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + port + System.Web.HttpContext.Current.Request.ApplicationPath;
if (sOut.EndsWith("/"))
{
sOut = sOut.Substring(0, sOut.Length - 1);
}
return sOut;
}
``` | This was not working on my localhost with a port number so made minor modification:
```
private string GetWebAppRoot()
{
string host = (HttpContext.Current.Request.Url.IsDefaultPort) ?
HttpContext.Current.Request.Url.Host :
HttpContext.Current.Request.Url.Authority;
host = String.Format("{0}://{1}", HttpContext.Current.Request.Url.Scheme, host);
if (HttpContext.Current.Request.ApplicationPath == "/")
return host;
else
return host + HttpContext.Current.Request.ApplicationPath;
}
``` | Request.Url.Host and ApplicationPath in one call | [
"",
"c#",
"asp.net",
"code-behind",
"httpcontext",
""
] |
I've got an interface that two classes implement at the moment. The data for these classes is read in from an xml file.
e.g.
```
[Serializable]
public interface IMyInterface { }
[Serializable]
public class MyClass1 : IMyInterface { }
[Serializable]
public class MyClass2 : IMyInterface { }
```
I want to infer the type from the Xml, is there a way of doing that?
So for example my xml looks like this:
```
<meta type="MyClass1">
<!--- Some meta data -->
</meta>
```
I want to be able to directly serialize from xml into objects. Currently I'm manually processing the xml.
Edit: To clarify, I know how to serialize out but I can't serialize back in without knowing which type it is first. Should I read the type attribute and then serialize based on that? | If you are using XmlSerializer, you can add the [XmlIncludeAttribute](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlincludeattribute(VS.80).aspx) to specify the derived classes that can be deserialized. But the thing is that you have to add it to the **base** class:
```
[XmlInclude(typeof(DerivedClass))]
public abstract class BaseClass
{
public abstract bool Property { get; set; }
}
public class DerivedClass : BaseClass
{
public override bool Property { get; set; }
}
```
Other way would be to implement IXmlSerializable for the member that can be derived, and then have a Factory for derived classes based on an attribute (or is that what you are doing right now?) | The XML Serializer is not meant for situations like this. It's meant for serializing objects that can be mapped in to XML described by an XML Schema.
On the other hand, runtime serialization includes a SOAP Formatter that can serialize objects, including details of their .NET types. So can the NetDataContractSerializer in WCF. | Strategy for XmlSerialisation with an Interface? | [
"",
"c#",
"xml-serialization",
"interface",
""
] |
I have a code file from the boto framework pasted below, all of the print statements are mine, and the one commented out line is also mine, all else belongs to the attributed author.
My question is what is the order in which instantiations and allocations occur in python when instantiating a class? The author's code below is under the assumption that 'DefaultDomainName' will exist when an instance of the class is created (e.g. \_\_init\_\_() is called), but this does not seem to be the case, at least in my testing in python 2.5 on OS X.
In the class Manager \_\_init\_\_() method, my print statements show as 'None'. And the print statements in the global function set\_domain() further down shows 'None' prior to setting Manager.DefaultDomainName, and shows the expected value of 'test\_domain' after the assignment. But when creating an instance of Manager again after calling set\_domain(), the \_\_init\_\_() method still shows 'None'.
Can anyone help me out, and explain what is going on here. It would be greatly appreciated. Thank you.
```
# Copyright (c) 2006,2007,2008 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import boto
from boto.utils import find_class
class Manager(object):
DefaultDomainName = boto.config.get('Persist', 'default_domain', None)
def __init__(self, domain_name=None, aws_access_key_id=None, aws_secret_access_key=None, debug=0):
self.domain_name = domain_name
self.aws_access_key_id = aws_access_key_id
self.aws_secret_access_key = aws_secret_access_key
self.domain = None
self.sdb = None
self.s3 = None
if not self.domain_name:
print "1: %s" % self.DefaultDomainName
print "2: %s" % Manager.DefaultDomainName
self.domain_name = self.DefaultDomainName
#self.domain_name = 'test_domain'
if self.domain_name:
boto.log.info('No SimpleDB domain set, using default_domain: %s' % self.domain_name)
else:
boto.log.warning('No SimpleDB domain set, persistance is disabled')
if self.domain_name:
self.sdb = boto.connect_sdb(aws_access_key_id=self.aws_access_key_id,
aws_secret_access_key=self.aws_secret_access_key,
debug=debug)
self.domain = self.sdb.lookup(self.domain_name)
if not self.domain:
self.domain = self.sdb.create_domain(self.domain_name)
def get_s3_connection(self):
if not self.s3:
self.s3 = boto.connect_s3(self.aws_access_key_id, self.aws_secret_access_key)
return self.s3
def get_manager(domain_name=None, aws_access_key_id=None, aws_secret_access_key=None, debug=0):
return Manager(domain_name, aws_access_key_id, aws_secret_access_key, debug=debug)
def set_domain(domain_name):
print "3: %s" % Manager.DefaultDomainName
Manager.DefaultDomainName = domain_name
print "4: %s" % Manager.DefaultDomainName
def get_domain():
return Manager.DefaultDomainName
def revive_object_from_id(id, manager):
if not manager.domain:
return None
attrs = manager.domain.get_attributes(id, ['__module__', '__type__', '__lineage__'])
try:
cls = find_class(attrs['__module__'], attrs['__type__'])
return cls(id, manager=manager)
except ImportError:
return None
def object_lister(cls, query_lister, manager):
for item in query_lister:
if cls:
yield cls(item.name)
else:
o = revive_object_from_id(item.name, manager)
if o:
yield o
``` | **A few python notes**
When python executes the **class** block, it creates all of the "attributes" of that class as it encounters them. They are usually class variables as well as functions (methods), and the like.
So the value for "Manager.DefaultDomainName" is set when it is encountered in the class definition. This code is **only ever run once** - never again. The reason for that is that it is just "defining" the class object called "Manager".
When an object of class "Manager" is instantiated, it is an instance of the "Manager" class. (that may sound repetitive). To be perfectly clear, the value:
```
self.DefaultDomainName
```
does not exist. Following the rules of classes, python says "hmm, that does not exist on this object instance, I'll look at the class object(s)". So python actually finds the value at:
```
Manager.DefaultDomainName
# also referenced by
self.__class__.DefaultDomainName
```
All of that to exemplify the point that the class attribute "Manager.DefaultDomainName" is only created once, can only exist once, and can only hold one value at once.
---
In the example above, run the builtin function id() on each of the values:
```
print "1: %s" % id(self.DefaultDomainName)
print "2: %s" % id(Manager.DefaultDomainName)
```
You should see that they are referring to exactly the same memory location.
---
**Now, in (non)answer to the original question...** I don't know from perusing the code above. I would suggest that you try a couple of techniques to find it out:
```
# Debug with pdb. Follow every step of the process to ensure that you are
# setting valeus as you thought, and that the code you thought would be
# called is actually being called. I've had many problems like this where
# the error was in procedure, not in the actual code at hand.
import pdb; pdb.set_trace()
# check to see if id(Manager) is the same as id(self.__class__)
# in the set_domain() function:
# check to see what attributes you can see on Manager,
# and if they match the attributes on Manager and self.__class__ in __init__
```
Please update here when you figure it out. | What gahooa said. Besides that, I assume that `boto.config.get(...)` returns `None`, presumably because the `default_domain` key is not defined in the `Persist` section of your config file.
`boto.config` is defined in `boto/__init__.py` as `config = boto.pyami.config.Config()` (essentially). `boto.pyami.config.Config` is a subclass of the standard [`ConfigParser.SafeConfigParser`](http://docs.python.org/library/configparser.html), and it looks for config files in the locations specified by `boto.pyami.BotoConfigLocations`, which defaults to a list containing `/etc/boto.cfg` and `$HOME/.boto`. If you don't have a config in either of those locations, you won't have a default domain name. | How do python classes work? | [
"",
"python",
""
] |
I need to make sure that a datatype implements the IComparable interface, and I was wondering if there was anyway to make that a requirement when you create the object? | You can perhaps use generic to do this, for example:
```
public static T Create<T>() where T : IComparable<T>, new() {
return new T();
}
```
Or if you mean "when you create the type" (in code), then no; you'd just have to remember, perhaps using unit-tests to verify that you've done it.
I recommend using the typed `IComparable<T>` over `IComparable` - it makes life a lot easier (and avoids some boxing, but that is less of an issue). Finally, remember that you can use `Comparer<T>.Default` and `Comparer.Default` in code if you want to duck-type the comparable bit (like how `List<T>.Sort()` works). | For a generic class you can do:
```
public class MyType<T>
where T:IComparable<T>
``` | How do i make sure that a datatype implement an IComparable interface | [
"",
"c#",
"interface",
""
] |
I'm working with a small (4 person) development team on a C# project. I've proposed setting up a build machine which will do nightly builds and tests of the project, because I understand that this is a Good Thing. Trouble is, we don't have a whole lot of budget here, so I have to justify the expense to the powers that be. So I want to know:
- What kind of tools/licenses will I need? Right now, we use Visual Studio and Smart Assembly to build, and Perforce for source control. Will I need something else, or is there an equivalent of a cron job for running automated scripts?- What, exactly, will this get me, other than an indication of a broken build? Should I set up test projects in this solution (sln file) that will be run by these scripts, so I can have particular functions tested? We have, at the moment, two such tests, because we haven't had the time (or frankly, the experience) to make good unit tests.- What kind of hardware will I need for this?- Once a build has been finished and tested, is it a common practice to put that build up on an ftp site or have some other way for internal access? The idea is that this machine makes *the* build, and we all go to it, but can make debug builds if we have to.
- How often should we make this kind of build?- How is space managed? If we make nightly builds, should we keep around all the old builds, or start to ditch them after about a week or so?- Is there anything else I'm not seeing here?
I realize that this is a very large topic, and I'm just starting out. I couldn't find a duplicate of this question here, and if there's a book out there I should just get, please let me know.
EDIT: I finally got it to work! Hudson is completely fantastic, and FxCop is showing that some features we thought were implemented were actually incomplete. We also had to change the installer type from Old-And-Busted vdproj to New Hotness WiX.
Basically, for those who are paying attention, if you can run your build from the command line, then you can put it into hudson. Making the build run from the command line via MSBuild is a useful exercise in itself, because it forces your tools to be current. | Update: [**Jenkins**](http://jenkins-ci.org/) is the most up to date version of Hudson. Everyone should be using Jenkins now. I'll be updating the links accordingly.
[**Hudson**](https://wiki.jenkins-ci.org/display/JENKINS/Meet+Jenkins) is free and extremely easy to configure and will easily run on a VM.
Partly from an old post of mine:
We use it to
* Deploy Windows services
* Deploy web services
* Run MSTests & display as much information as any junit tests
* Keep track of low,med,high tasks
* trendgraph warnings and errors
Here are some of the built in .net stuff that Hudson supports
* [MSBuild](https://wiki.jenkins-ci.org/display/JENKINS/MSBuild+Plugin)
* [NAnt](https://wiki.jenkins-ci.org/display/JENKINS/NAnt+Plugin)
* [MSTest](https://stackoverflow.com/questions/352703/integrating-hudson-with-ms-test/512092#512092)
* [Nunit](https://wiki.jenkins-ci.org/display/JENKINS/NUnit+Plugin)
* [Team Foundation Server](https://wiki.jenkins-ci.org/display/JENKINS/Team+Foundation+Server+Plugin)
* [fxcop](https://wiki.jenkins-ci.org/display/JENKINS/Violations)
* [stylecop](https://wiki.jenkins-ci.org/display/JENKINS/Violations)
* [compiler warnings](https://wiki.jenkins-ci.org/display/JENKINS/Warnings+Plugin)
* [code tasks](https://wiki.jenkins-ci.org/display/JENKINS/Task+Scanner+Plugin)
Also, god forbid you are using visual source safe, [it supports that as well](https://wiki.jenkins-ci.org/display/JENKINS/Visual+SourceSafe+Plugin). I'd recommend you take a look at [Redsolo's article on building .net projects using Hudson](http://redsolo.blogspot.com/2008/04/guide-to-building-net-projects-using.html)
**Your questions**
* **Q**: What kind of tools/licenses will I need? Right now, we use Visual Studio and Smart Assembly to build, and Perforce for source control. Will I need something else, or is there an equivalent of a cron job for running automated scripts?
* **A:** I just installed visual studio on a fresh copy of a VM running a fresh, patched, install of a windows server OS. So you'd need the licenses to handle that. Hudson will install itself as a windows service and run on port 8080 and you will configure how often you want it to scan your code repository for updated code, or you can tell it to build at a certain time. All configurable through the browser.
* **Q:** What, exactly, will this get me, other than an indication of a broken build? Should I set up test projects in this solution (sln file) that will be run by these scripts, so I can have particular functions tested? We have, at the moment, two such tests, because we haven't had the time (or frankly, the experience) to make good unit tests.
**A:** You will get an email on the first time a build fails, or becomes unstable. A build is unstable if a unit test fails or it can be marked unstable through any number of criteria that you set. When a unit test or build fails you will be emailed and it will tell you where, why and how it failed. With my configuration, we get:
+ list of all commits since the last working build
+ commit notes of those commits
+ list of files changed in the commits
+ console output from the build itself, showing the error or test failure
* **Q:** What kind of hardware will I need for this?
**A:** A VM will suffice
* **Q:** Once a build has been finished and tested, is it a common practice to put that build up on an ftp site or have some other way for internal access? The idea is that this machine makes the build, and we all go to it, but can make debug builds if we have to.
**A:** Hudson can do whatever you want with it, that includes ID'ing it via the md5 hash, uploading it, copying it, archiving it, etc. It does this automatically and provides you with a long running history of build artifacts.
* **Q:** How often should we make this kind of build?
**A:** We have ours poll SVN every hour, looking for code changes, then running a build. Nightly is ok, but somewhat worthless IMO since what you've worked on yesterday wont be fresh in your mind in the morning when you get in.
* **Q:** How is space managed? If we make nightly builds, should we keep around all the old builds, or start to ditch them after about a week or so?
**A:** Thats up to you, after so long I move our build artifacts to long term storage or delete them, but all the data which is stored in text files / xml files I keep around, this lets me store the changelog, trend graphs, etc on the server with verrrry little space consumed. Also you can set Hudson up to only keep artifacts from a trailing # of builds
* **Q:** Is there anything else I'm not seeing here?
**A:** No, Go get Hudson right now, you wont be disappointed! | We've had great luck with the following combo:
1. Visual Studio (specifically, using the MSBuild.exe command line tool and passing it our solution files. removes the need for msbuild scripts)
2. [NAnt](http://nant.sourceforge.net/) (like the XML syntax/task library better than MSBuild. Also has options for P4 src control operations)
3. [CruiseControl.net](http://confluence.public.thoughtworks.org/display/CCNET/Welcome+to+CruiseControl.NET) - built in web dashboard for monitoring/starting builds.
CCNet has built in notifiers to send emails when builds succeed/fail
On justification: This takes the load off developers doing manual builds and does a lot to take human error out of the equation. It is very hard to quantify this effect, but once you do it you will never go back. Having a repeatable process to build and release software is paramount. I'm sure you've been places where they build the software by hand and it gets out in the wild, only to have your build guy say "Oops, I must have forgotten to include that new DLL!"
On hardware: as powerful as you can get. More power/memory = faster build times. If you can afford it you'll never regret getting a top-notch build machine, no matter how small the group.
On space: Helps to have plenty of hard disk space. You can craft your NAnt scripts to delete intermediate files every time a build starts, so the real issue is keeping log histories and old application installers. We have software that monitors disk space and sends alerts. Then we clean up the drive manually. Usually needs to be done every 3-4 months.
On build notifications: This is built in to CCNet, but if you are going to add automated testing as an additional step then build this into the project from the get-go. It is extremely hard to back fit tests once a project gets large. There is tons of info on test frameworks out there (probably a ton of info on SO as well), so I'll defer on naming any specific tools. | How and why do I set up a C# build machine? | [
"",
"c#",
"build",
"continuous-integration",
"build-automation",
"hudson",
""
] |
I'm trying to do something like this:
```
time() + timedelta(hours=1)
```
however, [Python doesn't allow it](http://bugs.python.org/issue1487389), apparently for good reason.
Does anyone have a simple work around?
### Related:
* [What is the standard way to add N seconds to datetime.time in Python?](https://stackoverflow.com/questions/100210/python-easy-way-to-add-n-seconds-to-a-datetime-time) | The solution is in [the link that you provided](http://bugs.python.org/issue1487389) in your question:
```
datetime.combine(date.today(), time()) + timedelta(hours=1)
```
Full example:
```
from datetime import date, datetime, time, timedelta
dt = datetime.combine(date.today(), time(23, 55)) + timedelta(minutes=30)
print dt.time()
```
Output:
```
00:25:00
``` | If it's worth adding another file / dependency to your project, I've just written a tiny little class that extends `datetime.time` with the ability to do arithmetic. If you go past midnight, it just wraps around:
```
>>> from nptime import nptime
>>> from datetime import timedelta
>>> afternoon = nptime(12, 24) + timedelta(days=1, minutes=36)
>>> afternoon
nptime(13, 0)
>>> str(afternoon)
'13:00:00'
```
It's available from PyPi as `nptime` ("non-pedantic time"), or on GitHub: <https://github.com/tgs/nptime>
The documentation is at <http://tgs.github.io/nptime/> | python time + timedelta equivalent | [
"",
"python",
""
] |
I just recently changed my IDE to MS Visual Studio 2005 coming from MSVC++ 6, and I've gotten a lot of deprecation warnings. Rather than ignore the warning, I started to change them to the \_s equivalents. However, I then found out that these were microsoft-only implementations.
I read somewhere that they were pushing for these to become part of the standard. Is it?
Is it a good idea to use these \_s functions? Or should I use something else?
Thanks. | The `*_s()` functions are not part of the C standard, but there is a pending 'Technical Report' proposing that they be added (I'm not sure if the routines in the TR are exactly the same as Microsoft's or if they're just similar).
TR 24731-1: Extensions to the C Library Part I: Bounds-checking interfaces:
* <http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1225.pdf>
If you want to continue to use the old functions you can keep the deprecation warnings quiet by defining the macro `_CRT_SECURE_NO_WARNINGS` (was `_CRT_SECURE_NO_DEPRECATE` which might still be supported). | You upgraded your IDE and also upgraded your Microsoft libraries. Frankly you can continue to use your old libraries as they continue to be kept (for backwards compatibility) although Microsoft has said that they are going to actually start taking out some of these older functions. I would say that if you're developing forward then you can use the newer functions; if you're developing backwards (or not worrying what the version is) then you might want to use the older functions. | Microsoft _s functions, are they part of the C++ standard now? | [
"",
"c++",
"standards",
""
] |
I'm working on an application in ASP.NET, and was wondering specifically how I could implement a `Password Reset` function if I wanted to roll my own.
Specifically, I have the following questions:
* What is a good way of generating a Unique ID that is hard to crack?
* Should there be a timer attached to it? If so, how long should it be?
* Should I record the IP address? Does it even matter?
* What information should I ask for under the "Password Reset" screen ? Just Email address? Or maybe email address plus some piece of information that they 'know'? (Favorite team, puppy's name, etc)
Are there any other considerations I need to be aware of?
> **NB**: [Other questions](https://stackoverflow.com/questions/522967/forgot-password-what-is-the-best-method-of-implementing-a-forgot-password-functi) have [glossed over](https://stackoverflow.com/questions/270485/password-management-best-practices-soup-to-nuts-not-just-storage-or-generation) technical implementation entirely. Indeed the accepted answer glosses over the gory details. I hope that this question and subsequent answers will go into the gory details, and I hope by phrasing this question much more narrowly that the answers are less 'fluff' and more 'gore'.
**Edit**: Answers that also go into how such a table would be modeled and handled in SQL Server or any ASP.NET MVC links to an answer would be appreciated. | Lots of good answers here, I wont bother repeating it all...
Except for one issue, which is repeated by almost every answer here, even though its wrong:
> Guids are (realistically) unique and statistically impossible to guess.
This is not true, GUIDs are very weak identifiers, and should **NOT** be used to allow access to a user's account.
If you examine the structure, you get a total of 128 bits at most... which is not considered a lot nowadays.
Out of which the first half is typical invariant (for the generating system), and half of whats left is time-dependant (or something else similar).
All in all, its a very weak and easily bruteforced mechanism.
So don't use that!
Instead, simply use a cryptographically strong random number generator (`System.Security.Cryptography.RNGCryptoServiceProvider`), and get at least 256 bits of raw entropy.
All the rest, as the numerous other answers provided. | EDIT 2012/05/22: As a follow-up to this popular answer, I no longer use GUIDs myself in this procedure. Like the other popular answer, I now use my own hashing algorithm to generate the key to send in the URL. This has the advantage of being shorter as well. Look into System.Security.Cryptography to generate them, which I usually use a SALT as well.
## First, do not immediately reset the user's password.
First, do not immediately reset the user's password when they request it. This is a security breach as someone could guess email addresses (i.e. your email address at the company) and reset passwords at whim. Best practices these days usually include a "confirmation" link sent to the user's email address, confirming they want to reset it. This link is where you want to send the unique key link. I send mine with a link like: `example.com/User/PasswordReset/xjdk2ms92`
Yes, set a timeout on the link and store the key and timeout on your backend (and salt if you are using one). Timeouts of 3 days is the norm, and make sure to notify the user of 3 days at the web level when they request to reset.
## Use a unique hash key
My previous answer said to use a GUID. I'm now editing this to advise everyone to use a randomly generated hash, e.g. using the `RNGCryptoServiceProvider`. And, make sure to eliminate any "real words" from the hash. I recall a special 6am phone call of where a woman received a certain "c" word in her "suppose to be random" hashed key that a developer did. Doh!
## Entire procedure
* User clicks "reset" password.
* User is asked for an email.
* User enters email and clicks send. Do not confirm or deny the email as this is bad practice as well. Simply say, "We have sent a password reset request if the email is verified." or something cryptic alike.
* You create a hash from the `RNGCryptoServiceProvider`, store it as a separate entity in an `ut_UserPasswordRequests` table and link back to the user. So this so you can track old requests and inform the user that older links has expired.
* Send the link to the email.
User gets the link, like `http://example.com/User/PasswordReset/xjdk2ms92`, and clicks it.
If the link is verified, you ask for a new password. Simple, and the user gets to set their own password. Or, set your own cryptic password here and inform them of their new password here (and email it to them). | How to Implement Password Resets? | [
"",
"c#",
"asp.net",
"asp.net-mvc",
"security",
""
] |
I'd like to use Hibernate's criteria api to formulate a particular query that joins two entities. Let's say I have two entities, Pet and Owner with a owner having many pets, but crucially that association is not mapped in the Java annotations or xml.
With hql, I could select owners that have a pet called 'fido' by specifying the join in the query (rather than adding a set of pets to the owner class).
Can the same be done using hibernate criteria? If so how?
Thanks,
J | My understanding is that if you do this using HQL, you are creating a Cartesian join with a filter, rather than an inner join. Criteria queries do not support doing this. | This is indeed possible with criteria:
```
DetachedCriteria ownerCriteria = DetachedCriteria.forClass(Owner.class);
ownerCriteria.setProjection(Property.forName("id"));
ownerCriteria.add(Restrictions.eq("ownername", "bob"));
Criteria criteria = getSession().createCriteria(Pet.class);
criteria.add(Property.forName("ownerId").in(ownerCriteria));
```
**Update**: This actually performs a sub-query instead of a join but it allows you to use Criteria on two entities that do not have a hibernate relationship defined. | Hibernate criteria: Joining table without a mapped association | [
"",
"java",
"hibernate",
"hql",
"criteria",
""
] |
For example, I have a std::map with known sizeof(A) and sizeof(B), while map has N entries inside. How would you estimate its memory usage?
I'd say it's something like
```
(sizeof(A) + sizeof(B)) * N * factor
```
But what is the factor? Different formula maybe?
Maybe it's easier to ask for upper bound? | The estimate would be closer to
```
(sizeof(A) + sizeof(B) + ELEMENT_OVERHEAD) * N + CONTAINER_OVERHEAD
```
There is an overhead for each element you add, and there is also a fixed overhead for maintaining the data structure used for the data structure storing the map. This is typically a binary tree, such as a [Red-Black Tree](http://en.wikipedia.org/wiki/Red_Black_Tree). For instance, in the GCC C++ STL implementation `ELEMENT_OVERHEAD` would be `sizeof(_Rb_tree_node_base)` and `CONTAINER_OVERHEAD` would be `sizeof(_Rb_tree)`. To the above figure you should also add the overhead of memory management structures used for storing the map's elements.
It's probably easier to arrive at an estimate by measuring your code's memory consumption for various large collections. | You could use [MemTrack](http://www.almostinfinite.com/memtrack.html), by Curtis Bartley. It's a memory allocator that replaces the default one and can track memory usage down to the type of allocation.
An example of output:
```
-----------------------
Memory Usage Statistics
-----------------------
allocated type blocks bytes
-------------- ------ -----
struct FHRDocPath::IndexedRec 11031 13.7% 2756600 45.8%
class FHRDocPath 10734 13.3% 772848 12.8%
class FHRDocElemPropLst 13132 16.3% 420224 7.0%
struct FHRDocVDict::IndexedRec 3595 4.5% 370336 6.2%
struct FHRDocMDict::IndexedRec 13368 16.6% 208200 3.5%
class FHRDocObject * 36 0.0% 172836 2.9%
struct FHRDocData::IndexedRec 890 1.1% 159880 2.7%
struct FHRDocLineTable::IndexedRec 408 0.5% 152824 2.5%
struct FHRDocMList::IndexedRec 2656 3.3% 119168 2.0%
class FHRDocMList 1964 2.4% 62848 1.0%
class FHRDocVMpObj 2096 2.6% 58688 1.0%
class FHRDocProcessColor 1259 1.6% 50360 0.8%
struct FHRDocTextBlok::IndexedRec 680 0.8% 48756 0.8%
class FHRDocUString 1800 2.2% 43200 0.7%
class FHRDocGroup 684 0.8% 41040 0.7%
class FHRDocObject * (__cdecl*)(void) 36 0.0% 39928 0.7%
class FHRDocXform 516 0.6% 35088 0.6%
class FHRDocTextColumn 403 0.5% 33852 0.6%
class FHRDocTString 407 0.5% 29304 0.5%
struct FHRDocUString::IndexedRec 1800 2.2% 27904 0.5%
``` | How can i estimate memory usage of std::map? | [
"",
"c++",
"memory",
"stl",
"stdmap",
""
] |
i have a need to get an undefined $\_GET['$VARIABLE'].
so that if a link comes into item.php?changingitemstyle=10101010101010
I need to find out how to extract the name of the variable not the value.
Any ideas? | Use the [`array_keys()` function](http://docs.php.net/array_keys) to retrieve an array of the keys of an array. | figured it out
php function array\_keys | Getting the Get Variable's Name | [
"",
"php",
""
] |
We've got a large classic asp application and we consider migrating to either asp.net or php. I don't want to talk about the pros and cons of either one, but I'd rather like to know whether there are ways to avoid a complete rewrite in one shot when migrating to php. We simply can't stop maintaining the current codebase just to do a rewrite. So things have to go hand in hand.
If we'd move to asp.net, we should be able share session data among both technologies and have parts of the site replaced with new asp.net code, while other just keep on running. Is such an approach possible with php? Does anyone has got experiences with such a migration or could point me to some good readings? | The ability to share session state between ASP Classic and ASP.NET isn't an intrinsic feature of either language, though it's fairly easy to accomplish.
Microsoft provides sample code:
<http://www.google.com/search?client=safari&rls=en-us&q=share%20session%20data%20between%20ASP%20and%20ASP.NET%20pages&ie=UTF-8&oe=UTF-8>
By using Microsoft's example, you could pretty easily implement something similar in PHP. Basically you'd use the ASP Classic portion of Microsoft's code above. Then in PHP you'd write a fairly simple class to read session state from the database into an array or collection when each page is loaded. It's a little extra work in PHP, but shouldn't be more than a few extra days of coding and testing.
PHP runs pretty well on IIS6 in my limited experience and support for it is supposedly even better in IIS7. The only snag I've hit in is that a most of the PHP code out there assumes you're running on Linux/Unix... but generally this is only an issue for file-handling code (think: user image uploads) that works with local filesystem paths. Because they assume your filesystem uses / instead of \ like on Windows. Obviously fairly trivial to fix.
Good luck! | Yes; it is possible to share session data between ASP and ASP.NET pages on a single web application. We do that with our legacy code at my work.
I know it's possible to run PHP on the IIS. Not sure about sharing sessions between ASP and PHP scripts though. | Migrating a large classic ASP page to php? | [
"",
"php",
"asp.net",
"asp-classic",
"migration",
""
] |
I think every business person would like to have excel UI, however they are forced into using web applications that sometimes look like really bad excel.
Are there any frameworks that help build excel ui without VB? I dont mean framework like POI or JExcel that allows you to generate excel reports. | A combination of the two can work quite well... Excel is not great for inputting data, this is where an app (desktop or web) works better, but excel is great for dynamic reports and analyzing data.
The best approach for dynamic reports I've seen is to write add-ins that add new functions to excel (e.g. to pull in real time data). in the java space you could try [XLLoop](http://xlloop.sourceforge.net/ "XLLoop") - this allows you to expose POJO functions in excel (full disclosure: I work on this project). | I've seen many applications built using Excel. All of them were clumsy, error prone, and next to impossible to keep up-to-date.
If the end user needs an application to work like Excel for some grid calculations, then give them a tool to do so, or let them use Excel for that portion.
However using Excel / VBA exclusively to develop big Enterprise worthy applications is heading down the wrong road. It might work well for a while, but it won't be long before issues expose the weak points.
Since you ended talking about reports... yes, by all means have your application export to CSV, HTML, PDF, Excel etc. That way the user that wants to use Excel to generate pretty pie charts, and reformat/search/scan/crop the data can do so with the tool they feel comfortable with. | Using excel as UI without VB | [
"",
"java",
"excel",
"user-interface",
""
] |
I am in need of generating a random string with spaces and mixedCase.
[This](http://www.c-sharpcorner.com/UploadFile/mahesh/RandomNumber11232005010428AM/RandomNumber.aspx) is all I got so far:
```
/// <summary>
/// The Typing monkey generates random strings - can't be static 'cause it's a monkey.
/// </summary>
/// <remarks>
/// If you wait long enough it will eventually produce Shakespeare.
/// </remarks>
class TypingMonkey
{
/// <summary>
/// The Typing Monkey Generates a random string with the given length.
/// </summary>
/// <param name="size">Size of the string</param>
/// <returns>Random string</returns>
public string TypeAway(int size)
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
return builder.ToString();
}
}
```
I am getting only uppercase strings with no spaces - I believe the tweak should be pretty striaghtforward to get mixed case and spaces in the soup.
Any help greatly appreciated! | The easiest way to do this is to simply create a string with the following values:
```
private readonly string legalCharacters = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
```
Then use the RNG to access a random element in this string:
```
public string TypeAway(int size)
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch;
for (int i = 0; i < size; i++)
{
ch = legalCharacters[random.Next(0, legalCharacters.Length)];
builder.Append(ch);
}
return builder.ToString();
}
``` | You could start with an array of all the characters you'll allow
```
private static readonly char[] ALLOWED = new [] { 'a', 'b', 'c' ... '9' };
```
And then:
```
{
...
for (int i = 0; i < size; i++)
{
ch = ALLOWED[random.NextInt(0, ALLOWED.Length)];
builder.Append(ch);
}
...
return builder.ToString();
}
return builder.ToString();
```
I paraphrase, of course. I'm not certain about the syntax on random.NextInt(), but intelisense aught to help. | How to get random string with spaces and mixed case? | [
"",
"c#",
"string",
"random",
"mixed-case",
""
] |
Let's say I have a web service that allows users to insert a piece of JavaScript onto their page which, when loaded, will grab a widget from my server and insert it into their page. How might I go about doing that, and what techniques should I use?
document.write? | A step by step article on [DIY widgets - How to embed your site on another site](http://drnicwilliams.com/2006/11/21/diy-widgets/). It reproduces the technique used by Google Adsense | Depends on what your widget will do.
Simplest way may be by opening an iframe and loading the widget in it. Something like google does with adsense ads. | How do JavaScript tidbits insert remote widgets onto a page? | [
"",
"javascript",
"widget",
"document.write",
""
] |
Based on some advice I found on StackOverflow, I'm digging into Haskell. I was pleased to see that Haskell's parameterized types behave very much like C# generics. Both languages advise a single letter for the type parameter (usually), and both languages seem to follow a similiar process for substituting an actual type for the type parameter. I grokked the concept pretty quickly because of that.
Which leads to this: what are some ways in which Haskell's parameterized types differ from C# generic types? I know from learning Ruby that you can get into big trouble thinking that a concept you're familiar with from one language is the same in another language you're new to. Usually, the trouble is worse when the features actually *are* very similar ... because they're usually *not* 100% the same. So what are some of the "gotchas" I might get bitten by if I assume I understand parameterized types based on my knowledge of C# generics?
Thanks. | Here's one difference to keep in mind:
C# has subtyping, but Haskell does not, which means, for one thing, that you *know* more things by simply looking at a Haskell type.
```
id :: a -> a
```
This Haskell function takes a value of a type and returns that same value of that same type.
If you give it a `Bool`, it will return a `Bool`. Give it a `Int`, it will return a `Int`. Give it a `Person`, it will return a `Person`.
In C#, you can't be so sure. This is that 'function' in C#:
```
public T Id<T>(T x);
```
Now, because of subtyping you could call it like so:
```
var pers = Id<Person>(new Student());
```
While `pers` is of type `Person`, the argument to the `Id` function is not. In fact `pers` might have a more specific type than just `Person`. `Person` could even be an abstract type, guaranteeing that `pers` will have a more specific type.
As you can see, even with a function as simple as `id` the .NET type system already allows for a lot more than the stricter type system from `Haskell`. While that might be useful to do some programming work, it also makes it harder to reason about a program by just looking a the types of things (which is a joy to do in Haskell).
---
And a second thing, there is *ad hoc* polymorphism (aka overloading) in Haskell, via a mechanism known as 'type classes'.
```
equals :: Eq a => a -> a -> Bool
```
This function checks if two values are equal. But not just any two values, just the values that have instances for the `Eq` class. This is sort of like constraints on type parameters in C#:
```
public bool Equals<T>(T x, T y) where T : IComparable
```
There is a difference, however. For one thing, the subtyping: you could instantiate it with `Person` and call it with `Student` and `Teacher`.
But there is also a difference in what this compiles to. The C# code compiles to almost exactly what its type says. The type checker makes sure the arguments implement the proper interface, and than you're good.
Whereas the Haskell code complies to something like this:
```
equals :: EqDict -> a -> a -> Bool
```
The function gets an *extra argument*, a dictionary of all the functions it needs to do the `Eq` things. Here's how you could use this function, and what it compiles to:
```
b1 = equals 2 4 --> b1 = equals intEqFunctions 2 4
b2 = equals True False --> b2 = equals boolEqFunctions True False
```
This also shows what makes subtyping such a pain, imagine if this where possible.
```
b3 = equals someStudent someTeacher
--> b3 = equals personEqFunctions someStudent someTeacher
```
How is the `personEqFunctions` dictionary supposed to figure out if a `Student` is equal to a `Teacher`? They don't even have the same fields.
In short, while Haskell type constraints at first sight might look like .NET type constraints, they are implemented completely differently and compile to two really different things. | We can do other things with Haskell type classes too now. Googling for "generics" in Haskell opens up a whole field of higher-rank polymorphic generic programming, beyond the standard parametric polymorphism most people think of as "generics".
For example, GHC recently gained type families, enabling all sorts of interesting type programming capabilities. A very simple example is per-type data representation decisions for arbitrary polymorphic containers.
I can make a class for say, lists,
```
class Listy a where
data List a
-- this allows me to write a specific representation type for every particular 'a' I might store!
empty :: List a
cons :: a -> List a -> List a
head :: List a -> a
tail :: List a -> List a
```
I can write functions that operate on anything that instantiates List:
```
map :: (Listy a, Listy b) => (a -> b) -> List a -> List b
map f as = go as
where
go xs
| null xs = empty
| otherwise = f (head xs) `cons` go (tail xs)
```
And yet we've never given a particular representation type.
Now that is a class for a generic list. I can give particular cunning representations based on the element types. So e.g. for lists of Int, I might use an array:
```
instance Listy Int where
data List Int = UArray Int Int
...
```
So you can start doing some pretty powerful generic programming. | Contrasting C# generics with Haskell parameterized types | [
"",
"c#",
"generics",
"haskell",
"polymorphism",
"type-systems",
""
] |
I am currently trying to send a serialized object over a TCP connection as follows -
```
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(clientStream, (Object)Assembly.LoadFrom("test.dll"));
```
where clientStream is
```
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
```
This is the sending part. But can anyone tell me how do I receive this on the client side (i.e. deserialize it on the other end)? | Don't serialize the assembly. Send the assembly itself just by loading it as a file and sending those bytes to the other side.
Then, when both sides have the same code, send the object via serialization. I believe the AppDomain which deserializes the object will have to have the relevant assembly loaded (or at least available to be loaded). | You are trying to pass an in-memory representation of the assembly over the wire, not the bytes comprising the assembly file itself. Is that really what you want to do? | Transferring Assembly over TCP | [
"",
"c#",
".net",
"assemblies",
""
] |
I am trying to bind a `List<AreaField>` to a repeater. I have converted the list into an array by using the `ToArray()` method and now have a array of `AreaField[]`
Here's my class hierarchy
```
public class AreaFields
{
public List<Fields> Fields { set; get; }
}
public class Fields
{
public string Name { set; get; }
public string Value {set; get; }
}
```
In the aspx, I would like to bind it a repeater (something like this)
```
DataBinder.Eval(Container.DataItem, "MyAreaFieldName1")
```
The MyAreaFieldName1 is the value of the Name property in the AreaFieldItem class. | You may want to create a subRepeater.
```
<asp:Repeater ID="SubRepeater" runat="server" DataSource='<%# Eval("Fields") %>'>
<ItemTemplate>
<span><%# Eval("Name") %></span>
</ItemTemplate>
</asp:Repeater>
```
You can also cast your fields
```
<%# ((ArrayFields)Container.DataItem).Fields[0].Name %>
```
Finally you could do a little CSV Function and write out your fields with a function
```
<%# GetAsCsv(((ArrayFields)Container.DataItem).Fields) %>
public string GetAsCsv(IEnumerable<Fields> fields)
{
var builder = new StringBuilder();
foreach(var f in fields)
{
builder.Append(f);
builder.Append(",");
}
builder.Remove(builder.Length - 1);
return builder.ToString();
}
``` | It is surprisingly simple...
Code behind:
```
// Here's your object that you'll create a list of
private class Products
{
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public string ProductPrice { get; set; }
}
// Here you pass in the List of Products
private void BindItemsInCart(List<Products> ListOfSelectedProducts)
{
// The the LIST as the DataSource
this.rptItemsInCart.DataSource = ListOfSelectedProducts;
// Then bind the repeater
// The public properties become the columns of your repeater
this.rptItemsInCart.DataBind();
}
```
ASPX code:
```
<asp:Repeater ID="rptItemsInCart" runat="server">
<HeaderTemplate>
<table>
<thead>
<tr>
<th>Product Name</th>
<th>Product Description</th>
<th>Product Price</th>
</tr>
</thead>
<tbody>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("ProductName") %></td>
<td><%# Eval("ProductDescription")%></td>
<td><%# Eval("ProductPrice")%></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</tbody>
</table>
</FooterTemplate>
</asp:Repeater>
```
I hope this helps! | Binding a generic list to a repeater - ASP.NET | [
"",
"c#",
"asp.net",
"repeater",
""
] |
I imagine that this is a simple question, but I'm getting some strange results with my current code and I don't have the math background to fully understand why. My goal is simple, as stated in the title: I just want to find the point at some distance and angle from a center point.
My current code:
```
Point centerPoint = new Point ( 0, 0 );
Point result = new Point ( 0, 0 );
double angle = 0.5; //between 0 and 2 * PI, angle is in radians
int distance = 1000;
result.Y = centerPoint.Y + (int)Math.Round( distance * Math.Sin( angle ) );
result.X = centerPoint.X + (int)Math.Round( distance * Math.Cos( angle ) );
```
In general, this seems to work fairly reasonably, but I get problems at various spots, most notably when the angle corresponds to points in the negative x and y axis. Clearly I'm doing something wrong -- thoughts on what that is?
UPDATE: This was my mistake, this code works fine -- the few outliers that were not working were actually due to a bug in how the angle for 1.5PI was being calculated. I thought I had checked that well enough, but evidently had not. Thanks to everyone for their time, hopefully the working code above will prove helpful to someone else. | You forgot to add the center point:
```
result.Y = (int)Math.Round( centerPoint.Y + distance * Math.Sin( angle ) );
result.X = (int)Math.Round( centerPoint.X + distance * Math.Cos( angle ) );
```
The rest should be ok... (what strange results were you getting? Can you give an exact input?) | Firstly, since you're in radians it's probably beneficial to define your angle as such:
```
double angle = (Math.PI / 3); // 60 degrees...
```
The functions themselves are working fine. The rounding will only affect your answer if your distance is sufficiently small enough. Other than that, the answers should come out just fine.
If it's the rounding you're worried about, remember that by default, .NET does [banker's rounding](http://blog.troyd.net/Bankers+Rounding+Vs+Common+Rounding+In+NET.aspx), and you may want:
```
result.X = (int)Math.Round(centerPoint.X + distance * Math.Cos(angle), MidpointRounding.AwayFromZero);
result.Y = (int)Math.Round(centerPoint.Y + distance * Math.Sin(angle), MidpointRounding.AwayFromZero);
```
instead.
Additionally, in the question you want *distance X and angle Y*... I assume you're not relating that to the point `(X,Y)`, because that's completely different.
The distance formula is:
```
double distance = Math.Sqrt((centerPoint.X + result.X)^2 + (centerPoint.Y + result.Y)^2);
``` | Calculating point on a circle's circumference from angle in C#? | [
"",
"c#",
"math",
"geometry",
"angle",
""
] |
Why does list.index throw an exception, instead of using an arbitrary value (for example, `-1`)? What's the idea behind this?
To me it looks cleaner to deal with special values, rather than exceptions.
**EDIT**: I didn't realize `-1` is a potentially valid value. Nevertheless, why not something else? How about a value of None? | Because `-1` is itself a valid index. It could use a different value, such as `None`, but that wouldn't be useful, which `-1` can be in other situations (thus `str.find()`), and would amount simply to error-checking, which is exactly what exceptions are for. | Well, the special value would actually have to be **`None`**, because -1 is a valid index (meaning the last element of a list).
You can emulate this behavior by:
```
idx = l.index(x) if x in l else None
``` | Python list.index throws exception when index not found | [
"",
"python",
"indexing",
"list",
""
] |
As most of you may be following my line of questions already know, i'm trying to create a program that can serialize multiple structs to a .dat file, read them back in via loading it's serialization, edit the contents, and then re-write them to the file and so on. It's a inventory program I am trying to do and I can't get it to work for the life of me.
The file i'm loading in, is blank. My program takes like 10 seconds to even load and now I know why. It's cause the size of my vector is like 250 thousand. Oh wait... this time I ran it the size of my vector was 5,172,285. Thats a pretty big vector full of structs. There aren't any run-time or compile errors, but I am pretty sure I am doing something wrong. The file i'm loading in is completely blank too.
**Code:**
```
// Project 5.cpp : main project file.
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace System;
using namespace std;
#pragma hdrstop
int checkCommand (string line);
template<typename T>
void writeVector(ofstream &out, const vector<T> &vec);
template<typename T>
vector<T> readVector(ifstream &in);
struct InventoryItem {
string Item;
string Description;
int Quantity;
int wholesaleCost;
int retailCost;
int dateAdded;
} ;
int main(void)
{
cout << "Welcome to the Inventory Manager extreme! [Version 1.0]" << endl;
ifstream in("data.dat");
if (in.is_open()) { cout << "File \'data.dat\' has been opened successfully." << endl; } else { cout << "Error opening data.dat" << endl; return 0;}
cout << "Loading data..." << endl;
vector<InventoryItem> structList = readVector<InventoryItem>( in );
cout <<"Load complete." << endl;
while (1)
{
string line = "";
cout << "There are currently " << structList.size() << " items in memory.";
cout << endl;
cout << "Commands: " << endl;
cout << "1: Add a new record " << endl;
cout << "2: Display a record " << endl;
cout << "3: Edit a current record " << endl;
cout << "4: Exit the program " << endl;
cout << endl;
cout << "Enter a command 1-4: ";
getline(cin , line);
int rValue = checkCommand(line);
if (rValue == 1)
{
cout << "You've entered a invalid command! Try Again." << endl;
} else if (rValue == 2){
cout << "Error calling command!" << endl;
} else if (!rValue) {
break;
}
}
system("pause");
return 0;
}
int checkCommand (string line)
{
int intReturn = atoi(line.c_str());
int status = 3;
switch (intReturn)
{
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
status = 0;
break;
default:
status = 1;
break;
}
return status;
}
template<typename T>
void writeVector(ofstream &out, const vector<T> &vec)
{
out << vec.size();
for(vector<T>::const_iterator i = vec.begin(); i != vec.end(); i++)
{
out << *i;
}
}
ostream &operator<<(ostream &out, const InventoryItem &i)
{
out << i.Item << i.Description;
out << i.Quantity;
out << i.wholesaleCost << i.retailCost;
out << i.dateAdded;
return out;
}
istream &operator>>(istream &in, InventoryItem &i)
{
in >> i.Item >> i.Description;
in >> i.Quantity;
in >> i.wholesaleCost >> i.retailCost;
in >> i.dateAdded;
return in;
}
template<typename T>
vector<T> readVector(ifstream &in)
{
size_t size;
in >> size;
vector<T> vec;
vec.reserve(size);
for(unsigned int i = 0; i < size; i++)
{
T tmp;
in >> tmp;
vec.push_back(tmp);
}
return vec;
}
```
Can someone simply show me how to turn this in to a program that can actually write serialized vectors full of structs to a file, and then read them back in so I can edit them and store them back for loading later? Oh my goodness what a ride this has been!
THANK YOU for any help you can provide! | You say the file is actually empty. The first line in readVector is this:
```
in >> size;
```
What do you suppose is actually going to end up in size? Since it is empty, this will result in an error, which you aren't detecting. The variable `size` will remain uninitialised - hence you see weird values in it, since it takes whatever value happened to be in memory at that time. You can check the state of the stream by using the check:
```
if (in)
```
Treating it in boolean context tells you if an error occurred - this will also cover things like it being unable to read in a valid integer variable. I suggest you should figure out how to run your program in a debugger, you will be able to step through your code and see what the values of the variables are at a given time. | So if your file is blank and your doing:
> ```
> size_t size;
> in >> size;
>
> vector<T> vec;
> vec.reserve(size);
> ```
What do you think will happen? Size cannot be read and uses a random value | Why is the size of my vector full of structs so large when I load it's serialization in from a file? | [
"",
"c++",
"serialization",
"file",
"vector",
"struct",
""
] |
I have developed a Java swing application, then I have deployed it through a .jar package.
I run my application on my PC double-clicking over the .jar file and everything goes fine, everything goes fine from command line (dos prompt) too.
Here my problem.
I have tried to run my app on another PC:
* same OS (Windows XP)
* same JRE (1.6.0\_U13)
* but Oracle JInitiator 1.3.1.18 installed (this is the only difference with my PC)
The app works fine only from command line, but not from gui!
Double-clicking over the .jar file I get this error:
```
`Could not find the main class. program will exit!`
```
Can this error be due to some conflict between JRE and JInitiator?
Does anybody had the same trouble?
Thanks
---
edit:
executing .jar files from gui is associated to the "javaw" command | A quick description might be - jinitiator installs as a fully implemented JRE with some additional features for cached downloads when dealing with applets.
As all the JRE installers I've seen lately do, regardless of if they are new or old, they replace several entries in the registry to become the active JRE. Whatever you installed last will be run unless you provide a full path to java.exe or change the registry to re point at a different JRE.
examine:
* HKEY\_CLASSES\_ROOT\jarfile\shell\open\command
and see if the path to javaw.exe is correct. (or even included)
* HKEY\_LOCAL\_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App
Paths\java.exe and javaw.exe and javaws.exe to check the path there also. | It is probably a conflict with JInit, which changes the association between jar files and the java command used to launch them.
See this [thread](http://forums.rptools.net/viewtopic.php?p=2076&highlight=&sid=501680a0db6427ccca839676fe455ac1).
> Re-installed java and the problem has gone away. | Problem running Java application | [
"",
"jar",
"java",
""
] |
I have a standard Visual Studio (2008) application setup project, which generates an msi containing a few files. I noticed however that:
1) When the msi installs and some of the files already exist, it simply silently ignores these files. This is the behaviour that I *don't* want, because of obvious reasons.
2) When I uninstall the msi, it doesn't delete my main dll file.
How can I fix these two things? Together they make it impossible to automatically upgrade my software. | I had the exact same problem and eventually gave up. Getting it to work is a horrible, complicated process involving lots of GUIDs. You'll feel very dirty afterward (assuming you ever get it to work).
My advice is to switch to Inno Setup which is much more suited to people like you and me.
Leave .msi to people who do "corporate rollouts" instead of "installs". | Have you incremented the version number in your setup project? Incrementing the version number will also ask you to create a new product id. You should confirm this question with yes. | How can I make the msi overwrite old files? | [
"",
"c#",
".net",
"iis",
"installation",
""
] |
### Duplicate:
> [What is the use of labels in c#?](https://stackoverflow.com/questions/662577)
I was trawling through some .NET Source Code using reflector when I came across something which I see very little of on the web, which is the label syntax.
From here I can see that it raises the chance of ugly spaghetti code:
```
goto 1:
goto 2:
if(booleanProperty) goto 1:
```
Is the purpose of the label simply so you can jump back and fourth inside a function?
What model usages of the C# label would you say there is? Do you have any experience with its implementation yourself? Was it a good experience or not?
```
if (1 == 1)
goto Stage2;
Stage1:
Console.WriteLine("Stage1");
Stage2:
Console.WriteLine("Stage2");
``` | You see this in reflector most often because the programmer used a higher-level construct that was re-written behind the scenes so we now see goto/labels instead.
When considering whether to use a label as a programmer, my rule of thumb is that if you have to ask you probably shouldn't do it. | There are a very few situations - usually within autogenerated code representing a state machine - where `goto` can make life simpler. There's usually a way round it if you think hard enough, but for autogenerated code it's easier to work out a simple but less readable way of doing it than try to generate the code you'd write by hand.
Can't say I've used it myself in C#, but IIRC I did something similar when porting the Colossal Cave adventure to Java. | What is the benefit and model usage of the C# label | [
"",
"c#",
".net",
""
] |
I just want to know which is the best way to execute an external command in C++ and how can I grab the output if there is any?
**Edit**: I Guess I had to tell that I'm a newbie here in this world, so I think I'm gonna need a working example. For example I want to execute a command like:
```
ls -la
```
how do I do that? | Use the [`popen`](http://opengroup.org/onlinepubs/007908775/xsh/popen.html) function.
Example (not complete, production quality code, no error handling):
```
FILE* file = popen("ls", "r");
// use fscanf to read:
char buffer[100];
fscanf(file, "%100s", buffer);
pclose(file);
``` | An example:
```
#include <stdio.h>
int main() {
FILE * f = popen( "ls -al", "r" );
if ( f == 0 ) {
fprintf( stderr, "Could not execute\n" );
return 1;
}
const int BUFSIZE = 1000;
char buf[ BUFSIZE ];
while( fgets( buf, BUFSIZE, f ) ) {
fprintf( stdout, "%s", buf );
}
pclose( f );
}
``` | How can I execute external commands in C++/Linux? | [
"",
"c++",
"linux",
"command-line",
""
] |
I have switched to JUnit4.4 from JUnit3.8. I run my tests using ant, all my tests run successfully but test utility classes fail with "No runnable methods" error. The pattern I am using is to include all classes with name \*Test\* under test folder.
I understand that the runner can't find any method annotated with @Test attribute. But they don't contain such annotation because these classes are not tests.
Surprisingly when running these tests in eclipse, it doesn't complain about these classes.
In JUnit3.8 it wasn't a problem at all since these utility classes didn't extend TestCase so the runner didn't try to execute them.
I know I can exclude these specific classes in the junit target in ant script. But I don't want to change the build file upon every new utility class I add. I can also rename the classes (but giving good names to classes was always my weakest talent :-) )
Is there any elegant solution for this problem? | Assuming you're in control of the pattern used to find test classes, I'd suggest changing it to match `*Test` rather than `*Test*`. That way `TestHelper` won't get matched, but `FooTest` will. | Annotate your util classes with @Ignore. This will cause JUnit not to try and run them as tests. | JUnit: how to avoid "no runnable methods" in test utils classes | [
"",
"java",
"ant",
"junit",
"testing",
""
] |
I'm trying to figure out the cleanest way to do this.
Currently I have a customer object:
```
public class Customer
{
public int Id {get;set;}
public string name {get;set;}
public List<Email> emailCollection {get;set}
public Customer(int id)
{
this.emailCollection = getEmails(id);
}
}
```
Then my Email object is also pretty basic.
```
public class Email
{
private int index;
public string emailAddress{get;set;}
public int emailType{get;set;}
public Email(...){...}
public static List<Email> getEmails(int id)
{
return DataAccessLayer.getCustomerEmailsByID(id);
}
}
```
The DataAccessLayer currently connects to the data base, and uses a SqlDataReader to iterate over the result set and creates new Email objects and adds them to a List which it returns when done.
So where and how can I improve upon this?
Should I have my DataAccessLayer instead return a DataTable and leave it up to the Email object to parse and return a List back to the Customer?
I guess "Factory" is probably the wrong word, but should I have another type of EmailFactory which takes a DataTable from the DataAccessLayer and returns a List to the Email object? I guess that kind of sounds redundant...
Is this even proper practice to have my Email.getEmails(id) as a static method?
I might just be throwing myself off by trying to find and apply the best "pattern" to what would normally be a simple task.
Thanks.
---
Follow up
I created a working example where my Domain/Business object extracts a customer record by id from an existing database. The xml mapping files in nhibernate are really neat. After I followed a tutorial to setup the sessions and repository factories, pulling database records was pretty straight forward.
However, I've noticed a huge performance hit.
My original method consisted of a Stored Procedure on the DB, which was called by a DAL object, which parsed the result set into my domain/business object.
I clocked my original method at taking 30ms to grab a single customer record. I then clocked the nhibernate method at taking 3000ms to grab the same record.
Am I missing something? Or is there just a lot of overhead using this nhibernate route?
Otherwise I like the cleanliness of the code:
```
protected void Page_Load(object sender, EventArgs e)
{
ICustomerRepository repository = new CustomerRepository();
Customer customer = repository.GetById(id);
}
public class CustomerRepository : ICustomerRepository
{
public Customer GetById(string Id)
{
using (ISession session = NHibernateHelper.OpenSession())
{
Customer customer = session
.CreateCriteria(typeof(Customer))
.Add(Restrictions.Eq("ID", Id))
.UniqueResult<Customer>();
return customer;
}
}
}
```
The [example I followed](http://web.archive.org/web/20090805054123/http://blogs.hibernatingrhinos.com/nhibernate/archive/2008/04/01/your-first-nhibernate-based-application.aspx) had me create a helper class to help manage the Session, maybe that's why i'm getting this overhead?
```
public class NHibernateHelper
{
private static ISessionFactory _sessionFactory;
private static ISessionFactory SessionFactory
{
get
{
if (_sessionFactory == null)
{
Configuration cfg = new Configuration();
cfg.Configure();
cfg.AddAssembly(typeof(Customer).Assembly);
_sessionFactory = cfg.BuildSessionFactory();
}
return _sessionFactory;
}
}
public static ISession OpenSession()
{
return SessionFactory.OpenSession();
}
}
```
With the application i'm working on, speed is of the essence. And ultimately a lot of data will pass between the web-app and the database. If it takes an agent 1/3 of a second to pull up a customer record as opposed to 3 seconds, that would be a huge hit. But if i'm doing something weird and this is a one time initial setup cost, then it might be worth it if the performance was just as good as executing stored procedures on the DB.
Still open to suggestions!
---
Updated.
I'm scrapping my ORM/NHibernate route. I found the performance is just too slow to justify using it. Basic customer queries just take too long for our environment. 3 seconds compared to sub-second responses is too much.
If we wanted slow queries, we'd just keep our current implementation. The idea to rewrite it was to drastically increase times.
However, after having played with NHibernate this past week, it is a great tool! It just doesn't quite fit my needs for this project. | If the configuration you've got works now, why mess with it? It doesn't sound like you're identifying any particular needs or issues with the code as it is.
I'm sure a bunch of OO types could huddle around and suggest various refactorings here so that the correct responsibilities and roles are being respected, and somebody might even try to shoehorn in a design pattern or two. But the code you have now is simple and sounds like it doesn't have any issues - i'd say leave it. | I've implemented a DAL layer by basically doing what NHibernate does but manually. What NHibernate does is create a Proxy class that inherits from your Domain object (which should have all its fields marked as virtual). All data access code goes into property overrides, its pretty elegant actually.
I simplified this somewhat by having my Repositories fill out the simple properties themselves and only using a proxy for Lazy loading. What I ended up is a set of classes like this:
```
public class Product {
public int Id {get; set;}
public int CustomerId { get; set;}
public virtual Customer Customer { get; set;}
}
public class ProductLazyLoadProxy {
ICustomerRepository _customerRepository;
public ProductLazyLoadProxy(ICustomerRepository customerRepository) {
_customerRepository = customerRepository;
}
public override Customer {
get {
if(base.Customer == null)
Customer = _customerRepository.Get(CustomerId);
return base.Customer
}
set { base.Customer = value; }
}
}
public class ProductRepository : IProductRepository {
public Product Get(int id) {
var dr = GetDataReaderForId(id);
return new ProductLazyLoadProxy() {
Id = Convert.ToInt(dr["id"]),
CustomerId = Convert.ToInt(dr["customer_id"]),
}
}
}
```
But after writing about 20 of these I just gave up and learned NHibernate, with Linq2NHibernate for querying and FluentNHibernate for configuration nowadays the roadblocks are lower than ever. | Best "pattern" for Data Access Layer to Business Object | [
"",
"c#",
"asp.net",
"design-patterns",
"data-access-layer",
""
] |
Here is my current situation:
I have a web page containing a couple scrollable divs. Each of those divs contains a number of objects. I am using YUI to display popup menus of actions that can be performed on each object. Each object has its own menu associated with it that is constructed and displayed dynamically. The popup menus can be large and can overlap the bounds of the scrollable div.
From what I believe are issues with focus (the menus must be accessible), when I hover the mouse over an action that lies on top of an edge of the scrollable div, the div automatically scrolls, moving the content but leaving the menu stationary. Trying to move the menu dynamically when this happens is not something I want to do as I believe it would provide a poor user experience.
So I need to prevent this focused menu from scrolling the div. My idea for providing the best user interface is to prevent these inner divs from scrolling when a menu is open. This leaves the menu positioned in the optimal location to show the user which item is being acted upon. If the user wants to scroll the box, they can click to close the menu and then scroll normally.
How can I do this? I need a solution that works across the major browsers.
My first thought was to listen to the `onscroll` event for that particular element. Unfortunately, there does not seem to be an easy way from there to just prevent the scrolling from happening. For one, my JavaScript event code appears to execute after the actual scrolling has occurred.
Then, I thought that since my code is being run after the object has scrolled, I could just reset `obj.scrollTop` and `obj.scrollLeft`. Sure enough, this appears to work, though I am worried that on slow browsers the user will see the content inside the div "jump around". Also, it would be really nice if the amount the element scrolls is part of the event object. Is it stuck in there somewhere? I'm looking for an alternative to having to store the `scrollTop` and `scrollLeft` variables for this element and then using them while the scrolling is temporarily disabled.
What is the best way to solve this entire problem? | I found a way to work around this issue. By removing the menu element from the scrollable div and then appending it directly to document.body, the browsers all stop trying to scroll the div to reveal the focused element (even though the element is already completely visible).
Thanks to all for your time and your answers! | The simple answer is no you can't do this. Its doubly no if you want a cross-browser solution.
Providing the user with the clear affordance that something can be scrolled then denying them that is just plain poor UI design.
Ok so after your edit it turns out you are not actually trying to prevent the user from scrolling.
The main answer remains true though. It sounds as though the focus is going to rectangle (probably an anchor?) that is not fully in view and causes a scroll. Is there a reason this rectangle must get the focus? For accessibility? | How can I temporarily prevent a scrollable div from scrolling? | [
"",
"javascript",
"html",
"events",
"event-handling",
"dom-events",
""
] |
Tidying up some code that has what I consider to be a confusing line break structure:
```
return
CommonContext.HttpWebService.DownloadXml(configuration.MethodUrl(APIMethods.CharacterSheet),
postData);
```
If it were on one line it would clearly to be to long to be readable. As it stands it is not clear to me at a cursory glance how the "return" and "postData" are related to the long line. CommonContext and APIMethods are static classs, configuration is a local variable.
Thinking about this I would probably write the same in two lines as follows:
```
string methodUrl = configuration.MethodUrl(APIMethods.CharacterSheet);
return CommonContext.HttpWebService.DownloadXml(methodUrl, postData);
```
Is this an effective way of spiting the code up or is there a better way? In this instance I am using C# 2.0. | Yes. It's a good thing usually. It makes code more self-documenting (with a good variable name) and also makes debugging easier (allows putting a breakpoint on the first line, and when an exception is thrown from the first line, you can immediately distinguish it as opposed to the single line situation). | Yes, that's absolutely an effective way of refactoring the code. It can also be helpful if you want to use the debugger or a logger to look at the value of `methodUrl` before it's passed to `DownloadXml`.
Another additional benefit is that you're giving the value a *name*. That can be a big help by explaining its *meaning* at the same time. This can be particularly important if there are lots of parameters - it really helps to be able to quickly glance at an argument list at the call site and a parameter list at the method declaration and take a good guess what's going on just based on the names. | Is it appropiate to break down a long line into two operations? | [
"",
"c#",
"coding-style",
""
] |
A huge amount of example Python code shows the output of the Python REPL, for example:
```
>>> class eg(object):
... def __init__(self, name):
... self.name = name
... def hi(self):
... print "Hi %s" % (self.name)
...
>>> greeter = eg("Bob")
>>> greeter.hi()
Hi Bob
>>>
```
Now, the obvious thing you want to do is run the above code.. so, I run "python" and paste the above text in..
```
>>> >>> class eg(object):
File "<stdin>", line 1
>>> class eg(object):
^
SyntaxError: invalid syntax
>>> ... def __init__(self, name):
File "<stdin>", line 1
... def __init__(self, name):
^
```
The code is broken!?..
To get it to run, I would have to either..
* copy-and-paste the lines one at a time, making sure I copy all the indentation correctly. If you screw it up (say, miss a leading space, you have to start all over again)
* use a text editor to remove `>>>` and `...`, then paste again
It's not a huge issue, but given how much example code is presented in this format, it seems strange you have to do this.. | ### How to run/adopt "the output of Pythons REPL"
* Use [IPython](http://ipython.scipy.org/moin/) shell
```
In [99]: %cpaste
Pasting code; enter '--' alone on the line to stop.
:>>> class eg(object):
:... def __init__(self, name):
:... self.name = name
:... def hi(self):
:... print "Hi %s" % (self.name)
:...
:>>> greeter = eg("Bob")
:>>> greeter.hi()
:--
Hi Bob
```
* Use a capable text editor (e.g., `C-x r k` kills rectangular region in [Emacs](http://www.enigmacurry.com/2008/05/09/emacs-as-a-powerful-python-ide/))
* Use [doctest](http://docs.python.org/library/doctest.html) module
Copy without the shell prompt in the first place (though I don't know how to do it on Google Chrome, for example).
### Why the doctest format is used
Save the following to `documentation.txt`:
```
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat.
>>> class eg(object):
... def __init__(self, name):
... self.name = name
... def hi(self):
... print "Hi %s" % (self.name)
...
>>> greeter = eg("Bob")
>>> greeter.hi()
Hi Bob
>>>
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum
dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est
laborum.
```
Run:
```
$ python -c "import doctest; doctest.testfile('documentation.txt')" -v
```
Output:
```
Trying:
class eg(object):
def __init__(self, name):
self.name = name
def hi(self):
print "Hi %s" % (self.name)
Expecting nothing
ok
Trying:
greeter = eg("Bob")
Expecting nothing
ok
Trying:
greeter.hi()
Expecting:
Hi Bob
ok
1 items passed all tests:
3 tests in doctest.txt
3 tests in 1 items.
3 passed and 0 failed.
Test passed.
```
If you add the following snippet at the end of your module it will test all code in its docstrings:
```
if __name__=="__main__":
import doctest; doctest.testmod()
```
**`QED`** | I don't know if there's a good solution out there for this. Ideally, there'd be some way to modify the behavior of the interpretter to accept copy/paste input of this sort. Here are some alternate suggestions:
Use triple quoting to save the example to a string. Then, use exec:
```
>>> def chomp_prompt(s): return '\n'.join(ln[4:] for ln in s.splitlines())
...
>>> dirty = """>>> class eg(object):
... ... def __init__(self, name):
... ... self.name = name
... ... def hi(self):
... ... print "Hi %s" % (self.name)
... ...
... >>> greeter = eg("Bob")
... >>> greeter.hi()
... """
>>> clean = chomp_prompt(dirty)
>>> exec clean
Hi Bob
>>>
```
Not only does my solution all fit on one line (so it'll be easy for you to copy/paste it in the interpreter), it works on the above example :D :
```
>>> s = r'''>>> def chomp_prompt(s): return '\n'.join(ln[4:] for ln in s.splitlines())
... ...
... >>> dirty = """>>> class eg(object):
... ... ... def __init__(self, name):
... ... ... self.name = name
... ... ... def hi(self):
... ... ... print "Hi %s" % (self.name)
... ... ...
... ... >>> greeter = eg("Bob")
... ... >>> greeter.hi()
... ... """
... >>> clean = chomp_prompt(dirty)
... >>> exec clean'''
>>> s2 = chomp_prompt(s)
>>> exec s2
Hi Bob
```
My second suggestion is to look at ipython's ability to open an editor for you and execute what you entered there after you're done editing:
<http://ipython.scipy.org/doc/rel-0.9.1/html/interactive/tutorial.html#source-code-handling-tips>
If you set emacs as your editor, I know it has the ability to delete a rectangle of text (you can probably guess the command: M-x delete-rectangle), which would work perfectly for getting rid of those pesky prompts. I'm sure many other editors have this as well. | Why can I not paste the output of Pythons REPL without manual-editing? | [
"",
"python",
"user-interface",
"read-eval-print-loop",
""
] |
I'm trying to mimic static variables on a JavaScript function, with the following purpose:
```
$.fn.collapsible = function() {
triggers = $(this).children('.collapse-trigger');
jQuery.each(triggers, function() {
$(this).click(function() {
collapse = $(this).parent().find('.collapse');
})
})
}
```
How do I save the "collapse" object so it doesn't have to be "found" on each call? I know that with named functions I could do something like "someFunction.myvar = collapse", but how about anonymous functions like this one?
Thanks! | You can save your variable in the function, using either `functioName.myVar = value` or `arguments.callee.myVar = value` if you don't have the current function name.
`arguments.callee` is the current function you are in. | For anonymous function you could use a function that returns a function.
For instance:
```
var myAnonymousFunction = (function(){
var myFirstStatic = $("#anElement");
var anotherStatic = true;
return function(param1,param2) {
// myFirstStatic is in scope
// anotherStatic also
}
})();
```
Should work like a charm and you're assured initialisation code for statics is only executed once. | Static variables in an anonymous function | [
"",
"javascript",
"jquery",
"variables",
"function",
"memoization",
""
] |
Something like:
```
using (IDisposable disposable = GetSomeDisposable())
{
//.....
//......
return Stg();
}
```
I believe it is not a proper place for a return statement, is it? | As several others have pointed out in general this is not a problem.
The only case it will cause you issues is if you return in the middle of a using statement and additionally return the in using variable. But then again, this would also cause you issues even if you didn't return and simply kept a reference to a variable.
```
using ( var x = new Something() ) {
// not a good idea
return x;
}
```
Just as bad
```
Something y;
using ( var x = new Something() ) {
y = x;
}
``` | It's perfectly fine.
You are apparently thinking that
```
using (IDisposable disposable = GetSomeDisposable())
{
//.....
//......
return Stg();
}
```
is blindly translated into:
```
IDisposable disposable = GetSomeDisposable()
//.....
//......
return Stg();
disposable.Dispose();
```
Which, admittedly, would be a problem, and would make the `using` statement rather pointless --- which is why that's **not** what it does.
The compiler makes sure that the object is disposed before control leaves the block -- regardless of how it leaves the block. | returning in the middle of a using block | [
"",
"c#",
"dispose",
"idisposable",
"using-statement",
""
] |
How do I convert a string into a boolean in Python? This attempt returns `True`:
```
>>> bool("False")
True
``` | Really, you just compare the string to whatever you expect to accept as representing true, so you can do this:
```
s == 'True'
```
Or to checks against a whole bunch of values:
```
s.lower() in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh']
```
Be cautious when using the following:
```
>>> bool("foo")
True
>>> bool("")
False
```
Empty strings evaluate to `False`, but everything else evaluates to `True`. So this should not be used for any kind of parsing purposes. | #### Warning: This answer will no longer work as of Python 3.12 (it's deprecated as of 3.10)
Use:
```
bool(distutils.util.strtobool(some_string))
```
* **Python 2**: [`distutils.util.strtobool`](https://docs.python.org/2/distutils/apiref.html#distutils.util.strtobool)
* **Python >=3, <3.12**: [`distutils.util.strtobool`](https://docs.python.org/3/distutils/apiref.html#distutils.util.strtobool)
* **Python >=3.12**: No longer part of the standard library due to [PEP 632 – Deprecate distutils module](https://peps.python.org/pep-0632/)
> True values are y, yes, t, true, on and 1; false values are n, no, f, false, off and 0. Raises ValueError if val is anything else.
Be aware that `distutils.util.strtobool()` returns integer representations and thus it needs to be wrapped with `bool()` to get Boolean values.
Given that distutils will no longer be part of the standard library, here is the code for `distutils.util.strtobool()` (see the [source code](https://github.com/python/cpython/blob/v3.11.2/Lib/distutils/util.py#L308) for 3.11.2).
```
def strtobool (val):
"""Convert a string representation of truth to true (1) or false (0).
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'val' is anything else.
"""
val = val.lower()
if val in ('y', 'yes', 't', 'true', 'on', '1'):
return 1
elif val in ('n', 'no', 'f', 'false', 'off', '0'):
return 0
else:
raise ValueError("invalid truth value %r" % (val,))
``` | Converting from a string to boolean in Python | [
"",
"python",
"string",
"boolean",
""
] |
I have just stumbled across the Backgroundworker object, and it seems like the tool I'm looking for to make my GUI responding while performing calculations. I am writing IO plugins for ArcGIS.
I am doing some data processing outside ArcGIS, which works fine using the backgroundworker. But when I'm inserting the data into ArcGIS, the backgroundworker seems to increase the duration time by a factor 9 or so. Placing the processing code outside the DoWork method, increases the performance by a factor 9.
I have read about this several places on the net, but I have no experience in multithreaded programming and the terms like STA and MTA means nothing to me. [link text](http://edndoc.esri.com/arcobjects/9.2/NET/2c2d2655-a208-4902-bf4d-b37a1de120de.htm)
I have also tried to use a simple implementation of threading, but with similar results.
Does anyone know what I can do to be able to use ArcGIS processing and maintaining a responsive GUI?
EDIT: I have included a sample of my interaction with the background worker. If I put the code located in the StartImporting method in the cmdStart\_Click method, it executes much faster.
```
private void StartImporting(object sender, DoWorkEventArgs e)
{
DateTime BeginTime = DateTime.Now;
// Create a new report object.
SKLoggingObject loggingObject = new SKLoggingObject("log.txt");
loggingObject.Start("Testing.");
SKImport skImporter = new SKImport(loggingObject);
try
{
// Read from a text box - no writing.
skImporter.Open(txtInputFile.Text);
}
catch
{
}
SKGeometryCollection convertedCollection = null;
// Create a converter object.
GEN_SK2ArcGIS converter = new GEN_SK2ArcGIS(loggingObject);
// Convert the data.
convertedCollection = converter.Convert(skImporter.GetGeometry());
// Create a new exporter.
ArcGISExport arcgisExporter = new ArcGISExport(loggingObject);
// Open the file.
// Read from a text box - no writing.
arcgisExporter.Open(txtOutputFile.Text);
// Insert the geometry collection.
try
{
arcgisExporter.Insert(convertedCollection);
}
catch
{
}
TimeSpan totalTime = DateTime.Now - BeginTime;
lblStatus.Text = "Done...";
}
private void ChangeProgress(object sender, ProgressChangedEventArgs e)
{
// If any message was passed, display it.
if (e.UserState != null && !((string)e.UserState).Equals(""))
{
lblStatus.Text = (string)e.UserState;
}
// Update the progress bar.
pgStatus.Value = e.ProgressPercentage;
}
private void ImportDone(object sender, RunWorkerCompletedEventArgs e)
{
// If the process was cancelled, note this.
if (e.Cancelled)
{
pgStatus.Value = 0;
lblStatus.Text = "Operation was aborted by user...";
}
else
{
}
}
private void cmdStart_Click(object sender, EventArgs e)
{
// Begin importing the sk file to the geometry collection.
// Initialise worker.
bgWorker = new BackgroundWorker();
bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ImportDone);
bgWorker.ProgressChanged += new ProgressChangedEventHandler(ChangeProgress);
bgWorker.DoWork += new DoWorkEventHandler(StartImporting);
bgWorker.WorkerReportsProgress = true;
bgWorker.WorkerSupportsCancellation = true;
// Start worker.
bgWorker.RunWorkerAsync();
}
private void cmdCancel_Click(object sender, EventArgs e)
{
bgWorker.CancelAsync();
}
```
Kind Regards, Casper | I have continued trying to find a solution, and the following is what I ended up doing. The code is cut and paste from various files and presented to give an idea of what I did. It demonstrates how I can call methods which are communicating with ArcGIS using a thread. The code allows me to update the GUI in the main thread, abort the operation, and do post-operation stuff. I ended up using the first threading part from the link I posted initially.
The reason for the initial loss of performance is probably due to the single-threaded apartment (STA) which is required by ArcGIS. The Backgroundworker seems to be MTA, thus not appropriate for working with ArcGIS
Well here it goes, I hope I haven't forgotten anything, and feel very free to edit my solution. It will both help me and probably also other people developing stuff for ArcGIS.
```
public class Program
{
private volatile bool AbortOperation;
Func<bool> AbortOperationDelegate;
FinishProcessDelegate finishDelegate;
UpdateGUIDelegate updateGUIDelegate;
private delegate void UpdateGUIDelegate(int progress, object message);
private delegate void FinishProcessDelegate();
private void cmdBegin_Click(...)
{
// Create finish delegate, for determining when the thread is done.
finishDelegate = new FinishProcessDelegate(ProcessFinished);
// A delegate for updating the GUI.
updateGUIDelegate = new UpdateGUIDelegate(UpdateGUI);
// Create a delegate function for abortion.
AbortOperationDelegate = () => AbortOperation;
Thread BackgroundThread = new Thread(new ThreadStart(StartProcess));
// Force single apartment state. Required by ArcGIS.
BackgroundThread.SetApartmentState(ApartmentState.STA);
BackgroundThread.Start();
}
private void StartProcess()
{
// Update GUI.
updateGUIDelegate(0, "Beginning process...");
// Create object.
Converter converter = new Converter(AbortOperationDelegate);
// Parse the GUI update method to the converter, so it can update the GUI from within the converter.
converter.Progress += new ProcessEventHandler(UpdateGUI);
// Begin converting.
converter.Execute();
// Tell the main thread, that the process has finished.
FinishProcessDelegate finishDelegate = new FinishProcessDelegate(ProcessFinished);
Invoke(finishDelegate);
// Update GUI.
updateGUIDelegate(100, "Process has finished.");
}
private void cmdAbort_Click(...)
{
AbortOperation = true;
}
private void ProcessFinished()
{
// Post processing.
}
private void UpdateGUI(int progress, object message)
{
// If the call has been placed at the local thread, call it on the main thread.
if (this.pgStatus.InvokeRequired)
{
UpdateGUIDelegate guidelegate = new UpdateGUIDelegate(UpdateGUI);
this.Invoke(guidelegate, new object[] { progress, message });
}
else
{
// The call was made on the main thread, update the GUI.
pgStatus.Value = progress;
lblStatus.Text = (string)message;
}
}
}
public class Converter
{
private Func<bool> AbortOperation { get; set;}
public Converter(Func<bool> abortOperation)
{
AbortOperation = abortOperation;
}
public void Execute()
{
// Calculations using ArcGIS are done here.
while(...) // Insert your own criteria here.
{
// Update GUI, and replace the '...' with the progress.
OnProgressChange(new ProgressEventArgs(..., "Still working..."));
// Check for abortion at anytime here...
if(AbortOperation)
{
return;
}
}
}
public event ProgressEventHandler Progress;
private virtual void OnProgressChange(ProgressEventArgs e)
{
var p = Progress;
if (p != null)
{
// Invoke the delegate.
p(e.Progress, e.Message);
}
}
}
public class ProgressEventArgs : EventArgs
{
public int Progress { get; set; }
public string Message { get; set; }
public ProgressEventArgs(int _progress, string _message)
{
Progress = _progress;
Message = _message;
}
}
public delegate void ProgressEventHandler(int percentProgress, object userState);
``` | It is correct that you should use STA threads when working with the COM objects in ArcGIS. Still, you can get the convenience of the BackgroundWorker, which always is an MTA thread from the system's thread pool.
```
private static void OnBackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = (BackgroundWorker)sender;
ToolToStart tool = e.Argument as ToolToStart;
if (tool != null)
{
tool.BackgroundWorker = worker;
// The background worker thread is an MTA thread,
// and should not operate on ArcObjects/COM types.
// Instead we create an STA thread to run the tool in.
// When the the tool finishes the infomation from the STA thread
// is transferred to the background worker's event arguments.
Thread toolThread = new Thread(STAThreadStart);
toolThread.SetApartmentState(ApartmentState.STA);
toolThread.Start(tool);
toolThread.Join();
e.Cancel = m_ToolCanceled;
e.Result = m_ToolResult;
}
}
```
The STA thread can now use the BackgroundWorker's methods, such as reporting progress, checking for cancellation and reporting results.
```
protected virtual void StatusUpdateNotify(ProgressState progressState)
{
if (BackgroundWorker.CancellationPending)
{
throw new OperationCanceledException();
}
BackgroundWorker.ReportProgress(progressState.Progress, progressState);
}
```
In addition to only using STA threads when operating on ArcGIS objects, you should not share objects between two threds. From your code it seems like you access the GUI from the background worker: `lblStatus.Text = "Done...";`, which could be done in e.g. the delegate for RunWorkerComplete. | Threading and ArcGIS | [
"",
"c#",
"multithreading",
"backgroundworker",
"arcgis",
""
] |
Is there a fast and easy way of getting term frequencies from a Lucene index, without doing it through the `TermVectorFrequencies` class, since that takes an awful lot of time for large collections?
What I mean is, is there something like `TermEnum` which has not just the document frequency but term frequency as well?
UPDATE:
Using TermDocs is way too slow. | Use [`TermDocs`](http://lucene.apache.org/core/old_versioned_docs/versions/3_0_3/api/all/org/apache/lucene/index/TermDocs.html) to get the term frequency for a given document. Like the document frequency, you get the term documents from an `IndexReader`, using the term of interest.
---
You won't find a faster method than `TermDocs` without losing some generality. `TermDocs` reads directly from the ".frq" file in an index segment, where each term frequency is listed in document order.
If that's "too slow", make sure that you've optimized your index to merge multiple segments into a single segment. Iterate over the documents in order (skips are alright, but you can't jump back and forth in the document list efficiently).
Your next step might be additional processing to create an even more specialized file structure that leaves out the `SkipData`. Personally I would look for a better algorithm to achieve my objective, or provide better hardware—lots of memory, either to hold a `RAMDirectory`, or to give to the OS for use on its own file-caching system. | The trunk version of Lucene (to be 4.0, eventually) now exposes the totalTermFreq() for each term from the TermsEnum. This is the total number of times this term appeared in all content (but, like docFreq, does not take into account deletions). | Get term frequencies in Lucene | [
"",
"java",
"full-text-search",
"lucene",
""
] |
What would be the best way to implement the following?
I have a collection of objects that implement an interface, internally I want to be able to expose set and get on the properties and externally only get.
Here's an example of the sort of thing I want...
That does't compile.
```
public interface ITable
{
string Name { get; }
}
internal interface IInternalTable
{
string Name { get; set; }
}
internal class Table : ITable, IInternalTable
{
public string Name { get; set; }
public string ITable.Name { get { return Name; } }
}
public class Database
{
private List<IInternalTable> tables;
public List<ITable>
{
get { return this.tables; }
}
}
``` | ### Use this:
```
public interface ITable
{
string Name { get; }
}
public class Table : ITable
{
public string Name { get; internal set; }
}
public class Database
{
public List<ITable> Tables { get; private set; }
}
```
**Note**: The accessibility modifier used on a get or set accessor can only restrict visibility not increase it. | If Table implements IInternalTable implicitly, and IInternalTable is internal, then those methods will only be accessible internally (because only internal code will be able to use IInternalTable:
```
public interface ITable
{
string Name { get; }
}
internal interface IInternalTable
{
string Name { get; set; }
}
public class Table : ITable, IInternalTable
{
public string Name { get; set; }
string ITable.Name { get { return Name; } }
}
public class Database
{
private List<Table> tables;
public List<Table> Tables
{
get { return this.tables; }
}
}
```
(Also now exposing Table type to avoid issues with lack of covariance... which could also be solved by Database.Tables returning a copy and having a different internal only property.) | Internal and external interfaces and collections | [
"",
"c#",
"inheritance",
"interface",
""
] |
I am doing an application like Form builder in Cakephp.
I've created the module for Designing the forms. Is it a good way to create a separate table for each forms in the case of form building? | I don't think so. The database design should come first and it should be a clean, simple and as efficient as possible. Then you build your forms.
A good form building app should be able to look at a database table, or a group of tables, and figure out what belongs where, what type of content is being stored (Ints, primary keys, text, blobs, URLs) and function with as little configuration from the end user as possible. Otherwise you're not going to be able to normalize your database, and you're going to have all kinds of data all over the place.
It's easy enough to get the info on a particular table. That's the best route I think. | Like gargantaun said, start with the DB tables.
I'd want an easily overridable layer between the DB and the forms to manage the relationships between the two and make explicit the data relationships you can't get from the DB.
Someone will surely want to generate multiple forms from the same table (perhaps one form would be too long, perhaps there are different user levels).
The killer feature of something like that is always how well it handles foreign keys in the DB and one-to-one, one-to-many etc. relationships. Not much use if you can't even build a shopping cart with multiple items in it. | Is creating a separate table for each form a smart way to create forms? | [
"",
"php",
"forms",
"cakephp",
""
] |
I was reading C++ Faq Second Edition , faq number 32.08 .
FAQ says that parameter passed by const reference and returned by const reference can cause dangling reference.
But it is ok if parameter is passed by reference and returned by reference.
I got it that it is unsafe in case of const reference but how is it safe in case when parameter is non const reference.
Last line of FAQ says
"Note that if a function accepts a parameter by non-const reference (for example, f(string& s)), returning a copy of this reference parameter is safe because a temporary cannot be passed by non-const reference."
Need some insight on this!! | if you have like
```
const Foo & bar(const Foo &f) { return f; }
```
and call it like
```
const Foo &ret = bar(Foo());
```
This compiles, but the problem is that now 'ret' is a dangling reference, because the temporary object created by the call to Foo() gets freed after bar returns. The detailed execution sequence here is:
1. temporary Foo is allocated
2. bar is called with a reference to the temporary object
3. bar returns the reference
4. now that bar has returned the temporary Foo is released
5. the reference is now dangling as the object was destroyed
However, if you had Foo declared as
```
Foo & bar(Foo &f) { return f; }
```
then your call bar(Foo()) **would not be accepted by compiler**. When you pass a temporary object to a function, you can only take it by const reference or as a copy; this is part of the language definition. | Temporaries can be passed by const reference - when the function returns the temporaries are destoyed, so the caller is left with a dangling ref.
For example:
```
#include <iostream>
using namespace std;
int const& output( int const& x)
{
cout << x << endl;
return x;
}
int main ()
{
int a = 1;
int const& ref1 = output( a); // OK
int const& ref2 = output(a+1); // bad
return 0;
}
``` | Parameter passed by const reference returned by const reference | [
"",
"c++",
""
] |
does setting up proper relationships in a database help with anything else other than data integrity?
do they improve or hinder performance? | I'd have to say that proper relationships will help people to understand the data (or the intention of the data) better than if omitting them, especially as the overall cost is quite low in maintaining them.
Their presence doesn't hinder performance except in terms of architecture (as others have pointed out, data integrity will occasionally cause foreign key violations which may have some effect) but IMHO is outweighed by the many benefits (if used correctly).
I know you weren't asking whether to use FKs or not, but I thought I'd just add a couple of viewpoints about why to use them (and have to deal with the consequences):
There are other considerations too, such as if you ever plan to use an ORM (perhaps later on) you'll require foreign keys. They can also be very helpful for ETL/Data Import and Export and later for reporting and data warehousing.
It's also helpful if other applications will make use of the schema - since Foreign Keys implement a basic business logic. So your application (and any others) only need to be aware of the relationships (and honour them). It'll keep the data consistent and most likely reduce the number of data errors in any consuming applications.
Lastly, it gives you a pretty decent hint as to where to put indexes - since it's likely you'll lookup table data by an FK value. | As long as you have the obvious indexes in place corresponding to the foreign keys, there should be no perceptible negative effect on performance. It's one of the more foolproof database features you have to work with. | database relationships | [
"",
"sql",
"database",
"table-relationships",
""
] |
I have a masterpage with a Login Control in it. When the Login button is clicked, I would like for a JQuery Dialog to popup if the user's membership is about to expire within 30 days, else it will just log them in as normal. I can't figure out how to do it. I wll post parts of code:
Here is the javascript:
```
<script type="text/javascript">
function showjQueryDialog() {
$("#dialog").dialog("open");
}
$(document).ready(function() {
$("#dialog").dialog({
autoOpen: false,
modal: true,
buttons: { "Renew Membership": function()
{ $(this).dialog("close"); } }
});
});
</script>
```
The login button is called ibtnLoginButton and here is part of the code:
```
//Grab the user profile.
UserProfiles userProfile =
UserProfiles.GetUserProfiles(txtUserName1.Text);
//Calculate the Time Span
TimeSpan timeSpan = userProfile.Expiration.Subtract(DateTime.Now);
if (timeSpan.Days < 30)
{
//Show JQuery Dialog Here
}
else
{
//Continue with Login Process.
}
``` | how about this?
```
if (timeSpan.Days < 30)
{
//Show JQuery Dialog Here
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "showExpiration", "showjQueryDialog()", true);
}
``` | Why not always call the jquery method when the button is clicked, and then determine within the javascript method whether or not you want to show the dialogue? If not, just don't do anything. Since you're just checking whether ExpirationDate is smaller than now + 30 days, you can do that calculation just fine in javascript.
Edit:
I can't provide you with the exact solution, but here is some pseudocode to get you on your way.
First make the user profile's expiration date need available in javascript:
```
<script>
var userProfileExpiresOn = "<asp:Literal ID="userProfileExpiresOn" />";
</script>
```
Then edit your method so that it does the logic you're currently doing server-side for you:
```
<script>
function showjQueryDialog() {
if (userProfileExpiresOn < (now + 30 days))
$("#dialog").dialog("open");
}
</script>
```
You can find some documentation on [how to work with dates in Javascript at W3schools.](http://www.w3schools.com/jsref/jsref_obj_date.asp) | How to call a javascript function from a control within a masterpage? | [
"",
"c#",
"asp.net",
"jquery",
"jquery-ui",
""
] |
I am trying to read a UTF8 string via a java.nio.ByteBuffer. The size is an unsinged int, which, of course, Java doesn't have. I have read the value into a long so that I have the value.
The next issue I have is that I cannot create an array of bytes with the long, and casting he long back to an int will cause it to be signed.
I also tried using limit() on the buffer, but again it works with int not long.
The specific thing I am doing is reading the UTF8 strings out of a class file, so the buffer has more in it that just the UTF8 string.
Any ideas on how to read a UTF8 string that has a potential length of an unsigned int from a ByteBuffer.
EDIT:
[Here is an example of the issue](http://java.sun.com/j2se/1.4.2/docs/guide/jpda/SourceDebugExtension_attribute.html).
```
SourceDebugExtension_attribute {
u2 attribute_name_index;
u4 attribute_length;
u1 debug_extension[attribute_length];
}
attribute_name_index
The value of the attribute_name_index item must be a valid index into the constant_pool table. The constant_pool entry at that index must be a CONSTANT_Utf8_info structure representing the string "SourceDebugExtension".
attribute_length
The value of the attribute_length item indicates the length of the attribute, excluding the initial six bytes. The value of the attribute_length item is thus the number of bytes in the debug_extension[] item.
debug_extension[]
The debug_extension array holds a string, which must be in UTF-8 format. There is no terminating zero byte.
The string in the debug_extension item will be interpreted as extended debugging information. The content of this string has no semantic effect on the Java Virtual Machine.
```
So, from a technical point of view, it is possible to have a string in the class file that is the full u4 (unsigned, 4 bytes) in length.
These won't be an issue if there is a limit to the size of a UTF8 string (I am no UTF8 expert so perhaps there is such a limit).
I could just punt on it and go with the reality that there is not going to be a String that long... | Unless your array of bytes is more than 2GB (the largest positive value of a Java `int`), you won't have a problem with casting the `long` back into a signed `int`.
If your array of bytes needs to be more than 2GB in length, you're doing it wrong, not least because that's way more than the default maximum heapsize of the JVM... | Java arrays use a (Java, i.e. signed) int for access [as per the languge spec](http://java.sun.com/docs/books/jls/third_edition/html/arrays.html#10.4), so it's impossible to have an String (which is backed by a char array) longer than Integer.MAX\_INT
But even that much is way too much to be processing in one chunk - it'll totally kill performance and make your program fail with an OutOfMemoryError on most machines if a sufficiently large String is ever encountered.
What you should do is process any string in chunks of a sensible size, say a few megs at a time. Then there's no practical limit on the size you can deal with. | Reading a UTF-8 String from a ByteBuffer where the length is an unsigned int | [
"",
"java",
"string",
"utf-8",
"bytebuffer",
""
] |
How might I get the output from a CMD process to display in my GUI? This is the code I'm using to run the process:
```
try {
String line;
Process p = Runtime.getRuntime().exec("cmd /c \"e:\\folder\\someCommands.cmd\"");
BufferedReader input =
new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
} catch (Exception err) {
err.printStackTrace();
}
```
I've tried doing this:
```
jLabel1.setText(line);
```
...but the GUI is completely locked up while the process is running, so nothing updates until the very end, which isn't very useful. Other than that the CMD works fine. I just want to display the output in real-time. | Did you repaint() after setting the text of the label?
Anyway, you should generally be hesitant to execute a long operation on the GUI event thread. Look into using a [`SwingWorker`](http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html) instead. | You'll need to start a separate thread to run the process. The code you're using to run it can mostly just be inserted into the thread's (or `Runnable`'s) `run()` method as is, but to set the text in the JLabel, you should use something like this:
```
...
while ((line = input.readLine()) != null) {
SwingUtilities.invokeLater(new SetTextRunnable(jLabel1, line));
}
...
class SetTextRunnable implements Runnable {
private String line;
private JLabel jLabel1
public SetTextRunnable(JLabel jLabel1, String line) {
this.jLabel1 = jLabel1;
this.line = line;
}
public void run() {
jLabel1.setText(line);
}
}
```
*EDIT*: just noticed something: apparently the class `SwingWorker` was designed for this sort of thing, so that's another option for you (if it exists in your version of Java).
*EDIT to the EDIT*: so silly me, I didn't notice `SwingWorker` was already mentioned in another answer. | Display CMD output in my GUI (java) | [
"",
"java",
"user-interface",
"swing",
"cmd",
"real-time",
""
] |
Let's say that I've got my code base to as high a degree of unit test coverage as makes sense. (Beyond a certain point, increasing coverage doesn't have a good ROI.)
Next I want to test performance. To benchmark code to make sure that new commits aren't slowing things down needlessly. I was very intrigued by Safari's [zero tolerance policy](http://webkit.org/projects/performance/index.html) for slowdowns from commits. I'm not sure that level of commitment to speed has a good ROI for most projects, but I'd at least like to be alerted that a speed regression has happened, and be able to make a judgment call about it.
Environment is Python on Linux, and a suggestion that was also workable for BASH scripts would make me very happy. (But Python is the main focus.) | You will want to do performance testing at a system level if possible - test your application as a whole, in context, with data and behaviour as close to production use as possible.
This is not easy, and it will be even harder to automate it and get consistent results.
Moreover, you can't use a VM for performance testing (unless your production environment runs in VMs, and even then, you'd need to run the VM on a host with nothing else on).
When you say doing performance unit-testing, that may be valuable, but only if it is being used to diagnose a problem which really exists at a system level (not just in the developer's head).
Also, performance of units in unit testing sometimes fails to reflect their performance in-context, so it may not be useful at all. | While I agree that testing performance at a system level is ultimately more relevant, if you'd like to do UnitTest style load testing for Python, FunkLoad <http://funkload.nuxeo.org/> does exactly that.
Micro benchmarks have their place when you're trying to speed up a specific action in your codebase. And getting subsequent performance unit tests done is a useful way to ensure that this action that you just optimized does not unintentionally regress in performance upon future commits. | How to do "performance-based" (benchmark) unit testing in Python | [
"",
"python",
"linux",
"unit-testing",
"benchmarking",
""
] |
I open the application using the Process class:
```
System.Diagnostics.Process vsProc = new System.Diagnostics.Process();
vsProc.StartInfo.FileName = "program.exe";
vsProc.Start();
```
If I just kill it `vsProc.Kill()` the application ends uncorrectly. How can I close it correctly? | I think part of the reason it is ending incorrectly is that you have not freed all of the resources associated with it prior to killing it. Try using the [CloseMainWindow()](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.closemainwindow.aspx)and [Close()](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.close.aspx) methods. CloseMainWindow will send a close message to the specified applicaitions main window, and Close() should free resources associated with the process. | How to close a program 'correctly' depends 100% on the program you're dealing with. If you're the one writing the child program, you get to implement proper & sane behavior. If not, your best **general** bet is finding the application's main window and send it a close request... rather than terminating the process. | How can I correctly close the application opened with using of Process? | [
"",
"c#",
""
] |
I want to write a command line daemon that runs forever. I understand that if I want the JVM to be able to shutdown gracefully in linux, one needs to wrap the bootstrap via some C code. I think I'll be ok with a shutdown hook for now.
On to my questions:
1. My main(String[]) block will fire off a separate Superdaemon.
2. The Superdaemon will poll and loop forever.
So normally I would do:
```
class Superdaemon extends Thread { ... }
class Bootstrap
{
public static void main( String[] args )
{
Thread t = new Superdaemon();
t.start();
t.join();
}
}
```
Now I figured that if I started Superdaemon via an Executor, I can do
```
Future<?> f = exec.submit( new Superdaemon() );
f.get();
```
Is `Future.get()` implemented with Thread.join() ?
If not, does it behave equivalently ?
Regards,
ashitaka | Yes, the way you've written these is equivalent.
However, you don't really need to wait for the Superdaemon thread to complete. When the main thread finishes executing main(), that thread exits, but the JVM will not. The JVM will keep running until the last non-daemon thread exits its run method.
For example,
```
public class KeepRunning {
public static void main(String[] args) {
Superdaemon d = new Superdaemon();
d.start();
System.out.println(Thread.currentThread().getName() + ": leaving main()");
}
}
class Superdaemon extends Thread {
public void run() {
System.out.println(Thread.currentThread().getName() + ": starting");
try { Thread.sleep(2000); } catch(InterruptedException e) {}
System.out.println(Thread.currentThread().getName() + ": completing");
}
}
```
You'll see the output:
```
main: leaving main()
Thread-0: starting
Thread-0: completing
```
In other words, the main thread finishes first, then the secondary thread completes and the JVM exits. | > The issue is that books like JCIP is advocating that we use Executors to starts Threads. So I'm trying my best not to use Thread.start(). I'm not sure if I would necessarily choose a particular way of doing things just based on simplicity. There must be a more convincing reason, no ?
The convincing reason to use *java.util.concurrent* is that multi-threaded programming is very tricky. Java offers the tools to that (Threads, the *synchronized* and *volatile* keywords), but that does not mean that you can safely use them directly without shooting yourself in the foot: Either too much synchronization, resulting in unnecessary bottlenecks and deadlocks, or too less, resulting in erratic behaviour due to race conditions).
With *java.util.concurrent* you get a set of utilities (written by experts) for the most common usage patterns, that you can just use without worrying that you got the low-level stuff right.
In your particular case, though, I do not quite see why you need a separate Thread at all, you might as well use the main one:
```
public static void main( String[] args )
{
Runnable t = new Superdaemon();
t.run();
}
```
Executors are meant for tasks that you want to run in the background (when you have multiple parallel tasks or when your current thread can continue to do something else). | Is Future.get() a replacement for Thread.join()? | [
"",
"java",
"concurrency",
""
] |
I am new to Python. I was trying to define and run a simple function in a class.
Can anybody please tell me what's wrong in my code:
```
class A :
def m1(name,age,address) :
print('Name -->',name)
print('Age -->',age)
print('Address -->',address)
>>> a = A()
>>> a.m1('X',12,'XXXX')
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
a.m1('X',12,'XXXX')
```
I am getting below error
**TypeError: m1() takes exactly 3 positional arguments (4 given)** | Instance methods take instance as first argument:
```
class A :
def m1(self, name,age,address) :
print('Name -->',name)
print('Age -->',age)
print('Address -->',address)
```
You can also use [@staticmethod decorator](http://docs.python.org/library/functions.html#staticmethod) to create static function:
```
class A :
@staticmethod
def m1(name,age,address) :
print('Name -->',name)
print('Age -->',age)
print('Address -->',address)
``` | By convention, methods in a class instance receive an object reference as the 1st argument, named `self`.
```
>>> class A:
... def m1(self,name,age,address):
... print('Name -->',name)
... print('Age -->',age)
... print('Address -->',address)
...
>>> a=A()
>>> a.m1('X',12,'XXXX')
('Name -->', 'X')
('Age -->', 12)
('Address -->', 'XXXX')
>>>
``` | Function definition in Python | [
"",
"python",
""
] |
How can i use **second** method instead of **first**?
## first (web user control)
```
public void Remove()
{
int count = this.ListBox1.Items.Count;
for (int i = count - 1; i > -1; i--)
{
if (ListBox1.Items[i].Selected)
{
ListBox1.Items.Remove(ListBox1.Items[i]);
}
}
}
```
---
## Test.aspx(Test of first)
```
protected void btnRemove_Click(object sender, EventArgs e)
{
ItemOrderer2.Remove();
}
```
## second(web user control)
```
public void Remove(string value)
{
ListItem li = new ListItem();
li = ListBox1.Items.FindByValue(value);
if (li != null)
{
this.ListBox1.Items.Remove(li);
}
```
## Test.aspx( Test of Second)
```
protected void btnRemove_Click(object sender, EventArgs e)
{
// ItemOrderer2.Remove();
if (ItemOrderer2.Items.Count > 0)
foreach (ListItem li in ItemOrderer2.Items)
{
if (li.Selected)
{
ItemOrderer2.Remove(li.Value);
}
}
}
``` | You can't use `foreach` if you are removing data inside the `foreach` - it (intentionally) breaks the iterator.
If `for` works, why change it? If you are *desperate* to use `foreach`, then build a *separate* list first - for example:
```
List<ListItem> remove = new List<ListItem>();
foreach(ListItem li in ItemOrdere2.Items) {
if(li.Selected) remove.Add(li);
}
foreach(ListItem li in remove) {
ItemOrderer2.Remove(li); // or similar
}
```
The first query can often be simplified by LINQ if if is available. | You can get the values to be removed first to a list and then run them through the remove function. This can be further enhanced if needed.
```
var removedValues = ItemOrderer2.Items
.Where(li => li.Selected)
.Select(li => li.Value).ToList();
foreach (var removedValue in removedValues) {
ItemOrderer2.Remove(removedValue);
}
``` | how can i use foreach method instead of for method witn remove method of listbox? | [
"",
"c#",
".net",
"asp.net",
""
] |
I've written some code that is supposed to write a file to the temp directory, then copy it to a permanent location, but find that doing so creates a permission-related error on the copy command. The code looks like this:
```
string tempPath = Path.GetTempFileName();
Stream theStream = new FileStream(tempPath, FileMode.Create);
// Do stuff.
File.Copy(tempPath, _CMan.SavePath, true);
File.Delete(tempPath);
```
I dimly remember that there's an API call I can make to create a temp file in a specified directory, passed as a parameter. But, that's a dim memory from my VB 6 days.
So, how do I create a temp file in a directory other than the temp directory defined by Windows? | ```
Path.Combine(directoryYouWantTheRandomFile, Path.GetRandomFileName())
``` | Kinda off base with your question, but maybe you're just not closing the stream before you try to copy it? Seems like you get the permissions-based problem when you open the stream if it's really a permissions problem. | How do I create a temp file in a directory other than temp? | [
"",
"c#",
".net",
""
] |
I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the [flyweight design pattern](https://en.wikipedia.org/wiki/Flyweight_pattern).
However, I'm a bit confused as to why `__init__` is always called after `__new__`. I wasn't expecting this. Can anyone tell me why this is happening and how I can implement this functionality otherwise? (Apart from putting the implementation into the `__new__` which feels quite hacky.)
Here's an example:
```
class A(object):
_dict = dict()
def __new__(cls):
if 'key' in A._dict:
print "EXISTS"
return A._dict['key']
else:
print "NEW"
return super(A, cls).__new__(cls)
def __init__(self):
print "INIT"
A._dict['key'] = self
print ""
a1 = A()
a2 = A()
a3 = A()
```
Outputs:
```
NEW
INIT
EXISTS
INIT
EXISTS
INIT
```
Why? | > Use **`__new__`** when you need to control
> the creation of a new instance.
> Use
> **`__init__`** when you need to control initialization of a new instance.
>
> **`__new__`** is the first step of instance creation. It's called first, and is
> responsible for returning a new
> instance of your class.
> In contrast,
> **`__init__`** doesn't return anything; it's only responsible for initializing the
> instance after it's been created.
>
> In general, you shouldn't need to
> override **`__new__`** unless you're
> subclassing an immutable type like
> str, int, unicode or tuple.
From April 2008 post: [When to use `__new__` vs. `__init__`?](http://mail.python.org/pipermail/tutor/2008-April/061426.html) on mail.python.org.
You should consider that what you are trying to do is usually done with a [Factory](http://en.wikipedia.org/wiki/Factory_object) and that's the best way to do it. Using **`__new__`** is not a good clean solution so please consider the usage of a factory. Here's a good example: [ActiveState Fᴀᴄᴛᴏʀʏ ᴘᴀᴛᴛᴇʀɴ Recipe](http://code.activestate.com/recipes/86900/). | **`__new__`** is static class method, while **`__init__`** is instance method.
**`__new__`** has to create the instance first, so **`__init__`** can initialize it. Note that **`__init__`** takes **`self`** as parameter. Until you create instance there is no **`self`**.
Now, I gather, that you're trying to implement [singleton pattern](http://en.wikipedia.org/wiki/Singleton_pattern) in Python. There are a few ways to do that.
Also, as of Python 2.6, you can use class [decorators](http://www.python.org/dev/peps/pep-0318/).
```
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
@singleton
class MyClass:
...
``` | Why is __init__() always called after __new__()? | [
"",
"python",
"class-design",
"design-patterns",
""
] |
The setup:
```
class Item
{
private int _value;
public Item()
{
_value = 0;
}
public int Value { get { return _value; } set { _value = value; } }
}
class ItemCollection : Collection<Item>
{
private string _name;
public ItemCollection()
{
_name = string.Empty;
}
public string Name { get {return _name;} set {_name = value;} }
}
```
Now, trying to serialize using the following code fragment:
```
ItemCollection items = new ItemCollection();
...
XmlSerializer serializer = new XmlSerializer(typeof(ItemCollection));
using (FileStream f = File.Create(fileName))
serializer.Serialize(f, items);
```
Upon looking at the resulting XML I see that the ItemCollection.Name value is not there!
I think what may be happening is that the serializer sees the ItemCollection type as a simple Collection thus ignoring any other added properties...
Is there anyone having encountered such a problem and found a solution?
Regards,
Stécy | This behavior is "By Design". When deriving from a collection class the Xml Seralizier will only serialize the collection elements. To work around this you should create a class that encapsulates the collection and the name and have that serialized.
```
class Wrapper
{
private Collection<Item> _items;
private string _name;
public Collection<Item> Items { get {return _items; } set { _items = value; } }
public string Name { get { return _name; } set { _name = value; } }
}
```
A detailed discussion is available here: [http://blogs.vertigo.com/personal/chris/Blog/archive/2008/02/01/xml-serializing-a-derived-collection.aspx](http://blogs.vertigo.com/personal/Chris/Blog/Lists/Posts/Post.aspx?ID=18) | XmlSerializer is evil. That said, any object that implements IEnumerable will be serialized as an simple collection, ignoring any extra properties you've added yourself.
You will need to create a new class that holds both your property and a property that returns the collection. | c# inheriting generic collection and serialization | [
"",
"c#",
"inheritance",
"xml-serialization",
"collections",
"generics",
""
] |
I have a form which will open a new form when one button (form1button) is clicked. And on the child form there will be another button 'form2button'. Now if I click this form2button the new form2 should be disposed. But because the form2 object is created here in form1 class method, I cannot dispose that object in form2 class method (fom2buttonclick). So I used static to get my work done as in the following psuedo code.
Form1:
```
class Form1 : Form
{
static Form2 f2;
public void Form1_buttonclick(object sender, EventArgs e)
{
f2 = new Form2();
}
public void Disposef2()
{
f2.Dispose();
}
}
```
Form2:
```
class Form2 : Form
{
public void Form2_buttonclick(object sender, EventArgs e)
{
Form1 f1 = new Form1();
f1.Disposef2();
}
}
```
Is there any other better way to do it. Or C# design itself doesnot provide an alternative mechanism. I am new to C#.Please help me out..
**Edit**
I want to close (dispose explicitely) form2 object which is created in form1 class when button on form2 is clicked. This edit is to give some more clarity. | If the two forms doesn't have a parent-dialog type of relationship, you might just want to hook into the Disposed event on the subform to get notified when it closes.
```
public partial class Form1 : Form
{
private Form2 _Form2;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (_Form2 != null)
_Form2.Dispose();
_Form2 = new Form2();
_Form2.Disposed += delegate
{
_Form2.Dispose();
_Form2 = null;
};
_Form2.Show();
}
}
```
Then all you have to do in Form2 is simply to close it:
```
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Close();
}
}
``` | MSDN docs on disposing of forms:
> Dispose will be called automatically
> if the form is shown using the Show
> method. If another method such as
> ShowDialog is used, or the form is
> never shown at all, you must call
> Dispose yourself within your
> application.
[Source](http://msdn.microsoft.com/en-us/library/aw58wzka.aspx)
On closing vs. disposing:
> When a form is closed, all resources
> created within the object are closed
> and the form is disposed. You can
> prevent the closing of a form at run
> time by handling the Closing event and
> setting the Cancel property of the
> CancelEventArgs passed as a parameter
> to your event handler. If the form you
> are closing is the startup form of
> your application, your application
> ends.
>
> The two conditions when a form is not
> disposed on Close is when (1) it is
> part of a multiple-document interface
> (MDI) application, and the form is not
> visible; and (2) you have displayed
> the form using ShowDialog. In these
> cases, you will need to call Dispose
> manually to mark all of the form's
> controls for garbage collection. | Disposing a form from parent form in C#? | [
"",
"c#",
"class",
"forms",
"object",
"dispose",
""
] |
I wonder if anyone can explain the syntax in one line of this snippet of
code:
```
public class ContactController : Controller
{
private IContactManagerRepository _repository;
**public ContactController()
: this(new EntityContactManagerRepository())**
{}
public ContactController(IContactManagerRepository repository)
{
_repository = repository;
}
```
The bit I am particularly interested in is the first constructor. I
understand from the article I got it from
([<http://www.asp.net/learn/mvc/tutorial-29-cs.aspx>](http://www.asp.net/learn/mvc/tutorial-29-cs.aspx) - listing 3) that the
first constructor calls the second, and intellisense tells me when I hover
over this(new EntityContactManagerRepository()) that it does indeed refer to
the second constructor. But I haven't seen a constructor with a colon after
it before. I know that the colon in the class declaration tells the
compiler that ContactController inherits from Controller, but what does the
colon in the constructor do? | As you've said, it just calls the other constructor as the first part of execution. An alternative is to use `base` which calls a constructor in the base class instead. The language specification uses the term *constructor initializer* for this call. There's *always* something like this - if you don't specify anything, it's equivalent to a call to `base()`. In other words:
```
public Foo(int x)
```
is equivalent to
```
public Foo(int x) : base()
```
In both cases the base class's parameterless constructor is called before the body of the `Foo` constructor is executed. The compiler makes sure that you don't get into an infinite loop - every (non-static) class has to have at least one constructor which calls the base class constructor; you always end up calling the base class constructor before the constructor body for "this" class executes.
Unlike in Java, however, the instance variable initializers *are* executed before the base class constructor calls.
See my [article about constructor chaining](http://pobox.com/~skeet/csharp/constructors.html) for more information. | It is called [constructor chaining](http://www.csharp411.com/constructor-chaining/). With that syntax you can call the constructor of the base class or another constructor of the current class. | Dependency Injection and C# syntax | [
"",
"c#",
"model-view-controller",
""
] |
I make extensive use of inheritance, polymorphisim, and encapsulation but i just realised that i didn't know the following behavior about scope of an object vs a variable. The difference is best shown with code:
```
public class Obj
{
public string sss {get; set;}
public Obj()
{
sss = "0";
}
}
public partial class testScope : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Obj a = new Obj();
String sss = "0";
Context.Response.Write(sss); // 0
FlipString(sss);
FlipString(a.sss);
Context.Response.Write(sss + a.sss); // 0 0
FlipObject(a);
Context.Response.Write(a.sss); // 1
Context.Response.End();
}
public void FlipString(string str)
{ str = "1"; }
public void FlipObject(Obj str)
{ str.sss = "1"; }
}
```
So I thought that when a variable is passed into a method that changes are limited to the scope of the method. But it appears that if an object is passed into a method that changes to it's properties extend beyond the method.
I could accept this if the rule was that this behavior exists for object and not variables but in .net everything is an object, a string (like the one in the example is System.String) So whats the rule, how can i predict the scope of a parameter that i pass into a method? | You never pass an *object* as an argument - you only ever pass a *reference* or a value type value. Unless you use the `ref` keyword, arguments are passed by value - i.e. the initial value of the parameter is the evaluated value of the argument, and changes to the value of the parameter aren't seen by the caller.
However, it's very important to understand that the value of the parameter (for a reference type) is *just the reference*. If you change the contents of the object that the reference refers to, then *that* change *will* be seen by the caller.
It's a topic which deserves more than a few paragraphs - I suggest you read my [article about parameter passing in .NET](http://pobox.com/~skeet/csharp/parameters.html) for more information. | I think that i just figured it out googleing around, some things in .net are "value" types and others are "reference" types, so for value types the value is duplicated when being marshaled into a method, but reference types have a like a pointer, or reference passed into the method which obviously shares the same scope as the parent. So then my question is how can tell if something is a value type or not, i see that structs like ints are all value types but Strings appear to behave like structs even though they are objects System.String? | C# Scope of variables vs objects when parameterized into methods | [
"",
"c#",
"object",
"scope",
""
] |
I have a requirement where I can get the following in an object -
```
a type T or List<T>
```
Converting object into T is easy. How can I convert it to List(by first checking that it can be converted successfully or not), reason I want to convert is to scroll through the list and call tostring on each element.
My actual code -
```
namespace Generic_Collection_Code
{
class Program
{
public static string DumpObj(object obj)
{
string sTemp = String.Empty;
List<int> ints = obj as List<int>;
if (ints != null)
{
foreach (int i in ints)
sTemp += i.ToString() + ",";
sTemp.Trim(',');
}
else
{
List<string> strings = obj as List<string>;
if (strings != null)
{
foreach (string s in strings)
sTemp += s + ",";
sTemp.Trim(',');
}
else
{
sTemp += obj.ToString();
}
}
return sTemp;
}
static void Main(string[] args)
{
List<int> listInts = new List<int>();
listInts.Add(1);
listInts.Add(2);
listInts.Add(3);
Console.WriteLine("Object1: {0}", DumpObj(listInts));
int i = 90;
Console.WriteLine("Object2 {0}", DumpObj(i));
List<string> listStrings = new List<string>();
listStrings.Add("1");
listStrings.Add("2");
listStrings.Add("3");
Console.WriteLine("Object3: {0}", DumpObj(listStrings));
Console.ReadKey();
}
}
}
```
The above code works but I know its an ugly way to achieve this. I wanted to ask from community how can I have this function like -
```
public static string DumpObj<T>(object obj)
{
string sTemp = String.Empty;
List<T> list = obj as List<T>;
if (list != null)
{
foreach (T i in list)
sTemp += i.ToString() + ",";
sTemp.Trim(',');
}
return sTemp;
}
```
This gives me compilation errors as I have to specify T while calling DumpObj with error as -
Error 1 The type arguments for method 'Generic\_Collection\_Code.Program.DumpObj(object)' cannot be inferred from the usage. Try specifying the type arguments explicitly. D:\DotNet\Generic\_Collection\_Code\Generic\_Collection\_Code\Program.cs 57 47 Generic\_Collection\_Code
as you can see, obj is an object, i dont know its type while calling dumobj.
I hope I have made myself clear on this one.
I appreciate your time!
Regards
Amit | What is the compilation error you're getting? If T is declared as a generic type parameter in your context then then the only compile-time issue I can see with that statement is the use of the keyword `object` as a variable name. At any rate, I'd suggest something like this as best expressing your intention:
```
IEnumerable enumerable = obj as IEnumerable;
if (enumerable != null)
{
foreach (object item in enumerable)
{
sTemp += item.ToString();
}
}
```
You may also want to consider using a [StringBuilder](http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx) if your list is likely to have a lot of items. | Say
```
List<T> genericList = object as List<T>;
if(genericList != null)
{
// Do the loop
}
```
The "as" keyword verifies that "object" actually "is-a" List< T >. If so, you get a List< T > back from it. If not, you get null. | Cast an object into generic list | [
"",
"c#",
".net",
""
] |
i ve created two dimensional array inside a function, i want to return that array, and pass it somewhere to other function..
```
char *createBoard( ){
char board[16][10];
int j =0;int i = 0;
for(i=0; i<16;i++){
for( j=0;j<10;j++){
board[i][j]=(char)201;
}
}
return board;
}
```
but this keeps giving me error | Yeah see what you are doing there is returning a pointer to a object (the array called `board`) which was created on the stack. The array is destroyed when it goes out of scope so the pointer is no longer pointing to any valid object (a dangling pointer).
You need to make sure that the array is allocated on the heap instead, using `new`. The sanctified method to create a dynamically allocated array in modern C++ is to use something like the `std::vector` class, although that's more complicated here since you are trying to create a 2D array.
```
char **createBoard()
{
char **board=new char*[16];
for (int i=0; i<16; i++)
{
board[i] = new char[10];
for (int j=0; j<10; j++)
board[i][j]=(char)201;
}
return board;
}
void freeBoard(char **board)
{
for (int i=0; i<16; i++)
delete [] board[i];
delete [] board;
}
``` | The best approach is create a board class and make the ctreateBoard function its constructor:
```
class Board {
private:
char mSquares[16][10];
public:
Board() {
for(int i=0; i<16;i++){
for( int j=0;j<10;j++){
mSquares[i][j]=201;
}
}
// suitable member functions here
};
```
For information on how to use such a class, there is no substitute for reading a good book. I strongly recommend [Accelerated C++](http://www.acceleratedcpp.com/) by Andrew Koenig and Barbra Moo. | how to return two dimensional char array c++? | [
"",
"c++",
"arrays",
"multidimensional-array",
""
] |
I'm just starting to get my mind around this whole Object Oriented thing, so bear with me.
So, I saw an example of an object function (for Javascript) where you assign a new value and that value gets assigned as that property's actual value. Example:
```
function Meat (name, color, price) {
function newPrice (new_price) {
this.price = new_price;
}
this.name = name;
this.color = color;
this.price = price;
this.newprice = newPrice;
}
```
Fine and dandy. Now I have the ability to assign a price by using Bacon.price or Bacon.newprice. Personally, this seems like the highest order of semantics, since functionally it does the same thing. But as an advocate for semantic coding, I'll let it slide. Here's what I want:
When I change the value of Bacon.price, the object should include a function to store the old value in a property called oldprice automatically. I played around with this, but got nowhere. Here's what I've tried so far:
```
function Meat (name, color, price) {
function oldPrice () {
this.oldprice = this.price;
}
this.name = name;
this.color = color;
this.oldprice = oldPrice;
this.price = price;
}
///////////////////////
function Meat (name, color, price) {
this.name = name;
this.color = color;
this.oldprice = this.price;
this.price = price;
}
```
More or less variations of that. I thought that referring to the already assigned value (which would be nothing the first time) before the new value got assigned would be enough. I know that the value (or lack thereof) is stored somewhere before it gets assigned, I just don't know how to refer to it to assign it to the oldvalue property before it gets wiped out.
---
Okay, maybe the problem is with my eyes or fingers then. Because I thought I had tried the suggestions before asking (I know, I didn't mention them!) Unless I'm really confused, this should work:
```
function Meat(price)
{
function setPrice(price)
{
this.oldprice = this.price;
this.price = price;
}
this.price=setPrice;
}
bacon = new Meat()
bacon.price = "Expensive";
document.write(bacon.price+"<br />");
document.write(bacon.oldprice+"<br />");
bacon.price = "Cheap";
document.write(bacon.price+"<br />");
document.write(bacon.oldprice+"<br />");
```
But the output I get is:
Expensive
undefined
Cheap
undefined
All okay until that last one. Again, I am willing to accept bad eyesight and poor spelling as the root. But I can't figure it out. | This will store it when you call `obj.newPrice(xxx);` - I don't think you can do it automatically when using `obj.price = xxx;`
```
function Meat (name, color, price) {
function newPrice (new_price) {
this.oldprice = this.price
this.price = new_price;
}
this.name = name;
this.color = color;
this.price = price;
this.newprice = newPrice;
}
```
Edit:
As noted by @Mauris, Javascript 1.5 does support [getters and setters](https://developer.mozilla.org/En/Core_JavaScript_1.5_Guide:Creating_New_Objects:Defining_Getters_and_Setters) (see also [here](http://ejohn.org/blog/javascript-getters-and-setters/) - you can think of them as methods disguised as properties.
Using these, your code would look like this:
```
function Meat (name, color, price) {
function newPrice (new_price) {
this.oldprice = this.price
this.price = new_price;
}
this.name = name;
this.color = color;
this.__defineSetter__("price", function(newprice)
{
this.oldprice = this.price
this.price = price;
});
}
```
Unfortunately this syntax isn't supported by Internet Explorer yet. | Is that it?
```
function setPrice(price) {
this.oldprice = this.price;
this.price = price;
}
``` | Object property "Previous Value" in Javascript | [
"",
"javascript",
"variables",
"object",
"oop",
""
] |
When writing a LINQ query with multiple "and" conditions, should I write a single `where` clause containing `&&` or multiple `where` clauses, one for each conditon?
```
static void Main()
{
var ints = new List<int>(Enumerable.Range(-10, 20));
var positiveEvensA = from i in ints
where (i > 0) && ((i % 2) == 0)
select i;
var positiveEvensB = from i in ints
where i > 0 where (i % 2) == 0
select i;
System.Diagnostics.Debug.Assert(positiveEvensA.Count() ==
positiveEvensB.Count());
}
```
Is there any difference other than personal preference or coding style (long lines, readability, etc.) between *positiveEvensA* and *positiveEvensB*?
One possible difference that comes to mind is that different LINQ providers may be able to better cope with multiple `where`s rather than a more complex expression; is this true? | I personally would always go with the && vs. two where clauses whenever it doesn't make the statement unintelligible.
In your case, it probably won't be noticeble at all, but having 2 where clauses definitely will have a performance impact if you have a large collection, and if you use all of the results from this query. For example, if you call .Count() on the results, or iterate through the entire list, the first where clause will run, creating a new IEnumerable<T> that will be completely enumerated again, with a second delegate.
Chaining the 2 clauses together causes the query to form a single delegate that gets run as the collection is enumerated. This results in one enumeration through the collection and one call to the delegate each time a result is returned.
If you split them, things change. As your first where clause enumerates through the original collection, the second where clause enumerates its results. This causes, potentially (worst case), 2 full enumerations through your collection and 2 delegates called per member, which could mean this statement (theoretically) could take 2x the runtime speed.
If you do decide to use 2 where clauses, placing the more restrictive clause first will help quite a bit, since the second where clause is only run on the elements that pass the first one.
Now, in your case, this won't matter. On a large collection, it could. As a general rule of thumb, I go for:
1. Readability and maintainability
2. Performance
In this case, I think both options are equally maintainable, so I'd go for the more performant option. | This is mostly a personal style issue. Personally, as long as the `where` clause fits on one line, I group the clauses.
Using multiple `where`s will tend to be less performant because it requires an extra delegate invocation for every element that makes it that far. However it's likely to be an insignificant issue and should only be considered if a profiler shows it to be a problem. | Should I use two "where" clauses or "&&" in my LINQ query? | [
"",
"c#",
".net",
"linq",
""
] |
I'm working on an application and I need to store the users password, so I'm thinking I'll store it in the current-user class of the registry, but I also want to hash it for the obvious reason, and I've seen news items that state that SHA1 has been cracked, is there a better (uncracked) hashing algorithm available in the "standard" system or .net? | SHA1 is not [encryption](http://en.wikipedia.org/wiki/Encryption), it's a [cryptographic hash function](http://en.wikipedia.org/wiki/Cryptographic_hash_function). And yes it has been broken, which means it's possible to generate collisions faster than a brute force method. The SHA2 family has not been broken.
But I would advise to use a custom seed per entry so that a [rainbow table](http://en.wikipedia.org/wiki/Rainbow_table) could not be used for trying out passwords. If you're using the SQL Membership provider the [password format "Hashed"](http://msdn.microsoft.com/en-us/library/system.web.security.membershippasswordformat.aspx) already uses a different seed for each user.
More information about seeding your hash can be found in the article [What You Need To Know About Secure Password Schemes](http://chargen.matasano.com/chargen/2007/9/7/enough-with-the-rainbow-tables-what-you-need-to-know-about-secure-password-schemes.html) by Thomas Ptacek. | As you say in your comment, SHA1 is a hash algorithm, not encryption. It is a one-way function that, even if it is broken, does not allow the password to be retrieved.
If you want stronger hash functions that are already in .NET, look at the SHA2 family - SHA256, SHA384, SHA512. (SHA224 also exists, but isn't implemented in the System.Security.Cryptography namespace.)
The collision attacks on SHA1 are not practically exploitable yet, but you are right to be looking ahead. NIST is currently running a selection process for SHA3 in the light of these attacks, but this is a few years from completion and commercial acceptance. SHA2 on the other hand is an existing family of algorithms that are standardised by NIST and are not subject to the attacks that have been successful against MD5 and SHA1. | Better hashing than SHA1 | [
"",
"c#",
"hash",
""
] |
How can I align the column data to center in a WPF `DataGrid`? | It's hard to say without knowing specifics, but here's a `DataGridTextColumn` that is centered:
```
<wpf:DataGridTextColumn Header="Name" Binding="{Binding Name}" IsReadOnly="True">
<wpf:DataGridTextColumn.CellStyle>
<Style>
<Setter Property="FrameworkElement.HorizontalAlignment" Value="Center"/>
</Style>
</wpf:DataGridTextColumn.CellStyle>
</wpf:DataGridTextColumn>
``` | If you are using DataGridTextColumn you can use the following code snippet:
```
<Style TargetType="DataGridCell">
<Style.Setters>
<Setter Property="TextBlock.TextAlignment" Value="Center" />
</Style.Setters>
</Style>
``` | Text alignment in a WPF DataGrid | [
"",
"c#",
".net",
"wpf",
"xaml",
"wpftoolkit",
""
] |
I have a table structured like this:
```
CREATE TABLE [TESTTABLE]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[DateField] [datetime] NULL,
[StringField] [varchar](50),
[IntField] [int] NULL,
[BitField] [bit] NULL
)
```
I execute the following code:
```
BEGIN
INSERT INTO TESTTABLE (IntField, BitField, StringField, DateField)
VALUES ('1', 1, 'hello', {ts '2009-04-03 15:41:27.378'});
SELECT SCOPE_IDENTITY()
END
```
And then
```
select * from testtable with (NOLOCK)
```
and my result shows:
```
2009-04-03 15:41:27.*377*
```
for the `DateField` column.
Any ideas why I seem to be losing a millisecond?? | SQL Server only stores time to approximately 1/300th of a second. These always fall on the 0, 3 and 7 milliseconds. E.g. counting up from 0 in the smallest increment:
00:00:00.000
00:00:00.003
00:00:00.007
00:00:00.010
00:00:00.013
...
If you need that millisecond accuracy, there's no pleasant way around it. The best options I've seen are to store the value in custom number fields and rebuild it every time you fetch the value, or to store it as a string of a known format. You can then (optionally) store an 'approximate' date in the native date type for the sake of speed, but it introduces a conceptual complexity that often isn't wanted. | SQL Server 2008 has much more precision available. The datetime2 type will accurately store values like this: 2008-12-19 09:31:38.5670514 (accuracy to 100 nanoseconds).
Reference: [time and datetime2 - Exploring SQL Server 2008's New Date/Time Data Types](http://rwgarrison.com/PASS/TimeDateTime2/) | Why is SQL Server losing a millisecond? | [
"",
"sql",
"sql-server",
""
] |
I need to implement the method:
```
object GetFactory(Type type);
```
This method needs to return a Func<T> where typeparam 'T' is the 'type'.
So, my problem is that I don't know how to create a Func<?> at runtime using reflection. Activator.CreateInstance doesn't work because there are no constructors on delegates.
Any Ideas? | You use `Delegate.CreateDelegate`, i.e. from a `MethodInfo`; below, I've hard-coded, but you would use some logic, or `Expression`, to get the actual creation method:
```
using System;
using System.Reflection;
class Foo {}
static class Program
{
static Func<T> GetFactory<T>()
{
return (Func<T>)GetFactory(typeof(T));
}
static object GetFactory(Type type)
{
Type funcType = typeof(Func<>).MakeGenericType(type);
MethodInfo method = typeof(Program).GetMethod("CreateFoo",
BindingFlags.NonPublic | BindingFlags.Static);
return Delegate.CreateDelegate(funcType, method);
}
static Foo CreateFoo() { return new Foo(); }
static void Main()
{
Func<Foo> factory = GetFactory<Foo>();
Foo foo = factory();
}
}
```
For non-static methods, there is an overload of `Delegate.CreateDelegate` that accepts the target instance. | I use this with generics in EF Core including making Expression<Func<SomeModelType,bool>> for let's say a Where clause, you can chain MakeGenericType calls with nested generics.
```
var someType = SomeDbContext.SomeDataModelExample.GetType();
var funcType1 = typeof(Func<>).MakeGenericType(new Type[] { someType });
var result = Activator.CreateInstance(funcType1);
var result2 = Activator.CreateInstance(funcType1, someParams);
``` | Runtime creation of generic Func<T> | [
"",
"c#",
".net",
"reflection",
""
] |
I have the following simple script.
```
<script>
SPC = {
a : [10],
b : 10,
t: function()
{
y = this.a;
z = this.b;
y[0]++;
z++;
alert('this.a[0] = ' + this.a[0] + '\nthis.b = ' + this.b)
}
}
SPC.t();
SPC.t();
</script>
```
Running it in your browser will display two alert boxes with:
this.a[0] = 11
this.b = 10
and
this.a[0] = 12
this.b = 10
The question is, why does the value of this.a[0] increment? I'm assigning "y = this.a" and updating element of "y" as "y[0]++;"?
At the same time, exactly the same thing is happening with "b": "z = this.b; z++". Yet, "this.b" remains equal to 10.
How can I change value of "y[0]" in the local scope without affecting "this.a"?
Any ideas?
Thanks! | `a` is an array, and you're simply copying a reference to the array into `y`. You need to copy the array `a`'s *contents* into a *new array* `y` instead (using `Array.slice()` (`y = a.slice()` in your case) is the easiest way).
(Or, if you only need `a[0]`, you can set `y = a[0]`. Subsequent changes to `y` will not affect `a[0]`, since you are copying the value.)
See the "Javascript Arrays Are Assigned By Reference" and "Passing Arrays As Values" sections of [this article](http://www.hunlock.com/blogs/Mastering_Javascript_Arrays) for more information. | Try [Array.slice()](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/slice) function.
```
y = this.a.slice()
```
This will create a copy of `a` array and assign it to `y`. So modification of `y` won't affect `a`. | Is variable updated "by reference"? | [
"",
"javascript",
"scope",
""
] |
Isn’t a class with only static members a kind of singleton design pattern? Is there any disadvantage of having such a class? A detailed explanation would help. | This kind of class is known as a [monostate](http://jeremyjarrell.com/archive/2008/04/21/88.aspx) - it is somewhat different from a singleton.
Why use a monostate rather than a singleton? In their [original paper](http://portal.acm.org/citation.cfm?id=331120.331154&coll=GUIDE&dl=GUIDE&CFID=9560984&CFTOKEN=28610657) on the pattern, Bell & Crawford suggest three reasonns (paraphrased by me):
* More natural access syntax
* singleton lacks a name
* easier to inherit from
I must admit, I don't find any of these particularly compelling. On the other hand, the monostate is definitely no *worse* than the singleton. | Robert C. Martin wrote an [article](http://objectmentor.com/resources/articles/SingletonAndMonostate.pdf) some times ago about the differences between the mono state pattern and the singleton pattern. | Class with static members vs singleton | [
"",
"c++",
"design-patterns",
"static",
"singleton",
"monostate",
""
] |
I want to read a list the names of files in a folder in a web page using php.
is there any simple script to acheive it? | The simplest and most fun way (imo) is [glob](http://is.php.net/manual/en/function.glob.php)
```
foreach (glob("*.*") as $filename) {
echo $filename."<br />";
}
```
But the standard way is to use the [directory functions.](http://is.php.net/manual/en/function.opendir.php)
```
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "filename: .".$file."<br />";
}
closedir($dh);
}
}
```
There are also the [SPL DirectoryIterator methods](http://is.php.net/manual/en/directoryiterator.construct.php). If you are interested | This is what I like to do:
```
$files = array_values(array_filter(scandir($path), function($file) use ($path) {
return !is_dir($path . '/' . $file);
}));
foreach($files as $file){
echo $file;
}
``` | How to read a list of files from a folder using PHP? | [
"",
"php",
"file",
""
] |
I know Microsoft has a forum similar to uservoice.com for feature and bug submissions, but it has slipped my mind and my google-fu is fail this afternoon. Then I thought... hey, what a great question for Stack Overflow! So:
Where can I go to submit official requests for new features of the C# language? | GitHub is the correct place to lodge these requests. Raise them as GitHub issues.
<https://github.com/dotnet/csharplang> | GitHub Issues:
* [C# language](https://github.com/dotnet/csharplang)
* [VB language](https://github.com/dotnet/vblang)
* [C# cross cutting VB](https://github.com/dotnet/csharplang)
* [Roslyn](https://github.com/dotnet/roslyn/issues) discussions on the Rosyln compiler (only)
* [CoreFX](https://github.com/dotnet/runtime/issues/) This includes things like System.Collections, System.IO for .NET Core (.NET Core 2.0)
* [CoreCLR](https://github.com/dotnet/coreclr/issues) This covers RyuJIT, GC and mscorlib for .NET Core (.NET Core 2.0)
* [ASP.NET Core](https://github.com/aspnet/home/issues) This is for ASP.NET Core (.NET Core 2.0)
* ASP.NET 4.7 - unknown
Historical places not for current discussion:
* [Roslyn C# Language Design forum](https://roslyn.codeplex.com/discussions/topics/5998/c-language-design)
* [Roslyn](https://github.com/dotnet/roslyn/issues) discussions on C# 6.0, C# 7.0 and beyond
There is also the [Visual Studio Uservoice](https://visualstudio.uservoice.com/forums/121579-visual-studio/category/30931-languages-c) for requests pertaining to Visual Studio specifically | Where can I submit request for new features in the C# language? | [
"",
"c#",
""
] |
I have two tables that are something like this:
Main table: id (int), title (varchar), etc.
Sub-table: main\_table\_id (foreign key into main table), tag (varchar), etc.
There can be zero or more subtable rows for a given row in the main table.
I want to do a query that will return every row of the main table, with the columns of the main table, and a the columns from only a single row (doesn't matter which) of the sub-table, if there are any, otherwise NULL in those columns.
Of course if I just do a basic LEFT OUTER JOIN then of course I get the main table repeated multiple times, one for each match in the sub-table.
I'm sure I have seen this done before using a LEFT OUTER JOIN and some sort of trickery that forces only one row to be selected from the sub-table, not all of them -- maybe picking out the minimum or maximum OID. However, more than an hour of googling has not yielded any solutions.
Does anybody have this trick in their toolbelt? | I like Charlie's answer best, but i'm not sure if Postges has a TOP/LIMIT function, so here's an alternate solution that doesn't need one (but does assume sub\_table has a primary key called "id"):
```
SELECT *
FROM main_table m LEFT OUTER JOIN sub_table s
ON s.main_table_id = m.id
WHERE s.id IS NULL OR s.id IN (
SELECT MAX(id) FROM sub_table GROUP BY main_table_id
)
``` | If you're using SQL Server, you can use the TOP clause. If it is something other than SQL Server, you'll have to see if that database offers something equivalent (many of them do). Something like this ...
```
Select * from Main m
left outer join
(select top 1 * from subtable s
where s.main_table_id = m.id) q
on q.main_table_id = m.id;
```
Note: That is to show you the general idea. I didn't have a chance to run it, so there might be a couple of changes necessary, but the concept is there. | How to outer-join two tables (main and many-to-one sub-table) to get only ONE item from second table? | [
"",
"sql",
"postgresql",
"join",
"outer-join",
""
] |
To be more specific:
We have a web service (written in .Net) which utilizes a large number of COM dlls for core business logic (written in VB6). Assume for now that these are sealed libraries.
Unfortunately, many of these COM libraries implement their own error handling or validation messages; if we pass in data which isn't complete, or if another COM dependency is missing, they'll display a dialog box. These dialog boxes are the problem...when running in IIS, these message boxes hang the request, waiting for the user to click ok to a box that can't be seen.
Does anyone know a way to trap these UI calls (potentially it could be a form.show instead of a messagebox) on the .Net side, so we can throw an exception instead? | With the caveat that I haven't done this personally, I believe the intercept and redirect you desire could be achieved through [Win32 Hooks](http://msdn.microsoft.com/en-us/library/ms997537.aspx) | Display of forms is the least of your problems if these were written in VB6 to be used in a desktop application. These COM objects probably don't expect to be accessed by multiple threads at the same time, either. This can blow up very spectacularly or very subtly.
If management are depending on this to work for 10,000 libraries, then you need to make them understand that violating the assumptions of 10,000 pieces of ten year-old code is not a good idea.
If management is old enough (and in the US), then remind them of the old margerine commercials about "It's not *nice* to fool Mother Nature". Bad Things could happen.
---
I think I need to be more specific about "Bad Things".
I'm assuming these were VB6 COM objects created to interact with a VB6 forms application or applications. These COM objects could then reasonably assume there was only one thread at a time accessing them, only one user at a time accessing them, and in fact only one thread and one user accessing them during their entire lifetime.
As soon as you run them in a server, you violate their assumptions.
Who can tell what that will cause? Nobody will have done that analysis because they were basic (and valid) assumptions! Will the code maybe cache something in thread-local storage? That would have worked for the original scenario. Maybe Shared data are used to cache information. It needs to be interlocked if it wil be used by multiple threads, and then you'll have to hope the information doesn't vary per-user, because the different threads may be running on behalf of different users.
I once was told to go fix a memory leak. Long story short, it wasn't a memory leak. It was a piece of legacy, unmanaged code that assumed it was running in a desktop or batch application. In a web service, it was spewing garbage all over the heap. Therefore, it was throwing exceptions all over the place, and causing other, unrelated code to do the same. Unmanaged exceptions don't come with much detail, so it was impossible to see what had caused the problem, or how to solve it.
In this case, I was able to simply put an interlock around all access. This was good enough because this code assumed a batch environment, not an interactive environment. This might not be enough if your COM objects are making assumptions that their ten year-old requirements haven't changed out from under them.
If the COM objects can all run under a single user identity, that saves you one piece of grief. Beyond that, you may simply have to make sure there is only one instance of a given object at a time, and that all access to it is serialized. Use a SyncLock statement in VB.NET for this.
The ultimate solution would be to do a "Test-driven port" of the code. I would use the existing codebase to create automated unit tests (using [vbunit](http://www.vbunit.com/), maybe). Once a piece of code has adequate unit test coverage, you can port that code (still as a COM object) to VB.NET. The unit tests can be used to confirm that the port is still working.
Such a port may not be as tough as you may think. "Copy and paste and fix the compiler errors" works fairly well between VB6 and VB.NET. There are even tools to help out. But it's the automated tests that make this practical. Otherwise, you'd have reasonable fears of how well the port was done.
Note that the new COM objects should still be usable by the original VB6 code. That should be a test, in fact.
Note also that this would be a good opportunity to document the code being ported, so that this is less of a problem in another ten years. Just don't lose the documentation! | Can I stop a COM dll from displaying forms? | [
"",
"c#",
".net",
"com",
"vb6",
"interop",
""
] |
I've implementation of UnaryOperation like this
```
struct Converter
{
Converter( std::size_t value ):
value_( value ), i_( 0 )
{}
std::string operator() ( const std::string& word )
{
return ( value_ & ( 1 << i_++ ) ) ?
word:
std::string( word.size(), ' ' );
}
std::size_t value_;
std::size_t i_;
};
```
And I use it like
```
std::vector v;
// initialization of v
std::transform( v.begin(), v.end(),
std::back_inserter( result ),
Converter( data ) );
```
My **question** is can I rely on my assumption that algorithm will call my 'Converter operator ()' in the order that 'Converter::i\_' will correspond to number of element in 'v'.
Please quote the standard in case I can't rely on the order or put the stl-like solution that avoid possible problem if any.
Thanks.
**Edit:**
I am aware of "no Side effect" requirements in the standard for the transform algorithm. I can't find what is exactly "side effect" for functors in the same standard.
Maybe there is some good-looking-boost-like solution for this task? | Qute from standard:
> 25.2.3 Transform [lib.alg.transform]
> Requires:
> op and binary\_op shall not have any side effects.
[Side Effect ( wikipedia definition )](http://en.wikipedia.org/wiki/Side_effect_(computer_science))
In your case we have next side effect:
```
Converter c( data );
c( some_const_value ) != c( some_const_value );
```
You don't have any guarantees for your algorithms, but I belive that it will works on almost all stl implementations.
**Suggested solution**
It seems I know one way to do what you need:
use boost::counting\_iterator - for iterate over two containers;
it will looks like:
```
bool bit_enabled( size_t data, unsigned char number )
{
return ( data & 1 << number ) != 0;
}
std::string select_word(
const std::string& word,
size_t data,
size_t number )
{
return bit_enabled( data, number ) ? word : std::string( ' ', word.length() );
}
const size_t data = 7;
const boost::array< std::string, 3 > vocabulary = { "a", "b", "c" };
std::vector< std::string > result;
std::transform(
vocabulary.begin(),
vocabulary.end(),
boost::counting_iterator< size_t >(0),
back_inserter( result ),
boost::bind( &select_word, _1, data, _2 )
);
```
Also maybe if you will define bit iterator or will use some bit container you will can use boost::zip\_iterator for iterate both containers.
**EDIT:**
Yestarday I found [interest article](http://www.ddj.com/cpp/184403769) which contain definition of Side Effect by standard.
> The Standard defines a side effect as
> follows: Accessing an object
> designated by a volatile lvalue,
> modifying an object, calling a library
> I/O function, or calling a function
> that does any of those operations are
> all side effects, which are changes in
> the state of the execution
> environment.
**EDIT:**
I hope it will be latest edit.
I am always tought that "no have side effect" mean:
f(a) should be equal f(a) always. ( f independed from execution environment: memory/cpu/global variables/member variables as in your case etc).
"Not produce side effect" mean - don't changing execution environment.
But in c++ standard we have more low-level defintion for Side effect.
Thing what you do in your example named as **Stateful** functor.
Standard doesn't say about "Statefull" functors, but also doesn't say about count of copies of your functor - you couldn't use this trick because it is unspecified behavior.
See Standard Library Issues list ( similar issue for predicat ):
<http://anubis.dkuug.dk/jtc1/sc22/wg21/docs/lwg-active.html#92> | I've just checked the standard and if I understand it correctly the answer is no. The description of 'transform' has the following additional requirement (25.2.3):
> **Requires**: op and binary\_op shall not have any side effects.
Reaching back into the depths of my memory, I remember a talk given [Nicolai Josuttis](http://www.josuttis.com/) at an [ACCU](http://accu.org/) conference, where he showed that for a particular type of container and STL implementation, the function object was copied. [Éric](https://stackoverflow.com/users/59781/201ric-malenfant) provided [this](http://www.ddj.com/cpp/184403769) link to a Dr. Dobb's article that discusses the differences in more detail.
**EDIT:** Alternative solution:
The *for\_each* algorithm does not have this restriction, so you could change your Converter object to take a reference to the result vector and do the push\_back inside the Converter function.
```
struct Converter
{
Converter( std::size_t value, std::vector<std::string> & result ):
value_( value ), i_( 0 ), result_(result)
{}
void operator() ( const std::string& word )
{
result_.push_back ( value_ & ( 1 << i_++ ) ) ?
word:
std::string( word.size(), ' ' );
}
std::size_t value_;
std::size_t i_;
std::vector<std::string> & result_;
};
```
And use *for\_each* rather than *transform*:
```
std::vector v;
// initialization of v
std::for_each ( v.begin()
, v.end(),
Converter( data, result ) );
``` | C++ std::transform side effect | [
"",
"c++",
"stl",
""
] |
How do I read / write gzipped files in C++?
The `iostream` wrapper classes [here](http://www-d0.fnal.gov/d0dist/dist/packages/lm_access/devel/lm_access/gzstream.hpp) look good, and here is a simple usage example:
```
gz::igzstream in(filename);
std::string line;
while(std::getline(in, line)){
std::cout << line << std::endl;
}
```
But I wasn't able to actually link it (although I have a `/usr/lib/libz.a`). A simple
```
g++ test-gzstream.cpp -lz
```
didn't do it (`undefined reference to gz::gzstreambase::~gzstreambase()`). | Obviously you need the cpp-file where the gzstreambase destructor is defined as well, i.e. [gzstream.cpp](http://www.cs.unc.edu/Research/compgeom/gzstream/#inst) (that's the link fault). libz is just a c-api for gzip, it knows nothing of c++ stdlib streams.
Boost's iostream lib has gzip and bzip2 streams too.
EDIT: Updated the link to point to the latest version of the code that includes a major bug fix. | Consider using the Boost zip filters. According to them, it supports `bzip`, `gzip` and `zlib` format.
* [boost zlib](http://www.boost.org/doc/libs/1_38_0/libs/iostreams/doc/classes/zlib.html)
* [boost gzip](http://www.boost.org/doc/libs/1_38_0/libs/iostreams/doc/classes/gzip.html)
* [boost bzip2](http://www.boost.org/doc/libs/1_38_0/libs/iostreams/doc/classes/bzip2.html) | How do I read / write gzipped files in C++? | [
"",
"c++",
"gzip",
"zlib",
"gzipstream",
""
] |
I'm selecting a value out of a table that can either be an integer or a nvarchar. It's stored as nvarchar. I want to conditionally call a function that will convert this value if it is an integer (that is, if it can be converted into an integer), otherwise I want to select the nvarchar with no conversion.
This is hitting a SQL Server 2005 database.
```
select case
when T.Value (is integer) then SomeConversionFunction(T.Value)
else T.Value
end as SomeAlias
from SomeTable T
```
Note that it is the "(is integer)" part that I'm having trouble with. Thanks in advance.
**UPDATE**
Check the comment on Ian's answer. It explains the why and the what a little better. Thanks to everyone for their thoughts. | ```
select case
when ISNUMERIC(T.Value) then T.Value
else SomeConversionFunction(T.Value)
end as SomeAlias
```
Also, have you considered using the sql\_variant data type? | The result set can only have one type associated with it for each column, you will get an error if the first row converts to an integer and there are strings that follow:
Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the nvarchar value 'word' to data type int.
try this to see:
```
create table testing
(
strangevalue nvarchar(10)
)
insert into testing values (1)
insert into testing values ('word')
select * from testing
select
case
when ISNUMERIC(strangevalue)=1 THEN CONVERT(int,strangevalue)
ELSE strangevalue
END
FROM testing
```
best bet is to return two columns:
```
select
case
when ISNUMERIC(strangevalue)=1 THEN CONVERT(int,strangevalue)
ELSE NULL
END AS StrangvalueINT
,case
when ISNUMERIC(strangevalue)=1 THEN NULL
ELSE strangevalue
END AS StrangvalueString
FROM testing
```
or your application can test for numeric and do your special processing. | Conditionally branching in SQL based on the type of a variable | [
"",
"sql",
"sql-server",
"sql-server-2005",
"t-sql",
""
] |
I got a table (in file) which I split into blocks by spaces.
I need structure like this:
```
-----------------------------
|21|22|23|33|3323|
|32|32|
|434433|545454|5454|
------------------------------
```
It's more like each row is its own table. How should I do this?
I tried `List<List<string>> matrix = new List<List<string>>()`; but I can't seem to find a way to work with it.
**EDIT** - can someone tell me what's wrong with this code???? Matrix[0][0] is same as matrix [1][0].. it seems that same row is added to matrix all the time, but I clear it ...
```
static ArrayList ReadFromFile(string filename)
StreamReader SR;
string S;
string[] S_split;
SR = File.OpenText(filename);
S = SR.ReadLine();
ArrayList myItems = new ArrayList();
List<List<string>> matrix = new List<List<string>>();
List<string> row = new List<string>();
while (S != null)
{
row.Clear();
S_split = S.Split(' ');
for (int i = 1; i < S_split.GetLength(0); i++)
{
row.Add(S_split[i]);
matrix.Add(row);
}
S = SR.ReadLine();
}
Console.WriteLine(matrix[1][1]);
SR.Close();
return myItems;
}
``` | Not sure if I understand this correctly.
```
List<List<int>> table = new List<List<int>>();
List<int> row = new List<int>();
row.Add(21);
row.Add(22);
row.Add(23);
row.Add(33); // and so on
table.Add(row);
row = new List<int>();
row.Add(1001);
row.Add(1002);
table.Add(row);
MessageBox.Show(table[0][3].ToString());
```
The program should show a message box with text "33". | You should be able to work with it as you'd expect to deal with a list within a list.
```
matrix.Add(new List<string>);
matrix[0].Add("a string");
``` | How to create mutlidimensional list for this in C#? | [
"",
"c#",
"arrays",
"list",
"multidimensional-array",
""
] |
In my template.php file I've this:
```
function myadmintheme_theme(&$existing, $type, $theme, $path) {
return array(
'node_form' => array(
'arguments' => array('form' => NULL),
'template' => 'ccktype',
),
);
}
```
And I've a ccktype.tpl.php in the same dir:
```
<b>works!</b>
```
But is not working, if I enter to node/add/ccktype I don't get the "works!" message..
I tried everything!
any help would be appreciated | The theme function you need to override is ccktype\_node\_form, not node\_form. All node forms maintained by the node module get mapped to the node\_form function for building, but they still have unique form ids. | This is the solution:
```
function myadmintheme_theme($existing, $type, $theme, $path) {
return array(
'ccktype_node_form' => array(
'arguments' => array('form' => NULL),
'template' => 'ccktype',
),
);
}
```
thanks a lot Eaton! | Theme a CCK input form in Drupal 6 | [
"",
"php",
"drupal",
"drupal-6",
"themes",
"cck",
""
] |
I have a byte array which I got back from a FileStream.Read and I would like to turn that into a string. I'm not 100% sure of the encoding - it's just a file i saved to disk - how do I do the conversion? Is there a .NET class that reads the byte order mark and can figure out the encoding for me? | If `File.ReadAllText` will read the file correctly, then you have a couple of options.
Instead of calling `BeginRead`, you could just call `File.ReadAllText` asynchronously:
```
delegate string AsyncMethodCaller(string fname);
static void Main(string[] args)
{
string InputFilename = "testo.txt";
AsyncMethodCaller caller = File.ReadAllText;
IAsyncResult rslt = caller.BeginInvoke(InputFilename, null, null);
// do other work ...
string fileContents = caller.EndInvoke(rslt);
}
```
Or you can create a `MemoryStream` from the byte array, and then use a `StreamReader` on that. | See [how-to-guess-the-encoding-of-a-file-with-no-bom-in-net](https://stackoverflow.com/questions/694923/how-to-guess-the-encoding-of-a-file-with-no-bom-in-net).
Since strings are Unicode, you **must** specify an encoding on conversion. Text streams (even `ReadAllText()` ) have an active encoding inside, usually some sensible default. | How do I convert a byte array to a string | [
"",
"c#",
".net",
""
] |
I have a python GUI app that uses a long running function from a .so/.dll it calls through ctypes.
I'm looking for a way to communicate with the function while it's running in a separate thread or process, so that I can request it to terminate early (which requires some work on the C side before returning a partial result). I suppose this will need some kind of signal receiving or reading from pipes, but I want to keep it as simple as possible.
What would you consider the best approach to solve this kind of problem? I am able to change the code on both the python and C sides. | There's two parts you'll need to answer here: one if how to communicate between the two processes (your GUI and the process executing the function), and the other is how to change your function so it responds to asynchronous requests ("oh, I've been told to just return whatever I've got").
Working out the answer to the second question will probably dictate the answer to the first. You could do it by signals (in which case you get a signal handler that gets control of the process, can look for more detailed instructions elsewhere, and change your internal data structures before returning control to your function), or you could have your function monitor a control interface for commands (every millisecond, check to see if there's a command waiting, and if there is, see what it is).
In the first case, you'd want ANSI C signal handling (signal(), sighandler\_t), in the second you'd probably want a pipe or similar (pipe() and select()). | You mention that you can change both the C and Python sides. To avoid having to write any sockets or signal code in C, it might be easiest to break up the large C function into 3 smaller separate functions that perform setup, a small parcel of work, and cleanup. The work parcel should be between about 1 ms and 1 second run time to strike a balance between responsiveness and low overhead. It can be tough to break up calculations into even chunks like this in the face of changing data sizes, but you would have the same challenge in a single big function that also did I/O.
Write a worker process in Python that calls those 3 functions through ctypes. Have the worker process check a [Queue](http://docs.python.org/library/queue.html) object for a message from the GUI to stop the calculation early. Make sure to use the non-blocking Queue.get\_nowait call instead of Queue.get. If the worker process finds a message to quit early, call the C clean up code and return the partial result. | communication with long running tasks in python | [
"",
"python",
"multithreading",
"process",
"ctypes",
""
] |
Is it impossible to run a web crawler on GAE along side with my app considering the I am running the free startup version? | While Google hadn't exposed scheduling, queue and background tasks API, you can do any processing only as an answer to external HTTP request. You'd need some heartbeat service that will process one item from crawler's queue at a time (not to hit GAE limits).
To do crawling from GAE, you have to split your application into queue (that stores queue data in Datastore), queue processor that will react to external HTTP heartbeat and your actual crawling logic.
You'd manually have to watch your quota usage and start heartbeat when you have spare quota, and stop if it is used up.
When Google introduces the APIs I've told in the beginning you'd have to rewrite parts that are implemented more effectively via Google API.
UPDATE: Google introduced Task Queue API some time ago. See [task queue docs for python](http://code.google.com/appengine/docs/python/taskqueue/) and [java](http://code.google.com/appengine/docs/java/taskqueue/). | App Engine code only runs in response to HTTP requests, so you can't run a persistent crawler in the background. With the upcoming release of scheduled tasks, you could write a crawler that uses that functionality, but it would be less than ideal. | Web crawlers and Google App Engine Hosted applications | [
"",
"python",
"google-app-engine",
"web-crawler",
""
] |
Is there a way in code to disable certain warnings in C# alike #pragma warning(cmd: warningsNo) in c++? | Almost precisely [the same](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives/preprocessor-pragma-warning) directive. | To disable a warning you can use `#pragma`. For example, add the following line just before the code in question:
```
#pragma warning disable RCS1194
```
The preceding example disables the warning RCS1194 which is "Implement exception constructors."
To enable the warning again, add the following after the code in question:
```
#pragma warning restore RCS1194
```
If you have more than one warning, use a comma separated list. For example:
```
#pragma warning disable RCS1021, RCS1102, RCS1194
```
Although [the documentation](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives#pragma-warning) states that the prefix `CS` is optional, the prefix `RCS` is not optional. I believe this also applies for other prefixes. My recommendation would be to always use the prefix to be on the safe side. | C# disable warning | [
"",
"c#",
"suppress-warnings",
""
] |
I'm trying to host my service with IIS 6 but I keep get this exception.
```
Server Error in '/WebServices' Application.
--------------------------------------------------------------------------------
The type 'QS.DialogManager.Communication.IISHost.RecipientService', provided as the Service attribute value in the ServiceHost directive could not be found.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The type 'QS.DialogManager.Communication.IISHost.RecipientService', provided as the Service attribute value in the ServiceHost directive could not be found.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[InvalidOperationException: The type 'QS.DialogManager.Communication.IISHost.RecipientService', provided as the Service attribute value in the ServiceHost directive could not be found.]
System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(String constructorString, Uri[] baseAddresses) +6714599
System.ServiceModel.HostingManager.CreateService(String normalizedVirtualPath) +604
System.ServiceModel.HostingManager.ActivateService(String normalizedVirtualPath) +46
System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath) +654
[ServiceActivationException: The service '/WebServices/dm/RecipientService.svc' cannot be activated due to an exception during compilation. The exception message is: The type 'QS.DialogManager.Communication.IISHost.RecipientService', provided as the Service attribute value in the ServiceHost directive could not be found..]
System.ServiceModel.AsyncResult.End(IAsyncResult result) +15626880
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +15546921
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.ExecuteSynchronous(HttpApplication context, Boolean flowContext) +265
System.ServiceModel.Activation.HttpModule.ProcessRequest(Object sender, EventArgs e) +227
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +171
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.3082; ASP.NET Version:2.0.50727.3082
```
I have absolutely no clue except that it seems like it can't find my assemblies. The code should be correctly compiled with public classes.
Here is my .svc file:
```
<%@ ServiceHost Language="C#" Debug="true" Service="QS.DialogManager.Communication.IISHost.RecipientService" CodeBehind="RecipientService.svc.cs" %>
```
I have tried to create a very very simple service that contains just nothin too see if this would work but still the same old error shows up.
```
The type 'IISHost.Service1', provided as the Service attribute value in the ServiceHost directive could not be found.
``` | **Option One**:
This message is often due to an IIS 7 config problem. If you are used to creating a virtual directory pointing to the folder where your service resides, that no longer works. Now, you need to use the "Create Application..." option instead.
**Other Options**:
* [WCF: The type provided as the Service attribute could not be found](http://www.thejoyofcode.com/WCF_The_type_provided_as_the_Service_attribute_could_not_be_found.aspx)
* [The type , provided as the Service attribute value in the ServiceHost directive could not be found.](http://dennyonline.wordpress.com/2008/02/26/the-type-service-provided-as-the-service-attribute-value-in-the-servicehost-directive-could-not-be-found/) | The problem could also be a in a different namespace in svc file as it is in svc.cs file.
In svc file namespace must be in the following format.
```
Service="Namespace.SvcClassName"
``` | WCF, Service attribute value in the ServiceHost directive could not be found | [
"",
"c#",
"wcf",
"iis",
""
] |
I have a sql query for my SelectCommand on my SqlDataSource. It looks like the following:
```
SELECT * FROM Books WHERE BookID = @BookID
```
A TextBox feeds the @BookID parameter using an Asp:ControlParameter.
When I view the SelectCommand when stepping through the code, I see this:
```
SELECT * FROM Books WHERE BookID = @BookID
```
What I want to actually see is that if the person types in 3 in the TextBox, I want to see
```
SELECT * FROM Books WHERE BookID = 3
```
I can't figure out how to access the above though? | One way to view the actual query is by using SQL Profiler. | The query is never executed as
```
SELECT * FROM Books WHERE BookID = 3
```
It's actually the parameterised query with the parameter passed.
You can do a "Find/Replace" on the query with the related parameters to see what it would look like. | Can I get the query that was executed from the SqlDataSource? | [
"",
"c#",
"asp.net",
"sqldatasource",
""
] |
**[question update according to updated requirements]**
I've implemented following function which should return either first not null element or throw an exception.
Also could you invent more classic and shorter name like 'max', 'min', 'pair'?
```
template <typename T>
T select_first_not_empty( const T& a, const T&b )
{
static T null = T();
if ( a == null && b == null )
throw std::runtime_error( "null" );
return
a != null ? a : b;
}
int main()
{
const int a1 = 2;
const int b1 = 0;
const int* a2 = 0;
const int* b2 = new int(5);
const std::string a3 = "";
const std::string b3 = "";
std::cout << select_first_not_empty( a1, b1 ) << std::endl;
std::cout << select_first_not_empty( a2, b2 ) << std::endl;
std::cout << select_first_not_empty( a3, b3 ) << std::endl;
return 0;
}
``` | you can try do next
```
template < typename T >
T get_valuable( const T& firstValue,
const T& alternateValue,
const T& zerroValue = T() )
{
return firstValue != zerroValue ? firstValue : alternateValue;
}
// usage
char *str = "Something"; // sometimes can be NULL
std::string str2 ( get_valuable( str, "" ) );
// your function
template <typename T>
T select_first_not_empty( const T& a,
const T& b,
const T& zerroValue = T() )
{
const T result = get_valuable( a, b, zerroValue );
if ( result == zerroValue )
{
throw std::runtime_error( "null" );
}
return result;
}
``` | If the ctor for T does anything significant, it appears like you're doing it three times every time through "select\_first\_not\_empty".
Oracle calls something similar "COALESCE", if you're looking for a better name.
I'm not sure what the point is, though. If I really wanted to know whether something was set or not, I'd use nullable pointers rather than references. "NULL" is a far better indicator of the intent to not have the variable set than to use an in-band value like 0 or "". | C++ select first not null element | [
"",
"c++",
"naming",
"std",
""
] |
I have a varbinary(MAX) field in a SQL Server 2005 database. I'm trying to figure out how to insert binary data (ie. an image) into that field using PHP. I'm using ODBC for the connection to the SQL Server database. I have seen a number of examples that explain this for use with a MySql database but I have not been able to get it to work with SQL Server. Thanks. | The simple answer is: stop what you're doing.
You don't want to store binary files inside a database unless you have some very specific security issues. Instead you want to store their filenames (possibly rename the files to prevent confliction) and then store that in the database. If security is an issue, then put them in a non web folder and use your code to retrieve the file and only serve the file if the user has access to it.
Storing images or files inside a database is a waste of file space, a mis-use of databases, and not letting things do what they do best; the filesystem knows files, the database knows data. | ```
function prepareImageDBString($filepath)
{
$out = 'null';
$handle = @fopen($filepath, 'rb');
if ($handle)
{
$content = @fread($handle, filesize($filepath));
$content = bin2hex($content);
@fclose($handle);
$out = "0x".$content;
}
return $out;
}
```
usage:
```
$out = prepareImageDBString('/img/myimg.png');
mssql_query("INSERT INTO MyTable(MyImage) VALUES($out) ");
```
MyImage is SQL Server field where the type is image | Insert binary data into SQL Server using PHP | [
"",
"php",
"sql-server",
"odbc",
""
] |
A web service is configured to expose some of its data when receiving a USR1 signal. The signal will be sent by a xinetd server when it receives a request from a remote client, e.g. nc myserver 50666. When the web server receives USR1 signal, it opens a dedicated fifo pipe, writes its data to the pipe, and then close the pipe. In the meantime, the xinetd server reads the pipe and feeds to the remote client.
In most of times, they work nicely but occasionally, for some reason, the client will receive dup records. From the log, it seems like the pipe did not get closed properly and the cache is leftover, so when next time it serves, both previous and current are sent to the client. The problem is its not constantly happening when trying to reproduce, unluckily, I wasn't able to reproduce once.
The following are the simple snippets to demonstrate the process:
The web server: (webserver.py)
```
def SendStream(data, pipe):
try:
for i in data:
pipe.write(i + '\n')
pipe.flush()
finally:
pipe.close()
def Serve():
threading.Thread(target=SendStream, args=(data, pipe)).start()
```
The xinetd.d server: (spitter.py)
```
def Serve():
if not os.path.exists(PIPE_FILE):
os.mkfifo(PIPE_FILE)
os.kill(server_pid, signal.SIGUSR1)
for i in open(PIPE_FILE):
print i,
```
So what exactly happened to cause the dup? How to trigger it? The current fix I unlink the pipe file and recreate it every time to avoid any leftovers but I don't know if that's a proper solution. | If you get two copies of splitter.py running at the same time, there will be trouble and almost anything that happens to you is legal. Try adding a process id value to webserver.py, ie:
pipe.write(str(os.getpid()) + i + '\n')
That might be illuminating. | There isn't enough to debug here. You don't show how the server handles signals, or opens the pipe.
If at all possible I would recommend not using signals. They're hairy enough in C, nevermind with python's own peculiarities added on top. | How to debug a weird threaded open fifo issue? | [
"",
"python",
"multithreading",
"stream",
"fifo",
"inetd",
""
] |
What is the use of having destructor as private? | Basically, any time you want some other class to be responsible for the life cycle of your class' objects, or you have reason to prevent the destruction of an object, you can make the destructor private.
For instance, if you're doing some sort of reference counting thing, you can have the object (or manager that has been "friend"ed) responsible for counting the number of references to itself and delete it when the number hits zero. A private dtor would prevent anybody else from deleting it when there were still references to it.
For another instance, what if you have an object that has a manager (or itself) that may destroy it or may decline to destroy it depending on other conditions in the program, such as a database connection being open or a file being written. You could have a "request\_delete" method in the class or the manager that will check that condition and it will either delete or decline, and return a status telling you what it did. That's far more flexible that just calling "delete". | Such an object can never be created on the stack. Always on the heap. And deletion has to be done via a friend or a member. A product may use a single Object hierarchy and a custom memory-manager -- such scenarios may use a private dtor.
```
#include <iostream>
class a {
~a() {}
friend void delete_a(a* p);
};
void delete_a(a* p) {
delete p;
}
int main()
{
a *p = new a;
delete_a(p);
return 0;
}
``` | What is the use of having destructor as private? | [
"",
"c++",
"private",
"destructor",
""
] |
I wounder how I could use an alias in a where statement.
Example :
```
SELECT SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3) AS Col1
FROM MyTable
WHERE Col1 = 'MySearch'
```
I use MSSQL 2005 | Not possible, but you can do the following:
```
SELECT SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3) AS Col1
FROM MyTable
WHERE SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3) = 'MySearch'
```
No subqueries or hacks required | You can use "having" instead of "where".
```
SELECT
SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3) AS Col1
FROM
MyTable
HAVING
Col1 = 'MySearch'
```
Having do a "where" after execution of the query.
Be careful to use it in the right conditions to have no performance problem. | SQL Use alias in Where statement | [
"",
"sql",
""
] |
I could use some pseudo-code, or better, Python. I am trying to implement a rate-limiting queue for a Python IRC bot, and it partially works, but if someone triggers less messages than the limit (e.g., rate limit is 5 messages per 8 seconds, and the person triggers only 4), and the next trigger is over the 8 seconds (e.g., 16 seconds later), the bot sends the message, but the queue becomes full and the bot waits 8 seconds, even though it's not needed since the 8 second period has lapsed. | Here the [simplest algorithm](http://en.wikipedia.org/wiki/Token_bucket), if you want just to drop messages when they arrive too quickly (instead of queuing them, which makes sense because the queue might get arbitrarily large):
```
rate = 5.0; // unit: messages
per = 8.0; // unit: seconds
allowance = rate; // unit: messages
last_check = now(); // floating-point, e.g. usec accuracy. Unit: seconds
when (message_received):
current = now();
time_passed = current - last_check;
last_check = current;
allowance += time_passed * (rate / per);
if (allowance > rate):
allowance = rate; // throttle
if (allowance < 1.0):
discard_message();
else:
forward_message();
allowance -= 1.0;
```
There are no datastructures, timers etc. in this solution and it works cleanly :) To see this, 'allowance' grows at speed 5/8 units per seconds at most, i.e. at most five units per eight seconds. Every message that is forwarded deducts one unit, so you can't send more than five messages per every eight seconds.
Note that `rate` should be an integer, i.e. without non-zero decimal part, or the algorithm won't work correctly (actual rate will not be `rate/per`). E.g. `rate=0.5; per=1.0;` does not work because `allowance` will never grow to 1.0. But `rate=1.0; per=2.0;` works fine. | Use this decorator @RateLimited(ratepersec) before your function that enqueues.
Basically, this checks if 1/rate secs have passed since the last time and if not, waits the remainder of the time, otherwise it doesn't wait. This effectively limits you to rate/sec. The decorator can be applied to any function you want rate-limited.
In your case, if you want a maximum of 5 messages per 8 seconds, use @RateLimited(0.625) before your sendToQueue function.
```
import time
def RateLimited(maxPerSecond):
minInterval = 1.0 / float(maxPerSecond)
def decorate(func):
lastTimeCalled = [0.0]
def rateLimitedFunction(*args,**kargs):
elapsed = time.clock() - lastTimeCalled[0]
leftToWait = minInterval - elapsed
if leftToWait>0:
time.sleep(leftToWait)
ret = func(*args,**kargs)
lastTimeCalled[0] = time.clock()
return ret
return rateLimitedFunction
return decorate
@RateLimited(2) # 2 per second at most
def PrintNumber(num):
print num
if __name__ == "__main__":
print "This should print 1,2,3... at about 2 per second."
for i in range(1,100):
PrintNumber(i)
``` | What's a good rate limiting algorithm? | [
"",
"python",
"algorithm",
"message-queue",
""
] |
I have a C# project and a test project with unit tests for the main project. I want to have testable `internal` methods and I want to test them without a magical Accessor object that you can have with Visual Studio test projects. I want to use **`InternalsVisibleToAttribute`** but every time I've done it I've had to go back and look up how to do it, which I remember involves creating key files for signing the assemblies and then using `sn.exe` to get the public key and so on.
* **Is there a utility that automates the process of creating a SNK file, setting projects to sign the assemblies, extracting the public key, and applying the *InternalsVisibleTo* attribute?**
* **Is there a way to use the attribute *without* signed assemblies?** | You don't have to use signed assemblies to use `InternalsVisibleTo`. If you don't use signed assemblies, you can just enter the full name of the assembly.
So if you want to have access to `MyAssembly` in you test assembly (`MyAssembly.Test`) all you need in `AssemblyInfo.cs` for `MyAssembly` is the name of the test assembly like this:
```
[assembly: InternalsVisibleTo("CompanyName.Project.MyAssembly.Test")]
``` | Brian is right, but of course in some cases, you do have a signed assembly, and you do want to get the public key of that assembly.
Getting this key is indeed quite a hassle.
Therefore, I've done this:
I've customized my external tools in VS.NET, so that I can get the public key of the assembly of the current project with just one click of the mouse.
This is how it's done:
* In VS.NET, open the 'Tools' menu, and click on 'External Tools'
* A window that is called 'External
tools' will open
* Click on Add
* For title, type in 'Get public key'
* In 'Command', type in `C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sn.exe`
* In 'Arguments', type: `-Tp $(TargetPath)`
* Make sure you check the 'Use output
window' option
Then, you build the project, and when you click on 'Get public key', you should see the public key for this project in the output window. | Is there an easy way to use InternalsVisibleToAttribute? | [
"",
"c#",
".net",
"visual-studio",
""
] |
does anybody know what is the equivalent to SQL "INSERT OR REPLACE" clause in SQLAlchemy and its SQL expression language?
Many thanks -- honzas | I don't think (correct me if I'm wrong) INSERT OR REPLACE is in any of the SQL standards; it's an SQLite-specific thing. There is MERGE, but that isn't supported by all dialects either. So it's not available in SQLAlchemy's general dialect.
The cleanest solution is to use Session, as suggested by M. Utku. You could also use SAVEPOINTs to save, try: an insert, except IntegrityError: then rollback and do an update instead. A third solution is to write your INSERT with an OUTER JOIN and a WHERE clause that filters on the rows with nulls. | What about `Session.merge`?
```
Session.merge(instance, load=True, **kw)
```
Copy the state an instance onto the persistent instance with the same identifier.
If there is no persistent instance currently associated with the session, it will be loaded. Return the persistent instance. If the given instance is unsaved, save a copy of and return it as a newly persistent instance. The given instance does not become associated with the session. This operation cascades to associated instances if the association is mapped with cascade="merge".
from <http://www.sqlalchemy.org/docs/reference/orm/sessions.html> | SQLAlchemy - INSERT OR REPLACE equivalent | [
"",
"python",
"sqlalchemy",
""
] |
What general guidelines should I go by when considering whether I should mark a field 'not null' as opposed to just declaring everything but the primary key null?
Should 'not null' fields have DEFAULT values? | Depends on how you want your application to behave.
* First, there will never ever ever be a possible row where this value does NOT contain meaningful data, then use NOT NULL. That is, this value will always be meaningful and represent something.
* Do you want the value to always be filled out by the user or programmer in some form or fashion? Use NOT NULL without a DEFAULT
* Do you want it to be optional to users and programmers? Use NOT NULL with a DEFAULT | I think you've got 2 questions there:
Should you mark fields as not null?
Yes, assuming that you never intend a *valid* row to have a null value in that field. Think of "not null" as the easiest type of constraint you can put on a field. Constraints in a database help ensure the data is kept consistent by meeting expectations.
Should not null fields have defaults?
Only when there is an obvious default. For example the Paid field of an invoices table might have a default of 0 (false). In general it works the other way around - if a field has a default value, then it should probably also be not null.
Don't create defaults just for the sake of defaults - if a field should not be null, but there isn't a universal default, then leave it be. That ensures that any INSERT statements must provide a value for that field. | TSQL - When to use 'not null' | [
"",
"sql",
"sql-server",
""
] |
I have a 2 column table in a database 1,000 rows long(All integer data).
The display will allow for the user to delete a certain range of data from the table.
What I am looking for is a creative way to display all the data so the user can get to different parts of it really fast. Maybe displaying different chunks at once, represent with bar graphs or zooming the scope in/out would be really cool.
Any ideas,suggestions, examples at all are appreciated. Please just throw them out here for brainstorming.
Note: I am limited to JS, xml, html and C
Thanks! | Use a double slider with a min and max display range. [Here](http://developer.expressionz.in/blogs/2008/10/24/mootools-slider-with-two-knobs-double-pinned-slider-with-range-indicator/) is an example of one based on MooTools. Moving the slider controls will adjust which range of values are displayed in the table. | * By mouse scroll resize the text.
* Add drag'n'drop for moving text block.
Example: user resizes it to a smaller chunk by mouse weal then moves it by using drag'n'drop.
It is possible to implement such thing with jQuery/JavaScript | Creative ideas for display large amount of text on web page | [
"",
"javascript",
"html",
"c",
"xml",
""
] |
For about a few months i'm programming ASP C#. I always program a lot code in the events and in the load event i check the querystring for valid data. This is some sample code i have in one of my projects:
```
protected void Page_Load(object sender, EventArgs e)
{
if (Controller.Manual == null)
{
Response.Redirect("login.aspx");
}
lblLocation.Text = "<a href='viewdocument.aspx'>" + Controller.Manual.Title + "</a>";
if (Request.QueryString["gchap"] != null)
{
if (Controller.IsNumeric(Request.QueryString["gchap"].ToString()))
{
genchap = Convert.ToInt32(Request.QueryString["gchap"]);
FillGeneralList();
SetChapterTitle();
}
}
if (Request.QueryString["qchap"] != null)
{
if (Controller.IsNumeric(Request.QueryString["qchap"].ToString()))
{
qualchap = Convert.ToInt32(Request.QueryString["qchap"]);
FillQualityList();
SetChapterTitle();
}
}
// Check document Id is set (did)
if (Request.QueryString["did"] != null)
{
if (Controller.IsNumeric(Request.QueryString["did"].ToString()))
{
docId = Convert.ToInt32(Request.QueryString["did"]);
DetermineView();
}
}
}
```
I know there must be a way to accomplish this on a more neat way. And this is just the load event. On other events, like click and onchange events i have similar code. I think this is spaghetti code and not well-arranged. So can you tell me how i can arrange my code?
EDIT:
What i want to know is, is there a more neat way to, let's say, fill a listbox? And where do i check whether a querystring value has valid data? Where do i check whether the (input/querystring) data is a number? And where should you put the code that validates the Querystring? Also in the load event? | I feel your pain with some of the organization issues with ASP.NET websites. I've had similar code to yours on several projects.
If you have the choice of your frameworks you might look into ASP.NET MVC. This allows you to have clear separation between the View (Html), the Controllers (All actions and business logic) and the Model (database). That way you have zero code in your codebehind files, it all stays nice and neat in controllers. | Try using TryParse ([for example](http://msdn.microsoft.com/en-us/library/f02979c7.aspx)) and you can simplify all the code that looks like
```
xx.IsNumeric(Request.QueryString["qchap"].ToString())
```
and
```
Convert.ToInt32(Request.QueryString["gchap"]);
```
and reduce the number of calls to `Request.QueryString` variables
You could try something like
**Original code**
```
if (Request.QueryString["gchap"] != null)
{
if (Controller.IsNumeric(Request.QueryString["gchap"].ToString()))
{
gchap = Convert.ToInt32(Request.QueryString["gchap"]);
FillGeneralList();
SetChapterTitle();
}
}
```
**Suggestion**
```
int? gchap; //nullable types thanks Richard :D
if (!int.TryParse(Request.QueryString["gchap"], out id)) {gchap = null};
if (gchap != null) {
FillGeneralList();
SetChapterTitle();
}
// you could make this neater with your own little method
```
Have a look at this post [How do you test your Request.QueryString[] variables?](https://stackoverflow.com/questions/349742/how-do-you-test-your-request-querystring-variables) | ASP C# How to program neat GUI code | [
"",
"c#",
"user-interface",
"refactoring",
""
] |
How effective is the CXX test framework, given that you are writing unit test cases around the code that you have written. Any bug in the code might as well get translated into a bug in the unit test code as well? Isn't it something like two negatives make a positive?
Also, the time and effort spent on CXX is at least equal to if not more than the coding effort.
Need your thoughts on this since I'm not in favor of this framework being used in my project and am looking for strong points to oppose it.
On the other hand, if you think it's beneficial, please do enlighten me :). | CXX is not very active, and writing unit test generally involves a lot of efforts. But when the first refactoring comes in, you're very grateful of the spent effort.
I've used Boost.Test & CPPUNIT. I would prefer a little bit Boost.Test, but yes, you have to write your own projects, files etc.
If you know a tool to generate your skeleton from your code, I'm all ears. :)
I would suggest that you give a try to Boost.Test and CPPUNIT. If you think there are better it will give you good rounds to oppose CXXUNIT as you will propose alternatives. | Google offers a fantastic C++ testing framework that I have used... I never used any other C++ testing framework, and had *limited* experience with Junit, and I was able to pick this up *very* quickly, as the documentation is good. It's important to use a good testing framework, because testing is too important to give up on because of frustration with the framework. Here is a link:
<http://code.google.com/p/googletest/>
Hope this helps! | CXX Test Framework for C++ | [
"",
"c++",
"unit-testing",
"cxxtest",
""
] |
I have about 50 tables with created-by and changed-by referencing the user table. When I want to delete the user, I would like to create a list of what tables this user has data in, so one can go delete/edit everything belonging to said user. Is there any way of doing this in SQL? | Not exactly sure of what you're going for here..
If you want a list of foreign keys referencing a table try this question
[How can I list all foreign keys referencing a given table in SQL Server?](https://stackoverflow.com/questions/483193/how-can-i-list-all-foreign-keys-referencing-a-given-table-in-sql-server-2005/483266) | You can use cascaded delete. | Find what Foreign keys are in use | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
In C++ OpenGL, I want to draw each pixel manually (as a texture I assume) on to a simple square primitive, or indeed 2 polygons forming a square.
I have no idea where to start, or what phrases to look for. Am I looking for texture mapping or creating textures? Most examples are to load from a file, but I dont want to do that.
I've tried reading my OpenGL Programming Guide book, but its just a maze as I'm quite new to OpenGL. Please help. | Take a close look at glTexImage2D. This is the call that loads the image in OpenGL for a 2D Texture.
glTexImage2D actually takes a raw pointer to the pixel data in the image. You can allocate memory yourself, and set the image data directly (however you want), then call this function to pass the image to OpenGL.
Once you've created the texture, you can bind it to the state so that your triangles use that texture.
There is nothing in OpenGL that directly requires images used as textures to be loaded from files. A good resource for textures can be [found in this GameDev article.](http://www.gamedev.net/reference/articles/article947.asp) | If the square you are drawing to is 2 dimensional and not rotated, you may be looking for [glDrawPixels](http://www.glprogramming.com/red/chapter08.html#name6). It allows you to draw a rectangular region of pixels directly to the buffer without using any polygons. | How to I draw pixels as a texture to a polygon in OpenGL? | [
"",
"c++",
"opengl",
"textures",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.