Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
I've recently come across this piece of JavaScript code:
```
if (",>=,<=,<>,".indexOf("," + sCompOp + ",") != -1)
```
I was intrigued, because to write this test I would have done:
```
if (/(>=|<=|<>)/.test(sCompOp))
```
Is this just a stylistic difference, or does the author of the other code know something about optimization that I don't? Or perhaps there is a different good reason to do this, or to not use regexes...?
It seems to me that using `String.indexOf()` for this is a little more difficult to read (but then, I'm quite comfortable with regular expressions), but are there instances where it might be "better" than writing an equivalent regex?
By "better" that might be quicker or more efficient, (although obviously that depends on the browser's JavaScript engine), or some other reason I'm not aware of. Can anyone enlighten me?
|
I ran some tests. The first method is slightly faster, but not by enough to make any real difference even under heavy use... *except* when `sCompOp` could potentially be a very long string. Because the first method searches a fixed-length string, its execution time is very stable no matter how long `sCompOp` gets, while the second method will potentially iterate through the entire length of `sCompOp`.
Also, the second method will potentially match invalid strings - "blah blah blah <= blah blah" satisfies the test...
Given that you're likely doing the work of parsing out the operator elsewhere, i doubt either edge case would be a problem. But even if this were not the case, a small modification to the expression would resolve both issues:
```
/^(>=|<=|<>)$/
```
---
### Testing code:
```
function Time(fn, iter)
{
var start = new Date();
for (var i=0; i<iter; ++i)
fn();
var end = new Date();
console.log(fn.toString().replace(/[\r|\n]/g, ' '), "\n : " + (end-start));
}
function IndexMethod(op)
{
return (",>=,<=,<>,".indexOf("," + op + ",") != -1);
}
function RegexMethod(op)
{
return /(>=|<=|<>)/.test(op);
}
function timeTests()
{
var loopCount = 50000;
Time(function(){IndexMethod(">=");}, loopCount);
Time(function(){IndexMethod("<=");}, loopCount);
Time(function(){IndexMethod("<>");}, loopCount);
Time(function(){IndexMethod("!!");}, loopCount);
Time(function(){IndexMethod("the quick brown foxes jumped over the lazy dogs");}, loopCount);
Time(function(){IndexMethod("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");}, loopCount);
Time(function(){RegexMethod(">=");}, loopCount);
Time(function(){RegexMethod("<=");}, loopCount);
Time(function(){RegexMethod("<>");}, loopCount);
Time(function(){RegexMethod("!!");}, loopCount);
Time(function(){RegexMethod("the quick brown foxes jumped over the lazy dogs");}, loopCount);
Time(function(){RegexMethod("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");}, loopCount);
}
timeTests();
```
Tested in IE6, FF3, Chrome 0.2.149.30
|
I doubt it is a question of performance or optimization. I would suspect the author of that code was simply not comfortable or familiar with regular expressions. Also notice how the comma-separated string isn't split apart in order to leverage object properties - possibly also a case of lack of familiarity with the language.
For example, another way of testing for an operator in a comma-separated list of allowable operators would be to split the comma-separated list of allowable operators and do a one-time initialization of an object with the operators as properties:
```
var aOps = ">=,<=,<>".split(",");
var allowableOps = {};
for (var iLoop = 0; iLoop < aOps.length; iLoop++) {
allowableOps[aOps[iLoop]] = true;
} //for
```
This small initialization overhead would likely be offset by the ability to do speedy lookups:
```
if (allowableOps[sCompOp]) { ... }
```
Of course, this could end up being slower overall, but it is arguably a cleaner approach.
|
JavaScript style/optimization: String.indexOf() v. Regex.test()
|
[
"",
"javascript",
"regex",
"optimization",
"coding-style",
""
] |
One of the things that always bugs me about using Readers and Streams in Java is that the `close()` method can throw an exception. Since it's a good idea to put the close method in a finally block, that necessitates a bit of an awkward situation. I usually use this construction:
```
FileReader fr = new FileReader("SomeFile.txt");
try {
try {
fr.read();
} finally {
fr.close();
}
} catch(Exception e) {
// Do exception handling
}
```
But I've also seen this construction:
```
FileReader fr = new FileReader("SomeFile.txt");
try {
fr.read()
} catch (Exception e) {
// Do exception handling
} finally {
try {
fr.close();
} catch (Exception e) {
// Do exception handling
}
}
```
I prefer the first construction because there's only one catch block and it just seems more elegant. Is there a reason to actually prefer the second or an alternate construction?
UPDATE: Would it make a difference if I pointed out that both `read` and `close` only throw IOExceptions? So it seems likely to me that, if read fails, close will fail for the same reason.
|
I would always go for the first example.
If close were to throw an exception (in practice that will never happen for a FileReader), wouldn't the standard way of handling that be to throw an exception appropriate to the caller? The close exception almost certainly trumps any problem you had using the resource. The second method is probably more appropriate if your idea of exception handling is to call System.err.println.
There is an issue of how far exceptions should be thrown. ThreadDeath should always be rethrown, but any exception within finally would stop that. Similarly Error should throw further than RuntimeException and RuntimeException further than checked exceptions. If you really wanted to you could write code to follow these rules, and then abstract it with the "execute around" idiom.
|
I'm afraid there's a big problem with the first example, which is that if an exception happens on or after the read, the `finally` block executes. So far so good. But what if the `fr.close()` then causes another exception to be thrown? This will "trump" the first exception (a bit like putting `return` in a `finally` block) and **you will lose all information about what actually caused the problem** to begin with.
Your finally block should use:
```
IOUtil.closeSilently(fr);
```
where this utility method just does:
```
public static void closeSilently(Closeable c) {
try { c.close(); } catch (Exception e) {}
}
```
|
Is there a preference for nested try/catch blocks?
|
[
"",
"java",
"try-catch",
""
] |
When developing distributed applications, all written in Java by the same company, would you choose Web Services or RMI? What are the pros and cons in terms of performance, loose coupling, ease of use, ...? Would anyone choose WS? Can you build a service-oriented architecture with RMI?
|
I'd try to think about it this way:
Are you going for independent services running beneath each other, and those services may be accessed by non-java applications some time in the future? Then go for web services.
Do you just want to spread parts of an application (mind the singular) over several servers? Then go for RMI and you won't have to leave the Java universe to get everything working together tightly coupled.
|
I would choose WS.
* It is unlikely that WS/RMI will be your bottleneck.
* Why to close the door for other possible technologies in the future?
* RMI might have problem if version of classes on client/server get out of sync.
And... I would most likely choose REST services.
|
What are the pros and cons of Web Services and RMI in a Java-only environment?
|
[
"",
"java",
"web-services",
"remoting",
"rmi",
""
] |
Many times, a Java app needs to connect to the Internet. The most common example happens when it is reading an XML file and needs to download its schema.
I am behind a proxy server. How can I set my JVM to use the proxy ?
|
From the Java documentation (*not* the javadoc API):
<http://download.oracle.com/javase/6/docs/technotes/guides/net/proxies.html>
Set the JVM flags `http.proxyHost` and `http.proxyPort` when starting your JVM on the command line.
This is usually done in a shell script (in Unix) or bat file (in Windows). Here's the example with the Unix shell script:
```
JAVA_FLAGS=-Dhttp.proxyHost=10.0.0.100 -Dhttp.proxyPort=8800
java ${JAVA_FLAGS} ...
```
When using containers such as JBoss or WebLogic, my solution is to edit the start-up scripts supplied by the vendor.
Many developers are familiar with the Java API (javadocs), but many times the rest of the documentation is overlooked. It contains a lot of interesting information: <http://download.oracle.com/javase/6/docs/technotes/guides/>
---
**Update :** If you do not want to use proxy to resolve some local/intranet hosts, check out the comment from @Tomalak:
> Also don't forget the http.nonProxyHosts property!
```
-Dhttp.nonProxyHosts="localhost|127.0.0.1|10.*.*.*|*.example.com|etc"
```
|
To use the system proxy setup:
```
java -Djava.net.useSystemProxies=true ...
```
Or programatically:
```
System.setProperty("java.net.useSystemProxies", "true");
```
Source: <http://docs.oracle.com/javase/7/docs/api/java/net/doc-files/net-properties.html>
|
How do I set the proxy to be used by the JVM
|
[
"",
"java",
"proxy",
"jvm",
""
] |
I am going through John Resig's excellent [Advanced javascript tutorial](http://ejohn.org/apps/learn/#47) and I do not thoroughly understand what's the difference between the following calls: (please note that 'arguments' is a builtin javascript word and is not exactly an array hence the hacking with the Array.slice instead of simply calling arguments.slice)
```
>>> arguments
[3, 1, 2, 3]
>>> Array.slice.call( arguments )
3,1,2,3 0=3 1=1 2=2 3=3
>>> Array.slice.call( arguments, 1 )
[]
>>> Array().slice.call( arguments )
3,1,2,3 0=3 1=1 2=2 3=3
>>> Array().slice.call( arguments, 1 )
1,2,3 0=1 1=2 2=3
```
Basically my misunderstanding boils down to the difference between Array.slice and Array().slice. What exactly is the difference between these two and why does not Array.slice.call behave as expected? (which is giving back all but the first element of the arguments list).
|
Not quite.
Watch what happens when you call String.substring.call("foo", 1) and String().substring.call("foo", 2):
```
>>> String.substring.call("foo", 1)
"1"
>>> String().substring.call("foo", 1)
"oo"
```
Array.slice is *neither* properly referencing the slice function attached to the Array prototype nor the slice function attached to any instantiated Array instance (such as Array() or []).
The fact that Array.slice is even non-null at all is an incorrect implementation of the object (/function/constructor) itself. **Try running the equivalent code in IE and you'll get an error that Array.slice is null**.
This is why Array.slice does not behave correctly (nor does String.substring).
Proof (the following is something one should never expect based on the definition of slice()...just like substring() above):
```
>>> Array.slice.call([1,2], [3,4])
3,4
```
Now, if you properly call slice() on either an instantiated object *or* the Array prototype, you'll get what you expect:
```
>>> Array.prototype.slice.call([4,5], 1)
[5]
>>> Array().slice.call([4,5], 1)
[5]
```
More proof...
```
>>> Array.prototype.slice == Array().slice
true
>>> Array.slice == Array().slice
false
```
|
Array is just a function, albeit a special one (used to initialize arrays). Array.slice is a reference to the slice() function in the Array prototype. It can only be called on an array object and not on the Constructor (i.e. Array) itself. Array seems to behave specially though, as Array() returns an empty array. This doesn't seem to work for non-builtin Constructor functions (there you have to use new). So
```
Array().slice.call
```
is the same as
```
[].slice.call
```
|
Difference between Array.slice and Array().slice
|
[
"",
"javascript",
"arrays",
""
] |
So, I have a nice domain model built. Repositories handle the data access and what not. A new requirements has popped up that indicates that reasons need to be logged with deletes. Up until now, deletes have been fairly simple => Entity.Children.Remove(child). No internal change tracking was happening as my ORM tool was handling state management. However, I'm not sure exactyl how to handle this.
1) I could keep a deleted children collection in the parent entity and pull the change tracking out of nHibernate and handle it myself.
2) ??????
|
Ok, this sounds crazy and I'm going to take another shot at this -- even though I might be spanked for bad nHibernate usage. Before you delete, why don't you select the children that are going to be deleted (you already have their ids correct?) and do a transformation into whatever entity your going to be using to log your deletes to a table. Add the reason to the entities and save them -- then proceed with your deletes. Best part, you can use a generic entity i.e. "auditInfo" for the result of the transformation, and you can do it within a transaction so you can rollback everything if something fails! OK, maybe crazy but creative right?
|
If deletes are relatively rare for that particular entity type, I would add a flag to the entity to mark it as logically "deleted" rather than actually deleting the row. The application would then have to handle the hiding of these entities under normal circumstances.
If this would cause an unacceptable number of "stale" rows - I would suggest something similar to Watson's answer. Depending on the exact requirements, you could probably get away with logging the deleted data and an extra "reason" field somewhere directly from the application. Using interceptors is more transparent and more pleasing from an auditing point of view, but a separate deletion log (table, database, file) is probably simpler.
|
Domain Driven Design - Logical Deletes
|
[
"",
"c#",
".net",
"nhibernate",
"domain-driven-design",
"ddd-repositories",
""
] |
Suppose I have a LimitedValue class which holds a value, and is parameterized on int types 'min' and 'max'. You'd use it as a container for holding values which can only be in a certain range. You could use it such:
```
LimitedValue< float, 0, 360 > someAngle( 45.0 );
someTrigFunction( someAngle );
```
so that 'someTrigFunction' knows that it is guaranteed to be supplied a valid input (The constructor would throw an exception if the parameter is invalid).
Copy-construction and assignment are limited to exactly equal types, though. I'd like to be able to do:
```
LimitedValue< float, 0, 90 > smallAngle( 45.0 );
LimitedValue< float, 0, 360 > anyAngle( smallAngle );
```
and have that operation checked at compile-time, so this next example gives an error:
```
LimitedValue< float, -90, 0 > negativeAngle( -45.0 );
LimitedValue< float, 0, 360 > postiveAngle( negativeAngle ); // ERROR!
```
Is this possible? Is there some practical way of doing this, or any examples out there which approach this?
|
You can do this using templates -- try something like this:
```
template< typename T, int min, int max >class LimitedValue {
template< int min2, int max2 >LimitedValue( const LimitedValue< T, min2, max2 > &other )
{
static_assert( min <= min2, "Parameter minimum must be >= this minimum" );
static_assert( max >= max2, "Parameter maximum must be <= this maximum" );
// logic
}
// rest of code
};
```
|
OK, this is C++11 with no Boost dependencies.
Everything guaranteed by the type system is checked at compile time, and anything else throws an exception.
I've added `unsafe_bounded_cast` for conversions that *may* throw, and `safe_bounded_cast` for explicit conversions that are statically correct (this is redundant since the copy constructor handles it, but provided for symmetry and expressiveness).
## Example Use
```
#include "bounded.hpp"
int main()
{
BoundedValue<int, 0, 5> inner(1);
BoundedValue<double, 0, 4> outer(2.3);
BoundedValue<double, -1, +1> overlap(0.0);
inner = outer; // ok: [0,4] contained in [0,5]
// overlap = inner;
// ^ error: static assertion failed: "conversion disallowed from BoundedValue with higher max"
// overlap = safe_bounded_cast<double, -1, +1>(inner);
// ^ error: static assertion failed: "conversion disallowed from BoundedValue with higher max"
overlap = unsafe_bounded_cast<double, -1, +1>(inner);
// ^ compiles but throws:
// terminate called after throwing an instance of 'BoundedValueException<int>'
// what(): BoundedValueException: !(-1<=2<=1) - BOUNDED_VALUE_ASSERT at bounded.hpp:56
// Aborted
inner = 0;
overlap = unsafe_bounded_cast<double, -1, +1>(inner);
// ^ ok
inner = 7;
// terminate called after throwing an instance of 'BoundedValueException<int>'
// what(): BoundedValueException: !(0<=7<=5) - BOUNDED_VALUE_ASSERT at bounded.hpp:75
// Aborted
}
```
## Exception Support
This is a bit boilerplate-y, but gives fairly readable exception messages as above (the actual min/max/value are exposed as well, if you choose to catch the derived exception type and can do something useful with it).
```
#include <stdexcept>
#include <sstream>
#define STRINGIZE(x) #x
#define STRINGIFY(x) STRINGIZE( x )
// handling for runtime value errors
#define BOUNDED_VALUE_ASSERT(MIN, MAX, VAL) \
if ((VAL) < (MIN) || (VAL) > (MAX)) { \
bounded_value_assert_helper(MIN, MAX, VAL, \
"BOUNDED_VALUE_ASSERT at " \
__FILE__ ":" STRINGIFY(__LINE__)); \
}
template <typename T>
struct BoundedValueException: public std::range_error
{
virtual ~BoundedValueException() throw() {}
BoundedValueException() = delete;
BoundedValueException(BoundedValueException const &other) = default;
BoundedValueException(BoundedValueException &&source) = default;
BoundedValueException(int min, int max, T val, std::string const& message)
: std::range_error(message), minval_(min), maxval_(max), val_(val)
{
}
int const minval_;
int const maxval_;
T const val_;
};
template <typename T> void bounded_value_assert_helper(int min, int max, T val,
char const *message = NULL)
{
std::ostringstream oss;
oss << "BoundedValueException: !("
<< min << "<="
<< val << "<="
<< max << ")";
if (message) {
oss << " - " << message;
}
throw BoundedValueException<T>(min, max, val, oss.str());
}
```
## Value Class
```
template <typename T, int Tmin, int Tmax> class BoundedValue
{
public:
typedef T value_type;
enum { min_value=Tmin, max_value=Tmax };
typedef BoundedValue<value_type, min_value, max_value> SelfType;
// runtime checking constructor:
explicit BoundedValue(T runtime_value) : val_(runtime_value) {
BOUNDED_VALUE_ASSERT(min_value, max_value, runtime_value);
}
// compile-time checked constructors:
BoundedValue(SelfType const& other) : val_(other) {}
BoundedValue(SelfType &&other) : val_(other) {}
template <typename otherT, int otherTmin, int otherTmax>
BoundedValue(BoundedValue<otherT, otherTmin, otherTmax> const &other)
: val_(other) // will just fail if T, otherT not convertible
{
static_assert(otherTmin >= Tmin,
"conversion disallowed from BoundedValue with lower min");
static_assert(otherTmax <= Tmax,
"conversion disallowed from BoundedValue with higher max");
}
// compile-time checked assignments:
BoundedValue& operator= (SelfType const& other) { val_ = other.val_; return *this; }
template <typename otherT, int otherTmin, int otherTmax>
BoundedValue& operator= (BoundedValue<otherT, otherTmin, otherTmax> const &other) {
static_assert(otherTmin >= Tmin,
"conversion disallowed from BoundedValue with lower min");
static_assert(otherTmax <= Tmax,
"conversion disallowed from BoundedValue with higher max");
val_ = other; // will just fail if T, otherT not convertible
return *this;
}
// run-time checked assignment:
BoundedValue& operator= (T const& val) {
BOUNDED_VALUE_ASSERT(min_value, max_value, val);
val_ = val;
return *this;
}
operator T const& () const { return val_; }
private:
value_type val_;
};
```
## Cast Support
```
template <typename dstT, int dstMin, int dstMax>
struct BoundedCastHelper
{
typedef BoundedValue<dstT, dstMin, dstMax> return_type;
// conversion is checked statically, and always succeeds
template <typename srcT, int srcMin, int srcMax>
static return_type convert(BoundedValue<srcT, srcMin, srcMax> const& source)
{
return return_type(source);
}
// conversion is checked dynamically, and could throw
template <typename srcT, int srcMin, int srcMax>
static return_type coerce(BoundedValue<srcT, srcMin, srcMax> const& source)
{
return return_type(static_cast<srcT>(source));
}
};
template <typename dstT, int dstMin, int dstMax,
typename srcT, int srcMin, int srcMax>
auto safe_bounded_cast(BoundedValue<srcT, srcMin, srcMax> const& source)
-> BoundedValue<dstT, dstMin, dstMax>
{
return BoundedCastHelper<dstT, dstMin, dstMax>::convert(source);
}
template <typename dstT, int dstMin, int dstMax,
typename srcT, int srcMin, int srcMax>
auto unsafe_bounded_cast(BoundedValue<srcT, srcMin, srcMax> const& source)
-> BoundedValue<dstT, dstMin, dstMax>
{
return BoundedCastHelper<dstT, dstMin, dstMax>::coerce(source);
}
```
|
Limiting range of value types in C++
|
[
"",
"c++",
"templates",
""
] |
I have little knowledge of Flash but for a little Flash game I have to store score and successful tries of users in a database using PHP. Now the Flash runs locally on the users computer and connects to a remote server. How can I secure against manipulation of game scores. Is there any best practice for this use case?
|
You might want to check these other questions:
* Q46415 [Passing untampered data from Flash app to server?](https://stackoverflow.com/questions/46415/)
* Q73947 [What is the best way to stop people hacking the PHP-based highscore table of a Flash game.](https://stackoverflow.com/questions/73947/)
* Q25999 [Secure Online Highscore Lists for Non-Web Games](https://stackoverflow.com/questions/25999/)
|
What you are asking is inherently impossible. The game runs on the client and is therefore completely at the user's mercy. Only way to be sure is running a real time simulation of the game on the server based on user's input (mouse movement, keypresses), which is absolutely ridiculous.
|
Secure communication between Flash and PHP script
|
[
"",
"php",
"flash",
"security",
""
] |
I have a DataRow and I am getting one of the elements which is a Amount with a dollar sign. I am calling a toString on it. Is there another method I can call on it to remove the dollar sign if present.
**So something like:**
*dr.ToString.Substring(1, dr.ToString.Length);*
But more conditionally in case the dollar sign ever made an appearance again.
I am trying to do this with explicitly defining another string.
|
```
Convert.ToString(dr(columnName)).Replace("$", String.Empty)
```
--
If you are working with a data table, then you have to unbox the value (by default its Object) to a string, so you are already creating a string, and then another with the replacement. There is really no other way to get around it, but you will only see performance differences when dealing with tens of thousands of operations.
|
You could also use
```
string trimmed = (dr as string).Trim('$');
```
or
```
string trimmed = (dr as string).TrimStart('$');
```
|
Simple way to trim Dollar Sign if present in C#
|
[
"",
"c#",
""
] |
I have a class that defines the names of various session attributes, e.g.
```
class Constants {
public static final String ATTR_CURRENT_USER = "current.user";
}
```
I would like to use these constants within a JSP to test for the presence of these attributes, something like:
```
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="com.example.Constants" %>
<c:if test="${sessionScope[Constants.ATTR_CURRENT_USER] eq null}">
<%-- Do somthing --%>
</c:if>
```
But I can't seem to get the sytax correct. Also, to avoid repeating the rather lengthy tests above in multiple places, I'd like to assign the result to a local (page-scoped) variable, and refer to that instead. I believe I can do this with `<c:set>`, but again I'm struggling to find the correct syntax.
**UPDATE:** Further to the suggestion below, I tried:
```
<c:set var="nullUser" scope="session"
value="${sessionScope[Constants.ATTR_CURRENT_USER] eq null}" />
```
which didn't work. So instead, I tried substituting the literal value of the constant. I also added the constant to the content of the page, so I could verify the constant's value when the page is being rendered
```
<c:set var="nullUser" scope="session"
value="${sessionScope['current.user'] eq null}" />
<%= "Constant value: " + WebHelper.ATTR_CURRENT_PARTNER %>
```
This worked fine and it printed the expected value "current.user" on the page. I'm at a loss to explain why using the String literal works, but a reference to the constant doesn't, when the two appear to have the same value. Help.....
|
It's not working in your example because the `ATTR_CURRENT_USER` constant is not visible to the JSTL tags, which expect properties to be exposed by getter functions. I haven't tried it, but the cleanest way to expose your constants appears to be the [unstandard tag library](http://jakarta.apache.org/taglibs/sandbox/doc/unstandard-doc/index.html#useConstants "Unstandard tag library from Apache").
ETA: Old link I gave didn't work. New links can be found in this answer: [Java constants in JSP](https://stackoverflow.com/questions/127328/java-constants-in-jsp)
Code snippets to clarify the behavior you're seeing:
Sample class:
```
package com.example;
public class Constants
{
// attribute, visible to the scriptlet
public static final String ATTR_CURRENT_USER = "current.user";
// getter function;
// name modified to make it clear, later on,
// that I am calling this function
// and not accessing the constant
public String getATTR_CURRENT_USER_FUNC()
{
return ATTR_CURRENT_USER;
}
}
```
Snippet of the JSP page, showing sample usage:
```
<%-- Set up the current user --%>
<%
session.setAttribute("current.user", "Me");
%>
<%-- scriptlets --%>
<%@ page import="com.example.Constants" %>
<h1>Using scriptlets</h1>
<h3>Constants.ATTR_CURRENT_USER</h3>
<%=Constants.ATTR_CURRENT_USER%> <br />
<h3>Session[Constants.ATTR_CURRENT_USER]</h3>
<%=session.getAttribute(Constants.ATTR_CURRENT_USER)%>
<%-- JSTL --%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<jsp:useBean id="cons" class="com.example.Constants" scope="session"/>
<h1>Using JSTL</h1>
<h3>Constants.getATTR_CURRENT_USER_FUNC()</h3>
<c:out value="${cons.ATTR_CURRENT_USER_FUNC}"/>
<h3>Session[Constants.getATTR_CURRENT_USER_FUNC()]</h3>
<c:out value="${sessionScope[cons.ATTR_CURRENT_USER_FUNC]}"/>
<h3>Constants.ATTR_CURRENT_USER</h3>
<c:out value="${sessionScope[Constants.ATTR_CURRENT_USER]}"/>
<%--
Commented out, because otherwise will error:
The class 'com.example.Constants' does not have the property 'ATTR_CURRENT_USER'.
<h3>cons.ATTR_CURRENT_USER</h3>
<c:out value="${sessionScope[cons.ATTR_CURRENT_USER]}"/>
--%>
<hr />
```
This outputs:
# Using scriptlets
### Constants.ATTR\_CURRENT\_USER
current.user
### Session[Constants.ATTR\_CURRENT\_USER]
Me
---
# Using JSTL
### Constants.getATTR\_CURRENT\_USER\_FUNC()
current.user
### Session[Constants.getATTR\_CURRENT\_USER\_FUNC()]
Me
### Constants.ATTR\_CURRENT\_USER
---
|
You can define Constants.ATTR\_CURRENT\_USER as a variable with c:set,just as below:
```
<c:set var="ATTR_CURRENT_USER" value="<%=Constants.ATTR_CURRENT_USER%>" />
<c:if test="${sessionScope[ATTR_CURRENT_USER] eq null}">
<%-- Do somthing --%>
</c:if>
```
|
accessing constants in JSP (without scriptlet)
|
[
"",
"java",
"jsp",
"session",
"jstl",
""
] |
I am trying to uncompress some data created in VB6 using the zlib API.
I have read this is possible with the qUncompress function:
<http://doc.trolltech.com/4.4/qbytearray.html#qUncompress>
I have read the data in from QDataStream via readRawBytes into a char
array, which I then converted to a QByteArray for decompression. I
have the compressed length and the expected decompressed length but am not getting
anything back from qUncompress.
However I need to prepend the expected decompressed length in big endian format. Has anybody done this and have an example?
|
I haven't used VB6 in *ages*, so I hope this is approximately correct. I *think* that vb6 used () for array indexing. If I got anything wrong, please let me know.
Looking at the qUncompress docs, you should have put your data in your QByteArray starting at byte 5 (I'm going to assume that you left the array index base set to 1 for this example).
Let's say the array is named qArr, and the expected uncompressed size is Size.
In a "big-endian" representation, the first byte is at the first address.
```
qArr(1) = int(Size/(256*256*256))
qArr(2) = 255 And int(Size/256*256)
qArr(3) = 255 And int(Size/256)
qArr(4) = 255 And int(Size)
```
Does that make sense?
If you needed little endian, you could just reverse the order of the indexes (qArr(4) - qArr(1)) and leave the calculations the same.
|
This is how I can convert arbitary data from one format to another.
```
Private Type LongByte
H1 As Byte
H2 As Byte
L1 As Byte
L2 As Byte
End Type
Private Type LongType
L As Long
End Type
Function SwapEndian(ByVal LongData as Long) as Long
Dim TempL As LongType
Dim TempLB As LongByte
Dim TempVar As Long
TempL.L = LongData
LSet TempLB = TempL
'Swap is a subroutine I wrote to swap two variables
Swap TempLB.H1, TempLB.L2
Swap TempLB.H2, TempLB.L1
LSet TempL = TempLB
TempVar = TempL.L
SwapEndian = TempVar
End Function
```
If you are dealing with FileIO then you can use the Byte fields of TempLB
The trick is using LSET an obscure command of VB6
If you are using .NET then doing the process is much easier. Here the trick is using a MemoryStream to retrieve and set the individual bytes. Now you could do math for int16/int32/int64. But if you are dealing with with floating point data, using LSET or the MemoryStream is much clearer and easier to debug.
If you are using Framework version 1.1 or beyond then you have the BitConvertor Class which uses arrays of bytes.
```
Private Structure Int32Byte
Public H1 As Byte
Public H2 As Byte
Public L1 As Byte
Public L2 As Byte
Public Function Convert() As Integer
Dim M As New MemoryStream()
Dim bR As IO.BinaryReader
Dim bW As New IO.BinaryWriter(M)
Swap(H1, L2)
Swap(H2, L1)
bW.Write(H1)
bW.Write(H2)
bW.Write(L1)
bW.Write(L2)
M.Seek(0, SeekOrigin.Begin)
bR = New IO.BinaryReader(M)
Convert = bR.ReadInt32()
End Function
End Structure
```
|
How to convert a number to a bytearray in bit endian order
|
[
"",
"c++",
"qt",
"vb6",
"compression",
"endianness",
""
] |
I wrote some code with a lot of recursion, that takes quite a bit of time to complete. Whenever I "pause" the run to look at what's going on I get:
> > Cannot evaluate expression because the code of the current method is optimized.
I think I understand what that means. However, what puzzles me is that after I hit step, the code is not "optimized" anymore, and I can look at my variables. How does this happen? How can the code flip back and forth between optimized and non-optimzed code?
|
The Debugger uses FuncEval to allow you to "look at" variables. FuncEval requires threads to be stopped in managed code at a GarbageCollector safe point. Manually "pausing" the run in the IDE causes all threads to stop as soon as possible. Your highly recursive code will tend to stop at an unsafe point. Hence, the debugger is unable to evaluate expressions.
Pressing F10 will move to the next Funceval Safe point and will enable function evaluation.
For further information review the [rules of FuncEval](http://blogs.msdn.com/jmstall/archive/2005/11/15/funceval-rules.aspx).
|
While the Debug.Break() line is on top of the callstack you can't eval expressions. That's because that line is optimized. Press F10 to move to the next line - a valid line of code - and the watch will work.
|
What does "Cannot evaluate expression because the code of the current method is optimized." mean?
|
[
"",
"c#",
".net",
"debugging",
"optimization",
"compiler-construction",
""
] |
I'm trying to learn C++ so forgive me if this question demonstrates a lack of basic knowledge, you see, the fact is, I have a lack of basic knowledge.
I want some help working out how to create an iterator for a class I have created.
I have a class 'Shape' which has a container of Points.
I have a class 'Piece' which references a Shape and defines a position for the Shape.
Piece does not have a Shape it just references a Shape.
I want it to seem like Piece is a container of Points which are the same as those of the Shape it references but with the offset of the Piece's position added.
I want to be able to iterate through the Piece's Points just as if Piece was a container itself. I've done a little reading around and haven't found anything which has helped me. I would be very grateful for any pointers.
|
You should use Boost.Iterators. It contains a number of templates and concepts to implement new iterators and adapters for existing iterators. I have written [an article about this very topic](http://accu.org/index.php/journals/1527); it's in the December 2008 ACCU magazine. It discusses an (IMO) elegant solution for exactly your problem: exposing member collections from an object, using Boost.Iterators.
If you want to use the stl only, the [Josuttis book](http://www.josuttis.com/libbook/) has a chapter on implementing your own STL iterators.
|
/EDIT: I see, an own iterator is actually necessary here (I misread the question first). Still, I'm letting the code below stand because it can be useful in similar circumstances.
---
Is an own iterator actually necessary here? Perhaps it's sufficient to forward all required definitions to the container holding the actual Points:
```
// Your class `Piece`
class Piece {
private:
Shape m_shape;
public:
typedef std::vector<Point>::iterator iterator;
typedef std::vector<Point>::const_iterator const_iterator;
iterator begin() { return m_shape.container.begin(); }
const_iterator begin() const { return m_shape.container.begin(); }
iterator end() { return m_shape.container.end(); }
const_iterator end() const { return m_shape.const_container.end(); }
}
```
This is assuming you're using a `vector` internally but the type can easily be adapted.
|
Creating my own Iterators
|
[
"",
"c++",
"iterator",
""
] |
What are [metaclasses](https://docs.python.org/3/reference/datamodel.html#metaclasses)? What are they used for?
|
A metaclass is the class of a class. A class defines how an instance of the class (i.e. an object) behaves while a metaclass defines how a class behaves. A class is an instance of a metaclass.
While in Python you can use arbitrary callables for metaclasses (like [Jerub](https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python/100037#100037) shows), the better approach is to make it an actual class itself. `type` is the usual metaclass in Python. `type` is itself a class, and it is its own type. You won't be able to recreate something like `type` purely in Python, but Python cheats a little. To create your own metaclass in Python you really just want to subclass `type`.
A metaclass is most commonly used as a class-factory. When you create an object by calling the class, Python creates a new class (when it executes the 'class' statement) by calling the metaclass. Combined with the normal `__init__` and `__new__` methods, metaclasses therefore allow you to do 'extra things' when creating a class, like registering the new class with some registry or replace the class with something else entirely.
When the `class` statement is executed, Python first executes the body of the `class` statement as a normal block of code. The resulting namespace (a dict) holds the attributes of the class-to-be. The metaclass is determined by looking at the baseclasses of the class-to-be (metaclasses are inherited), at the `__metaclass__` attribute of the class-to-be (if any) or the `__metaclass__` global variable. The metaclass is then called with the name, bases and attributes of the class to instantiate it.
However, metaclasses actually define the *type* of a class, not just a factory for it, so you can do much more with them. You can, for instance, define normal methods on the metaclass. These metaclass-methods are like classmethods in that they can be called on the class without an instance, but they are also not like classmethods in that they cannot be called on an instance of the class. `type.__subclasses__()` is an example of a method on the `type` metaclass. You can also define the normal 'magic' methods, like `__add__`, `__iter__` and `__getattr__`, to implement or change how the class behaves.
Here's an aggregated example of the bits and pieces:
```
def make_hook(f):
"""Decorator to turn 'foo' method into '__foo__'"""
f.is_hook = 1
return f
class MyType(type):
def __new__(mcls, name, bases, attrs):
if name.startswith('None'):
return None
# Go over attributes and see if they should be renamed.
newattrs = {}
for attrname, attrvalue in attrs.iteritems():
if getattr(attrvalue, 'is_hook', 0):
newattrs['__%s__' % attrname] = attrvalue
else:
newattrs[attrname] = attrvalue
return super(MyType, mcls).__new__(mcls, name, bases, newattrs)
def __init__(self, name, bases, attrs):
super(MyType, self).__init__(name, bases, attrs)
# classregistry.register(self, self.interfaces)
print "Would register class %s now." % self
def __add__(self, other):
class AutoClass(self, other):
pass
return AutoClass
# Alternatively, to autogenerate the classname as well as the class:
# return type(self.__name__ + other.__name__, (self, other), {})
def unregister(self):
# classregistry.unregister(self)
print "Would unregister class %s now." % self
class MyObject:
__metaclass__ = MyType
class NoneSample(MyObject):
pass
# Will print "NoneType None"
print type(NoneSample), repr(NoneSample)
class Example(MyObject):
def __init__(self, value):
self.value = value
@make_hook
def add(self, other):
return self.__class__(self.value + other.value)
# Will unregister the class
Example.unregister()
inst = Example(10)
# Will fail with an AttributeError
#inst.unregister()
print inst + inst
class Sibling(MyObject):
pass
ExampleSibling = Example + Sibling
# ExampleSibling is now a subclass of both Example and Sibling (with no
# content of its own) although it will believe it's called 'AutoClass'
print ExampleSibling
print ExampleSibling.__mro__
```
|
# Classes as objects
Prior to delving into metaclasses, a solid grasp of Python classes is beneficial. Python holds a particularly distinctive concept of classes, a notion it adopts from the Smalltalk language.
In most languages, classes are just pieces of code that describe how to produce an object. That is somewhat true in Python too:
```
>>> class ObjectCreator(object):
... pass
>>> my_object = ObjectCreator()
>>> print(my_object)
<__main__.ObjectCreator object at 0x8974f2c>
```
But classes are more than that in Python. **Classes are objects too.**
Yes, objects.
When a Python script runs, every line of code is executed from top to bottom. When the Python interpreter encounters the `class` keyword, Python creates an **object** out of the "description" of the class that follows. Thus, the following instruction
```
>>> class ObjectCreator(object):
... pass
```
...creates an *object* with the name `ObjectCreator`!
This object (the class) is itself capable of creating objects (called *instances*).
But still, it's an object. Therefore, like all objects:
* you can assign it to a variable1
```
JustAnotherVariable = ObjectCreator
```
* you can attach attributes to it
```
ObjectCreator.class_attribute = 'foo'
```
* you can pass it as a function parameter
```
print(ObjectCreator)
```
1 Note that merely assigning it to another variable doesn't change the class's `__name__`, i.e.,
```
>>> print(JustAnotherVariable)
<class '__main__.ObjectCreator'>
>>> print(JustAnotherVariable())
<__main__.ObjectCreator object at 0x8997b4c>
```
# Creating classes dynamically
Since classes are objects, you can create them on the fly, like any object.
First, you can create a class in a function using `class`:
```
>>> def choose_class(name):
... if name == 'foo':
... class Foo(object):
... pass
... return Foo # return the class, not an instance
... else:
... class Bar(object):
... pass
... return Bar
>>> MyClass = choose_class('foo')
>>> print(MyClass) # the function returns a class, not an instance
<class '__main__.Foo'>
>>> print(MyClass()) # you can create an object from this class
<__main__.Foo object at 0x89c6d4c>
```
But it's not so dynamic, since you still have to write the whole class yourself.
Since classes are objects, they must be generated by something.
When you use the `class` keyword, Python creates this object automatically. But as
with most things in Python, it gives you a way to do it manually.
Remember the function `type`? The good old function that lets you know what
type an object is:
```
>>> print(type(1))
<class 'int'>
>>> print(type("1"))
<class 'str'>
>>> print(type(ObjectCreator))
<class 'type'>
>>> print(type(ObjectCreator()))
<class '__main__.ObjectCreator'>
```
Well, [`type`](http://docs.python.org/2/library/functions.html#type) has also a completely different ability: it can create classes on the fly. `type` can take the description of a class as parameters,
and return a class.
(I know, it's silly that the same function can have two completely different uses according to the parameters you pass to it. It's an issue due to backward
compatibility in Python)
`type` works this way:
```
type(name, bases, attrs)
```
Where:
* **`name`**: name of the class
* **`bases`**: tuple of the parent class (for inheritance, can be empty)
* **`attrs`**: dictionary containing attributes names and values
e.g.:
```
>>> class MyShinyClass(object):
... pass
```
can be created manually this way:
```
>>> MyShinyClass = type('MyShinyClass', (), {}) # returns a class object
>>> print(MyShinyClass)
<class '__main__.MyShinyClass'>
>>> print(MyShinyClass()) # create an instance with the class
<__main__.MyShinyClass object at 0x8997cec>
```
You'll notice that we use `MyShinyClass` as the name of the class
and as the variable to hold the class reference. They can be different,
but there is no reason to complicate things.
`type` accepts a dictionary to define the attributes of the class. So:
```
>>> class Foo(object):
... bar = True
```
Can be translated to:
```
>>> Foo = type('Foo', (), {'bar':True})
```
And used as a normal class:
```
>>> print(Foo)
<class '__main__.Foo'>
>>> print(Foo.bar)
True
>>> f = Foo()
>>> print(f)
<__main__.Foo object at 0x8a9b84c>
>>> print(f.bar)
True
```
And of course, you can inherit from it, so:
```
>>> class FooChild(Foo):
... pass
```
would be:
```
>>> FooChild = type('FooChild', (Foo,), {})
>>> print(FooChild)
<class '__main__.FooChild'>
>>> print(FooChild.bar) # bar is inherited from Foo
True
```
Eventually, you'll want to add methods to your class. Just define a function
with the proper signature and assign it as an attribute.
```
>>> def echo_bar(self):
... print(self.bar)
>>> FooChild = type('FooChild', (Foo,), {'echo_bar': echo_bar})
>>> hasattr(Foo, 'echo_bar')
False
>>> hasattr(FooChild, 'echo_bar')
True
>>> my_foo = FooChild()
>>> my_foo.echo_bar()
True
```
And you can add even more methods after you dynamically create the class, just like adding methods to a normally created class object.
```
>>> def echo_bar_more(self):
... print('yet another method')
>>> FooChild.echo_bar_more = echo_bar_more
>>> hasattr(FooChild, 'echo_bar_more')
True
```
You see where we are going: in Python, classes are objects, and you can create a class on the fly, dynamically.
This is what Python does when you use the keyword `class`, and it does so by using a metaclass.
# What are metaclasses (finally)
Metaclasses are the 'stuff' that creates classes.
You define classes in order to create objects, right?
But we learned that Python classes are objects.
Well, metaclasses are what create these objects. They are the classes' classes,
you can picture them this way:
```
MyClass = MetaClass()
my_object = MyClass()
```
You've seen that `type` lets you do something like this:
```
MyClass = type('MyClass', (), {})
```
It's because the function `type` is in fact a metaclass. `type` is the
metaclass Python uses to create all classes behind the scenes.
Now you wonder "why the heck is it written in lowercase, and not `Type`?"
Well, I guess it's a matter of consistency with `str`, the class that creates
strings objects, and `int` the class that creates integer objects. `type` is
just the class that creates class objects.
You see that by checking the `__class__` attribute.
Everything, and I mean everything, is an object in Python. That includes integers,
strings, functions and classes. All of them are objects. And all of them have
been created from a class:
```
>>> age = 35
>>> age.__class__
<type 'int'>
>>> name = 'bob'
>>> name.__class__
<type 'str'>
>>> def foo(): pass
>>> foo.__class__
<type 'function'>
>>> class Bar(object): pass
>>> b = Bar()
>>> b.__class__
<class '__main__.Bar'>
```
Now, what is the `__class__` of any `__class__` ?
```
>>> age.__class__.__class__
<type 'type'>
>>> name.__class__.__class__
<type 'type'>
>>> foo.__class__.__class__
<type 'type'>
>>> b.__class__.__class__
<type 'type'>
```
So, a metaclass is just the stuff that creates class objects.
You can call it a 'class factory' if you wish.
`type` is the built-in metaclass Python uses, but of course, you can create your
own metaclass.
# The [`__metaclass__`](http://docs.python.org/2/reference/datamodel.html?highlight=__metaclass__#__metaclass__) attribute
In Python 2, you can add a `__metaclass__` attribute when you write a class (see next section for the Python 3 syntax):
```
class Foo(object):
__metaclass__ = something...
[...]
```
If you do so, Python will use the metaclass to create the class `Foo`.
Careful, it's tricky.
You write `class Foo(object)` first, but the class object `Foo` is not created
in memory yet.
Python will look for `__metaclass__` in the class definition. If it finds it,
it will use it to create the object class `Foo`. If it doesn't, it will use
`type` to create the class.
Read that several times.
When you do:
```
class Foo(Bar):
pass
```
Python does the following:
Is there a `__metaclass__` attribute in `Foo`?
If yes, create in-memory a class object (I said a class object, stay with me here), with the name `Foo` by using what is in `__metaclass__`.
If Python can't find `__metaclass__`, it will look for a `__metaclass__` at the MODULE level, and try to do the same (but only for classes that don't inherit anything, basically old-style classes).
Then if it can't find any `__metaclass__` at all, it will use the `Bar`'s (the first parent) own metaclass (which might be the default `type`) to create the class object.
Be careful here that the `__metaclass__` attribute will not be inherited, the metaclass of the parent (`Bar.__class__`) will be. If `Bar` used a `__metaclass__` attribute that created `Bar` with `type()` (and not `type.__new__()`), the subclasses will not inherit that behavior.
Now the big question is, what can you put in `__metaclass__`?
The answer is something that can create a class.
And what can create a class? `type`, or anything that subclasses or uses it.
# Metaclasses in Python 3
The syntax to set the metaclass has been changed in Python 3:
```
class Foo(object, metaclass=something):
...
```
i.e. the `__metaclass__` attribute is no longer used, in favor of a keyword argument in the list of base classes.
The behavior of metaclasses however stays [largely the same](https://www.python.org/dev/peps/pep-3115/).
One thing added to metaclasses in Python 3 is that you can also pass attributes as keyword-arguments into a metaclass, like so:
```
class Foo(object, metaclass=something, kwarg1=value1, kwarg2=value2):
...
```
Read the section below for how Python handles this.
# Custom metaclasses
The main purpose of a metaclass is to change the class automatically,
when it's created.
You usually do this for APIs, where you want to create classes matching the
current context.
Imagine a stupid example, where you decide that all classes in your module
should have their attributes written in uppercase. There are several ways to
do this, but one way is to set `__metaclass__` at the module level.
This way, all classes of this module will be created using this metaclass,
and we just have to tell the metaclass to turn all attributes to uppercase.
Luckily, `__metaclass__` can actually be any callable, it doesn't need to be a
formal class (I know, something with 'class' in its name doesn't need to be
a class, go figure... but it's helpful).
So we will start with a simple example, by using a function.
```
# the metaclass will automatically get passed the same argument
# that you usually pass to `type`
def upper_attr(future_class_name, future_class_parents, future_class_attrs):
"""
Return a class object, with the list of its attribute turned
into uppercase.
"""
# pick up any attribute that doesn't start with '__' and uppercase it
uppercase_attrs = {
attr if attr.startswith("__") else attr.upper(): v
for attr, v in future_class_attrs.items()
}
# let `type` do the class creation
return type(future_class_name, future_class_parents, uppercase_attrs)
__metaclass__ = upper_attr # this will affect all classes in the module
class Foo(): # global __metaclass__ won't work with "object" though
# but we can define __metaclass__ here instead to affect only this class
# and this will work with "object" children
bar = 'bip'
```
Let's check:
```
>>> hasattr(Foo, 'bar')
False
>>> hasattr(Foo, 'BAR')
True
>>> Foo.BAR
'bip'
```
Now, let's do exactly the same, but using a real class for a metaclass:
```
# remember that `type` is actually a class like `str` and `int`
# so you can inherit from it
class UpperAttrMetaclass(type):
# __new__ is the method called before __init__
# it's the method that creates the object and returns it
# while __init__ just initializes the object passed as parameter
# you rarely use __new__, except when you want to control how the object
# is created.
# here the created object is the class, and we want to customize it
# so we override __new__
# you can do some stuff in __init__ too if you wish
# some advanced use involves overriding __call__ as well, but we won't
# see this
def __new__(
upperattr_metaclass,
future_class_name,
future_class_parents,
future_class_attrs
):
uppercase_attrs = {
attr if attr.startswith("__") else attr.upper(): v
for attr, v in future_class_attrs.items()
}
return type(future_class_name, future_class_parents, uppercase_attrs)
```
Let's rewrite the above, but with shorter and more realistic variable names now that we know what they mean:
```
class UpperAttrMetaclass(type):
def __new__(cls, clsname, bases, attrs):
uppercase_attrs = {
attr if attr.startswith("__") else attr.upper(): v
for attr, v in attrs.items()
}
return type(clsname, bases, uppercase_attrs)
```
You may have noticed the extra argument `cls`. There is
nothing special about it: `__new__` always receives the class it's defined in, as the first parameter. Just like you have `self` for ordinary methods which receive the instance as the first parameter, or the defining class for class methods.
But this is not proper OOP. We are calling `type` directly and we aren't overriding or calling the parent's `__new__`. Let's do that instead:
```
class UpperAttrMetaclass(type):
def __new__(cls, clsname, bases, attrs):
uppercase_attrs = {
attr if attr.startswith("__") else attr.upper(): v
for attr, v in attrs.items()
}
return type.__new__(cls, clsname, bases, uppercase_attrs)
```
We can make it even cleaner by using `super`, which will ease inheritance (because yes, you can have metaclasses, inheriting from metaclasses, inheriting from type):
```
class UpperAttrMetaclass(type):
def __new__(cls, clsname, bases, attrs):
uppercase_attrs = {
attr if attr.startswith("__") else attr.upper(): v
for attr, v in attrs.items()
}
# Python 2 requires passing arguments to super:
return super(UpperAttrMetaclass, cls).__new__(
cls, clsname, bases, uppercase_attrs)
# Python 3 can use no-arg super() which infers them:
return super().__new__(cls, clsname, bases, uppercase_attrs)
```
Oh, and in Python 3 if you do this call with keyword arguments, like this:
```
class Foo(object, metaclass=MyMetaclass, kwarg1=value1):
...
```
It translates to this in the metaclass to use it:
```
class MyMetaclass(type):
def __new__(cls, clsname, bases, dct, kwargs1=default):
...
```
That's it. There is really nothing more about metaclasses.
The reason behind the complexity of the code using metaclasses is not because
of metaclasses, it's because you usually use metaclasses to do twisted stuff
relying on introspection, manipulating inheritance, vars such as `__dict__`, etc.
Indeed, metaclasses are especially useful to do black magic, and therefore
complicated stuff. But by themselves, they are simple:
* intercept a class creation
* modify the class
* return the modified class
# Why would you use metaclasses classes instead of functions?
Since `__metaclass__` can accept any callable, why would you use a class
since it's obviously more complicated?
There are several reasons to do so:
* The intention is clear. When you read `UpperAttrMetaclass(type)`, you know
what's going to follow
* You can use OOP. Metaclass can inherit from metaclass, override parent methods. Metaclasses can even use metaclasses.
* Subclasses of a class will be instances of its metaclass if you specified a metaclass-class, but not with a metaclass-function.
* You can structure your code better. You never use metaclasses for something as trivial as the above example. It's usually for something complicated. Having the ability to make several methods and group them in one class is very useful to make the code easier to read.
* You can hook on `__new__`, `__init__` and `__call__`. Which will allow you to do different stuff, Even if usually you can do it all in `__new__`,
some people are just more comfortable using `__init__`.
* These are called metaclasses, damn it! It must mean something!
# Why would you use metaclasses?
Now the big question. Why would you use some obscure error-prone feature?
Well, usually you don't:
> Metaclasses are deeper magic that
> 99% of users should never worry about it.
> If you wonder whether you need them,
> you don't (the people who actually
> need them know with certainty that
> they need them, and don't need an
> explanation about why).
*Python Guru Tim Peters*
The main use case for a metaclass is creating an API. A typical example of this is the Django ORM. It allows you to define something like this:
```
class Person(models.Model):
name = models.CharField(max_length=30)
age = models.IntegerField()
```
But if you do this:
```
person = Person(name='bob', age='35')
print(person.age)
```
It won't return an `IntegerField` object. It will return an `int`, and can even take it directly from the database.
This is possible because `models.Model` defines `__metaclass__` and
it uses some magic that will turn the `Person` you just defined with simple statements
into a complex hook to a database field.
Django makes something complex look simple by exposing a simple API
and using metaclasses, recreating code from this API to do the real job
behind the scenes.
# The last word
First, you know that classes are objects that can create instances.
Well, in fact, classes are themselves instances. Of metaclasses.
```
>>> class Foo(object): pass
>>> id(Foo)
142630324
```
Everything is an object in Python, and they are all either instance of classes
or instances of metaclasses.
Except for `type`.
`type` is actually its own metaclass. This is not something you could
reproduce in pure Python, and is done by cheating a little bit at the implementation
level.
Secondly, metaclasses are complicated. You may not want to use them for
very simple class alterations. You can change classes by using two different techniques:
* [monkey patching](http://en.wikipedia.org/wiki/Monkey_patch)
* class decorators
99% of the time you need class alteration, you are better off using these.
But 98% of the time, you don't need class alteration at all.
|
What are metaclasses in Python?
|
[
"",
"python",
"oop",
"metaclass",
"python-class",
"python-datamodel",
""
] |
Specifically, in VS 2008, I want to connect to a data source that you can have by right-clicking on the automatically-generated App\_Data folder (an .mdf "database"). Seems easy, and it is once you know how.
|
So here's the answer from MSDN:
> Choos[e] "Add New Data Source" from the
> Data menu.[And follow the connection wizard]
Very easy, except that I have no Data menu. If you don't have a Data menu, do the following:
* Click on Tools >> Connect to Database...
* Select "Microsoft SQL Server Database File", take the default Data provider, and click OK
* On the next screen, browse to your Database file, which will be in your VS Solution folder structure somewhere.
Test the connection. It'll be good. If you want to add the string to the web.config, click the Advanced button, and copy the Data Source line (at the bottom of the dialog box), and paste it into a connection string in the appropriate place in the web.config file. You will have to add the "`AttachDbFilename`" attribute and value. Example:
The raw text from the Advanced panel:
```
Data Source=.\SQLEXPRESS;Integrated Security=True;Connect Timeout=30;User Instance=True
```
The actual entry in the web.config:
```
<add name="SomeDataBase" connectionString="Data Source=.\SQLEXPRESS;
AttachDbFilename=C:\Development\blahBlah\App_Data\SomeDataFile.mdf;
Integrated Security=True; Connect Timeout=30; User Instance=True" />
```
|
A great resource I always keep around is [connectionstrings.com](http://connectionstrings.com).
It's really handy for finding these connection strings when you can't find an example.
Particularly [this page](http://connectionstrings.com/?carrier=sqlserver2005) applied to your problem
**Attach a database file on connect to a local SQL Server Express instance**
```
Driver={SQL Native Client};Server=.\SQLExpress;AttachDbFilename=c:\asd\qwe\mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;
```
|
How do I connect to an .mdf (Microsoft SQL Server Database File) in a simple web project?
|
[
"",
"c#",
"asp.net",
"database",
"visual-studio-2008",
""
] |
Which type of input is least vulnerable to Cross-Site Scripting (XSS) and SQL Injection attacks.
PHP, HTML, BBCode, etc. I need to know for a forum I'm helping a friend set up.
|
We need to know more about your situation. Vulnerable how? Some things you should always do:
* Escape strings before storing them in a database to guard against SQL injections
* HTML encode strings when printing them back to the user from an unknown source, to prevent malicious html/javascript
I would never execute php provided by a user. BBCode/UBBCode are fine, because they are converted to semantically correct html, though you may want to look into XSS vulnerabilities related to malformed image tags. If you allow HTML input, you can whitelist certain elements, but this will be a complicated approach that is prone to errors. So, given all of the preceding, I would say that using a good off-the-shelf **BBCode** library would be your best bet.
|
*(I just posted this in a comment, but it seems a few people are under the impression that select lists, radio buttons, etc don't need to be sanitized.)*
Don't count on radio buttons being secure. You should still sanitize the data on the server. People could create an html page on their local machine, and make a text box with the same name as your radio button, and have that data get posted back.
A more advanced user could use a proxy like [WebScarab](http://www.owasp.org/index.php/Category:OWASP_WebScarab_Project), and just tweak the parameters as they are posted back to the server.
A good rule of thumb is to *always* use parameterized SQL statements, and *always* escape user-generated data before putting it into the HTML.
|
Which Type of Input is Least Vulnerable to Attack?
|
[
"",
"php",
"html",
"forum",
"bbcode",
"security",
""
] |
What are the C++ rules for calling the base class constructor from a derived class?
For example, I know in Java, you must do it as the first line of the subclass constructor (and if you don't, an implicit call to a no-arg super constructor is assumed - giving you a compile error if that's missing).
|
Base class constructors are automatically called for you if they have no argument. If you want to call a superclass constructor with an argument, you must use the subclass's constructor initialization list. Unlike Java, C++ supports multiple inheritance (for better or worse), so the base class must be referred to by name, rather than "super()".
```
class SuperClass
{
public:
SuperClass(int foo)
{
// do something with foo
}
};
class SubClass : public SuperClass
{
public:
SubClass(int foo, int bar)
: SuperClass(foo) // Call the superclass constructor in the subclass' initialization list.
{
// do something with bar
}
};
```
More info on the constructor's initialization list [here](http://www.cprogramming.com/tutorial/initialization-lists-c++.html) and [here](http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6).
|
In C++, the no-argument constructors for all superclasses and member variables are called for you, before entering your constructor. If you want to pass them arguments, there is a separate syntax for this called "constructor chaining", which looks like this:
```
class Sub : public Base
{
Sub(int x, int y)
: Base(x), member(y)
{
}
Type member;
};
```
If anything run at this point throws, the bases/members which had previously completed construction have their destructors called and the exception is rethrown to to the caller. If you want to catch exceptions during chaining, you must use a function try block:
```
class Sub : public Base
{
Sub(int x, int y)
try : Base(x), member(y)
{
// function body goes here
} catch(const ExceptionType &e) {
throw kaboom();
}
Type member;
};
```
In this form, note that the try block **is** the body of the function, rather than being inside the body of the function; this allows it to catch exceptions thrown by implicit or explicit member and base class initializations, as well as during the body of the function. However, if a function catch block does not throw a different exception, the runtime will rethrow the original error; exceptions during initialization **cannot** be ignored.
|
What are the rules for calling the base class constructor?
|
[
"",
"c++",
"inheritance",
"constructor",
""
] |
What is a good regular expression that can validate a text string to make sure it is a valid Windows filename? (AKA not have `\/:*?"<>|` characters).
I'd like to use it like the following:
```
// Return true if string is invalid.
if (Regex.IsMatch(szFileName, "<your regex string>"))
{
// Tell user to reformat their filename.
}
```
|
As answered already, GetInvalidFileNameChars should do it for you, and you don't even need the overhead of regular expressions:
```
if (proposedFilename.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) != -1)
{
MessageBox.Show("The filename is invalid");
return;
}
```
|
This isn't as simple as just checking whether the file name contains any of [System.IO.Path.GetInvalidFileNameChars](http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidfilenamechars.aspx) (as mentioned in a couple of other answers already).
For example what if somebody enters a name that contains no invalid chars but is 300 characters long (i.e. greater than MAX\_PATH) - this won't work with any of the .NET file APIs, and only has limited support in the rest of windows using the \?\ path syntax. You need context as to how long the rest of the path is to determine how long the file name can be. You can find [more information about this type of thing here](http://blogs.msdn.com/brian_dewey/archive/2004/01/19/60263.aspx).
Ultimately all your checks can *reliably* do is prove that a file name is not valid, or give you a reasonable estimate as to whether it is valid. It's virtually impossible to prove that the file name is valid without actually trying to use it. (And even then you have issues like what if it already exists? It may be a valid file name, but is it valid in your scenario to have a duplicate name?)
|
Regular expressions in C# for file name validation
|
[
"",
"c#",
"regex",
""
] |
I have PHP configured so that magic quotes are on and register globals are off.
I do my best to always call htmlentities() for anything I am outputing that is derived from user input.
I also occasionally seach my database for common things used in xss attached such as...
```
<script
```
What else should I be doing and how can I make sure that the things I am trying to do are **always** done.
|
Escaping input is not the best you can do for successful XSS prevention. Also output must be escaped. If you use Smarty template engine, you may use `|escape:'htmlall'` modifier to convert all sensitive characters to HTML entities (I use own `|e` modifier which is alias to the above).
My approach to input/output security is:
* store user input not modified (no HTML escaping on input, only DB-aware escaping done via PDO prepared statements)
* escape on output, depending on what output format you use (e.g. HTML and JSON need different escaping rules)
|
I'm of the opinion that one shouldn't escape anything during input, only on output. Since (most of the time) you can not assume that you know where that data is going. Example, if you have form that takes data that later on appears in an email that you send out, you need different escaping (otherwise a malicious user could rewrite your email-headers).
In other words, you can only escape at the very last moment the data is "leaving" your application:
* List item
* Write to XML file, escape for XML
* Write to DB, escape (for that particular DBMS)
* Write email, escape for emails
* etc
To go short:
1. You don't know where your data is going
2. Data might actually end up in more than one place, needing different escaping mechanism's BUT NOT BOTH
3. Data escaped for the wrong target is really not nice. (E.g. get an email with the subject "Go to Tommy\'s bar".)
Esp #3 will occur if you escape data at the input layer (or you need to de-escape it again, etc).
PS: I'll second the advice for not using magic\_quotes, those are pure evil!
|
What are the best practices for avoiding xss attacks in a PHP site
|
[
"",
"php",
"security",
"xss",
""
] |
We have an Apache ANT script to build our application, then check in the resulting JAR file into version control (VSS in this case). However, now we have a change that requires us to build 2 JAR files for this project, then check both into VSS.
The current target that checks the original JAR file into VSS discovers the name of the JAR file through some property. Is there an easy way to "generalize" this target so that I can reuse it to check in a JAR file with any name? In a normal language this would obviously call for a function parameter but, to my knowledge, there really isn't an equivalent concept in ANT.
|
I would suggest to work with [macros](http://ant.apache.org/manual/Tasks/macrodef.html) over subant/antcall because the main advantage I found with macros is that you're in complete control over the properties that are passed to the macro (especially if you want to add new properties).
You simply refactor your Ant script starting with your target:
```
<target name="vss.check">
<vssadd localpath="D:\build\build.00012.zip"
comment="Added by automatic build"/>
</target>
```
creating a macro (notice the copy/paste and replacement with the @{file}):
```
<macrodef name="private-vssadd">
<attribute name="file"/>
<sequential>
<vssadd localpath="@{file}"
comment="Added by automatic build"/>
</sequential>
</macrodef>
```
and invoke the macros with your files:
```
<target name="vss.check">
<private-vssadd file="D:\build\File1.zip"/>
<private-vssadd file="D:\build\File2.zip"/>
</target>
```
Refactoring, "the Ant way"
|
It is generally considered a bad idea to version control your binaries and I do not recommend doing so. But if you absolutely have to, you can use antcall combined with param to pass parameters and call a target.
```
<antcall target="reusable">
<param name="some.variable" value="var1"/>
</antcall>
<target name="reusable">
<!-- Do something with ${some.variable} -->
</target>
```
You can find more information about the [antcall task here](http://ant.apache.org/manual/Tasks/antcall.html).
|
Is there a way to generalize an Apache ANT target?
|
[
"",
"java",
"build-process",
"build-automation",
"ant",
""
] |
We are using [JetBrains](http://en.wikipedia.org/wiki/JetBrains)' [dotTrace](http://en.wikipedia.org/wiki/DotTrace). What other profiling tools can be recommended that are better for profiling C# [Windows Forms](http://en.wikipedia.org/wiki/Windows_Forms) applications?
|
No. I have tried pretty much every .NET profiler on the market (ANTS, vTune, OptimizeIt, DevPartner, YourKit), and in my opinion dotTrace is the best of the lot. It is one of only two profilers I have used (the other being YourKit) that has low enough overhead to handle a highly CPU-intensive application.
If and only if your application is relatively light, I could recommend [ANTS Profiler](http://www.red-gate.com/products/ants_profiler/index.htm). Its line-by-line stats are sometimes quite useful, but they come at a price in profiling efficiency.
|
I have used the [EQATEC Profiler](http://eqatec.com/Profiler/Home.aspx). It is free and is a code profiler, not a memory profiler.
|
Best .NET memory and performance profiler?
|
[
"",
"c#",
".net",
"profiling",
"profiler",
""
] |
I have this web application that has grown to an unmanageable mess.
I want to split it into a common "framework" part (that still includes web stuff like pages and images) and several modules that add extra functionality and screens. I want this refactoring to also be useful as a plugin system for third-party extensions.
All modules need to be separate unit of deployments, ideally a war or jar file.
I tried to just make several regular war files, but Tomcat keeps (according to the servlet spec) these war files completely separate from each-other, so that they cannot share their classes, for example.
I need to plugins to be able to see the "main" classpath.
I need to main application to have some control over the plugins, such as being able to list them, and set their configuration.
I would like to maintain complete separation between the plugins themselves (unless they specify dependencies) and any other unrelated web applications that may be running on the same Tomcat.
I would like them to be rooted under the "main" application URL prefix, but that is not necessary.
I would like to use Tomcat (big architectural changes need to be coordinated with too many people), but also to hear about a clean solution in the EJB or OSGi world if there are.
|
I have been tinkering with the idea of using OSGi to solve the same problem you are describing. In particular I am looking at using [Spring Dynamic Modules](http://www.springframework.org/osgi).
|
Take a look at Java Portlets - <http://developers.sun.com/portalserver/reference/techart/jsr168/> - in a nutshell, a specification that allows interoperability between what are otherwise self-contained j2ee web applications
**Edit**
I forgot to mention that Portlets are pretty much framework agnostic - so you can use Spring for the parent application, and individual developers can use whatever they want on their Portlets.
|
Extending Java Web Applications with plugins
|
[
"",
"java",
"tomcat",
"servlets",
"modularity",
""
] |
Is there a way to get stored procedures from a SQL Server 2005 Express database using C#? I would like to export all of this data in the same manner that you can script it our using SQL Server Management Studio, without having to install the GUI.
I've seen some references to do thing via the PowerShell but in the end a C# console app is what I really want.
***To clarify....***
I'd like to script out the stored procedures. The list via the `Select * from sys.procedures` is helpful, but in the end I need to script out each of these.
|
Just read the output of SELECT NAME from SYS.PROCEDURES , then call EXEC sp\_HelpText SPNAME for each stored procedure, you'll get a record set with one line of text per row.
|
You can use SMO for that. First of all, add references to these assemblies to your project:
* Microsoft.SqlServer.ConnectionInfo
* Microsoft.SqlServer.Smo
* Microsoft.SqlServer.SmoEnum
They are located in the GAC (browse to C:\WINDOWS\assembly folder).
Use the following code as an example of scripting stored procedures:
```
using System;
using System.Collections.Generic;
using System.Data;
using Microsoft.SqlServer.Management.Smo;
class Program
{
static void Main(string[] args)
{
Server server = new Server(@".\SQLEXPRESS");
Database db = server.Databases["Northwind"];
List<SqlSmoObject> list = new List<SqlSmoObject>();
DataTable dataTable = db.EnumObjects(DatabaseObjectTypes.StoredProcedure);
foreach (DataRow row in dataTable.Rows)
{
string sSchema = (string)row["Schema"];
if (sSchema == "sys" || sSchema == "INFORMATION_SCHEMA")
continue;
StoredProcedure sp = (StoredProcedure)server.GetSmoObject(
new Urn((string)row["Urn"]));
if (!sp.IsSystemObject)
list.Add(sp);
}
Scripter scripter = new Scripter();
scripter.Server = server;
scripter.Options.IncludeHeaders = true;
scripter.Options.SchemaQualify = true;
scripter.Options.ToFileOnly = true;
scripter.Options.FileName = @"C:\StoredProcedures.sql";
scripter.Script(list.ToArray());
}
}
```
See also: [SQL Server: SMO Scripting Basics](http://blogs.msdn.com/mwories/archive/2005/05/07/basic-scripting.aspx).
|
Simple way to programmatically get all stored procedures
|
[
"",
"c#",
"sql-server",
"sql-server-2005",
"stored-procedures",
""
] |
I want to use a timer in my simple [.NET](http://en.wikipedia.org/wiki/.NET_Framework) application written in C#. The only one I can find is the Windows.Forms.Timer class. I don't want to reference this namespace just for my console application.
Is there a C# timer (or timer like) class for use in console applications?
|
System.Timers.Timer
And as MagicKat says:
System.Threading.Timer
You can see the differences here:
<http://intellitect.com/system-windows-forms-timer-vs-system-threading-timer-vs-system-timers-timer/>
And you can see MSDN examples here:
<http://msdn.microsoft.com/en-us/library/system.timers.timer(VS.80).aspx>
And here:
<http://msdn.microsoft.com/en-us/library/system.threading.timer(VS.80).aspx>
|
I would recommend the [`Timer`](http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx) class in the [`System.Timers`](http://msdn.microsoft.com/en-us/library/system.timers.aspx) namespace. Also of interest, the [`Timer`](http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx) class in the [`System.Threading`](http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx) namespace.
```
using System;
using System.Timers;
public class Timer1
{
private static Timer aTimer = new System.Timers.Timer(10000);
public static void Main()
{
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Enabled = true;
Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine();
}
// Specify what you want to happen when the Elapsed event is
// raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
}
}
```
Example from MSDN docs.
|
Is there a timer class in C# that isn't in the Windows.Forms namespace?
|
[
"",
"c#",
".net",
"scheduling",
"timer",
""
] |
I'm trying to get a case-insensitive search with two strings in JavaScript working.
Normally it would be like this:
```
var string="Stackoverflow is the BEST";
var result= string.search(/best/i);
alert(result);
```
The `/i` flag would be for case-insensitive.
But I need to search for a second string; without the flag it works perfect:
```
var string="Stackoverflow is the BEST";
var searchstring="best";
var result= string.search(searchstring);
alert(result);
```
If I add the `/i` flag to the above example it would search for searchstring and not for what is in the variable "searchstring" (next example not working):
```
var string="Stackoverflow is the BEST";
var searchstring="best";
var result= string.search(/searchstring/i);
alert(result);
```
How can I achieve this?
|
Yeah, use `.match`, rather than `.search`. The result from the `.match` call will return the actual string that was matched itself, but it can still be used as a boolean value.
```
var string = "Stackoverflow is the BEST";
var result = string.match(/best/i);
// result == 'BEST';
if (result){
alert('Matched');
}
```
Using a regular expression like that is probably the tidiest and most obvious way to do that in JavaScript, but bear in mind it *is* a regular expression, and thus can contain regex metacharacters. If you want to take the string from elsewhere (eg, user input), or if you want to avoid having to escape a lot of metacharacters, then you're probably best using `indexOf` like this:
```
matchString = 'best';
// If the match string is coming from user input you could do
// matchString = userInput.toLowerCase() here.
if (string.toLowerCase().indexOf(matchString) != -1){
alert('Matched');
}
```
|
Replace
```
var result= string.search(/searchstring/i);
```
with
```
var result= string.search(new RegExp(searchstring, "i"));
```
|
Case-insensitive search
|
[
"",
"javascript",
"search",
"string-comparison",
"case-insensitive",
""
] |
I am setting up a test version of my website against a new schema. I am trying to connect using the proxy connection and am getting the following error:
> ORA-28150: proxy not authorized to connect as client
my connect string has the following form:
> Data Source=*Instance*; User Id=*user*; Proxy User Id=*prxy\_usr*;Proxy Password=*prxy\_pass*; Min Pool Size = 0; Connection Timeout = 30
Do you have any idea what might be wrong?
|
According to [the docs](http://download.oracle.com/docs/cd/B28359_01/server.111/b28278/e24280.htm#ORA-28150): Grant the proxy user permission to perform actions on behalf of the client by using the ALTER USER ... GRANT CONNECT command.
|
EddieAwad's answer was correct but here is the specific code to run:
> ALTER USER *username* GRANT CONNECT THROUGH *proxyUserName*;
The THROUGH keyword is the part I couldn't find in the documentation.
|
.NET unable to connect to Oracle DB using Oracle proxy user
|
[
"",
"c#",
"oracle",
"odp.net",
""
] |
Consider a normal customer-orders application based on MVC pattern using WinForms.
The view part has grown too much (over 4000 files) and it needs to be split into smaller ones.
---
For this example we are going to use 3 projects for the view part:
* **Main** - has dependencies to the other 2 projects. Instantiates the forms with the lists.
* **Customers** - has 2 forms - customers list and customer details.
* **Orders** - has 2 forms - orders list and order details.
---
On the customer details form there is also a list of orders for that customer. The list is received from the OrdersController so it's no problem getting it. When the user selects an order, the list will get it's guid and pass it as reference to the Order Details form.
*This would mean that we need to have a reference to Orders Project in the Customers Project.* **(1)**
But also on the order details form there is a link to the customer that made that order. When clicked, it should open the Customer Details form.
*This would mean that we need to have a reference to Customers Project in the Orders Project.* **(2)**
**From (1) and (2) we'll have cyclic dependencies between the Orders and Customers projects.**
---
**How can this be avoided?** Some kind of plug-in architecture? The project is already developed and the best solution would involve as little code change as possible.
|
Change at least one of the types to an interface.
For example have a ICustomer interface and a Customer type that implements this interface. Now add the ICustomer to the orders project and from the customers project set a reference to the Orders project so you can implement the interface. The Order type can now work against the ICustomer type without knowing the actual implementation.
And for a better solution :-)
Create both an ICustomer and an IOrder interface and add them to a third library project. And reference this project from the other two and only work with the interfaces, never with the implemenation.
|
If they are that tightly coupled maybe they should not be split.
|
Cyclic Dependencies
|
[
"",
"c#",
"asp.net-mvc",
"dependencies",
""
] |
I have a WinForms app written in C# with .NET 3.5. It runs a lengthy batch process. I want the app to update status of what the batch process is doing. What is the best way to update the UI?
|
The BackgroundWorker sounds like the object you want.
|
The quick and dirty way is using `Application.DoEvents()` But this can cause problems with the order events are handled. So it's not recommended
The problem is probably not that you have to yield to the ui thread but that you do the processing on the ui thread blocking it from handling messages. You can use the backgroundworker component to do the batch processing on a different thread without blocking the UI thread.
|
How do I Yield to the UI thread to update the UI while doing batch processing in a WinForm app?
|
[
"",
"c#",
".net",
"winforms",
""
] |
How can I *programmatically* determine if I have access to a server (TCP) with a given IP address and port using C#?
|
Assuming you mean through a TCP socket:
```
IPAddress IP;
if(IPAddress.TryParse("127.0.0.1",out IP)){
Socket s = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
try{
s.Connect(IPs[0], port);
}
catch(Exception ex){
// something went wrong
}
}
```
For more information: <http://msdn.microsoft.com/en-us/library/4xzx2d41.aspx?ppud=4>
|
Declare string address and int port and you are ready to connect through the TcpClient class.
```
System.Net.Sockets.TcpClient client = new TcpClient();
try
{
client.Connect(address, port);
Console.WriteLine("Connection open, host active");
} catch (SocketException ex)
{
Console.WriteLine("Connection could not be established due to: \n" + ex.Message);
}
finally
{
client.Close();
}
```
|
How can I test a TCP connection to a server with C# given the server's IP address and port?
|
[
"",
"c#",
"networking",
""
] |
How do I programmatically force an onchange event on an input?
I've tried something like this:
```
var code = ele.getAttribute('onchange');
eval(code);
```
But my end goal is to fire any listener functions, and that doesn't seem to work. Neither does just updating the 'value' attribute.
|
Create an `Event` object and pass it to the `dispatchEvent` method of the element:
```
var element = document.getElementById('just_an_example');
var event = new Event('change');
element.dispatchEvent(event);
```
This will trigger event listeners regardless of whether they were registered by calling the `addEventListener` method or by setting the `onchange` property of the element.
---
By default, events created and dispatched like this don't propagate (bubble) up the DOM tree like events normally do.
If you want the event to bubble, you need to pass a second argument to the `Event` constructor:
```
var event = new Event('change', { bubbles: true });
```
---
Information about browser compability:
* [dispatchEvent()](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent#Browser_Compatibility)
* [Event()](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event#Browser_compatibility)
|
In jQuery I mostly use:
```
$("#element").trigger("change");
```
|
How do I programmatically force an onchange event on an input?
|
[
"",
"javascript",
""
] |
How can I convert a JavaScript string value to be in all lowercase letters?
Example: `"Your Name"` to `"your name"`
|
```
const lowerCaseName = "Your Name".toLowerCase(); // your name
```
|
Use either [toLowerCase](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/toLowerCase) or [toLocaleLowerCase](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/toLocaleLowerCase) methods of the [String](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String) object. The difference is that `toLocaleLowerCase` will take current locale of the user/host into account. As per § 15.5.4.17 of the [ECMAScript Language Specification (ECMA-262)](http://www.ecma-international.org/publications/standards/Ecma-262.htm), `toLocaleLowerCase`…
> …works exactly the same as toLowerCase
> except that its result is intended to
> yield the correct result for the host
> environment’s current locale, rather
> than a locale-independent result.
> There will only be a difference in the
> few cases (such as Turkish) where the
> rules for that language conflict with
> the regular Unicode case mappings.
Example:
```
var lower = 'Your Name'.toLowerCase();
```
Also note that the `toLowerCase` and `toLocaleLowerCase` functions are implemented to work generically on *any* value type. Therefore you can invoke these functions even on non-`String` objects. Doing so will imply automatic conversion to a string value prior to changing the case of each character in the resulting string value. For example, you can *apply* `toLowerCase` directly on a date like this:
```
var lower = String.prototype.toLowerCase.apply(new Date());
```
and which is effectively equivalent to:
```
var lower = new Date().toString().toLowerCase();
```
The second form is generally preferred for its simplicity and readability. On earlier versions of IE, the first had the benefit that it could work with a `null` value. The result of applying `toLowerCase` or `toLocaleLowerCase` on `null` would yield `null` (and not an error condition).
|
Convert JavaScript String to be all lowercase
|
[
"",
"javascript",
"string",
""
] |
I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of another program doesn't seem very elegant not to mention error prone.
Does anyone know a cross platform method (windows and linux) method to get the MAC address? If not, does anyone know any more elegant methods then those I listed above?
|
Python 2.5 includes an uuid implementation which (in at least one version) needs the mac address. You can import the mac finding function into your own code easily:
```
from uuid import getnode as get_mac
mac = get_mac()
```
The return value is the mac address as 48 bit integer.
|
The pure python solution for this problem under Linux to get the MAC for a specific local interface, originally posted as a comment by vishnubob and improved by on Ben Mackey in [this activestate recipe](http://code.activestate.com/recipes/439094-get-the-ip-address-associated-with-a-network-inter/)
```
#!/usr/bin/python
import fcntl, socket, struct
def getHwAddr(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', ifname[:15]))
return ':'.join(['%02x' % ord(char) for char in info[18:24]])
print getHwAddr('eth0')
```
This is the Python 3 compatible code:
```
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import fcntl
import socket
import struct
def getHwAddr(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', bytes(ifname, 'utf-8')[:15]))
return ':'.join('%02x' % b for b in info[18:24])
def main():
print(getHwAddr('enp0s8'))
if __name__ == "__main__":
main()
```
|
Getting MAC Address
|
[
"",
"python",
"windows",
"linux",
"networking",
""
] |
I'm having trouble coming up with the correct regex string to remove a sequence of multiple ? characters. I want to replace more than one sequential ? with a single ?, but which characters to escape...is escaping me.
Example input:
> Is this thing on??? or what???
Desired output:
> Is this thing on? or what?
I'm using [preg\_replace()](http://php.net/preg_replace) in PHP.
|
```
preg_replace('{\?+}', '?', 'Is this thing on??? or what???');
```
That is, you only have to escape the question mark, the plus in "\?+" means that we're replacing every instance with one or more characters, though I suspect "\?{2,}" might be even better and more efficient (replacing every instance with two or more question mark characters.
|
`preg_replace( '{\\?+}', '?', $text );`
should do it.
You need to escape the question mark itself with a backslash, and then escape the backslash itself with another backslash.
It's situations like this where C#'s [verbatim strings](http://msdn.microsoft.com/en-us/library/aa691090(VS.71).aspx) are nice.
|
PHP regex to remove multiple ?-marks
|
[
"",
"php",
"regex",
"escaping",
""
] |
I would like to do a lookup of tables in my SQL Server 2005 Express database based on table name. In `MySQL` I would use `SHOW TABLES LIKE "Datasheet%"`, but in `T-SQL` this throws an error (it tries to look for a `SHOW` stored procedure and fails).
Is this possible, and if so, how?
|
This will give you a list of the tables in the current database:
```
Select Table_name as "Table name"
From Information_schema.Tables
Where Table_type = 'BASE TABLE' and Objectproperty
(Object_id(Table_name), 'IsMsShipped') = 0
```
Some other useful T-SQL bits can be found here: <http://www.devx.com/tips/Tip/28529>
|
I know you've already accepted an answer, but why not just use the much simpler [sp\_tables](https://msdn.microsoft.com/en-us/library/ms186250.aspx)?
```
sp_tables 'Database_Name'
```
|
How can I do the equivalent of "SHOW TABLES" in T-SQL?
|
[
"",
"sql",
"t-sql",
"sql-server-2005",
""
] |
I want my WPF application to be skinnable, by applying a certain XAML template, and the changes to be application wide, even for dynamic controls or controls that aren't even in the visual/logical tree.
What can I use to accomplish this type of functionality? Are there any good resources or tutorials that show how this specific task can be done?
|
The basic approach to take is using resources all through your application and dynamically replacing the resources at runtime.
See <http://www.nablasoft.com/alkampfer/index.php/2008/05/22/simple-skinnable-and-theme-management-in-wpf-user-interface/> for the basic approach
|
The replacing of resource will work but I found "structural skinning" to be more powerfull! Read more about it on CodeProject...
<http://www.codeproject.com/KB/WPF/podder1.aspx>
|
What is the recommended way to skin an entire application in WPF?
|
[
"",
"c#",
".net",
"wpf",
"templates",
"skinning",
""
] |
I see on Stack Overflow and [PEP 8](http://www.python.org/dev/peps/pep-0008/) that the recommendation is to use spaces only for indentation in Python programs. I can understand the need for consistent indentation and I have felt that pain.
Is there an underlying reason for spaces to be preferred? I would have thought that tabs were far easier to work with.
|
The answer was given right there in the PEP [ed: this passage has been edited out in [2013](https://hg.python.org/peps/rev/fb24c80e9afb#l1.75)]. I quote:
> The **most popular** way of indenting Python is with spaces only.
What other underlying reason do you need?
To put it less bluntly: Consider also the scope of the PEP as stated in the very first paragraph:
> This document gives coding conventions for the Python code comprising the standard library in the main Python distribution.
The intention is to make *all code that goes in the official python distribution* consistently formatted (I hope we can agree that this is universally a Good Thing™).
Since the decision between spaces and tabs for an individual programmer is a) really a matter of taste and b) easily dealt with by technical means (editors, conversion scripts, etc.), there is a clear way to end all discussion: choose one.
Guido was the one to choose. He didn't even have to give a reason, but he still did by referring to empirical data.
For all other purposes you can either take this PEP as a recommendation, or you can ignore it -- your choice, or your team's, or your team leaders.
But if I may give you one advice: don't mix'em ;-) [ed: Mixing tabs and spaces is no longer an option.]
|
Well well, seems like everybody is strongly biased towards spaces.
I use tabs exclusively. I know very well why.
Tabs are actually a cool invention, that came **after** spaces. It allows you to indent without pushing space millions of times or using a fake tab (that produces spaces).
I really don't get why everybody is discriminating against the use of tabs. It is very much like old people discriminating against younger people for choosing a newer more efficient technology and complaining that pulse dialing works on **every phone**, not just on these fancy new ones. "Tone dialing doesn't work on every phone, that's why it is wrong".
Your editor cannot handle tabs properly? Well, get a **modern** editor. Might be darn time, we are now in the 21st century and the time when an editor was a high tech complicated piece of software is long past. We have now tons and tons of editors to choose from, all of them that support tabs just fine. Also, you can define how much a tab should be, a thing that you cannot do with spaces. Cannot see tabs? What is that for an argument? Well, you cannot see spaces neither!
May I be so bold to suggest to get a better editor? One of these high tech ones, that were released some 10 years ago already, that **display invisible characters**? (sarcasm off)
Using spaces causes a lot more deleting and formatting work. That is why (and all other people that know this and agree with me) use tabs for Python.
Mixing tabs and spaces is a no-no and no argument about that. That is a mess and can never work.
|
Why does Python pep-8 strongly recommend spaces over tabs for indentation?
|
[
"",
"python",
"indentation",
"pep8",
""
] |
When displaying the value of a decimal currently with `.ToString()`, it's accurate to like 15 decimal places, and since I'm using it to represent dollars and cents, I only want the output to be 2 decimal places.
Do I use a variation of `.ToString()` for this?
|
```
decimalVar.ToString("#.##"); // returns ".5" when decimalVar == 0.5m
```
or
```
decimalVar.ToString("0.##"); // returns "0.5" when decimalVar == 0.5m
```
or
```
decimalVar.ToString("0.00"); // returns "0.50" when decimalVar == 0.5m
```
|
I know this is an old question, but I was surprised to see that no one seemed to post an answer that;
1. Didn't use bankers rounding
2. Keeps the value as a decimal.
This is what I would use:
```
decimal.Round(yourValue, 2, MidpointRounding.AwayFromZero);
```
<http://msdn.microsoft.com/en-us/library/9s0xa85y.aspx>
|
How do I display a decimal value to 2 decimal places?
|
[
"",
"c#",
".net",
"format",
"decimal",
""
] |
I would like to compress a folder and all its sub-folders/files, and email the zip file as an attachment. What would be the best way to achieve this with Python?
|
You can use the [zipfile](http://docs.python.org/dev/library/zipfile.html) module to compress the file using the zip standard, the [email](http://docs.python.org/dev/library/email.html) module to create the email with the attachment, and the [smtplib](http://docs.python.org/dev/library/smtplib.html) module to send it - all using only the standard library.
# Python - Batteries Included
If you don't feel like programming and would rather ask a question on stackoverflow.org instead, or (as suggested in the comments) left off the `homework` tag, well, here it is:
```
import smtplib
import zipfile
import tempfile
from email import encoders
from email.message import Message
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
def send_file_zipped(the_file, recipients, sender='you@you.com'):
zf = tempfile.TemporaryFile(prefix='mail', suffix='.zip')
zip = zipfile.ZipFile(zf, 'w')
zip.write(the_file)
zip.close()
zf.seek(0)
# Create the message
themsg = MIMEMultipart()
themsg['Subject'] = 'File %s' % the_file
themsg['To'] = ', '.join(recipients)
themsg['From'] = sender
themsg.preamble = 'I am not using a MIME-aware mail reader.\n'
msg = MIMEBase('application', 'zip')
msg.set_payload(zf.read())
encoders.encode_base64(msg)
msg.add_header('Content-Disposition', 'attachment',
filename=the_file + '.zip')
themsg.attach(msg)
themsg = themsg.as_string()
# send the message
smtp = smtplib.SMTP()
smtp.connect()
smtp.sendmail(sender, recipients, themsg)
smtp.close()
"""
# alternative to the above 4 lines if you're using gmail
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.login("username", "password")
server.sendmail(sender,recipients,themsg)
server.quit()
"""
```
With this function, you can just do:
```
send_file_zipped('result.txt', ['me@me.org'])
```
You're welcome.
|
Look at [zipfile](http://www.python.org/doc/2.5.2/lib/module-zipfile.html) for compressing a folder and it's subfolders.
Look at [smtplib](http://www.python.org/doc/2.5.2/lib/module-smtplib.html) for an email client.
|
How can I compress a folder and email the compressed file in Python?
|
[
"",
"python",
""
] |
I have a .NET **2.0** WebBrowser control used to navigate some pages with no user interaction (don't ask...long story). Because of the user-less nature of this application, I have set the WebBrowser control's ScriptErrorsSuppressed property to true, which the documentation included with VS 2005 states will [...]"hide all its dialog boxes that originate from the underlying ActiveX control, not just script errors." The [MSDN article](http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.scripterrorssuppressed(VS.80).aspx) doesn't mention this, however.
I have managed to cancel the NewWindow event, which prevents popups, so that's taken care of.
Anyone have any experience using one of these and successfully blocking **all** dialogs, script errors, etc?
**EDIT**
This isn't a standalone instance of IE, but an instance of a WebBrowser control living on a Windows Form application. Anyone have any experience with this control, or the underlying one, **AxSHDocVW**?
**EDIT again**
Sorry I forgot to mention this... I'm trying to block a **JavaScript alert()**, with just an OK button. Maybe I can cast into an IHTMLDocument2 object and access the scripts that way, I've used MSHTML a little bit, anyone know?
|
This is most definitely hacky, but if you do any work with the WebBrowser control, you'll find yourself doing a lot of hacky stuff.
This is the easiest way that I know of to do this. You need to inject JavaScript to override the alert function... something along the lines of injecting this JavaScript function:
```
window.alert = function () { }
```
There are *many ways to do this*, but it is very possible to do. One possibility is to hook an implementation of the [DWebBrowserEvents2](http://msdn.microsoft.com/en-us/library/aa768283.aspx) interface. Once this is done, you can then plug into the NavigateComplete, the DownloadComplete, or the DocumentComplete (or, as we do, some variation thereof) and then call an InjectJavaScript method that you've implemented that performs this overriding of the window.alert method.
Like I said, hacky, but it works :)
I can go into more details if I need to.
|
And for an easy way to inject that magic line of javascript, read [how to inject javascript into webbrowser control](https://stackoverflow.com/questions/153748/webbrowser-control-from-net-how-to-inject-javascript).
Or just use this complete code:
```
private void InjectAlertBlocker() {
HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
string alertBlocker = "window.alert = function () { }";
scriptEl.SetAttribute("text", alertBlocker);
head.AppendChild(scriptEl);
}
```
|
Blocking dialogs in .NET WebBrowser control
|
[
"",
"c#",
".net",
"winforms",
"activex",
"mshtml",
""
] |
What libraries and/or packages have you used to create blog posts with code blocks? Having a JavaScript library that would support line numbers and indentation is ideal.
|
The [GeSHi text highlighter](http://qbnz.com/highlighter/) is pretty awesome. If you're using WordPress, [there's a plugin](http://wordpress.org/extend/plugins/wp-syntax/) for you already
|
A simple Google query reveals <http://code.google.com/p/syntaxhighlighter/>
From initial looks it seems pretty good. Entirly JS based so can be implemented independent of the server side language used.
|
Displaying code in blog posts
|
[
"",
"javascript",
"syntax-highlighting",
""
] |
In the [Google C++ Style Guide](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml), the [section on Operator Overloading](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Operator_Overloading) recommends against overloading *any* operators ("except in rare, special circumstances"). Specifically, it recommends:
> In particular, do not overload
> `operator==` or `operator<` just so that
> your class can be used as a key in an
> STL container; instead, you should
> create equality and comparison functor
> types when declaring the container.
I'm a little fuzzy on what such a functor would look like, but my main question is, *why* would you want to write your own functors for this? Wouldn't defining `operator<`, and using the standard `std::less<T>` function, be simpler? Is there any advantage to using one over the other?
|
Except for the more fundamental types, the less-than operation isn't always trivial, and even equality may vary from situation to situation.
Imagine the situation of an airline that wants to assign all passengers a boarding number. This number reflects the boarding order (of course). Now, what determines who comes before who? You might just take the order in which the customers registered – in that case, the less-than operation would compare the check-in times. You might also consider the price customers paid for their tickets – less-than would now compare ticket prices.
… and so on. All in all, it's just not meaningful to define an `operator <` on the `Passenger` class although it may be required to have passengers in a sorted container. I think that's what Google warns against.
|
Generally, defining `operator<` is better and simpler.
The case where you would want to use functors is when you need multiple ways of comparing a particular type. For example:
```
class Person;
struct CompareByHeight {
bool operator()(const Person &a, const Person &b);
};
struct CompareByWeight {
bool operator()(const Person &a, const Person &b);
};
```
In this case there may not be a good "default" way to compare and order people so not defining `operator<` and using functors may be better. You could also say that generally people are ordered by height, and so `operator<` just calls `CompareByHeight`, and anyone who needs Person's to be ordered by weight has to use `CompareByWeight` explicitly.
Often times the problem is that defining the functors is left up to the user of the class, so that you tend to get many redefinitions of the same thing, whenever the class needs to be used in an ordered container.
|
Comparison Functor Types vs. operator<
|
[
"",
"c++",
"stl",
"coding-style",
""
] |
I see lots of job ads for C#/.NET programmers, so I thought it could be a good idea to have had a look at it.
After looking at a few tutorials I found nothing really new to me. Just a language with a syntax somewhere between Java and C++ (arguably nicer than both though).
So, what features in particular should I look at? What are some special features? What's the reason that C#/.NET is so large? What are some killer features or perhaps some really evil language gotchas?
Links and code examples are very welcome.
I am using the Mono-implementation on Linux.
|
Compared with Java:
* The "using" statement (try/finally is rarely explicit in C#) (C# 1)
* Delegates as a first class concept (C# 1)
* Properties and events as first class concepts (C# 1)
* User-defined value types (C# 1)
* Operator overloading (use with care!) (C# 1)
* Iterator blocks (C# 2)
* Generics without type erasure (C# 2)
* Anonymous methods (C# 2)
* Partial types (good for code generation) (C# 2)
* Object and collection initializers (C# 3)
* Lambda expressions (C# 3)
* Extension methods (C# 3)
* Expression trees (C# 3)
* Query expressions (aka query comprehensions) (C# 3)
* Anonymous types (mostly used in query expessions) (C# 3)
They're the things I miss from C# when I write in Java, anyway. (That's not an exhaustive list of differences, of course.) Which ones are most important to you is subjective, of course. From a simple "getting things done" point of view the `using` statement is probably the single biggest pragmatic gain, even though it only builds a try/finally block for you.
EDIT: For quick examples of the C# 2 and 3 features, you might want to look at my [Bluffer's Guide to C# 2](http://csharpindepth.com/Articles/General/BluffersGuide2.aspx) and the [equivalent for C# 3](http://csharpindepth.com/Articles/General/BluffersGuide3.aspx).
|
The .Net Framework library is more important than the language.
|
C#/.NET, what to look at?
|
[
"",
"c#",
""
] |
Trying to perform a single boolean NOT operation, it appears that under MS SQL Server 2005, the following block does not work
```
DECLARE @MyBoolean bit;
SET @MyBoolean = 0;
SET @MyBoolean = NOT @MyBoolean;
SELECT @MyBoolean;
```
Instead, I am getting more successful with
```
DECLARE @MyBoolean bit;
SET @MyBoolean = 0;
SET @MyBoolean = 1 - @MyBoolean;
SELECT @MyBoolean;
```
Yet, this looks a bit a twisted way to express something as simple as a negation.
Am I missing something?
|
Use the ~ operator:
```
DECLARE @MyBoolean bit
SET @MyBoolean = 0
SET @MyBoolean = ~@MyBoolean
SELECT @MyBoolean
```
|
Your solution is a good one... you can also use this syntax to toggle a bit in SQL...
```
DECLARE @MyBoolean bit;
SET @MyBoolean = 0;
SET @MyBoolean = @MyBoolean ^ 1;
SELECT @MyBoolean;
```
|
Boolean 'NOT' in T-SQL not working on 'bit' datatype?
|
[
"",
"sql",
"sql-server",
"t-sql",
"boolean-operations",
""
] |
I have a list string tag.
I am trying to initialize a dictionary with the key as the tag string and values as the array index.
```
for i, ithTag in enumerate(tag):
tagDict.update(ithTag=i)
```
The above returns me {'ithTag': 608} *608 is the 608th index*
My problem is that while the i is being interpreted as a variable, Python is treating the "ithTag" as a string instead of a variable.
I'm confused, it is kind of hard to google these kind of specific questions. I hope I worded the title of this question correctly,
Thanks!
|
You actually want to do this:
```
for i, tag in enumerate(tag):
tagDict[tag] = i
```
The .update() method is used for updating a dictionary using another dictionary, not for changing a single key/value pair.
|
If you want to be clever:
```
tagDict.update(map(reversed, enumerate(tag)))
```
Thanks to Brian for the update. This is apparently ~5% faster than the iterative version.
(EDIT: Thanks saverio for pointing out my answer was incorrect (now fixed). Probably the most efficient/Pythonic way would be Torsten Marek's answer, slightly modified:
```
tagDict.update((t, i) for (i,t) in enumerate(tag))
```
)
|
python dictionary update method
|
[
"",
"python",
"dictionary",
"variables",
""
] |
I'm trying to define a task that emits (using echo) a message when a target completes execution, regardless of whether that target was successful or not. Specifically, the target executes a task to run some unit tests, and I want to emit a message indicating where the results are available:
```
<target name="mytarget">
<testng outputDir="${results}" ...>
...
</testng>
<echo>Tests complete. Results available in ${results}</echo>
</target>
```
Unfortunately, if the tests fail, the task fails and execution aborts. So the message is only output if the tests pass - the opposite of what I want. I know I can put the task before the task, but this will make it easier for users to miss this message. Is what I'm trying to do possible?
**Update:** It turns out I'm dumb. I had haltOnFailure="true" in my <testng> task, which explains the behaviour I was seeing. Now the issue is that setting this to false causes the overall ant build to succeed even if tests fail, which is not what I want. The answer below using the task looks like it might be what I want..
|
The solution to your problem is to use the `failureProperty` in conjunction with the `haltOnFailure` property of the testng task like this:
```
<target name="mytarget">
<testng outputDir="${results}" failureProperty="tests.failed" haltOnFailure="false" ...>
...
</testng>
<echo>Tests complete. Results available in ${results}</echo>
</target>
```
Then, elsewhere when you want the build to fail you add ant code like this:
```
<target name="doSomethingIfTestsWereSuccessful" unless="tests.failed">
...
</target>
<target name="doSomethingIfTestsFailed" if="tests.failed">
...
<fail message="Tests Failed" />
</target>
```
You can then call doSomethingIfTestsFailed where you want your ant build to fail.
|
According to the [Ant docs](http://ant.apache.org/manual/Tasks/exec.html), there are two properties that control whether the build process is stopped or not if the testng task fails:
> **haltonfailure** - Stop the build process
> if a failure has occurred during the
> test run. Defaults to false.
>
> **haltonskipped** - Stop the build process
> if there is at least on skipped test.
> Default to false.
I can't tell from the snippet if you're setting this property or not. May be worth trying to explicitly set haltonfailure to false if it's currently set to true.
Also, assuming you're using the <exec> functionality in Ant, there are similar properties to control what happens if the executed command fails:
> **failonerror** - Stop the buildprocess if the command exits with a return code
> signaling failure. Defaults to false.
>
> **failifexecutionfails** - Stop the build if we can't start the program.
> Defaults to true.
Can't tell based on the partial code snippet in your post, but my guess is that the most likely culprit is **failonerror** or **haltonfailure** being set to true.
|
Unconditionally execute a task in ant?
|
[
"",
"java",
"unit-testing",
"ant",
""
] |
It seems like most examples of JPA/Hibernate entity bean classes I've seen do no explicit synchronization. Yet, it is possible to call getters/setters on those objects in the context of building up a transaction. And it's possible for those methods to be called across multiple threads (although maybe that's unusual and weird).
It seems like if it is built up across multiple threads then it's possible for changes to object state to be lost, which would be sad.
So, is leaving out synchronization best practice? Is the Hibernate instrumented code taking care of proper synchronization for me?
As an example:
```
@Entity
public class Ninja {
@Id @GeneratedValue
private Long id;
@Column
private String name;
@Column
private int throwingStars;
public Ninja() {}
public int getThrowingStars() { return throwingStars; }
public void addThrowingStar() { throwingStars += 1; }
}
```
Do the throwing star methods need synchronization? I sure don't want my ninja to lose any throwing stars.
|
The object probably is not the same for the 2 threads. Supposing your threads use a session factory to access the db, the objects you get from the session should be viewed as 'independent' (I believe hibernate creates 'fresh' objects for each get(), unless they are in the session).
As for your stars question, it's the same when two persons fetch the same row from a DB, the DB 'ACID' properties will make sure that each operation is atomic, so if you remove a star from a ninja in Thread t1 and **commit**, Thread t2 will read the committed values of t1.
Alternatively, you can ask hibernate to lock the row of the relevant ninja in T1, so that even if T2 asks for the row it will have to wait until T1 commits or aborts.
|
In my opinion you should NEVER share domains objects across threads. In fact I typically share very little between threads as such data must be protected. I have built some large/high performance systems and have never had to break this rule. If you need to parallelize work then do so but NOT by sharing instances of domain objects. Each thread should read data from the database, operate on it by mutating/creating objects and then commit/rollback the transaction. Work pass in/out should be value/readonly objects generally.
|
What is the best practice for JPA/Hibernate entity classes and synchronization?
|
[
"",
"java",
"multithreading",
"hibernate",
"jpa",
""
] |
Is there a way to get more useful information on validation error? XmlSchemaException provides the line number and position of the error which makes little sense to me. Xml document after all is not about its transient textual representation. I'd like to get an enumerated error (or an error code) specifying what when wrong, node name (or an xpath) to locate the source of the problem so that perhaps I can try and fix it.
Edit: I'm talking about valid xml documents - just not valid against a particular schema!
|
You can accomplish this, sort of, by setting up an XmlReader whose XmlReaderSettings contain the schema and then using it to read through the input stream node by node. You can keep track of the last node read and have a pretty good idea of where you are in the document when a validation error happens.
I think that if you try this exercise, you'll discover that there are a lot of validation errors (e.g. required element missing) where the concept of the error node doesn't make much sense. Yes, the parent element is clearly what's in error in that case, but what really triggered the error was the reader encountering the end tag without ever seeing the required element, which is why the error line and position point at the end tag.
|
In my experience, you are lucky to get a line number and parse position.
|
Validating and reparing xml
|
[
"",
"c#",
"xml",
"xsd",
""
] |
I'm trying to create a ImageIcon from a animated gif stored in a jar file.
```
ImageIcon imageIcon = new ImageIcon(ImageIO.read(MyClass.class.getClassLoader().getResourceAsStream("animated.gif")));
```
The image loads, but only the first frame of the animated gif. The animation does not play.
If I load the animated gif from a file on the filesystem, everything works as expected. The animation plays through all the of frames. So this works:
```
ImageIcon imageIcon = new ImageIcon("/path/on/filesystem/animated.gif");
```
How can I load an animated gif into an ImageIcon from a jar file?
EDIT: Here is a complete test case, why doesn't this display the animation?
```
import javax.imageio.ImageIO;
import javax.swing.*;
public class AnimationTest extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
AnimationTest test = new AnimationTest();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.setVisible(true);
}
});
}
public AnimationTest() {
super();
try {
JLabel label = new JLabel();
ImageIcon imageIcon = new ImageIcon(ImageIO.read(AnimationTest.class.getClassLoader().getResourceAsStream("animated.gif")));
label.setIcon(imageIcon);
imageIcon.setImageObserver(label);
add(label);
pack();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
|
This reads gif animation from inputStream
```
InputStream in = ...;
Image image = Toolkit.getDefaultToolkit().createImage(org.apache.commons.io.IOUtils.toByteArray(in));
```
|
You have to use getClass().getResource(imgName); to get a URL to the image file. Check out [this tutorial](http://www.rgagnon.com/javadetails/java-0240.html) from Real's HowTo.
EDIT: Once the image is loaded you have to [set the ImageObserver property](http://java.sun.com/javase/6/docs/api/javax/swing/ImageIcon.html#setImageObserver(java.awt.image.ImageObserver)) to get the animation to run.
|
Loading animated gif from JAR file into ImageIcon
|
[
"",
"java",
"swing",
"animated-gif",
"javax.imageio",
""
] |
I'm looking for a few talking points I could use to convince coworkers that it's NOT OK to run a 24/7 production application by simply opening Visual Studio and running the app in debug mode.
What's different about running a compiled console application vs. running that same app in debug mode?
Are there ever times when you would use the debugger in a live setting? (live: meaning connected to customer facing databases)
Am I wrong in assuming that it's always a bad idea to run a live configuration via the debugger?
|
You will suffer from reduced performance when running under the debugger (not to mention the complexity concerns [mentioned by Bruce](https://stackoverflow.com/questions/136674/reasons-to-not-run-a-business-critical-c-console-application-via-the-debugger#136699)), and there is nothing to keep you from getting the same functionality as running under the debugger when compiled in release mode -- you can always set your program up to [log unhandled exceptions](http://www.julmar.com/blog/mark/PermaLink,guid,f733e261-5d39-4ca1-be1a-c422f3cf1f1b.aspx) and [generate a core dump](http://blogs.msdn.com/tess/archive/2008/05/21/debugdiag-1-1-or-windbg-which-one-should-i-use-and-how-do-i-gather-memory-dumps.aspx) that will allow you to debug issues even after restarting your app.
In addition, it sounds just plain wrong to be manually managing an app that needs 24/7 availability. You should be using scheduled tasks or some sort of automated process restarting mechanism.
Stepping back a bit, [this question](https://stackoverflow.com/questions/12745/how-do-you-handle-poor-quality-code-from-team-members) may provide some guidance on influencing your team.
|
Just in itself there's no issue in running it in debugging if the performance is good enough. What strikes me as odd is that you are running business critical 24/7 applications as users, perhaps even on a workstation. If you want to ensure robustness and avaliability you should consider running this on dedicated hardware that no one uses besides the application. If you are indeed running this on a users machine, accidents can be easily made, such as closing down the "wrong" visual studio, or crashing the computer etc.
Running in debug should be done in the test environment. Where I've work/worked we usually have three environments, Production, Release and Test.
**Production**
* Dedicated hardware
* Limited access, usually only the main developers/technology
* Version control, a certain tagged version from SVN/CVS
* Runs the latest stable version that has been promoted to production status
**Release**
* Dedicate hardware
* Full access to all developers
* Version control, a certain tagged version from SVN/CVS
* Runs the next version of the product, not yet promoted to production status, but will probably be. "Gold" if you like.
**Test**
* Virtual machine or louse hardware
* Full access
* No version control, could be the next, next version, or just a custom build that someone wanted to test out on "near prod environment"
This way we can easily test new version in Release, even debug them there. In Test environment it's anything-goes. It's more if someone want to test something involving more than one box (your own).
This way it will protect you against quick-hacks that wasn't tested enough by having dedicated test machines, but still allow you to release those hacks in an emergency.
|
Reasons to NOT run a business-critical C# console application via the debugger?
|
[
"",
"c#",
"debugging",
""
] |
Does anyone have any code examples on how to create controllers that have parameters other than using a Dependency Injection Container?
I see plenty of samples with using containers like StructureMap, but nothing if you wanted to pass in the dependency class yourself.
|
You can use poor-man's dependency injection:
```
public ProductController() : this( new Foo() )
{
//the framework calls this
}
public ProductController(IFoo foo)
{
_foo = foo;
}
```
|
One way is to create a ControllerFactory:
```
public class MyControllerFactory : DefaultControllerFactory
{
public override IController CreateController(
RequestContext requestContext, string controllerName)
{
return [construct your controller here] ;
}
}
```
Then, in Global.asax.cs:
```
private void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
ControllerBuilder.Current.SetControllerFactory(
new MyNamespace.MyControllerFactory());
}
```
|
Constructor parameters for controllers without a DI container for ASP.NET MVC
|
[
"",
"c#",
".net",
"asp.net-mvc",
""
] |
I have a Hashtable<Integer, Sport> called sportMap and a list of sportIds (List<Integer> sportIds) from my backing bean. The Sport object has a List<String> equipmentList. Can I do the following using the unified EL to get the list of equipment for each sport?
```
<h:dataTable value="#{bean.sportIds}" var="_sportId" >
<c:forEach items="#{bean.sportMap[_sportId].equipmentList}" var="_eqp">
<h:outputText value="#{_eqp}"></h:outputText>
<br/>
</c:forEach>
</h:dataTable>
```
I get the following exception when trying to run this JSP code.
```
15:57:59,438 ERROR [ExceptionFilter] exception root cause
javax.servlet.ServletException: javax.servlet.jsp.JspTagException:
Don't know how to iterate over supplied "items" in <forEach>
```
Here's a print out of my environment
```
Server: JBossWeb/2.0.1.GA
Servlet Specification: 2.5
JSP version: 2.1
JSTL version: 1.2
Java Version: 1.5.0_14
```
Note: The following does work using a JSF tag. It prints out the list of equipment for each sport specified in the list of sportIds.
```
<h:dataTable value="#{bean.sportIds}" var="_sportId" >
<h:outputText value="#{bean.sportMap[_sportId].equipmentList}">
</h:outputText>
</h:dataTable>
```
I would like to use the c:forEach tag. Does anyone know if this is possible? If not, anyone have suggestions? In the end I want a stacked list instead of the comma seperated list provided by equipmentList.toString(); (Also, don't want to override toString()).
|
@[keith30xi.myopenid.com](https://stackoverflow.com/questions/136696/can-i-use-a-hashtable-in-a-unified-el-expression-on-a-cforeach-tag-using-jsf-12#137188)
**Not TRUE in JSF 1.2**. According to the [java.net wiki faq](http://wiki.java.net/bin/view/Projects/JavaServerFacesSpecFaq#12coreTags) they should work together as expected.
Here's an extract from each faq:
> **JSF 1.1 FAQ**
> Q. Do JavaServer Faces tags interoperate with JSTL core tags, forEach, if, choose and when?
>
> A. The forEach tag does not work with JavaServer Faces technology, version 1.0 and 1.1 tags due to an incompatibility between the strategies used by JSTL and and JavaServer
> Faces technology. Instead, you could use a renderer, such as the Table renderer used by the dataTable tag, that performs its own iteration. The if, choose and when tags work, but the JavaServer Faces tags nested within these tags must have explicit identifiers.
>
> ***This shortcoming has been fixed in JSF 1.2.***
>
> **JSF 1.2 FAQ**
> Q. Do JavaServer Faces tags interoperate with JSTL core tags, forEach, if, choose and when?
>
> A. Yes. A new feature of JSP 2.1, called JSP Id Consumer allows these tags to work as expected.
Has anyone used JSF tags with JSTL core tags specifically forEach?
|
I had the same problem once, and I couldn't find a solution using dataTable.
The problem is that the var **\_sportId** can be read only by the dataTable component.
If you need to do a loop inside a loop, you can use a dataTable inside a dataTable:
```
<h:dataTable value="#{bean.sportIds}" var="_sportId" >
<h:dataTable value="#{bean.sportMap[_sportId].equipmentList}" var="_eqp">
<h:outputText value="#{_eqp}"></h:outputText>
</h:dataTable>
</h:dataTable>
```
But in this case each of yours equipmentList items is printed inside a table row. It was not a great solution form me.
I chose to use a normal html table instead of a dataTable:
```
<table>
<c:forEach items="#{bean.sportIds}" var="_sportId">
<tr>
<td>
<c:forEach items="#{bean.sportMap[_sportId].equipmentList" var="_eqp">
<h:outputText value="#{_eqp} " />
</c:forEach>
</td>
</tr>
</c:forEach>
</table>
```
It works. If you need some specific dataTable functionality like binding and row mapping, you can obtain it in an easy way using the **f:setPropertyActionListener** tag.
|
Can I use a Hashtable in a unified EL expression on a c:forEach tag using JSF 1.2 with JSP 2.1?
|
[
"",
"java",
"jsp",
"jsf",
"jstl",
""
] |
I have a web part that I've developed, and if I manually install the web part it is fine.
However when I have packaged the web part following the instructions on this web site as a guide:
<http://www.theartofsharepoint.com/2007/05/how-to-build-solution-pack-wsp.html>
I get this error in the log files:
```
09/23/2008 14:13:03.67 w3wp.exe (0x1B5C) 0x1534 Windows SharePoint Services Web Parts 8l4d Monitorable Error importing WebPart. Cannot import Project Filter.
09/23/2008 14:13:03.67 w3wp.exe (0x1B5C) 0x1534 Windows SharePoint Services Web Parts 89ku High Failed to add webpart http%253A%252F%252Fuk64p12%252FPWA%252F%255Fcatalogs%252Fwp%252FProjectFilter%252Ewebpart;Project%2520Filter. Exception Microsoft.SharePoint.WebPartPages.WebPartPageUserException: Cannot import Project Filter. at Microsoft.SharePoint.WebPartPages.WebPartImporter.CreateWebPart(Boolean clearConnections) at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, Uri webPartPageUri, SPWeb spWeb) at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, SPWeb spWeb) at Microsoft.SharePoint.WebPartPages.WebPartQuickAdd.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(...
09/23/2008 14:13:03.67* w3wp.exe (0x1B5C) 0x1534 Windows SharePoint Services Web Parts 89ku High ...String eventArgument)
```
The pertinent bit is:
```
http%253A%252F%252Fuk64p12%252FPWA%252F%255Fcatalogs%252Fwp%252FProjectFilter%252Ewebpart;Project%2520Filter.
Exception Microsoft.SharePoint.WebPartPages.WebPartPageUserException: Cannot import Project Filter.
at Microsoft.SharePoint.WebPartPages.WebPartImporter.CreateWebPart(Boolean clearConnections)
at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, Uri webPartPageUri, SPWeb spWeb)
at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, SPWeb spWeb)
at Microsoft.SharePoint.WebPartPages.WebPartQuickAdd.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
```
And that's accompanied by a rather terse error message: "Cannot import web part".
I have checked and my .dll is registered as safe, it is in the GAC, the feature is activated, and the web parts appear in the web part library with all of the correct properties showing that the webpart files were read successfully.
Everything appears to be in place, yet I get that error and little explanation from SharePoint of how to resolve it.
Any help finding a solution is appreciated.
|
Figured it out.
The error message is the one from the .webpart file:
```
<?xml version="1.0" encoding="utf-8"?>
<webParts>
<webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
<metaData>
<!--
The following Guid is used as a reference to the web part class,
and it will be automatically replaced with actual type name at deployment time.
-->
<type name="7F8C4D34-6311-4f22-87B4-A221FA8735BA" />
<importErrorMessage>Cannot import Project Filter.</importErrorMessage>
</metaData>
<data>
<properties>
<property name="Title" type="string">Project Filter</property>
<property name="Description" type="string">Provides a list of Projects that can be used to Filter other Web Parts.</property>
</properties>
</data>
</webPart>
</webParts>
```
The problem is that the original .webpart file was created on a 32-bit system with Visual Studio Extensions for WSS installed.
However as I'm now on a 64-bit machine VSEWSS is unavailable, and I believe that results in the above GUID not being substituted as I am not using those deployment tools.
Replacing the GUID with the full type name works.
So if you encounter the error message from your importErrorMessage node, then check that your type node in the .webpart file looks more like this (unrelated example):
```
<type name="TitleWP.TitleWP, TitleWP, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5" />
```
This is in the format:
Class, Namespace, Version, Culture, PublicKey
You can grab that easily from the web.config file associated with your SharePoint instance, as it will be in the safe controls list.
|
We had this same problem and found that the constructor of our web part was being called by the WebPartImporter and within the constructor we were doing SPSecurity.RunWithElevatedPrivileges.
For some reason the WebPartImporter cannot handle this. So, we simply moved our code out of the constructor to OnInit (where it really belonged) and all is well.
|
SharePoint error: "Cannot import Web Part"
|
[
"",
"c#",
"sharepoint",
"moss",
"web-parts",
"project-server",
""
] |
I switched from Perl to Python about a year ago and haven't looked back. There is only *one* idiom that I've ever found I can do more easily in Perl than in Python:
```
if ($var =~ /foo(.+)/) {
# do something with $1
} elsif ($var =~ /bar(.+)/) {
# do something with $1
} elsif ($var =~ /baz(.+)/) {
# do something with $1
}
```
The corresponding Python code is not so elegant since the if statements keep getting nested:
```
m = re.search(r'foo(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'bar(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'baz(.+)', var)
if m:
# do something with m.group(2)
```
Does anyone have an elegant way to reproduce this pattern in Python? I've seen anonymous function dispatch tables used, but those seem kind of unwieldy to me for a small number of regular expressions...
|
Starting `Python 3.8`, and the introduction of [assignment expressions (PEP 572)](https://www.python.org/dev/peps/pep-0572/) (`:=` operator), we can now capture the condition value `re.search(pattern, text)` in a variable `match` in order to both check if it's not `None` and then re-use it within the body of the condition:
```
if match := re.search(r'foo(.+)', text):
# do something with match.group(1)
elif match := re.search(r'bar(.+)', text):
# do something with match.group(1)
elif match := re.search(r'baz(.+)', text)
# do something with match.group(1)
```
|
Using named groups and a dispatch table:
```
r = re.compile(r'(?P<cmd>foo|bar|baz)(?P<data>.+)')
def do_foo(data):
...
def do_bar(data):
...
def do_baz(data):
...
dispatch = {
'foo': do_foo,
'bar': do_bar,
'baz': do_baz,
}
m = r.match(var)
if m:
dispatch[m.group('cmd')](m.group('data'))
```
With a little bit of introspection you can auto-generate the regexp and the dispatch table.
|
How do you translate this regular-expression idiom from Perl into Python?
|
[
"",
"python",
"regex",
"perl",
""
] |
I have a Java application that monitors a folder for incoming XML files. When a new file is detected I need to test the file that it is not currently being updated and is closed. My thought is to use [File.canWrite()](http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html#canWrite()) to test this. Is there any issue with doing this? Is this a good way to test that a file has been completely written?
Other ideas I am throwing around are:
* Parse the incoming XML file and test
that the closing tag is there.
* Check for the EoF character.
I just am not sure that any of these methods will handle all scenarios.
|
No, canWrite is not suitable for this purpose. In general the file will be writable even if another process is writing.
You need a higher level protocol to coordinate the locking. If you plan to use this code on a single platform, you may be able to use [NIO's FileLock facility](http://java.sun.com/j2se/1.5.0/docs/api/java/nio/channels/FileLock.html). But read the documentation carefully, and note that on many platforms, the lock is only advisory.
Another approach is to have one process write the file with a name that your process won't recognize, then rename the file to a recognizable name when the write is complete. On most platforms, the rename operation is atomic if the source and destination are the same file system volume. The name change might use a different file extension, or even moving the file from one directory to another (on the same volume).
Since in this case you are working exclusively with XML, looking for a close tag would work, but it isn't foolproof—what if there are comments after the final markup, or the writer or simply doesn't write valid XML?
Looking for the EOF will *not* work. There will always be an EOF, even when the writer has just opened the file and hasn't written anything yet. If this weren't so, the easiest thing would be to allow the reader to start parsing as soon as the file showed up; it would simply block until the writer closed the file. But the file system doesn't work this way. Every file has an end, even if some process is currently moving it.
|
Additionally, if you do a check followed by a write, then you have a race condition. The state could change between the check and the write. Sometimes its best to try and do the thing you want and handle errors gracefully. perhaps an n-attempt retry mechanism with a increased fallback delay time.
Or redefine your test. In this case, you could perhaps test that the filesize hasn't changed over a period of time before processing it.
Another option is to split the code into two, you could have another thread -- perhaps a quartz task -- responsible for moving finished files into a different directory that your main code processes.
|
Can the Java File method "canWrite()" support locking?
|
[
"",
"java",
"xml",
"file-io",
""
] |
I need a quick easy way to get a string from a file in standard C++. I can write my own, but just want to know if there is already a standard way, in C++.
Equivalent of this if you know Cocoa:
```
NSString *string = [NSString stringWithContentsOfFile:file];
```
|
We can do it but it's a long line :
```
#include<fstream>
#include<iostream>
#include<iterator>
#include<string>
using namespace std;
int main()
{
// The one-liner
string fileContents(istreambuf_iterator<char>(ifstream("filename.txt")), istreambuf_iterator<char>());
// Check result
cout << fileContents;
}
```
Edited : use "istreambuf\_iterator" instead of "istream\_iterator"
|
Its almost possible with an istream\_iterator (3 lines!)
```
#include <iostream>
#include <fstream>
#include <iterator>
#include <string>
#include <sstream>
using namespace std;
int main()
{
ifstream file("filename.txt");
string fileContents;
copy(istreambuf_iterator<char>(file),
istreambuf_iterator<char>(),
back_inserter(fileContents));
}
```
Edited - got rid of intermediate string stream, now copies straight into the string, and now using istreambuf\_iterator, which ignores whitespace (thanks Martin York for your comment).
|
Is there a one-liner to read in a file to a string in C++?
|
[
"",
"c++",
"file",
"filesystems",
""
] |
Does anyone know if there is a good equivalent to Java's `Set` collection in C#? I know that you can somewhat mimic a set using a `Dictionary` or a `HashTable` by populating but ignoring the values, but that's not a very elegant way.
|
Try [HashSet](http://msdn.microsoft.com/en-us/library/bb359438.aspx):
> The HashSet(Of T) class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order...
>
> The capacity of a HashSet(Of T) object is the number of elements that the object can hold. A HashSet(Of T) object's capacity automatically increases as elements are added to the object.
>
> The HashSet(Of T) class is based on the model of mathematical sets and provides high-performance set operations similar to accessing the keys of the [Dictionary(Of TKey, TValue)](https://msdn.microsoft.com/en-us/library/xfhwa508.aspx) or [Hashtable](https://msdn.microsoft.com/en-us/library/system.collections.hashtable.aspx) collections. In simple terms, the HashSet(Of T) class can be thought of as a [Dictionary(Of TKey, TValue)](https://msdn.microsoft.com/en-us/library/xfhwa508.aspx) collection without values.
>
> A HashSet(Of T) collection is not sorted and cannot contain duplicate elements...
|
If you're using .NET 3.5, you can use [`HashSet<T>`](http://msdn.microsoft.com/en-us/library/bb359438.aspx). It's true that .NET doesn't cater for sets as well as Java does though.
The [Wintellect PowerCollections](https://github.com/timdetering/Wintellect.PowerCollections) may help too.
|
C# Set collection?
|
[
"",
"c#",
".net",
"collections",
"set",
""
] |
Trying to honor a feature request from our customers, I'd like that my application, when Internet is available, check on our website if a new version is available.
The problem is that I have no idea about what have to be done on the server side.
I can imagine that my application (developped in C++ using Qt) has to send a request (HTTP ?) to the server, but what is going to respond to this request ? In order to go through firewalls, I guess I'll have to use port 80 ? Is this correct ?
Or, for such a feature, do I have to ask our network admin to open a specific port number through which I'll communicate ?
---
@[pilif](https://stackoverflow.com/questions/56391/automatically-checking-for-a-new-version-of-my-application/56418#56418) : thanks for your detailed answer. There is still something which is unclear for me :
> like
>
> `http://www.example.com/update?version=1.2.4`
>
> Then you can return what ever you want, probably also the download-URL of the installer of the new version.
How do I return something ? Will it be a php or asp page (I know nothing about PHP nor ASP, I have to confess) ? How can I decode the `?version=1.2.4` part in order to return something accordingly ?
|
I would absolutely recommend to just do a plain HTTP request to your website. Everything else is bound to fail.
I'd make a HTTP GET request to a certain page on your site containing the version of the local application.
like
```
http://www.example.com/update?version=1.2.4
```
Then you can return what ever you want, probably also the download-URL of the installer of the new version.
Why not just put a static file with the latest version to the server and let the client decide? Because you may want (or need) to have control over the process. Maybe 1.2 won't be compatible with the server in the future, so you want the server to force the update to 1.3, but the update from 1.2.4 to 1.2.6 could be uncritical, so you might want to present the client with an optional update.
Or you want to have a breakdown over the installed base.
Or whatever. Usually, I've learned it's best to keep as much intelligence on the server, because the server is what you have ultimate control over.
Speaking here with a bit of experience in the field, here's a small preview of what can (and will - trust me) go wrong:
* Your Application will be prevented from making HTTP-Requests by the various Personal Firewall applications out there.
* A considerable percentage of users won't have the needed permissions to actually get the update process going.
* Even if your users have allowed the old version past their personal firewall, said tool will complain because the .EXE has changed and will recommend the user not to allow the new exe to connect (users usually comply with the wishes of their security tool here).
* In managed environments, you'll be shot and hanged (not necessarily in that order) for loading executable content from the web and then actually executing it.
So to keep the damage as low as possible,
* fail silently when you can't connect to the update server
* before updating, make sure that you have write-permission to the install directory and warn the user if you do not, or just don't update at all.
* Provide a way for administrators to turn the auto-update off.
It's no fun to do what you are about to do - especially when you deal with non technically inclined users as I had to numerous times.
|
Pilif answer was good, and I have lots of experience with this too, but I'd like to add something more:
Remember that if you start yourapp.exe, then the "updater" will try to overwrite yourapp.exe with the newest version. Depending upon your operating system and programming environment (you've mentioned C++/QT, I have no experience with those), you will **not** be able to overwrite *yourapp.exe* because it will be in use.
What I have done is create a launcher. I have a MyAppLauncher.exe that uses a config file (xml, very simple) to launch the "real exe". Should a new version exist, the Launcher can update the "real exe" because it's not in use, and then relaunch the new version.
Just keep that in mind and you'll be safe.
|
Automatically checking for a new version of my application
|
[
"",
"c++",
"qt",
""
] |
I'd like to know if there's an easier way to insert a record if it doesn't already exist in a table. I'm still trying to build my LINQ to SQL skills.
Here's what I've got, but it seems like there should be an easier way.
```
public static TEntity InsertIfNotExists<TEntity>
(
DataContext db,
Table<TEntity> table,
Func<TEntity,bool> where,
TEntity record
)
where TEntity : class
{
TEntity existing = table.SingleOrDefault<TEntity>(where);
if (existing != null)
{
return existing;
}
else
{
table.InsertOnSubmit(record);
// Can't use table.Context.SubmitChanges()
// 'cause it's read-only
db.SubmitChanges();
}
return record;
}
```
|
```
public static void InsertIfNotExists<TEntity>
(this Table<TEntity> table,
TEntity entity,
Expression<Func<TEntity,bool>> predicate)
where TEntity : class
{
if (!table.Any(predicate))
{
table.InsertOnSubmit(record);
table.Context.SubmitChanges();
}
}
table.InsertIfNotExists(entity, e=>e.BooleanProperty);
```
|
As others have pointed out, the `if (!Any()) { InsertOnSubmit(); }` solutions all have a race condition. If you go that route, when you call `SubmitChanges`, you have to take into account that either a) a `SqlException` could be raised for a duplicate insert, or b) you could have duplicate records in the table.
Fortunately, we can use the database to avoid the race condition by enforcing uniqueness. The following code assumes that there is a primary key or unique constraint on the table to prevent the insertion of duplicate records.
```
using (var db = new DataContext()) {
// Add the new (possibly duplicate) record to the data context here.
try {
db.SubmitChanges();
} catch (SqlException ex) {
const int violationOfPrimaryKeyContraint = 2627;
const int violationOfUniqueConstraint = 2601;
var duplicateRecordExceptionNumbers = new [] {
violationOfPrimaryKeyContraint, violationOfUniqueConstraint
};
if (!duplicateRecordExceptionNumbers.Contains(ex.Number)) {
throw;
}
}
}
```
Now... things get a fair bit more complicated if you have to perform the insert in a batch transaction with other database updates.
|
LINQ to SQL insert-if-non-existent
|
[
"",
"c#",
"linq-to-sql",
""
] |
Something like
```
var life= {
users : {
guys : function(){ this.SOMETHING.mameAndDestroy(this.girls); },
girls : function(){ this.SOMETHING.kiss(this.boys); },
},
mameAndDestroy : function(group){ },
kiss : function(group){ }
};
```
this.SOMETHING is what I imagine the format is, but it might not be. What will step back up to the parent of an object?
|
JavaScript does not offer this functionality natively. And I doubt you could even create this type of functionality. For example:
```
var Bobby = {name: "Bobby"};
var Dad = {name: "Dad", children: [ Bobby ]};
var Mom = {name: "Mom", children: [ Bobby ]};
```
Who does Bobby belong to?
|
I simply added in first function
```
parentThis = this;
```
and use parentThis in subfunction. Why? Because in JavaScript, objects are soft. A new member can be added to a soft object by simple assignment (not like ie. Java where classical objects are hard. The only way to add a new member to a hard object is to create a new class) More on this here: <http://www.crockford.com/javascript/inheritance.html>
And also at the end you don't have to kill or destroy the object. Why I found here: <http://bytes.com/topic/javascript/answers/152552-javascript-destroy-object>
Hope this helps
|
Access parent's parent from javascript object
|
[
"",
"javascript",
"oop",
""
] |
I want to resize the font of a SPAN element's style until it the SPAN's text is 7.5 inches wide when printed out on paper, but JavaScript only reports the SPAN's clientWidth property in pixels.
```
<span id="test">123456</span>
```
And then:
```
#test {
font-size:1.2in; /* adjust this for yourself until printout measures 7.5in wide */
}
```
And then:
```
console.log(document.getElementById('test').clientWidth);
```
I've determined experimentally on one machine that it uses approximately 90 DPI as a conversion factor, because the above code logs approximately 675, at least under Firefox 3.
This number is not necessarily the same under different browser, printer, screen, etc. configurations.
So, how do I find the DPI the browser is using? What can I call to get back "90" on my system?
|
I think this does what you want. But I agree with the other posters, HTML isn't really suited for this sort of thing. Anyway, hope you find this useful.
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
#container {width: 7in; border: solid 1px red;}
#span {display: table-cell; width: 1px; border: solid 1px blue; font-size: 12px;}
</style>
<script language="javascript" type="text/javascript">
function resizeText() {
var container = document.getElementById("container");
var span = document.getElementById("span");
var containerWidth = container.clientWidth;
var spanWidth = span.clientWidth;
var nAttempts = 900;
var i=1;
var font_size = 12;
while ( spanWidth < containerWidth && i < nAttempts ) {
span.style.fontSize = font_size+"px";
spanWidth = span.clientWidth;
font_size++;
i++;
}
}
</script>
</head>
<body>
<div id="container">
<span id="span">test</span>
</div>
<a href="javascript:resizeText();">resize text</a>
</body>
</html>
```
|
To summarize:
This is not a problem you can solve using HTML. Apart from the [CSS2 print properties](http://www.w3schools.com/css/css_ref_print.asp), there is no defined or expected way for browsers to print things.
Firstly, [A pixel (in CSS) is not neccessarily the same size as a pixel (on your screen)](http://webkit.org/blog/57/css-units/), so the fact that a certain value works for you doesn't mean it will translate to other setups.
Secondly, users can change the text size using features like page zoom, etc.
Thirdly, because there are is no defined way of how to lay out web pages for print purposes, each browser does it differently. Just print preview something in firefox vs IE and see the difference.
Fourthly, printing brings in a whole slew of other variables, such as the DPI of the printer, the paper size. Additionally, most printer drivers support user-scaling of the output *set in the print dialog* which the browser never sees.
Finally, most likely because printing is not a goal of HTML, the 'print engine' of the web browser is (in all browsers I've seen anyway) disconnected from the rest of it. There is no way for your javascript to 'talk' to the print engine, or vice versa, so the "DPI number the browser is using for print previews" is not exposed in any way.
I'd recommend a PDF file.
|
How do you convert pixels to printed inches in JavaScript?
|
[
"",
"javascript",
"css",
"printing",
""
] |
ReSharper likes to point out multiple functions per ASP.NET page that could be made static. Does it help me if I do make them static? Should I make them static and move them to a utility class?
|
**Static methods versus Instance methods**
[Static and instance members](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/classes#static-and-instance-members) of the C# Language Specification explains the difference. Generally, static methods can provide a very small performance enhancement over instance methods, but only in somewhat extreme situations (see [this answer](https://stackoverflow.com/a/12279898/23234) for some more details on that).
Rule CA1822 in FxCop or Code Analysis states:
> *"After [marking members as static], the compiler will emit non-virtual call sites to these members which will prevent a check at
> runtime for each call that ensures the current object pointer is
> non-null. This can result in a measurable performance gain for
> performance-sensitive code. In some cases, the failure to access the
> current object instance represents a correctness issue."*
**Utility Class**
You shouldn't move them to a utility class unless it makes sense in your design. If the static method relates to a particular type, like a `ToRadians(double degrees)` method relates to a class representing angles, it makes sense for that method to exist as a static member of that type (note, this is a convoluted example for the purposes of demonstration).
|
Performance, namespace pollution etc are all secondary in my view. Ask yourself what is logical. Is the method logically operating on an instance of the type, or is it related to the type itself? If it's the latter, make it a static method. Only move it into a utility class if it's related to a type which isn't under your control.
Sometimes there are methods which logically act on an instance but don't happen to use any of the instance's state *yet*. For instance, if you were building a file system and you'd got the concept of a directory, but you hadn't implemented it yet, you could write a property returning the kind of the file system object, and it would always be just "file" - but it's logically related to the instance, and so should be an instance method. This is also important if you want to make the method virtual - your particular implementation may need no state, but derived classes might. (For instance, asking a collection whether or not it's read-only - you may not have implemented a read-only form of that collection yet, but it's clearly a property of the collection itself, not the type.)
|
Method can be made static, but should it?
|
[
"",
"c#",
".net",
"refactoring",
"resharper",
"static-methods",
""
] |
I search an implementation of a network (or distributed) file system like NFS in Java. The goal is to extend it and do some research stuff with it. On the web I found some implementation e.g. [DJ NFS](http://users.csc.calpoly.edu/~jbergami/projects/djnfs/), but the open question is how mature and fast they are.
Can anyone purpose a good starting point, has anyone experience with such things?
P.S. I know Hadoop DFS and I used it for some projects, but Hadoop is not a good fit for the things I want to do here.
--EDIT--
Hadoop is really focused on highly scalable, high throughput computing without the possibilities to overwrite parts of a file and so an. The goal is you could use the filesystem e.g. for user home directories.
--EDIT--
More Details: The idea is to modify such a implementation so that the files are not stored directly on a local filesystem, but to apply data de-duplication.
|
Have a look at [dcache.org](http://www.dcache.org).
They implement a NFSv4.1 server in Java.
* [whitepaper](https://www.dcache.org/manuals/dcache-whitepaper-light.pdf)
* [github](https://github.com/dCache/nfs4j)
* [manual](https://www.dcache.org/manuals/book.shtml)
|
You may want to take a look at [Alfresco JLAN](http://www.alfresco.com/products/aifs/):
> Alfresco JLAN uses a virtual file system interface that allows you to plug in your own file system implementation with the core server handling all of the network protocol exchange between the client and server. JLAN is also the only Java implementation of Window’s CIFS (Common Internet File System), in addition to supporting NFS and FTP.
|
NFS Server in Java
|
[
"",
"java",
"filesystems",
""
] |
Is it possible to make it appear to a system that a key was pressed, for example I need to make `A` key be pressed thousands of times, and it is much to time consuming to do it manually, I would like to write something to do it for me, and the only thing I know well enough is Python.
A better way to put it, I need to emulate a key press, I.E. not capture a key press.
More Info (as requested):
I am running windows XP and need to send the keys to another application.
|
Install the [pywin32](https://github.com/mhammond/pywin32) extensions. Then you can do the following:
```
import win32com.client as comclt
wsh= comclt.Dispatch("WScript.Shell")
wsh.AppActivate("Notepad") # select another application
wsh.SendKeys("a") # send the keys you want
```
Search for documentation of the WScript.Shell object (I believe installed by default in all Windows XP installations). You can start [here](http://www.microsoft.com/technet/scriptcenter/guide/sas_wsh_pkoy.mspx?mfr=true), perhaps.
**EDIT:** Sending F11
```
import win32com.client as comctl
wsh = comctl.Dispatch("WScript.Shell")
# Google Chrome window title
wsh.AppActivate("icanhazip.com")
wsh.SendKeys("{F11}")
```
|
You could also use PyAutoGui to send a virtual key presses.
Here's the documentation: <https://pyautogui.readthedocs.org/en/latest/>
```
import pyautogui
pyautogui.press('Any key combination')
```
You can also send keys like the shift key or enter key with:
```
import pyautogui
pyautogui.press('shift')
```
Pyautogui can also send straight text like so:
```
import pyautogui
pyautogui.typewrite('any text you want to type')
```
As for pressing the "A" key 1000 times, it would look something like this:
```
import pyautogui
for i in range(999):
pyautogui.press("a")
```
alt-tab or other tasks that require more than one key to be pressed at the same time:
```
import pyautogui
# Holds down the alt key
pyautogui.keyDown("alt")
# Presses the tab key once
pyautogui.press("tab")
# Lets go of the alt key
pyautogui.keyUp("alt")
```
|
Key Presses in Python
|
[
"",
"python",
"keypress",
""
] |
I'm starting with Python coming from java.
I was wondering if there exists something similar to JavaDoc API where I can find the class, its methods and and example of how to use it.
I've found very helpul to use *help( thing )* from the Python ( command line )
I have found this also:
<http://docs.python.org/2/>
<https://docs.python.org/2/py-modindex.html>
But it seems to help when you already have the class name you are looking for. In JavaDoc API I have all the classes so if I need something I scroll down to a class that "sounds like" what I need. Or some times I just browse all the classes to see what they do, and when I need a feature my brain recalls me *We saw something similar in the javadoc remember!?*
But I don't seem to find the similar in Python ( yet ) and that why I'm posting this questin.
BTW I know that I would eventually will read this:
<https://docs.python.org/2/library/>
But, well, I think it is not today.
|
[pydoc](http://docs.python.org/library/pydoc.html)?
I'm not sure if you're looking for something more sophisticated, but it does the trick.
|
The standard python library is fairly well documented. Try jumping into python and importing a module say "os" and running:
```
import os
help(os)
```
This reads the doc strings on each of the items in the module and displays it. This is exactly what pydoc will do too.
EDIT: [epydoc](http://epydoc.sourceforge.net/) is probably exactly what you're looking for:
|
Python language API
|
[
"",
"python",
"reference",
"documentation",
"python-2.x",
""
] |
In java, which regular expression can be used to replace these,
for example:
before:
aaabbb
after:
ab
before:
14442345
after:
142345
thanks!
|
In perl
```
s/(.)\1+/$1/g;
```
Does the trick, I assume if java has perl compatible regexps it should work too.
Edit: Here is what it means
```
s {
(.) # match any charater ( and capture it )
\1 # if it is followed by itself
+ # One or more times
}{$1}gx; # And replace the whole things by the first captured character (with g modifier to replace all occurences)
```
Edit: As others have pointed out, the syntax in Java would become
```
original.replaceAll("(.)\\1+", "$1");
```
remember to escape the \1
|
```
String a = "aaabbb";
String b = a.replaceAll("(.)\\1+", "$1");
System.out.println("'" + a + "' -> '" + b + "'");
```
|
regular expression to replace two (or more) consecutive characters by only one?
|
[
"",
"java",
"regex",
""
] |
I have a `SqlCommand` that I want to call `Prepare()` on whose `CommandType = Text` (it **cannot** be a stored procedure).
In order to do this, I need to set the `Size` attribute on the parameters to be non-zero otherwise an exception is thrown. Are there any negative effects from setting the `Size` on all parameters to the maximum possible size even if the size of the actual values will never come close to that? Is there a better way to do this?
|
I think the only potential negative side effect of doing something like that would be the cost of memory allocation for the parameters.
Since you're calling 'Prepare()' I'm guessing you're planning to use the SqlCommand multiple times against the same SqlConnection which suggests a discrete section of code where it's likely to be used (if the connection closes for a prepared command, the command text will have to be re-transmitted to the server on the next usage).
If you know the nature of your parameters, it seems like you might have some idea about their potential sizes. If not, then I don't see what alternative you have, really, than to declare a significantly large size for each - large enough to hold most/any potential values.
|
This is the way the framework does it if you use the SqlParameter constructor that just takes a parameter name and a value. There might be a slight inefficiency on the client side, but I have never noticed a difference in query performance.
|
SqlParameter Size - negative effects of setting to max size?
|
[
"",
"c#",
"sql-server",
"ado.net",
""
] |
Is it possible to embed a pre-existing DLL into a compiled C# executable (so that you only have one file to distribute)? If it is possible, how would one go about doing it?
Normally, I'm cool with just leaving the DLLs outside and having the setup program handle everything, but there have been a couple of people at work who have asked me this and I honestly don't know.
|
I highly recommend to use [Costura.Fody](https://github.com/Fody/Costura) - by far the best and easiest way to embed resources in your assembly. It's available as NuGet package.
```
Install-Package Costura.Fody
```
After adding it to the project, it will automatically embed all references that are copied to the output directory into your *main* assembly. You might want to clean the embedded files by adding a target to your project:
```
Install-CleanReferencesTarget
```
You'll also be able to specify whether to include the pdb's, exclude certain assemblies, or extracting the assemblies on the fly. As far as I know, also unmanaged assemblies are supported.
**Update**
Currently, some people are trying to add [support for DNX](https://github.com/Fody/Fody/issues/206).
**Update 2**
For the lastest Fody version, you will need to have MSBuild 16 (so Visual Studio 2019). Fody version 4.2.1 will do MSBuild 15. (reference: [Fody is only supported on MSBuild 16 and above. Current version: 15](https://stackoverflow.com/questions/55795625/fody-is-only-supported-on-msbuild-16-and-above-current-version-15))
|
Just right-click your project in Visual Studio, choose Project Properties -> Resources -> Add Resource -> Add Existing File…
And include the code below to your App.xaml.cs or equivalent.
```
public App()
{
AppDomain.CurrentDomain.AssemblyResolve +=new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}
System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
string dllName = args.Name.Contains(',') ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(".dll","");
dllName = dllName.Replace(".", "_");
if (dllName.EndsWith("_resources")) return null;
System.Resources.ResourceManager rm = new System.Resources.ResourceManager(GetType().Namespace + ".Properties.Resources", System.Reflection.Assembly.GetExecutingAssembly());
byte[] bytes = (byte[])rm.GetObject(dllName);
return System.Reflection.Assembly.Load(bytes);
}
```
Here's my original blog post:
<http://codeblog.larsholm.net/2011/06/embed-dlls-easily-in-a-net-assembly/>
|
Embedding DLLs in a compiled executable
|
[
"",
"c#",
".net",
"dll",
"merge",
"linker",
""
] |
I know how to use JSON to create objects, but there doesn't seem to be away to use JSON to create an object that is of a specific object type.
Here's an example of an Object and creating an instance of it:
```
Person = function() { };
Person.prototype = {
FirstName: null,
GetFirstName: function() {
return this.FirstName;
}
};
//Create an instance of the Person Object
var me = new Person();
me.FirstName = "Chris";
alert(me.GetFirstName()); //alert the FirstName property
```
Now, I would like to use JSON to create a new Person object so that the GetFirstName function works on it.
Here's something like that I'm looking to do (but this code doesn't work):
```
var you = new Person() { FirstName: "Mike" };
// OR
var you = new Person{ FirstName: "Mike" };
```
Is there anyway to use JSON to create an object that is of a specific type?
UPDATE: My sample with the Person object is just to simplify the question. In fact, I am unable to modify the constructors of the actual objects that I need to create instances of. The objects are part of a third-party library.
UPDATE: Using some of the suggestions below, I was able to figure out a way to create an object that inherits from the original, and accept JSON in it's constructor. This is neat!
```
personWrapper = function(obj){
for(var o in obj){
this[o] = obj[o];
}
};
personWrapper.prototype = new Person();
var you = new personWrapper({FirstName: "Chris"});
alert(you.GetFirstName());
alert(you instanceof Person); // returns True - we are successfully inheriting from Person!
```
|
I don't imagine so. I'd create a function on the Person class to initialise from a JSON object if I were you.
```
function Person() {
this.loadFromJSON = function(json) {
this.FirstName = json.FirstName;
};
}
```
If you didn't know what class the JSON object was representing beforehand, perhaps add an extra variable into your JSON.
```
{ _className : "Person", FirstName : "Mike" }
```
And then have a 'builder' function which interprets it.
```
function buildFromJSON(json) {
var myObj = new json["_className"]();
myObj.loadFromJSON(json);
return myObj;
}
```
---
Update: since you say the class is part of a third-party library which you can't change, you could either extend the class with prototyping, or write a function which just populates the class externally.
eg:
```
Person.prototype.loadFromJSON = function(json) {
// as above...
};
```
or
```
function populateObject(obj, json) {
for (var i in json) {
// you might want to put in a check here to test
// that obj actually has an attribute named i
obj[i] = json[i];
}
}
```
|
You could allow new Person() to accept an object to populate attributes with as a parameter.
```
var you = new Person({ firstName: 'Mike' });
```
|
How to use JSON to create object that Inherits from Object Type?
|
[
"",
"javascript",
"json",
"inheritance",
""
] |
In order to help my team write testable code, I came up with this simple list of best practices for making our C# code base more testable. (Some of the points refer to limitations of Rhino Mocks, a mocking framework for C#, but the rules may apply more generally as well.) Does anyone have any best practices that they follow?
To maximize the testability of code, follow these rules:
1. **Write the test first, then the code.** Reason: This ensures that you write testable code and that every line of code gets tests written for it.
2. **Design classes using dependency injection.** Reason: You cannot mock or test what cannot be seen.
3. **Separate UI code from its behavior using Model-View-Controller or Model-View-Presenter.** Reason: Allows the business logic to be tested while the parts that can't be tested (the UI) is minimized.
4. **Do not write static methods or classes.** Reason: Static methods are difficult or impossible to isolate and Rhino Mocks is unable to mock them.
5. **Program off interfaces, not classes.** Reason: Using interfaces clarifies the relationships between objects. An interface should define a service that an object needs from its environment. Also, interfaces can be easily mocked using Rhino Mocks and other mocking frameworks.
6. **Isolate external dependencies.** Reason: Unresolved external dependencies cannot be tested.
7. **Mark as virtual the methods you intend to mock.** Reason: Rhino Mocks is unable to mock non-virtual methods.
|
Definitely a good list. Here are a few thoughts on it:
> **Write the test first, then the code.**
I agree, at a high level. But, I'd be more specific: "Write a test first, then write *just enough* code to pass the test, and repeat." Otherwise, I'd be afraid that my unit tests would look more like integration or acceptance tests.
> **Design classes using dependency injection.**
Agreed. When an object creates its own dependencies, you have no control over them. Inversion of Control / Dependency Injection gives you that control, allowing you to isolate the object under test with mocks/stubs/etc. This is how you test objects in isolation.
> **Separate UI code from its behavior using Model-View-Controller or Model-View-Presenter.**
Agreed. Note that even the presenter/controller can be tested using DI/IoC, by handing it a stubbed/mocked view and model. Check out [Presenter First](http://www.atomicobject.com/pages/Presenter+First) TDD for more on that.
> **Do not write static methods or classes.**
Not sure I agree with this one. It is possible to unit test a static method/class without using mocks. So, perhaps this is one of those Rhino Mock specific rules you mentioned.
> **Program off interfaces, not classes.**
I agree, but for a slightly different reason. Interfaces provide a great deal of flexibility to the software developer - beyond just support for various mock object frameworks. For example, it is not possible to support DI properly without interfaces.
> **Isolate external dependencies.**
Agreed. Hide external dependencies behind your own facade or adapter (as appropriate) with an interface. This will allow you to isolate your software from the external dependency, be it a web service, a queue, a database or something else. This is *especially* important when your team doesn't control the dependency (a.k.a. external).
> **Mark as virtual the methods you intend to mock.**
That's a limitation of Rhino Mocks. In an environment that prefers hand coded stubs over a mock object framework, that wouldn't be necessary.
And, a couple of new points to consider:
**Use creational design patterns.** This will assist with DI, but it also allows you to isolate that code and test it independently of other logic.
**Write tests using [Bill Wake's Arrange/Act/Assert technique](http://weblogs.java.net/blog/wwake/archive/2003/12/tools_especiall.html).** This technique makes it very clear what configuration is necessary, what is actually being tested, and what is expected.
**Don't be afraid to roll your own mocks/stubs.** Often, you'll find that using mock object frameworks makes your tests incredibly hard to read. By rolling your own, you'll have complete control over your mocks/stubs, and you'll be able to keep your tests readable. (Refer back to previous point.)
**Avoid the temptation to refactor duplication out of your unit tests into abstract base classes, or setup/teardown methods.** Doing so hides configuration/clean-up code from the developer trying to grok the unit test. In this case, the clarity of each individual test is more important than refactoring out duplication.
**Implement Continuous Integration.** Check-in your code on every "green bar." Build your software and run your full suite of unit tests on every check-in. (Sure, this isn't a coding practice, per se; but it is an incredible tool for keeping your software clean and fully integrated.)
|
If you are working with .Net 3.5, you may want to look into the [Moq](https://github.com/Moq/moq4) mocking library - it uses expression trees and lambdas to remove non-intuitive record-reply idiom of most other mocking libraries.
Check out this [quickstart](https://github.com/Moq/moq4/wiki/Quickstart) to see how much more intuitive your test cases become, here is a simple example:
```
// ShouldExpectMethodCallWithVariable
int value = 5;
var mock = new Mock<IFoo>();
mock.Expect(x => x.Duplicate(value)).Returns(() => value * 2);
Assert.AreEqual(value * 2, mock.Object.Duplicate(value));
```
|
Best Practices of Test Driven Development Using C# and RhinoMocks
|
[
"",
"c#",
"unit-testing",
"tdd",
"rhino-mocks",
""
] |
For a new Java web project I thought about using:
* Eclipse as IDE
* Mercurial for version control
* Some kind of bug tracking software
I have heard of bug tracking software where you can tie a change to an unresolved bug when you check it in. I haven't used any such solution myself, but it sounds good. Are there any good bug tracking applications which work well in combination with Eclipse and Mercurial and lets you tie a change to an unresolved bug? And if not, are there at least good plug ins for Eclipse to use Mercurial for version control? Would it support `hg rename` and `hg copy`?
If I can get something good working using a mix of the above three components I plan on throwing Hudson into the mix as well. To be able to track how changes in the code base affects our unit tests.
First of all I want feedback on the above question. But I would appreciate any thoughts regarding handling versioning, bug tracking and their integration into Eclipse.
|
In my experience the MercurialEclipse plug-in works quite well - as far as I understood, nobody commenting here has actually used it, so don't base your decisions solely on those opinions. You'd probably be better off to test it yourself. As I said before - it works for me.
Disclaimer: I've participated in developing the plug-in...
|
Vectrace offers [Mercurial Eclipse](http://www.vectrace.com/mercurialeclipse/). But, it doesn't sound finished.
For bug tracking, you may try [Trac](http://trac.edgewall.org/) with [TracMercurial](http://trac.edgewall.org/wiki/TracMercurial).
|
Eclipse as IDE + Mercurial for version control + ? Bug tracking = Good idea?
|
[
"",
"java",
"eclipse",
"mercurial",
"hudson",
"bug-tracking",
""
] |
I've created a language pack for a site before, but I'm not sure if what I'm doing is the best method.
Basically, all I have is a file with variables defining string constants. Usually a set of arrays where an array usually refers to a particular elements of the site.
Then the site code just includes the appropriate file based on a flag and then echo's out the appropriate array element.
What are some ways of doing this to reduce maintenance headaches and performance?
|
I suggest using [Zend\_Translate](http://framework.zend.com/manual/en/zend.translate.html). It is somewhat a combination of the other suggestions people left here, only more maintainable and better designed.
You can switch adapters depending on your preference (supports gettext, csv and a multitude of others), you don't need defines or globals polluting your global scope and it is well documented.
|
The best option you could have, with PHP, is [GetText](http://be.php.net/manual/en/book.gettext.php), but not all the server have it built-in, so it may be a show stopper if you're managing your server.
|
Best practices for creating various language-packs on a site? PHP
|
[
"",
"php",
"language-agnostic",
"language-packs",
""
] |
I have a C# interface with certain method parameters declared as `object` types. However, the actual type passed around can differ depending on the class implementing the interface:
```
public interface IMyInterface
{
void MyMethod(object arg);
}
public class MyClass1 : IMyInterface
{
public void MyMethod(object arg)
{
MyObject obj = (MyObject) arg;
// do something with obj...
}
}
public class MyClass2 : IMyInterface
{
public void MyMethod(object arg)
{
byte[] obj = (byte[]) arg;
// do something with obj...
}
}
```
The problem with MyClass2 is that the conversion of `byte[]` to and from `object` is [boxing and unboxing](http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx), which are computationally expensive operations affecting performance.
Would solving this problem with a [generic interface](http://msdn.microsoft.com/en-us/library/kwtft8ak.aspx) avoid boxing/unboxing?
```
public interface IMyInterface<T>
{
void MyMethod(T arg);
}
public class MyClass1 : IMyInterface<MyObject>
{
public void MyMethod(MyObject arg)
{
// typecast no longer necessary
//MyObject obj = (MyObject) arg;
// do something with arg...
}
}
public class MyClass2 : IMyInterface<byte[]>
{
public void MyMethod(byte[] arg)
{
// typecast no longer necessary
//byte[] obj = (byte[]) arg;
// do something with arg...
}
}
```
How is this implemented in .NET vs Mono? Will there be any performance implications on either platform?
Thank you!
|
I'm not sure how it is implemented in mono, but generic interfaces will help because the compiler creates a new function of the specific type for each different type used (internally, there are a few cases where it can utilize the same generated function). If a function of the specific type is generated, there is no need to box/unbox the type.
This is why the Collections.Generic library was a big hit at .NET 2.0 because collections no longer required boxing and became significantly more efficient.
|
You will get the same benefits in Mono that you do in .NET.
We strongly recommend that you use Mono 1.9 or Mono 2.0 RCx in general, as generics support only matured with 1.9.
|
Do generic interfaces in C# prevent boxing? (.NET vs Mono performance)
|
[
"",
"c#",
"performance",
"generics",
"mono",
"boxing",
""
] |
Is there any way (in Java Servlet) to determine whether a HTTP POST or GET request is a result from a submission from a HTML form or otherwise?
|
You could possibly do it with a hidden form field + a cookie.
What you could do is set up a [nonce](http://en.wikipedia.org/wiki/Cryptographic_nonce), and have that as the hidden field of the form. You would then apply that to a cookie that is sent along with the form. The cookie should be linked to the hidden field, and should also contain some kind of nonce. Finally, when the form is submitted, you can check the cookie and hidden field, and see if they are correct. If you want, link it up to the IP address and user agent of the original request for the form. You could even spice all this up with some Javascript. Make the hidden field blank to start with, but then some ajax to request the hidden field nonce from the server.
This won't be perfect, but that should get you 80%-90% of the way there. Someone with decent HTTP skills could still spoof it though.
It raises the question however, why do you want to differentiate the request at that level?
Or are you really just trying to figure out whether or not the user hit the "submit" button? (If that is the case, then the name/value pair of the submit button should be in the request entity/query string... depending on the form method.)
|
I think it is impossible unless the client itself is co-operating (means the client set some header)
|
How to differentiate a HTTP Request submitted from a HTML form and a HTTP Request submitted from a client?
|
[
"",
"java",
"http",
""
] |
I'm writing a website that will sell items from one of my classes. It will be linked to a SQL Server db where I will pull pricing, item name, quantity and description. If I wanted to display the items from the database in a thinkgeek fashion, what would be the best control to use so I can custimize the display to actually look ok?
|
You'll get the best flexibility with an asp:Repeater. This means you'll have to program more, but it will give you more flexibility.
|
Not sure if you have any technology requirements, but the ASP.Net has a new type of ASP.NET project called the [Dynamic Data project](http://msdn.microsoft.com/en-us/library/cc488546.aspx). Using that project you can point to your SQL Server and generate pages to display and edit the data. Pretty easy to get up and running quickly using that.
|
What is the best control to use to display items from a database?
|
[
"",
"c#",
"asp.net",
""
] |
I have used the XML Parser before, and even though it worked OK, I wasn't happy with it in general, it felt like I was using workarounds for things that should be basic functionality.
I recently saw SimpleXML but I haven't tried it yet. Is it any simpler? What advantages and disadvantages do both have? Any other parsers you've used?
|
I would have to say [SimpleXML](http://php.net/manual/simplexml.examples.php) takes the cake because it is firstly an extension, written in C, and is very fast. But second, the parsed document takes the form of a PHP object. So you can "query" like `$root->myElement`.
|
Have a look at PHP's [available XML extensions](http://php.net/manual/en/book.xml.php).
The main difference between XML Parser and SimpleXML is that the latter is not a pull parser. SimpleXML is built on top of the DOM extensions and will load the entire XML file into memory. XML Parser like XMLReader will only load the current node into memory. You define handlers for specific nodes which will get triggered when the Parser encounters it. That is faster and saves on memory. You pay for that with not being able to use XPath.
Personally, I find SimpleXml quite limiting (hence simple) in what it offers over DOM. You can switch between DOM and SimpleXml easily though, but I usually dont bother and go the DOM route directly. DOM is an implementation of the W3C DOM API, so you might be familiar with it from other languages, for instance JavaScript.
|
Best XML Parser for PHP
|
[
"",
"php",
"xml",
"parsing",
"xml-parsing",
""
] |
I frequently encounter some definitions for Win32API structures (but not limited to it) that have a `cbSize` member as in the following example.
```
typedef struct _TEST {
int cbSize;
// other members follow
} TEST, *PTEST;
```
And then we use it like this:
```
TEST t = { sizeof(TEST) };
...
```
or
```
TEST t;
t.cbSize = sizeof(TEST);
...
```
My initial guess is that this could potentially be used for versioning. A DLL that receives a pointer for a struct like this can check if the `cbSize` member has the expected value with which the DLL was compiled. Or to check if proper packing is done for the struct. But I would like to here from you.
**What is the purpose of the `cbSize` member in some C++ structures on Win32API?**
|
> My initial guess is that this could
> potentially be used for versioning.
That's one reason. I think it's the more usual one.
Another is for structures that have variable length data.
I don't think that checking for correct packing or bugs in the caller are a particular reasoning behind it, but it would have that effect.
|
It is used for versioning. A good example is the [GetVersionEx](http://msdn.microsoft.com/en-us/library/ms724451(VS.85).aspx) call. You can pass in either an [OSVERSIONINFO](http://msdn.microsoft.com/en-us/library/ms724834(VS.85).aspx) or [OSVERSIONINFOEX](http://msdn.microsoft.com/en-us/library/ms724833(VS.85).aspx). The OSVERSIONINFOEX is a superset of OSVERSIONINFO, and the only way the OS knows which you have passed in is by the dwOSVersionInfoSize member.
|
What is the purpose of the cbSize member in Win32API structs
|
[
"",
"c++",
"winapi",
"api",
""
] |
I'm familiar with some of the basics, but what I would like to know more about is when and why error handling (including throwing exceptions) should be used in PHP, especially on a live site or web app. Is it something that can be overused and if so, what does overuse look like? Are there cases where it shouldn't be used? Also, what are some of the common security concerns in regard to error handling?
|
One thing to add to what was said already is that it's paramount that you record any errors in your web application into a log. This way, as Jeff "Coding Horror" Atwood suggests, you'll know when your users are experiencing trouble with your app (instead of "asking them what's wrong").
To do this, I recommend the following type of infrastructure:
* Create a "crash" table in your database and a set of wrapper classes for reporting errors. I'd recommend setting categories for the crashes ("blocking", "security", "PHP error/warning" (vs exception), etc).
* In all of your error handling code, make sure to record the error. Doing this consistently depends on how well you built the API (above step) - it should be *trivial* to record crashes if done right.
Extra credit: sometimes, your crashes will be database-level crashes: i.e. DB server down, etc. If that's the case, your error logging infrastructure (above) will fail (you can't log the crash to the DB because the log tries to write to the DB). In that case, I would write failover logic in your Crash wrapper class to either
* send an email to the admin, AND/OR
* record the details of the crash to a plain text file
All of this sounds like an overkill, but believe me, this makes a difference in whether your application is accepted as a "stable" or "flaky". That difference comes from the fact that all apps start as flaky/crashing all the time, but those developers that know about all issues with their app have a chance to actually fix it.
|
Roughly speaking, errors are a legacy in PHP, while exceptions are the modern way to treat errors. The simplest thing then, is to set up an error-handler, that throws an exception. That way all errors are converted to exceptions, and then you can simply deal with one error-handling scheme. The following code will convert errors to exceptions for you:
```
function exceptions_error_handler($severity, $message, $filename, $lineno) {
if (error_reporting() == 0) {
return;
}
if (error_reporting() & $severity) {
throw new ErrorException($message, 0, $severity, $filename, $lineno);
}
}
set_error_handler('exceptions_error_handler');
error_reporting(E_ALL ^ E_STRICT);
```
There are a few cases though, where code is specifically designed to work with errors. For example, the [`schemaValidate` method of `DomDocument`](http://docs.php.net/manual/en/domdocument.schemavalidate.php) raises warnings, when validating a document. If you convert errors to exceptions, it will stop validating after the first failure. Some times this is what you want, but when validating a document, you might actually want *all* failures. In this case, you can temporarily install an error-handler, that collects the errors. Here's a small snippet, I've used for that purpose:
```
class errorhandler_LoggingCaller {
protected $errors = array();
function call($callback, $arguments = array()) {
set_error_handler(array($this, "onError"));
$orig_error_reporting = error_reporting(E_ALL);
try {
$result = call_user_func_array($callback, $arguments);
} catch (Exception $ex) {
restore_error_handler();
error_reporting($orig_error_reporting);
throw $ex;
}
restore_error_handler();
error_reporting($orig_error_reporting);
return $result;
}
function onError($severity, $message, $file = null, $line = null) {
$this->errors[] = $message;
}
function getErrors() {
return $this->errors;
}
function hasErrors() {
return count($this->errors) > 0;
}
}
```
And a use case:
```
$doc = new DomDocument();
$doc->load($xml_filename);
$validation = new errorhandler_LoggingCaller();
$validation->call(
array($doc, 'schemaValidate'),
array($xsd_filename));
if ($validation->hasErrors()) {
var_dump($validation->getErrors());
}
```
|
Error handling in PHP
|
[
"",
"php",
"error-handling",
""
] |
I've written a small hello world test app in Silverlight which i want to host on a Linux/Apache2 server. I want the data to come from MySQL (or some other linux compatible db) so that I can databind to things in the db.
I've managed to get it working by using the [MySQL Connector/.NET](http://www.mysql.com/products/connector/net/):
```
MySqlConnection conn = new MySqlConnection("Server=the.server.com;Database=theDb;User=myUser;Password=myPassword;");
conn.Open();
MySqlCommand command = new MySqlCommand("SELECT * FROM test;", conn);
using (MySqlDataReader reader = command.ExecuteReader())
{
StringBuilder sb = new StringBuilder();
while (reader.Read())
{
sb.AppendLine(reader.GetString("myColumn"));
}
this.txtResults.Text = sb.ToString();
}
```
This works fine if I give the published ClickOnce app full trust (or at least SocketPermission) and **run it locally**.
I want this to run on the server and I can't get it to work, always ending up with permission exception (SocketPermission is not allowed).
The database is hosted on the same server as the silverlight app if that makes any difference.
**EDIT**
Ok, I now understand why it's a bad idea to have db credentials in the client app (obviously). How do people do this then? How do you secure the proxy web service so that it relays data to and from the client/db in a secure way? Are there any examples out there on the web?
Surely, I cannot be the first person who'd like to use a database to power a silverlight application?
|
The easiest way to do what you want (having read through your edits now :)) will be to expose services that can be consumed. The pattern that Microsoft is REALLY pushing right now is to expose WCF services, but the truth is that your Silverlight client can use WCF to consume a lot of different types of services.
What may be easiest for you to do right now would be to use a .NET service on a web server or maybe a PHP REST service, and then point your Silverlight app at that service. By doing so, you're protecting your database not only from people snooping through it, but more importantly, you're restricting what people can do to your database. If your data is supposed to be read-only, and your service's contract only allows reading operations, you're set. Alternatively, your service may negotiate sessions with credentials, again, set up through WCF.
WCF can be a client-only, server-only, or client-server connector platform. What you choose will affect the code you write, but it's all going to be independent of your database. Your code can be structured such that it's a one-to-one mapping to your database table, or it can be far more abstract (you can set up classes that represent full logical views if you choose).
|
While the "official" answer is to use WCF to push a service to Silverlight, I kind of figure that anyone using MySQL would probably not be using a complete ASP.NET solution. My solution was to build a PHP webservice (like Rob suggested) to interact with the MySQL database and have the Silverlight access it in a RESTful manner.
Here is beginning of a three part tutorial for using Silverlight to access a MySQL database through a PHP web service:
[PHP, MySQL and Silverlight: The Complete Tutorial](http://www.designersilverlight.com/2010/05/23/php-mysql-and-silverlight-the-complete-tutorial-part-1/)
|
How to have silverlight get its data from MySQL
|
[
"",
"c#",
".net",
"mysql",
"silverlight",
"data-binding",
""
] |
I'm investigating the following `java.lang.VerifyError`:
```
java.lang.VerifyError: (class: be/post/ehr/wfm/application/serviceorganization/report/DisplayReportServlet, method: getMonthData signature: (IILjava/util/Collection;Ljava/util/Collection;Ljava/util/HashMap;Ljava/util/Collection;Ljava/util/Locale;Lorg/apache/struts/util/MessageRe˜̴Mt̴MÚw€mçw€mp:”MŒŒ
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2357)
at java.lang.Class.getConstructor0(Class.java:2671)
```
It occurs when the jboss server in which the servlet is deployed is started.
It is compiled with jdk-1.5.0\_11 and I tried to recompile it with jdk-1.5.0\_15 without succes. That is the compilation runs fine but when deployed, the java.lang.VerifyError occurs.
When I changed the method name and got the following error:
```
java.lang.VerifyError: (class: be/post/ehr/wfm/application/serviceorganization/report/DisplayReportServlet, method: getMD signature: (IILjava/util/Collection;Lj ava/util/Collection;Ljava/util/HashMap;Ljava/util/Collection;Ljava/util/Locale;Lorg/apache/struts/util/MessageResources ØÅN|ØÅNÚw€mçw€mX#ÖM|XÔM
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2357
at java.lang.Class.getConstructor0(Class.java:2671)
at java.lang.Class.newInstance0(Class.java:321)
at java.lang.Class.newInstance(Class.java:303)
```
You can see that more of the method signature is shown.
The actual method signature is:
```
private PgasePdfTable getMonthData(int month, int year, Collection dayTypes,
Collection calendarDays,
HashMap bcSpecialDays,
Collection activityPeriods,
Locale locale, MessageResources resources) throws Exception {
```
I already tried looking at it with `javap` and that gives the method signature as it should be.
When my other colleagues check out the code, compile it and deploy it, they have the same problem. When the build server picks up the code and deploys it on development or testing environments (HPUX), the same error occurs. Also an automated testing machine running Ubuntu shows the same error during server startup.
The rest of the application runs okay, only that one servlet is out of order.
Any ideas where to look would be helpful.
|
`java.lang.VerifyError` can be the result when you have compiled against a different library than you are using at runtime.
For example, this happened to me when trying to run a program that was compiled against Xerces 1, but Xerces 2 was found on the classpath. The required classes (in `org.apache.*` namespace) were found at runtime, so `ClassNotFoundException` was ***not*** the result. There had been changes to the classes and methods, so that the method signatures found at runtime did not match what was there at compile-time.
Normally, the compiler will flag problems where method signatures do not match. The JVM will verify the bytecode again when the class is loaded, and throws `VerifyError` when the bytecode is trying to do something that should not be allowed -- e.g. calling a method that returns `String` and then stores that return value in a field that holds a `List`.
|
`java.lang.VerifyError` are the worst.
You would get this error if the bytecode size of your method exceeds the 64kb limit; but you would probably have noticed that.
Are you 100% sure this class isn't present in the classpath elsewhere in your application, maybe in another jar?
Also, from your stacktrace, is the character encoding of the source file (`utf-8`?) Is that correct?
|
Causes of getting a java.lang.VerifyError
|
[
"",
"java",
"exception",
"deployment",
"runtime-error",
"verifyerror",
""
] |
In a [related question](https://stackoverflow.com/questions/168408/c-alternatives-to-void-pointers-that-isnt-templates) I asked about creating a generic container. Using polymorphic templates seems like the right way to go.
However, I can't for the life of me figure out how a destructor should be written. I want the owner of the memory allocated to be the containers even if the example constructor takes in an array of `T` (along with its dimensions), allocated at some other point.
I would like to be able to do something like
```
MyContainer<float> blah();
...
delete blah;
```
and
```
MyContainer<ComplexObjectType*> complexBlah();
...
delete complexBlah;`
```
Can I do something like this? Can I do it without smart pointers?
Again, thanks for your input.
|
I'd recommend if you want to store pointers to complex types, that you use your container as: `MyContainer<shared_ptr<SomeComplexType> >`, and for primitive types just use `MyContainer<float>`.
The `shared_ptr` should take care of deleting the complex type appropriately when it is destructed. And nothing fancy will happen when the primitive type is destructed.
---
You don't need much of a destructor if you use your container this way. How do you hold your items in the container? Do you use an STL container, or an array on the heap? An STL container would take care of deleting itself. If you delete the array, this would cause the destructor for each element to be executed, and if each element is a `shared_ptr`, the `shared_ptr` destructor will delete the pointer it itself is holding.
|
You most probably *do* want to use smart pointers here, it really simplifies the problem. However, just as an excercise, it's quite easy to determine if given type is pointer. Rough implementation (could be more elegant, but I dont want to introduce int2type):
```
typedef char YesType;
typedef char NoType[2];
template<typename T>
struct IsPointer
{
typedef NoType Result;
};
template<typename T>
struct IsPointer<T*>
{
typedef YesType Result;
};
template<typename T>
struct MyContainer
{
~MyContainer()
{
IsPointer<T>::Result r;
Clear(&r);
delete[] data;
}
void Clear(YesType*)
{
for (int i = 0; i < numElements; ++i)
delete data[i];
}
void Clear(NoType*) {}
T* data;
int numElements;
```
};
|
C++ template destructors for both primitive and complex data types
|
[
"",
"c++",
"templates",
""
] |
I'm developing an application for an internal customer. One of the requirements is that it be developed in such a way that it could potentially be sold to other organizations. The application is a tracking application for a fund-raising organization that will manage their donations, donors, participants, and events. I already know that I'll need to develop a plugin architecture for authentication (authorization will be handled internally) and to derive demographic data from an external directory.
The application will be built on ASP.NET/C#/Linq/SQL Server. At this point I'm not really open to supporting alternative databases, but I'm thinking I could do this in the future via different Linq drivers, if necessary.
All of the web applications that I've built to date have been custom implementations so I'd like to know if there are other things that I need to address via plugins and/or configuration items. Any input would be helpful.
Thanks.
|
I want to caution you against trying to make the "do everything" framework. This is a common mistake that a lot of developers make when trying to build their first few mass-market software apps.
You have a customer already, and they are likely bankrolling the initial version of the application. You need to deliver as much of what this customer needs as fast as you can or it fails before you even get to thinking about the mass-market.
Do yourself a favor and expect that this is the only customer that will EVER use or buy the application. Design your application pretty much the exact same as you would have designed any of your other custom apps in the past.
All you need to do in order to scale it out to other customers later is to stick to the stock asp.net features and functionality as much as possible, keep it as simple and lean as possible, and cut as many "advanced" features from version 1.x as you can get away with.
1.x will be your proving ground. Make sure you deliver an application that does what your initial customer needs it to do and that it does it exceedingly well.
If you are successful, and 1.x does actually meet most of your initial customer's requirements then you will know you also have an application that will meet most of the needs of any of your customers. Congratulations, you are already most of the way towards having a viable commercial market application!
Things to watch out for:
1. Do you really need to support multiple database platforms? Sure, you might have "some" customers that might "prefer" MySql to SQL Server. You will be tempted to try and write some magic DAL that can support Oracle, MySQL, VistaDB, SQL Server, etc. just by changing some config options or making the right selection in an installer. But the fact is that this kind of "platform" neutrality adds massive complexity to your design and imposes severe limitations on what features you take advantage of. Things like the provider design pattern may fool you into thinking that this kind of design isn't so hard... but you would be wrong. Be pragmatic and design your application so that it will be acceptable to 90% of your potential market. With data access in particular it is generally safe to say that 90% or more of the market willing to install and run an ASP.NET application are also capable and willing to use SQLExpress or SQL Server. In most cases You will save much more money and time by designing for just SQL server than you will ever make in additional sales from supporting multiple databases.
2. Try to avoid making "everything" configurable via online admin tools. For example, you will be tempted to have ALL text in the application configurable by admin tools. That's great, but it is also expensive. It takes longer to develop, requires that you increase the scope of your application to include a whole mess of admin tools that you wouldn't have otherwise needed, and it makes the application more complex and difficult to use for the 90% of your customers that don't mind the default text.
3. Carefully consider localization. If you don't think you will have a large international market stick to one language. Localization isn't too hard, but it does complicate every aspect of your code a little... and that adds up to a lot in any application of any size at all. My rule of thumb is to target only the language of my initial market. If the app has interest in other markets then I go back and do localization in version 2.x after I recoup some cash from version 1.0 and prove the application has a viable market in the first place. But if you know you will be in more than one language or culture, support localization from the very beginning.
4. For version 1.0, don't worry too much about drop-in modules or fancy service APIs. If you already had a lot of experience in reusable frameworks you would be able to have this stuff in version 1.0, but if you lack experience in this kind of architectures you will just waste too much time on these features in version 1.x and you will likely still get it wrong and have to re-architect in version 2.x anyway.
5. Make sure the application has REALLY good reporting. For the kind of application you are talking about, this will be what decides if the application even has a market at all. You need pretty reports that are not only sortable/filterable on screen, but are also printable. Put your money and time into this out of the gate.
|
The most important thing is to design it in such a way that it is completely generic i.e. there is no client specific information hard coded or embedded.
Anything client specific must be configurable through meta-data. How you do this is completely up to you, but the main ways are through XML, Database or properties files.
If you design it this way it could be on sold to any number of clients who will each have their own configuration files or data.
|
What are some common things to consider when developing a web-based application to be sold
|
[
"",
"c#",
"asp.net",
"architecture",
"web-applications",
"product",
""
] |
Given the following code (that doesn't work):
```
while True:
# Snip: print out current state
while True:
ok = get_input("Is this ok? (y/n)")
if ok.lower() == "y": break 2 # This doesn't work :(
if ok.lower() == "n": break
# Do more processing with menus and stuff
```
Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?
|
My first instinct would be to refactor the nested loop into a function and use `return` to break out.
|
Here's another approach that is short. The disadvantage is that you can only break the outer loop, but sometimes it's exactly what you want.
```
for a in xrange(10):
for b in xrange(20):
if something(a, b):
# Break the inner loop...
break
else:
# Continue if the inner loop wasn't broken.
continue
# Inner loop was broken, break the outer.
break
```
This uses the for / else construct explained at: [Why does python use 'else' after for and while loops?](https://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops)
Key insight: It only *seems* as if the outer loop always breaks. **But if the inner loop doesn't break, the outer loop won't either.**
The `continue` statement is the magic here. It's in the for-else clause. [By definition](https://stackoverflow.com/a/9980752/673991) that happens if there's no inner break. In that situation `continue` neatly circumvents the outer break.
|
How can I break out of multiple loops?
|
[
"",
"python",
"nested-loops",
"break",
"control-flow",
""
] |
One of the vagaries of my development system (Codegear C++Builder) is that some of the auto-generated headers insist on having...
```
using namespace xyzzy
```
...statements in them, which impact on my code when I least want or expect it.
Is there a way I can somehow cancel/override a previous "using" statement to avoid this.
Maybe...
```
unusing namespace xyzzy;
```
|
Nope. But there's a potential solution: if you enclose your include directive in a namespace of its own, like this...
```
namespace codegear {
#include "codegear_header.h"
} // namespace codegear
```
...then the effects of any using directives within that header are neutralized.
That might be problematic in some cases. That's why every C++ style guide strongly recommends *not* putting a "using namespace" directive in a header file.
|
No you can't *unuse* a namespace. The only thing you can do is putting the `using namespace`-statement a block to limit it's scope.
Example:
```
{
using namespace xyzzy;
} // stop using namespace xyzzy here
```
Maybe you can change the template which is used of your auto-generated headers.
|
How can I "unuse" a namespace?
|
[
"",
"c++",
"namespaces",
"c++builder",
""
] |
i am looking for opinions if the following problem maybe has a better/different/common solution:
---
I have a database for products which contains the names of the products in english (the default language of this application) and i need translations of the names if available.
Currently i have this setup:
A product table
```
CREATE TABLE products
(
id serial NOT NULL,
"name" character varying(255) NOT NULL,
CONSTRAINT products_pkey PRIMARY KEY (id)
)
```
and a product localization table
```
CREATE TABLE products_l10n
(
product_id serial NOT NULL,
"language" character(2) NOT NULL,
"name" character varying(255) NOT NULL,
CONSTRAINT products_l10n_pkey PRIMARY KEY (product_id, language),
CONSTRAINT products_l10n_product_id_fkey FOREIGN KEY (product_id)
REFERENCES products (id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE
)
```
and i use the following query to retrieve a list of localized products (german in this case) with fallback to the default english names:
```
SELECT p.id, COALESCE(pl.name, p.name)
from products p LEFT
JOIN products_l10n pl ON p.id = pl.product_id AND language = 'de';
```
The SQL code is in postgres dialect. Data is stored as UTF-8.
|
Looks good to me. The one thing I might change is the way you handle languages: that should probably be a separate table. Thus, you would have:
```
CREATE TABLE products_l10n
(
product_id serial NOT NULL,
language_id int NOT NULL,
"name" character varying(255) NOT NULL,
CONSTRAINT products_l10n_pkey PRIMARY KEY (product_id, language),
CONSTRAINT products_l10n_product_id_fkey FOREIGN KEY (product_id)
REFERENCES products (id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE
CONSTRAINT products_l10n_language_id_fkey FOREIGN KEY (language_id)
REFERENCES languages (id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE
)
CREATE TABLE languages
)
id serial not null
"language" character(2) NOT NULL
)
```
Besides that, I think you've got just about the best possible solution.
|
Looks good - similar to my preferred localization technique - what about wide characters (Japanese)? We always used nvarchar to handle that.
What we actually found, however in our international purchasing operation, was that there was no consistency across international boundaries on products, since the suppliers in each country were different, so we internationalized/localized our interface, but the databases were completely distinct.
|
Database localization
|
[
"",
"sql",
"database",
"localization",
""
] |
One of our unit tests is to populate properties within our business objects with random data.
These properties are of different intrinsic types and therefore we would like to use the power of generics to return data of the type you pass in. Something along the lines of:
```
public static T GetData<T>()
```
How would you go about approaching this? Would a low level interface work? (IConvertible)
|
It depends on what data you want to randomize, because the *way* or the *algorithm* you want to use is totally different depending on the type.
For example:
```
// Random int
Random r = new Random();
return r.Next();
// Random Guid
return Guid.NewGuid();
...
```
So this obviously makes the use of generics a nice semplification on the user's end, but it adds no value to the way you write the class. You could use a switch clause or a dictionary (like Jon Skeet suggests):
```
switch(typeof(T))
{
case System.Int32:
Random r = new Random();
return (T)r.Next();
case System.Guid:
return (T)Guid.NewGuid();
...
```
Then you would use the class as you expect:
```
RandomGenerator.GetData<Guid>();
...
```
|
You could keep the "easy to use" GetData interface you've got there, but internally have a Dictionary<Type, object> where each value is a Func<T> for the relevant type. GetData would then have an implementation such as:
```
public static T GetData<T>()
{
object factory;
if (!factories.TryGet(typeof(T), out factory))
{
throw new ArgumentException("No factory for type " + typeof(T).Name);
}
Func<T> factoryFunc = (Func<T>) factory;
return factoryFunc();
}
```
You'd then set up the factory dictionary in a static initializer, with one delegate for each type of random data you wanted to create. In some cases you could use a simple lambda expression (e.g. for integers) and in some cases the delegate could point to a method doing more work (e.g. for strings).
You may wish to use my [StaticRandom](http://pobox.com/~skeet/csharp/miscutil/usage/staticrandom.html) class for threads-safe RNG, by the way.
|
Get random data using Generics
|
[
"",
"c#",
"unit-testing",
"generics",
""
] |
I have a VB6 COM component which I need to call from my .Net method. I use reflection to create an instance of the COM object and activate it in the following manner:
```
f_oType = Type.GetTypeFromProgID(MyProgId);
f_oInstance = Activator.CreateInstance(f_oType);
```
I need to use GetTypeFromProgID rather than using tlbimp to create a library against the COM DLL as the ProgId of the type I need to instantiate can vary. I then use Type.InvokeMember to call the COM method in my code like:
```
f_oType.InvokeMember("Process", BindingFlags.InvokeMethod, null, f_oInstance, new object[] { param1, param2, param3, param4 });
```
I catch any raised TargetInvocationException's for logging and can get the detailed error description from the TargetInvocationException.InnerException field. However, I know that the COM component uses Error.Raise to generate an error number and I need to somehow get hold of this in my calling .Net application.
The problem seems to stem from the TargetInvocationException not containing the error number as I'd expect if it were a normal COMException so:
***How can I get the Error Number from the COM object in my .Net code?***
or
***Can I make this same call in a way that would cause a COMException (containing the error number) rather than a TargetInvocationException when the COM component fails?***
Please also note that the target platform is .Net 2.0 and I do have access to the VB6 source code but would regard altering the error message raised from VB6 to contain the error code as part of the text to be a bit of a hack.
|
I looked at your code a little closer and with reflection you handle TargetInvocationException and work with the inner exception that is a COMException... Code example below (I ran and tested this as well):
```
private void button1_Click(object sender, EventArgs e)
{
try
{
var f_oType = Type.GetTypeFromProgID("Project1.Class1");
var f_oInstance = Activator.CreateInstance(f_oType);
f_oType.InvokeMember("Test3", BindingFlags.InvokeMethod, null, f_oInstance, new object[] {});
}
catch(TargetInvocationException ex)
{
//no need to subtract -2147221504 if non custom error etc
int errorNumber = ((COMException)ex.InnerException).ErrorCode - (-2147221504);
MessageBox.Show(errorNumber.ToString() + ": " + ex.InnerException.Message);
}
catch(Exception ex)
{ MessageBox.Show(ex.Message); }
}
```
|
You will handle COMException and use the ErrorCode property of that exception object. Normally in visual basic DLLs if you are throwing custom errors you would raise the error with:
Err.Raise vbObjectError + 88, "Project1.Class1.Test3()", "Forced error test"
If this is the case you will need to subtract vbobjecterror (-2147221504) from the exceptions ErrorCode to get the actual error number. If not just use the ErrorCode value.
Example VB dll code: (from Project1.Class1)
Public Sub Test3()
```
MsgBox "this is a test 3"
Err.Raise vbObjectError + 88, "Project1.Class1.Test3()", "Forced error test"
```
End Sub
Example C# consumption handling code:
```
private void button1_Click(object sender, EventArgs e)
{
try
{
var p = new Class1();
p.Test3();
}
catch (COMException ex)
{
int errorNumber = (ex.ErrorCode - (-2147221504));
MessageBox.Show(errorNumber.ToString() + ": " + ex.Message);
}
catch(Exception ex)
{ MessageBox.Show(ex.Message); }
}
```
The ErrorCode in this test I just completed returns 88 as expected.
|
Retrieving the original error number from a COM method called via reflection
|
[
"",
"c#",
".net",
"com",
"interop",
""
] |
Is it possible to read and write Word (2003 and 2007) files in Python without using a COM object?
I know that I can:
```
f = open('c:\file.doc', "w")
f.write(text)
f.close()
```
but Word will read it as an HTML file not a native .doc file.
|
I'd look into [IronPython](http://ironpython.net/) which intrinsically has access to windows/office APIs because it runs on .NET runtime.
|
See [python-docx](https://github.com/python-openxml/python-docx), its official documentation is available [here](https://python-docx.readthedocs.org/en/latest/).
This has worked very well for me.
Note that this does not work for .doc files, only .docx files.
|
Reading/Writing MS Word files in Python
|
[
"",
"python",
"ms-word",
"read-write",
""
] |
In a C++ project, compilation dependencies can make a software project difficult to maintain. What are some of the best practices for limiting dependencies, both within a module and across modules?
|
* [Forward Declarations](http://en.wikipedia.org/wiki/Forward_declaration)
* [Abstract Interfaces](http://en.wikipedia.org/wiki/Abstract_interface)
* [The Pimpl Idiom](http://en.wikipedia.org/wiki/Opaque_pointer)
|
Herb Sutter has a great treatment of this exact topic in Items 26, 27 and 28, "Minimizing Compile-time Dependencies, Parts 1, 2 and 3", in his excellent book *Exceptional C++*, ISBN: 0201615622.
IMHO, this is one of the best C++ programming books available.
|
What are some techniques for limiting compilation dependencies in C++ projects?
|
[
"",
"c++",
"dependencies",
""
] |
What is the difference between `UNION` and `UNION ALL`?
|
`UNION` removes duplicate rows (where all columns in the results are the same), `UNION ALL` does not.
There is a performance hit when using `UNION` instead of `UNION ALL`, since the database server must do additional work to remove the duplicate rows, but usually you do not want the duplicates (especially when developing reports).
To identify duplicates, rows must be comparable types as well as compatible types. This will depend on the SQL system. For example the system may truncate all long text columns to make short text columns for comparison (MS Jet), or may refuse to compare binary columns (ORACLE)
### UNION Example:
```
SELECT 'foo' AS bar
UNION
SELECT 'foo' AS bar
```
**Result:**
```
+-----+
| bar |
+-----+
| foo |
+-----+
1 row in set (0.00 sec)
```
### UNION ALL example:
```
SELECT 'foo' AS bar
UNION ALL
SELECT 'foo' AS bar
```
**Result:**
```
+-----+
| bar |
+-----+
| foo |
| foo |
+-----+
2 rows in set (0.00 sec)
```
|
Both UNION and UNION ALL concatenate the result of two different SQLs. They differ in the way they handle duplicates.
* UNION performs a DISTINCT on the result set, eliminating any duplicate rows.
* UNION ALL does not remove duplicates, and it therefore faster than UNION.
> **Note:** While using this commands all selected columns need to be of the same data type.
Example: If we have two tables, 1) Employee and 2) Customer
1. Employee table data:

2. Customer table data:

3. UNION Example (It removes all duplicate records):

4. UNION ALL Example (It just concatenate records, not eliminate duplicates, so it is faster than UNION):

|
What is the difference between UNION and UNION ALL?
|
[
"",
"sql",
"union",
"union-all",
""
] |
Is there an open-source alternative to MATLAB's [`fmincon`](https://www.mathworks.com/help/optim/index.html;jsessionid=95cd06964ab253598de29e7d0a80) function for constrained linear optimization? I'm rewriting a MATLAB program to use Python / [NumPy](https://numpy.org/) / [SciPy](https://scipy.org/) and this is the only function I haven't found an equivalent to. A NumPy-based solution would be ideal, but any language will do.
|
Is your problem convex? Linear? Non-linear? I agree that SciPy.optimize will probably do the job, but fmincon is a sort of bazooka for solving optimization problems, and you'll be better off if you can confine it to one of the categories below (in increasing level of difficulty to solve efficiently)
* Linear Program (LP)
* Quadratic Program (QP)
* Convex Quadratically-Constrained Quadratic Program (QCQP)
* Second Order Cone Program (SOCP)
* Semidefinite Program (SDP)
* Non-Linear Convex Problem
* Non-Convex Problem
There are also combinatoric problems such as Mixed-Integer Linear Programs (MILP), but you didn't mention any sort of integrality constraints, suffice to say that they fall into a different class of problems.
The CVXOpt package will be of great use to you if your problem is convex.
If your problem is not convex, you need to choose between finding a local solution or the global solution. Many convex solvers 'sort of' work in a non-convex domain. Finding a good approximation to the global solution would require some form Simulated Annealing or Genetic Algorithm. Finding the global solution will require an enumeration of all local solutions or a combinatorial strategy such as Branch and Bound.
|
Python optimization software:
* **OpenOpt** <http://openopt.org> **(this one is numpy-based as you wish, with automatic differentiation by FuncDesigner)**
* **Pyomo** <https://software.sandia.gov/trac/coopr/wiki/Package/pyomo>
* **CVXOPT** <http://abel.ee.ucla.edu/cvxopt/>
* **NLPy** <http://nlpy.sourceforge.net/>
|
Open source alternative to MATLAB's fmincon function?
|
[
"",
"python",
"numpy",
"matlab",
"numeric",
"scientific-computing",
""
] |
I'm trying:
```
import commands
print commands.getoutput("ps -u 0")
```
But it doesn't work on os x.
os instead of commands gives the same output:
USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND
nothing more
|
This works on Mac OS X 10.5.5. Note the capital **-U** option. Perhaps that's been your problem.
```
import subprocess
ps = subprocess.Popen("ps -U 0", shell=True, stdout=subprocess.PIPE)
print ps.stdout.read()
ps.stdout.close()
ps.wait()
```
Here's the Python version
```
Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53)
[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin
```
|
If the OS support the /proc fs you can do:
```
>>> import os
>>> pids = [int(x) for x in os.listdir('/proc') if x.isdigit()]
>>> pids
[1, 2, 3, 6, 7, 9, 11, 12, 13, 15, ... 9406, 9414, 9428, 9444]
>>>
```
A cross-platform solution (linux, freebsd, osx, windows) is by using [psutil](http://code.google.com/p/psutil/):
```
>>> import psutil
>>> psutil.pids()
[1, 2, 3, 6, 7, 9, 11, 12, 13, 15, ... 9406, 9414, 9428, 9444]
>>>
```
|
Which is the best way to get a list of running processes in unix with python?
|
[
"",
"python",
""
] |
Is it possible to read and write Word (2003 and 2007) files in PHP without using a COM object?
I know that I can:
```
$file = fopen('c:\file.doc', 'w+');
fwrite($file, $text);
fclose();
```
but Word will read it as an HTML file not a native .doc file.
|
Reading binary Word documents would involve creating a parser according to the published file format specifications for the DOC format. I think this is no real feasible solution.
You could use the [Microsoft Office XML formats](http://en.wikipedia.org/wiki/Microsoft_Office_XML_formats#Word_XML_Format_example) for reading and writing Word files - this is compatible with the 2003 and 2007 version of Word. For reading you have to ensure that the Word documents are saved in the correct format (it's called Word 2003 XML-Document in Word 2007). For writing you just have to follow the openly available XML schema. I've never used this format for writing out Office documents from PHP, but I'm using it for reading in an Excel worksheet (naturally saved as XML-Spreadsheet 2003) and displaying its data on a web page. As the files are plainly XML data it's no problem to navigate within and figure out how to extract the data you need.
The other option - a Word 2007 only option (if the OpenXML file formats are not installed in your Word 2003) - would be to ressort to [OpenXML](http://en.wikipedia.org/wiki/Office_Open_XML). As [databyss](https://stackoverflow.com/users/9094/databyss) pointed out [here](https://stackoverflow.com/questions/188452/readingwriting-a-ms-word-file-in-php#191849) the DOCX file format is just a ZIP archive with XML files included. There are a lot of resources on [MSDN](http://msdn.microsoft.com/en-us/office/default.aspx) regarding the OpenXML file format, so you should be able to figure out how to read the data you want. Writing will be much more complicated I think - it just depends on how much time you'll invest.
**Perhaps you can have a look at [PHPExcel](http://www.codeplex.com/PHPExcel/) which is a library able to write to Excel 2007 files and read from Excel 2007 files using the OpenXML standard. You could get an idea of the work involved when trying to read and write OpenXML Word documents.**
|
this works with vs < office 2007 and its pure PHP, no COM crap, still trying to figure 2007
```
<?php
/*****************************************************************
This approach uses detection of NUL (chr(00)) and end line (chr(13))
to decide where the text is:
- divide the file contents up by chr(13)
- reject any slices containing a NUL
- stitch the rest together again
- clean up with a regular expression
*****************************************************************/
function parseWord($userDoc)
{
$fileHandle = fopen($userDoc, "r");
$line = @fread($fileHandle, filesize($userDoc));
$lines = explode(chr(0x0D),$line);
$outtext = "";
foreach($lines as $thisline)
{
$pos = strpos($thisline, chr(0x00));
if (($pos !== FALSE)||(strlen($thisline)==0))
{
} else {
$outtext .= $thisline." ";
}
}
$outtext = preg_replace("/[^a-zA-Z0-9\s\,\.\-\n\r\t@\/\_\(\)]/","",$outtext);
return $outtext;
}
$userDoc = "cv.doc";
$text = parseWord($userDoc);
echo $text;
?>
```
|
Reading/Writing a MS Word file in PHP
|
[
"",
"php",
"ms-word",
"read-write",
""
] |
Suppose I have one list:
```
IList<int> originalList = new List<int>();
originalList.add(1);
originalList.add(5);
originalList.add(10);
```
And another list...
```
IList<int> newList = new List<int>();
newList.add(1);
newList.add(5);
newList.add(7);
newList.add(11);
```
How can I update originalList so that:
1. If the int appears in newList, keep
2. If the int does not appear in newList, remove
3. Add any ints from newList into originalList that aren't there already
Thus - making the contents of originalList:
```
{ 1, 5, 7, 11 }
```
The reason I'm asking is because I have an object with a collection of children. When the user updates this collection, instead of just deleting all children, then inserting their selections, I think it would be more efficient if I just acted on the children that were added or removed, rather than tearing down the whole collection, and inserting the newList children as if they are all new.
EDIT - Sorry - I wrote a horrible title... I should have written 'least amount of code' instead of 'efficient'. I think that threw off alot of the answers I've gotten. They are all great... thank you!
|
Sorry, wrote my first response before I saw your last paragraph.
```
for(int i = originalList.length-1; i >=0; --i)
{
if (!newList.Contains(originalList[i])
originalList.RemoveAt(i);
}
foreach(int n in newList)
{
if (!originaList.Contains(n))
originalList.Add(n);
}
```
|
```
originalList = newList;
```
Or if you prefer them being distinct lists:
```
originalList = new List<int>(newList);
```
But, either way does what you want. By your rules, after updating, originalList will be identical to newList.
UPDATE: I thank you all for the support of this answer, but after a closer reading of the question, I believe my other response (below) is the correct one.
|
What is the least amount of code needed to update one list with another list?
|
[
"",
"c#",
"generics",
"merge",
"generic-list",
""
] |
I am trying to use `WebClient` to download a file from web using a WinForms application. However, I really only want to download HTML file. Any other type I will want to ignore.
I checked the `WebResponse.ContentType`, but its value is always `null`.
Anyone have any idea what could be the cause?
|
Given your update, you can do this by changing the .Method in GetWebRequest:
```
using System;
using System.Net;
static class Program
{
static void Main()
{
using (MyClient client = new MyClient())
{
client.HeadOnly = true;
string uri = "http://www.google.com";
byte[] body = client.DownloadData(uri); // note should be 0-length
string type = client.ResponseHeaders["content-type"];
client.HeadOnly = false;
// check 'tis not binary... we'll use text/, but could
// check for text/html
if (type.StartsWith(@"text/"))
{
string text = client.DownloadString(uri);
Console.WriteLine(text);
}
}
}
}
class MyClient : WebClient
{
public bool HeadOnly { get; set; }
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest req = base.GetWebRequest(address);
if (HeadOnly && req.Method == "GET")
{
req.Method = "HEAD";
}
return req;
}
}
```
Alternatively, you can check the header when overriding GetWebRespons(), perhaps throwing an exception if it isn't what you wanted:
```
protected override WebResponse GetWebResponse(WebRequest request)
{
WebResponse resp = base.GetWebResponse(request);
string type = resp.Headers["content-type"];
// do something with type
return resp;
}
```
|
I'm not sure the cause, but perhaps you hadn't downloaded anything yet. This is the lazy way to get the content type of a remote file/page (I haven't checked if this is efficient on the wire. For all I know, it may download huge chunks of content)
```
Stream connection = new MemoryStream(""); // Just a placeholder
WebClient wc = new WebClient();
string contentType;
try
{
connection = wc.OpenRead(current.Url);
contentType = wc.ResponseHeaders["content-type"];
}
catch (Exception)
{
// 404 or what have you
}
finally
{
connection.Close();
}
```
|
How to check if System.Net.WebClient.DownloadData is downloading a binary file?
|
[
"",
"c#",
"file",
"download",
"webclient",
""
] |
im creating a Factory class that will contruct and return an object. I normally would do all of the data stuff at the Data Access Layer, but i dont think i could reach my objective and still do so. What i want to do is use a SQLDataReader to quickly read the data information and populate the object to be returned from the factory. Is this a stupid idea? Is there a better approach? I would prefer not to just return a DataSet from the DAL if possible, or is it a question of performance vs. maintainability?
|
In most cases this is a good idea as this way provides two major benefits:
1. This way you can seperate the data access and business logic, which means if you change database design the upper layer algorithms do not need to be changed.
2. From OO stand point, you are converting some pure data into objects and may also added behavior to the objects, which makes the code easier to maintain and reuseable.
|
If you're sure you're going to be using all of the data you load from the SQLDataReader, then yes, you could do it at construction time in the factory. However if the data set has many fields, which only a minority of will be used, then demand-loading the data at the time the accessors are called would be a better use of resources.
That said, I suggest you load it in the factory when you have all the 'pieces' at hand, and if it's not exactly right, you'll know what needs fixing. Always start with the simplest thing that could possibly work.
|
Factory Class - Should i populate my object with data here?
|
[
"",
"c#",
".net",
"factory",
""
] |
I would like to be able to trap `Ctrl`+`C` in a C# console application so that I can carry out some cleanups before exiting. What is the best way of doing this?
|
See MSDN:
[Console.CancelKeyPress Event](https://learn.microsoft.com/en-us/dotnet/api/system.console.cancelkeypress?view=net-6.0)
Article with code samples:
[Ctrl-C and the .NET console application](https://web.archive.org/web/20200810221940/http://geekswithblogs.net/mrnat/archive/2004/09/23/11594.aspx)
|
The [Console.CancelKeyPress](https://learn.microsoft.com/en-us/dotnet/api/system.console.cancelkeypress) event is used for this. This is how it's used:
```
public static void Main(string[] args)
{
Console.CancelKeyPress += delegate {
// call methods to clean up
};
while (true) {}
}
```
When the user presses `Ctrl`+`C` the code in the delegate is run and the program exits. This allows you to perform cleanup by calling necessary methods. Note that no code after the delegate is executed.
There are other situations where this won't cut it. For example, if the program is currently performing important calculations that can't be immediately stopped. In that case, the correct strategy might be to tell the program to exit after the calculation is complete. The following code gives an example of how this can be implemented:
```
class MainClass
{
private static bool keepRunning = true;
public static void Main(string[] args)
{
Console.CancelKeyPress += delegate(object? sender, ConsoleCancelEventArgs e) {
e.Cancel = true;
MainClass.keepRunning = false;
};
while (MainClass.keepRunning) {
// Do your work in here, in small chunks.
// If you literally just want to wait until Ctrl+C,
// not doing anything, see the answer using set-reset events.
}
Console.WriteLine("exited gracefully");
}
}
```
The difference between this code and the first example is that `e.Cancel` is set to true, which means the execution continues after the delegate. If run, the program waits for the user to press `Ctrl`+`C`. When that happens the `keepRunning` variable changes value which causes the while loop to exit. This is a way to make the program exit gracefully.
|
How do I trap Ctrl+C (SIGINT) in a C# console app?
|
[
"",
"c#",
".net",
"console",
""
] |
I am using the next class (simplified for the sake of understandability) to download images in a struts web application.
It is working fine in every browser but firefox, which cuts names containing spaces. That it is to say: **file with spaces.pdf** gets downloaded in firefox as: **file** while in chrome, IE7 IE6 is downloaded as **file with spaces.pdf**.
```
public class Download extends Action {
private static final int BUFFER_SIZE = 4096;
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
String filename = "file with spaces.pdf";
File file = ... // variable containing the file;
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType(getMimeType(request, file));
response.setHeader("Content-Type", getMimeType(request, file));
response.setHeader("Content-Disposition","attachment; filename="+ filename);
InputStream is = new FileInputStream(file);
sendFile(is, response);
return null;
}
protected String getMimeType(HttpServletRequest request, File file) {
ServletContext application = super.servlet.getServletContext();
return application.getMimeType(file.getName());
}
protected void sendFile(InputStream is, HttpServletResponse response) throws IOException {
BufferedInputStream in = null;
try {
int count;
byte[] buffer = new byte[BUFFER_SIZE];
in = new BufferedInputStream(is);
ServletOutputStream out = response.getOutputStream();
while(-1 != (count = in.read(buffer)))
out.write(buffer, 0, count);
out.flush();
} catch (IOException ioe) {
System.err.println("IOException in Download::sendFile");
ioe.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ioe) { ioe.printStackTrace(); }
}
}
}
}
```
Does anyone know about what is going on here? Note i am using firefox 3.0.3 under Windows Vista.
|
The filename should be a **quoted** string. (According to [Section 19.5.1 of RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.5.1))
```
response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
```
|
URLEncode the filename?
Or at least substitute %20 for the space character.
(I don't know if this will work, but give it a try)
have you tried just putting quotes around the filename as well?
|
Firefox cuts files, whose name contains spaces, in a Struts application
|
[
"",
"java",
"firefox",
"struts",
""
] |
This is clearly not appears like it wouldn't be a best practice. Can someone explain why it would not be a best practice or how this works? Any books or articles providing an explanation would be appreciated.
```
//The constructor
public Page_Index() {
//create a local value
string currentValue = "This is the FIRST value";
//use the local variable in a delegate that fires later
this.Load += delegate(object sender, EventArgs e) {
Response.Write(currentValue);
};
//change it again
currentValue = "This is the MODIFIED value";
}
```
The value that is output is the second value *"Modified"*. What part of the compiler magic is making this work? Is this as simple as keeping track of the value on the heap and retrieving it again later?
[Edit]: Given some of the comments, changing the original sentence some...
|
currentValue is no longer a local variable: it is a *captured* variable. This compiles to something like:
```
class Foo {
public string currentValue; // yes, it is a field
public void SomeMethod(object sender, EventArgs e) {
Response.Write(currentValue);
}
}
...
public Page_Index() {
Foo foo = new Foo();
foo.currentValue = "This is the FIRST value";
this.Load += foo.SomeMethod;
foo.currentValue = "This is the MODIFIED value";
}
```
Jon Skeet has a really good write up of this in [C# in Depth](http://www.manning.com/skeet/), and a separate (not as detailed) discussion [here](http://csharpindepth.com/Articles/Chapter5/Closures.aspx).
Note that the variable currentValue is now on the heap, not the stack - this has lots of implications, not least that it can now be used by various callers.
This is different to java: in java the *value* of a variable is captured. In C#, the *variable itself* is captured.
|
> I suppose more the question I am asking is that how is it working with a local variable
> [MG edit: "Ack - ignore this..." was added afterwards]
That is the point; it really *isn't* a local variable any more - at least, not in terms of how we normally think of them (on the stack etc). It looks like one, but it isn't.
And for info, re "not good practice" - anonymous methods and captured variables are actually an incredibly powerful tool, *especially* when working with events. Feel free to use them, but if you are going down this route, I would recommend picking up Jon's book to make sure you understand what is actually happening.
|
Local variables with Delegates
|
[
"",
"c#",
"delegates",
"closures",
"heap-memory",
""
] |
How can I drop sql server agent jobs, if (and only if) it exists?
This is a well functioning script for *stored procedures*. How can I do the same to sql server agent jobs?
```
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[storedproc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[storedproc]
GO
CREATE PROCEDURE [dbo].[storedproc] ...
```
|
Try something like this:
```
DECLARE @jobId binary(16)
SELECT @jobId = job_id FROM msdb.dbo.sysjobs WHERE (name = N'Name of Your Job')
IF (@jobId IS NOT NULL)
BEGIN
EXEC msdb.dbo.sp_delete_job @jobId
END
DECLARE @ReturnCode int
EXEC @ReturnCode = msdb.dbo.sp_add_job @job_name=N'Name of Your Job'
```
Best to read the docs on all the parameters required for ['sp\_add\_job'](http://msdn.microsoft.com/en-us/library/ms182079.aspx) and ['sp\_delete\_job'](http://msdn.microsoft.com/en-us/library/ms188376.aspx)
|
```
IF EXISTS (SELECT job_id
FROM msdb.dbo.sysjobs_view
WHERE name = N'Your Job Name')
EXEC msdb.dbo.sp_delete_job @job_name=N'Your Job Name'
, @delete_unused_schedule=1
```
|
SQL Server Agent Job - Exists then Drop?
|
[
"",
"sql",
"sql-server",
"sql-server-agent",
"sql-job",
""
] |
According to select name from system\_privilege\_map System has been granted:
```
SELECT ANY TABLE
```
...and lots of other \* ANY TABLES.
Plainly running
```
select * from the_table;
select * from the_table;
```
...nets the given response:
> ERROR at line 1:
> ORA-00942: table or view does not exist
I can log in as that user and run the same command just fine.
I'm running under the assumption I should be able to run queries (select in this case) agaisnt a general user's DB table. Is my assumption correct, and if so, how do I do it?
|
If the\_table is owned by user "some\_user" then:
```
select * from some_user.the_table;
```
|
As the previous responses have said, you can prefix the object name with the schema name:
```
SELECT * FROM schema_name.the_table;
```
Or you can use a synonym (private or public):
```
CREATE (PUBLIC) SYNONYM the_table FOR schema_name.the_table;
```
Or you can issue an alter session command to set the default schema to the the one you want:
```
ALTER SESSION SET current_schema=schema_name;
```
Note that this just sets the default schema, and is the equivalent of prefixing all (unqualified) object names with `schema_name`. You can still prefix objects with a different schema name to access an object from another schema. Using `SET current_schema` does not affect your privileges: you still have the privileges of the user you logged in as, not the schema you have set.
|
As System in Sqlplus, how do I query another user's table?
|
[
"",
"sql",
"oracle",
"sqlplus",
"ora-00942",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.