Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
I have inherited a client site which crashes every 3 or 4 days. It is built using the zend-framework with which I have no knowledge.
The following code:
```
<?php
// Make sure classes are in the include path.
ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . 'lib' . PATH_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'classes');
// Use autoload so include or require statements are not needed.
require_once 'Zend/Loader.php';
Zend_Loader::registerAutoload();
// Run the application.
App_Main::run('production');
```
Is causing the following error:
```
[Tue Sep 02 12:58:45 2008] [error] [client 78.***.***.32] PHP Warning: require_once(Zend/Loader.php) [function.require-once]: failed to open stream: No such file or directory in /srv/www/vhosts/example.co.uk/httpdocs/bootstrap.php on line 6
[Tue Sep 02 12:58:45 2008] [error] [client 78.***.***.32] PHP Fatal error: require_once() [function.require]: Failed opening required 'Zend/Loader.php' (include_path='.:.:/usr/share/php5:/usr/share/php5/PEAR') in /srv/www/vhosts/example.co.uk/httpdocs/bootstrap.php on line 6
```
I don't even know where to begin trying to fix this. My level of knowledge of PHP is intermediate but like I said, I have no experience with Zend. Also, contacting the original developer is not an option.
The interesting thing is that even though the code is run every time a page of the site is hit the error is only happening every now and then.
I believe it must be something to do with the include\_path but I am not sure.
|
for a start I think your include path should maybe have a trailing slash. Here is an example of mine :
```
set_include_path('../library/ZendFramework-1.5.2/library/:../application/classes/:../application/classes/excpetions/:../application/forms/');
```
You bootstrap file will be included by another file (probably an index.php file). This means that if your include path is relative (as mine is) instead of absolute, then the path at which Loader.php is looked for changes if the file including bootstrap.php changes.
For example, I have two index.php files in my Zend app, one for the front end, and one for the admin area. These index files each need there own bootstrap.php with different relative paths in because they are included by different index files, which means they **have to be relative to the original requested index file, not the bootstrap file they are defined within**.
This could explain why your problem is intermittent, there could be another file including the bootstrap somewhere that is only used occasionally. I'd search through all the sites files for 'bootstrap.php' and see all the places which are including / requiring this file.
|
The fact that it only happens sporadically makes me think this is less of a programming issue, and more of a sysadmin issue - if it were a defect in the implementation, you'd expect it to fail consistently considering the error is "No such file or directory". Two guesses
* There are multiple front-end web servers, and one of them is mis-configured (missing the Zend Framework).
* The PEAR include directory is network mounted, and occasionally vanishes for short periods of time.
It could be a more insidious file system problem, but one would think this would effect more than just one file.
|
Failed to load Zend/Loader.php. Trying to work out why?
|
[
"",
"php",
"zend-framework",
""
] |
I am using [Hibernate](http://www.hibernate.org/) in a Java application to access my Database and it works pretty well with MS-SQL and MySQL. But some of the data I have to show on some forms has to come from Text files, and by Text files I mean Human-Readable files, they can be CSV, Tab-Delimited, or even a key, value pair, per line since my data is as simple as this, but my preference of course is XML files.
My question is: Can I use hibernate to read those files using HQL, Query , EntityManager and all those resources Hibernate provides me to access files. Which file format should I use and How I configure My persistence.xml file to recognize files as Tables?
|
Hibernate is written against the JDBC API. So, you need a JDBC driver that works with the file format you are interested in. Obviously, even for read-only access, this isn't going to perform well, but it might still be useful if that's not a high priority. On a Windows system, you can set up ODBC datasources for delimited text files, Excel files, etc. Then you can set up the JdbcOdbcDriver in your Java application to use this data source.
For most of the applications I work on, I would not consider this approach; I would use an import/export mechanism to convert from a real database (even if it's an in-process database like Berkeley DB or Derby) to the text files. Yes, it's an extra step, but it could be automated, and the performance isn't likely to be much worse than trying to use the text files directly (it will likely be much better, overall), and it will be more robust and easy to develop.
|
A quick google came up with
* [JDBC driver for csv files](http://sourceforge.net/projects/csvjdbc)
* [JDBC driver for XML files](http://www.csv-jdbc.com/stels_xml_jdbc.htm)
Hope this might provide some inspiration?
|
Using Hibernate to work with Text Files
|
[
"",
"java",
"database",
"hibernate",
"text-files",
""
] |
I know I must be missing something, but in a `while` statement how does the variable hold the data, when it finishes the first pass and goes into the second pass?
---
{
```
int num1 = 0 ;
int num2 = 0;
int num3 = 0;
while (num1 < 10)
{cout << "enter your first number: ";
cin >> num1;
cout << "Enter your second number: ";
cin >> num2;
num1 = num1 + num2 ;
cout << "Number 1 is now: " << num1 <<endl;
cout << "Enter Number 3: " ;
cin >> num3;
num1 = num1 + num3;
cout << "Number 1 is now: " << num1 << endl;
num1++;
};
```
In this code. The Variable doesn't hold the data. I'm not sure what I'm doing wrong!
|
Is num1 the variable you're having trouble with? This line:
```
cin >> num1;
```
is setting num1 to the value input by the user. So the value calculated for it in the previous run through the loop is being overwritten each time by the new input.
|
I'm not clear exactly what you're asking, but variables will maintain their value for each iteration of a loop, as long as they're declared outside of the loop itself. For example:
```
int a = 0;
while(a < 10)
{
int b = 0;
cout << "a: " << a << " b: " << b << "\n";
a++;
b++;
}
```
In the above, the value output for b will always be 0, as it's declared inside the loop and is being reinitialized each time, whereas a will maintain its value and get incremented each iteration. If b were an object, rather than an int, its constructor and destructor would get called each iteration.
|
Variable Holding data in a while statement
|
[
"",
"c++",
""
] |
Is it possible for gcc to link against a library that was created with Visual C++? If so, are there any conflicts/problems that might arise from doing so?
|
Some of the comments in the answers here are slightly too generalistic.
Whilst no, in the specific case mentioned gcc binaries won't link with a VC++ library (AFAIK). The actual means of interlinking code/libraries is a question of the ABI standard being used.
An increasingly common standard in the embedded world is the EABI (or ARM ABI) standard (based on work done during Itanium development <http://www.codesourcery.com/cxx-abi/>). If compilers are EABI compliant they can produce executables and libraries which will work with each other. An example of multiple toolchains working together is ARM's RVCT compiler which produces binaries which will work with GCC ARM ABI binaries.
(The code sourcery link is down at the moment but can be google cached)
|
I would guess not. Usually c++ compilers have quite different methods of name-mangling which means that the linkers will fail to find the correct symbols. This is a good thing by the way, because C++ compilers are allowed by the standard to have much greater levels of incompatibility than just this that will cause your program to crash, die, eat puppies and smear paint all over the wall.
Usual schemes to work around this usually involve language independent techniques like COM or CORBA. A simpler sanctified method is to use C "wrappers" around your C++ code.
|
Mixing C/C++ Libraries
|
[
"",
"c++",
"visual-studio",
"gcc",
"linker",
""
] |
There are two popular closure styles in javascript. The first I call *anonymous constructor*:
```
new function() {
var code...
}
```
and the *inline executed function*:
```
(function() {
var code...
})();
```
are there differences in behaviour between those two? Is one "better" over the other?
|
Both cases will execute the function, the only real difference is what the return value of the expression may be, and what the value of "this" will be inside the function.
Basically behaviour of
```
new expression
```
Is effectively equivalent to
```
var tempObject = {};
var result = expression.call(tempObject);
if (result is not an object)
result = tempObject;
```
Although of course tempObject and result are transient values you can never see (they're implementation details in the interpreter), and there is no JS mechanism to do the "is not an object" check.
Broadly speaking the "new function() { .. }" method will be slower due to the need to create the this object for the constructor.
That said this should be not be a real difference as object allocation is not slow, and you shouldn't be using such code in hot code (due to the cost of creating the function object and associated closure).
Edit: one thing i realised that i missed from this is that the `tempObject` will get `expression`s prototype, eg. (before the `expression.call`) `tempObject.__proto__ = expression.prototype`
|
@Lance: the first one is also executing. Compare it with a named constructor:
```
function Blah() {
alert('blah');
}
new Bla();
```
this is actually also executing code. The same goes for the anonymous constructor...
But that was not the question ;-)
|
What's the difference in closure style
|
[
"",
"javascript",
""
] |
I have a ASP.NET page with an asp:button that is not visible. I can't turn it visible with JavaScript because it is not rendered to the page.
What can I do to resolve this?
|
If you need to manipulate it on the client side, you can't use the Visible property on the server side. Instead, set its CSS display style to "none". For example:
```
<asp:Label runat="server" id="Label1" style="display: none;" />
```
Then, you could make it visible on the client side with:
```
document.getElementById('Label1').style.display = 'inherit';
```
You could make it hidden again with:
```
document.getElementById('Label1').style.display = 'none';
```
Keep in mind that there may be issues with the ClientID being more complex than "Label1" in practice. You'll need to use the ClientID with getElementById, not the server side ID, if they differ.
|
Try this.
```
<asp:Button id="myButton" runat="server" style="display:none" Text="Click Me" />
<script type="text/javascript">
function ShowButton() {
var buttonID = '<%= myButton.ClientID %>';
var button = document.getElementById(buttonID);
if(button) { button.style.display = 'inherit'; }
}
</script>
```
Don't use server-side code to do this because that would require a postback. Instead of using Visibility="false", you can just set a CSS property that hides the button. Then, in javascript, switch that property back whenever you want to show the button again.
The ClientID is used because it can be different from the server ID if the button is inside a Naming Container control. These include Panels of various sorts.
|
Change visibility of ASP.NET label with JavaScript
|
[
"",
"asp.net",
"javascript",
""
] |
Will limiting a query to one result record, improve performance in a large(ish) MySQL table if the table only has one matching result?
for example
```
select * from people where name = "Re0sless" limit 1
```
if there is only one record with that name? and what about if `name` was the primary key/ set to unique? and is it worth updating the query or will the gain be minimal?
|
If the column has
**a unique index: no,** it's no faster
**a non-unique index: maybe,** because it will prevent sending any additional rows beyond the first matched, if any exist
**no index: sometimes**
* if 1 or more rows match the query, **yes**, because the full table scan will be halted after the first row is matched.
* if no rows match the query, **no**, because it will need to complete a full table scan
|
If you have a slightly more complicated query, with one or more joins, the LIMIT clause gives the optimizer extra information. If it expects to match two tables and return all rows, a [hash join](http://en.wikipedia.org/wiki/Hash_join "hash join") is typically optimal. A hash join is a type of join optimized for large amounts of matching.
Now if the optimizer knows you've passed LIMIT 1, it knows that it won't be processing large amounts of data. It can revert to a [loop join](http://en.wikipedia.org/wiki/Nested_loop_join "loop join").
Based on the database (and even database version) this can have a huge impact on performance.
|
Does limiting a query to one record improve performance
|
[
"",
"sql",
"mysql",
"database",
""
] |
I have read through several reviews on Amazon and some books seem outdated. I am currently using MyEclipse 6.5 which is using Eclipse 3.3. I'm interested in hearing from people that have experience learning RCP and what reference material they used to get started.
|
I've been doing Eclipse RCP development for almost 2 years now. When I first started, I wanted a book for help and many people told me, with Eclipse you're better off using the [Eclipsepedia](http://wiki.eclipse.org/index.php/Rich_Client_Platform) and Google.
However, I started with "[The Java Developer's Guide to Eclipse](https://rads.stackoverflow.com/amzn/click/com/0321305027)" by D'Anjou et al, and I still reference it when I need a better starting point or a good reference. It's probably a little outdated now, but is very thorough and really explains how the Eclipse framework works. Like just about anything, RCP isn't too hard to pick up if you've figured out how the framework supporting it works and you'll get a lot more mileage out of your code.
|
I agree with Thomas Owens on "[Eclipse Rich Client Platform: Designing, Coding, and Packaging Java(TM) Applications](https://rads.stackoverflow.com/amzn/click/com/0321334612)" and would also add "[Eclipse: Building Commercial-Quality Plug-ins](https://rads.stackoverflow.com/amzn/click/com/032142672X)" to the list of rather outdated but still somewhat useful books on Eclipse RCP. Even though the latter does not go much into the Rich Client Platform, it explains quite a lot about the Eclipse plug-in architecture that is useful knowledge for developers of RCP applications.
There has been a lot of improvements in the Eclipse RCP platform since the release of both of these books, so I really hope that there are new versions of these books coming out soon.
|
I would like a recommendation for a book on Eclipse's Rich Client Platform (RCP)
|
[
"",
"java",
"eclipse",
"rcp",
"myeclipse",
""
] |
There are a couple of things that I am having a difficult time understanding with regards to developing custom components in JSF. For the purposes of these questions, you can assume that all of the custom controls are using valuebindings/expressions (not literal bindings), but I'm interested in explanations on them as well.
1. Where do I set the value for the valuebinding? Is this supposed to happen in decode? Or should decode do something else and then have the value set in encodeBegin?
2. Read from the Value Binding - When do I read data from the valuebinding vs. reading it from submittedvalue and putting it into the valuebinding?
3. When are action listeners on forms called in relation to all of this? The JSF lifecycle pages all mention events happening at various steps, but its not completely clear to me when just a simple listener for a commandbutton is being called
I've tried a few combinations, but always end up with hard to find bugs that I believe are coming from basic misunderstandings of the event lifecycle.
|
There is a pretty good diagram in the [JSF specification](http://java.sun.com/javaee/javaserverfaces/download.html) that shows the request lifecycle - essential for understanding this stuff.
The steps are:
* **Restore View**. The UIComponent tree is rebuilt.
* **Apply Request Values**. Editable components should implement EditableValueHolder. This phase walks the component tree and calls the *processDecodes* methods. If the component isn't something complex like a UIData, it won't do much except call its own *decode* method. The *decode* method doesn't do much except find its renderer and invokes its *decode* method, passing itself as an argument. It is the renderer's job to get any submitted value and set it via *setSubmittedValue*.
* **Process Validations**. This phase calls *processValidators* which will call *validate*. The *validate* method takes the submitted value, converts it with any converters, validates it with any validators and (assuming the data passes those tests) calls *setValue*. This will store the value as a local variable. While this local variable is not null, it will be returned and not the value from the value binding for any calls to *getValue*.
* **Update Model Values**. This phase calls *processUpdates*. In an input component, this will call *updateModel* which will get the *ValueExpression* and invoke it to set the value on the model.
* **Invoke Application**. Button event listeners and so on will be invoked here (as will navigation if memory serves).
* **Render Response**. The tree is rendered via the renderers and the state saved.
* If any of these phases fail (e.g. a value is invalid), the lifecycle skips to Render Response.
* Various events can be fired after most of these phases, invoking listeners as appropriate (like value change listeners after Process Validations).
This is a somewhat simplified version of events. Refer to the specification for more details.
I would question why you are writing your own UIComponent. This is a non-trivial task and a deep understanding of the JSF architecture is required to get it right. If you need a custom control, it is better to create a concrete control that extends an exisiting UIComponent (like HtmlInputText does) with an equivalent renderer.
If contamination isn't an issue, there is an open-source JSF implementation in the form of Apache MyFaces.
|
Action listeners, such as for a *CommandButton*, are called during the *Invoke Application* phase, which is the last phase before the final *Render Response* phase. This is shown in [The JSF Lifecycle - figure 1](http://www.ibm.com/developerworks/library/j-jsf2/#figure1).
|
JSF Lifecycle and Custom components
|
[
"",
"java",
"jsf",
"jakarta-ee",
"custom-component",
""
] |
The MSDN documentation on [Object.GetHashCode()](http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx) describes 3 contradicting rules for how the method should work.
1. If two objects of the same type represent the same value, the hash function must return the same constant value for either object.
2. For the best performance, a hash function must generate a random distribution for all input.
3. The hash function must return exactly the same value regardless of any changes that are made to the object.
Rules 1 & 3 are contradictory to me.
Does Object.GetHashCode() return a unique number based on the **value** of an object, or the **reference** to the object. If I override the method I can choose what to use, but I'd like to know what is used internally if anyone knows.
|
> Rules 1 & 3 are contradictory to me.
To a certain extent, they are. The reason is: if an object is stored in a hash table and, by changing its value, you change its hash then the hash table has lost the value and you can't find it again by querying the hash table. — It is therefore important that while objects are stored in a hash table, they retain their hash value.
To ensure this it is often simplest to make hashable objects immutable, thus side-stepping the problem wholly. But it is actually sufficient to make only those fields immutable that determine the hash value.
Consider the following example:
```
struct Person {
public readonly string FirstName;
public readonly string Name;
public readonly DateTime Birthday;
public int ShoeSize;
}
```
People rarely change their name, and even less frequently their birthday. However, their shoe size may grow arbitrarily, or even shrink. It is therefore reasonable to identify people using their birthday and name but not their shoe size. The hash value should reflect this:
```
public override int GetHashCode() {
return HashCode.Combine(FirstName, Name, Birthday);
}
```
[And remember to override `Equals` whenever you override `GetHashCode` (and vice-versa)!](https://stackoverflow.com/a/104309/1968)
|
Not sure what MSDN documentation you are referring to. Looking at the current documentation on Object.GetHashCode (<http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx>) provides the following "rules":
* If two objects compare as equal, the GetHashCode method for each object must return the same value. However, if two objects do not compare as equal, the GetHashCode methods for the two object do not have to return different values.
* The GetHashCode method for an object must consistently return the same hash code as long as there is no modification to the object state that determines the return value of the object's Equals method. Note that this is true only for the current execution of an application, and that a different hash code can be returned if the application is run again.
* For the best performance, a hash function must generate a random distribution for all input.
If you are referring to the second bullet point, the key phrases here are "as long as there is no modification to the object state" and "true only for the current execution of an application".
Also from the documentation,
> A hash function is used to quickly generate a number (hash code) that corresponds to the **value** of an object. Hash functions are usually specific to each Type and must use at least one of the **instance** fields as input. [*Emphasis added is mine.*]
As for the actual implementation, it clearly states that derived classes can defer to the Object.GetHashCode implementation **if and only if** that derived class defines value equality to be reference equality and the type is not a value type. In other words, the default implementation of Object.GetHashCode is going to be based on reference equality since there are no real instance fields to use and, therefore, does not guarantee unique return values for different objects. Otherwise, your implementation should be specific to your type and should use at least one of your instance fields. As an example, the implementation of String.GetHashCode returns identical hash codes for identical string values, so two String objects return the same hash code if they represent the same string value, and uses all the characters in the string to generate that hash value.
|
Is Object.GetHashCode() unique to a reference or a value?
|
[
"",
"c#",
".net",
""
] |
Is there anyway to have a sort of virtual static member in C++?
For example:
```
class BaseClass {
public:
BaseClass(const string& name) : _name(name) {}
string GetName() const { return _name; }
virtual void UseClass() = 0;
private:
const string _name;
};
class DerivedClass : public BaseClass {
public:
DerivedClass() : BaseClass("DerivedClass") {}
virtual void UseClass() { /* do something */ }
};
```
I know this example is trivial, but if I have a vector of complex data that is going to be always the same for all derived class but is needed to be accessed from base class methods?
```
class BaseClass {
public:
BaseClass() {}
virtual string GetName() const = 0;
virtual void UseClass() = 0;
};
class DerivedClass : public BaseClass {
public:
DerivedClass() {}
virtual string GetName() const { return _name; }
virtual void UseClass() { /* do something */ }
private:
static const string _name;
};
string DerivedClass::_name = "DerivedClass";
```
This solution does not satify me because I need reimplement the member \_name and its accessor GetName() in every class. In my case I have several members that follows \_name behavior and tenths of derived classes.
Any idea?
|
Here is one solution:
```
struct BaseData
{
const string my_word;
const int my_number;
};
class Base
{
public:
Base(const BaseData* apBaseData)
{
mpBaseData = apBaseData;
}
const string getMyWord()
{
return mpBaseData->my_word;
}
int getMyNumber()
{
return mpBaseData->my_number;
}
private:
const BaseData* mpBaseData;
};
class Derived : public Base
{
public:
Derived() : Base(&sBaseData)
{
}
private:
static BaseData sBaseData;
}
BaseData Derived::BaseData = { "Foo", 42 };
```
|
It seems like the answer is in the question - the method you suggested seems to be the right direction to go, except that if you have a big number of those shared members you might want to gather them into a struct or class and past that as the argument to the constructor of the base class.
If you insist on having the "shared" members implemented as static members of the derived class, you might be able to auto-generate the code of the derived classes. XSLT is a great tool for auto-generating simple classes.
In general, the example doesn't show a need for "virtual static" members, because for purposes like these you don't actually need inheritance - instead you should use the base class and have it accept the appropriate values in the constructor - maybe creating a single instance of the arguments for each "sub-type" and passing a pointer to it to avoid duplication of the shared data. Another similar approach is to use templates and pass as the template argument a class that provides all the relevant values (this is commonly referred to as the "Policy" pattern).
To conclude - for the purpose of the original example, there is no need for such "virtual static" members. If you still think they are needed for the code you are writing, please try to elaborate and add more context.
Example of what I described above:
```
class BaseClass {
public:
BaseClass(const Descriptor& desc) : _desc(desc) {}
string GetName() const { return _desc.name; }
int GetId() const { return _desc.Id; }
X GetX() connst { return _desc.X; }
virtual void UseClass() = 0;
private:
const Descriptor _desc;
};
class DerivedClass : public BaseClass {
public:
DerivedClass() : BaseClass(Descriptor("abc", 1,...)) {}
virtual void UseClass() { /* do something */ }
};
class DerDerClass : public BaseClass {
public:
DerivedClass() : BaseClass("Wowzer", 843,...) {}
virtual void UseClass() { /* do something */ }
};
```
I'd like to elaborate on this solution, and maybe give a solution to the de-initialization problem:
With a small change, you can implement the design described above without necessarily create a new instance of the "descriptor" for each instance of a derived class.
You can create a singleton object, DescriptorMap, that will hold the single instance of each descriptor, and use it when constructing the derived objects like so:
```
enum InstanceType {
Yellow,
Big,
BananaHammoc
}
class DescriptorsMap{
public:
static Descriptor* GetDescriptor(InstanceType type) {
if ( _instance.Get() == null) {
_instance.reset(new DescriptorsMap());
}
return _instance.Get()-> _descriptors[type];
}
private:
DescriptorsMap() {
descriptors[Yellow] = new Descriptor("Yellow", 42, ...);
descriptors[Big] = new Descriptor("InJapan", 17, ...)
...
}
~DescriptorsMap() {
/*Delete all the descriptors from the map*/
}
static autoptr<DescriptorsMap> _instance;
map<InstanceType, Descriptor*> _descriptors;
}
```
Now we can do this:
```
class DerivedClass : public BaseClass {
public:
DerivedClass() : BaseClass(DescriptorsMap.GetDescriptor(InstanceType.BananaHammoc)) {}
virtual void UseClass() { /* do something */ }
};
class DerDerClass : public BaseClass {
public:
DerivedClass() : BaseClass(DescriptorsMap.GetDescriptor(InstanceType.Yellow)) {}
virtual void UseClass() { /* do something */ }
};
```
At the end of execution, when the C runtime performs uninitializations, it also calls the destructor of static objects, including our autoptr, which in deletes our instance of the DescriptorsMap.
So now we have a single instance of each descriptor that is also being deleted at the end of execution.
Note that if the only purpose of the derived class is to supply the relevant "descriptor" data (i.e. as opposed to implementing virtual functions) then you should make do with making the base class non-abstract, and just creating an instance with the appropriate descriptor each time.
|
Simulating a virtual static member of a class in c++?
|
[
"",
"c++",
"virtual-functions",
""
] |
I've learned in College that you always have to free your unused Objects but not how you actually do it. For example structuring your code right and so on.
Are there any general rules on how to handle pointers in C++?
I'm currently not allowed to use boost. I have to stick to pure c++ because the framework I'm using forbids any use of generics.
|
I have worked with the embedded Symbian OS, which had an excellent system in place for this, based entirely on developer conventions.
1. Only one object will ever own a pointer. By default this is the creator.
2. Ownership can be passed on. To indicate passing of ownership, the object is passed as a pointer in the method signature (e.g. void Foo(Bar \*zonk);).
3. The owner will decide when to delete the object.
4. To pass an object to a method just for use, the object is passed as a reference in the method signature (e.g. void Foo(Bat &zonk);).
5. Non-owner classes may store references (never pointers) to objects they are given only when they can be certain that the owner will not destroy it during use.
Basically, if a class simply uses something, it uses a reference. If a class owns something, it uses a pointer.
This worked beautifully and was a pleasure to use. Memory issues were very rare.
|
Rules:
1. Wherever possible, use a
[smart pointer](http://en.wikipedia.org/wiki/Smart_pointer). Boost has some
[good ones](http://www.boost.org/doc/libs/1_35_0/libs/smart_ptr/sp_techniques.html).
2. If you
can't use a smart pointer, [null out
your pointer after deleting it](http://csis.pace.edu/~bergin/papers/PointerTraps.html).
3. Never work anywhere that won't let you use rule 1.
If someone disallows rule 1, remember that if you grab someone else's code, change the variable names and delete the copyright notices, no-one will ever notice. Unless it's a school project, where they actually check for that kind of shenanigans with quite sophisticated tools. See also, [this question](https://stackoverflow.com/questions/21506/please-sir-send-me-the-codes).
|
C++ Memory management
|
[
"",
"c++",
"memory",
"pointers",
""
] |
How do I check if an object property in JavaScript is undefined?
|
The usual way to check if the value of a property is the special value `undefined`, is:
```
if(o.myProperty === undefined) {
alert("myProperty value is the special value `undefined`");
}
```
To check if an object does not actually have such a property, and will therefore return `undefined` by default when you try to access it:
```
if(!o.hasOwnProperty('myProperty')) {
alert("myProperty does not exist");
}
```
To check if the value associated with an identifier is the special value `undefined`, *or* if that identifier has not been declared:
```
if(typeof myVariable === 'undefined') {
alert('myVariable is either the special value `undefined`, or it has not been declared');
}
```
Note: this last method is the only way to refer to an **undeclared** identifier without an early error, which is different from having a value of `undefined`.
In versions of JavaScript prior to ECMAScript 5, the property named "undefined" on the global object was writeable, and therefore a simple check `foo === undefined` might behave unexpectedly if it had accidentally been redefined. In modern JavaScript, the property is read-only.
However, in modern JavaScript, "undefined" is not a keyword, and so variables inside functions can be named "undefined" and shadow the global property.
If you are worried about this (unlikely) edge case, you can use [the void operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void) to get at the special `undefined` value itself:
```
if(myVariable === void 0) {
alert("myVariable is the special value `undefined`");
}
```
|
I believe there are a number of incorrect answers to this topic. Contrary to common belief, "undefined" is **not** a keyword in JavaScript and can in fact have a value assigned to it.
# Correct Code
The most robust way to perform this test is:
```
if (typeof myVar === "undefined")
```
This will always return the correct result, and even handles the situation where `myVar` is not declared.
# Degenerate code. DO NOT USE.
```
var undefined = false; // Shockingly, this is completely legal!
if (myVar === undefined) {
alert("You have been misled. Run away!");
}
```
Additionally, `myVar === undefined` will raise an error in the situation where myVar is undeclared.
|
Detecting an undefined object property
|
[
"",
"javascript",
"object",
"undefined",
"object-property",
""
] |
What are the best methods for tracking and/or automating DB schema changes? Our team uses Subversion for version control and we've been able to automate some of our tasks this way (pushing builds up to a staging server, deploying tested code to a production server) but we're still doing database updates manually. I would like to find or create a solution that allows us to work efficiently across servers with different environments while continuing to use Subversion as a backend through which code and DB updates are pushed around to various servers.
Many popular software packages include auto-update scripts which detect DB version and apply the necessary changes. Is this the best way to do this even on a larger scale (across multiple projects and sometimes multiple environments and languages)? If so, is there any existing code out there that simplifies the process or is it best just to roll our own solution? Has anyone implemented something similar before and integrated it into Subversion post-commit hooks, or is this a bad idea?
While a solution that supports multiple platforms would be preferable, we definitely need to support the Linux/Apache/MySQL/PHP stack as the majority of our work is on that platform.
|
In the Rails world, there's the concept of migrations, scripts in which changes to the database are made in Ruby rather than a database-specific flavour of SQL. Your Ruby migration code ends up being converted into the DDL specific to your current database; this makes switching database platforms very easy.
For every change you make to the database, you write a new migration. Migrations typically have two methods: an "up" method in which the changes are applied and a "down" method in which the changes are undone. A single command brings the database up to date, and can also be used to bring the database to a specific version of the schema. In Rails, migrations are kept in their own directory in the project directory and get checked into version control just like any other project code.
[This Oracle guide to Rails migrations](http://www.oracle.com/technology/pub/articles/kern-rails-migrations.html "Oracle guide to Ruby on Rails migrations") covers migrations quite well.
Developers using other languages have looked at migrations and have implemented their own language-specific versions. I know of **[Ruckusing](https://github.com/ruckus/ruckusing-migrations "Ruckusing")**, a PHP migrations system that is modelled after Rails' migrations; it might be what you're looking for.
|
We use something similar to bcwoord to keep our database schemata synchronized across 5 different installations (production, staging and a few development installations), and backed up in version control, and it works pretty well. I'll elaborate a bit:
---
To synchronize the database structure, we have a single script, update.php, and a number of files numbered 1.sql, 2.sql, 3.sql, etc. The script uses one extra table to store the current version number of the database. The N.sql files are crafted by hand, to go from version (N-1) to version N of the database.
They can be used to add tables, add columns, migrate data from an old to a new column format then drop the column, insert "master" data rows such as user types, etc. Basically, it can do anything, and with proper data migration scripts you'll never lose data.
The update script works like this:
> * Connect to the database.
> * Make a backup of the current database (because stuff *will* go wrong) [mysqldump].
> * Create bookkeeping table (called \_meta) if it doesn't exist.
> * Read current VERSION from \_meta table. Assume 0 if not found.
> * For all .sql files numbered higher than VERSION, execute them in order
> * If one of the files produced an error: roll back to the backup
> * Otherwise, update the version in the bookkeeping table to the highest .sql file executed.
Everything goes into source control, and every installation has a script to update to the latest version with a single script execution (calling update.php with the proper database password etc.). We SVN update staging and production environments via a script that automatically calls the database update script, so a code update comes with the necessary database updates.
We can also use the same script to recreate the entire database from scratch; we just drop and recreate the database, then run the script which will completely repopulate the database. We can also use the script to populate an empty database for automated testing.
---
It took only a few hours to set up this system, it's conceptually simple and everyone gets the version numbering scheme, and it has been invaluable in having the ability to move forward and evolving the database design, without having to communicate or manually execute the modifications on all databases.
*Beware when pasting queries from phpMyAdmin though!* Those generated queries usually include the database name, which you definitely don't want since it will break your scripts! Something like CREATE TABLE `mydb`.`newtable`(...) will fail if the database on the system is not called mydb. We created a pre-comment SVN hook that will disallow .sql files containing the `mydb` string, which is a sure sign that someone copy/pasted from phpMyAdmin without proper checking.
|
Mechanisms for tracking DB schema changes
|
[
"",
"php",
"mysql",
"database",
"svn",
"migration",
""
] |
I am running a Tomcat application, and I need to display some time values. Unfortunately, the time is coming up an hour off. I looked into it and discovered that my default TimeZone is being set to:
```
sun.util.calendar.ZoneInfo[id="GMT-08:00",
offset=-28800000,
dstSavings=0,
useDaylight=false,
transitions=0,
lastRule=null]
```
Rather than the Pacific time zone. This is further indicated when I try to print the default time zone's [display name](http://docs.oracle.com/javase/7/docs/api/java/util/TimeZone.html#getDisplayName()), and it comes up "GMT-08:00", which seems to indicate to me that it is not correctly set to the US Pacific time zone. I am running on Ubuntu Hardy Heron, upgraded from Gutsy Gibbon.
Is there a configuration file I can update to tell the JRE to use Pacific with all the associated daylight savings time information? The time on my machine shows correctly, so it doesn't seem to be an OS-wide misconfiguration.
---
Ok, here's an update. A coworker suggested I update JAVA\_OPTS in my /etc/profile to include "-Duser.timezone=US/Pacific", which worked (I also saw CATALINA\_OPTS, which I updated as well). Actually, I just exported the change into the variables rather than use the new /etc/profile (a reboot later will pick up the changes and I will be golden).
However, I still think there is a better solution... there should be a configuration for Java somewhere that says what timezone it is using, or how it is grabbing the timezone. If someone knows such a setting, that would be awesome, but for now this is a decent workaround.
---
I am using 1.5, and it is most definitely a DST problem. As you can see, the time zone is set to not use daylight savings. My belief is it is generically set to -8 offset rather than the specific Pacific timezone. Since the generic -8 offset has no daylight savings info, it's of course not using it, but the question is, where do I tell Java to use Pacific time zone when it starts up? I'm NOT looking for a programmatic solution, it should be a configuration solution.
|
It's a "quirk" in the way the JVM looks up the zoneinfo file. See [Bug ID 6456628](https://bugs.java.com/bugdatabase/view_bug?bug_id=6456628).
The easiest workaround is to make /etc/localtime a symlink to the correct zoneinfo file. For Pacific time, the following commands should work:
```
# sudo cp /etc/localtime /etc/localtime.dist
# sudo ln -fs /usr/share/zoneinfo/America/Los_Angeles /etc/localtime
```
I haven't had any problems with the symlink approach.
Edit: Added "sudo" to the commands.
|
On Ubuntu, it's not enough to just change the /etc/localtime file. It seems to read /etc/timezone file, too. It's better follow the [instruction](https://help.ubuntu.com/community/UbuntuTime) to set the time zone properly. In particular, do the following:
```
$ sudo cp /etc/timezone /etc/timezone.dist
$ echo "Australia/Adelaide" | sudo tee /etc/timezone
Australia/Adelaide
$ sudo dpkg-reconfigure --frontend noninteractive tzdata
Current default time zone: 'Australia/Adelaide'
Local time is now: Sat May 8 21:19:24 CST 2010.
Universal Time is now: Sat May 8 11:49:24 UTC 2010.
```
On my Ubuntu, if /etc/localtime and /etc/timezone are inconsistent, Java seems to read default time zone from /etc/timezone .
|
Java Time Zone is messed up
|
[
"",
"java",
"linux",
"timezone",
""
] |
Given 2 rgb colors and a rectangular area, I'd like to generate a basic linear gradient between the colors. I've done a quick search and the only thing I've been able to find is [this blog entry](http://jtauber.com/blog/2008/05/18/creating_gradients_programmatically_in_python/), but the example code seems to be missing, or at least it was as of this posting. Anything helps, algorithms, code examples, whatever. This will be written in Java, but the display layer is already taken care of, I just need to figure out how to figure out what to display.
|
you want an interpolation between the first and the second colour. Interpolating colours is easy by calculating the same interpolation for each of its components (R, G, B). There are many ways to interpolate. The easiest is to use linear interpolation: just take percentage *p* of the first colour and percentage 1 - *p* of the second:
```
R = firstCol.R * p + secondCol.R * (1 - p)
```
There's [another question](https://stackoverflow.com/questions/25007/conditional-formatting-percentage-to-color-conversion) related to this.
There are other methods of interpolation that sometimes work better. For example, using a [bell-shaped (sigmoidal)](http://en.wikipedia.org/wiki/Sigmoid_function) interpolation function makes the transition smoother.
/EDIT: Oops, you mean using a predefined function. OK, even easier. The blog post you linked now has an example code in Python.
In Java, you could use the [`GradientPaint`](http://docs.oracle.com/javase/7/docs/api/java/awt/GradientPaint.html).
|
You can use the built in [GradientPaint](https://docs.oracle.com/javase/7/docs/api/java/awt/GradientPaint.html) class.
```
void Paint(Graphics2D g, Regtangle r, Color c1, Color c2)
{
GradientPaint gp = new GradientPaint(0,0,c1,r.getWidth(),r.getHeight(),c2);
g.setPaint(gp);
g.fill(rect);
}
```
|
Generating gradients programmatically?
|
[
"",
"java",
"colors",
"rgb",
"gradient",
""
] |
I am using LINQ to query a generic dictionary and then use the result as the datasource for my ListView (WebForms).
Simplified code:
```
Dictionary<Guid, Record> dict = GetAllRecords();
myListView.DataSource = dict.Values.Where(rec => rec.Name == "foo");
myListView.DataBind();
```
I thought that would work but in fact it throws a **System.InvalidOperationException**:
> ListView with id 'myListView' must
> have a data source that either
> implements ICollection or can perform
> data source paging if AllowPaging is
> true.
In order to get it working I have had to resort to the following:
```
Dictionary<Guid, Record> dict = GetAllRecords();
List<Record> searchResults = new List<Record>();
var matches = dict.Values.Where(rec => rec.Name == "foo");
foreach (Record rec in matches)
searchResults.Add(rec);
myListView.DataSource = searchResults;
myListView.DataBind();
```
Is there a small gotcha in the first example to make it work?
(Wasn't sure what to use as the question title for this one, feel free to edit to something more appropriate)
|
Try this:
```
var matches = dict.Values.Where(rec => rec.Name == "foo").ToList();
```
Be aware that that will essentially be creating a new list from the original Values collection, and so any changes to your dictionary won't automatically be reflected in your bound control.
|
I tend to prefer using the new Linq syntax:
```
myListView.DataSource = (
from rec in GetAllRecords().Values
where rec.Name == "foo"
select rec ).ToList();
myListView.DataBind();
```
Why are you getting a dictionary when you don't use the key? You're paying for that overhead.
|
How can I convert IEnumerable<T> to List<T> in C#?
|
[
"",
"c#",
"linq",
"generics",
"listview",
""
] |
I've been having a hard time trying to understand PyPy's translation. It looks like something absolutely revolutionary from simply reading the description, however I'm hard-pressed to find good documentation on actually translating a real world piece of code to something such as LLVM. Does such a thing exist? The official PyPy documentation on it just skims over the functionality, rather than providing anything I can try out myself.
|
This document seems to go into quite a bit of detail (and I think a complete description is out of scope for a stackoverflow answer):
* <http://codespeak.net/pypy/dist/pypy/doc/translation.html>
The general idea of translating from one language to another isn't particularly revolutionary, but it has only recently been gaining popularity / applicability in "real-world" applications. [GWT](http://code.google.com/webtoolkit/) does this with Java (generating Javascript) and there is a library for translating Haskell into various other languages as well (called [YHC](http://www.haskell.org/haskellwiki/Yhc))
|
If you want some hand-on examples, [PyPy's Getting Started](http://codespeak.net/pypy/dist/pypy/doc/getting-started.html) document has a section titled "Trying out the translator".
|
Where can I learn more about PyPy's translation function?
|
[
"",
"python",
"translation",
"pypy",
""
] |
I'm having issues with my SQL Reporting Services reports. I'm using a custom font for report headers, and when deployed to the server it does not render correctly when I print or export to PDF/TIFF. I have installed the font on the server. Is there anything else I need to do in order to use custom fonts?
When viewing the font in the browser it looks correct - since all client computers have the font installed...
---
Thanks Ryan, your post to the FAQ solved the problem. Installing the fonts on the server fixes the print problem, as well as problems with charts (which are also rendered on the server). Like you point out (as well as being mentioned in the FAQ) Reporting Services 2005 does not do font embedding in PDF files. I guess that is okay for now - the most important part was being able to hit print and get the correct fonts.
The reason the fonts didn't show up straight away is answered in the FAQ:
> **Q: I've installed the font on my client/server but I still see ?'s or
> black boxes. Why?** A: For the client
> machine, closing all instances of the
> PDF viewer then reopening them should
> fix the issue.
>
> For the server, restarting the
> services should allow the PDF renderer
> to pick up the new font information.
>
> Unfortunately, I have also seen times
> where I needed a full machine reboot
> to get the client/server to recognize
> the newly installed font.
|
The PDF files served up from SSRS, like many PDF files, have embedded postscript fonts. So, the local fonts used in the report are converted to a best matching postscript font when the conversion takes place so the PDF is totally portable without relying on locally installed fonts.
You can see the official MS guidelines and font requirements for SSRS PDF exports here: [SQL Server 2005 Books Online (September 2007) Designing for PDF Output](http://technet.microsoft.com/en-us/library/ms159713(SQL.90).aspx). Also, this post should provide some help as well: [Reporting Services: PDF Renderer FAQ](http://blogs.msdn.com/donovans/pages/reporting-services-pdf-renderer-faq.aspx)
---
Aspose apparently also has a component that claims to be able to add custom embedded fonts in SQL Report PDFs.
See [Aspose.Pdf for Reporting Services](http://www.aspose.com/community/blogs/aspose.pdf/archive/2008/05/02/aspose-pdf-for-reporting-services-v1-3-0-0-released.aspx)
> Aspose.Pdf for Reporting Services
> makes it possible generating PDF
> reports in Microsoft SQL Server 2000
> and 2005 Reporting Services. Some
> advanced features like XMP metadata,
> **custom embedded font** and rendering
> watermark for pages are now supported.
> All RDL report features including
> sections, images, charts, tables,
> matrices, headers and footers are
> converted with the highest degree of
> precision to PDF.
I've not tried this component, so I can only share what it claims to be able to do.
|
Note: I have found that when you install the fonts on the Reporting Services server box, you may need to:
= Actually open the font from the Fonts control panel, so you can see the preview
AND
= Reboot the server box.
And yes, I agree you should not need to do this - but I have seen it work.
|
Custom font in SQL Server 2005 Reporting Services
|
[
"",
"sql",
"reporting-services",
""
] |
I'm currently trying to read in an XML file, make some minor changes (alter the value of some attributes), and write it back out again.
I have intended to use a StAX parser (`javax.xml.stream.XMLStreamReader`) to read in each event, see if it was one I wanted to change, and then pass it straight on to the StAX writer (`javax.xml.stream.XMLStreamReader`) if no changes were required.
Unfortunately, that doesn't look to be so simple - The writer has no way to take an event type and a parser object, only methods like `writeAttribute` and `writeStartElement`. Obviously I could write a big switch statement with a case for every possible type of element which can occur in an XML document, and just write it back out again, but it seems like a lot of trouble for something which seems like it should be simple.
Is there something I'm missing that makes it easy to write out a very similar XML document to the one you read in with StAX?
|
StAX works pretty well and is very fast. I used it in a project to parse XML files which are up to 20MB. I don't have a thorough analysis, but it was definitely faster than SAX.
As for your question: The difference between streaming and event-handling, AFAIK is control. With the streaming API you can walk through your document step by step and get the contents you want. Whereas the event-based API you can only handle what you are interested in.
|
After a bit of mucking around, the answer seems to be to use the Event reader/writer versions rather than the Stream versions.
(i.e. javax.xml.stream.XMLEventReader and javax.xml.stream.XMLEventWriter)
See also <http://www.devx.com/tips/Tip/37795>, which is what finally got me moving.
|
Small modification to an XML document using StAX
|
[
"",
"java",
"xml",
"stax",
""
] |
I'm interested in seeing a good diff algorithm, possibly in Javascript, for rendering a side-by-side diff of two HTML pages. The idea would be that the diff would show the differences of the *rendered* HTML.
To clarify, I want to be able to see the side-by-side diffs *as* rendered output. So if I delete a paragraph, the side by side view would know to space things correctly.
---
@Josh exactly. Though maybe it would show the deleted text in red or something. The idea is that if I use a WYSIWYG editor for my HTML content, I don't want to have to switch to HTML to do diffs. I want to do it with two WYSIWYG editors side by side maybe. Or at least display diffs side-by-side in an end-user friendly matter.
|
There's another nice trick you can use to significantly improve the look of a rendered HTML diff. Although this doesn't fully solve the initial problem, it will make a significant difference in the appearance of your rendered HTML diffs.
Side-by-side rendered HTML will make it very difficult for your diff to line up vertically. Vertical alignment is crucial for comparing side-by-side diffs. In order to improve the vertical alignment of a side-by-side diff, you can insert invisible HTML elements in each version of the diff at "checkpoints" where the diff should be vertically aligned. Then you can use a bit of client-side JavaScript to add vertical spacing around checkpoint until the sides line up vertically.
Explained in a little more detail:
If you want to use this technique, run your diff algorithm and insert a bunch of `visibility:hidden` `<span>`s or tiny `<div>`s wherever your side-by-side versions should match up, according to the diff. Then run JavaScript that finds each checkpoint (and its side-by-side neighbor) and adds vertical spacing to the checkpoint that is higher-up (shallower) on the page. Now your rendered HTML diff will be vertically aligned up to that checkpoint, and you can continue repairing vertical alignment down the rest of your side-by-side page.
|
Over the weekend I posted a new project on codeplex that implements an HTML diff algorithm in C#. The original algorithm was written in Ruby. I understand you were looking for a JavaScript implementation, perhaps having one available in C# with source code could assist you to port the algorithm. Here is the link if you are interested: [htmldiff.codeplex.com](http://htmldiff.codeplex.com). You can read more about it [here](http://www.rohland.co.za/index.php/2009/10/31/csharp-html-diff-algorithm/).
**UPDATE:** This library has been moved to [GitHub](https://github.com/Rohland/htmldiff.net).
|
Anyone have a diff algorithm for rendered HTML?
|
[
"",
"javascript",
"html",
"diff",
""
] |
I am looking for the best method to run a Java Application as a \*NIX daemon or a Windows Service. I've looked in to the [Java Service Wrapper](http://wrapper.tanukisoftware.org/), the [Apache Commons project 'jsvc'](http://commons.apache.org/daemon/jsvc.html), and the [Apache Commons project 'procrun'](http://commons.apache.org/daemon/procrun.html). So far, the Java Service Wrapper looks like it's the best option... but, I'm wondering if there are any other "Open Source friendly" licensed products out there.
|
I've had great success with Java Service Wrapper myself. I haven't looked at the others, but the major strengths of ServiceWrapper are:
* Great x-platform support - I've used it on Windows and Linux, and found it easy on both
* Solid Documentation - The docs are clear and to the point, with great examples
* Deep per-platform support - There are some unique features in the window service management system that are supported perfectly by service wrapper (w/o restarting). And on Windows, you will even see your app name in the process list instead of just "java.exe".
* Standards Compliant - Unlike many ad-hoc Java init scripts, the scripts for service wrapper tend to be compliant with LSB standards. This can end up being very important if you ever want high availability management from something like Linux Heartbeat/HA.
Anyway, just my 2 cents... :)
|
Another option is [WinRun4J](http://winrun4j.sourceforge.net/ "WinRun4J"). This is windows only but has some useful features:
* 32 bit and 64 bit support
* API to access the event log and registry
* Can register service to be dependent on other services (i.e serviceA and serviceB must startup before serviceC)
Its also open source friendly (CPL) so no restrictions on use.
(full disclosure: I work on this project).
|
Best Method to run a Java Application as a *nix Daemon or Windows Service?
|
[
"",
"java",
"unix",
"windows-services",
"daemon",
""
] |
What would be the Master Pages equivalent in the Java web development world? I've heard of Tiles, Tapestry and Velocity but don't know anything about them. Are they as easy to use as Master Pages?
I want something as easy as set up one template and subsequent pages derive from the template and override content regions, similar to Master Pages.
Any examples would be great!!
|
First, the equivalent of ASP.Net in Java is going to be a web framework, such as the ones you mention (Tiles, Tapestry and Velocity).
Master pages give the ability to define pages in terms of content slotted into a master template.
Master pages are a feature of ASP.Net (the .Net web framework), so you are looking for a feature similar to master pages in a Java web framework.
<http://tiles.apache.org/framework/tutorial/basic/pages.html> gives some basic examples using Tiles and JSP to implement something similar with Struts, a Java web framework. In this case, the Master Pages functionality is a plugin on top of Struts.
Velocity is a generic templating engine, not specialized for web pages and definitely more complicated than you need. (I've seen it used for code generation.)
Tapestry is more of a full featured web stack than Tile, and is probably good for your purposes. Its templating functionality involves creating a component and putting all common markup in that. An example is at <http://www.infoq.com/articles/tapestry5-intro>.
The specifics of this differ based on which Java web framework you choose.
|
You should also check out [Facelets](https://facelets.java.net/); there is a [good introductory article](http://www.ibm.com/developerworks/java/library/j-facelets/) on DeveloperWorks.
The Facelets `<ui:insert/>` tag is comparable to the ASP.NET `<asp:ContentPlaceHolder/>` tag used in master pages; it lets you provide default content for that area of the page, but this can be overridden.
To fill the Facelets template in another page, you start with a `<ui:composition/>` element that points to the template file. This is roughly equivalent to declaring the MasterPageFile attribute in an ASP.NET page.
Inside the `<ui:composition/>` element, you use `<ui:define/>` elements to override the template defaults, similar to the way an `<asp:Content/>` tag is used. These elements can contain any kind of content - from simple strings to JSF elements.
So, to bring it all together...
In *master.xhtml*:
```
<!-- HTML header content here -->
<ui:insert name="AreaOne">Default content for AreaOne</ui:insert>
<ui:insert name="AreaTwo">Default content for AreaTwo</ui:insert>
<!-- HTML footer content here -->
```
In *page.xhtml*:
```
<ui:composition template="/WEB-INF/templates/master.xhtml">
<ui:define name="AreaOne">Here is some new content</ui:define>
<ui:define name="AreaTwo">
<p>Some new content here too</p>
</ui:define>
</ui:composition>
```
And this will render as:
```
<!-- HTML header content here -->
Here is some new content
<p>Some new content here too</p>
<!-- HTML footer content here -->
```
You also get some other benefits with Facelets, such as the ability to reuse page components with different data.
(Edited to provide more information.)
|
ASP.NET Master Pages equivalent in Java
|
[
"",
"java",
"model-view-controller",
"master-pages",
""
] |
Is there a way to find the number of files of a specific type without having to loop through all results inn a Directory.GetFiles() or similar method? I am looking for something like this:
```
int ComponentCount = MagicFindFileCount(@"c:\windows\system32", "*.dll");
```
I know that I can make a recursive function to call Directory.GetFiles , but it would be much cleaner if I could do this without all the iterating.
**EDIT:** If it is not possible to do this without recursing and iterating yourself, what would be the best way to do it?
|
You should use the [Directory.GetFiles(path, searchPattern, SearchOption)](http://msdn.microsoft.com/en-us/library/ms143316.aspx) overload of Directory.GetFiles().
Path specifies the path, searchPattern specifies your wildcards (e.g., \*, \*.format) and SearchOption provides the option to include subdirectories.
The Length property of the return array of this search will provide the proper file count for your particular search pattern and option:
```
string[] files = directory.GetFiles(@"c:\windows\system32", "*.dll", SearchOption.AllDirectories);
return files.Length;
```
**EDIT:** Alternatively you can use [Directory.EnumerateFiles method](https://msdn.microsoft.com/en-us/library/system.io.directory.enumeratefiles(v=vs.110).aspx)
```
return Directory.EnumerateFiles(@"c:\windows\system32", "*.dll", SearchOption.AllDirectories).Count();
```
|
The slickest method woud be to use linq:
```
var fileCount = (from file in Directory.EnumerateFiles(@"H:\iPod_Control\Music", "*.mp3", SearchOption.AllDirectories)
select file).Count();
```
|
Find number of files with a specific extension, in all subdirectories
|
[
"",
"c#",
"file",
"recursion",
""
] |
We've been using the 32bit linux version of the [JavaServiceWrapper](http://wrapper.tanukisoftware.org/) for quite a while now and it's working perfectly. We are now considering also using it on 64bit linux systems. There are downloads for 64bit binaries on the website, but looking into Makefile for the 64bit version I found the following comment, though:
# This makefile is in progess. It builds, but the resulting libwrapper.so does not yet work.
# If you know how to fix it then please help out.
Can anyone confirm, that this comment is just outdated and the resulting wrapper will work without flaws?
|
I've had it running in production on 64-bit red hat without any trouble for the last year or so.
|
From <http://wrapper.tanukisoftware.org/doc/english/introduction.html> :
> Binary distributions are provided for
> the following list of platforms and
> are available on the download page.
> Only OS versions which are known to
> work have been listed.
>
> (snip...)
>
> * linux - Linux kernels; 2.2.x 2.4.x, 2.6.x. Known to work with Debian and Red Hat, but should work with any
> distribution. Currently supported on
> both 32 and **64-bit** x86, and 64-bit ppc
> systems.
|
JavaServiceWrapper on 64bit linux, any problems?
|
[
"",
"java",
"daemon",
""
] |
In Java (or any other language with checked exceptions), when creating your own exception class, how do you decide whether it should be checked or unchecked?
My instinct is to say that a checked exception would be called for in cases where the caller might be able to recover in some productive way, where as an unchecked exception would be more for unrecoverable cases, but I'd be interested in other's thoughts.
|
Checked Exceptions are great, so long as you understand when they should be used. The Java core API fails to follow these rules for SQLException (and sometimes for IOException) which is why they are so terrible.
**Checked Exceptions** should be used for **predictable**, but **unpreventable** errors that are **reasonable to recover from**.
**Unchecked Exceptions** should be used for everything else.
I'll break this down for you, because most people misunderstand what this means.
1. **Predictable but unpreventable**: The caller did everything within their power to validate the input parameters, but some condition outside their control has caused the operation to fail. For example, you try reading a file but someone deletes it between the time you check if it exists and the time the read operation begins. By declaring a checked exception, you are telling the caller to anticipate this failure.
2. **Reasonable to recover from**: There is no point telling callers to anticipate exceptions that they cannot recover from. If a user attempts to read from an non-existing file, the caller can prompt them for a new filename. On the other hand, if the method fails due to a programming bug (invalid method arguments or buggy method implementation) there is nothing the application can do to fix the problem in mid-execution. The best it can do is log the problem and wait for the developer to fix it at a later time.
Unless the exception you are throwing meets **all** of the above conditions it should use an Unchecked Exception.
**Reevaluate at every level**: Sometimes the method catching the checked exception isn't the right place to handle the error. In that case, consider what is reasonable for your own callers. If the exception is predictable, unpreventable and reasonable for them to recover from then you should throw a checked exception yourself. If not, you should wrap the exception in an unchecked exception. If you follow this rule you will find yourself converting checked exceptions to unchecked exceptions and vice versa depending on what layer you are in.
For both checked and unchecked exceptions, **use the right abstraction level**. For example, a code repository with two different implementations (database and filesystem) should avoid exposing implementation-specific details by throwing `SQLException` or `IOException`. Instead, it should wrap the exception in an abstraction that spans all implementations (e.g. `RepositoryException`).
|
From [A Java Learner](http://lankireddy.blogspot.com/2007/10/checked-vs-unchecked-exceptions.html):
> When an exception occurs, you have to
> either catch and handle the exception,
> or tell compiler that you can't handle
> it by declaring that your method
> throws that exception, then the code
> that uses your method will have to
> handle that exception (even it also
> may choose to declare that it throws
> the exception if it can't handle it).
>
> Compiler will check that we have done
> one of the two things (catch, or
> declare). So these are called Checked
> exceptions. But Errors, and Runtime
> Exceptions are not checked for by
> compiler (even though you can choose
> to catch, or declare, it is not
> required). So, these two are called
> Unchecked exceptions.
>
> Errors are used to represent those
> conditions which occur outside the
> application, such as crash of the
> system. Runtime exceptions are
> usually occur by fault in the
> application logic. You can't do
> anything in these situations. When
> runtime exception occur, you have to
> re-write your program code. So, these
> are not checked by compiler. These
> runtime exceptions will uncover in
> development, and testing period. Then
> we have to refactor our code to remove
> these errors.
|
When to choose checked and unchecked exceptions
|
[
"",
"java",
"exception",
"checked-exceptions",
""
] |
What issues / pitfalls must be considered when overriding `equals` and `hashCode`?
|
### The theory (for the language lawyers and the mathematically inclined):
`equals()` ([javadoc](http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object))) must define an equivalence relation (it must be *reflexive*, *symmetric*, and *transitive*). In addition, it must be *consistent* (if the objects are not modified, then it must keep returning the same value). Furthermore, `o.equals(null)` must always return false.
`hashCode()` ([javadoc](http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode())) must also be *consistent* (if the object is not modified in terms of `equals()`, it must keep returning the same value).
The **relation** between the two methods is:
> *Whenever `a.equals(b)`, then `a.hashCode()` must be same as `b.hashCode()`.*
### In practice:
If you override one, then you should override the other.
Use the same set of fields that you use to compute `equals()` to compute `hashCode()`.
Use the excellent helper classes [EqualsBuilder](http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/EqualsBuilder.html) and [HashCodeBuilder](http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/HashCodeBuilder.html) from the [Apache Commons Lang](http://commons.apache.org/lang/) library. An example:
```
public class Person {
private String name;
private int age;
// ...
@Override
public int hashCode() {
return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
// if deriving: appendSuper(super.hashCode()).
append(name).
append(age).
toHashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Person))
return false;
if (obj == this)
return true;
Person rhs = (Person) obj;
return new EqualsBuilder().
// if deriving: appendSuper(super.equals(obj)).
append(name, rhs.name).
append(age, rhs.age).
isEquals();
}
}
```
### Also remember:
When using a hash-based [Collection](http://download.oracle.com/javase/1.4.2/docs/api/java/util/Collection.html) or [Map](http://download.oracle.com/javase/1.4.2/docs/api/java/util/Map.html) such as [HashSet](http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashSet.html), [LinkedHashSet](http://download.oracle.com/javase/1.4.2/docs/api/java/util/LinkedHashSet.html), [HashMap](http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html), [Hashtable](http://download.oracle.com/javase/1.4.2/docs/api/java/util/Hashtable.html), or [WeakHashMap](http://download.oracle.com/javase/1.4.2/docs/api/java/util/WeakHashMap.html), make sure that the hashCode() of the key objects that you put into the collection never changes while the object is in the collection. The bulletproof way to ensure this is to make your keys immutable, [which has also other benefits](http://www.javapractices.com/topic/TopicAction.do?Id=29).
|
There are some issues worth noticing if you're dealing with classes that are persisted using an Object-Relationship Mapper (ORM) like Hibernate, if you didn't think this was unreasonably complicated already!
**Lazy loaded objects are subclasses**
If your objects are persisted using an ORM, in many cases you will be dealing with dynamic proxies to avoid loading object too early from the data store. These proxies are implemented as subclasses of your own class. This means that`this.getClass() == o.getClass()` will return `false`. For example:
```
Person saved = new Person("John Doe");
Long key = dao.save(saved);
dao.flush();
Person retrieved = dao.retrieve(key);
saved.getClass().equals(retrieved.getClass()); // Will return false if Person is loaded lazy
```
*If you're dealing with an ORM, using `o instanceof Person` is the only thing that will behave correctly.*
**Lazy loaded objects have null-fields**
ORMs usually use the getters to force loading of lazy loaded objects. This means that `person.name` will be `null` if `person` is lazy loaded, even if `person.getName()` forces loading and returns "John Doe". In my experience, this crops up more often in `hashCode()` and `equals()`.
*If you're dealing with an ORM, make sure to always use getters, and never field references in `hashCode()` and `equals()`.*
**Saving an object will change its state**
Persistent objects often use a `id` field to hold the key of the object. This field will be automatically updated when an object is first saved. Don't use an id field in `hashCode()`. But you can use it in `equals()`.
A pattern I often use is
```
if (this.getId() == null) {
return this == other;
}
else {
return this.getId().equals(other.getId());
}
```
But: you cannot include `getId()` in `hashCode()`. If you do, when an object is persisted, its `hashCode` changes. If the object is in a `HashSet`, you'll "never" find it again.
In my `Person` example, I probably would use `getName()` for `hashCode` and `getId()` plus `getName()` (just for paranoia) for `equals()`. It's okay if there are some risk of "collisions" for `hashCode()`, but never okay for `equals()`.
*`hashCode()` should use the non-changing subset of properties from `equals()`*
|
What issues should be considered when overriding equals and hashCode in Java?
|
[
"",
"java",
"overriding",
"equals",
"hashcode",
""
] |
I'm trying to extend some "base" classes in Python:
```
class xlist (list):
def len(self):
return len(self)
def add(self, *args):
self.extend(args)
return None
class xint (int):
def add(self, value):
self += value
return self
x = xlist([1,2,3])
print x.len() ## >>> 3 ok
print x ## >>> [1,2,3] ok
x.add (4, 5, 6)
print x ## >>> [1,2,3,4,5,6] ok
x = xint(10)
print x ## >>> 10 ok
x.add (2)
print x ## >>> 10 # Not ok (#1)
print type(x) ## >>> <class '__main__.xint'> ok
x += 5
print type(x) ## >>> <type 'int'> # Not ok (#2)
```
It works fine in the *list* case because the *append* method modifies the object "in place", without returning it. But in the *int* case, the *add* method doesn't modify the value of the external *x* variable. I suppose that's fine in the sense that *self* is a local variable in the *add* method of the class, but this is preventing me from modifying the initial value assigned to the instance of the class.
Is it possible to extend a class this way or should I define a class property with the base type and map all the needed methods to this property?
|
`int` is a value type, so each time you do an assignment, (e.g. both instances of `+=` above), it doesn't modify the object you have on the heap, but replaces the reference with one of the result of the right hand side of the assignment (i.e. an `int`)
`list` isn't a value type, so it isn't bound by the same rules.
this page has more details on the differences: [The Python Language Reference - 3. Data model](https://docs.python.org/3/reference/datamodel.html)
IMO, yes, you should define a new class that keeps an int as an instance variable
|
Your two `xint` examples don't work for two different reasons.
The first doesn't work because `self += value` is equivalent to `self = self + value` which just reassigns the local variable `self` to a different object (an integer) but doesn't change the original object. You can't really get this
```
>>> x = xint(10)
>>> x.add(2)
```
to work with a subclass of `int` since integers are [immutable](http://docs.python.org/ref/objects.html).
To get the second one to work you can define an [`__add__` method](http://docs.python.org/ref/numeric-types.html), like so:
```
class xint(int):
def __add__(self, value):
return xint(int.__add__(self, value))
>>> x = xint(10)
>>> type(x)
<class '__main__.xint'>
>>> x += 3
>>> x
13
>>> type(x)
<class '__main__.xint'>
```
|
Extending base classes in Python
|
[
"",
"python",
""
] |
I have an images folder with a png in it. I would like to set a MenuItem's icon to that png. How do I write this in procedural code?
|
```
menutItem.Icon = new System.Windows.Controls.Image
{
Source = new BitmapImage(new Uri("images/sample.png", UriKind.Relative))
};
```
|
```
<MenuItem>
<MenuItem.Icon>
<Image>
<Image.Source>
<BitmapImage UriSource="/your_assembly;component/your_path_here/Image.png" />
</Image.Source>
</Image>
</MenuItem.Icon>
</MenuItem>
```
Just make sure your image in also included in the project file and marked as resource, and you are good to go :)
|
WPF setting a MenuItem.Icon in code
|
[
"",
"c#",
"wpf",
"icons",
"menuitem",
""
] |
Is it possible to access an element on a Master page from the page loaded within the `ContentPlaceHolder` for the master?
I have a ListView that lists people's names in a navigation area on the Master page. I would like to update the ListView after a person has been added to the table that the ListView is data bound to. The `ListView` currently does not update it's values until the cache is reloaded. We have found that just re-running the `ListView.DataBind()` will update a listview's contents. We have not been able to run the `ListView.DataBind()` on a page that uses the Master page.
Below is a sample of what I wanted to do but a compiler error says
> "PeopleListView does not exist in the current context"
GIS.master - Where ListView resides
```
...<asp:ListView ID="PeopleListView"...
```
GISInput\_People.aspx - Uses GIS.master as it's master page
GISInput\_People.aspx.cs
```
AddNewPerson()
{
// Add person to table
....
// Update Person List
PeopleListView.DataBind();
...
}
```
What would be the best way to resolve an issue like this in C# .Net?
|
I believe you *could* do this by using this.Master.FindControl or something similar, but you probably shouldn't - it requires the content page to know too much about the structure of the master page.
I would suggest another method, such as firing an event in the content area that the master could listen for and re-bind when fired.
|
Assuming the control is called "PeopleListView" on the master page
```
ListView peopleListView = (ListView)this.Master.FindControl("PeopleListView");
peopleListView.DataSource = [whatever];
peopleListView.DataBind();
```
But @[palmsey](https://stackoverflow.com/users/521/palmsey) is more correct, especially if your page could have the possibility of more than one master page. Decouple them and use an event.
|
How to access .Net element on Master page from a Content page?
|
[
"",
"c#",
".net",
""
] |
In a C# (feel free to answer for other languages) loop, what's the difference between `break` and `continue` as a means to leave the structure of the loop, and go to the next iteration?
Example:
```
foreach (DataRow row in myTable.Rows)
{
if (someConditionEvalsToTrue)
{
break; //what's the difference between this and continue ?
//continue;
}
}
```
|
`break` will exit the loop completely, `continue` will just **skip** the current iteration.
For example:
```
for (int i = 0; i < 10; i++) {
if (i == 0) {
break;
}
DoSomeThingWith(i);
}
```
The `break` will cause the loop to exit on the first iteration —`DoSomeThingWith` will never be executed.
While:
```
for (int i = 0; i < 10; i++) {
if (i == 0) {
continue;
}
DoSomeThingWith(i);
}
```
Here `continue` skips to the next iteration of the for-loop, meaning `DoSomeThingWith` will not execute for `i == 0`.
But the loop will **continue** and `DoSomeThingWith` will be executed for `i == 1` to `i == 9`.
|
A really easy way to understand this is to place the word "loop" after each of the keywords. The terms now make sense if they are just read like everyday phrases.
**`break`** loop - looping is broken and stops.
**`continue`** loop - loop continues to execute with the next iteration.
|
C# loop — break vs. continue
|
[
"",
"c#",
"loops",
"break",
"enumeration",
"continue",
""
] |
I've deployed some Managed Beans on WebSphere 6.1 and I've managed to invoke them through a standalone client, but when I try to use the application "jconsole" distributed with the standard JDK can can't make it works.
Has anyone achieved to connect the jconsole with WAS 6.1?
IBM WebSphere 6.1 it's supossed to support JSR 160 JavaTM Management Extensions (JMX) Remote API. Furthermore, it uses the MX4J implementation (<http://mx4j.sourceforge.net>). But I can't make it works with neither "jconsole" nor "MC4J".
I have the Classpath and the JAVA\_HOME correctly setted, so the issue it's not there.
|
WebSphere's support for JMX is crap. Particularly, if you need to connect to any secured JMX beans. Here's an interesting tidbit, their own implementation of jConsole will not connect to their own JVM. I have had a PMR open with IBM for over a year to fix this issue, and have gotten nothing but the runaround. They clearly don't want to fix this issue.
The only way I have been able to invoke remote secured JMX beans hosted on WebSphere has been to implement a client using the "WebSphere application client". This is basically a stripped down app server used for stuff like this.
Open a PMR with IBM. Perhaps if more people report this issue, they will actually fix it.
> **Update:** You can run your application as a WebSphere Application Client in RAD. Open the run menu, then choose "Run...". In the dialog that opens, towards the bottom on the left hand side, you will see "WebSphere v6.1 Application Client". I'm not sure how to start and Application Client outside of RAD.
|
IT WORKS !
<http://issues.apache.org/jira/browse/GERONIMO-4534;jsessionid=FB20DD5973F01DD2D470FB9A1B45D209?page=com.atlassian.jira.plugin.system.issuetabpanels%3Aall-tabpanel>
```
1) Change the config.xml and start the server.
```
-see here how to change config.xml: <http://publib.boulder.ibm.com/wasce/V2.1.0/en/working-with-jconsole.html>
```
2) start the jconsole with : jconsole -J-Djavax.net.ssl.keyStore=%GERONIMO_HOME%\var\security\keystores\geronimo-default -J-Djavax.net.ssl.keyStorePassword=secret -J-Djavax.net.ssl.trustStore=%GERONIMO_HOME%\var\security\keystores\geronimo-default -J-Djavax.net.ssl.trustStorePassword=secret -J-Djava.class.path=%JAVA_HOME%\lib\jconsole.jar;%JAVA_HOME%\lib\tools.jar;%GERONIMO_HOME%\repository\org\apache\geronimo\framework\geronimo-kernel\2.1.4\geronimo-kernel-2.1.4.jar
```
[or your version of geronimo-kernel jar]
```
3) in the jconsole interface->advanced, input:
JMX URL: service:jmx:rmi:///jndi/rmi://localhost:1099/JMXSecureConnector
user name: system
password: manager
4) click the connect button.
```
|
How can I make "jconsole" work with Websphere 6.1?
|
[
"",
"java",
"websphere",
"jmx",
"mbeans",
""
] |
(**Updated a little**)
I'm not very experienced with internationalization using PHP, it must be said, and a deal of searching didn't really provide the answers I was looking for.
I'm in need of working out a reliable way to convert only 'relevant' text to Unicode to send in an SMS message, using PHP (just temporarily, whilst service is rewritten using C#) - obviously, messages sent at the moment are sent as plain text.
I could conceivably convert everything to the Unicode charset (as opposed to using the standard GSM charset), but that would mean that *all* messages would be limited to 70 characters (instead of 160).
So, I guess my real question is: *what is the most reliable way to detect the requirement for a message to be Unicode-encoded, so I only have to do it when it's* ***absolutely necessary*** *(e.g. for non-Latin-language characters)?*
## Added Info:
Okay, so I've spent the morning working on this, and I'm still no further on than when I started (certainly due to my complete lack of competency when it comes to charset conversion). So here's the revised scenario:
I have text SMS messages coming from an external source, this external source provides the responses to me in plain text + Unicode slash-escaped characters. E.g. the 'displayed' text:
> Let's test öäü éàè אין תמיכה בעברית
Returns:
> Let's test \u00f6\u00e4\u00fc \u00e9\u00e0\u00e8 \u05d0\u05d9\u05df \u05ea\u05de\u05d9\u05db\u05d4 \u05d1\u05e2\u05d1\u05e8\u05d9\u05ea
Now, I can send on to my SMS provider in plaintext, GSM 03.38 or Unicode. Obviously, sending the above as plaintext results in a lot of missing characters (they're replaced by spaces by my provider) - I need to adopt relating to what content there is. What I want to *do* with this is the following:
1. If all text is within the [GSM 03.38 codepage](http://www.dreamfabric.com/sms/default_alphabet.html), send it as-is. (All but the Hebrew characters above fit into this category, but need to be converted.)
2. Otherwise, convert it to Unicode, and send it over multiple messages (as the Unicode limit is 70 chars not 160 for an SMS).
As I said above, I'm stumped on doing this in PHP (C# wasn't much of an issue due to some simple conversion functions built-in), but it's quite probable I'm just missing the obvious, here. I couldn't find any pre-made conversion classes for 7-bit encoding in PHP, either - and my attempts to convert the string myself and send it on seemed futile.
**Any help would be greatly appreciated.**
|
To deal with it conceptually before getting into mechanisms, and apologies if any of this is obvious, a string can be defined as a sequence of Unicode characters, Unicode being a database that gives an id number known as a code point to every character you might need to work with. GSM-338 contains a subset of the Unicode characters, so what you're doing is extracting a set of codepoints from your string, and checking to see if that set is contained in GSM-338.
```
// second column of http://unicode.org/Public/MAPPINGS/ETSI/GSM0338.TXT
$gsm338_codepoints = array(0x0040, 0x0000, ..., 0x00fc, 0x00e0)
$can_use_gsm338 = true;
foreach(codepoints($mystring) as $codepoint){
if(!in_array($codepoint, $gsm338_codepoints)){
$can_use_gsm338 = false;
break;
}
}
```
That leaves the definition of the function codepoints($string), which isn't built in to PHP. PHP understands a string to be a sequence of bytes rather than a sequence of Unicode characters. The best way of bridging the gap is to get your strings into UTF8 as quickly as you can and keep them in UTF8 as long as you can - you'll have to use other encodings when dealing with external systems, but isolate the conversion to the interface to that system and deal only with utf8 internally.
The functions you need to convert between php strings in utf8 and sequences of codepoints can be found at <http://hsivonen.iki.fi/php-utf8/> , so that's your codepoints() function.
If you're taking data from an external source that gives you Unicode slash-escaped characters ("Let's test \u00f6\u00e4\u00fc..."), that string escape format should be converted to utf8. I don't know offhand of a function to do this, if one can't be found, it's a matter of string/regex processing + the use of the hsivonen.iki.fi functions, for example when you hit \u00f6, replace it with the utf8 representation of the codepoint 0xf6.
|
Although this is an old thread I recently had to solve a very similar problem and wanted to post my answer. The PHP code is somewhat simple. It starts with a painstakingly large array of GSM valid character codes in an array, then simply checks if the current character is in that array using the [ord($string) function](https://www.php.net/ord) which returns the ascii value of the first character of the string passed. Here is the code I use to validate if a string is GSM worth.
```
$valid_gsm_keycodes = Array(
0x0040, 0x0394, 0x0020, 0x0030, 0x00a1, 0x0050, 0x00bf, 0x0070,
0x00a3, 0x005f, 0x0021, 0x0031, 0x0041, 0x0051, 0x0061, 0x0071,
0x0024, 0x03a6, 0x0022, 0x0032, 0x0042, 0x0052, 0x0062, 0x0072,
0x00a5, 0x0393, 0x0023, 0x0033, 0x0043, 0x0053, 0x0063, 0x0073,
0x00e8, 0x039b, 0x00a4, 0x0034, 0x0035, 0x0044, 0x0054, 0x0064, 0x0074,
0x00e9, 0x03a9, 0x0025, 0x0045, 0x0045, 0x0055, 0x0065, 0x0075,
0x00f9, 0x03a0, 0x0026, 0x0036, 0x0046, 0x0056, 0x0066, 0x0076,
0x00ec, 0x03a8, 0x0027, 0x0037, 0x0047, 0x0057, 0x0067, 0x0077,
0x00f2, 0x03a3, 0x0028, 0x0038, 0x0048, 0x0058, 0x0068, 0x0078,
0x00c7, 0x0398, 0x0029, 0x0039, 0x0049, 0x0059, 0x0069, 0x0079,
0x000a, 0x039e, 0x002a, 0x003a, 0x004a, 0x005a, 0x006a, 0x007a,
0x00d8, 0x001b, 0x002b, 0x003b, 0x004b, 0x00c4, 0x006b, 0x00e4,
0x00f8, 0x00c6, 0x002c, 0x003c, 0x004c, 0x00d6, 0x006c, 0x00f6,
0x000d, 0x00e6, 0x002d, 0x003d, 0x004d, 0x00d1, 0x006d, 0x00f1,
0x00c5, 0x00df, 0x002e, 0x003e, 0x004e, 0x00dc, 0x006e, 0x00fc,
0x00e5, 0x00c9, 0x002f, 0x003f, 0x004f, 0x00a7, 0x006f, 0x00e0 );
for($i = 0; $i < strlen($string); $i++) {
if(!in_array($string[$i], $valid_gsm_keycodes)) return false;
}
return true;
```
|
'Reliable' SMS Unicode & GSM Encoding in PHP
|
[
"",
"php",
"unicode",
"sms",
"gsm",
""
] |
How can I calculate the value of PI using C#?
I was thinking it would be through a recursive function, if so, what would it look like and are there any math equations to back it up?
I'm not too fussy about performance, mainly how to go about it from a learning point of view.
|
If you want recursion:
```
PI = 2 * (1 + 1/3 * (1 + 2/5 * (1 + 3/7 * (...))))
```
This would become, after some rewriting:
```
PI = 2 * F(1);
```
with F(i):
```
double F (int i) {
return 1 + i / (2.0 * i + 1) * F(i + 1);
}
```
Isaac Newton (you may have heard of him before ;) ) came up with this trick.
Note that I left out the end condition, to keep it simple. In real life, you kind of need one.
|
How about using:
```
double pi = Math.PI;
```
If you want better precision than that, you will need to use an algorithmic system and the Decimal type.
|
How do I calculate PI in C#?
|
[
"",
"c#",
"pi",
""
] |
I have just received and bypassed a problem with LightWindow and IE7 where, on page load, it throws a JavaScript error on line 444 of `lightwindow.js`, claiming that the `object does not support this property or method`. Despite finding various postings on various forums, no Google result I could find had a solution, so I am posting this here in the hopes that it will help someone / myself later.
Many suggested a specific order of the script files but I was already using this order (prototype, scriptaculous, lightwindow).
These are the steps I took that seemed to finally work, I write them here only as a record as I do not know nor have time to test which ones specifically "fixed" the issue:
1. Moved the call to lightwindow.js to the bottom of the page.
2. Changed line 444 to: `if (this._getGalleryInfo(link.rel)) {`
3. Changed line 1157 to: `if (this._getGalleryInfo(this.element.rel)) {`
4. Finally, I enclosed (and this is dirty, my apologies) lines 1417 to 1474 with a `try/catch` block, swallowing the exception.
**EDIT:**
I realised that this broke Firefox. Adding the following as line 445 now makes it work - `try { gallery = this._getGalleryInfo(link.rel); } catch (e) { }`
It's not a very nice fix, but my page (which contains a lightwindow link with no "rel" tag, several lightwindow links which do have "rel" tags, and one "inline" link) works just fine in IE7 now. Please comment if you have anything to add about this issue or problems with / improvements to my given solution.
|
I fixed this by changing line 444 to:
```
var gallery = this._getGalleryInfo(link.rel)
```
Then changing the subsequent comparison statement to:
```
if(gallery.length > 0)
{
// Rest of code here...
```
...which seems to have sorted it in IE6+ and kept it working in Firefox etc.
I didn't change line 1157 at all, but I haven't read the code to see what I actually does so I can't comment on its relevance?
I suspect the ? used in the example rel attribute (Evoution?[man]) may be causing the problem with IE but without spending some time testing a few things, I can't be sure?
HTH.
|
Instead of the try..catch maybe you could try using
```
if( this && this._getGalleryInfo )
{
//use the function
}
```
you could also check in the same way **this.element.rel** ( `if(this && this.element && this.element.rel)` ... ) before using it.
It looks like there's a case that the `_getGalleryInfo` or `this.element.rel` has not yet been initialized so it wouldn't exist yet. Check if it exists then if I does use it.
of course i could be completely wrong, the only way to know is by testing it out.
|
LightWindow & IE7, "Line 444 - object does not support this property or method"
|
[
"",
"javascript",
"debugging",
"internet-explorer-7",
"lightwindow",
""
] |
What's the best Python idiom for this C construct?
```
while ((x = next()) != END) {
....
}
```
I don't have the ability to recode next().
update: and the answer from seems to be:
```
for x in iter(next, END):
....
```
|
Short answer: there's no way to do inline variable assignment in a while loop in Python. Meaning that I **cannot** say:
```
while x=next():
// do something here!
```
Since that's not possible, there are a number of "idiomatically correct" ways of doing this:
```
while 1:
x = next()
if x != END:
// Blah
else:
break
```
Obviously, this is kind of ugly. You can also use one of the "iterator" approaches listed above, but, again, that may not be ideal. Finally, you can use the "pita pocket" approach that I actually just found while googling:
```
class Pita( object ):
__slots__ = ('pocket',)
marker = object()
def __init__(self, v=marker):
if v is not self.marker:
self.pocket = v
def __call__(self, v=marker):
if v is not self.marker:
self.pocket = v
return self.pocket
```
Now you can do:
```
p = Pita()
while p( next() ) != END:
// do stuff with p.pocket!
```
Thanks for this question; learning about the `__call__` idiom was really cool! :)
EDIT: I'd like to give credit where credit is due. The 'pita pocket' idiom was found [here](http://mail.python.org/pipermail/python-list/2003-July/216789.html)
|
@Mark Harrison's answer:
```
for x in iter(next_, END):
....
```
Here's an excerpt from [Python's documentation](http://docs.python.org/library/functions.html):
```
iter(o[, sentinel])
```
> Return an iterator object.
> *...(snip)...* If the second argument, `sentinel`, is given, then `o` must be
> a callable object. The iterator
> created in this case will call `o`
> with no arguments for each call to its
> `next()` method; if the value returned
> is equal to `sentinel`,
> `StopIteration` will be raised,
> otherwise the value will be returned.
|
Most Pythonic way equivalent for: while ((x = next()) != END)
|
[
"",
"c",
"python",
""
] |
I'm trying to serialize a Type object in the following way:
```
Type myType = typeof (StringBuilder);
var serializer = new XmlSerializer(typeof(Type));
TextWriter writer = new StringWriter();
serializer.Serialize(writer, myType);
```
When I do this, the call to Serialize throws the following exception:
> "The type System.Text.StringBuilder was not expected. Use the
> XmlInclude or SoapInclude attribute to specify types that are not
> known statically."
Is there a way for me to serialize the `Type` object? Note that I am not trying to serialize the `StringBuilder` itself, but the `Type` object containing the metadata about the `StringBuilder` class.
|
I wasn't aware that a Type object could be created with only a string containing the fully-qualified name. To get the fully qualified name, you can use the following:
```
string typeName = typeof (StringBuilder).FullName;
```
You can then persist this string however needed, then reconstruct the type like this:
```
Type t = Type.GetType(typeName);
```
If you need to create an instance of the type, you can do this:
```
object o = Activator.CreateInstance(t);
```
If you check the value of o.GetType(), it will be StringBuilder, just as you would expect.
|
I had the same problem, and my solution was to create a SerializableType class. It freely converts to and from System.Type, but it serializes as a string. All you have to do is declare the variable as a SerializableType, and from then on you can refer to it as System.Type.
Here is the class:
```
// a version of System.Type that can be serialized
[DataContract]
public class SerializableType
{
public Type type;
// when serializing, store as a string
[DataMember]
string TypeString
{
get
{
if (type == null)
return null;
return type.FullName;
}
set
{
if (value == null)
type = null;
else
{
type = Type.GetType(value);
}
}
}
// constructors
public SerializableType()
{
type = null;
}
public SerializableType(Type t)
{
type = t;
}
// allow SerializableType to implicitly be converted to and from System.Type
static public implicit operator Type(SerializableType stype)
{
return stype.type;
}
static public implicit operator SerializableType(Type t)
{
return new SerializableType(t);
}
// overload the == and != operators
public static bool operator ==(SerializableType a, SerializableType b)
{
// If both are null, or both are same instance, return true.
if (System.Object.ReferenceEquals(a, b))
{
return true;
}
// If one is null, but not both, return false.
if (((object)a == null) || ((object)b == null))
{
return false;
}
// Return true if the fields match:
return a.type == b.type;
}
public static bool operator !=(SerializableType a, SerializableType b)
{
return !(a == b);
}
// we don't need to overload operators between SerializableType and System.Type because we already enabled them to implicitly convert
public override int GetHashCode()
{
return type.GetHashCode();
}
// overload the .Equals method
public override bool Equals(System.Object obj)
{
// If parameter is null return false.
if (obj == null)
{
return false;
}
// If parameter cannot be cast to SerializableType return false.
SerializableType p = obj as SerializableType;
if ((System.Object)p == null)
{
return false;
}
// Return true if the fields match:
return (type == p.type);
}
public bool Equals(SerializableType p)
{
// If parameter is null return false:
if ((object)p == null)
{
return false;
}
// Return true if the fields match:
return (type == p.type);
}
}
```
and an example of usage:
```
[DataContract]
public class A
{
...
[DataMember]
private Dictionary<SerializableType, B> _bees;
...
public B GetB(Type type)
{
return _bees[type];
}
...
}
```
You might also consider using AssemblyQualifiedName instead of Type.FullName - see comment by @GreyCloud
|
Can I serialize a C# Type object?
|
[
"",
"c#",
"serialization",
""
] |
I'm looking to the equivalent of Windows [`_wfopen()`](http://msdn.microsoft.com/fr-fr/library/yeby3zcb.aspx) under Mac OS X. Any idea?
I need this in order to port a Windows library that uses `wchar*` for its File interface. As this is intended to be a cross-platform library, I am unable to rely on how the client application will get the file path and give it to the library.
|
POSIX API in Mac OS X are usable with UTF-8 strings. In order to convert a wchar\_t string to UTF-8, it is possible to use the CoreFoundation framework from Mac OS X.
Here is a class that will wrap an UTF-8 generated string from a wchar\_t string.
```
class Utf8
{
public:
Utf8(const wchar_t* wsz): m_utf8(NULL)
{
// OS X uses 32-bit wchar
const int bytes = wcslen(wsz) * sizeof(wchar_t);
// comp_bLittleEndian is in the lib I use in order to detect PowerPC/Intel
CFStringEncoding encoding = comp_bLittleEndian ? kCFStringEncodingUTF32LE
: kCFStringEncodingUTF32BE;
CFStringRef str = CFStringCreateWithBytesNoCopy(NULL,
(const UInt8*)wsz, bytes,
encoding, false,
kCFAllocatorNull
);
const int bytesUtf8 = CFStringGetMaximumSizeOfFileSystemRepresentation(str);
m_utf8 = new char[bytesUtf8];
CFStringGetFileSystemRepresentation(str, m_utf8, bytesUtf8);
CFRelease(str);
}
~Utf8()
{
if( m_utf8 )
{
delete[] m_utf8;
}
}
public:
operator const char*() const { return m_utf8; }
private:
char* m_utf8;
};
```
Usage:
```
const wchar_t wsz = L"Here is some Unicode content: éà€œæ";
const Utf8 utf8 = wsz;
FILE* file = fopen(utf8, "r");
```
This will work for reading or writing files.
|
You just want to open a file handle using a path that may contain Unicode characters, right? Just pass the path in *filesystem representation* to `fopen`.
* If the path came from the stock Mac OS X frameworks (for example, an Open panel whether Carbon or Cocoa), you won't need to do any conversion on it and will be able to use it as-is.
* If you're generating part of the path yourself, you should create a CFStringRef from your path and then get that in filesystem representation to pass to POSIX APIs like `open` or `fopen`.
Generally speaking, you won't have to do a lot of that for most applications. For example, many applications may have auxiliary data files stored the user's Application Support directory, but as long as the names of those files are ASCII, and you use standard Mac OS X APIs to locate the user's Application Support directory, you don't need to do a bunch of paranoid conversion of a path constructed with those two components.
*Edited to add:* I would strongly caution **against** arbitrarily converting everything to UTF-8 using something like `wcstombs` because filesystem encoding is not necessarily identical to the generated UTF-8. Mac OS X and Windows both use specific (but different) canonical decomposition rules for the encoding used in filesystem paths.
For example, they need to decide whether "é" will be stored as one or two code units (either `LATIN SMALL LETTER E WITH ACUTE` or `LATIN SMALL LETTER E` followed by `COMBINING ACUTE ACCENT`). These will result in two different — and different-length — byte sequences, and both Mac OS X and Windows work to avoid putting multiple files with the same name (as the user perceives them) in the same directory.
The rules for how to perform this canonical decomposition can get pretty hairy, so rather than try to implement it yourself it's best to leave it to the functions the system frameworks have provided for you to do the heavy lifting.
|
_wfopen equivalent under Mac OS X
|
[
"",
"c++",
"winapi",
"macos",
"porting",
"fopen",
""
] |
I am looking for a more technical explanation than the OS calls the function.
Is there a website or book?
|
The .exe file (or equivalent on other platforms) contains an 'entry point' address. To a first approximation, the OS loads the relevant sections of the .EXE file into RAM, and then jumps to the entry point.
As others have said, this entry point will not be 'main', but will instead be a part of the runtime library - it will do things like initialising static objects, setting up the *argc* and *argv* parameters, setting up standard input, standard output, standard error, etc. When it's done all that, it will call your main() function. When main exits, the runtime goes through an analogous process of passing your return code back to the environment, calling static destructors, calling \_atexit routines, etc.
If you have Microsoft tools (perhaps not the freebie ones), then you have all the runtime source, and an easy way to look at it is to put a breakpoint on the closing brace of your main() method, and single step back up into the runtime.
|
`main()` is part of the C library and is not a system function. I don't know for OS X or Linux, but Windows usually starts a program with `WinMainCRTStartup()`. This symbol init your process, extract command line arguments and environment (`argc, argv, end`) and calls `main()`. It is also responsible of calling any code that should run after `main()`, like `atexit()`.
By looking in your Visual Studio file, you should be able to find the default implementation of `WinMainCRTStartup` to see what it does.
You can also define a function of your own to call at startup, this is done by changing "entry point" in the linker options. This is often a function that takes no arguments and returns a void.
|
In a C/C++ program, how does the system (Windows, Linux, and Mac OS X) call the main() function?
|
[
"",
"c++",
"c",
"program-entry-point",
""
] |
I'm running PHP 5.2.3 on Windows 2000 Server with IIS 5. I'm trying
to get cURL working, so in my **php.ini** file, I have this line:
> extension\_dir ="F:\PHP\ext"
And later, I have:
> extension=php\_curl.dll
The file **F:\PHP\ext\php\_curl.dll** exists, but when I try to run any PHP
script, I get this in the error log:
> PHP Warning: PHP Startup: Unable to load dynamic library 'F:\PHP\ext
> \php\_curl.dll' - The specified module could not be found.
> in Unknown on line 0
|
Problem solved!
Although the error message said **The specified module could not be found**, this is a little misleading -- it's not that it couldn't find `php_curl.dll`, but rather it couldn't find a module that `php_curl.dll` required. The 2 DLLs it requires are `libeay32.dll` and `SSLeay32.dll`.
So, you have to put those 2 DLLs somewhere in your PATH (e.g., `C:\Windows\system32`). That's all there is to it.
However, even that did not work for me initially. So I downloaded the Windows zip of the latest version of PHP, which includes all the necessary DLLs. I didn't reinstall PHP, I just copied all of the DLLs in the "ext" folder to my PHP extensions folder (as specified in the `extension_dir` variable in `php.ini`), and I copied the versions of `libeay32.dll` and `SSLeay32.dll` from the PHP download into my System32 directory.
I also did an iisreset, but I don't know if that was necessary.
|
`libeay32.dll` and `ssleay32.dll` have to be path-accessible for `php_curl.dll` to work correctly.
In **Control Panel** -> **Search** -> **Advanced System Settings** and use the button **Environment Variables**.
Under **System Variables** find **Path** add the `c:/php` folder (or whatever path) and restart Apache.
|
PHP / cURL on Windows install: "The specified module could not be found."
|
[
"",
"php",
"windows",
"curl",
""
] |
I've written a stored proc that will do an update if a record exists, otherwise it will do an insert. It looks something like this:
```
update myTable set Col1=@col1, Col2=@col2 where ID=@ID
if @@rowcount = 0
insert into myTable (Col1, Col2) values (@col1, @col2)
```
My logic behind writing it in this way is that the update will perform an implicit select using the where clause and if that returns 0 then the insert will take place.
The alternative to doing it this way would be to do a select and then based on the number of rows returned either do an update or insert. This I considered inefficient because if you are to do an update it will cause 2 selects (the first explicit select call and the second implicit in the where of the update). If the proc were to do an insert then there'd be no difference in efficiency.
Is my logic sound here?
Is this how you would combine an insert and update into a stored proc?
|
Your assumption is right, this is the optimal way to do it and it's called [upsert/merge](http://en.wikipedia.org/wiki/Upsert).
[Importance of UPSERT - from sqlservercentral.com](http://www.sqlservercentral.com/articles/T-SQL/61773/):
> For every update in the case mentioned above we are removing one
> additional read from the table if we
> use the UPSERT instead of EXISTS.
> Unfortunately for an Insert, both the
> UPSERT and IF EXISTS methods use the
> same number of reads on the table.
> Therefore the check for existence
> should only be done when there is a
> very valid reason to justify the
> additional I/O. The optimized way to
> do things is to make sure that you
> have little reads as possible on the
> DB.
>
> The best strategy is to attempt the
> update. If no rows are affected by the
> update then insert. In most
> circumstances, the row will already
> exist and only one I/O will be
> required.
**Edit**:
Please check out [this answer](https://stackoverflow.com/questions/13540/insert-update-stored-proc-on-sql-server/193876#193876) and the linked blog post to learn about the problems with this pattern and how to make it work safe.
|
Please read the [post on my blog](http://samsaffron.com/blog/archive/2007/04/04/14.aspx) for a good, safe pattern you can use. There are a lot of considerations, and the accepted answer on this question is far from safe.
For a quick answer try the following pattern. It will work fine on SQL 2000 and above. SQL 2005 gives you error handling which opens up other options and SQL 2008 gives you a MERGE command.
```
begin tran
update t with (serializable)
set hitCount = hitCount + 1
where pk = @id
if @@rowcount = 0
begin
insert t (pk, hitCount)
values (@id,1)
end
commit tran
```
|
Insert Update stored proc on SQL Server
|
[
"",
"sql",
"sql-server",
"stored-procedures",
"upsert",
""
] |
I'm having trouble figuring out how to get the testing framework set up and usable in **Visual Studio 2008** for C++ presumably with the built-in unit testing suite.
Any links or tutorials would be appreciated.
|
[This page](http://gamesfromwithin.com/exploring-the-c-unit-testing-framework-jungle) may help, it reviews quite a few C++ unit test frameworks:
* CppUnit
* Boost.Test
* CppUnitLite
* NanoCppUnit
* Unit++
* CxxTest
Check out ***[CPPUnitLite](http://www.objectmentor.com/resources/downloads.html)*** or ***[CPPUnitLite2](http://gamesfromwithin.com/?p=48)***.
*CPPUnitLite* was created by Michael Feathers, who originally ported Java's JUnit to C++ as CPPUnit (CPPUnit tries mimic the development model of JUnit - but C++ lacks Java's features [e.g. reflection] to make it easy to use).
CPPUnitLite attempts to make a true C++-style testing framework, not a Java one ported to C++. (I'm paraphrasing from Feather's [Working Effectively with Legacy Code](https://rads.stackoverflow.com/amzn/click/com/0131177052) book). *CPPUnitLite2* seems to be another rewrite, with more features and bug fixes.
I also just stumbled across ***[UnitTest++](http://sourceforge.net/projects/unittest-cpp/)*** which includes stuff from CPPUnitLite2 and some other framework.
Microsoft has released ***[WinUnit](http://winunit.codeplex.com/)***.
Also checkout ***[Catch](https://github.com/philsquared/Catch)*** or ***[Doctest](https://github.com/onqtam/doctest)***
|
**There is a way to test unmanaged C++ using the built in testing framework within Visual Studio 2008**. If you create a C++ Test Project, using C++/CLI, you can then make calls to an unmanaged DLL. You will have to switch the Common Language Runtime support to /clr from /clr:safe if you want to test code that was written in unmanaged C++.
I have step by step details on my blog here: <http://msujaws.wordpress.com/2009/05/06/unit-testing-mfc-with-mstest/>
|
How to set up unit testing for Visual Studio C++
|
[
"",
"c++",
"unit-testing",
"testing",
"visual-studio-2008",
"frameworks",
""
] |
I need to store products for an e-commerce solution in a database. Each product should have descriptive information, such as name, description etc.
I need any product to be localized to x number of languages.
What I've done so far, is to make any column that should be localized and `nvarchar(MAX)` and then i store an XML string like this:
```
<cultures>
<culture code="en-us">Super fast laptop</culture>
<culture code="da-dk">Super hurtig bærbar</culture>
</cultures>
```
And when I load it from the database, into my business logic objects, I parse the XML string to a `Dictionary<string, string>` where the key is the culture/language code.
So when I want to display the name of a product, I do this:
```
lblName.Text = product.Name["en-us"];
```
Does anyone have a better solution?
|
You should store the current language somewhere (in a [singleton](http://www.yoda.arachsys.com/csharp/singleton.html), for instance) and in the product.Name property use the language setting to get the correct string. This way you only have to write the language specific code once for each field rather than thinking about languages everywhere the field is used.
For example, assuming your singleton is defined in the Localizer class that stores an enum corresponding to the current language:
```
public class Product
{
private idType id;
public string Name
{
get
{
return Localizer.Instance.GetLocalString(id, "Name");
}
}
}
```
Where GetLocalString looks something like:
```
public string GetLocalString(idType objectId, string fieldName)
{
switch (_currentLanguage)
{
case Language.English:
// db access code to retrieve your string, may need to include the table
// the object is in (e.g. "Products" "Orders" etc.)
db.GetValue(objectId, fieldName, "en-us");
break;
}
}
```
|
Rob Conery's MVC Storefront webcast series has [a video on this issue](http://blog.wekeroad.com/mvc-storefront/mvcstore-part-5/) (he gets to the database around 5:30). He stores a list of cultures, and then has a Product table for non-localized data and a ProductCultureDetail table for localized text.
|
Globalization architecture
|
[
"",
"c#",
"architecture",
"localization",
"globalization",
""
] |
What is the **complete** and correct syntax for the SQL Case expression?
|
The **complete** syntax depends on the database engine you're working with:
For SQL Server:
```
CASE case-expression
WHEN when-expression-1 THEN value-1
[ WHEN when-expression-n THEN value-n ... ]
[ ELSE else-value ]
END
```
or:
```
CASE
WHEN boolean-when-expression-1 THEN value-1
[ WHEN boolean-when-expression-n THEN value-n ... ]
[ ELSE else-value ]
END
```
expressions, etc:
```
case-expression - something that produces a value
when-expression-x - something that is compared against the case-expression
value-1 - the result of the CASE statement if:
the when-expression == case-expression
OR the boolean-when-expression == TRUE
boolean-when-exp.. - something that produces a TRUE/FALSE answer
```
Link: [CASE (Transact-SQL)](http://msdn.microsoft.com/en-us/library/ms181765.aspx)
Also note that the ordering of the WHEN statements is important. You can easily write multiple WHEN clauses that overlap, and **the first one that matches is used**.
**Note**: If no ELSE clause is specified, and no matching WHEN-condition is found, the value of the CASE expression will be *NULL*.
|
Considering you tagged multiple products, I'd say the *full* correct syntax would be the one found in the ISO/ANSI SQL-92 standard:
```
<case expression> ::=
<case abbreviation>
| <case specification>
<case abbreviation> ::=
NULLIF <left paren> <value expression> <comma>
<value expression> <right paren>
| COALESCE <left paren> <value expression>
{ <comma> <value expression> }... <right paren>
<case specification> ::=
<simple case>
| <searched case>
<simple case> ::=
CASE <case operand>
<simple when clause>...
[ <else clause> ]
END
<searched case> ::=
CASE
<searched when clause>...
[ <else clause> ]
END
<simple when clause> ::= WHEN <when operand> THEN <result>
<searched when clause> ::= WHEN <search condition> THEN <result>
<else clause> ::= ELSE <result>
<case operand> ::= <value expression>
<when operand> ::= <value expression>
<result> ::= <result expression> | NULL
<result expression> ::= <value expression>
```
Syntax Rules
```
1) NULLIF (V1, V2) is equivalent to the following <case specification>:
CASE WHEN V1=V2 THEN NULL ELSE V1 END
2) COALESCE (V1, V2) is equivalent to the following <case specification>:
CASE WHEN V1 IS NOT NULL THEN V1 ELSE V2 END
3) COALESCE (V1, V2, . . . ,n ), for n >= 3, is equivalent to the
following <case specification>:
CASE WHEN V1 IS NOT NULL THEN V1 ELSE COALESCE (V2, . . . ,n )
END
4) If a <case specification> specifies a <simple case>, then let CO
be the <case operand>:
a) The data type of each <when operand> WO shall be comparable
with the data type of the <case operand>.
b) The <case specification> is equivalent to a <searched case>
in which each <searched when clause> specifies a <search
condition> of the form "CO=WO".
5) At least one <result> in a <case specification> shall specify a
<result expression>.
6) If an <else clause> is not specified, then ELSE NULL is im-
plicit.
7) The data type of a <case specification> is determined by ap-
plying Subclause 9.3, "Set operation result data types", to the
data types of all <result expression>s in the <case specifica-
tion>.
Access Rules
None.
General Rules
1) Case:
a) If a <result> specifies NULL, then its value is the null
value.
b) If a <result> specifies a <value expression>, then its value
is the value of that <value expression>.
2) Case:
a) If the <search condition> of some <searched when clause> in
a <case specification> is true, then the value of the <case
specification> is the value of the <result> of the first
(leftmost) <searched when clause> whose <search condition> is
true, cast as the data type of the <case specification>.
b) If no <search condition> in a <case specification> is true,
then the value of the <case expression> is the value of the
<result> of the explicit or implicit <else clause>, cast as
the data type of the <case specification>.
```
|
SQL Case Expression Syntax?
|
[
"",
"sql",
""
] |
In Visual C++ a DWORD is just an unsigned long that is machine, platform, and SDK dependent. However, since DWORD is a double word (that is 2 \* 16), is a DWORD still 32-bit on 64-bit architectures?
|
Actually, on 32-bit computers a word is 32-bit, but the DWORD type is a leftover from the good old days of 16-bit.
In order to make it easier to port programs to the newer system, Microsoft has decided all the old types will not change size.
You can find the official list here:
<http://msdn.microsoft.com/en-us/library/aa383751(VS.85).aspx>
All the platform-dependent types that changed with the transition from 32-bit to 64-bit end with \_PTR (DWORD\_PTR will be 32-bit on 32-bit Windows and 64-bit on 64-bit Windows).
|
It is defined as:
```
typedef unsigned long DWORD;
```
However, according to the MSDN:
> On 32-bit platforms, long is
> synonymous with int.
Therefore, DWORD is 32bit on a 32bit operating system. There is a separate define for a 64bit DWORD:
```
typdef unsigned _int64 DWORD64;
```
Hope that helps.
|
How large is a DWORD with 32- and 64-bit code?
|
[
"",
"c++",
"winapi",
"64-bit",
"dword",
""
] |
I have developed some classes with similar behavior, they all implement the same interface. I implemented a factory that creates the appropriate object and returns the interface. I am writing a unit test for the factory. All you get back is an interface to the object.
What is the best way to test that the factory has worked correctly?
I would like to know the answer in Java, but if there is a solution that crosses languages I would like to know it.
Number 2. in the answer, would be done like the other answer? If so I will mark the other answer accepted as well and reword my question to adress both a factory where an interface is returned and you have no clue what type of concrete class implemented the interface, and the case where you do know what concrete class was used.
|
Since I don't know how your factory method looks like, all I can advise right now is to
1. Check to see the object is the correct concrete implementation you were looking for:
```
IMyInterface fromFactory = factory.create(...);
Assert.assertTrue(fromFactory instanceof MyInterfaceImpl1);
```
2. You can check if the factory setup the concrete instances with valid instance variables.
|
# What you are trying to do is not Unit Testing
If you test whether or not the returned objects are instances of specific concrete classes, you aren't unit testing. You are integration testing. While integration testing is important, it is not the same thing.
In unit testing, you only need to test the object itself. If you assert on the concrete type of the abstract objects returned, you are testing over the implementation of the returned object.
# Unit Testing on Objects in general
When unit testing, there are four things, you want to assert:
1. Return values of queries (non-void methods) are what you expect them to be.
2. Side-effects of commands (void methods) modify the object itself as you expect them to.
3. Commands send to other objects are received (This is usually done using mocks).
Furthermore, you only want to test what could be observed from an object instance, i.e. the public interface. Otherwise, you tie yourself to a specific set of implementation details. This would require you to change your tests when those details change.
# Unit Testing Factories
Unit testing on Factories is really uninteresting, because **you are not interested in the behavior of the returned objects of queries**. That behavior is (hopefully) tested elsewhere, presumable while unit testing that object itself. You are only really interested in whether or not the returned object has the correct *type*, which is guaranteed if your program compiles.
As Factories do not change over time (because then they would be "Builders", which is another pattern), there are no commands to test.
Factories are responsible for instantiating objects, so they should not depend on other factories to do this for them. They *might* depend on a Builder, but even so, we are not supposed to test the Builder's correctness, only whether or not the Builder receives the message.
This means that all you have to test on Factories is whether or not they send the messages to the objects on which they depend. If you use Dependency Injection, this is almost trivial. Just mock the dependencies in your unit tests, and verify that they receive the messages.
# Summary of Unit Testing Factories
1. Do not test the behavior nor the implementation details of the returned objects! Your Factory is not responsible for the implementation of the object instances!
2. Test whether or not the commands sent to dependencies are received.
That's it. If there are no dependencies, there is nothing to test. Except maybe to assert that the returned object isn't a `null` reference.
# Integration Testing Factories
If you have a requirement that the returned abstract object type is an instance of a specific concrete type, then this falls under integration testing.
Others here have already answered how to do this using the `instanceof` operator.
|
Checking the results of a Factory in a unit test
|
[
"",
"java",
"unit-testing",
"tdd",
""
] |
I'm working on a windows forms application (C#) where a user is entering data in a form. At any point while editing the data in the form the user can click one of the buttons on the form to perform certain actions. By default the focus goes to the clicked button so the user has to click back on to the control they want to edit in order to continue modifying the data on the form. What I need to be able to do is return the focus to the last edited control after the button click event has been processed. Here's a sample screenshot that illustrates what I'm talking about:

The user can be entering data in textbox1, textbox2, textbox3, etc and click the button. I need the button to return the focus back to the control that most recently had the focus before the button was clicked.
I'm wondering if anyone has a better way of implementing this functionality than what I've come up with. Here's what I'm doing right now:
```
public partial class Form1 : Form
{
Control _lastEnteredControl;
private void textBox_Enter(object sender, EventArgs e)
{
_lastEnteredControl = (Control)sender;
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Do something here");
_lastEnteredControl.Focus();
}
}
```
So basically what we have here is a class variable that points to the last entered control. Each textbox on the form is setup so the textBox\_Enter method is fired when the control receives the focus. Then, when the button is clicked focus is returned to the control that had the focus before the button was clicked. Anybody have any more elegant solutions for this?
|
For a bit of 'simplicity' maybe try.
```
public Form1()
{
InitializeComponent();
foreach (Control ctrl in Controls)
{
if (ctrl is TextBox)
{
ctrl.Enter += delegate(object sender, EventArgs e)
{
_lastEnteredControl = (Control)sender;
};
}
}
}
```
then you don't have to worry about decorating each textbox manually (or forgetting about one too).
|
You could do the following
Change the button to a label and make it look like a button. The label will never get focus and you don't have to do all the extra coding.
|
How do you return the focus to the last used control after clicking a button in a winform app?
|
[
"",
"c#",
".net",
"winforms",
""
] |
I have multiple selects:
```
<select id="one">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
<select id="two">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
```
What I want is to select "one" from the first select, then have that option be removed from the second one.
Then if you select "two" from the second one, I want that one removed from the first one.
Here's the JS I have currently:
```
$(function () {
var $one = $("#one");
var $two = $("#two");
var selectOptions = [];
$("select").each(function (index) {
selectOptions[index] = [];
for (var i = 0; i < this.options.length; i++) {
selectOptions[index][i] = this.options[i];
}
});
$one.change(function () {
var selectedValue = $("option:selected", this).val();
for (var i = 0; i < selectOptions[1].length; i++) {
var exists = false;
for (var x = 0; x < $two[0].options.length; x++) {
if ($two[0].options[x].value == selectOptions[1][i].value)
exists = true;
}
if (!exists)
$two.append(selectOptions[1][i]);
}
$("option[value='" + selectedValue + "']", $two).remove();
});
$two.change(function () {
var selectedValue = $("option:selected", this).val();
for (var i = 0; i < selectOptions[0].length; i++) {
var exists = false;
for (var x = 0; x < $one[0].options.length; x++) {
if ($one[0].options[x].value == selectOptions[0][i].value)
exists = true;
}
if (!exists)
$one.append(selectOptions[0][i]);
}
$("option[value='" + selectedValue + "']", $one).remove();
});
});
```
But when the elements get repopulated, it fires the change event in the select whose options are changing. I tried just setting the `disabled` attribute on the option I want to remove, but that doesn't work with IE6.
|
I am not (currently) a user of jQuery, but I can tell you that you need to temporarily disconnect your event handler while you repopulate the items or, at the least, set a flag that you then test for and based on its value, handle the change.
|
Here's the final code that I ended up using, the flag (`changeOnce`) worked great, thanks @Jason.
```
$(function () {
var $one = $("#one");
var $two = $("#two");
var selectOptions = [];
$("select").each(function (index) {
selectOptions[index] = [];
for (var i = 0; i < this.options.length; i++) {
selectOptions[index][i] = this.options[i];
}
});
var changeOnce = false;
$one.change(function () {
if (changeOnce) return;
changeOnce = true;
var selectedValue = $("option:selected", this).val();
filterSelect(selectedValue, $two, 1);
changeOnce = false;
});
$two.change(function () {
if (changeOnce) return;
changeOnce = true;
var selectedValue = $("option:selected", this).val();
filterSelect(selectedValue, $one, 0);
changeOnce = false;
});
function filterSelect(selectedValue, $selectToFilter, selectIndex) {
for (var i = 0; i < selectOptions[selectIndex].length; i++) {
var exists = false;
for (var x = 0; x < $selectToFilter[0].options.length; x++) {
if ($selectToFilter[0].options[x].value == selectOptions[selectIndex][i].value)
exists = true;
}
if (!exists)
$selectToFilter.append(selectOptions[selectIndex][i]);
}
$("option[value='" + selectedValue + "']", $selectToFilter).remove();
sortSelect($selectToFilter[0]);
}
function sortSelect(selectToSort) {
var arrOptions = [];
for (var i = 0; i < selectToSort.options.length; i++) {
arrOptions[i] = [];
arrOptions[i][0] = selectToSort.options[i].value;
arrOptions[i][1] = selectToSort.options[i].text;
arrOptions[i][2] = selectToSort.options[i].selected;
}
arrOptions.sort();
for (var i = 0; i < selectToSort.options.length; i++) {
selectToSort.options[i].value = arrOptions[i][0];
selectToSort.options[i].text = arrOptions[i][1];
selectToSort.options[i].selected = arrOptions[i][2];
}
}
});
```
|
Is there any way to repopulate an Html Select's Options without firing the Change event (using jQuery)?
|
[
"",
"javascript",
"jquery",
"dom",
"html-select",
""
] |
When writing a switch statement, there appears to be two limitations on what you can switch on in case statements.
For example (and yes, I know, if you're doing this sort of thing it probably means your [object-oriented](https://en.wikipedia.org/wiki/Object-oriented_programming) (OO) architecture is iffy - this is just a contrived example!),
```
Type t = typeof(int);
switch (t) {
case typeof(int):
Console.WriteLine("int!");
break;
case typeof(string):
Console.WriteLine("string!");
break;
default:
Console.WriteLine("unknown!");
break;
}
```
Here the switch() statement fails with 'A value of an integral type expected' and the case statements fail with 'A constant value is expected'.
Why are these restrictions in place, and what is the underlying justification? I don't see any reason why the switch statement *has* to succumb to static analysis only, and why the value being switched on has to be integral (that is, primitive). What is the justification?
|
This is my original post, which sparked some debate... **because it is wrong**:
> The switch statement is not the same
> thing as a big if-else statement.
> Each case must be unique and evaluated
> statically. The switch statement does
> a constant time branch regardless of
> how many cases you have. The if-else
> statement evaluates each condition
> until it finds one that is true.
---
In fact, the C# switch statement is **not** always a constant time branch.
In some cases the compiler will use a CIL switch statement which is indeed a constant time branch using a jump table. However, in sparse cases as pointed out by [Ivan Hamilton](https://stackoverflow.com/questions/44905/c-switch-statement-limitations-why#48259) the compiler may generate something else entirely.
This is actually quite easy to verify by writing various C# switch statements, some sparse, some dense, and looking at the resulting CIL with the ildasm.exe tool.
|
It's important not to confuse the C# switch statement with the CIL switch instruction.
The CIL switch is a jump table, that requires an index into a set of jump addresses.
This is only useful if the C# switch's cases are adjacent:
```
case 3: blah; break;
case 4: blah; break;
case 5: blah; break;
```
But of little use if they aren't:
```
case 10: blah; break;
case 200: blah; break;
case 3000: blah; break;
```
(You'd need a table ~3000 entries in size, with only 3 slots used)
With non-adjacent expressions, the compiler may start to perform linear if-else-if-else checks.
With larger non- adjacent expression sets, the compiler may start with a binary tree search, and finally if-else-if-else the last few items.
With expression sets containing clumps of adjacent items, the compiler may binary tree search, and finally a CIL switch.
This is full of "mays" & "mights", and it is dependent on the compiler (may differ with Mono or Rotor).
I replicated your results on my machine using adjacent cases:
> total time to execute a 10 way switch, 10000 iterations (ms): 25.1383
> approximate time per 10 way switch (ms): 0.00251383
>
> total time to execute a 50 way switch, 10000 iterations (ms): 26.593
> approximate time per 50 way switch (ms): 0.0026593
>
> total time to execute a 5000 way switch, 10000 iterations (ms): 23.7094
> approximate time per 5000 way switch (ms): 0.00237094
>
> total time to execute a 50000 way switch, 10000 iterations (ms): 20.0933
> approximate time per 50000 way switch (ms): 0.00200933
Then I also did using non-adjacent case expressions:
> total time to execute a 10 way switch, 10000 iterations (ms): 19.6189
> approximate time per 10 way switch (ms): 0.00196189
>
> total time to execute a 500 way switch, 10000 iterations (ms): 19.1664
> approximate time per 500 way switch (ms): 0.00191664
>
> total time to execute a 5000 way switch, 10000 iterations (ms): 19.5871
> approximate time per 5000 way switch (ms): 0.00195871
>
> A non-adjacent 50,000 case switch statement would not compile.
> "An expression is too long or complex to compile near 'ConsoleApplication1.Program.Main(string[])'
What's funny here, is that the binary tree search appears a little (probably not statistically) quicker than the CIL switch instruction.
Brian, you've used the word "**constant**", which has a very definite meaning from a computational complexity theory perspective. While the simplistic adjacent integer example may produce CIL that is considered O(1) (constant), a sparse example is O(log n) (logarithmic), clustered examples lie somewhere in between, and small examples are O(n) (linear).
This doesn't even address the String situation, in which a static `Generic.Dictionary<string,int32>` may be created, and will suffer definite overhead on first use. Performance here will be dependent on the performance of `Generic.Dictionary`.
If you check the [C# Language Specification](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf) (not the CIL spec)
you'll find "15.7.2 The switch statement" makes no mention of "constant time" or that the underlying implementation even uses the CIL switch instruction (be very careful of assuming such things).
At the end of the day, a C# switch against an integer expression on a modern system is a sub-microsecond operation, and not normally worth worrying about.
---
Of course these times will depend on machines and conditions. I wouldn’t pay attention to these timing tests, the microsecond durations we’re talking about are dwarfed by any “real” code being run (and you must include some “real code” otherwise the compiler will optimise the branch away), or jitter in the system. My answers are based on using [IL DASM](http://msdn.microsoft.com/en-us/library/f7dy01k1(VS.80).aspx) to examine the CIL created by the C# compiler. Of course, this isn’t final, as the actual instructions the CPU runs are then created by the JIT.
I have checked the final CPU instructions actually executed on my x86 machine, and can confirm a simple adjacent set switch doing something like:
```
jmp ds:300025F0[eax*4]
```
Where a binary tree search is full of:
```
cmp ebx, 79Eh
jg 3000352B
cmp ebx, 654h
jg 300032BB
…
cmp ebx, 0F82h
jz 30005EEE
```
|
C# switch statement limitations - why?
|
[
"",
"c#",
"switch-statement",
""
] |
I was just looking through some information about Google's [protocol buffers](http://code.google.com/apis/protocolbuffers/) data interchange format. Has anyone played around with the code or even created a project around it?
I'm currently using XML in a Python project for structured content created by hand in a text editor, and I was wondering what the general opinion was on Protocol Buffers as a user-facing input format. The speed and brevity benefits definitely seem to be there, but there are so many factors when it comes to actually generating and processing the data.
|
If you are looking for user facing interaction, stick with xml. It has more support, understanding, and general acceptance currently. If it's internal, I would say that protocol buffers are a great idea.
Maybe in a few years as more tools come out to support protocol buffers, then start looking towards that for a public facing api. Until then... [JSON](http://en.wikipedia.org/wiki/JSON)?
|
Protocol buffers are intended to optimize communications between machines. They are really not intended for human interaction. Also, the format is binary, so it could not replace XML in that use case.
I would also recommend [JSON](http://en.wikipedia.org/wiki/JSON) as being the most compact text-based format.
|
Any experiences with Protocol Buffers?
|
[
"",
"python",
"xml",
"database",
"protocol-buffers",
""
] |
I am trying to grab the capital letters of a couple of words and wrap them in span tags. I am using [preg\_replace](http://php.net/manual/en/function.preg-replace.php) for extract and wrapping purposes, but it's not outputting anything.
```
preg_replace("/[A-Z]/", "<span class=\"initial\">$1</span>", $str)
```
|
You need to put the pattern in parentheses `/([A-Z])/`, like this:
```
preg_replace("/([A-Z])/", "<span class=\"initial\">$1</span>", $str)
```
|
`\0` will also match the entire matched expression without doing an explicit capture using parenthesis.
```
preg_replace("/[A-Z]/", "<span class=\"initial\">\\0</span>", $str)
```
As always, you can go to [php.net/preg\_replace](http://php.net/preg_replace) or php.net/<whatever search term> to search the documentation quickly. Quoth the documentation:
> \0 or $0 refers to the text matched by the whole pattern.
|
How can I get at the matches when using preg_replace in PHP?
|
[
"",
"php",
"regex",
"html-parsing",
"preg-replace",
""
] |
I am getting back into a bit more .NET after a few-years of not using it full-time and am wondering what the good unit testing packages are these days.
I'm familiar with NUnit (a few years ago) and have played briefly around with [IronRuby](https://en.wikipedia.org/wiki/IronRuby), with the goal of getting something like [RSpec](https://en.wikipedia.org/wiki/RSpec) going, but I don't know much beyond that.
I realize I could google for this and call it a day, but I believe I'm likely to get a better and more informed response from asking a question here :-)
Suggestions?
|
There are so many it's crazy. Crazy good, I guess.
* For the conservative types (me), [**NUnit**](http://www.nunit.org/) is still available and still more than capable.
* For the Microsoft-types, [**MSTest**](http://msdn.microsoft.com/en-us/vstudio/default.aspx) is adequate, but it is slow and clunky compared to NUnit. It also lacks code coverage without paying the big bucks for the pricey versions of Visual Studio.
* There's also [**MbUnit**](http://www.mbunit.com/About.aspx). It's like NUnit, but it has nifty features like RowTest (run the same test with different parameters) and Rollback (put the database back like you found it after a test).
* And finally, [**xUnit.net**](http://www.codeplex.com/xunit) is the trendy option with some attitude.
* Oh, and [**TestDriven.NET**](http://testdriven.net/) will give you IDE integration for both NUnit and MbUnit.
I'm sure they're all just fine. I'd steer away from MSTest though, unless you just enjoy the convenience of having everything in one IDE out of the box.
[Scott Hanselman](http://www.hanselminutes.com/default.aspx?showID=130) has a podcast on this very topic.
|
Stick to NUnit. Don't go anywhere near MSTest.
NUnit + ReSharper is an absolute joy to work with.
|
.NET unit testing packages
|
[
"",
"c#",
".net",
"unit-testing",
"testing",
""
] |
If I have a variable in C# that needs to be checked to determine if it is equal to one of a set of variables, what is the best way to do this?
I'm not looking for a solution that stores the set in an array. I'm more curious to see if there is a solution that uses boolean logic in some way to get the answer.
I know I could do something like this:
```
int baseCase = 5;
bool testResult = baseCase == 3 || baseCase == 7 || baseCase == 12 || baseCase == 5;
```
I'm curious to see if I could do something more like this:
```
int baseCase = 5;
bool testResult = baseCase == (3 | 7 | 12 | 5);
```
Obviously the above won't work, but I'm interested in seeing if there is something more succinct than my first example, which has to repeat the same variable over and over again for each test value.
**UPDATE:**
I decided to accept CoreyN's answer as it seems like the most simple approach. It's practical, and still simple for a novice to understand, I think.
Unfortunately where I work our system uses the .NET 2.0 framework and there's no chance of upgrading any time soon. Are there any other solutions out there that don't rely on the .NET 3.5 framework, besides the most obvious one I can think of:
```
new List<int>(new int[] { 3, 6, 7, 1 }).Contains(5);
```
|
```
bool b = new int[] { 3,7,12,5 }.Contains(5);
```
|
You can do something similar with .NET 2.0, by taking advantage of the fact that an array of T implements IList<T>, and IList<T> has a Contains method. Therefore the following is equivalent to Corey's .NET 3.5 solution, though obviously less clear:
```
bool b = ((IList<int>)new int[] { 3, 7, 12, 5 }).Contains(5);
```
I often use IList<T> for array declarations, or at least for passing one-dimensional array arguments. It means you can use IList properties such as Count, and switch from an array to a list easily. E.g.
```
private readonly IList<int> someIntegers = new int[] { 1,2,3,4,5 };
```
|
Most succinct way to determine if a variable equals a value from a 'list' of values
|
[
"",
"c#",
"logic",
"boolean-logic",
""
] |
When I am writing code in Python, I often need to remove items from a list or other sequence type based on some criteria. I haven't found a solution that is elegant and efficient, as removing items from a list you are currently iterating through is bad. For example, you can't do this:
```
for name in names:
if name[-5:] == 'Smith':
names.remove(name)
```
I usually end up doing something like this:
```
toremove = []
for name in names:
if name[-5:] == 'Smith':
toremove.append(name)
for name in toremove:
names.remove(name)
del toremove
```
This is innefficient, fairly ugly and possibly buggy (how does it handle multiple 'John Smith' entries?). Does anyone have a more elegant solution, or at least a more efficient one?
How about one that works with dictionaries?
|
Two easy ways to accomplish just the filtering are:
1. Using `filter`:
`names = filter(lambda name: name[-5:] != "Smith", names)`
2. Using list comprehensions:
`names = [name for name in names if name[-5:] != "Smith"]`
Note that both cases keep the values for which the predicate function evaluates to `True`, so you have to reverse the logic (i.e. you say "keep the people who do not have the last name Smith" instead of "remove the people who have the last name Smith").
**Edit** Funny... two people individually posted both of the answers I suggested as I was posting mine.
|
You can also iterate backwards over the list:
```
for name in reversed(names):
if name[-5:] == 'Smith':
names.remove(name)
```
This has the advantage that it does not create a new list (like `filter` or a list comprehension) and uses an iterator instead of a list copy (like `[:]`).
Note that although removing elements while iterating backwards is safe, inserting them is somewhat trickier.
|
Elegant way to remove items from sequence in Python?
|
[
"",
"python",
"optimization",
"set",
"series",
""
] |
Does the Java language have delegate features, similar to how C# has support for delegates?
|
Not really, no.
You may be able to achieve the same effect by using reflection to get Method objects you can then invoke, and the other way is to create an interface with a single 'invoke' or 'execute' method, and then instantiate them to call the method your interested in (i.e. using an anonymous inner class).
You might also find this article interesting / useful : [A Java Programmer Looks at C# Delegates (@blueskyprojects.com)](https://web.archive.org/web/20210225165533/https://www.blueskyprojects.com/print-design/)
|
Depending precisely what you mean, you can achieve a similar effect (passing around a method) using the Strategy Pattern.
Instead of a line like this declaring a named method signature:
```
// C#
public delegate void SomeFunction();
```
declare an interface:
```
// Java
public interface ISomeBehaviour {
void SomeFunction();
}
```
For concrete implementations of the method, define a class that implements the behaviour:
```
// Java
public class TypeABehaviour implements ISomeBehaviour {
public void SomeFunction() {
// TypeA behaviour
}
}
public class TypeBBehaviour implements ISomeBehaviour {
public void SomeFunction() {
// TypeB behaviour
}
}
```
Then wherever you would have had a `SomeFunction` delegate in C#, use an `ISomeBehaviour` reference instead:
```
// C#
SomeFunction doSomething = SomeMethod;
doSomething();
doSomething = SomeOtherMethod;
doSomething();
// Java
ISomeBehaviour someBehaviour = new TypeABehaviour();
someBehaviour.SomeFunction();
someBehaviour = new TypeBBehaviour();
someBehaviour.SomeFunction();
```
With anonymous inner classes, you can even avoid declaring separate named classes and almost treat them like real delegate functions.
```
// Java
public void SomeMethod(ISomeBehaviour pSomeBehaviour) {
...
}
...
SomeMethod(new ISomeBehaviour() {
@Override
public void SomeFunction() {
// your implementation
}
});
```
This should probably only be used when the implementation is very specific to the current context and wouldn't benefit from being reused.
And then of course in Java 8, these do become basically lambda expressions:
```
// Java 8
SomeMethod(() -> { /* your implementation */ });
```
|
Java Delegates?
|
[
"",
"java",
"delegates",
""
] |
We currently maintain a suit of MFC applications that are fairly well designed, however the user interface is beginning to look tired and a lot of the code is in need quite a bit of refactoring to tidy up some duplication and/or performance problems. We make use of quite a few custom controls that handle all their own drawing (all written using MFC).
Recently I've been doing more research into Qt and the benefits it provides (cross-platform and supports what you might call a more "professional" looking framework for UI development).
My question is - **what would be the best approach to perhaps moving to the Qt framework**? Does Qt play nice with MFC? Would it be better to start porting some of our custom controls to Qt and gradually integrate more and more into our existing MFC apps? (is this possible?).
Any advice or previous experience is appreciated.
|
In my company, we are currently using Qt and are very happy with it.
I personnally never had to move a MFC-app into using the Qt framework, but here is something which might be of some interest for you :
[Qt/MFC Migration Framework](http://www.qtsoftware.com/products/appdev/add-on-products/catalog/3/Windows/qtwinmigrate/)
[Qt/MFC Migration Framework](http://doc.qt.nokia.com/solutions/4/qtwinmigrate/index.html)
It's part of Qt-Solutions, so this means you'll have to buy a Qt license along with a Qt-Solutions license. (edit: [not any more](http://www.qtsoftware.com/about/news/lgpl-license-option-added-to-qt))
I hope this helps !
|
(This doesn't really answer your specific questions but...)
I haven't personally used Qt, but it's not free for commercial Windows development.
Have you looked at [wxWindows](http://wxwindows.org/) which is free? Nice article [here](http://www.linuxjournal.com/article/6778). Just as an aside, if you wanted a single code base for all platforms, then you may have to migrate away from MFC - I am pretty sure (someone will correct if wrong) that MFC only targets Windows.
One other option would be to look at the [Feature Pack update](http://msdn.microsoft.com/en-us/library/bb983962.aspx) to MFC in SP1 of VS2008 - it includes access to new controls, including the Office style ribbon controls.
|
Integrating Qt into legacy MFC applications
|
[
"",
"c++",
"qt",
"mfc",
""
] |
Is there any efficiency difference in an explicit vs implicit inner join?
For example:
```
SELECT * FROM
table a INNER JOIN table b
ON a.id = b.id;
```
vs.
```
SELECT a.*, b.*
FROM table a, table b
WHERE a.id = b.id;
```
|
Performance-wise, they are exactly the same (at least in SQL Server).
PS: Be aware that the "implicit `OUTER JOIN`" syntax--using `*=` or `=*` in a `WHERE` after using comma--is deprecated since SQL Server 2005. (The "implicit (`CROSS`) `JOIN`" syntax using comma as used in the question is still supported.)
[Deprecation of "Old Style" JOIN Syntax: Only A Partial Thing](https://learn.microsoft.com/en-us/archive/blogs/wardpond/deprecation-of-old-style-join-syntax-only-a-partial-thing)
|
Personally I prefer the join syntax as its makes it clearer that the tables are joined and how they are joined. Try compare larger SQL queries where you selecting from 8 different tables and you have lots of filtering in the where. By using join syntax you separate out the parts where the tables are joined, to the part where you are filtering the rows.
|
Explicit vs implicit SQL joins
|
[
"",
"sql",
"join",
""
] |
I am trying to set a flag to show or hide a page element, but it always displays even when the expression is false.
```
$canMerge = ($condition1 && $condition2) ? 'true' : 'false';
...
<?php if ($canMerge) { ?>Stuff<?php } ?>
```
What's up?
|
This is broken because 'false' as a string will evaluate to true as a boolean.
However, this is an unneeded ternary expression, because the resulting values are simple true and false. This would be equivalent:
```
$canMerge = ($condition1 && $condition2);
```
|
The value of 'false' is true. You need to remove the quotes:
```
$canMerge = ($condition1 && $condition2) ? true : false;
```
|
Why is my ternary expression not working?
|
[
"",
"php",
"ternary-operator",
""
] |
Can you cast a `List<int>` to `List<string>` somehow?
I know I could loop through and .ToString() the thing, but a cast would be awesome.
I'm in C# 2.0 (so no [LINQ](http://en.wikipedia.org/wiki/Language_Integrated_Query)).
|
.NET 2.0 has the `ConvertAll` method where you can pass in a converter function:
```
List<int> l1 = new List<int>(new int[] { 1, 2, 3 } );
List<string> l2 = l1.ConvertAll<string>(delegate(int i) { return i.ToString(); });
```
|
Updated for 2010
```
List<int> l1 = new List<int>(new int[] { 1,2,3 } );
List<string> l2 = l1.ConvertAll<string>(x => x.ToString());
```
|
Cast List<int> to List<string> in .NET 2.0
|
[
"",
"c#",
"generics",
"casting",
""
] |
I have a class property exposing an internal IList<> through
```
System.Collections.ObjectModel.ReadOnlyCollection<>
```
How can I pass a part of this `ReadOnlyCollection<>` without copying elements into a new array (I need a live view, and the target device is short on memory)? I'm targetting Compact Framework 2.0.
|
Try a method that returns an enumeration using yield:
```
IEnumerable<T> FilterCollection<T>( ReadOnlyCollection<T> input ) {
foreach ( T item in input )
if ( /* criterion is met */ )
yield return item;
}
```
|
These foreach samples are fine, though you can make them much more terse if you're using .NET 3.5 and LINQ:
```
return FullList.Where(i => IsItemInPartialList(i)).ToList();
```
|
How can I expose only a fragment of IList<>?
|
[
"",
"c#",
"windows-mobile",
"compact-framework",
".net-2.0",
""
] |
I have a form in C# that has a button that, when clicked, I want the background image to cycle through a set of images (which I have as resources to the project). The images are named '\_1', '\_2', etc. and each time I click the button I want its background image to increment to the next one and go back to "\_1" when it gets to the highest. Is there a way to do this?
I tried getting `button1.BackgroundImage.ToString()` but that yields `System.Drawing.Bitmap` instead of `Resources._1` like I was thinking it would (in which case I could just get the last character and switch on that to change the background to the appropriate new image).
Thanks for your help.
|
Why don't you just put the images in an array?
|
You could subclass Button and override the BackgroundImage property so you can better keep track of the current resource that represents the image. You might also override the onclick method to internally handle cycling to the next image, though that might be a little weird if the resources are handled outside of your derived button class.
|
Cycle Button Background Images in C#
|
[
"",
"c#",
".net",
"winforms",
""
] |
I'm working on a C#/ASP.NET project that has all the javascript files in a /Javascript folder. If I refer to the JS file using this syntax: src="/Javascript/jsfile.js" then the file is correctly picked up if the project is deployed to the root of the URL.
However, if this "web site" is deployed to a sub-folder of the main url this won't work. So the solution could be to use relative urls - but there's a problem with that as well because the master pages reference many of the javascript files and these master pages can be used by pages in the root and in subfolders many levels deep.
Does anybody have any ideas for resolving this?
|
If you reference the JS-file in a section that is "runat=server" you could write src="~/Javascript/jsfile.js" and it will always work.
You could also do this in your Page\_Load (In your masterpage):
```
Page.ClientScript.RegisterClientScriptInclude("myJsFile", Page.ResolveClientUrl("~/Javascript/jsfile.js"))
```
|
Try something like this in the Master Page:
```
<script type="text/javascript" src="<%= Response.ApplyAppPathModifier("~/javascript/globaljs.aspx") %>"></script>
```
For whatever reason, I've found the browsers to be quite finicky about the final tag, so just ending the tag with /> doesn't seem to work.
|
How do I reference a javascript file?
|
[
"",
"asp.net",
"javascript",
""
] |
I'm currently building a Java app that could end up being run on many different platforms, but primarily variants of Solaris, Linux and Windows.
Has anyone been able to successfully extract information such as the current disk space used, CPU utilisation and memory used in the underlying OS? What about just what the Java app itself is consuming?
Preferrably I'd like to get this information without using JNI.
|
You can get some limited memory information from the Runtime class. It really isn't exactly what you are looking for, but I thought I would provide it for the sake of completeness. Here is a small example. Edit: You can also get disk usage information from the java.io.File class. The disk space usage stuff requires Java 1.6 or higher.
```
public class Main {
public static void main(String[] args) {
/* Total number of processors or cores available to the JVM */
System.out.println("Available processors (cores): " +
Runtime.getRuntime().availableProcessors());
/* Total amount of free memory available to the JVM */
System.out.println("Free memory (bytes): " +
Runtime.getRuntime().freeMemory());
/* This will return Long.MAX_VALUE if there is no preset limit */
long maxMemory = Runtime.getRuntime().maxMemory();
/* Maximum amount of memory the JVM will attempt to use */
System.out.println("Maximum memory (bytes): " +
(maxMemory == Long.MAX_VALUE ? "no limit" : maxMemory));
/* Total memory currently available to the JVM */
System.out.println("Total memory available to JVM (bytes): " +
Runtime.getRuntime().totalMemory());
/* Get a list of all filesystem roots on this system */
File[] roots = File.listRoots();
/* For each filesystem root, print some info */
for (File root : roots) {
System.out.println("File system root: " + root.getAbsolutePath());
System.out.println("Total space (bytes): " + root.getTotalSpace());
System.out.println("Free space (bytes): " + root.getFreeSpace());
System.out.println("Usable space (bytes): " + root.getUsableSpace());
}
}
}
```
|
The [java.lang.management](http://java.sun.com/javase/6/docs/api/java/lang/management/package-summary.html) package does give you a whole lot more info than Runtime - for example it will give you heap memory (`ManagementFactory.getMemoryMXBean().getHeapMemoryUsage()`) separate from non-heap memory (`ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage()`).
You can also get process CPU usage (without writing your own JNI code), but you need to cast the `java.lang.management.OperatingSystemMXBean` to a `com.sun.management.OperatingSystemMXBean`. This works on Windows and Linux, I haven't tested it elsewhere.
For example ... call the get getCpuUsage() method more frequently to get more accurate readings.
```
public class PerformanceMonitor {
private int availableProcessors = getOperatingSystemMXBean().getAvailableProcessors();
private long lastSystemTime = 0;
private long lastProcessCpuTime = 0;
public synchronized double getCpuUsage()
{
if ( lastSystemTime == 0 )
{
baselineCounters();
return;
}
long systemTime = System.nanoTime();
long processCpuTime = 0;
if ( getOperatingSystemMXBean() instanceof OperatingSystemMXBean )
{
processCpuTime = ( (OperatingSystemMXBean) getOperatingSystemMXBean() ).getProcessCpuTime();
}
double cpuUsage = (double) ( processCpuTime - lastProcessCpuTime ) / ( systemTime - lastSystemTime );
lastSystemTime = systemTime;
lastProcessCpuTime = processCpuTime;
return cpuUsage / availableProcessors;
}
private void baselineCounters()
{
lastSystemTime = System.nanoTime();
if ( getOperatingSystemMXBean() instanceof OperatingSystemMXBean )
{
lastProcessCpuTime = ( (OperatingSystemMXBean) getOperatingSystemMXBean() ).getProcessCpuTime();
}
}
}
```
|
Get OS-level system information
|
[
"",
"java",
"memory",
"resources",
"system",
""
] |
I've got a Windows DLL that I wrote, written in C/C++ (all exported functions are 'C'). The DLL works fine for me in VC++. I've given the DLL to another company who do all their development in VB. They seem to be having a problem linking to the functions. I haven't used VB in ten years and I don't even have it installed. What could be the problem?
I've declared all my public functions as follows:
```
#define MYDCC_API __declspec(dllexport)
MYDCCL_API unsigned long MYDCC_GetVer( void);
.
.
.
```
Any ideas?
---
Finally got back to this today and have it working. The answers put me on the right track but I found this most helpful:
<http://www.codeproject.com/KB/DLL/XDllPt2.aspx>
Also, I had a few problems passing strings to the DLL functions, I found this helpful:
<http://www.flipcode.com/archives/Interfacing_Visual_Basic_And_C.shtml>
---
|
By using `__declspec` for export, the function name will get exported *mangled*, i.e. contain type information to help the C++ compiler resolve overloads.
VB6 cannot handle mangled names. As a workaround, you have to de-mangle the names. The easiest solution is to link the DLL file using an [export definition](http://msdn.microsoft.com/en-us/library/d91k01sh%28VS.80%29.aspx) file in VC++. The export definition file is very simple and just contains the name of the DLL and a list of exported functions:
```
LIBRARY mylibname
EXPORTS
myfirstfunction
secondfunction
```
Additionally, you have to specify the `stdcall` calling convention because that's the only calling convention VB6 can handle. There's a project using assembly injection to handle C calls but I guess you don't want to use this difficult and error-prone method.
|
Try adding \_\_stdcall at the end
```
#define MYDCC_API __declspec(dllexport) __stdcall
```
We have some C++ dlls that interact with our old VB6 apps and they all have that at the end.
|
Calling DLL functions from VB6
|
[
"",
"c++",
"c",
"vb6",
""
] |
With the increased power of JavaScript frameworks like YUI, JQuery, and Prototype, and debugging tools like Firebug, doing an application entirely in browser-side JavaScript looks like a great way to make simple applications like puzzle games and specialized calculators.
Is there any downside to this other than exposing your source code? How should you handle data storage for this kind of program?
Edit: yes, Gears and cookies can be used for local storage, but you can't easily get access to files and other objects the user already has around. You also can't save data to a file for a user without having them invoke some browser feature like printing to PDF or saving page as a file.
|
I've written several application in JS including a spreadsheet.
Upside:
* great language
* short code-run-review cycle
* DOM manipulation is great for UI design
* clients on every computer (and phone)
Downside:
* differences between browsers (especially IE)
* code base scalability (with no intrinsic support for namespaces and classes)
* no good debuggers (especially, again, for IE)
* performance (even though great progress has been made with FireFox and Safari)
* You need to write some server code as well.
Bottom line: Go for it. I did.
|
Another option for developing simple desktop like applications or games in JavaScript is [Adobe AIR](http://www.adobe.com/devnet/air/). You can build your app code in either HTML + JavaScript or using Flash/Flex or a combination of both. It has the advantage of being cross-platform (actually cross-platform, Linux, OS X, and Windows. Not just Windows and OS X).
Heck, it may be the only time in your career as a developer that you can write a web page and ONLY target ONE browser.
|
Building Standalone Applications in JavaScript
|
[
"",
"javascript",
"deployment",
"web-applications",
"browser",
""
] |
Is there a standard convention (like phpdoc or python's docstring) for commenting C# code so that class documentation can be automatically generated from the source code?
|
You can use XML style comments, and use tools to pull those comments out into API documentation.
Here is an example of the comment style:
```
/// <summary>
/// Authenticates a user based on a username and password.
/// </summary>
/// <param name="username">The username.</param>
/// <param name="password">The password.</param>
/// <returns>
/// True, if authentication is successful, otherwise False.
/// </returns>
/// <remarks>
/// For use with local systems
/// </remarks>
public override bool Authenticate(string username, string password)
```
Some items to facilitate this are:
[GhostDoc](http://www.roland-weigelt.de/ghostdoc/), which give a single shortcut key to automatically generate comments for a class or method.
[Sandcastle](http://blogs.msdn.com/sandcastle/about.aspx), which generates MSDN style documentation from XML comments.
|
```
/// <summary>
///
/// </summary>
/// <param name="strFilePath"></param>
```
<http://msdn.microsoft.com/en-us/magazine/cc302121.aspx>
|
Is there a standard (like phpdoc or python's docstring) for commenting C# code?
|
[
"",
"c#",
"comments",
""
] |
Does anyone know how to get IntelliSense to work reliably when working in C/C++ projects? It seems to work for about 1 in 10 files. Visual Studio 2005 seems to be a lot better than 2008.
Edit: Whilst not necessarily a solution, the work-around provided here:
[How to get IntelliSense to reliably work in Visual Studio 2008](https://stackoverflow.com/questions/39474/how-to-get-intellisense-to-reliably-work-in-visual-studio-2008#39590)
Is probably the best bet if I want a decent IntelliSense system.
|
I've also realized than Intellisense is sometime 'lost', on some big project. Why? No idea.
This is why we have bought [Visual Assist](http://www.wholetomato.com/) (from [Tomato software](http://www.wholetomato.com/)) and disabled Intellisense by deleting the dll feacp.dll in the Visual studio subdirectory (C:\Program Files\Microsoft Visual Studio 8\VC\vcpackages)
This is not a solution, just a workaround.
|
Native C++ intellisense does not work reliably in any version of Visual Studio. I find there are two common problems:
1) Header file paths are not set-up correctly. When you find a type where intellisense is not working, use the IDE to click through each header file to find the one containing the type. (Right click on #include and select Open Document...). If this fails before you get to the file which declares the type then this is your problem. Make sure header file search paths are set-up correctly.
And,
2) The intellisense database is corrupt. This happens ALL The time. You need to close the solution, delete the .ncb file, and then reopen the solution. I posted the macro I use for this in answer to another question [here](https://stackoverflow.com/questions/15056/do-you-have-any-recommended-macros-for-microsoft-visual-studio#32884).
---
The preprocessor can also confuse intellisense - so make sure any #defines during build are also available to intellisense. Other than that, I don't know what else can break it. I've not seen any particular issues with forward declarations.
|
How to get IntelliSense to reliably work in Visual Studio 2008
|
[
"",
"c++",
"c",
"visual-studio-2008",
"intellisense",
""
] |
In the [How Can I Expose Only a Fragment of IList<>](https://stackoverflow.com/questions/39447/how-can-i-expose-only-a-fragment-of-ilist) question one of the answers had the following code snippet:
```
IEnumerable<object> FilteredList()
{
foreach(object item in FullList)
{
if(IsItemInPartialList(item))
yield return item;
}
}
```
What does the yield keyword do there? I've seen it referenced in a couple places, and one other question, but I haven't quite figured out what it actually does. I'm used to thinking of yield in the sense of one thread yielding to another, but that doesn't seem relevant here.
|
The `yield` contextual keyword actually does quite a lot here.
The function returns an object that implements the `IEnumerable<object>` interface. If a calling function starts `foreach`ing over this object, the function is called again until it "yields". This is syntactic sugar introduced in **C# 2.0**. In earlier versions you had to create your own `IEnumerable` and `IEnumerator` objects to do stuff like this.
The easiest way understand code like this is to type-in an example, set some breakpoints and see what happens. Try stepping through this example:
```
public void Consumer()
{
foreach(int i in Integers())
{
Console.WriteLine(i.ToString());
}
}
public IEnumerable<int> Integers()
{
yield return 1;
yield return 2;
yield return 4;
yield return 8;
yield return 16;
yield return 16777216;
}
```
When you step through the example, you'll find the first call to `Integers()` returns `1`. The second call returns `2` and the line `yield return 1` is not executed again.
Here is a real-life example:
```
public IEnumerable<T> Read<T>(string sql, Func<IDataReader, T> make, params object[] parms)
{
using (var connection = CreateConnection())
{
using (var command = CreateCommand(CommandType.Text, sql, connection, parms))
{
command.CommandTimeout = dataBaseSettings.ReadCommandTimeout;
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
yield return make(reader);
}
}
}
}
}
```
|
Iteration. It creates a state machine "under the covers" that remembers where you were on each additional cycle of the function and picks up from there.
|
What is the yield keyword used for in C#?
|
[
"",
"c#",
"yield",
""
] |
I can do an `eval("something()");` to execute the code dynamically in JavaScript. Is there a way for me to do the same thing in C#?
An example of what I am trying to do is: I have an integer variable (say `i`) and I have multiple properties by the names: "Property1", "Property2", "Property3", etc.
Now, I want to perform some operations on the " Property*i* " property depending on the value of `i`.
This is really simple with Javascript. Is there any way to do this with C#?
|
**DISCLAIMER:** This answer was written back in 2008. The landscape has changed drastically since then.
Look at the other answers on this page, especially the one detailing `Microsoft.CodeAnalysis.CSharp.Scripting`.
Rest of answer will be left as it was originally posted but is no longer accurate.
---
Unfortunately, C# isn't a dynamic language like that.
What you can do, however, is to create a C# source code file, full with class and everything, and run it through the CodeDom provider for C# and compile it into an assembly, and then execute it.
This forum post on MSDN contains an answer with some example code down the page somewhat:
[create a anonymous method from a string?](https://social.msdn.microsoft.com/Forums/vstudio/en-US/6a783cc4-bb54-4fec-b504-f9b1ed786b54/create-a-anonymous-method-from-a-string)
I would hardly say this is a very good solution, but it is possible anyway.
What kind of code are you going to expect in that string? If it is a minor subset of valid code, for instance just math expressions, it might be that other alternatives exists.
---
**Edit**: Well, that teaches me to read the questions thoroughly first. Yes, reflection would be able to give you some help here.
If you split the string by the ; first, to get individual properties, you can use the following code to get a PropertyInfo object for a particular property for a class, and then use that object to manipulate a particular object.
```
String propName = "Text";
PropertyInfo pi = someObject.GetType().GetProperty(propName);
pi.SetValue(someObject, "New Value", new Object[0]);
```
Link: [PropertyInfo.SetValue Method](https://learn.microsoft.com/en-us/dotnet/api/system.reflection.propertyinfo.setvalue)
|
Using the Roslyn scripting API. More samples [in the Rolsyn wiki](https://github.com/dotnet/roslyn/blob/main/docs/wiki/Scripting-API-Samples.md).
```
// add NuGet package 'Microsoft.CodeAnalysis.Scripting'
using Microsoft.CodeAnalysis.CSharp.Scripting;
await CSharpScript.EvaluateAsync("System.Math.Pow(2, 4)") // returns 16
```
You can also run any piece of code:
```
var script = await CSharpScript.RunAsync(@"
class MyClass
{
public void Print() => System.Console.WriteLine(1);
}")
```
And reference the code that was generated in previous runs:
```
await script.ContinueWithAsync("new MyClass().Print();");
```
|
How can I evaluate C# code dynamically?
|
[
"",
"c#",
"reflection",
"properties",
"c#-2.0",
""
] |
Example: I have two shared objects (same should apply to .dlls). The first shared object is from a third-party library, we'll call it libA.so. I have wrapped some of this with JNI and created my own library, libB.so. Now libB depends on libA.
When webstarting, both libraries are places in some webstart working area. My java code attempts to load libB. At this point the system loader will attempt to load libA which is not in the system library path (java.library.path won't help this). The end result is that libB has an unsatisfied link and cannot be used.
I have tried loading libA before libB, but that still does not work. Seems the OS wants to do that loading for me. Is there any way I can make this work other than statically compiling?
|
Static compilation proved to be the only way to webstart multiple dependent native libraries.
|
I'm not sure if this would be handled exactly the same way for webstart, but we ran into this situation in a desktop application when dealing with a set of native libraries (dlls in our case).
Loading libA before libB should work, unless one of those libraries has a dependency that is unaccounted for and not in the path. My understanding is that once it gets to a system loadLibrary call (i.e. Java has found the library in its java.library.path and is now telling the OS to load it) - it is completely dependent on the operating system to find any dependent libraries, because at that point it is the operating system that is loading the library for the process, and the OS only knows how to look in the system path. That seems hard to set in the case of a Webstart app, but there is a way around this that does not involve static compiling. You may be able to shuffle where your libraries are - I am unsure
If you use a custom classloader, you can override loadLibrary and findLibrary so that it can locate your libraries from within a jar in your classpath, and if you also make it aware of your native library dependencies (i.e. libB depends on libA depends on libX, then when loading libB you can catch yourself and ensure you load libA first, and in checking that notice and load libX first. Then the OS doesn't try to find a library that isn't in your path. It's klunky and a bit painful, but ensuring Java finds them and loads them all in the correct order can work.
|
How can I Java webstart multiple, dependent, native libraries?
|
[
"",
"java",
"java-native-interface",
"java-web-start",
""
] |
I have to develop an application which parses a log file and sends specific data to a server. It has to run on both Linux and Windows.
The problem appears when I want to test the log rolling system (which appends .1 to the name of the creates a new one with the same name). On Windows (haven't tested yet on Linux) I can't rename a file that I have opened with std::ifstream() (exclusive access?) even if I open it in "input mode" (ios::in).
Is there a cross-platform way to open file in a non-exclusive way?
|
> Is there a way to open file in a non-exclusive way,
Yes, using Win32, passing the various FILE\_SHARE\_Xxxx flags to CreateFile.
> is it cross platform?
No, it requires platform-specific code.
Due to annoying backwards compatibility concerns (DOS applications, being single-tasking, assume that nothing can delete a file out from under them, i.e. that they can fclose() and then fopen() without anything going amiss; Win16 preserved this assumption to make porting DOS applications easier, Win32 preserved this assumption to make porting Win16 applications easier, and it's awful), Windows defaults to opening files exclusively.
The underlying OS infrastructure supports deleting/renaming open files (although I believe it does have the restriction that memory-mapped files cannot be deleted, which I think isn't a restriction found on \*nix), but the default opening semantics do not.
C++ has no notion of any of this; the C++ operating environment is much the same as the DOS operating environment--no other applications running concurrently, so no need to control file sharing.
|
It's not the reading operation that's requiring the exclusive mode, it's the rename, because this is essentially the same as moving the file to a new location.
I'm not sure but I don't think this can be done. Try copying the file instead, and later delete/replace the old file when it is no longer read.
|
C++ : Opening a file in non exclusive mode
|
[
"",
"c++",
"windows",
"linux",
"filesystems",
""
] |
This most be the second most simple rollover effect, still I don't find any simple solution.
**Wanted:** I have a list of items and a corresponding list of slides (DIVs). After loading, the first list item should be selected (bold) and the first slide should be visible. When the user hovers over another list item, that list item should be selected instead and the corresponding slide be shown.
The following code works, but *is awful*. How can I get this behaviour in an elegant way? jquery has dozens of animated and complicated rollover effects, but I didn't come up with a clean way for this effect.
```
<script type="text/javascript">
function switchTo(id) {
document.getElementById('slide1').style.display=(id==1)?'block':'none';
document.getElementById('slide2').style.display=(id==2)?'block':'none';
document.getElementById('slide3').style.display=(id==3)?'block':'none';
document.getElementById('slide4').style.display=(id==4)?'block':'none';
document.getElementById('switch1').style.fontWeight=(id==1)?'bold':'normal';
document.getElementById('switch2').style.fontWeight=(id==2)?'bold':'normal';
document.getElementById('switch3').style.fontWeight=(id==3)?'bold':'normal';
document.getElementById('switch4').style.fontWeight=(id==4)?'bold':'normal';
}
</script>
<ul id="switches">
<li id="switch1" onmouseover="switchTo(1);" style="font-weight:bold;">First slide</li>
<li id="switch2" onmouseover="switchTo(2);">Second slide</li>
<li id="switch3" onmouseover="switchTo(3);">Third slide</li>
<li id="switch4" onmouseover="switchTo(4);">Fourth slide</li>
</ul>
<div id="slides">
<div id="slide1">Well well.</div>
<div id="slide2" style="display:none;">Oh no!</div>
<div id="slide3" style="display:none;">You again?</div>
<div id="slide4" style="display:none;">I'm gone!</div>
</div>
```
|
Rather than displaying all slides when JS is off (which would likely break the page layout) I would place inside the switch LIs real A links to server-side code which returns the page with the "active" class pre-set on the proper switch/slide.
```
$(document).ready(function() {
switches = $('#switches > li');
slides = $('#slides > div');
switches.each(function(idx) {
$(this).data('slide', slides.eq(idx));
}).hover(
function() {
switches.removeClass('active');
slides.removeClass('active');
$(this).addClass('active');
$(this).data('slide').addClass('active');
});
});
```
```
#switches .active {
font-weight: bold;
}
#slides div {
display: none;
}
#slides div.active {
display: block;
}
```
```
<html>
<head>
<title>test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="switch.js"></script>
</head>
<body>
<ul id="switches">
<li class="active">First slide</li>
<li>Second slide</li>
<li>Third slide</li>
<li>Fourth slide</li>
</ul>
<div id="slides">
<div class="active">Well well.</div>
<div>Oh no!</div>
<div>You again?</div>
<div>I'm gone!</div>
</div>
</body>
</html>
```
|
Here's my light-markup jQuery version:
```
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function switchTo(i) {
$('#switches li').css('font-weight','normal').eq(i).css('font-weight','bold');
$('#slides div').css('display','none').eq(i).css('display','block');
}
$(document).ready(function(){
$('#switches li').mouseover(function(event){
switchTo($('#switches li').index(event.target));
});
switchTo(0);
});
</script>
<ul id="switches">
<li>First slide</li>
<li>Second slide</li>
<li>Third slide</li>
<li>Fourth slide</li>
</ul>
<div id="slides">
<div>Well well.</div>
<div>Oh no!</div>
<div>You again?</div>
<div>I'm gone!</div>
</div>
```
This has the advantage of showing all the slides if the user has javascript turned off, uses very little HTML markup and the javascript is pretty readable. The `switchTo` function takes an index number of which `<li>` / `<div>` pair to activate, resets all the relevant elements to their default styles (non-bold for list items, `display:none` for the DIVs) and the sets the desired `list-item` and `div` to `bold` and `display`. As long as the client has javascript enabled, the functionality will be exactly the same as your original example.
|
How do you swap DIVs on mouseover (jQuery)?
|
[
"",
"javascript",
"jquery",
"html",
"css",
""
] |
I've been using PostgreSQL a little bit lately, and one of the things that I think is cool is that you can use languages other than SQL for scripting functions and whatnot. But when is this actually useful?
For example, the documentation says that the main use for PL/Perl is that it's pretty good at text manipulation. But isn't that more of something that should be programmed into the application?
Secondly, is there any valid reason to use an untrusted language? It seems like making it so that any user can execute any operation would be a bad idea on a production system.
PS. Bonus points if someone can make [PL/LOLCODE](http://pgfoundry.org/projects/pllolcode) seem useful.
|
"isn't that [text manipulation] more of something that should be programmed into the application?"
Usually, yes. The generally accepted "[three-tier](http://en.wikipedia.org/wiki/Multitier_architecture)" application design for databases says that your logic should be in the middle tier, between the client and the database. However, sometimes you need some logic in a trigger or need to index on a function, requiring that some code be placed into the database. In that case all the usual "which language should I use?" questions come up.
If you only need a little logic, the most-portable language should probably be used (pl/pgSQL). If you need to do some serious programming though, you might be better off using a more expressive language (maybe pl/ruby). This will always be a judgment call.
"is there any valid reason to use an untrusted language?"
As above, yes. Again, putting direct file access (for example) into your middle tier is best when possible, but if you need to fire things off based on triggers (that might need access to data not available directly to your middle tier), then you need untrusted languages. It's not ideal, and should generally be avoided. And you definitely need to guard access to it.
|
@Mike: this kind of thinking makes me nervous. I've heard to many times "this should be infinitely portable", but when the question is asked: do you actually foresee that there will be any porting? the answer is: no.
Sticking to the lowest common denominator can really hurt performance, as can the introduction of abstraction layers (ORM's, PHP PDO, etc). My opinion is:
* Evaluate realistically if there is a need to support multiple RDBMS's. For example if you are writing an open source web application, chances are that you need to support MySQL and PostgreSQL at least (if not MSSQL and Oracle)
* After the evaluation, make the most of the platform you decided upon
And BTW: you are mixing relational with non-relation databases (CouchDB is *not* a RDBMS comparable with Oracle for example), further exemplifying the point that the perceived need for portability is many times greatly overestimated.
|
Languages other than SQL in postgres
|
[
"",
"sql",
"database",
"postgresql",
"trusted-vs-untrusted",
""
] |
I'm looking for a simple way to encrypt my soap communication in my C# Web-Service.
I was looking into [WSE 3.0](http://www.google.com/url?sa=t&ct=res&cd=1&url=http%3A%2F%2Fwww.microsoft.com%2Fdownloads%2Fdetails.aspx%3Ffamilyid%3D018a09fd-3a74-43c5-8ec1-8d789091255d&ei=x1isSPTUO4bS0QXsjIzWAw&usg=AFQjCNHn7aOkIXoysM1woIgRBe20Ptu_6g&sig2=RTyvtw71nWYyoDGIEh0TlQ) but it seems Microsoft dropped support for it, and therefore it's not straightforward to use.
It seems WCF could've been an option but I prefer not to upgrade from .NET 2.0 .
Any **simple**, straightforward encryption method?
|
I think this can help; last year we used this to compress the webservices and it performed very well, I believe it could be enhanced with encryption classes;
[Creating Custom SOAP Extensions - Compression Extension](http://www.mastercsharp.com/article.aspx?ArticleID=86&&TopicID=7)
|
Anything you do to provide "encryption" that isn't using SSL/TLS is likely to be vulnerable. Now you have to ask yourself, is it worth burning dev hours you could be spending on features on a rubber-chicken security measure? Maybe it is.
.NET APIs like DPAPI and the Win32 crypt32 API make it easy to encrypt blobs of data with static keys. But how will your clients receive the keys? Any installed SOAP client will have to either have the key burned into its configuration, or receive it over the insecure Internet.
This is the problem SSL/TLS solves for you; the dance you do with TLS certificates is what solves the problem of communicating public keys over untrusted channels.
|
Encryption in C# Web-Services
|
[
"",
"c#",
"web-services",
"security",
"encryption",
""
] |
For those of us who use standard shared hosting packages, such as GoDaddy or Network Solutions, how do you handle datetime conversions when your hosting server (PHP) and MySQL server are in different time zones?
Also, does anybody have some best practice advice for determining what time zone a visitor to your site is in and manipulating a datetime variable appropriately?
|
As of PHP 5.1.0 you can use [*date\_default\_timezone\_set()*](http://www.php.net/manual/en/function.date-default-timezone-set.php) function to set the default timezone used by all date/time functions in a script.
For MySql (quoted from [MySQL Server Time Zone Support](http://dev.mysql.com/doc/refman/4.1/en/time-zone-support.html) page)
> Before MySQL 4.1.3, the server operates only in the system time zone set at startup. Beginning with MySQL 4.1.3, the server maintains several time zone settings, some of which can be modified at runtime.
Of interest to you is per-connection setting of the time zones, which you would use at the beginning of your scripts
```
SET timezone = 'Europe/London';
```
As for detecting the client timezone setting, you could use a bit of JavaScript to get and save that information to a cookie, and use it on subsequent page reads, to calculate the proper timezone.
```
//Returns the offset (time difference) between Greenwich Mean Time (GMT)
//and local time of Date object, in minutes.
var offset = new Date().getTimezoneOffset();
document.cookie = 'timezoneOffset=' + escape(offset);
```
Or you could offer users the chioce to set their time zones themselves.
|
Store everything as UTC. You can do conversions at the client level, or on the server side using client settings.
[php - date](http://us.php.net/date)
[mysql - utc-timestamp](http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_utc-timestamp)
|
Dealing with PHP server and MySQL server in different time zones
|
[
"",
"php",
"mysql",
"datetime",
"date",
"timezone",
""
] |
I have a fairly small MySQL database (a Textpattern install) on a server that I do not have SSH access to (I have FTP access only). I need to regularly download the live database to my local dev server on demand; i.e., I would like to either run a script and/or have a cron job running. What are some good ways of doing this?
Some points to note:
* Live server is running Linux, Apache 2.2, PHP 5.2 and MySQL 4.1
* Local server is running the same (so using PHP is an option), but the OS is Windows
* Local server has Ruby on it (so using Ruby is a valid option)
* The live MySQL db *can* accept remote connections from different IPs
* I cannot enable replication on the remote server
***Update:*** I've accepted BlaM's answer; it is beautifully simple. Can't believe I didn't think of that. There was one problem, though: I wanted to automate the process, but the proposed solution prompts the user for a password. Here is a slightly modified version of the mysqldump command that passes in the password:
`mysqldump -u USER --password=MYPASSWORD DATABASE_TO_DUMP -h HOST > backup.sql`
|
Since you can access your database remotely, you can use mysqldump from your windows machine to fetch the remote database. From commandline:
```
cd "into mysql directory"
mysqldump -u USERNAME -p -h YOUR_HOST_IP DATABASE_TO_MIRROR >c:\backup\database.sql
```
The program will ask you for the database password and then generate a file c:\backup\database.sql that you can run on your windows machine to insert the data.
With a small database that should be fairly fast.
|
Here's what I use. This dumps the database from the live server while uploads it to the local server.
`mysqldump -hlive_server_addresss -ulive_server_user -plive_server_password --opt --compress live_server_db | mysql -ulocal_server_user -plocal_server_password local_server_db`
You can run this from a **bat** file. You can ever use a scheduled task.
|
How to download a live MySQL db into a local test db on demand, without SSH?
|
[
"",
"php",
"ruby",
"database",
"mysql",
""
] |
I completely understand the concept of expression trees, but I am having a hard time trying to find situations in which they are useful. Is there a specific instance in which expression trees can be applied? Or is it only useful as a transport mechanism for code? I feel like I am missing something here. Thanks!
|
> Or is it only useful as a transport mechanism for code?
It's useful as an *execution mechanism* for code. Using the [interpreter pattern](http://en.wikipedia.org/wiki/Interpreter_pattern), expression trees can directly be interpreted. This is useful because it's very easy and fast to implement. Such interpreters are ubiquitous and used even in cases that don't seem to “interpret” anything, e.g. for printing nested structures.
|
Some unit test mocking frameworks make use of expression trees in order to set up strongly typed expectations/verifications. Ie:
```
myMock.Verify(m => m.SomeMethod(someObject)); // tells moq to verify that the method
// SomeMethod was called with
// someObject as the argument
```
Here, the expression is never actually executed, but the expression itself holds the interesting information. The alternative without expression trees would be
```
myMock.Verify("SomeMethod", someObject) // we've lost the strong typing
```
|
What are some instances in which expression trees are useful?
|
[
"",
"c#",
"expression",
""
] |
I need to find out how to format numbers as strings. My code is here:
```
return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm
```
Hours and minutes are integers, and seconds is a float. the str() function will convert all of these numbers to the tenths (0.1) place. So instead of my string outputting "5:30:59.07 pm", it would display something like "5.0:30.0:59.1 pm".
Bottom line, what library / function do I need to do this for me?
|
Starting with Python 3.6, formatting in Python can be done using [formatted string literals](https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498) or *f-strings*:
```
hours, minutes, seconds = 6, 56, 33
f'{hours:02}:{minutes:02}:{seconds:02} {"pm" if hours > 12 else "am"}'
```
or the [`str.format`](https://docs.python.org/library/stdtypes.html#str.format) function starting with 2.7:
```
"{:02}:{:02}:{:02} {}".format(hours, minutes, seconds, "pm" if hours > 12 else "am")
```
or the [string formatting `%` operator](https://docs.python.org/library/stdtypes.html#printf-style-string-formatting) for even older versions of Python, but see the note in the docs:
```
"%02d:%02d:%02d" % (hours, minutes, seconds)
```
And for your specific case of formatting time, there’s [`time.strftime`](https://docs.python.org/library/time.html#time.strftime):
```
import time
t = (0, 0, 0, hours, minutes, seconds, 0, 0, 0)
time.strftime('%I:%M:%S %p', t)
```
|
The OP & accepted answer focus on formatting time, but the OP *question* itself discusses formatting numbers to strings in Python. In many cases, the output requires additional data fields be included along with timestamps, all of which include formatting numbers as strings.
Below are a variety of *non time-based* examples of formatting numbers as strings, and different ways to do so, starting with the existing string format operator (`%`) which has been around for as long as Python has been around (meaning this solution is compatible across Python 1.x, 2.x, and 3.x):
```
>>> "Name: %s, age: %d" % ('John', 35)
'Name: John, age: 35'
>>> i = 45
>>> 'dec: %d/oct: %#o/hex: %#X' % (i, i, i)
'dec: 45/oct: 055/hex: 0X2D'
>>> "MM/DD/YY = %02d/%02d/%02d" % (12, 7, 41)
'MM/DD/YY = 12/07/41'
>>> 'Total with tax: $%.2f' % (13.00 * 1.0825)
'Total with tax: $14.07'
>>> d = {'web': 'user', 'page': 42}
>>> 'http://xxx.yyy.zzz/%(web)s/%(page)d.html' % d
'http://xxx.yyy.zzz/user/42.html'
```
Starting in Python 2.6 (meaning it works for 2.x and 3.x), there is an alternative: the `str.format()` method. Here are the equivalent snippets to the above but using `str.format()`:
```
>>> "Name: {0}, age: {1}".format('John', 35)
'Name: John, age: 35'
>>> i = 45
>>> 'dec: {0}/oct: {0:#o}/hex: {0:#X}'.format(i)
'dec: 45/oct: 0o55/hex: 0X2D'
>>> "MM/DD/YY = {0:02d}/{1:02d}/{2:02d}".format(12, 7, 41)
'MM/DD/YY = 12/07/41'
>>> 'Total with tax: ${0:.2f}'.format(13.00 * 1.0825)
'Total with tax: $14.07'
>>> d = {'web': 'user', 'page': 42}
>>> 'http://xxx.yyy.zzz/{web}/{page}.html'.format(**d)
'http://xxx.yyy.zzz/user/42.html'
```
Like Python 2.6+, all Python 3 releases (so far) understand how to do both. I shamelessly ripped this stuff straight out of [my hardcore Python intro book](https://rads.stackoverflow.com/amzn/click/com/0132269937) and the slides for the Intro+Intermediate [Python courses I offer](http://cyberwebconsulting.com) from time-to-time. `:-)`
**Aug 2018 UPDATE**: Of course, now that we have [the f-string feature introduced in 3.6](https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498) (only works in 3.6 and newer), we need the equivalent examples of *that*; yes, another alternative:
```
>>> name, age = 'John', 35
>>> f'Name: {name}, age: {age}'
'Name: John, age: 35'
>>> i = 45
>>> f'dec: {i}/oct: {i:#o}/hex: {i:#X}'
'dec: 45/oct: 0o55/hex: 0X2D'
>>> m, d, y = 12, 7, 41
>>> f"MM/DD/YY = {m:02d}/{d:02d}/{y:02d}"
'MM/DD/YY = 12/07/41'
>>> f'Total with tax: ${13.00 * 1.0825:.2f}'
'Total with tax: $14.07'
>>> d = {'web': 'user', 'page': 42}
>>> f"http://xxx.yyy.zzz/{d['web']}/{d['page']}.html"
'http://xxx.yyy.zzz/user/42.html'
```
|
Format numbers to strings in Python
|
[
"",
"python",
"string-formatting",
""
] |
What are the best practices to consider when catching exceptions and re-throwing them? I want to make sure that the `Exception` object's `InnerException` and stack trace are preserved. Is there a difference between the following code blocks in the way they handle this?
```
try
{
//some code
}
catch (Exception ex)
{
throw ex;
}
```
Vs:
```
try
{
//some code
}
catch
{
throw;
}
```
|
The way to preserve the stack trace is through the use of the `throw;` This is valid as well
```
try {
// something that bombs here
} catch (Exception ex)
{
throw;
}
```
`throw ex;` is basically like throwing an exception from that point, so the stack trace would only go to where you are issuing the `throw ex;` statement.
[Mike](https://stackoverflow.com/questions/22623/net-throwing-exceptions-best-practices#22649) is also correct, assuming the exception allows you to pass an exception (which is recommended).
[Karl Seguin](http://openmymind.net) has a [great write up on exception handling](http://codebetter.com/blogs/karlseguin/archive/2008/05/29/foundations-of-programming-pt-8-back-to-basics-exceptions.aspx) in his [foundations of programming e-book](http://openmymind.net/FoundationsOfProgramming.pdf) as well, which is a great read.
Edit: Working link to [Foundations of Programming](http://openmymind.net/FoundationsOfProgramming.pdf) pdf. Just search the text for "exception".
|
If you throw a new exception with the initial exception you will preserve the initial stack trace too..
```
try{
}
catch(Exception ex){
throw new MoreDescriptiveException("here is what was happening", ex);
}
```
|
Best practices for catching and re-throwing .NET exceptions
|
[
"",
"c#",
".net",
"exception",
"rethrow",
""
] |
Google is not being my friend - it's been a long time since my stats class in college...I need to calculate the start and end points for a trendline on a graph - is there an easy way to do this? (working in C# but whatever language works for you)
|
Given that the trendline is straight, find the slope by choosing any two points and calculating:
(A) slope = (y1-y2)/(x1-x2)
Then you need to find the offset for the line. The line is specified by the equation:
(B) y = offset + slope\*x
So you need to solve for offset. Pick any point on the line, and solve for offset:
(C) offset = y - (slope\*x)
Now you can plug slope and offset into the line equation (B) and have the equation that defines your line. If your line has noise you'll have to decide on an averaging algorithm, or use curve fitting of some sort.
If your line isn't straight then you'll need to look into [Curve fitting](http://www.aip.org/tip/INPHFA/vol-9/iss-2/p24.html), or [Least Squares Fitting](http://mathworld.wolfram.com/LeastSquaresFitting.html) - non trivial, but do-able. You'll see the various types of curve fitting at the bottom of the least squares fitting webpage (exponential, polynomial, etc) if you know what kind of fit you'd like.
Also, if this is a one-off, use Excel.
|
Thanks to all for your help - I was off this issue for a couple of days and just came back to it - was able to cobble this together - not the most elegant code, but it works for my purposes - thought I'd share if anyone else encounters this issue:
```
public class Statistics
{
public Trendline CalculateLinearRegression(int[] values)
{
var yAxisValues = new List<int>();
var xAxisValues = new List<int>();
for (int i = 0; i < values.Length; i++)
{
yAxisValues.Add(values[i]);
xAxisValues.Add(i + 1);
}
return new Trendline(yAxisValues, xAxisValues);
}
}
public class Trendline
{
private readonly IList<int> xAxisValues;
private readonly IList<int> yAxisValues;
private int count;
private int xAxisValuesSum;
private int xxSum;
private int xySum;
private int yAxisValuesSum;
public Trendline(IList<int> yAxisValues, IList<int> xAxisValues)
{
this.yAxisValues = yAxisValues;
this.xAxisValues = xAxisValues;
this.Initialize();
}
public int Slope { get; private set; }
public int Intercept { get; private set; }
public int Start { get; private set; }
public int End { get; private set; }
private void Initialize()
{
this.count = this.yAxisValues.Count;
this.yAxisValuesSum = this.yAxisValues.Sum();
this.xAxisValuesSum = this.xAxisValues.Sum();
this.xxSum = 0;
this.xySum = 0;
for (int i = 0; i < this.count; i++)
{
this.xySum += (this.xAxisValues[i]*this.yAxisValues[i]);
this.xxSum += (this.xAxisValues[i]*this.xAxisValues[i]);
}
this.Slope = this.CalculateSlope();
this.Intercept = this.CalculateIntercept();
this.Start = this.CalculateStart();
this.End = this.CalculateEnd();
}
private int CalculateSlope()
{
try
{
return ((this.count*this.xySum) - (this.xAxisValuesSum*this.yAxisValuesSum))/((this.count*this.xxSum) - (this.xAxisValuesSum*this.xAxisValuesSum));
}
catch (DivideByZeroException)
{
return 0;
}
}
private int CalculateIntercept()
{
return (this.yAxisValuesSum - (this.Slope*this.xAxisValuesSum))/this.count;
}
private int CalculateStart()
{
return (this.Slope*this.xAxisValues.First()) + this.Intercept;
}
private int CalculateEnd()
{
return (this.Slope*this.xAxisValues.Last()) + this.Intercept;
}
}
```
|
How do I calculate a trendline for a graph?
|
[
"",
"c#",
"math",
"graph",
""
] |
I am storing a PNG as an embedded resource in an assembly. From within the same assembly I have some code like this:
```
Bitmap image = new Bitmap(typeof(MyClass), "Resources.file.png");
```
The file, named "file.png" is stored in the "Resources" folder (within Visual Studio), and is marked as an embedded resource.
The code fails with an exception saying:
> Resource MyNamespace.Resources.file.png cannot be found in class MyNamespace.MyClass
I have identical code (in a different assembly, loading a different resource) which works. So I know the technique is sound. My problem is I end up spending a lot of time trying to figure out what the correct path is. If I could simply query (eg. in the debugger) the assembly to find the correct path, that would save me a load of headaches.
|
This will get you a string array of all the resources:
```
System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();
```
|
I find myself forgetting how to do this every time as well so I just wrap the two one-liners that I need in a little class:
```
public class Utility
{
/// <summary>
/// Takes the full name of a resource and loads it in to a stream.
/// </summary>
/// <param name="resourceName">Assuming an embedded resource is a file
/// called info.png and is located in a folder called Resources, it
/// will be compiled in to the assembly with this fully qualified
/// name: Full.Assembly.Name.Resources.info.png. That is the string
/// that you should pass to this method.</param>
/// <returns></returns>
public static Stream GetEmbeddedResourceStream(string resourceName)
{
return Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName);
}
/// <summary>
/// Get the list of all emdedded resources in the assembly.
/// </summary>
/// <returns>An array of fully qualified resource names</returns>
public static string[] GetEmbeddedResourceNames()
{
return Assembly.GetExecutingAssembly().GetManifestResourceNames();
}
}
```
|
How can I discover the "path" of an embedded resource?
|
[
"",
"c#",
".net",
"resources",
""
] |
How do I use JUnit to test a class that has internal private methods, fields or nested classes?
It seems bad to change the access modifier for a method just to be able to run a test.
|
If you have somewhat of a legacy **Java** application, and you're not allowed to change the visibility of your methods, the best way to test private methods is to use [reflection](http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29).
Internally we're using helpers to get/set `private` and `private static` variables as well as invoke `private` and `private static` methods. The following patterns will let you do pretty much anything related to the private methods and fields. Of course, you can't change `private static final` variables through reflection.
```
Method method = TargetClass.getDeclaredMethod(methodName, argClasses);
method.setAccessible(true);
return method.invoke(targetObject, argObjects);
```
And for fields:
```
Field field = TargetClass.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, value);
```
---
> **Notes:**
>
> 1. `TargetClass.getDeclaredMethod(methodName, argClasses)` lets you look into `private` methods. The same thing applies for
> `getDeclaredField`.
> 2. The `setAccessible(true)` is required to play around with privates.
|
The best way to test a private method is via another public method. If this cannot be done, then one of the following conditions is true:
1. The private method is dead code
2. There is a design smell near the class that you are testing
3. The method that you are trying to test should not be private
|
How do I test a class that has private methods, fields or inner classes?
|
[
"",
"java",
"unit-testing",
"junit",
"tdd",
""
] |
I'm looking for a good way to perform multi-row inserts into an Oracle 9 database. The following works in MySQL but doesn't seem to be supported in Oracle.
```
INSERT INTO TMP_DIM_EXCH_RT
(EXCH_WH_KEY,
EXCH_NAT_KEY,
EXCH_DATE, EXCH_RATE,
FROM_CURCY_CD,
TO_CURCY_CD,
EXCH_EFF_DATE,
EXCH_EFF_END_DATE,
EXCH_LAST_UPDATED_DATE)
VALUES
(1, 1, '28-AUG-2008', 109.49, 'USD', 'JPY', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
(2, 1, '28-AUG-2008', .54, 'USD', 'GBP', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
(3, 1, '28-AUG-2008', 1.05, 'USD', 'CAD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
(4, 1, '28-AUG-2008', .68, 'USD', 'EUR', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
(5, 1, '28-AUG-2008', 1.16, 'USD', 'AUD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
(6, 1, '28-AUG-2008', 7.81, 'USD', 'HKD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008');
```
|
This works in Oracle:
```
insert into pager (PAG_ID,PAG_PARENT,PAG_NAME,PAG_ACTIVE)
select 8000,0,'Multi 8000',1 from dual
union all select 8001,0,'Multi 8001',1 from dual
```
The thing to remember here is to use the `from dual` statement.
|
In Oracle, to insert multiple rows into table t with columns col1, col2 and col3 you can use the following syntax:
```
INSERT ALL
INTO t (col1, col2, col3) VALUES ('val1_1', 'val1_2', 'val1_3')
INTO t (col1, col2, col3) VALUES ('val2_1', 'val2_2', 'val2_3')
INTO t (col1, col2, col3) VALUES ('val3_1', 'val3_2', 'val3_3')
.
.
.
SELECT 1 FROM DUAL;
```
---
In Oracle 23c, you can insert multiple rows with this simplified syntax:
```
INSERT INTO t(col1, col2, col3) VALUES
('val1_1', 'val1_2', 'val1_3'),
('val2_1', 'val2_2', 'val2_3'),
('val3_1', 'val3_2', 'val3_3');
```
For inserting a large number of rows, the new syntax is much faster than the older `INSERT ALL` approach and about as fast as the `UNION ALL` approach. However, due to exponentially increasing parse times, you still want to avoid inserting more than about 1000 rows at a time.
|
Best way to do multi-row insert in Oracle?
|
[
"",
"sql",
"oracle",
"sql-insert",
"oracle9i",
""
] |
The following code works great in IE, but not in FF or Safari. I can't for the life of me work out why. The code is *supposed* to disable radio buttons if you select the "Disable 2 radio buttons" option. It should enable the radio buttons if you select the "Enable both radio buttons" option. These both work...
However, if you don't use your mouse to move between the 2 options ("Enable..." and "Disable...") then the radio buttons do not appear to be disabled or enabled correctly, until you click anywhere else on the page (not on the radio buttons themselves).
If anyone has time/is curious/feeling helpful, please paste the code below into an html page and load it up in a browser. It works great in IE, but the problem manifests itself in FF (3 in my case) and Safari, all on Windows XP.
```
function SetLocationOptions() {
var frmTemp = document.frm;
var selTemp = frmTemp.user;
if (selTemp.selectedIndex >= 0) {
var myOpt = selTemp.options[selTemp.selectedIndex];
if (myOpt.attributes[0].nodeValue == '1') {
frmTemp.transfer_to[0].disabled = true;
frmTemp.transfer_to[1].disabled = true;
frmTemp.transfer_to[2].checked = true;
} else {
frmTemp.transfer_to[0].disabled = false;
frmTemp.transfer_to[1].disabled = false;
}
}
}
```
```
<form name="frm" action="coopfunds_transfer_request.asp" method="post">
<select name="user" onchange="javascript: SetLocationOptions()">
<option value="" />Choose One
<option value="58" user_is_tsm="0" />Enable both radio buttons
<option value="157" user_is_tsm="1" />Disable 2 radio buttons
</select>
<br /><br />
<input type="radio" name="transfer_to" value="fund_amount1" />Premium
<input type="radio" name="transfer_to" value="fund_amount2" />Other
<input type="radio" name="transfer_to" value="both" CHECKED />Both
<br /><br />
<input type="button" class="buttonStyle" value="Submit Request" />
</form>
```
|
To get FF to mimic IE's behavior when using the keyboard, you can use the keyup event on the select box. In your example (I am not a fan of attaching event handlers this way, but that's another topic), it would be like this:
```
<select name="user" id="selUser" onchange="javascript:SetLocationOptions()" onkeyup="javascript:SetLocationOptions()">
```
|
Well, IE has a somewhat non-standard object model; what you're doing shouldn't work but you're getting away with it because IE is being nice to you. In Firefox and Safari, document.frm in your code evaluates to undefined.
You need to be using id values on your form elements and use `document.getElementById('whatever')` to return a reference to them instead of referring to non-existent properties of the document object.
So this works a bit better and may do what you're after:
```
Line 27: <form name="frm" id="f" ...
Line 6: var frmTemp = document.getElementById('f');
```
But you might want to check out this excellent book if you want to learn more about the right way of going about things: [DOM Scripting](http://domscripting.com/book/) by Jeremy Keith
Also while we're on the subject, [Bulletproof Ajax](http://bulletproofajax.com/) by the same author is also deserving of a place on your bookshelf as is [JavaScript: The Good Parts](http://www.amazon.co.uk/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742) by Doug Crockford
|
How can I enable disabled radio buttons?
|
[
"",
"javascript",
"html",
"radio-button",
""
] |
I'm using JBoss Seam Framework, but it's seems to me isn't very popular among java developers.
I want to know how many java programmers here are using it, and in what kind of projects.
Is as good as django, or RoR?
|
In our [JBoss Seam in Action presentation](http://www.lunatech-research.com/archives/2007/12/14/javapolis-2007-seam) at the Javapolis conference last year, my colleague and I said that 'Seam is the next Struts'. This needed some explanation, which I later wrote-up as [Seam is the new Struts](http://www.lunatech-research.com/archives/2008/03/17/seam-is-the-new-struts). Needless to say, we like Seam.
One indication of Seam's popularity is the level of traffic on the [Seam Users Forum](http://www.seamframework.org/Community/SeamUsers).
|
I have used JBoss Seam now for about a year and like it very much over Spring. Unfortunately, I don't use this at work, more for side projects and personal projects. For me, it saves me a lot of time developing new projects for clients. And, one big reason I use it primarily is, the tight integration with each layer and I never get any lazy load errors that I used to get with Spring (even after the filter and other hacks).
An equivalent Spring application would have much more boilerplate code within it to get stuff working. Spring does not integrate each layer very well, it more or less is a wrapper for a lot of different things, but doesn't glue itself together very well.
The other nice thing I like with Seam is they practice what they preach. Take a look at their website. Take a guess what it is running, hmm, a live example of their code. Seam Wiki, Seam Forums, etc. If you truly believe in your code, stand behind it. I would be happy to have their pager 24x7x365, I bet it rarely goes off.
While you write a lot less code, the learning curve is about twice as steep. The further I get in, the more I understand how to write good code. I would like to see more comments, but as far as coding style, it is well written.
On the negative side, just as any product you try to market, Seam was years after Spring had already become popular so Spring is by far still more popular. Search on Indeed and Seam only has a few hits. If you look on Spring, there are roughly 40k registered users, while Seam has about 7k.
Depends on what is important to you, as a Java developer/engineer/programmer, you should be able to work with both technologies and chances are, you will most likely encounter a Spring application before a Seam one. Learn both and how to leverage both. If you use both properly and know the nuances and quirks of each, development becomes much easier whether you're using Spring or Seam.
I don't agree with the statement, "Seam is the next Struts". Struts was a view technology whereas Seam integrates all layers. I will agree that it is a new concept like Struts and will bring the same impact to the Java community that Struts did. I don't think we'll see that until Java EE 6 and CDI become more popular, and of course Seam 3 is released.
Walter
|
How Popular is the Seam Framework
|
[
"",
"java",
"frameworks",
"seam",
""
] |
Which C#/.NET Dependency Injection frameworks are worth looking into?
And what can you say about their complexity and speed.
|
**edit** (not by the author): There is a comprehensive list of IoC frameworks available at <https://github.com/quozd/awesome-dotnet/blob/master/README.md#ioc>:
* [Castle Windsor](https://github.com/castleproject/Windsor) - Castle Windsor is best of breed, mature Inversion of Control container available for .NET and Silverlight
* [Unity](https://github.com/unitycontainer/unity) - Lightweight extensible dependency injection container with support for constructor, property, and method call injection
* [Autofac](https://github.com/autofac/Autofac) - An addictive .NET IoC container
* [DryIoc](https://github.com/dadhi/DryIoc) - Simple, fast all fully featured IoC container.
* [Ninject](https://github.com/ninject/ninject) - The ninja of .NET dependency injectors
* [Spring.Net](https://github.com/spring-projects/spring-net) - Spring.NET is an open source application framework that makes building enterprise .NET applications easier
* [Lamar](https://jasperfx.github.io/lamar/) - A fast IoC container heavily optimized for usage within ASP.NET Core and other .NET server side applications.
* [LightInject](https://github.com/seesharper/LightInject) - A ultra lightweight IoC container
* [Simple Injector](https://github.com/simpleinjector/SimpleInjector) - Simple Injector is an easy-to-use Dependency Injection (DI) library for .NET 4+ that supports Silverlight 4+, Windows Phone 8, Windows 8 including Universal apps and Mono.
* [Microsoft.Extensions.DependencyInjection](https://github.com/aspnet/DependencyInjection) - The default IoC container for ASP.NET Core applications.
* [Scrutor](https://github.com/khellang/Scrutor) - Assembly scanning extensions for Microsoft.Extensions.DependencyInjection.
* [VS MEF](https://github.com/Microsoft/vs-mef) - Managed Extensibility Framework (MEF) implementation used by Visual Studio.
* [TinyIoC](https://github.com/grumpydev/TinyIoC) - An easy to use, hassle free, Inversion of Control Container for small projects, libraries and beginners alike.
* [Stashbox](https://github.com/z4kn4fein/stashbox) - A lightweight, fast and portable dependency injection framework for .NET based solutions.
Original answer follows.
---
I suppose I might be being a bit picky here but it's important to note that DI (Dependency Injection) is a programming pattern and is facilitated by, but does not require, an IoC (Inversion of Control) framework. IoC frameworks just make DI much easier and they provide a host of other benefits over and above DI.
That being said, I'm sure that's what you were asking. About IoC Frameworks; I used to use [Spring.Net](http://www.springframework.net/) and [CastleWindsor](https://github.com/castleproject/Windsor/blob/master/docs/README.md) a lot, but the real pain in the behind was all that pesky XML config you had to write! They're pretty much all moving this way now, so I have been using [StructureMap](http://structuremap.github.io/) for the last year or so, and since it has moved to a fluent config using strongly typed generics and a registry, my pain barrier in using IoC has dropped to below zero! I get an absolute kick out of knowing now that my IoC config is checked at compile-time (for the most part) and I have had nothing but joy with StructureMap and its speed. I won't say that the others were slow at runtime, but they were more difficult for me to setup and frustration often won the day.
**Update**
I've been using [Ninject](http://ninject.org/) on my latest project and it has been an absolute pleasure to use. Words fail me a bit here, but (as we say in the UK) this framework is 'the Dogs'. I would highly recommend it for any green fields projects where you want to be up and running quickly. I got all I needed from a [fantastic set of Ninject screencasts](http://www.dimecasts.net/Casts/ByAuthor/Justin%20Etheredge) by Justin Etheredge. I can't see that retro-fitting Ninject into existing code being a problem at all, but then the same could be said of [StructureMap](http://structuremap.github.io/) in my experience. It'll be a tough choice going forward between those two, but I'd rather have competition than stagnation and there's a decent amount of healthy competition out there.
Other IoC screencasts can also be found [here on Dimecasts](http://www.dimecasts.net/Casts/ByTag/IoC).
|
It depends on what you are looking for, as they each have their pros and cons.
1. **`Spring.NET`** is the most mature as it comes out of Spring from the Java world. Spring has a very rich set of framework libraries that extend it to support Web, Windows, etc.
2. **`Castle Windsor`** is one of the most widely used in the .NET platform and has the largest ecosystem, is highly configurable / extensible, has custom lifetime management, AOP support, has inherent NHibernate support and is an all around awesome container. Windsor is part of an entire stack which includes Monorail, Active Record, etc. NHibernate itself builds on top of Windsor.
3. **`Structure Map`** has very rich and fine grained configuration through an internal DSL.
4. **`Autofac`** is an IoC container of the new age with all of it's inherent functional programming support. It also takes a different approach on managing lifetime than the others. Autofac is still very new, but it pushes the bar on what is possible with IoC.
5. **`Ninject`** I have heard is more bare bones with a less is more approach (heard not experienced).
6. The biggest discriminator of **`Unity`** is: it's from and supported by Microsoft (p&p). Unity has very good performance, and great documentation. It is also highly configurable. It doesn't have all the bells and whistles of say Castle / Structure Map.
So in summary, it really depends on what is important to you. I would agree with others on going and evaluating and seeing which one fits. The nice thing is you have a nice selection of donuts rather than just having to have a jelly one.
|
Which .NET Dependency Injection frameworks are worth looking into?
|
[
"",
"c#",
".net",
"dependency-injection",
"inversion-of-control",
""
] |
I'm trying to learn C. As a C# developer, my IDE is Visual Studio. I've heard this is a good environment for C/C++ development. However, it seems no matter what little thing I try to do, intuition fails me. Can someone give good resources for how to either:
* learn the ins and out of C in Visual Studio
* recommend a better C IDE + compiler
---
**Edit:** See also: <https://stackoverflow.com/questions/951516/a-good-c-ide>
|
Answering the purely subject question "recommend me a better C IDE and compiler" I find [Ming32w and Code::blocks (now with combined installer)](http://www.codeblocks.org/) very useful on windows but YMMV as you are obviously used to the MS IDE and are just struggling with C.
May I suggest you concentrate on console applications to get a feel for the language first before you attempt to tie it together with a windows UI which in my experience is the hardest bit of windows development.
|
well you can use visual studio just fine take a look at here man
<http://www.daniweb.com/forums/thread16256.html>
Go to View Menu select Solution Explorer or CTRL+ ALT +L
Then Select The project that your are developing and right click on that.
Then select the Properties from the submenu.
Then select the Configuration properties from the Tree structure. under that select C/C++ then select Advanced. Now in the right side pane change the property
Compile As from Compile as C++ Code (/TP) to Compile as C Code (/TC)
Finally change your file extensions to .c
# Now you configured you Visual Studio to compile C programs
**And you can use NetBeans too it could even be more user friendly than Visual Studio download it you wont regret i promise**
|
C on Visual Studio
|
[
"",
"c++",
"c",
"ide",
"compiler-construction",
""
] |
I am about to reenter the MFC world after years away for a new job. What resources to people recommend for refreshing the memory? I have been doing mainly C# recently.
Also any MFC centric websites or blogs that people recommend?
|
* For blogs: Your best bet would be the [Visual C++ Team Blog](http://blogs.msdn.com/vcblog/default.aspx).
* For books: [Programming Windows with MFC](https://rads.stackoverflow.com/amzn/click/com/1572316950) is one of the best book on the subject.
* For tutorials: Simply [search google for various tutorials on MFC](http://www.google.ca/search?q=mfc+tutorial&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a).

|
The best: [The Code Project](http://www.codeproject.com/)
|
MFC resources / links
|
[
"",
"c++",
"c",
"mfc",
""
] |
How do you find a memory leak in Java (using, for example, JHat)? I have tried to load the heap dump up in JHat to take a basic look. However, I do not understand how I am supposed to be able to find the root reference ([ref](https://stackoverflow.com/questions/104/anatomy-of-a-memory-leak)) or whatever it is called. Basically, I can tell that there are several hundred megabytes of hash table entries ([java.util.HashMap$Entry or something like that), but maps are used all over the place... Is there some way to search for large maps, or perhaps find general roots of large object trees?
[Edit]
Ok, I've read the answers so far but let's just say I am a cheap bastard (meaning I am more interested in learning how to use JHat than to pay for JProfiler). Also, JHat is always available since it is part of the JDK. Unless of course there is no way with JHat but brute force, but I can't believe that can be the case.
Also, I do not think I will be able to actually modify (adding logging of *all* map sizes) and run it for long enough for me to notice the leak.
|
I use following approach to finding memory leaks in Java. I've used jProfiler with great success, but I believe that any specialized tool with graphing capabilities (diffs are easier to analyze in graphical form) will work.
1. Start the application and wait until it get to "stable" state, when all the initialization is complete and the application is idle.
2. Run the operation suspected of producing a memory leak several times to allow any cache, DB-related initialization to take place.
3. Run GC and take memory snapshot.
4. Run the operation again. Depending on the complexity of operation and sizes of data that is processed operation may need to be run several to many times.
5. Run GC and take memory snapshot.
6. Run a diff for 2 snapshots and analyze it.
Basically analysis should start from greatest positive diff by, say, object types and find what causes those extra objects to stick in memory.
For web applications that process requests in several threads analysis gets more complicated, but nevertheless general approach still applies.
I did quite a number of projects specifically aimed at reducing memory footprint of the applications and this general approach with some application specific tweaks and trick always worked well.
|
Questioner here, I have got to say getting a tool that does not take 5 minutes to answer any click makes it a lot easier to find potential memory leaks.
Since people are suggesting several tools ( I only tried visual wm since I got that in the JDK and JProbe trial ) I though I should suggest a free / open source tool built on the Eclipse platform, the Memory Analyzer (sometimes referenced as the SAP memory analyzer) available on <http://www.eclipse.org/mat/> .
What is really cool about this tool is that it indexed the heap dump when I first opened it which allowed it to show data like retained heap without waiting 5 minutes for each object (pretty much all operations were tons faster than the other tools I tried).
When you open the dump, the first screen shows you a pie chart with the biggest objects (counting retained heap) and one can quickly navigate down to the objects that are to big for comfort. It also has a Find likely leak suspects which I reccon can come in handy, but since the navigation was enough for me I did not really get into it.
|
How to find a Java Memory Leak
|
[
"",
"java",
"memory",
"memory-leaks",
"jhat",
""
] |
What is the best way of creating an alphabetically sorted list in Python?
|
Basic answer:
```
mylist = ["b", "C", "A"]
mylist.sort()
```
This modifies your original list (i.e. sorts in-place). To get a sorted copy of the list, without changing the original, use the [`sorted()`](http://docs.python.org/library/functions.html#sorted) function:
```
for x in sorted(mylist):
print x
```
However, the examples above are a bit naive, because they don't take locale into account, and perform a case-sensitive sorting. You can take advantage of the optional parameter `key` to specify custom sorting order (the alternative, using `cmp`, is a deprecated solution, as it has to be evaluated multiple times - `key` is only computed once per element).
So, to sort according to the current locale, taking language-specific rules into account ([`cmp_to_key`](http://docs.python.org/library/functools.html#functools.cmp_to_key) is a helper function from functools):
```
sorted(mylist, key=cmp_to_key(locale.strcoll))
```
And finally, if you need, you can specify a [custom locale](http://docs.python.org/library/locale.html) for sorting:
```
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale
assert sorted((u'Ab', u'ad', u'aa'),
key=cmp_to_key(locale.strcoll)) == [u'aa', u'Ab', u'ad']
```
Last note: you will see examples of case-insensitive sorting which use the `lower()` method - those are incorrect, because they work only for the ASCII subset of characters. Those two are wrong for any non-English data:
```
# this is incorrect!
mylist.sort(key=lambda x: x.lower())
# alternative notation, a bit faster, but still wrong
mylist.sort(key=str.lower)
```
|
It is also worth noting the [`sorted()`](https://docs.python.org/3/library/functions.html#sorted "sorted") function:
```
for x in sorted(list):
print x
```
This returns a new, sorted version of a list without changing the original list.
|
How to sort a list of strings?
|
[
"",
"python",
"string",
"sorting",
""
] |
I need a C# profiler.
Although I'm not averse to paying for one, something which is free or at least with a trial version would be ideal since it takes time to raise a purchase order.
Any recommendations?
|
You can try the following:
* [nprof](http://nprof.sourceforge.net/Site/Description.html) (free but kinda old)
* [ProfileSharp](http://sourceforge.net/projects/profilesharp/) (open source)
* [.Net Memory Profiler](http://memprofiler.com/) (really good for memory leaks, there's a trial version)
---
Edit:
Nprof has been replaced with [SlimTune](https://code.google.com/p/slimtune/) and works with .Net 4.0 applications
|
I used [Ants profiler](http://www.red-gate.com/products/dotnet-development/ants-performance-profiler/) on a large c# project a year and a half ago. It really performed very nicely for what it cost, and even outperformed a few of the more expensive competitors.
It calculates cost on with almost a line by line resolution.
|
Any decent C# profilers out there?
|
[
"",
"c#",
".net",
"profiling",
"profiler",
""
] |
My project is based on spring framework 2.5.4. And I try to add aspects for some controllers (I use aspectj 1.5.3).
I've enabled auto-proxy in application-servlet.xml, just pasted these lines to the end of the xml file:
```
<aop:aspectj-autoproxy />
<bean id="auditLogProcessor" class="com.example.bg.web.utils.AuditLogProcessor" />
```
Created aspect:
```
package com.example.bg.web.utils;
import org.apache.log4j.Logger;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class AuditLogProcessor
{
private final static Logger log = Logger.getLogger(AuditLogProcessor.class);
@After("execution(* com.example.bg.web.controllers.assets.AssetThumbnailRebuildController.rebuildThumbnail(..))")
public void afterHandleRequest() {
log.info("test111");
}
@After("execution(* com.example.bg.web.controllers.assets.AssetThumbnailRebuildController.rebuildThumbnail(..))")
public void afterRebuildThumbnail() {
log.info("test222");
}
}
```
My controllers:
```
class AssetAddController implements Controller
class AssetThumbnailRebuildController extends MultiActionController
```
When I set brake points in aspect advisors and invoke controllers I catch only afterHandleRequest() but not afterRebildThumbnail()
What did I do wrong?
**NOTE**
I'm asking this question on behalf of my friend who doesn't have access to SO beta, and I don't have a clue what it's all about.
**EDIT**
There were indeed some misspellings, thanks Cheekysoft. But the problem still persists.
|
Your breakpoints aren't being hit because you are using Spring's AOP Proxies. See [understanding-aop-proxies](http://static.springframework.org/spring/docs/2.5.x/reference/aop.html#aop-understanding-aop-proxies) for a description of how AOP Proxies are special.
Basically, the MVC framework is going to call the `handleRequest` method on your controller's proxy (which for example the `MultiActionController` you're using as a base class implements), this method will then make an "internal" call to its rebuildThumbnail method, but this won't go through the proxy and thus won't pick up any aspects. (This has nothing to do with the methods being final.)
To achieve what you want, investigate using "real" AOP via load time weaving (which Spring supports very nicely).
|
AspectJ doesn't work well with classes in the Spring Web MVC framework. [Read the bottom of the "Open for extension..." box on the right side of the page](http://static.springframework.org/spring/docs/2.0.x/reference/mvc.html)
Instead, take a look at the [HandlerInterceptor](http://static.springframework.org/spring/docs/2.0.x/api/org/springframework/web/servlet/HandlerInterceptor.html) interface.
The new Spring MVC Annotations may work as well since then the Controller classes are all POJOs, but I haven't tried it myself.
|
Aspectj doesn't catch all events in spring framework?
|
[
"",
"java",
"spring",
"spring-aop",
""
] |
I'm creating an application which lets you define events with a time frame. I want to automatically fill in the end date when the user selects or changes the start date. I can't quite figure out, however, how to get the difference between the two times, and then how to create a new end Date using that difference.
|
In JavaScript, dates can be transformed to the number of milliseconds since the epoc by calling the `getTime()` method **or** just using the date in a numeric expression.
So to get the difference, just subtract the two dates.
To create a new date based on the difference, just pass the number of milliseconds in the constructor.
```
var oldBegin = ...
var oldEnd = ...
var newBegin = ...
var newEnd = new Date(newBegin + oldEnd - oldBegin);
```
This should just work
**EDIT**: Fixed bug pointed by @bdukes
**EDIT**:
For an explanation of the behavior, `oldBegin`, `oldEnd`, and `newBegin` are `Date` instances. Calling operators `+` and `-` will trigger Javascript auto casting and will automatically call the `valueOf()` prototype method of those objects. It happens that the `valueOf()` method is implemented in the `Date` object as a call to `getTime()`.
So basically: `date.getTime() === date.valueOf() === (0 + date) === (+date)`
|
JavaScript perfectly supports date difference out of the box
<https://jsfiddle.net/b9chris/v5twbe3h/>
```
var msMinute = 60*1000,
msDay = 60*60*24*1000,
a = new Date(2012, 2, 12, 23, 59, 59),
b = new Date("2013 march 12");
console.log(Math.floor((b - a) / msDay) + ' full days between'); // 364
console.log(Math.floor(((b - a) % msDay) / msMinute) + ' full minutes between'); // 0
```
---
Now some pitfalls. Try this:
```
console.log(a - 10); // 1331614798990
console.log(a + 10); // mixed string
```
So if you have risk of adding a number and Date, convert Date to `number` directly.
```
console.log(a.getTime() - 10); // 1331614798990
console.log(a.getTime() + 10); // 1331614799010
```
My fist example demonstrates the power of Date object but it actually appears to be a time bomb
|
How do I get the difference between two Dates in JavaScript?
|
[
"",
"javascript",
"date",
""
] |
We’ve found that the unit tests we’ve written for our C#/C++ code have really paid off.
But we still have thousands of lines of business logic in stored procedures, which only really get tested in anger when our product is rolled out to a large number of users.
What makes this worse is that some of these stored procedures end up being very long, because of the performance hit when passing temporary tables between SPs. This has prevented us from refactoring to make the code simpler.
We have made several attempts at building unit tests around some of our key stored procedures (primarily testing the performance), but have found that setting up the test data for these tests is really hard. For example, we end up copying around test databases. In addition to this, the tests end up being really sensitive to change, and even the smallest change to a stored proc. or table requires a large amount of changes to the tests. So after many builds breaking due to these database tests failing intermittently, we’ve just had to pull them out of the build process.
So, the main part of my questions is: has anyone ever successfully written unit tests for their stored procedures?
The second part of my questions is whether unit testing would be/is easier with linq?
I was thinking that rather than having to set up tables of test data, you could simply create a collection of test objects, and test your linq code in a “linq to objects” situation? (I am a totally new to linq so don’t know if this would even work at all)
|
I ran into this same issue a while back and found that if I created a simple abstract base class for data access that allowed me to inject a connection and transaction, I could unit test my sprocs to see if they did the work in SQL that I asked them to do and then rollback so none of the test data is left in the db.
This felt better than the usual "run a script to setup my test db, then after the tests run do a cleanup of the junk/test data". This also felt closer to unit testing because these tests could be run alone w/out having a great deal of "everything in the db needs to be 'just so' before I run these tests".
**Here is a snippet of the abstract base class used for data access**
```
Public MustInherit Class Repository(Of T As Class)
Implements IRepository(Of T)
Private mConnectionString As String = ConfigurationManager.ConnectionStrings("Northwind.ConnectionString").ConnectionString
Private mConnection As IDbConnection
Private mTransaction As IDbTransaction
Public Sub New()
mConnection = Nothing
mTransaction = Nothing
End Sub
Public Sub New(ByVal connection As IDbConnection, ByVal transaction As IDbTransaction)
mConnection = connection
mTransaction = transaction
End Sub
Public MustOverride Function BuildEntity(ByVal cmd As SqlCommand) As List(Of T)
Public Function ExecuteReader(ByVal Parameter As Parameter) As List(Of T) Implements IRepository(Of T).ExecuteReader
Dim entityList As List(Of T)
If Not mConnection Is Nothing Then
Using cmd As SqlCommand = mConnection.CreateCommand()
cmd.Transaction = mTransaction
cmd.CommandType = Parameter.Type
cmd.CommandText = Parameter.Text
If Not Parameter.Items Is Nothing Then
For Each param As SqlParameter In Parameter.Items
cmd.Parameters.Add(param)
Next
End If
entityList = BuildEntity(cmd)
If Not entityList Is Nothing Then
Return entityList
End If
End Using
Else
Using conn As SqlConnection = New SqlConnection(mConnectionString)
Using cmd As SqlCommand = conn.CreateCommand()
cmd.CommandType = Parameter.Type
cmd.CommandText = Parameter.Text
If Not Parameter.Items Is Nothing Then
For Each param As SqlParameter In Parameter.Items
cmd.Parameters.Add(param)
Next
End If
conn.Open()
entityList = BuildEntity(cmd)
If Not entityList Is Nothing Then
Return entityList
End If
End Using
End Using
End If
Return Nothing
End Function
End Class
```
**next you will see a sample data access class using the above base to get a list of products**
```
Public Class ProductRepository
Inherits Repository(Of Product)
Implements IProductRepository
Private mCache As IHttpCache
'This const is what you will use in your app
Public Sub New(ByVal cache As IHttpCache)
MyBase.New()
mCache = cache
End Sub
'This const is only used for testing so we can inject a connectin/transaction and have them roll'd back after the test
Public Sub New(ByVal cache As IHttpCache, ByVal connection As IDbConnection, ByVal transaction As IDbTransaction)
MyBase.New(connection, transaction)
mCache = cache
End Sub
Public Function GetProducts() As System.Collections.Generic.List(Of Product) Implements IProductRepository.GetProducts
Dim Parameter As New Parameter()
Parameter.Type = CommandType.StoredProcedure
Parameter.Text = "spGetProducts"
Dim productList As List(Of Product)
productList = MyBase.ExecuteReader(Parameter)
Return productList
End Function
'This function is used in each class that inherits from the base data access class so we can keep all the boring left-right mapping code in 1 place per object
Public Overrides Function BuildEntity(ByVal cmd As System.Data.SqlClient.SqlCommand) As System.Collections.Generic.List(Of Product)
Dim productList As New List(Of Product)
Using reader As SqlDataReader = cmd.ExecuteReader()
Dim product As Product
While reader.Read()
product = New Product()
product.ID = reader("ProductID")
product.SupplierID = reader("SupplierID")
product.CategoryID = reader("CategoryID")
product.ProductName = reader("ProductName")
product.QuantityPerUnit = reader("QuantityPerUnit")
product.UnitPrice = reader("UnitPrice")
product.UnitsInStock = reader("UnitsInStock")
product.UnitsOnOrder = reader("UnitsOnOrder")
product.ReorderLevel = reader("ReorderLevel")
productList.Add(product)
End While
If productList.Count > 0 Then
Return productList
End If
End Using
Return Nothing
End Function
End Class
```
**And now in your unit test you can also inherit from a very simple base class that does your setup / rollback work - or keep this on a per unit test basis**
**below is the simple testing base class I used**
```
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Public MustInherit Class TransactionFixture
Protected mConnection As IDbConnection
Protected mTransaction As IDbTransaction
Private mConnectionString As String = ConfigurationManager.ConnectionStrings("Northwind.ConnectionString").ConnectionString
<TestInitialize()> _
Public Sub CreateConnectionAndBeginTran()
mConnection = New SqlConnection(mConnectionString)
mConnection.Open()
mTransaction = mConnection.BeginTransaction()
End Sub
<TestCleanup()> _
Public Sub RollbackTranAndCloseConnection()
mTransaction.Rollback()
mTransaction.Dispose()
mConnection.Close()
mConnection.Dispose()
End Sub
End Class
```
**and finally - the below is a simple test using that test base class that shows how to test the entire CRUD cycle to make sure all the sprocs do their job and that your ado.net code does the left-right mapping correctly**
**I know this doesn't test the "spGetProducts" sproc used in the above data access sample, but you should see the power behind this approach to unit testing sprocs**
```
Imports SampleApplication.Library
Imports System.Collections.Generic
Imports Microsoft.VisualStudio.TestTools.UnitTesting
<TestClass()> _
Public Class ProductRepositoryUnitTest
Inherits TransactionFixture
Private mRepository As ProductRepository
<TestMethod()> _
Public Sub Should-Insert-Update-And-Delete-Product()
mRepository = New ProductRepository(New HttpCache(), mConnection, mTransaction)
'** Create a test product to manipulate throughout **'
Dim Product As New Product()
Product.ProductName = "TestProduct"
Product.SupplierID = 1
Product.CategoryID = 2
Product.QuantityPerUnit = "10 boxes of stuff"
Product.UnitPrice = 14.95
Product.UnitsInStock = 22
Product.UnitsOnOrder = 19
Product.ReorderLevel = 12
'** Insert the new product object into SQL using your insert sproc **'
mRepository.InsertProduct(Product)
'** Select the product object that was just inserted and verify it does exist **'
'** Using your GetProductById sproc **'
Dim Product2 As Product = mRepository.GetProduct(Product.ID)
Assert.AreEqual("TestProduct", Product2.ProductName)
Assert.AreEqual(1, Product2.SupplierID)
Assert.AreEqual(2, Product2.CategoryID)
Assert.AreEqual("10 boxes of stuff", Product2.QuantityPerUnit)
Assert.AreEqual(14.95, Product2.UnitPrice)
Assert.AreEqual(22, Product2.UnitsInStock)
Assert.AreEqual(19, Product2.UnitsOnOrder)
Assert.AreEqual(12, Product2.ReorderLevel)
'** Update the product object **'
Product2.ProductName = "UpdatedTestProduct"
Product2.SupplierID = 2
Product2.CategoryID = 1
Product2.QuantityPerUnit = "a box of stuff"
Product2.UnitPrice = 16.95
Product2.UnitsInStock = 10
Product2.UnitsOnOrder = 20
Product2.ReorderLevel = 8
mRepository.UpdateProduct(Product2) '**using your update sproc
'** Select the product object that was just updated to verify it completed **'
Dim Product3 As Product = mRepository.GetProduct(Product2.ID)
Assert.AreEqual("UpdatedTestProduct", Product2.ProductName)
Assert.AreEqual(2, Product2.SupplierID)
Assert.AreEqual(1, Product2.CategoryID)
Assert.AreEqual("a box of stuff", Product2.QuantityPerUnit)
Assert.AreEqual(16.95, Product2.UnitPrice)
Assert.AreEqual(10, Product2.UnitsInStock)
Assert.AreEqual(20, Product2.UnitsOnOrder)
Assert.AreEqual(8, Product2.ReorderLevel)
'** Delete the product and verify it does not exist **'
mRepository.DeleteProduct(Product3.ID)
'** The above will use your delete product by id sproc **'
Dim Product4 As Product = mRepository.GetProduct(Product3.ID)
Assert.AreEqual(Nothing, Product4)
End Sub
End Class
```
I know this is a long example, but it helped to have a reusable class for the data access work, and yet another reusable class for my testing so I didn't have to do the setup/teardown work over and over again ;)
|
Have you tried [DBUnit](http://dbunit.sourceforge.net/)? It's designed to unit test your database, and just your database, without needing to go through your C# code.
|
Has anyone had any success in unit testing SQL stored procedures?
|
[
"",
"sql",
"unit-testing",
"linq-to-sql",
""
] |
Is there a tag in HTML that will only display its content if JavaScript is enabled? I know `<noscript>` works the opposite way around, displaying its HTML content when JavaScript is turned off. But I would like to only display a form on a site if JavaScript is available, telling them why they can't use the form if they don't have it.
The only way I know how to do this is with the `document.write();` method in a script tag, and it seems a bit messy for large amounts of HTML.
|
You could have an invisible div that gets shown via JavaScript when the page loads.
|
Easiest way I can think of:
```
<html>
<head>
<noscript><style> .jsonly { display: none } </style></noscript>
</head>
<body>
<p class="jsonly">You are a JavaScript User!</p>
</body>
</html>
```
No document.write, no scripts, pure CSS.
|
Is there a HTML opposite to <noscript>?
|
[
"",
"javascript",
"html",
"noscript",
""
] |
How can one determine, in code, how long the machine is locked?
Other ideas outside of C# are also welcome.
---
I like the windows service idea (and have accepted it) for simplicity and cleanliness, but unfortunately I don't think it will work for me in this particular case. I wanted to run this on my workstation at work rather than home (or in addition to home, I suppose), but it's locked down pretty hard courtesy of the DoD. That's part of the reason I'm rolling my own, actually.
I'll write it up anyway and see if it works. Thanks everyone!
|
I hadn't found this before, but from any application you can hookup a SessionSwitchEventHandler. Obviously your application will need to be running, but so long as it is:
```
Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);
void SystemEvents_SessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e)
{
if (e.Reason == SessionSwitchReason.SessionLock)
{
//I left my desk
}
else if (e.Reason == SessionSwitchReason.SessionUnlock)
{
//I returned to my desk
}
}
```
|
I would create a Windows Service (a visual studio 2005 project type) that handles the OnSessionChange event as shown below:
```
protected override void OnSessionChange(SessionChangeDescription changeDescription)
{
if (changeDescription.Reason == SessionChangeReason.SessionLock)
{
//I left my desk
}
else if (changeDescription.Reason == SessionChangeReason.SessionUnlock)
{
//I returned to my desk
}
}
```
What and how you log the activity at that point is up to you, but a Windows Service provides quick and easy access to windows events like startup, shutdown, login/out, along with the lock and unlock events.
|
Programmatically Determine a Duration of a Locked Workstation?
|
[
"",
"c#",
"windows",
""
] |
I've got a menu in Python. That part was easy. I'm using `raw_input()` to get the selection from the user.
The problem is that `raw_input` (and input) require the user to press `Enter` after they make a selection. Is there any way to make the program act immediately upon a keystroke? Here's what I've got so far:
```
import sys
print """Menu
1) Say Foo
2) Say Bar"""
answer = raw_input("Make a selection> ")
if "1" in answer: print "foo"
elif "2" in answer: print "bar"
```
It would be great to have something like
```
print menu
while lastKey = "":
lastKey = check_for_recent_keystrokes()
if "1" in lastKey: #do stuff...
```
|
**On Windows:**
```
import msvcrt
answer=msvcrt.getch()
```
|
**On Linux:**
* set raw mode
* select and read the keystroke
* restore normal settings
```
import sys
import select
import termios
import tty
def getkey():
old_settings = termios.tcgetattr(sys.stdin)
tty.setraw(sys.stdin.fileno())
select.select([sys.stdin], [], [], 0)
answer = sys.stdin.read(1)
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
return answer
print """Menu
1) Say Foo
2) Say Bar"""
answer=getkey()
if "1" in answer: print "foo"
elif "2" in answer: print "bar"
```
|
How do I make a menu that does not require the user to press [enter] to make a selection?
|
[
"",
"python",
""
] |
In .net frameworks 1.1, I use
```
System.Configuration.ConfigurationSettings.AppSettings["name"];
```
for application settings. But in .Net 2.0, it says ConfigurationSettings is obsolete and to use ConfigurationManager instead. So I swapped it out with this:
```
System.Configuration.ConfigurationManager.AppSettings["name"];
```
The problem is, ConfigurationManager was not found in the System.Configuration namespace. I've been banging my head against the wall trying to figure out what I'm doing wrong. Anybody got any ideas?
|
You have to reference the System.configuration assembly (note the lowercase)
I don't know why this assembly is not added by default to new projects on Visual Studio, but I find myself having the same problem every time I start a new project. I always forget to add the reference.
|
If you're just trying to get a value from the app.config file, you might want to use:
```
ConfigurationSettings.AppSettings["name"];
```
That works for me, anyways.
/Jonas
|
Help accessing application settings using ConfigurationManager
|
[
"",
"c#",
".net",
".net-2.0",
""
] |
How do you OCR an tiff file using Tesseract's interface in c#?
Currently I only know how to do it using the executable.
|
The source code seemed to be geared for an executable, you might need to rewire stuffs a bit so it would build as a DLL instead. I don't have much experience with Visual C++ but I think it shouldn't be too hard with some research. My guess is that someone might have had made a library version already, you should try Google.
Once you have tesseract-ocr code in a DLL file, you can then import the file into your C# project via Visual Studio and have it create wrapper classes and do all the marshaling stuffs for you. If you can't import then [DllImport](http://www.codeproject.com/KB/cs/c__and_api.aspx) will let you call the functions in the DLL from C# code.
Then you can take a look at the original executable to find clues on what functions to call to properly OCR a tiff image.
|
Take a look at [tessnet](http://www.pixel-technology.com/freeware/tessnet2/)
|
OCR with the Tesseract interface
|
[
"",
"c#",
"ocr",
"tesseract",
""
] |
In your applications, what's a "long time" to keep a transaction open before committing or rolling back? Minutes? Seconds? Hours?
and on which database?
|
@lomaxx, @ChanChan: to the best of my knowledge cursors are only a problem on SQL Server and Sybase (T-SQL variants). If your database of choice is Oracle, then cursors are your friend. I've seen a number of cases where the use of cursors has actually improved performance. Cursors are an incredibly useful mechanism and tbh, saying things like "if you use a cursor we fire you" is a little ridiculous.
Having said that, you only want to keep a cursor open for the absolute minimum that is required. Specifying a maximum time would be arbitrary and pointless without understanding the problem domain.
|
I'm probably going to get flamed for this, but you really should try and avoid using cursors as they incur a serious performance hit. If you must use it, you should keep it open the absolute minimum amount of time possible so that you free up the resources being blocked by the cursor ASAP.
|
What is a "reasonable" length of time to keep a SQL cursor open?
|
[
"",
"sql",
"cursors",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.