Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
How can I find out what caused equals() to return false?
I'm not asking about a sure-way, always right approach, but of something to aid in the development process. Currently I have to step into the equals() calls (usually a tree of them) until one of them is false, then step into it, ad nauseam.
I thought about using the object graph, outputting it to xml and comparing the two objects. However, XMLEncoder requires default constructors, jibx requires pre-compilation, x-stream and simple api are not used in my project. I don't mind copying a single class, or even a package, into my test area and using it there, but importing a whole jar for this just isn't going to happen.
I also thought about building an object graph traverser myself, and I might still do it, but I'd hate to start dealing with special cases (ordered collections, non-ordered collections, maps...)
Any idea how to go about it?
Edit: I know adding jars is the normal way of doing things. I know jars are reusable units. However, the bureaucracy needed (at my project) for this doesn't justify the results - I'd keep on debugging and stepping into. | It's presumably not a full graph comparison... unless your equals include every property in each class ... (you could try == :))
Try [hamcrest matchers](http://code.google.com/p/hamcrest/) - you can compose each matcher in an "all of" matcher:
```
Matcher<MyClass> matcher = CoreMatchers.allOf(
HasPropertyWithValue.hasProperty("myField1", getMyField1()),
HasPropertyWithValue.hasProperty("myField2", getMyField2()));
if (!matcher.matches(obj)){
System.out.println(matcher.describeFailure(obj));
return false;
}
return true;
```
It will say things like: 'expected myField1 to have a value of "value" but was "a different value"'
Of course you can inline the static factories. This is a bit heavier than using [apache-commons EqualsBuilder](http://commons.apache.org/lang/api/org/apache/commons/lang/builder/EqualsBuilder.html), but it does give you an accurate description of exactly what failed.
You can create your own specialised matcher for quickly creating these expressions. It would be wise to copy [apache-commons EqualsBuilder](http://commons.apache.org/lang/api/org/apache/commons/lang/builder/EqualsBuilder.html) here.
BTW, the hamcrest basic jar is 32K (including source!) giving you the option of reviewing the code and saying to your bosses "I'll stand by this as my own code" (which I presume is your import problem). | You could use aspects to patch "equal" on the classes in your object graph and make them log the object state to a file when they return false. To log the object state you could use something like beanutils to inspect the object and dump it. This is one jar-based solution which can be easily used in your workspace
If the hierarchy of the objects stored in your tree is simple enough, you could place conditional breakpoints on your classes "equal" implementation which only triggers when "equal" returns false which would limit the number of times you have to step into ... you can use this wherever you have debugger access. eclipse handles this just fine. | Finding out what caused equals() to return false | [
"",
"java",
"xml",
"equals",
"graph-theory",
""
] |
Can a Java application be loaded in a separate process using its name, as opposed to its location, in a platform independent manner?
I know you can execute a program via ...
```
Process process = Runtime.getRuntime().exec( COMMAND );
```
... the main issue of this method is that such calls are then platform specific.
Ideally, I'd wrap a method into something as simple as...
```
EXECUTE.application( CLASS_TO_BE_EXECUTED );
```
... and pass in the fully qualified name of an application class as `CLASS_TO_BE_EXECUTED`. | Two hints:
`System.getProperty("java.home") + "/bin/java"` gives you a path to the java executable.
`((URLClassLoader) Thread.currentThread().getContextClassLoader()).getURL()` helps you to reconstruct the classpath of current application.
Then your `EXECUTE.application` is just (pseudocode):
`Process.exec(javaExecutable, "-classpath", urls.join(":"), CLASS_TO_BE_EXECUTED)` | This is a synthesis of some of the other answers that have been provided. The Java system properties provide enough information to come up with the path to the java command and the classpath in what, I think, is a platform independent way.
```
public final class JavaProcess {
private JavaProcess() {}
public static int exec(Class klass, List<String> args) throws IOException,
InterruptedException {
String javaHome = System.getProperty("java.home");
String javaBin = javaHome +
File.separator + "bin" +
File.separator + "java";
String classpath = System.getProperty("java.class.path");
String className = klass.getName();
List<String> command = new LinkedList<String>();
command.add(javaBin);
command.add("-cp");
command.add(classpath);
command.add(className);
if (args != null) {
command.addAll(args);
}
ProcessBuilder builder = new ProcessBuilder(command);
Process process = builder.inheritIO().start();
process.waitFor();
return process.exitValue();
}
}
```
You would run this method like so:
```
int status = JavaProcess.exec(MyClass.class, args);
```
I thought it made sense to pass in the actual class rather than the String representation of the name since the class has to be in the classpath anyways for this to work. | Executing a Java application in a separate process | [
"",
"java",
"process",
"exec",
""
] |
We have a Java application server running on Sun Solaris. We now need to be able to write files and read files to/from a separate machine, which is running WindowsXP. These 2 machines are administered by 2 separate groups within the same firewall. If it is easier, we could use Java to write the file to Solaris and then use some 3rd party program to move the files to/from the Windows machine.
What is the best way to handle this?
Just one more piece of information: our group administers the Solaris machine and we could add software to that machine if necessary. But trying to get the other group to add any software to the Windows machine would be a major pain. So I would prefer a solution that does not require installing anything on the Windows machine. | Probably the simplest way would be to set up a share on the windows machine and use Samba to mount that on the Solaris machine. Then your Java app would see that directory just like any other local directory on the filesystem. | Synchronise the datastores/filesystem (folder) of the machines using a tool like [Rsync](http://samba.anu.edu.au/rsync/)
> > [Installing ssh and rsync on a Windows machine: minimalist approach](http://optics.ph.unimelb.edu.au/help/rsync/rsync_pc1.html) | Best way for Java to write/read file on a separate machine? | [
"",
"java",
"windows",
"solaris",
"admin",
""
] |
I have a question for anyone who has experience on i4o or PLINQ. I have a big object collection (about 400K ) needed to query. The logic is very simple and straightforward. For example, there has a collection of Person objects, I need to find the persons matched with same firstName, lastName, datebirth, or the first initial of FirstName/lastname, etc. It is just a time consuming process using LINQ to Object.
I am wondering if i4o [(http://www.codeplex.com/i4o](http://www.codeplex.com/i4o))
or PLINQ can help on improving the query performance. Which one is better? And if there has any approach out there.
Thanks! | With 400k objects, I wonder whether a database (either in-process or out-of-process) wouldn't be a more appropriate answer. This then abstracts the index creation process. In particular, any database will support multiple different indexes over different column(s), making the queries cited all very supportable without having to code specifically for each (just let the query optimizer worry about it).
Working with it in-memory may be valid, but you might (with vanilla .NET) have to do a lot more manual index management. By the sounds of it, i4o would certainly be worth investigating, but I don't have any existing comparison data. | i4o : is meant to speed up quering using linq by using indexes like old relational database days.
PLinq: is meant to use extra cpu cores to process the query in parallel.
If performance is your target, depending on your hardware, I say go with i4o it will make a hell of improvement. | Comparing i4o vs. PLINQ for larger collections | [
"",
"c#",
"linq",
"linq-to-objects",
"plinq",
""
] |
Which is the simplest way to update a `Label` from another `Thread`?
* I have a `Form` running on `thread1`, and from that I'm starting another thread (`thread2`).
* While `thread2` is processing some files I would like to update a `Label` on the `Form` with the current status of `thread2`'s work.
How could I do that? | For .NET 2.0, here's a nice bit of code I wrote that does exactly what you want, and works for any property on a `Control`:
```
private delegate void SetControlPropertyThreadSafeDelegate(
Control control,
string propertyName,
object propertyValue);
public static void SetControlPropertyThreadSafe(
Control control,
string propertyName,
object propertyValue)
{
if (control.InvokeRequired)
{
control.Invoke(new SetControlPropertyThreadSafeDelegate
(SetControlPropertyThreadSafe),
new object[] { control, propertyName, propertyValue });
}
else
{
control.GetType().InvokeMember(
propertyName,
BindingFlags.SetProperty,
null,
control,
new object[] { propertyValue });
}
}
```
Call it like this:
```
// thread-safe equivalent of
// myLabel.Text = status;
SetControlPropertyThreadSafe(myLabel, "Text", status);
```
If you're using .NET 3.0 or above, you could rewrite the above method as an extension method of the `Control` class, which would then simplify the call to:
```
myLabel.SetPropertyThreadSafe("Text", status);
```
**UPDATE 05/10/2010:**
For .NET 3.0 you should use this code:
```
private delegate void SetPropertyThreadSafeDelegate<TResult>(
Control @this,
Expression<Func<TResult>> property,
TResult value);
public static void SetPropertyThreadSafe<TResult>(
this Control @this,
Expression<Func<TResult>> property,
TResult value)
{
var propertyInfo = (property.Body as MemberExpression).Member
as PropertyInfo;
if (propertyInfo == null ||
!@this.GetType().IsSubclassOf(propertyInfo.ReflectedType) ||
@this.GetType().GetProperty(
propertyInfo.Name,
propertyInfo.PropertyType) == null)
{
throw new ArgumentException("The lambda expression 'property' must reference a valid property on this Control.");
}
if (@this.InvokeRequired)
{
@this.Invoke(new SetPropertyThreadSafeDelegate<TResult>
(SetPropertyThreadSafe),
new object[] { @this, property, value });
}
else
{
@this.GetType().InvokeMember(
propertyInfo.Name,
BindingFlags.SetProperty,
null,
@this,
new object[] { value });
}
}
```
which uses LINQ and lambda expressions to allow much cleaner, simpler and safer syntax:
```
// status has to be of type string or this will fail to compile
myLabel.SetPropertyThreadSafe(() => myLabel.Text, status);
```
Not only is the property name now checked at compile time, the property's type is as well, so it's impossible to (for example) assign a string value to a boolean property, and hence cause a runtime exception.
Unfortunately this doesn't stop anyone from doing stupid things such as passing in another `Control`'s property and value, so the following will happily compile:
```
myLabel.SetPropertyThreadSafe(() => aForm.ShowIcon, false);
```
Hence I added the runtime checks to ensure that the passed-in property does actually belong to the `Control` that the method's being called on. Not perfect, but still a lot better than the .NET 2.0 version.
If anyone has any further suggestions on how to improve this code for compile-time safety, please comment! | The **simplest** way is an anonymous method passed into [`Label.Invoke`](https://msdn.microsoft.com/en-us/library/zyzhdc6b(v=vs.110).aspx):
```
// Running on the worker thread
string newText = "abc";
form.Label.Invoke((MethodInvoker)delegate {
// Running on the UI thread
form.Label.Text = newText;
});
// Back on the worker thread
```
Notice that `Invoke` blocks execution until it completes--this is synchronous code. The question doesn't ask about asynchronous code, but there is lots of [content on Stack Overflow](https://stackoverflow.com/search?q=c%23+await+async+pattern) about writing asynchronous code when you want to learn about it. | How do I update the GUI from another thread? | [
"",
"c#",
".net",
"multithreading",
"winforms",
"user-interface",
""
] |
In JavaScript, when converting from a float to a string, how can I get just 2 digits after the decimal point? For example, 0.34 instead of 0.3445434. | ```
var result = Math.round(original*100)/100;
```
[The specifics](http://www.javascriptkit.com/javatutors/round.shtml), in case the code isn't self-explanatory.
edit: ...or just use `toFixed`, as proposed by [Tim Büthe](https://stackoverflow.com/questions/661562/comma-format-in-javascript/661579#661579). Forgot that one, thanks (and an upvote) for reminder :) | There are functions to round numbers. For example:
```
var x = 5.0364342423;
print(x.toFixed(2));
```
will print 5.04.
**EDIT:**
[Fiddle](http://jsfiddle.net/TM7DQ/) | How to format a float in javascript? | [
"",
"javascript",
"floating-point",
""
] |
I have on my database a column that holds text in RTF format.
How can I get only the plain text of it, using C#?
Thanks :D | Microsoft provides [an example](http://msdn.microsoft.com/en-us/library/cc488002.aspx) where they basically stick the rtf text in a `RichTextBox` and then read the `.Text` property... it feels somewhat kludgy, but it works.
```
static public string ConvertToText(string rtf)
{
using(RichTextBox rtb = new RichTextBox())
{
rtb.Rtf = rtf;
return rtb.Text;
}
}
``` | for WPF you can use
(using Xceed WPF Toolkit) this extension method :
```
public static string RTFToPlainText(this string s)
{
// for information : default Xceed.Wpf.Toolkit.RichTextBox formatter is RtfFormatter
Xceed.Wpf.Toolkit.RichTextBox rtBox = new Xceed.Wpf.Toolkit.RichTextBox(new System.Windows.Documents.FlowDocument());
rtBox.Text = s;
rtBox.TextFormatter = new Xceed.Wpf.Toolkit.PlainTextFormatter();
return rtBox.Text;
}
``` | Get plain text from an RTF text | [
"",
"c#",
".net",
"rtf",
""
] |
This question is somewhat related to [Hibernate Annotation Placement Question](https://stackoverflow.com/questions/305880/hibernate-annotation-placement-question).
But I want to know which is **better**? Access via properties or access via fields?
What are the advantages and disadvantages of each? | I prefer accessors, since I can add some business logic to my accessors whenever I need.
Here's an example:
```
@Entity
public class Person {
@Column("nickName")
public String getNickName(){
if(this.name != null) return generateFunnyNick(this.name);
else return "John Doe";
}
}
```
Besides, if you throw another libs into the mix (like some JSON-converting lib or BeanMapper or Dozer or other bean mapping/cloning lib based on getter/setter properties) you'll have the guarantee that the lib is in sync with the persistence manager (both use the getter/setter). | There are arguments for both, but most of them stem from certain user requirements "What if you need to add logic for", or "xxxx breaks encapsulation". However, nobody has really commented on the theory, and given a properly reasoned argument.
What is Hibernate/JPA actually doing when it persists an object - well, it is persisting the STATE of the object. That means storing it in a way that it can be easily reproduced.
What is encapsulation? Encapsulations means encapsulating the data (or state) with an interface that the application/client can use to access the data safely - keeping it consistent and valid.
Think of this like MS Word. MS Word maintains a model of the document in memory - the documents STATE. It presents an interface that the user can use to modify the document - a set of buttons, tools, keyboard commands, etc. However, when you persist (Save) that document, it saves the internal state, not the set of keypresses and mouse clicks used to generate it.
Saving the internal state of the object DOES NOT break encapsulation - otherwise, you don't really understand what encapsulation means, and why it exists. It is just like object serialization really.
For this reason, IN MOST CASES, it is appropriate to persist the FIELDS and not the ACCESSORS. This means that an object can be accurately recreated from the database exactly how it was stored. It should not need any validation, because this was done on the original when it was created, and before it was stored in the database (unless, God forbid, you are storing invalid data in the DB!!!!). Likewise, there should be no need to calculate values, as they were already calculated before the object was stored. The object should look just the way it did before it was saved. In fact, by adding additional stuff into the getters/setters you are actually *increasing* the risk that you will recreate something that is not an exact copy of the original.
Of course, this functionality was added for a reason. There may be some valid use cases for persisting the accessors, however, they will typically be rare. An example may be that you want to avoid persisting a calculated value. However, you may want to ask the question why you don't calculate it on demand in the value's getter, or lazily initialize it in the getter. Personally, I cannot think of any good use case, and none of the answers here really give a "Software Engineering" answer. | Hibernate Annotations - Which is better, field or property access? | [
"",
"java",
"hibernate",
"orm",
"jpa",
"annotations",
""
] |
So I'm working on my own little MVC framework as a learning exercise. It's working great, but I want to be able to reference variables in my view files without $this.
So for example I have a controller object which instantiates a view object. From the controller I pass the variables to the view like this
```
$this->view->foo = "bar";
```
Then the view object includes the relevant code for the view (eg: myView.phtml). So to access "foo" in the view file I use this
```
echo $this->foo;
```
But what I would like to do, and I don't know if this is possible or wether I'm missing something obvious, but what I would like to do is reference the variables like this
```
echo $foo;
```
Without me posting the entire source, can anyone point me in the right direction? | If you would like every variable in the view object to be availble inside the view, you could add your variables to a property of the view object that is an array and then use [extract()](http://us.php.net/extract) to make them available:
```
$this->view->variables['foo'] = 'bar';
extract($this->view->variables); // now $foo = 'bar';
```
I'm not a big fan of extract(), but this would accomplish what you are looking for. | You could write some code that parses your html view input and automatically modifies your entries from $foo or [foo] to $this->foo.
So you could put something like this in your html view:
```
<p>[foo]</p>
```
and then have some view code parse the file and change all instances of [foo] to the value of $this->foo. So your output becomes:
```
<p>I'm the foo value</p>
```
Or, you could use something like [Smarty](http://www.smarty.net/) - it does this for you and has many other reasons to use it too. | How can I pass variables to a file included in a class in PHP? | [
"",
"php",
"templates",
"variable-assignment",
""
] |
In this example, what's the regexp to to extract 'first' from location.href, such as:
<http://www.mydomain.com/first/> | Perhaps not an answer to your question, but if you're writing in Javascript, you probably want to use location.pathname rather than extract it yourself from the entire href. | [window.location.pathname](https://developer.mozilla.org/en/DOM/window.location) | How to extract part of location.href in JavaScript? | [
"",
"javascript",
"regex",
""
] |
Friends
In our C++ , Iam current using realloc method to resize the memory allocated by malloc.
realloc() usage is done as below
```
my_Struct *strPtr =(my_struct*)malloc(sizeof(my_Struct));
/* an later */
strPtr = (my_struct*)realloc(strPtr,sizeof(my_Struct)*NBR);
```
now wikipeadia (\_http://en.wikipedia.org/wiki/Malloc)says that
If instead one did
```
void *p = malloc(orig_size);
/* and later... */
p = realloc(p, big_size);
```
then in case it is not possible to obtain big\_size bytes of memory, p will have value NULL and we no longer have a pointer to the memory previously allocated for p, creating a memory leak
And it also says that the correct way to rectify the above error is
```
void *p = malloc(orig_size);
/* and later... */
void *tmp = realloc(p, big_size);
if (tmp != NULL)
{
p = tmp; /* OK, assign new, larger storage to p */
}
else
{
/* handle the problem somehow */
}
```
---
Can you tell me which is the best way to use realloc()
also once I have pointer to a structure and then while using realloc later can i use pointer to a void ???
Many Thanks | Of course you must protect against the case that `realloc()` returns `NULL`. It is a memory allocation, and in C (where `realloc()`) is mostly used, I think C++ programmers think it is a bit low-level/qaint to use raw `realloc()` calls, memory allocations can always fail.
Directly overwriting the pointer with the return value is an error, as that drops the original pointer and makes the memory leak in case the reallocation failed. | Malloc() and realloc() are C functions. Actually, realloc() does malloc() and free() depending on the arguments you pass:
* If you pass it a null pointer, realloc does what malloc does.
* If you pass it a zero size, realloc does what free does.
Quoted from [Here](http://www.ddj.com/cpp/184403806), where you have a deeper explanation.
The C library makes it impossible to expand a memory block in place, so C++ doesn't support it either.
If you want to stick to C functions, then you should hold the pointer of your first memory allocation when calling realloc(). Then you check if it is NULL, otherwise you assign it, just as you did in your latst code.
But maybe for C++ the best solution is to make your own mallocator, the std solution based on C's malloc(). Check [this](http://blogs.msdn.com/vcblog/archive/2008/08/28/the-mallocator.aspx), or [this](http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c4079). | Question on using realloc implementation in C++ code | [
"",
"c++",
"memory-management",
"realloc",
""
] |
I'd like a `floor` function with the syntax
```
int floor(double x);
```
but `std::floor` returns a `double`. Is
```
static_cast <int> (std::floor(x));
```
guaranteed to give me the correct integer, or could I have an off-by-one problem? It seems to work, but I'd like to know for sure.
For bonus points, why the heck does `std::floor` return a `double` in the first place? | The range of double is way greater than the range of 32 or 64 bit integers, which is why `std::floor` returns a `double`. Casting to `int` should be fine so long as it's within the appropriate range - but be aware that a `double` can't represent all 64 bit integers exactly, so you may also end up with errors when you go beyond the point at which the accuracy of `double` is such that the difference between two consecutive doubles is greater than 1. | ```
static_cast <int> (std::floor(x));
```
does pretty much what you want, yes. It gives you the nearest integer, rounded towards -infinity. At least as long as your input is in the range representable by ints.
I'm not sure what you mean by 'adding .5 and whatnot, but it won't have the same effect
And std::floor returns a double because that's the most general. Sometimes you might want to round off a float or double, but preserve the type. That is, round 1.3f to 1.0f, rather than to 1.
That'd be hard to do if std::floor returned an int. (or at least you'd have an extra unnecessary cast in there slowing things down).
If floor only performs the rounding itself, without changing the type, you can cast that to int if/when you need to.
Another reason is that the range of doubles is far greater than that of ints. It may not be possible to round all doubles to ints. | Does casting to an int after std::floor guarantee the right result? | [
"",
"c++",
"math",
"floor",
""
] |
How to use Query cache with ADOdb in PHP? Is it default in ADOdb or Is there any configuration needed ? | Set the cache directory, e.g.
```
$GLOBALS['ADODB_CACHE_DIR']=$_SERVER['DOCUMENT_ROOT'].'/../cache/adodb';
```
Now you can use the Cache\* methods like [CacheGetOne](http://phplens.com/lens/adodb/docs-adodb.htm#cachegetone) to get a cached result
```
$data = $rs->CacheGetOne($seconds_to_cache, $sql);
``` | You can do this:
```
CacheFlush($sql=false,$inputarr=false);
``` | How to use Query cache with ADODB? | [
"",
"php",
"database",
"caching",
"adodb",
""
] |
I am loading a bunch of images for a GUI which will pick attributes for my clients product.
Is it best to pre-load all the images at the start (which I'm guessing would take some time) and then have the GUI have full functionality or is it better to load images on the fly.
Essentially i am working on a picture/poster framing application. I have about 20+ frames that will be able to be selected by the user and when a frame is clicked I change the images for the frame on the display in the GUI.
I am using Jquery. Any insight would be helpful as to the best case scenario for this.
And if I will be pre-loading all the images how do I put one of those loading bars on the screen like you see in Flash or a loading gif like i've seen in Ajax?
Thanks
Mike | Why not do both?
You can load images lazily, but also hook `$(document).ready()` to pre-load the images. That way, if the user accesses an image before it's preloaded, it comes in then; if the user waits long enough it will be instantaneous.
This technique is common with things like menubar roll-overs. | Depends on frame images' size...if they are small like 1 - 2K, I'd load the images dynamicaly, otherwise you can preload, but be sure to set the headers right so only once are read and fetched from cache next time.
As for progress bar, I suggest you check this article (talks about preloading images in jQuery and includes progress bar) on [Ajaxian](http://ajaxian.com/archives/preloading-images-with-jquery). | Jquery Best Case Scenario | [
"",
"javascript",
"jquery",
"image-preloader",
""
] |
I'm designing a database schema, and I'm wondering what criteria I should use for deciding whether each column should be `nullable` or not.
Should I mark as NOT NULL only those columns that absolutely *must* be filled out for a row to make any sense at all to my application?
Or should I mark all columns that I intend to never be null?
What are the performance implications of small vs large numbers of NOT NULL columns?
I assume lots of NOT NULL columns would slow down inserts a bit, but it might actually speed up selects, since the query execution plan generator has more information about the columns..
Can someone with more knowledge than me give me the low-down? | Honestly, I've always thought NOT NULL should be the default. NULL is the odd special case, and you should make a case for it whenever you use it. Plus it's much easier to change a column from NOT NULL to nullable than it is to go the other way. | There are no significant performance consequences. Don't even think about considering this as an issue. To do so is a huge early optimization antipattern.
"Should I only mark as NOT NULL only those columns that absolutely must be filled out for a row to make any sense at all to my application?"
Yes. It's as simple as that. You're a lot better off with a NULLable column without any NULL values in it, than with the need for NULLs and having to fake it. And anyway, any ambiguous cases are better filtered out in your Business Rules.
---
EDIT:
There's another argument for nullable fields that I think is ultimately the most compelling, which is the Use Case argument. We've all been subject to data entry forms that require values for some fields; and we've all abandoned forms where we had no sensible values for required fields. Ultimately, the application, the form, and the database design are only defensible if they reflect the user requirements; and it's clear that there are many, many database columns for which users can present no value - sometimes at given points in the business process, sometimes ever. | How liberal should I be with NOT NULL columns? | [
"",
"sql",
"sql-server",
"schema",
"nullable",
""
] |
I'm building a pacman game. Basically, I want to have a map representation of this window consisting of blocks/tiles. Then as the pacman character/ghost moves i would change their position on the map to represent what's on the screen, and use that for collision detection etc.
How can I build this map, especially since the screen is made of x,y coordinates, so how can I correctly represent them in tiles/on this map? | I know it's tempting to start thinking of objects and interfaces but have you thought about a 2-dimensional array with each element representing 40 pixels or something? I don't remember pacman being pixel accurate when it came to collision, more a question of the direction each piece was moving in. | Generally you have an abstract representation that doesn't reference pixels as such (for example, maybe the Pac-Man maze is simply w units wide), and then you have a linear transformation (you know, y = mx + b) to carry the abstract representation to actual pixels.
To make it concrete, let's say that you want your abstract representation to be 100 units wide, and you want to render it as 400 pixels. Then the transformation is just scrn\_x = 4 \* x. | How to represent a 400x400 window as a map in a Java game? | [
"",
"java",
"2d",
"maps",
""
] |
I've both the jquery-UI Tabs & [jcarousel lite plugin](http://www.gmarwaha.com/jquery/jcarousellite/demo.php) in my webpage, all works good in all browsers apart from IE where i assume there's some sort of conflict as if i take out the jcarousel JS then the tabs works fine.
Has anyone got any suggestion on this issue or how to fix it? Thanks
```
<script type="text/javascript">
$(document).ready(function() {
$('#tabs > ul').tabs({
fx: { opacity: 'toggle' }
});
$("#carousel").jCarouselLite({
btnNext: ".prev",
btnPrev: ".next",
visible: 4,
});
});
</script>
``` | Found out is was simply the comma at the end of "visible: 4," needed to be taken out. | [](https://i.stack.imgur.com/IwFIp.png)
(source: [stackoverflow.com](http://i.stackoverflow.com/Content/Img/stackoverflow-logo-250.png)) Nise Code for jquery
$(function() {
$(".mouseWheel .jCarouselLite").jCarouselLite({
btnNext: ".mouseWheel .next",
btnPrev: ".mouseWheel .prev",
easing: "easeinout",
visible: 4,
mouseWheel: true
});
});
$(function() {
$(".anyClass2").jCarouselLite({
btnNext: ".next2",
btnPrev: ".prev2"
});
}); | Jquery UI Tabs & jcarousel lite pluings does not seem to work (conflict) in Internet Explorer (IE) | [
"",
"javascript",
"jquery",
"jquery-ui",
"jquery-ui-tabs",
"jcarousellite",
""
] |
Does CoCreateInstance automatically calls AddRef on the interface I'm creating or should I call it manually afterwards? | The contract with COM is anytime you are handed an object from a function like this, such as CoCreateInstance(), QueryInterface() (which is what CoCreateInstance() ultimately calls), etc, the callee always calls AddRef() before returning, and the caller (you) always Release() when you are done.
You can use CComPtr<> to make this simpler, and it just does the right thing.
Now if you need to hand this pointer out to another object that expects it to be usable beyond the lifetime of your object, then you need to call AddRef() before giving it out.
I recommend [Essential COM by Don Box](https://rads.stackoverflow.com/amzn/click/com/0201634465) for further reading on this topic. | In short: **No**.
You **don't** need to call [AddRef](http://msdn.microsoft.com/en-us/library/ms691379(VS.85).aspx) in your code.
A reference counter which **COM object** has is 1 after [CoCreateInstance](http://msdn.microsoft.com/en-us/library/ms686615.aspx).
So, if you call [Release](http://msdn.microsoft.com/en-us/library/ms682317(VS.85).aspx), the reference counter will be 0 and COM object will be disposed. | In COM: should I call AddRef after CoCreateInstance? | [
"",
"c++",
"com",
""
] |
I want to light up/off LEDs without a microcontroller. I'm looking to control the LEDs by writing a C++ program. but the problem im having is hooking them up is there a free way to do !!!!
I'm using Windows XP if that is relevant.
I have LEDs but I don't have a microcontroller.
Well, I found some functions but their headers are not working, so can someone help me find headers?
Here is an example of what I'm talking about:
```
poke(0x0000,0x0417,16);
gotoxy(1,1);
printf("Num Lock LED is now on r");
delay(10);
```
Also, does anyone have a "Kernel Programming" eBook?
I also need a circuit diagram to show where to hook up the LEDs. | That completely depends on which hardware you have, which determines which driver you need. Back then, i got a simple led and put it into the printer LPT port. Then i could write a byte to address 0x0378h and the bits in it determined whether a pin had power or not (using linux). For windows, you need a driver that allows you to access the lpt port directly. I did it with a friend back then too, and it worked nicely (we built up a traffic light :)) Read [this page](http://logix4u.net/) (click on Parallel Port on the left. For some reason, i cannot link directly to it) for details on windows. And read `man outb` on linux. Now, that Port is really old. But if you have some machine around that still got one, i think it's a lot of fun to play with it.
Anyway, i've got a fritz box that has a neat LED. One can connect to it via `telnet` and then write something (i forgot the numbers) into `/proc/led` iirc. A kernel driver then interprets the number and makes the right LED blink. That's another way of doing it :) | Playing with microcontrollers is fun. The [arduino](http://www.arduino.cc/) is an open source board with nice development tools.
Some boards [like this one](http://www.moderndevice.com/) start at around $15 | How to hook up LED lights in C++ without microcontroller? | [
"",
"c++",
"led",
""
] |
When / what are the conditions when a `JSESSIONID` is created?
Is it per a domain? For instance, if I have a Tomcat app server, and I deploy multiple web applications, will a different `JSESSIONID` be created per context (web application), or is it shared across web applications as long as they are the same domain? | JSESSIONID cookie is created/sent when session is created. Session is created when your code calls `request.getSession()` or `request.getSession(true)` for the first time. If you just want to get the session, but not create it if it doesn't exist, use `request.getSession(false)` -- this will return you a session or `null`. In this case, new session is not created, and JSESSIONID cookie is not sent. (This also means that **session isn't necessarily created on first request**... you and your code are in control *when* the session is created)
Sessions are per-context:
> SRV.7.3 Session Scope
>
> HttpSession objects must be scoped at
> the application (or servlet context)
> level. The underlying mechanism, such
> as the cookie used to establish the
> session, can be the same for different
> contexts, but the object referenced,
> including the attributes in that
> object, must never be shared between
> contexts by the container.
([Servlet 2.4 specification](http://jcp.org/aboutJava/communityprocess/final/jsr154/index.html))
Update: Every call to JSP page implicitly creates a new session if there is no session yet. This can be turned off with the `session='false'` page directive, in which case session variable is not available on JSP page at all. | Here is some information about one more source of the `JSESSIONID` cookie:
I was just debugging some Java code that runs on a tomcat server. I was not calling `request.getSession()` explicitly anywhere in my code but I noticed that a `JSESSIONID` cookie was still being set.
I finally took a look at the generated Java code corresponding to a JSP in the work directory under Tomcat.
It appears that, whether you like it or not, if you invoke a JSP from a servlet, `JSESSIONID` will get created!
Added: I just found that by adding the following JSP directive:
```
<%@ page session="false" %>
```
you can disable the setting of `JSESSIONID` by a JSP. | Under what conditions is a JSESSIONID created? | [
"",
"java",
"jsessionid",
""
] |
I'm trying to use the BufferedImage class in AWT. I'm using J2ME on IBM's J9 virtual machine.
When I try and call the BufferedImge.getRastor() method I get the following exception:
```
Exception in thread "main" java.lang.NoSuchMethodError: java/awt/image/BufferedImage.getRastor()Ljava/awt/image/WritableRaster;
```
Now, from what I know about the JVM that error is basically telling me that the BufferedImage class does not have a method called getRastor() which returns a WritableRaster object, however this method is documented in the API and it's from version 1.4.2 so should be compatable with J2ME.
I have no idea what is going on here, can you help?
Cheers,
Pete | You won't be able to use anything from AWT in J2ME since its not supported.
That happens because J2ME doesn't have AWT. AWT is intended to be used in desktop applications (Java SE), with a different user model and functionalities.
You can take a look at J2ME docs [here](http://java.sun.com/javame/reference/apis.jsp)
J2ME uses a different approach regarding GUIs, you may use the high level abstraction API (FORMS) and the low level API (CANVAS). | I don't think this is your answer... but since you quoted your exception and I assume you cut and pasted it, I'll try to help.
Isn't the method:
```
getRaster
```
not
```
getRastor
```
?
*(sorry if this is not what it is ailing you...)* | Java AWT - BufferedImage problems when using J2ME and J9 | [
"",
"java",
"exception",
"awt",
""
] |
I am using a library that consists almost entirely of **templated classes and functions in header files**, like this:
```
// foo.h
template<class T>
class Foo {
Foo(){}
void computeXYZ() { /* heavy code */ }
};
template<class T>
void processFoo(const Foo<T>& foo) { /* more heavy code */ }
```
Now this is bad because **compile times are unbearable** whenever I include one of those header files (and actually I include many of them in each of my compilation units).
Since as a template parameter I only use one or two types anyway I am planning to create, for each library header file, **a file that contains only declarations**, without the heavy code, like this:
```
// NEW: fwd-foo.h
template<class T>
class Foo {
Foo();
void computeXYZ();
};
template<class T>
void processFoo(const Foo<T>& foo);
```
And then one file that creates all the instantiations that I'll need. That file can be **compiled separately once and for all**:
```
// NEW: foo.cpp
#include "foo.h"
template class Foo<int>;
template class Foo<double>;
template void processFoo(const Foo<int>& foo);
template void processFoo(const Foo<double>& foo);
```
Now I can just include `fwd-foo.h` in my code and have short compile times. I'll link against `foo.o` at the end.
The downside, of course, is that I have to create these new `fwd-foo.h` and `foo.cpp` files myself. And of course it's a maintenance problem: When a new library version is released I have to adapt them to that new version. Are there any other downsides?
And my main question is:
Is there any chance I can create these new files, especially `fwd-foo.h`, **automatically** from the original `foo.h`? I have to do this for many library header files (maybe 20 or so), and an automatic solution would be best especially in case a new library version is released and I have to do this again with the new version. Are any tools available for this task?
**EDIT:**
Additional question: How can the newly supported `extern` keyword help me in this case? | We use [lzz](http://www.lazycplusplus.com) which splits out a single file into a separate header and translation unit. By default, it would normally put the template definitions into the header too, however, you can specify that you don't want this to happen.
To show you how you might use it consider the following:
```
// t.cc
#include "b.h"
#include "c.h"
template <typename T>
class A {
void foo () {
C c;
c.foo ();
b.foo ();
}
B b;
}
```
Take the above file and copy it to 't.lzz' file. Place any *#include* directives into separate $hdr and $src blocks as necessary:
```
// t.lzz
$hdr
#include "b.h"
$end
$src
#include "c.h"
$end
template <typename T>
class A {
void foo () {
C c;
c.foo ();
b.foo ();
}
B b;
}
```
Now finally, run lzz over the file specifying that it places the template definitions into the source file. You can either do this using a *$pragma* in the source file, or you can use the command line option "-ts":
This will result in the following files being generated:
```
// t.h
//
#ifndef LZZ_t_h
#define LZZ_t_h
#include "b.h"
#undef LZZ_INLINE
#ifdef LZZ_ENABLE_INLINE
#define LZZ_INLINE inline
#else
#define LZZ_INLINE
#endif
template <typename T>
class A
{
void foo ();
B b;
};
#undef LZZ_INLINE
#endif
```
And:
```
// t.cpp
//
#include "t.h"
#include "c.h"
#define LZZ_INLINE inline
template <typename T>
void A <T>::foo ()
{
C c;
c.foo ();
b.foo ();
}
#undef LZZ_INLINE
```
You can then run these through some grep/sed commands to remove the LZZ helper macros. | Try using precompiled headers. I know GCC and MSVC support this feature. Usage is vender-specific, though. | Automatically separate class definitions from declarations? | [
"",
"c++",
"templates",
"compilation",
"declaration",
"instantiation",
""
] |
i'm doing a test how hash and salt passwords.
Well , i can add hash and salt password to the Database but i got stuck to store passwords from database.
i have a simple Database :
```
Table
_______
ProvaHS
--------
(PK) LoginID int
UserName nvarchar(50)
Password nvarchar(50)
Salt nvarchar(50)
```
So i create a form to add new record to the database with this code:
```
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
#region SALT
public static class PasswordCrypto
{
private static SHA1CryptoServiceProvider Hasher = new SHA1CryptoServiceProvider();
//Private Hasher As New MD5CryptoServiceProvider()
static internal string GetSalt(int saltSize)
{
byte[] buffer = new byte[saltSize + 1];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(buffer);
return Convert.ToBase64String(buffer);
}
static internal string HashEncryptString(string s)
{
byte[] clearBytes = Encoding.UTF8.GetBytes(s);
byte[] hashedBytes = Hasher.ComputeHash(clearBytes);
return Convert.ToBase64String(hashedBytes);
}
static internal string HashEncryptStringWithSalt(string s, string salt)
{
return HashEncryptString(salt + s);
}
}
#endregion
private void GetSalt()
{
this.textBoxSalt.Text = PasswordCrypto.GetSalt(16);
}
private void GetSaltHash()
{
// It's how i salt and hash the password before to save it to the Database
this.textBoxPassword.Text = PasswordCrypto.HashEncryptStringWithSalt(this.textBoxClear.Text, this.textBoxSalt.Text);
}
private void GetHash()
{
//Demo purposes -- this is an unsalted hash
this.textBoxClear.Text = PasswordCrypto.HashEncryptString(this.textBoxPassword.Text);
}
private void Add(object sender, RoutedEventArgs e)
{
DataClasses1DataContext dc = new DataClasses1DataContext();
try
{
if (textBoxUserName.Text.Length > 0)
{
ProvaH tab = new ProvaH();
tab.UserName = textBoxUserName.Text;
tab.Password = textBoxPassword.Text;
tab.Salt = textBoxSalt.Text;
dc.ProvaHs.InsertOnSubmit(tab);
dc.SubmitChanges();
}
}
catch (Exception ex)
{
MessageBox.Show("Error!!!");
}
}
private void HashButton(object sender, RoutedEventArgs e)
{
GetHash();
}
private void SaltButton(object sender, RoutedEventArgs e)
{
GetSalt();
}
private void HashSaltButton(object sender, RoutedEventArgs e)
{
GetSaltHash();
}
private void Close_W(object sender, RoutedEventArgs e)
{
this.Close();
}
}
```
}
* with this method i can salt,hash and save password to the database..(following advices StackOverflow's member ) thanks..
Now i'm testing how store password from the database and here i got a trouble...
```
public partial class Login : Window
{
public Login()
{
InitializeComponent();
}
#region SALT
public static class PasswordCrypto
{
private static SHA1CryptoServiceProvider Hasher = new SHA1CryptoServiceProvider();
//Private Hasher As New MD5CryptoServiceProvider()
static internal string GetSalt(int saltSize)
{
byte[] buffer = new byte[saltSize + 1];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(buffer);
return Convert.ToBase64String(buffer);
}
static internal string HashEncryptString(string s)
{
byte[] clearBytes = Encoding.UTF8.GetBytes(s);
byte[] hashedBytes = Hasher.ComputeHash(clearBytes);
return Convert.ToBase64String(hashedBytes);
}
static internal string HashEncryptStringWithSalt(string s, string salt)
{
return HashEncryptString(salt + s);
}
}
#endregion
private void closs(object sender, RoutedEventArgs e)
{
this.Close();
}
public bool ValidateApplicationUser(string userName, string password)
{
bool OK = false;
DataClasses1DataContext dc = new DataClasses1DataContext();
object saltValue = from c in dc.ProvaHs where c.UserName == userName select c.Salt;
if (!(saltValue == System.DBNull.Value))
{
password = PasswordCrypto.HashEncryptStringWithSalt(passwordTextBox.Password, saltValue.ToString());
}
var query = from c in dc.ProvaHs where c.UserName == userName && c.Password == password select new { c.LoginID, c.UserName, c.Password };
if (query.Count() != 0)
{
return true;
}
return false;
}
private void Confirm(object sender, RoutedEventArgs e)
{
bool authenticated = true;
if (usernameTextBox.Text != "" && passwordTextBox.Password.ToString() != "")
{
authenticated = ValidateApplicationUser(usernameTextBox.Text, passwordTextBox.Password.ToString());
}
if (!authenticated)
{
MessageBox.Show("Invalid login. Try again.");
}
else
{
MessageBox.Show("Aaaaahhhh.JOB DONE!!!!....");
}
}
}
```
when i debug the application i receive always an error at this code line :
if (query.Count() != 0) in "query" = Empty :"Enumeration yielded no results"
Do you have any suggest how work out this error and store password from database in my case?
Thanks | Try:
```
public bool ValidateApplicationUser(string userName, string password)
{
DataClasses1DataContext dc = new DataClasses1DataContext();
var saltValue = dc.ProvaHs.Where(c => c.UserName == userName)
.Select(c => c.Salt)
.SingleOrDefault();
if (saltValue == null) return false;
password = PasswordCrypto.HashEncryptStringWithSalt(passwordTextBox.Password, saltValue.ToString());
return dc.ProvaHs.Any(c => c.UserName == userName && c.Password == password);
}
``` | Don't use SHA1. Use SHA256, real random salt, and lots (ie. 8000) of SHA256 iterations. Because SHA is designed for speed, but that means that dictionary attack is fast. There are also better ways, like scrypt algorithm. Or SRP protocol. | Trying to store password to database | [
"",
"c#",
".net",
"database",
"linq-to-sql",
""
] |
What is the *worst* **real-world** macros/pre-processor abuse you've ever come across (please no contrived IOCCC answers \*haha\*)?
Please add a short snippet or story if it is really entertaining. The goal is to teach something instead of always telling people "never use macros".
---
p.s.: I've used macros before... but usually I get rid of them eventually when I have a "real" solution (even if the real solution is inlined so it becomes similar to a macro).
---
**Bonus:** Give an example where the macro was really was better than a not-macro solution.
**Related question:** [When are C++ macros beneficial?](https://stackoverflow.com/questions/96196/when-are-c-macros-beneficial) | From memory, it looked something like this:
```
#define RETURN(result) return (result);}
int myfunction1(args) {
int x = 0;
// do something
RETURN(x)
int myfunction2(args) {
int y = 0;
// do something
RETURN(y)
int myfunction3(args) {
int z = 0;
// do something
RETURN(z)
```
Yes that's right, no closing braces in any of the functions. Syntax highlighting was a mess, so he used vi to edit (not vim, it has syntax coloring!)
He was a Russian programmer who had mostly worked in assembly language. He was fanatical about saving as many bytes as possible because he had previously worked on systems with very limited memory. "It was for satellite. Only very few byte, so we use each byte over for many things." (bit fiddling, reusing machine instruction bytes for their numeric values) When I tried to find out what kinds of satellites, I was only able to get "Orbiting satellite. For making to orbit."
He had two other quirks: A convex mirror mounted above his monitor "For knowing who is watching", and an occasional sudden exit from his chair to do a quick ten pushups. He explained this last one as "Compiler found error in code. This is punishment". | My worst:
```
#define InterlockedIncrement(x) (x)++
#define InterlockedDecrement(x) (x)--
```
I spent two days of my life tracking down some multi-threaded COM ref-counting issue because some idiot put this in a header file. I won't mention the company I worked for at the time.
The moral of this story? If you don't understand something, read the documentation and learn about it. Don't just make it go away. | What is the worst real-world macros/pre-processor abuse you've ever come across? | [
"",
"c++",
"c",
"macros",
"preprocessor",
""
] |
> **Possible Duplicate:**
> [Convert HTML to PDF in .NET](https://stackoverflow.com/questions/564650/convert-html-to-pdf-in-net)
In our applications we make html documents as reports and exports.
But now our customer wants a button that saves that document on their pc. The problem is that the document includes images.
You can create a word document with the following code:
```
private void WriteWordDoc(string docName)
{
Response.Buffer = true;
Response.ContentType = "application/msword";
Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.doc", docName.Replace(" ", "_")));
Response.Charset = "utf-8";
}
```
But the problem is that the images are just links an thus not embedded in the word document.
Therefore I'm looking for an alternative
PDF seems to be a good alternative, does anyone know a good pdf writer for C#?
One that has some good references and has been tested properly? | I would opt for creating a PDF file on the server. There are many products that do so but you should research the one that works best in your case considering the following:
* Computer resources needed to create the PDF. If it's a complex document it may take too long and or slow down the response to other users.
* Number of concurrent users that will require this same function
* Cost (there are free solutions as well as heavy weight commercial products).
I would not rely on Word format for that as PDF will give you some more guarantee that it will be readable in the future.
Also, the option of embedding hard links to the images don't seem a good idea to me. What if the user wants to open the document and the server is not accessible? | You have a bigger problem... saving the file generated is the prerogative of the browser. How the browser deals with any particular file stream, even when you set the content type, is entirely up to the browser. Your best bet is probably to use something like ABCpdf to convert the HTML/images into a PDF. I've had pretty good luck with their software, and they have decent support. Of course, this is a third party tool you'll have to install. Without doing that, your next best option is probably to create a zip of the HTML with images and other files (CSS, javascript?)... but that is going to take quite a bit of back-end logic.
Some browsers have this feature built-in. You could ask your users to use that. :) | Export from HTML to PDF (C#) | [
"",
"c#",
"asp.net",
"html",
"export",
""
] |
On line:
```
private boolean someFlag;
```
I get the following PMD warning:
> Found non-transient, non-static member. Please mark as transient or provide accessors.
Can someone please explain why this warning is there and what it means? (I understand how to fix it, I don't understand why it's there...)
I'm getting this on many other member declarations as well...
---
**EDIT:** My class is *definitely* not a bean, and not serializable... | I assume your class is a bean that by definition implements `Serializable`. A transient variable will be excluded from the serialization process. If you serialize and then deserialize the bean the value will be actually have the default value.
PMD assumes you are dealing with a serializable bean here. For a bean it is expected to have getters/setters for all member variables. As you have omitted these, you imply that your member variable is not part of the bean ....and so does not need to be serialized. If that is the case you should exclude it from the serialization. Which you do by marking the variable as "transient". | Now I get it.
After adding this definition:
```
private boolean someFlag;
```
...it is clear what happens here:
This error message does refer to the accessing schema. PMD states that classes referred to by beans, must also follow the bean schema.
Most likely to support property-style access like `MyBean.referredClass.someFlag` will be translated to `someObject.getReferredClass().getSomeFlag()`
PMD it expects that there is a `isSomeFlag/getSomeFlag` and `setSomeFlag` method by which you could access its value, and not access it directly.
```
Found non-transient, non-static member. Please mark as transient **or provide accessors**.
``` | Java PMD warning on non-transient class member | [
"",
"java",
"coding-style",
"javabeans",
"pmd",
""
] |
In the Solution Explorer when working with C++ projects there is the standard filters of Header Files, Resource Files, and Source Files. What I'm wanting to accomplish is essentially Filters by folder.
---
Lets say the structure of the files was like this:
* ../Folder1/Source1.cpp
* ../Folder1/Header1.h
* ../Folder1/Source2.cpp
* ../Folder1/Header2.h
* ../AnotherFolder/Source1.cpp
* ../AnotherFolder/Header1.h
* ../AnotherFolder/Source2.cpp
* ../AnotherFolder/Header2.h
* ../SomeOtherSource.cpp
In the Solution Explorer, it would look like:
* Header Files/Header1.h
* Header Files/Header1.h
* Header Files/Header2.h
* Header Files/Header2.h
* Source Files/SomeOtherSource.cpp
* Source Files/Source1.cpp
* Source Files/Source1.cpp
* Source Files/Source2.cpp
* Source Files/Source2.cpp
And I would like to have it look like this:
* Header Files/AnotherFolder/Header1.h
* Header Files/AnotherFolder/Header2.h
* Header Files/Folder1/Header1.h
* Header Files/Folder1/Header2.h
* Source Files/AnotherFolder/Source1.cpp
* Source Files/AnotherFolder/Source2.cpp
* Source Files/Folder1/Source1.cpp
* Source Files/Folder1/Source2.cpp
* Source Files/SomeOtherSource.cpp
---
How would this be accomplished? | You are free to manually create folders yourself and move the files around. I agree this is a much more convenient way to arrange files but AFAIK there is no way to make VS do this automatically. | You can create the Visual Studio Plugin to do this.
I am not sure how you can access "Solution Explorer" programatically. | Microsoft Visual Studio (2008) - Filters in the Solution Explorer | [
"",
"c++",
"visual-studio",
"visual-studio-2008",
"visual-c++",
"solution-explorer",
""
] |
I have Java classes with the following structure (the class names do not imply anything, I was just making them up).
```
package test;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
@XmlRootElement
public class Test
{
@XmlAccessorType(XmlAccessType.FIELD)
static class Machine
{
@XmlElementWrapper(name="servers")
@XmlElement(name="server")
List<Server> servers = new ArrayList<Server>();
}
@XmlAccessorType(XmlAccessType.FIELD)
static class Server
{
Threshold t = new Threshold();
}
@XmlAccessorType(XmlAccessType.FIELD)
static class Threshold
{
RateThreshold load = new RateThreshold();
}
@XmlAccessorType(XmlAccessType.FIELD)
static class RateThreshold
{
@XmlAccessorType(XmlAccessType.FIELD)
static class Rate
{
int count;
Period period = new Period();
}
@XmlAccessorType(XmlAccessType.FIELD)
private static class Period
{
@XmlAttribute
private String type = "second";
@XmlValue
private float period;
}
Rate min = new Rate();
Rate max = new Rate();
}
@XmlElementWrapper(name="machines")
@XmlElement(name="machine")
List<Machine> machines = new ArrayList<Machine>();
public static void main(String[] args)
{
Machine m = new Machine();
Server s = new Server();
s.t.load.max.count = 10;
s.t.load.min.count = 1;
m.servers.add(s);
Test t = new Test();
t.machines.add(m);
JAXBContext jaxbContext;
Marshaller marshaller;
try
{
jaxbContext = JAXBContext.newInstance(Test.class);
marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(t, System.out);
}
catch (JAXBException e)
{
e.printStackTrace();
}
}
}
```
The problem I am having is with the XML output generated by JAXB when marshalling a Test instance. The XML output would always look like the following:
```
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<test>
<machines>
<machine>
<servers>
<server>
<t>
<load>
<min>
<count>1</count>
<period type="second">0.0</period>
</min>
<max>
<count>10</count>
<period type="second">0.0</period>
</max>
</load>
</t>
</server>
</servers>
</machine>
</machines>
</test>
```
As you can see, some elements are not being indented properly (that is, the deepest elements, count and period). Why is that? Is there something wrong with the way I created the JAXB context? Or is there a maximum limit to how many elements that can be indented recursively by JAXB? How could I fix this? Note that I have also set JAXB\_FORMATTED\_OUTPUT to true, but still get the improper indentation.
Thanks. | Indenting occurs modulo 8, in
```
com.sun.xml.bind.v2.runtime.output.IndentingUTF8XmlOutput
```
you find
```
int i = depth%8;
``` | One of the overloads of the `marshal()` method of the marshaler accepts an XMLStreamWriter, so you can bypass the brain-damaged formatting mechanism of the Reference Implementation of JAXB by writing your own formatting XML stream writer. You would end up doing something like this:
```
public static void SaveContainer( Container container, OutputStream stream ) throws ...
{
XMLOutputFactory factory = XMLOutputFactory.newInstance();
XMLStreamWriter writer = factory.createXMLStreamWriter( stream, "UTF-8" );
writer = new MyAwesomeCoolFormattingXMLStreamWriter( writer );
marshaller.marshal( container, writer );
}
``` | JAXB XML output format questions | [
"",
"java",
"xml",
"jaxb",
""
] |
I am in the process of converting my Tournament Organizer software, which allows the creation and manipulation of Double Elimination Tournaments, to use the MVVM design pattern so that it can be more easily tested. In doing so, I'm separating out the 'model' from some code in the UI that directly manipulates the bracket structure.
This will be the third iteration of software I've written to handle tournaments. The first was written in PHP and stored the data in a database. The second version is the WPF version I made, and it stores the data in memory, and then serializes it to an XML file. However, in both versions, there are aspects of the implementation that I feel aren't clean, and seem like they break the law of DRY.
**If you were creating a data structure from scratch to handle double elimination brackets, how would you do it?**
Note that it doesn't need to be able to automatically generate the brackets algorithmically (loading from a pre-made double-elimination with 4/8/16/32 people is how I'm doing it now), just the main use case of setting winners of matches and 'advancing' them through the bracket.
Edit: To make it clear, the data structure needs to handle double elimination tournaments, so potentially, the winner of one match could end up competing against the loser of another. | My solution to this was to have two sets of data structures. One for the bracket part, and one for the seats.
```
class Match
{
string Id;
MatchSeat red;
MatchSeat blue;
MatchSeat winner;
MatchSeat loser;
}
class MatchSeat
{
string Id;
Entry Entry;
}
```
And then to set it up, I made some helper functions that took the bracket information and built the structures.
```
{ "1", "seed1", "seed4", "W1", "L1" },
{ "2", "seed2", "seed3", "W2", "L2" },
{ "3", "W1", "W2", "W3", "L3" },
{ "4", "L1", "L2", "W4", "L4" },
{ "5", "W4", "L3", "W5", "L5" },
{ "F", "W3", "W5", "WF", "WF" }
```
Then when the seeds and winners/losers are filled out, the value only gets set in one place. | So, at the end points, you have 64 teams. So there's a collection, somehow, of 64 Teams.
But they're paired off, and for each pair, there's a winner. And in the middle brackets, that winner actually emerged from a bracket, so I think your bracket object actually looks like:
```
public class Bracket
{
Team winner; //if this is null or whatever, then we don't have a winner yet
Bracket topBracket;
Bracket bottomBracket;
}
```
...and when you're instantiating your ends, you'd just leave the two sub-Brackets null, with only a winner.
To handle double-elimination, there's a second bracket, which is a losers bracket. It would be nice if you could automatically handle the addition of losers into this bracket (design a bracket that starts with 32, who play down to 16, add in the 16 losers from winner bracket round 2, etc.) but that's all implementation. The data structure doesn't need to change to accommodate that, you just need more of them. | Data structure for Double Elmination Tournament | [
"",
"c#",
"data-structures",
"mvvm",
"tdd",
"tournament",
""
] |
Microsoft has naming guidelines on their website ([here](http://msdn.microsoft.com/en-us/library/xzf533w0(VS.71).aspx)). Also I have the Framework Design Guidelines book.
What I could not find was a guideline about naming controls.
For example, a button, when dropped to a form, gets the typename + number, camel-cased as default name, such as "button1".
This is what I do: I delete the number and add a meaningful description after. For example "buttonDelete" or "buttonSave".
This way you do not have to maintain a big list of controls and their abbreviated names in a guideline somewhere.
Do you agree? | I don't have a convention as such, but I do try to be very broad with the 'type' portion of the name. e.g. Button, Link Button, Image Button tend to be named 'somethingButton'. Combo boxes, radio button lists all end up as 'somethingSelector'. TextBoxes and Calendars are 'somethingInput'. That way I get a rough idea of what sort of control it is without the name being tied to the actual implementation. If I decide to replace an option button group with a dropdown then no need to rename! | Here are some common ones:
```
frm Form
mnu Form menu
cmd Command button
chk Check button
opt Radio button
lbl Text label
txt Text edit box
pb Picture box
pic Picture
lst List box
cbo Combo box
tmr Timer
```
A longer list is at *[INFO: Object Hungarian Notation Naming Conventions for VB](http://support.microsoft.com/kb/173738)*. | Naming convention for controls | [
"",
"c#",
".net",
"naming-conventions",
""
] |
If I have a function :
```
@aDecorator
def myfunc1():
# do something here
if __name__ = "__main__":
# this will call the function and will use the decorator @aDecorator
myfunc1()
# now I want the @aDecorator to be replaced with the decorator @otherDecorator
# so that when this code executes, the function no longer goes through
# @aDecorator, but instead through @otherDecorator. How can I do this?
myfunc1()
```
Is it possible to replace a decorator at runtime? | I don't know if there's a way to "replace" a decorator once it has been applied, but I guess that probably there's not, because the function has already been changed.
You might, anyway, apply a decorator at runtime based on some condition:
```
#!/usr/bin/env python
class PrintCallInfo:
def __init__(self,f):
self.f = f
def __call__(self,*args,**kwargs):
print "-->",self.f.__name__,args,kwargs
r = self.f(*args,**kwargs)
print "<--",self.f.__name__,"returned: ",r
return r
# the condition to modify the function...
some_condition=True
def my_decorator(f):
if (some_condition): # modify the function
return PrintCallInfo(f)
else: # leave it as it is
return f
@my_decorator
def foo():
print "foo"
@my_decorator
def bar(s):
print "hello",s
return s
@my_decorator
def foobar(x=1,y=2):
print x,y
return x + y
foo()
bar("world")
foobar(y=5)
``` | As Miya mentioned, you can replace the decorator with another function any point before the interpreter gets to that function declaration. However, once the decorator is applied to the function, I don't think there is a way to dynamically replace the decorator with a different one. So for example:
```
@aDecorator
def myfunc1():
pass
# Oops! I didn't want that decorator after all!
myfunc1 = bDecorator(myfunc1)
```
Won't work, because myfunc1 is no longer the function you originally defined; it has already been wrapped. The best approach here is to manually apply the decorators, oldskool-style, i.e:
```
def myfunc1():
pass
myfunc2 = aDecorator(myfunc1)
myfunc3 = bDecorator(myfunc1)
```
Edit: Or, to be a little clearer,
```
def _tempFunc():
pass
myfunc1 = aDecorator(_tempFunc)
myfunc1()
myfunc1 = bDecorator(_tempFunc)
myfunc1()
``` | Is it possible to replace a Python function/method decorator at runtime? | [
"",
"python",
"runtime",
"language-features",
"decorator",
""
] |
I know how to get an intersection of two flat lists:
```
b1 = [1,2,3,4,5,9,11,15]
b2 = [4,5,6,7,8]
b3 = [val for val in b1 if val in b2]
```
or
```
def intersect(a, b):
return list(set(a) & set(b))
print intersect(b1, b2)
```
But when I have to find intersection for nested lists then my problems starts:
```
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
```
In the end I would like to receive:
```
c3 = [[13,32],[7,13,28],[1,6]]
```
Can you guys give me a hand with this?
### Related
* [Flattening a shallow list in python](https://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python) | **If you want:**
```
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
c3 = [[13, 32], [7, 13, 28], [1,6]]
```
**Then here is your solution for Python 2:**
```
c3 = [filter(lambda x: x in c1, sublist) for sublist in c2]
```
**In Python 3 `filter` returns an iterable instead of `list`, so you need to wrap `filter` calls with `list()`:**
```
c3 = [list(filter(lambda x: x in c1, sublist)) for sublist in c2]
```
**Explanation:**
The filter part takes each sublist's item and checks to see if it is in the source list c1.
The list comprehension is executed for each sublist in c2. | You don't need to define intersection. It's already a first-class part of set.
```
>>> b1 = [1,2,3,4,5,9,11,15]
>>> b2 = [4,5,6,7,8]
>>> set(b1).intersection(b2)
set([4, 5])
``` | Find intersection of two nested lists? | [
"",
"python",
"list",
"intersection",
""
] |
What's your favorite way of testing javascript code snippets?
I like to use the browser's address field directly:
```
javascript:void(document.getElementById("textbox").style.display='none'))
javascript:void(document.write("Testing"))
javascript:alert(parseFloat("33.33"))
```
If using the latter trick, don't forget to wrap everything in a `void()` call or an `alert()` call, lest the page will be blanked out.
Alternatively, there is the Firebug extension on firefox in which you can edit javascript code arbitrarily.
Any other interesting ways out there? | [Firebug Console Logging](http://getfirebug.com/console.html) | You can use [JSBin](http://jsbin.com/) to test snippets of code with snippets of html and some js frameworks. | What's your favorite way of testing javascript code snippets? | [
"",
"javascript",
"debugging",
"testing",
""
] |
I continuously check string fields to check if they are null or blank.
```
if(myString == null || myString.Trim().Length == 0)
{
throw new ArgumentException("Blank strings cannot be handled.");
}
```
To save myself a bit of typing is it possible to create an extension method for the String class that would have the same effect? I understand how extension methods can be added for a class instance but what about adding a static extension method to a class?
```
if(String.IsNullOrBlank(myString))
{
throw new ArgumentException("Blank strings cannot be handled.");
}
``` | You could do:
```
public static bool IsNullOrBlank(this String text)
{
return text==null || text.Trim().Length==0;
}
```
And then call it like this:
```
if(myString.IsNullOrBlank())
{
throw new ArgumentException("Blank strings cannot be handled.");
}
```
This works because C# allows you to call extension method on `null` instances. | I know this is an old question but since it was bumped and it hasn't been mentioned already, as of .NET 4.0 you can simply use the [String.IsNullOrWhiteSpace method](http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx) to achieve the same result. | String.IsNullOrBlank Extension Method | [
"",
"c#",
"extension-methods",
""
] |
I am looking for a good example implementation of a JavaScript/HTML AutoSuggest input box to get me started. What I am trying to implement will behave "Exactly" like the Tags input box here on stackoverflow.
If it helps I am using jQuery to perform Ajax request.
I am finding examples to help me implement this however I am concerned what about best practices in the area and would love to get opinions also. | Er, [jQuery Autocomplete](http://www.ajaxdaddy.com/demo-jquery-autocomplete.html)? And [another example](http://jquery.bassistance.de/autocomplete/demo/). | Antonio Lupetti has just posted a review of Javascript based auto suggest scripts in his article [Useful Ajax Auto Suggest scripts collection](http://woork.blogspot.com/2009/02/useful-ajax-auto-suggest-scripts.html).
You might find some interesting links there? | Where can I find a good JavaScript/HTML AutoSuggest example | [
"",
"javascript",
"jquery",
"html",
""
] |
Refactoring legacy code, I came across this function (pseudocode):
```
int getMessage( char * buffer, int size = 300 );
```
Gee, look at that buffer just waiting to overflow. So I came up with a function using std::string, and thought it would be nice to use function overloading:
```
int getMessage( std::string & buffer );
```
So far, so good. But when I try to *call* the function with a string:
```
std::string buffer;
int rc = getMessage( buffer );
```
I get this error:
```
cannot convert 'std::string' to 'char*' for argument '1' to 'int getMessage(char*, int)'
```
Obviously, the compiler (GCC 4.1.2) tries hard to convert std::string to char\* to satisfy the first function's parameter list (using the default value to satisfy the second parameter), gives up, but doesn't try the second function...
I wouldn't have a problem working around this issue, but I'd like to know why this fails, and whether there would be a way to make it work as intended. | As always, once the problem is solved, the solution is painfully trivial and should have been obvious all along.
> So I came up with a function using std::string...
...in my working directory, which compiled just fine, but -I and -L in my makefile were still pointing at the previous version of the library, which was blissfully unaware of the new function.
Sorry for the bother. I've been an idiot. I hope this doesn't become a habit. ;-) | It works as expected on my GCC 4.3.2, maybe you misspelled the name of the overload? There's no conversion from std::string to char\*, so the compiler shouldn't have any problems choosing the correct overload.
```
$ cat test.cpp
#include <string>
#include <stdio.h>
int getMessage( char * buffer, int size = 300 )
{
printf("1\n");
return 1;
}
int getMessage( std::string & buffer )
{
printf("2\n");
return 2;
}
int main()
{
std::string buffer;
buffer = "Hello";
int rc = getMessage( buffer );
}
$ g++ test.cpp -Wall -pedantic
test.cpp: In function ‘int main()’:
test.cpp:20: warning: unused variable ‘rc’
$ ./a.out
2
$ $ g++ -v 2>&1|tail -n1
gcc version 4.3.2 (Ubuntu 4.3.2-1ubuntu12)
$
``` | Overloading, strings, and default parameters | [
"",
"c++",
"overloading",
""
] |
Is there a way to add optional parameters to C# 3.0 like there will be in C# 4.0? I gotta have this feature, I just can't wait!
**Edit:**
If you know a work-around/hack to accomplish this, post it also. Thanks! | You can use an anonymous type and reflection as a workaround to named parameters:
```
public void Foo<T>(T parameters)
{
var dict = typeof(T).GetProperties()
.ToDictionary(p => p.Name,
p => p.GetValue(parameters, null));
if (dict.ContainsKey("Message"))
{
Console.WriteLine(dict["Message"]);
}
}
```
So now I can call Foo like this:
```
Foo(new { Message = "Hello World" });
```
... and it will write my message.
Basically I'm extracting all the properties from the anonymous type that was passed, and converting them into a dictionary of string and object (the name of the property and its value). | There's always method overloading. :) | Named/Optional parameters in C# 3.0? | [
"",
"c#",
"c#-3.0",
"c#-4.0",
""
] |
Is there a simple way of testing if the generator has no items, like `peek`, `hasNext`, `isEmpty`, something along those lines? | The simple answer to your question: no, there is no simple way. There are a whole lot of work-arounds.
There really shouldn't be a simple way, because of what generators are: a way to output a sequence of values *without holding the sequence in memory*. So there's no backward traversal.
You could write a has\_next function or maybe even slap it on to a generator as a method with a fancy decorator if you wanted to. | Suggestion:
```
def peek(iterable):
try:
first = next(iterable)
except StopIteration:
return None
return first, itertools.chain([first], iterable)
```
Usage:
```
res = peek(mysequence)
if res is None:
# sequence is empty. Do stuff.
else:
first, mysequence = res
# Do something with first, maybe?
# Then iterate over the sequence:
for element in mysequence:
# etc.
``` | How do I know if a generator is empty from the start? | [
"",
"python",
"generator",
""
] |
I have a super basic form that shoots out an email. The code is contained within a virtual directory like <http://url/emailer/emailer.aspx> on a new server and is working fine.
We are in the process of migrating a few additional sites over to this new server. To test, I'm accessing the files via the ip address so I can see the site on the new server like <http://ip/url/emailer/emailer.aspx>.
For some reason, whenever I access the aspx page via the IP URL, I receive the "*could not load the assembly...make sure that it is compiled before accessing the page*" error. However, I've confirmed when pulled into the live site, it works fine.
Why does referencing the IP URL cause this exception? | Is it setup correctly in IIS? If it's not set as an application in the same way as the original server then it will be looking for the bin directory in a different location. For example, if you have /myapp as a directory, but not an application it will look in /bin, but if you change it to an application it will look for it in /myapp/bin.
The only other time I've seen this is when the same app pool is specified for 2 different apps, each set to run a different version of the framework. It doesn't sound like this is your problem, but it might be worth checking the app pool identities in case there's something else that's listening on the ip that might be using a different framework version. | This could be an IIS issue. Sometimes IIS is setup so that the IP address itself is pointing to another site since you have multiple web sites/applications all on the same server and some are picky about what the URL is for proper resolution.
Can you check the IIS settings for the application and see if the IP address is mapped to your site? | Odd .Net Could Not Load Assembly Error | [
"",
"c#",
".net",
"iis",
""
] |
I am passing my vector to a function that expects a c array. It returns the amount of data it filled (similar to fread). Is there a way i can tell my vector to change its size to include the amount that function has passed in?
of course i make sure the vector has the capacity() to hold that amount of data. | No, there is no supported way to "expand" a vector so it contains extra values that have been directly copied in. Relying on "capacity" to allocate non-sized memory that you can write to is definitely not something you should rely on.
You should ensure your vector has the required amount of space by resizing before calling the function and then resizing to the correct value afterwards. E.g.
```
vector.resize(MAX_SIZE);
size_t items = write_array(&(vec[0]), MAX_SIZE)
vector.resize(items);
``` | `capacity` tells you only how much memory is reserved, but it is not the size of the vector.
What you should do is resizes to maximum required size first:
```
vec.resize(maxSizePossible);
size_t len = cfunc(&(vec[0]));
vec.resize(len);
``` | expand size of vector passed as memory | [
"",
"c++",
"stl",
"vector",
""
] |
I have a C++ dll file that uses a lot of other c++ librarys (IPP, Opencv +++) that I need to load into matlab. How can I do this?
I have tried loadlibrary and mex. The load library does not work.
The mex finds the linux things (platform independent library) and tries to include them. And that does not work.
Does anyone have any good ideas? | loadlibrary should work. I use it all the time to call functions from dlls written in C++ with C wrappers.
What errors are you getting when you try to use loadlibrary?
Make sure that the exported functions of the dll are C functions, not C++ functions. If not, then write C wrappers.
More info on exactly what you are doing when using loadlibrary would be helpful. | As mentioned by others, you should first wrap your C++ library as a C library - mathworks used to advise not to use C++ code directly in mex (dlopening C++ core directly is complicated), maybe it is still true.
Your description is quite unclear, too: what do you mean by "mex finds the linux thing", but that does not work. Saying that it does not work is not helpful: the exact commands and error message are. | How to load a c++ dll file into Matlab | [
"",
"c++",
"matlab",
"dll",
"shared-libraries",
"loadlibrary",
""
] |
I am curious on how the following code works, especially the part the contains the delegate stuff since I am new to it. Also, are there any bottlenecks in the code, for example, would using a SortedDictionary be better than using a List and then sorting it using LINQ? Ok, here is the code:
```
public class ColorManager
{
private List<ColorData> colorCodes = new List<ColorData>();
public List<ColorData> ColorCodes
{
get
{
var sortList = from a in this.colorCodes
orderby a.colorCode ascending
select a;
return sortList.ToList();
}
}
public void FillData(DataTable table)
{
for(int row = 0; row < table.Rows.Count; row++)
{
ColorData cData = new ColorData();
string name = table.Rows[row]["Color"].ToString().Trim();
if(!this.colorCodes.Exists(
delegate(ColorData e)
{
return e.ColorCode == name;
}))
{
cData.Add(table.Rows[row]["Color"].ToString());
this.colorCodes.Add(cData);
}
else
{
this.colorCodes.Find(
delegate(ColorData e)
{
return e.ColorCode == name;
}).Count++;
}
}
}
}
``` | > I am curious on how the following code works, especially the part the contains the delegate stuff since I am new to it.
First take a look at this `ColorCodes` property accessor:
```
var sortList = from a in this.colorCodes
orderby a.colorCode ascending
select a;
```
It returns a list of all the color codes (`this.colorCodes`) in ascending order (`...orderby a.colorCode ascending`). Simple so far. How about the meatier `FillData` method?
First, we'll loop over every row in this table:
```
for(int row = 0; row < table.Rows.Count; row++)
{
```
Then, we're going to look at the `Color` column of the current row.
```
ColorData cData = new ColorData();
string name = table.Rows[row]["Color"].ToString().Trim();
```
If that column has no match in our list of color codes, this `if` condition is true. The `Exists` method takes a single-argument function that returns a bool, which is what this anonymous delegate is: a single-argument (`ColorData e`) function that returns a boolean (`e.ColorCode == name`). It gets negated (`!this.[...]`), so if a match is found, the condition is false.
```
if(!this.colorCodes.Exists(
delegate(ColorData e)
{
return e.ColorCode == name;
}))
{
cData.Add(table.Rows[row]["Color"].ToString());
this.colorCodes.Add(cData);
}
```
Otherwise, if there's a match, find the name using another anonymous delegate, and add one to the count of items of that color.
```
else
{
this.colorCodes.Find(
delegate(ColorData e)
{
return e.ColorCode == name;
}).Count++;
}
}
```
Note that this code is somewhat inefficient, since the two different anonymous delegates really do the same thing and could be shared. | Actually, there are more delegates there than you expect. The LINQ query:
```
var sortList = from a in this.colorCodes
orderby a.colorCode ascending
select a;
```
is actually:
```
var sortList = this.colorCodes.OrderBy(a => a.colorCode);
```
which (for LINQ-to-Objects) is the same as:
```
var sortList = this.colorCodes.OrderBy(delegate (ColorData a) {
return a.colorCode;
})
```
This uses a delegate to identify the item to sort by - i.e. "given a ColorData, I'll give you the colorCode". Note that many `select` uses *also* involve a delegate, but not in this case (the trivial `select a` is removed by the compiler).
In the code:
```
if(!this.colorCodes.Exists(
delegate(ColorData e)
{
return e.ColorCode == name;
}))
```
we are using a predicate; "given a ColorData, I'll tell you whether it is a match, by testing the name for equality". Note that `name` here is "captured" into the delegate, which involves some fairly complex compiler tricks (I won't describe them).
---
Re efficiencies; it is hard to be sure, but perhaps:
```
Dictionary<string, ColorData> items = new Dictionary<string, ColorData>();
foreach(DataRow row in table.Rows) {
string name = row["Color"].ToString().Trim();
ColorData cData;
if (items.TryGetValue(name, out cData)) {
cData.Count++;
} else {
cData.Add(name);
colorCodes.Add(cData);
items.Add(name, cData);
}
}
```
This avoids lots of duplication, and uses a dictionary to find values rather than constantly using Contains/Find. In many cases, a LINQ `GroupBy` might have helped, but not in this case, perhaps. | Explain how delegates work in the following code? | [
"",
"c#",
".net",
"delegates",
""
] |
I recently wrote a class that renders B-spline curves. These curves are defined by a number of control points. Originally, I had intended to use eight control points, so I added a constant to the class, like so:
```
class Curve
{
public:
static const int CONTROL_POINT_COUNT = 8;
};
```
Now I want to extend this class to allow an arbitrary amount of control points. So I want to change this to:
```
class Curve
{
public:
int getControlPointCount() {return _controlPointCount;}
};
```
The question is whether it isn't better to store constants in methods to begin with, to facilitate adaptability. In other words, isn't it better to have started thus:
```
class Curve
{
public:
int getControlPointCount() {return 8;}
};
```
The advantage of this is that I could have just changed one symbol in the method in question, instead of moving around constants etc.
Is this a good practice or a bad one? | Typically I favour maintaining as few couplings manually as possible.
The number of control points in the curve is, well, the number of control points in the curve. It's not an independent variable that can be set at will.
So I usually would expose a const standard container reference:
```
class Curve
{
private:
std::vector<Point>& _controlPoints;
public:
Curve ( const std::vector<Point>& controlPoints) : _controlPoints(controlPoints)
{
}
const std::vector<Point>& getControlPoints ()
{
return _controlPoints;
}
};
```
And if you want to know how many control points, then use `curve.getControlPoints().size()`. I'd suspect that in most of the use cases you'd want the points as well as the count anyway, and by exposing a standard container you can use the standard library's iterator idioms and built-in algorithms, rather getting the count and calling a function like `getControlPointWithIndex` in a loop.
If there really is nothing else in the curve class, I might even go as far as:
```
typedef std::vector<Point> Curve;
```
(often a curve won't render itself, as a renderer class can have details about the rendering pipeline, leaving a curve as purely the geometric artifact) | ```
int getControlPointCount() {return _controlPointCount;}
```
This is an accessor. Swapping a const static for an accessor is not really a gain as litb has pointed out. What you really need to *future-proof* is probably a pair of accessor and mutator.
```
int getControlPointCount() {return _controlPointCount;} // accessor
```
I'd also throw in a design-const for the accessor and make it:
```
int getControlPointCount() const {return _controlPointCount;} // accessor
```
and the corresponding:
```
void setControlPointCount(int cpc) { _controlPointCount = cpc;} //mutator
```
Now, the big difference with a static object is that the control-point count is no longer a class-level attribute but an instance level one. This is a *design change*. Do you want it this way?
*Nit:* Your class level static count is `public` and hence does not need an accessor. | Is it better to store class constants in data members or in methods? | [
"",
"c++",
"constants",
"members",
""
] |
Ok, everybody get in your wayback machine. I need to have a phone dial into my computer's 56k modem. I need my computer to have the modem "on" and have an active dialtone.
Here is why:
I have a sump pump alarm that will call me on a pump failure. It only works with a landline. I want to stop paying for my landline to save money and just have my cell. My idea is to intercept the outbound caLL from my sump alarm on my pc's 56k v90 modem. Then I can text message, email,etc... for free.
Does anybody know how to get started? I have found plenty of stuff on how to make outbound calls from my pc, but I want a phone (device) to dial my pc. I think the sump alarm will not dial unless it hears a dialtone.
I prefer a C# or vb6 program, but willing to go with anything. I have some experience working with serial comm devices so I just need to be pointed in the right direction.
Thanks!!! | You're going to need more than a modem in your PC to accomplish what you've described. Both the sump pump and your PC have modems, which are the subscriber end of a telephone "loop". The CO end (Central office in telephony terms) provides functions that you're telephone and both the modems mentioned above.
A big one is the generation of a ring ... this is a relatively high voltage AC signal that actually rang the bell in the old style telephones, but is simply detected in newer phones and your modems. In order for your sump pump's call to be recognized, this ring voltage has to be received at your PC's modem, but the sump pump won't actually generate this tone.
The other ideas presented here (the use of a PABX SOHO switch or connecting the detected signal from the sump pump directly to a I/O port on your PC), I can think of one other option. Somewhere inside the sump pump is a UART chip that does the serial communications to the included modem. If you disconnect the modem from the UART, you have the basics of a serial port, which can be connected to the serial port on a PC (though you may need an interface chip to get the levels right ... see the ICs provided by Maxim).
Good luck! | The easy way: Take a simple PABX (small SOHO kind) to let your alarm call your PC. You can use your PC's modem to wait for a RING from your modem. (Use the System.IO.Ports.SerialPort class to accoumplish this.) You'll need to program your alarm system to call the internal number of your PC.
Once you get a ring, you let your software do the rest. | create a dialtone from 56k modem | [
"",
"c#",
"vb6",
"serial-port",
"modem",
"mscomct2.ocx",
""
] |
I have been getting an error message that I can't resolve. It originates from Visual Studio or the debugger. I'm not sure whether the ultimate error condition is in VS, the debugger, my program, or the database.
This is a Windows app. Not a web app.
First message from VS is a popup box saying:
"No symbols are loaded for any call stack frame. The source code can not be displayed."
When that is clicked away, I get:
"**ContextSwitchDeadlock was detected**", along with a long message reproduced below.
The error arises in a loop that scans down a DataTable. For each line, it uses a key (HIC #) value from the table as a parameter for a SqlCommand. The command is used to create a SqlDataReader which returns one line. Data are compared. If an error is detected a row is added to a second DataTable.
The error seems to be related to how long the procedure takes to run (i.e. after 60 sec), not how many errors are found. I don't think it's a memory issue. No variables are declared within the loop. The only objects that are created are the SqlDataReaders, and they are in Using structures. Add System.GC.Collect() had no effect.
The db is a SqlServer site on the same laptop.
There are no fancy gizmos or gadgets on the Form.
I am not aware of anything in this proc which is greatly different from what I've done dozens of times before. I have seen the error before, but never on a consistent basis.
Any ideas, anyone?
**Full error Text:**
The CLR has been unable to transition from COM context 0x1a0b88 to COM context 0x1a0cf8 for 60 seconds. The thread that owns the destination context/apartment is most likely either doing a non pumping wait or processing a very long running operation without pumping Windows messages. This situation generally has a negative performance impact and may even lead to the application becoming non responsive or memory usage accumulating continually over time. To avoid this problem, all single threaded apartment (STA) threads should use pumping wait primitives (such as CoWaitForMultipleHandles) and routinely pump messages during long running operations. | The `ContextSwitchDeadlock` doesn't necessarily mean your code has an issue, just that there is a potential. If you go to `Debug > Exceptions` in the menu and expand the `Managed Debugging Assistants`, you will find `ContextSwitchDeadlock` is enabled.
If you disable this, VS will no longer warn you when items are taking a long time to process. In some cases you may validly have a long-running operation. It's also helpful if you are debugging and have stopped on a line while this is processing - you don't want it to complain before you've had a chance to dig into an issue. | In Visual Studio 2017, unchecked the ContextSwitchDeadlock option by:
Debug > Windows > Exception Settings
[](https://i.stack.imgur.com/IJ0UY.png)
In Exception Setting Windows: Uncheck the ContextSwitchDeadlock option
[](https://i.stack.imgur.com/nlo0W.png) | Visual Studio: ContextSwitchDeadlock | [
"",
"c#",
"sql-server",
"visual-studio",
""
] |
Is there a reason to include both `@version` and `@since` as part of a class?
They seem to be mutually exclusive.
Also, what does `%I%` and `%G%` mean, and how to set/use them?
```
@version %I%, %G%
``` | The `@version` tag should be the current version of the release or file in question. The `%I%`, `%G%` syntax are macros that the source control software would replace with the current version of the file and the date when the file is checked out.
The `@since` tag should be used to define which version you added the method, class, etc. This is your hint to other developers that they should only expect the method when they run against a particular version of the package. I would consider these uber-important parts of the documentation if you're shipping your code as a library intended for someone else to use. | Explained well in an article from Oracle, [How to Write Doc Comments for the Javadoc Tool](http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html).
# `@version`
> …classes and interfaces only.
>
> At Java Software, we use @version for the SCCS version. See "man sccs-get" for details. The consensus seems to be the following:
>
> %I% gets incremented each time you edit and delget a file
>
> %G% is the date mm/dd/yy
>
> When you create a file, %I% is set to 1.1. When you edit and delget it, it increments to 1.2.
>
> Some developers omit the date %G% (and have been doing so) if they find it too confusing -- for example, 3/4/96, which %G% would produce for March 4th, would be interpreted by those outside the United States to mean the 3rd of April. Some developers include the time %U% only if they want finer resolution (due to multiple check-ins in a day).
>
> The clearest numeric date format would be to have the date formatted with the year first, something like yyyy-mm-dd, as proposed in ISO 8601 and elsewhere (such as <http://www.cl.cam.ac.uk/~mgk25/iso-time.html>), but that enhancement would need to come from SCCS.
# `@since`
> Specify the product version when the Java name was added to the API specification (if different from the implementation). For example, if a package, class, interface or member was added to the Java 2 Platform, Standard Edition, API Specification at version 1.2, use:
```
/**
* @since 1.2
*/
```
> The Javadoc standard doclet displays a "Since" subheading with the string argument as its text. This subheading appears in the generated text only in the place corresponding to where the @since tag appears in the source doc comments (The Javadoc tool does not proliferate it down the hierarchy).
>
> (The convention once was " @since JDK1.2" but because this is a specification of the Java Platform, not particular to the Oracle JDK or SDK, we have dropped "JDK".)
>
> When a package is introduced, specify an @since tag in its package description and each of its classes. (Adding @since tags to each class is technically not needed, but is our convention, as enables greater visibility in the source code.) In the absence of overriding tags, the value of the @since tag applies to each of the package's classes and members.
>
> When a class (or interface) is introduced, specify one @since tag in its class description and no @since tags in the members. Add an @since tag only to members added in a later version than the class. This minimizes the number of @since tags.
>
> If a member changes from protected to public in a later release, the @since tag would not change, even though it is now usable by any caller, not just subclassers. | javadoc: @version and @since | [
"",
"java",
"documentation",
"javadoc",
""
] |
class A was using below two functions to build and send messages 1 & 2
```
builder::prepareAndDeliverMsg1(msg1_arg1,msg1_arg2)
{
}
builder::prepareAndDeliverMsg2(msg2_arg1,msg2_arg2)
{
}
```
Now, a new class B is introduced, which would like to do what A was doing in two stages
stage1->prepare
stage2->deliver
I was thinking to extend the builder class like below:
```
///----
builder::prepareMsg1(msg1_arg1,msg1_arg2)
{
}
builder::prepareMsg2(msg2_arg1,msg2_arg2)
{
}
builder::deliverMsg1(msg1_arg1)
{
This function, inserts re-calculated msg1_arg1 into the prepared message in stage1
}
builder::deliverMsg2(msg2_arg1)
{
This function, inserts re-calculated msg2_arg1 into the prepared message in stage1
}
// These two functions are still retained for the usage of class A
builder::prepareAndDeliverMsg1(msg1_arg1,msg1_arg2)
{
}
builder::prepareAndDeliverMsg2(msg2_arg1,msg2_arg2)
{
}
//---
```
I would like to know, if there is any better way of designing this ? | To expand on Darks idea you can have a base class that implements the combined prepare and delivers in terms of the separate functions and allows deriving classes to override those as required:
```
class base {
virtual bool prepareMsg1() = 0;
virtual bool prepareMsg2() = 0;
virtual bool deliverMsg1() = 0;
virtual bool deliverMsg2() = 0;
bool prepareAndDeliverMsg1(){
prepareMsg1();
deliverMsg1();
}
bool prepareAndDeliverMsg2(msg2_arg1,msg2_arg2){
prepareMsg2();
deliverMsg2();
}
};
```
You may find that a lot of the functionality from the two derived classes is the same in which case you won't want to use pure virtuals in the base class:
```
class base {
virtual bool prepareMsg1(args) {//not pure virtual
//do the common stuff
}
};
class derived {
bool prepareMsg1( args ) {
base::prepareMsg1(args);
//code to specailise the message
}
};
```
It could even be that the base class implments your original class but allows your second class to be derived without having to repeat the common code. | maybe for each message, create your own class and inherit from the base message class?
```
class TBaseMsg
{
public:
virtual void prepare() = 0;
virtual void deliver() = 0;
}
``` | Is there a better way to design this message passing code? | [
"",
"c++",
""
] |
I'm creating a web based system which will be used in countries from all over the world. One type of data which must be stored is dates and times.
What are the pros and cons of using the Java date and time classes compared to 3rd party libraries such as [Joda time](http://www.joda.org/joda-time/)? I guess these third party libraries exist for a good reason, but I've never really compared them myself. | EDIT: Now that Java 8 has been released, if you can use that, do so! `java.time` is even cleaner than Joda Time, in my view. However, if you're stuck pre-Java-8, read on...
Max asked for the pros and cons of using Joda...
Pros:
* It works, very well. I strongly suspect there are far fewer bugs in Joda than the standard Java libraries. Some of the bugs in the Java libraries are really hard (if not impossible) to fix due to the design.
* It's designed to encourage you to think about date/time handling in the right way - separating the concept of a "local time" (e.g "wake me at 7am wherever I am") and an instant in time ("I'm calling James at 3pm PST; it may not be 3pm where he is, but it's the same instant")
* I believe it makes it easier to update the timezone database, which *does* change relatively frequently
* It has a good immutability story, which makes life a *lot* easier IME.
* Leading on from immutability, all the formatters are thread-safe, which is great because you almost *always* want to reuse a single formatter through the application
* You'll have a head-start on learning `java.time` in Java 8, as they're at least somewhat similar
Cons:
* It's another API to learn (although the docs are pretty good)
* It's another library to build against and deploy
* When you use Java 8, there's still some work to migrate your skills
* I've failed to use the `DateTimeZoneBuilder` effectively in the past. This is a *very* rare use case though.
To respond to the oxbow\_lakes' idea of effectively building your own small API, here are my views of why this is a bad idea:
* It's work. Why do work when it's already been done for you?
* A newcomer to your team is much more likely to be familiar with Joda than with your homegrown API
* You're likely to get it wrong for anything beyond the simplest uses... and even if you initially *think* you only need simple functionality, these things have a habit of growing more complicated, one tiny bit at a time. Date and time manipulation is *hard* to do properly. Furthermore, the built-in Java APIs are hard to *use* properly - just look at the rules for how the calendar API's date/time arithmetic works. Building anything on top of these is a bad idea rather than using a well-designed library to start with. | Well, unless you intend to wait for Java 8, hoping that they will implement [a better API](https://jcp.org/en/jsr/detail?id=310) for manipulating date and time, yes, please, use [Joda-Time](http://www.joda.org/joda-time/). It's time saving and avoid many headaches. | Should I use Java date and time classes or go with a 3rd party library like Joda Time? | [
"",
"java",
"date",
"time",
"jodatime",
""
] |
Ok I've got a bit of an interesting problem on my hands. Here's a bit of background:
I'm writing a media library service implementation that will serve URLs to a front end flash player. The client wants to be able to push content into the service by uploading files with some metadata into an FTP folder - I have control of the metadata schema. The service watching this folder will pick up any new files, copy them to a "content" folder with, then push the meta data and the url's to the content down the content service and into the database.
The content service isn't a problem, done. Watching an FTP folder is.
My current implementation uses the FileSystemWatcher object with a filter for xml files.
There may be more than one file for each content item e.g. high, med, low quality videos.
I plan to enforce either by process or by a tool that the content is organised into it's own folders just for brevity but this isn't really an issue.
The xml file will look a bit like this:
```
<media>
<meta type="video">
<name>The Name Displayed</name>
<heading>The title of the video</heading>
<description>
A lengthy description about the video..
</description>
<length>00:00:19</length>
</meta>
<files>
<video file="somevideo.flv" quality="low"/>
<video file="somevideo.flv" quality="medium"/>
<video file="somevideo.flv" quality="high"/>
</files>
</media>
```
So when a new file is created the FileSystemWatcher.Created event fires. I've got a seperate thread running to process the content which shares a queue with the main service process (don't worry it's using the producer consumer pattern as detailed here: <http://msdn.microsoft.com/en-us/library/yy12yx1f.aspx>).
This all works fine, but now I'm running into edge cases left right and centre!
I've taken into account that the videos will take longer to upload so the processor will try to get an exclusive lock, if that fails it will move the item to the back of the queue and move onto the next item.
* What happens if the service crashes or there's already files there? so I wrote a method to queue up an existing files.
* What if files are getting uploaded while it's queueing up the existing files? Hopefully it will handle this? Should I periodically rescan the directory to see if I missed anything?
Can anyone recommend a best practice for this scenario? Is the filesystemwatcher a good idea or should the service just periodically scan the folder?
Edit: Just to give you some idea of scale. We're talking 10s of 1000s of items in total. Probably uploaded in large chunks. | FileSystemWatcher is a pragmatic way of getting early visibility of a file drop, but there are a lot of edge-cases that can cause missed events. You would still need a periodic sweep to be sure.
To avoid as many mutex issues; could the clients upload as foo.xml.upload, and then rename to foo.xml one there? That would avoid a lengthy locked file... (you just ignore the .upload ones).
Also: beware "not invented here"... there are many existing utilities that monitor folders; BizTalk for (an overkill) example. I'm not saying "don't do it yourself", but at least consider pre-canned options. | A common pitfall when watching for a file *creation* is that you may recieve your event before the upload has completed, so you end up processing a file that is incomplete.
Of course you can check for that, since the xml of an incomplete file will not be well formed. But a better solution IMO is to have the uploader write to a temp file, and after completion of the upload have it rename the file to \*.xml.
As for the FileSystemWatcher itself, well... I have come to distrust it when it is used on a network share (`delete` event never got fired). So I wrote my own 'watcher' that has a similar interface to the FSW, but is just polling the directory for file creation/deletion/change. Not as elegant as the FSW, but more reliable. | Best Practice for watching an upload folder? | [
"",
"c#",
"multithreading",
""
] |
I am looking for a way for clients in a LAN to find all the instances of my server application without any configuration. Instead of hacking something myself, I'd like to use an existing solution. Personally, I need it to be done in Python, but I'd happy to hear about solutions in any other language.
So why am I not using [avahi](http://avahi.org/) or [OpenSLP](http://www.openslp.org/) or some other [Zeroconf](http://en.wikipedia.org/wiki/Zeroconf#Service_discovery)/[SLP](https://www.rfc-editor.org/rfc/rfc2608) solution? Well, there are a couple of additional criteria, and I'm under the impression neither of the aforementioned systems matches them.
I'm looking for a solution that is:
* **Flexible**. It must not require superuser rights, i.e. only use ports>1024.
* **Solid**. It must allow multiple services of the same and different service type on a single machine and continue advertising the services even when the instance that started the advertisement server stops or crashes.
* **Portable**. It must run nearly everywhere, or at least on \*BSD, Debian/gentoo/RedHat/SuSe Linux, Mac OS X, Solaris and Windows NT.
* **Light**. Ideally, one Python script would be the whole solution. I'm not in the least interested in address autoconfiguration or something like that, although I'd begrudgingly accept a solution that has lots of features I don't need. Furthermore, any one-time setup is a strict no-no.
I expect something like this:
```
def registerService(service): # (type, port)
if listen(multicast, someport):
if fork() == child:
services = [service]
for q in queriesToMe():
if q == DISCOVERY:
answer(filter(q.criteria, services))
elif q == ADVERTISE and q.sender == "localhost":
services.append(q.service)
else:
advertiseAt("localhost", service)
``` | I wrote an application/library (currently Python and CLI interface) that matches all these critera. It's called [minusconf](http://code.google.com/p/minusconf/). Turns out forking is not even necessary. | For node discovery in a LAN I've used Twisted and UDP Multicast. Hope it helps you too.
Link to the twisted documentation that explains how to do it:
<https://twistedmatrix.com/documents/current/core/howto/udp.html#auto3>
Here is a basic implementation of a server/client based in the twisted's code.
It answers itself if you run once, but all the checking code and extra features were removed in order to make it simpler to read.
```
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
class MulticastPingPong(DatagramProtocol):
MULTICAST_ADDR = ('228.0.0.5', 8005)
CMD_PING = "PING"
CMD_PONG = "PONG"
def startProtocol(self):
"""
Called after protocol has started listening.
"""
# Set the TTL>1 so multicast will cross router hops:
self.transport.setTTL(5)
# Join a specific multicast group:
self.transport.joinGroup(self.MULTICAST_ADDR[0])
self.send_alive()
def send_alive(self):
"""
Sends a multicast signal asking for clients.
The receivers will reply if they want to be found.
"""
self.transport.write(self.CMD_PING, self.MULTICAST_ADDR)
def datagramReceived(self, datagram, address):
print "Datagram %s received from %s" % (repr(datagram), repr(address))
if datagram.startswith(self.CMD_PING):
# someone publishes itself, we reply that we are here
self.transport.write(self.CMD_PONG, address)
elif datagram.startswith(self.CMD_PONG):
# someone reply to our publish message
print "Got client: ", address[0], address[1]
if __name__ == '__main__':
reactor.listenMulticast(8005, MulticastPingPong(), listenMultiple=True)
reactor.run()
``` | Flexible, Solid and Portable Service Discovery | [
"",
"python",
"language-agnostic",
"service-discovery",
""
] |
I'm writing a bit of javascript and need to choose between SVG or VML (or both, or something else, it's a weird world).
Whilst I know that for now that only IE supports VML, I'd much rather detect functionality than platform.
SVG appears to have a few properties which you can go for: window.SVGAngle for example.
Is this the best way to check for SVG support?
Is there any equivalent for VML?
Unfortuntaly - in firefox I can quite happily do all the rendering in VML without error - just nothing happens on screen. It's quite hard to detect that situation from script. | For VML detection, here's what [google maps does](http://maps.google.com/intl/en_ALL/mapfiles/73/maps2.api/main.js) (search for "`function Xd`"):
```
function supportsVml() {
if (typeof supportsVml.supported == "undefined") {
var a = document.body.appendChild(document.createElement('div'));
a.innerHTML = '<v:shape id="vml_flag1" adj="1" />';
var b = a.firstChild;
b.style.behavior = "url(#default#VML)";
supportsVml.supported = b ? typeof b.adj == "object": true;
a.parentNode.removeChild(a);
}
return supportsVml.supported
}
```
I see what you mean about FF: it allows arbitrary elements to be created, including vml elements (`<v:shape>`). It looks like it's the test for the [adjacency attribute](http://msdn.microsoft.com/en-us/library/bb250527(VS.85).aspx) that can determine if the created element is truly interpreted as a vml object.
For SVG detection, this works nicely:
```
function supportsSvg() {
return document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#Shape", "1.0")
}
``` | I'd suggest one tweak to crescentfresh's answer - use
```
document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")
```
rather than
```
document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#Shape", "1.0")
```
to detect SVG. WebKit is currently very picky about reporting features, and returns false for `feature#Shape` despite having relatively solid SVG support. The `feature#BasicStructure` alternative is suggested in the comments to <https://bugs.webkit.org/show_bug.cgi?id=17400> and gives me the answers I expected on Firefox/Opera/Safari/Chrome (true) and IE (false).
Note that the `implementation.hasFeature` approach will ignore support via plugins, so if you want to check for e.g. the Adobe SVG Viewer plugin for IE you'll need to do that separately. I'd imagine the same is true for the RENESIS plugin, but haven't checked. | How do you detect support for VML or SVG in a browser | [
"",
"javascript",
"internet-explorer",
"svg",
"browser-detection",
"vml",
""
] |
In Perl I can skip a foreach (or any loop) iteration with a `next;` command.
Is there a way to skip over an iteration and jump to the next loop in C#?
```
foreach (int number in numbers)
{
if (number < 0)
{
// What goes here to skip over the loop?
}
// otherwise process number
}
``` | You want:
```
foreach (int number in numbers) // <--- go back to here --------+
{ // |
if (number < 0) // |
{ // |
continue; // Skip the remainder of this iteration. -----+
}
// do work
}
```
Here's more about the [**`continue` keyword**](http://msdn.microsoft.com/en-us/library/923ahwt1.aspx).
---
**Update:** In response to Brian's follow-up question in the comments:
> Could you further clarify what I would do if I had nested for loops, and wanted to skip the iteration of one of the extended ones?
>
> ```
> for (int[] numbers in numberarrays) {
> for (int number in numbers) { // What to do if I want to
> // jump the (numbers/numberarrays)?
> }
> }
> ```
A `continue` always applies to the nearest enclosing scope, so you couldn't use it to break out of the outermost loop. If a condition like that arises, you'd need to do something more complicated depending on exactly what you want, like `break` from the inner loop, then `continue` on the outer loop. See here for the documentation on the [**`break` keyword**](http://msdn.microsoft.com/en-us/library/adbctzc4.aspx). The `break` C# keyword is similar to the Perl `last` keyword.
Also, consider taking Dustin's suggestion to just filter out values you don't want to process beforehand:
```
foreach (var basket in baskets.Where(b => b.IsOpen())) {
foreach (var fruit in basket.Where(f => f.IsTasty())) {
cuteAnimal.Eat(fruit); // Om nom nom. You don't need to break/continue
// since all the fruits that reach this point are
// in available baskets and tasty.
}
}
``` | Another approach is to filter using LINQ before the loop executes:
```
foreach ( int number in numbers.Where(n => n >= 0) )
{
// process number
}
``` | How do I skip an iteration of a `foreach` loop? | [
"",
"c#",
".net",
"loops",
""
] |
I have some Javascript that is opening a blank window, assigning it with a stylesheet and then writing some text to it. This is all working fine except that the content is not having the styles applied to it.
The code looks like this:
```
var newWindow = window.open('', 'SecondWindow', 'toolbar=0,stat=0');
var style = newWindow.document.createElement('link');
style.type = "text/css";
style.rel = "stylesheet";
style.href = "styles/style.css";
newWindow.document.getElementsByTagName("head")[0].appendChild(style);
newWindow.document.body.innerHTML="<p class='verystylish'>Hello world!</p>";
```
If I use the Firefox Web Developer tools to view the generated source, save that as an html file and then open the html file manually, it applies the styles correctly, so it looks as though I need to be doing something to force the browser to apply the styles or re-render the page somehow. Any suggestions?
Edited to add, the generated source looks like this:
```
<html>
<head>
<title></title>
<link href="styles/style.css" rel="stylesheet" type="text/css">
<head>
<body>
<p class='verystylish'>Hello world!</p>
</body>
</html>
```
The problem being that no style whatsoever is assigned to the paragraph. But opening a file with the same source code renders correctly. | A new window opens by default with the URL ‘about:blank’. Relative URL references won't work for this reason. To change the location of the window to match the original document, call:
```
newWindow.document.open();
```
You should then write the skeleton of the document you want to the window. You can include the stylesheet now if you want, as document.write is a more reliable way of adding a stylesheet across older browsers than DOM methods. This method also allows you to write a DOCTYPE so you don't unexpectedly end up in Quirks Mode.
```
newWindow.document.write(
'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">'+
'<html><head>'+
' <link rel="stylesheet" href="styles/style.css">'+
'</head><body>'+
'</body></html>'+
);
newWindow.document.close();
``` | What do you mean by "it applies the styles correctly"? Are you talking about the `class="verystylish"`? If that's it, then it doesn't mean styles are getting applied at all, but that the new paragraph element has that class.
You're not writing anything to the window except for that `<P>`. Don't you have to write the whole code of the page, including `<HTML>`, `<HEAD>` and `<BODY>` tags? | Assigning a stylesheet in JavaScript creates good html, but does not show the styles | [
"",
"javascript",
"html",
"css",
""
] |
I have been working on a project that dynamically creates a javascript file using ASP.NET which is called from another site.
This jquery javascript file appends a div and fills it with a rather large HTML segment and in order to do that I need to turn the segment into a string like so:
```
$(document).ready(function(){
var html = "Giving this magazine such a lofty epithet may seem a bit presumptuous, but for a non scientifically trained outsider this magazine offers a fresh and challenging look at the fast paced world of science that doesn't shy away from humor and the use of terms and ideas that may require its readers to go online and define a term. And in some cases it may inspire the reader to pick up a book on science by such greats as Hawking and Greene in order to better grasp some of the concepts dealing with time, space and atoms. This magazine isn't dumbed down. It includes well placed and efficient illustrations to help explain some of the more abstract points. It is not designed in the way popular magazinea are, in so much as they only touch upon a topic in the simplest manner and then move on before the audience is lost. Yet this magazine keeps the attention of the reader by combining explanatory notes that help people with no background knowledge have some grasp of the topic and by using humor and well written articles to clearly make their points. <br />For a magazine with a serious and well researched list of topics having small cartoons the likes of the New Yorker shows how comfortable this magazine is with itself. From the moment I picked up this magazine for the first time I felt like every word I read mattered and was worth my time to read. (Not true of many other magazines) American Scientist may not have the audience of Discover or National Geographic, nor is it as accessible as said titles, but for those with a true interest in science willing to challenge themselves and commit to real learning this magazine may be a perfect fit. At $4.95 it is certainly worth it to pick a copy on the news stand and try it out."
$("#divname").append(html);
});
```
As you can see the segment will be pretty large and I have no way of knowing how big as it is generated dynamically from my database depending on the reviewID which is defined by the user in their request.
The html to be inserted into the div is a list of reviews and is generated using asp.net MVC by a repeater which loops through a list. (if that helps give you an idea of what I am doing).
Is there any way to turn this large segment into one string which can be inserted into the append script?
Thank You | Cross domain jquery json
<http://docs.jquery.com/Release:jQuery_1.2/Ajax#Cross-Domain_getJSON_.28using_JSONP.29> | Some ideas:
* You can replace new lines with spaces and create a huge line. There shouldn't be a problem with it.
* Use string concatenation. Split the string and lines and do:
var html = line1 +
line2 +
...
linen;
* Make an Ajax call to fill the div:
$("#divname").load(service\_url);
You need to create a service that will return the string.
In my opinion the 3rd option is better than the other ones. | Jquery append using multiline | [
"",
"javascript",
"jquery",
""
] |
There is a [questions asking how to simulate static variables in python](https://stackoverflow.com/questions/460586/simulating-a-local-static-variable-in-python).
Also, on the web one can find many different solutions to create static variables. (Though I haven't seen one that I like yet.)
Why doesn't Python support static variables in methods? Is this considered unpythonic or has it something to do with Python's syntax?
**Edit:**
I asked specifically about the *why* of the design decision and I haven't provided any code example because I wanted to avoid explanation to simulate static variables. | The idea behind this omission is that static variables are only useful in two situations: when you really should be using a class and when you really should be using a generator.
If you want to attach stateful information to a function, what you need is a class. A trivially simple class, perhaps, but a class nonetheless:
```
def foo(bar):
static my_bar # doesn't work
if not my_bar:
my_bar = bar
do_stuff(my_bar)
foo(bar)
foo()
# -- becomes ->
class Foo(object):
def __init__(self, bar):
self.bar = bar
def __call__(self):
do_stuff(self.bar)
foo = Foo(bar)
foo()
foo()
```
If you want your function's behavior to change each time it's called, what you need is a generator:
```
def foo(bar):
static my_bar # doesn't work
if not my_bar:
my_bar = bar
my_bar = my_bar * 3 % 5
return my_bar
foo(bar)
foo()
# -- becomes ->
def foogen(bar):
my_bar = bar
while True:
my_bar = my_bar * 3 % 5
yield my_bar
foo = foogen(bar)
foo.next()
foo.next()
```
Of course, static variables *are* useful for quick-and-dirty scripts where you don't want to deal with the hassle of big structures for little tasks. But there, you don't really need anything more than `global` — it may seem a but kludgy, but that's okay for small, one-off scripts:
```
def foo():
global bar
do_stuff(bar)
foo()
foo()
``` | One alternative to a class is a function attribute:
```
def foo(arg):
if not hasattr(foo, 'cache'):
foo.cache = get_data_dict()
return foo.cache[arg]
```
While a class is probably cleaner, this technique can be useful and is nicer, in my opinion, then a global. | Why doesn't Python have static variables? | [
"",
"python",
""
] |
I know C# is getting a lot of parallel programming support, but AFAIK there is still no constructs for side-effects verification, right?
I assume it's more tricky now that C# is already laid out. But are there plans to get this in? Or is F# the only .NET language that has constructs for side-effects verification? | C# the language isn't, but .NET the framework may be.
The Contracts library + the static analysis tools being introduced in .NET 4 might introduce these:
Microsoft is using [Immutable] and [Pure] inside .NET 3.5 framework right now.
For example, see [Microsoft.Contracts.Immutable] and [Microsoft.Contracts.Pure] inside .NET 3.5, in the System.Core.dll. Unfortunately, they're internal. However, Microsoft.Contracts.\* is mostly born out of Spec# research, and Spec# has been folded into the Contracts APIs that will be part of .NET 4.0.
We'll see what comes of this. I haven't checked to see if the pre-release .NET 4.0 bits contain any APIs like [Pure] or [Immutable] in the Contracts APIs. If they do, I'd imagine the static analysis tool will be the one to enforce the rule, rather than the compiler.
**edit** I just loaded up Microsoft.Contracts.dll from the [latest pre-release drop of MS Code Contracts](http://research.microsoft.com/en-us/projects/contracts/) this week. Good news: [Pure] and [Mutability(Mutability.Immutable)] attributes exist in the library, which suggests they will be in .NET 4.0. Woohoo!
**edit 2** Now that .NET 4 has been released, I looked up these types. [[Pure]](https://msdn.microsoft.com/en-us/library/system.diagnostics.contracts.pureattribute%28v=vs.110%29.aspx) is still there in System.Diagnostics.Contracts namespace. It's not intended for general use, but rather, for use with the Contract API's pre- and post-condition checking. It is not compiler enforced, [neither does the Code Contract checker tool enforce purity](https://softwareengineering.stackexchange.com/a/246579). [Mutability] is gone. Interestingly, where Microsoft was using Mutability and Pure attributes in .NET 3.5 (in the internal BigInteger class in System.Core.dll), .NET 4 has moved BigInteger into System.Numerics, and has stripped the [Pure] and [Mutability] attributes off that type. **Bottom line: it appears .NET 4 does nothing for side-effects verification.**
**edit 3** With the recently (late 2011) previewed Microsoft Rosyln compiler-as-a-service tools -- believed to be scheduled for RTM in Visual Studio 2015 -- look like they'll be able to support stuff like this; you could write extensions to the compiler to check for purity and immutability, and issue compiler warnings if something decorated with those attributes don't follow the rules. Even so, we're looking at a few years out to support this.
**edit 4** Now that Rosyln is here as of summer 2015, the ability to build a compiler extension for pure/immutability does indeed exist. However, that doesn't do anything for existing framework code, nor 3rd party library code. But on the horizon is a [C# 7 proposal for immutable types](https://github.com/dotnet/roslyn/issues/159). This would be enforced by the compiler and would introduce a new **immutable** keyword to C# and a [Immutable] attribute in the .NET framework. Usage:
```
// Edit #4: This is a proposed design for C# 7 immutable as of June 2015.
// Compiler will implicitly mark all fields as readonly.
// Compiler will enforce all fields must be immutable types.
public immutable class Person
{
public Person(string firstName, string lastName, DateTimeOffset birthDay)
{
FirstName = firstName; // Properties can be assigned only in the constructor.
LastName = lastName;
BirthDay = birthDay;
}
public string FirstName { get; } // String is [Immutable], so OK to have as a readonly property
public string LastName { get; }
public DateTime BirthDay { get; } // Date is [Immutable] too.
}
```
**edit 5** It's November 2016, and it appears immutable types were dropped from C# 7. There's always hope for C# 8. :-)
**edit 6** It's November 2017. C# 8 is coming into full view, and while we won't have pure functions, we will have [readonly structs](https://learn.microsoft.com/en-us/dotnet/csharp/reference-semantics-with-value-types). This makes a struct immutable, which allows several compiler optimizations.
**edit 7** It's July 2020, and C# 9 is coming with support for [records](https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/), which are fully immutable types. Additionally, records will have `With` expressions for creating new records from existing records to represent new state.
**edit 8** It's November 2021, and C# 10 has been released with support for `With` expressions for structs, as well as `record` structs. These also aid in the creation of immutable types. | Not only is there nothing for side-effect verification - there's nothing even to verify that a type is immutable, which is a smaller step along the same route IMO.
I don't believe there's anything coming down the pipe in C# 4.0 (although I could easily be wrong). I really *hope* that immutability makes an impact in C# 5.0; certainly Eric Lippert has blogged quite a bit about it, and folks at MS have been thinking about parallelism a fair amount.
Sorry it's not a more encouraging picture.
Edit: [Judah's answer](https://stackoverflow.com/questions/592934/pure-functions-in-c/592990#592990) is considerably brighter... would framework support be good enough for you? :) (I wouldn't be entirely surprised if some aspects of Code Contracts weren't ready for .NET 4.0, mind you - if perhaps they kept the initial release *relatively* small and boosted it later.) | Does (or will) C# include features for side-effects verification? | [
"",
"c#",
".net",
"f#",
"parallel-processing",
"immutability",
""
] |
I need to retrieve data from several rows and then insert the results into an enumerated array so then I can use a "for" loop to echo it...
I have this (I already connected to the database):
```
$genres_sql = 'SELECT genreID FROM genres WHERE imdbID = ?';
if ($stmt->prepare($genres_sql)) {
// bind the query parameters
$stmt->bind_param('i', $movieid);
// bind the results to variables
$stmt->bind_result($genre);
// execute the query
$stmt->execute();
$stmt->fetch();
}
```
Here I get the first result (row) into a variable. But I need to insert it into an enumerated array so the I can echo each result using this:
```
if (!empty($genre)) {
for ($i = 0; $i + 1 < count($genre); $i++)
{
echo $genre[$i].', ';
}
echo $genre[$i];
}
```
This will echo: `$genre[0], $genre[1], $genre[2],` and so on until the last one.
I know that `mysql_fetch_row` can do the work, but I'm new to programming so I need a very detailed explanation..
Thank you!! | You can loop using the `MySQLi_Statement::fetch` method:
```
$stmt->bind_result($genre);
$stmt->execute();
$genres = array();
while ($stmt->fetch()) {
$genres[] = $genre;
}
```
Basically `fetch` provides an iterator that the `while` can use to iterate through each result. The variables in `bind_result` (in this case `$genre`) are reassigned with each iteration. | I'm not 100% familiar with mysqli but I've played with a lot of pgsql commands doing this sort of thing and i think what your looking for is [mysqli-result->fetch\_assoc](https://www.php.net/manual/en/mysqli-result.fetch-assoc.php). This will produce an associative array that you can loop over pretty easily like so:
```
while ($row = $result->fetch_assoc()) {
printf ($row["genre"]);
}
```
**EDIT:** [Alnitak](https://stackoverflow.com/users/6782/alnitak) has linked to better explanation than i have in the comments for this answer. | Use "mysql_fetch_row" to retrieve results from database and insert into array using PHP and mysqli? | [
"",
"php",
"mysql",
"arrays",
"loops",
"mysqli",
""
] |
This should be a quick one. Is it possible to do something like this:
```
[Callback(funtionY)]
void functionX()
{
}
void functionY()
{
}
```
So that when functionX is called, functionY is called automatically too? Reason I ask is because I'm going to implement networking functionality to a small XNA based game engine, and I want to mark functions as Synched, to mark that when a function gets called it should be called across all clients.
Thanks. | Sounds like you want [Aspect-Oriented Programming](http://en.wikipedia.org/wiki/Aspect-oriented_programming).
I've used [PostSharp](http://www.postsharp.org/) for this before now, and it works pretty well. | You can probably do that quite easily with [PostSharp](http://www.postsharp.org/), but in general: no; you'd have to call it explicitly. | Automatically call function #2 upon calling function #1 | [
"",
"c#",
"attributes",
"function-calls",
""
] |
[This is my site.](http://www.musicking.in) When i will select songs for playing player.php file will open and it will play the songs selected.
Everything working fine,but the problem is when o will go back and select another songs it is opening one more player window. please help me.
I want only one player window has to be opened even i select other songs also.
to check the problem go to [this url](http://musicking.in/ilayaraja-hitstelugu.html) and play the songs once
player.php
```
createElement("playlist");
$dom->appendChild($root);
$root->setAttribute('version', "1");
$root->setAttribute('xmlns', "http://xspf.org/ns/0/");
$rootnext = $dom->createElement("trackList");
$root->appendChild($rootnext);
foreach ($song as $counter) {
$tokens = ",";
$tokenized = strtok($counter, $tokens);
// create child element
$song = $dom->createElement("track");
$rootnext->appendChild($song);
$song1 = $dom->createElement("creator");
$song->appendChild($song1);
$text = $dom->createTextNode("www.musicking.in");
$song1->appendChild($text);
$song1 = $dom->createElement("title");
$song->appendChild($song1);
// create text node
$text = $dom->createTextNode($tokenized);
$song1->appendChild($text);
$tokenized = strtok($tokens);
$song1 = $dom->createElement("location");
$song->appendChild($song1);
$text = $dom->createTextNode($tokenized);
$song1->appendChild($text);
}
// save
$dom->save("playlist.xml");
?>
```
playlist.xml
```
www.musicking.inDuryodhana's dialouge1/Ntr dialouges/duryodhana's dialouge.mp3www.musicking.inDuryodhana's dialouge2/Ntr dialouges/dvsk_dialogues-10.mp3www.musicking.inDuryodhana's dialouge3/Ntr dialouges/dvsk_dialogues-3.mp3www.musicking.inDuryodhana's dialouge4/Ntr dialouges/dvsk_dialogues-4.mp3www.musicking.inDuryodhana's dialouge5/Ntr dialouges/dvsk_dialogues-5.mp3www.musicking.inDuryodhana's dialouge6/Ntr dialouges/dvsk_dialogues-6.mp3www.musicking.inDuryodhana's dialouge7/Ntr dialouges/dvsk_dialogues-7.mp3www.musicking.inDuryodhana's dialouge8/Ntr dialouges/dvsk_dialogues-8.mp3www.musicking.inDuryodhana's dialouge9/Ntr dialouges/dvsk_dialogues-9.mp3www.musicking.inDuryodhana's dialouge10/Ntr dialouges/dvsk_dialogues-11.mp3www.musicking.inDuryodhana's dialouge11/Ntr dialouges/karna's dialouge.mp3
``` | Alekc has it right.
Your form code is this:
```
<form method="post" action="/player.php" target="_blank">
```
You should change the target to something like `player`. This change will still cause the player to open in a new window, but that window will be uniquely named.
```
<form method="post" action="/player.php" target="player">
```
Then, when a user clicks on "Play Selected," instead of opening another window, it will load into the old player. | I think that it opens a new window because you have specified target='\_blank' in the form. Try to use different target (i.e. target="player"). | player opening more than one time? | [
"",
"php",
"html",
"xml",
""
] |
There is another thread to discuss Fibo series in Python. This is to tweak code into more pythonic. [How to write the Fibonacci Sequence in Python](https://stackoverflow.com/questions/494594/how-to-write-the-fibonacci-sequence-in-python)
I am in love with this program I wrote to solve Project Euler Q2. I am newly coding in Python and rejoice each time I do it The Pythonic way! Can you suggest a better Pythonic way to do this?
[Project Euler Q2](http://projecteuler.net/index.php?section=problems&id=2). Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.
```
fib=[]
def fibo(a=-1,b=1,upto=4000000):
if a+b>=upto:
return
else:
a,b=b,a+b
fib.append(b)
fibo(a,b)
fibo()
even=[i for i in fib if not i%2]
print sum(even)
``` | First I'd do fibo() as a generator:
```
def fibo(a=-1,b=1,upto=4000000):
while a+b<upto:
a,b = b,a+b
yield b
```
Then I'd also select for evenness as a generator rather than a list comprehension.
```
print sum(i for i in fibo() if not i%2)
``` | Using generators is a Pythonic way to generate long sequences while preserving memory:
```
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
import itertools
upto_4000000 = itertools.takewhile(lambda x: x <= 4000000, fibonacci())
print(sum(x for x in upto_4000000 if x % 2 == 0))
``` | Python program to find fibonacci series. More Pythonic way | [
"",
"python",
""
] |
I'm getting this exception (Full exception at the bottom):
```
NHibernate.PropertyValueException was unhandled by user code
Message="not-null property references a null or transient
valueClearwave.Models.Encounters.Insurance.Patient"
Source="NHibernate"
EntityName="Clearwave.Models.Encounters.Insurance"
PropertyName="Patient"
```
I've done a lot of Googling and it seems the most common cause for
that error is when an association is bi-directional but only one half
has been set. As in: Insurance.Patient = Patient is called but
Patient.Insurances.Add(Insurance) is not. I do, in fact, have a
scenario like that but I've checked the object just before calling
Save with it and both Insurance.Patient and Patient.Insurances[0] are
the right objects.
The other possibility that this exception seems to reference is a
transient value. In my case *every* object is transient so I'm
suspecting the root of my problem is here. However, everything needs
to be transient right now because nothing has been saved yet. I would
expect NHibernate to persist things rather than complain that they are
not persisted.
Here are some snippets from my mappings (fluent):
```
public PatientMap()
{
WithTable("tPatient");
Id(x => x.Id, "uid_Patient").GeneratedBy.GuidComb
().Access.AsReadOnlyPropertyThroughCamelCaseField();
HasMany(x => x.Insurances).WithKeyColumn("uid_Patient")
.Cascade.All()
.Inverse();
...
}
public InsuranceMap()
{
WithTable("tPatientInsuranceInfo");
Id(x => x.Id,
"uid_PatientInsuranceInfo").GeneratedBy.GuidComb
().Access.AsReadOnlyPropertyThroughCamelCaseField();
References(x => x.Patient, "uid_Patient").Not.Nullable
().Cascade.All();
...
}
```
So, what could be the issue?
---
```
NHibernate.PropertyValueException was unhandled by user code
Message="not-null property references a null or transient
valueClearwave.Models.Encounters.Insurance.Patient"
Source="NHibernate"
EntityName="Clearwave.Models.Encounters.Insurance"
PropertyName="Patient"
StackTrace:
at NHibernate.Engine.Nullability.CheckNullability(Object[]
values, IEntityPersister persister, Boolean isUpdate)
at
NHibernate.Event.Default.AbstractSaveEventListener.PerformSaveOrReplicate
(Object entity, EntityKey key, IEntityPersister persister, Boolean
useIdentityColumn, Object anything, IEventSource source, Boolean
requiresImmediateIdAccess)
at
NHibernate.Event.Default.AbstractSaveEventListener.PerformSave(Object
entity, Object id, IEntityPersister persister, Boolean
useIdentityColumn, Object anything, IEventSource source, Boolean
requiresImmediateIdAccess)
at
NHibernate.Event.Default.AbstractSaveEventListener.SaveWithGeneratedId
(Object entity, String entityName, Object anything, IEventSource
source, Boolean requiresImmediateIdAccess)
at
NHibernate.Event.Default.DefaultMergeEventListener.EntityIsTransient
(MergeEvent event, IDictionary copyCache)
at NHibernate.Event.Default.DefaultMergeEventListener.OnMerge
(MergeEvent event, IDictionary copyCache)
at NHibernate.Impl.SessionImpl.FireSaveOrUpdateCopy(IDictionary
copiedAlready, MergeEvent event)
at NHibernate.Impl.SessionImpl.SaveOrUpdateCopy(String
entityName, Object obj, IDictionary copiedAlready)
at
NHibernate.Engine.CascadingAction.SaveUpdateCopyCascadingAction.Cascade
(IEventSource session, Object child, String entityName, Object
anything, Boolean isCascadeDeleteEnabled)
at NHibernate.Engine.Cascade.CascadeToOne(Object child, IType
type, CascadeStyle style, Object anything, Boolean
isCascadeDeleteEnabled)
at NHibernate.Engine.Cascade.CascadeAssociation(Object child,
IType type, CascadeStyle style, Object anything, Boolean
isCascadeDeleteEnabled)
at NHibernate.Engine.Cascade.CascadeProperty(Object child,
IType type, CascadeStyle style, Object anything, Boolean
isCascadeDeleteEnabled)
at NHibernate.Engine.Cascade.CascadeOn(IEntityPersister
persister, Object parent, Object anything)
at
NHibernate.Event.Default.AbstractSaveEventListener.CascadeBeforeSave
(IEventSource source, IEntityPersister persister, Object entity,
Object anything)
at
NHibernate.Event.Default.DefaultMergeEventListener.EntityIsTransient
(MergeEvent event, IDictionary copyCache)
at NHibernate.Event.Default.DefaultMergeEventListener.OnMerge
(MergeEvent event, IDictionary copyCache)
at NHibernate.Impl.SessionImpl.FireSaveOrUpdateCopy(IDictionary
copiedAlready, MergeEvent event)
at NHibernate.Impl.SessionImpl.SaveOrUpdateCopy(String
entityName, Object obj, IDictionary copiedAlready)
at
NHibernate.Engine.CascadingAction.SaveUpdateCopyCascadingAction.Cascade
(IEventSource session, Object child, String entityName, Object
anything, Boolean isCascadeDeleteEnabled)
at NHibernate.Engine.Cascade.CascadeToOne(Object child, IType
type, CascadeStyle style, Object anything, Boolean
isCascadeDeleteEnabled)
at NHibernate.Engine.Cascade.CascadeAssociation(Object child,
IType type, CascadeStyle style, Object anything, Boolean
isCascadeDeleteEnabled)
at NHibernate.Engine.Cascade.CascadeProperty(Object child,
IType type, CascadeStyle style, Object anything, Boolean
isCascadeDeleteEnabled)
at NHibernate.Engine.Cascade.CascadeOn(IEntityPersister
persister, Object parent, Object anything)
at
NHibernate.Event.Default.AbstractSaveEventListener.CascadeBeforeSave
(IEventSource source, IEntityPersister persister, Object entity,
Object anything)
at
NHibernate.Event.Default.DefaultMergeEventListener.EntityIsTransient
(MergeEvent event, IDictionary copyCache)
at NHibernate.Event.Default.DefaultMergeEventListener.OnMerge
(MergeEvent event, IDictionary copyCache)
at NHibernate.Event.Default.DefaultMergeEventListener.OnMerge
(MergeEvent event)
at NHibernate.Impl.SessionImpl.FireSaveOrUpdateCopy(MergeEvent
event)
at NHibernate.Impl.SessionImpl.SaveOrUpdateCopy(Object obj)
at Clearwave.Models.Data.Util.RepositoryBase`2.Save(EntityType&
entity) in C:\Projects\ClearWave\Src\Common\Domain Models
\Clearwave.Models.Data-NHibernate\Util\RepositoryBase.cs:line 25
at IntegrationWebServices.FromMirth.SubmitMessage(Message
theMessage, Guid providerOrganizationId)
at SyncInvokeSubmitMessage(Object , Object[] , Object[] )
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke
(Object instance, Object[] inputs, Object[]& outputs)
at
System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin
(MessageRpc& rpc)
InnerException:
``` | Another possibility is that you're saving an entire object graph, and that graph is circular, and items cannot be null. You could be giving NHibernate no legal order in which to do the inserts. (It should produce a better error message, but it produces this one).
Without seeing the rest of the source, it's hard to be of more help. Try removing entities from the mappings (and not saving them) until you can figure out what is causing the problem. | not sure if it helps but this did it for me.
```
<many-to-one name="Company" column="CompanyId" cascade="all" not-null="true"/>
```
cascade="all" was what I missed out before | NHibernate - not-null property reference a null or transient value | [
"",
"c#",
"nhibernate",
"exception",
"fluent-nhibernate",
"nhibernate-mapping",
""
] |
I have the following code in my `btn_click` event:
```
Sqlconnection con = new Sqlconnection("server=.;database=bss;user id=ab;pwd=ab");
con.open();
SqlCommand cmd = new Sqlcommand("select * from login where username='"
+ txt4name.Text + "' and pwd='" + txt4pwd.Text + "'", con);
SqlDataReader reader = cmd.execute Reader();
```
Where `login` is the table and `username` and `pwd` are its fields. After this code all the values are stored in the `reader` object. I want to store `username` and `pwd` in the separate variables.
How can I accomplish this? | In general, when accessing your DB, you should be using something similar to this instead to eliminate SQL injection vulnerabilities:
```
using (SqlCommand myCommand = new SqlCommand("SELECT * FROM USERS WHERE USERNAME=@username AND PASSWORD=HASHBYTES('SHA1', @password)", myConnection))
{
myCommand.Parameters.AddWithValue("@username", user);
myCommand.Parameters.AddWithValue("@password", pass);
myConnection.Open();
SqlDataReader myReader = myCommand.ExecuteReader())
...................
}
```
**But more realistically to store credentials, you should be using something like the [Membership system](http://msdn.microsoft.com/en-us/library/yh26yfzy.aspx) instead of rolling your own.** | [You're running a huge risk of sql injection with that.](http://en.wikipedia.org/wiki/SQL_injection) Use SQL Parameters for values into SqlCommands. | How can I get a username and password from my database in C#? | [
"",
"c#",
".net",
"asp.net",
"t-sql",
"sql-injection",
""
] |
How can I split correctly a string containing a sentence with special chars using whitespaces as separator ?
Using regex split method I cannot obtain the desired result.
Example code:
```
# -*- coding: utf-8 -*-
import re
s="La felicità è tutto" # "The happiness is everything" in italian
l=re.compile("(\W)").split(s)
print " s> "+s
print " wordlist> "+str(l)
for i in l:
print " word> "+i
```
The output is :
```
s> La felicità è tutto
wordlist> ['La', ' ', 'felicit', '\xc3', '', '\xa0', '', ' ', '', '\xc3', '', '\xa8', '', ' ', 'tutto']
word> La
word>
word> felicit
word> Ã
word>
word> ?
word>
word>
word>
word> Ã
word>
word> ?
word>
word>
word> tutto
```
while I'm looking for an output like:
```
s> La felicità è tutto
wordlist> ['La', ' ', 'felicità', ' ', 'è', ' ', 'tutto']
word> La
word>
word> felicità
word>
word> è
word>
word> tutto
```
To be noted that s is a string that is returned from another method so I cannot force the encoding like
```
s=u"La felicità è tutto"
```
On official python documentation of Unicode and reg-ex I haven't found a satisfactory explanation.
Thanks.
Alessandro | Your regex should be `(\s)` instead of `(\W)` like this:
```
l = re.compile("(\s)").split(s)
```
The code above will give you the exact output you requested. However the following line makes more sense:
```
l = re.compile("\s").split(s)
```
which splits on whitespace characters and doesn't give you all the spaces as matches. You may need them though so I posted both answers. | Try defining an encoding for the regular expression:
```
l=re.compile("\W", re.UNICODE).split(s)
``` | python, regex split and special character | [
"",
"python",
"regex",
"unicode",
"split",
""
] |
I'm going to deploy a django app on a shared hosting provider. I installed my own python in my home, it works fine. My promblem comes with the installation of PIL, i have no support for JPEG after the compile process.
I know that the compiler dont find "libjpeg", so i tried to install it at my home, i download the tar.gz and compile it with
```
./configure -prefix=$HOME/lib
make
make install
```
after i put the path in my.bashrc file.
After all i re-compile PIL and still no have the jpeg support.
It is possible to have the libs installed in a shared hosted enviroment? How would I do this? | Does the machine actually have libjpeg available on it?
Look for /usr/lib/libjpeg.so, and /usr/include/jpeglib.h; they may possibly be in a different lib and include directory. If you can't find them you'll have to also download and compile libjpeg into your home (typically prefix ~/.local).
Then you'll need to add the ‘lib’ path to the ‘library\_dirs’ variable and the ‘include’ to ‘include\_dirs’ in PIL's setup.py (eg. just under “# add standard directories”), to get it to notice the availability of libjpeg. | Pillow v8 works well on shared hosting cpanel by this current time, python 3.7 pillow==8.0.0 | python PIL install on shared hosting | [
"",
"python",
"compilation",
"python-imaging-library",
""
] |
My customer has a PHP web service, that they want me to use.
It's PHP-based, while my *web* is ASP-based.
The ASP code looks like this:
```
Dim soapclient
WSDL_URL = "http://xxx.xxxx.xx/index.php?Action=service"
set soapclient = Server.CreateObject("MSSOAP.SoapClient30")
soapclient.ClientProperty("ServerHTTPRequest") = True
```
on error resume next
> soapclient.mssoapinit WSDL\_URL ' error here
Is ASP able to call a PHP-based soap service?
or
What should I adjust?
Thanks a lot! | We find a way to solve this question is not use "MSSOAP.SoapClient30" to ask web service, but "Msxml2.ServerXMLHTTP.4.0".
Sample code like this:
url = "<http://xxx.xxx.xx/xxx.php>"
SoapRequest="<?xml version="&CHR(34)&"1.0"&CHR(34)&" encoding="&CHR(34)&"utf-8"&CHR(34)&"?>"
"<soap:Envelope xmlns:xsi="&CHR(34)&"<http://www.w3.org/2001/XMLSchema-instance>"&CHR(34)&" xmlns:xsd="&CHR(34)&"<http://www.w3.org/2001/XMLSchema>"&CHR(34)&" xmlns:soap="&CHR(34)&"<http://schemas.xmlsoap.org/soap/envelope/>"&CHR(34)&"><soap:Body><getList></getList></soap:Body></soap:Envelope>"
Set xmlhttp = server.CreateObject("Msxml2.ServerXMLHTTP.4.0")
xmlhttp.Open "POST",url,false
xmlhttp.setRequestHeader "Content-Type", "text/xml;charset=utf-8"
xmlhttp.setRequestHeader "Content-Length",LEN(SoapRequest)
xmlhttp.Send(SoapRequest)
Response.Write xmlhttp.responseText
Set xmlhttp = Nothing | The whole point of web services and SOAP is that it *does not matter* what language the service is implemented in and on what hardware and OS it runs.
Either there is a bug in the web service or (more likely) you're calling it in a wrong way. | Can use ASP to call PHP soap? | [
"",
"php",
"web-services",
"soap",
"asp-classic",
""
] |
> **Possible Duplicate:**
> [What is the most efficient way to clone a JavaScript object?](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-a-javascript-object)
I need to copy an (ordered, not associative) array of objects. I'm using jQuery. I initially tried
```
jquery.extend({}, myArray)
```
but, naturally, this gives me back an object, where I need an array (really love jquery.extend, by the way).
So, what's the best way to copy an array? | Since Array.slice() does not do deep copying, it is not suitable for multidimensional arrays:
```
var a =[[1], [2], [3]];
var b = a.slice();
b.shift().shift();
// a is now [[], [2], [3]]
```
Note that although I've used `shift().shift()` above, the point is just that *`b[0][0]` contains a pointer to `a[0][0]`* rather than a value.
Likewise `delete(b[0][0])` also causes `a[0][0]` to be deleted and `b[0][0]=99` also changes the value of `a[0][0]` to 99.
jQuery's `extend` method *does* perform a deep copy when a true value is passed as the initial argument:
```
var a =[[1], [2], [3]];
var b = $.extend(true, [], a);
b.shift().shift();
// a is still [[1], [2], [3]]
``` | `$.extend(true, [], [['a', ['c']], 'b'])`
That should do it for you. | (Deep) copying an array using jQuery | [
"",
"javascript",
"jquery",
""
] |
say I have `vector<class1a>,vector<class1b>` how to remove the common entities from both of them
I have defined ==operator for the class1 objects class1a,class1b | The [stl algorithms](http://www.cplusplus.com/reference/algorithm/) provide several functions to perform set operations, notably calculating the [set symmetric difference](http://www.cplusplus.com/reference/algorithm/set_symmetric_difference.html), which is what you need.
Here's an example of use:
```
#include <algorithm>
#include <vector>
int main(int argc, char **argv) {
std::vector<int> v1;
v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
v1.push_back(4);
v1.push_back(5);
v1.push_back(6);
std::vector<int> v2;
v2.push_back(2);
v2.push_back(4);
v2.push_back(6);
v2.push_back(8);
// Ranges must be sorted!
std::sort(v1.begin(), v1.end());
std::sort(v2.begin(), v2.end());
std::vector<int> res; // Will contain the symmetric difference
std::set_symmetric_difference(v1.begin(), v1.end(),
v2.begin(), v2.end(),
std::back_inserter(res));
// Copy result to the output
std::copy(res.begin(), res.end(), std::ostream_iterator<int>(cout, " "));
// Prints "1 3 5"
return 0;
}
```
`std::set_symmetric_difference` takes two range (i.e. two pairs of OutputIterators) and an InputIterator where it will put the result. It also returns an iterator to the end of the result range.
---
**EDIT**
I just read your comments on your question. If you want the two original vectors to be modified, you can use `std::set_difference`:
```
vector<int>::iterator endRange;
endRange = set_difference(v1.begin(), v1.end(),
v2.begin(), v2.end(),
v1.begin());
v1.erase(endRange, v1.end());
```
Here, we put the result of the set difference v1 - v2 into v1. However, we can't do the vice-versa since v1 is now modified. The solution is to calculate the intersection of v1 and v2, and then the difference with this intersection `std::set_intersection` :
```
vector<int> inter;
set_intersection(v1.begin(), v1.end(),
v2.begin(), v2.end(),
back_inserter(inter));
// inter is "2 4 6"
v1.erase(set_difference(v1.begin(), v1.end(),
inter.begin(), inter.end(),
v1.begin()),
v1.end());
// v1 is "1 3 5"
v2.erase(set_difference(v2.begin(), v2.end(),
inter.begin(), inter.end(),
v2.begin()),
v2.end());
// v2 is "8"
```
I guess there are much more performant solutions, but this one is clear, and really convey your intents by using widely known stl algorithms. | In the stl header algorithm is a function called "set\_symmetric\_difference" that will put all of the elements of one, but not both source ranges into a single destination range.
Bear in mind that both of the ranges must start sorted.
[msdn documentation](http://msdn.microsoft.com/en-us/library/t333wak6.aspx) | Remove the common entities from two vector? | [
"",
"c++",
"vector",
""
] |
I am writing a networked application in Java, to communicate between the client and the server I am using serialized objects to represent data/commands and sending them through object output/input streams.
I am having problems cleanly closing the connections, I assume that I am missing something fundamental that I do not really know about, I've never used sockets with serialization before.
What ever order I try to shutdown the connection (close client first, close server first) a `ConnectionReset` exception is thrown. I cannot catch this exception as the client runs in another thread to the rest of the program constantly listening for messages, this must be done, as in Java `socket.read()` is a blocking method.
What is the correct way to close a socket that I am using to send objects? | You need to send your listener (whether client or server, it doesn't matter) some kind of signal to stop listening for more data. Here is a very simple example:
```
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(sock.getInputStream()));
while (true) {
Object obj = ois.readObject();
if (obj instanceof String) {
if ((String)obj).equalsIgnoreCase("quit")) {
break;
}
}
// handle object
}
ois.close();
sock.close();
``` | You should probably not be waiting to read() from a socket, while the other end is closing it. In a good network protocol, the client can inform the server that it has nothing more to write (maybe by sending it a special close character) before closing the connection. | Correct way to close a socket and ObjectOutputStream? | [
"",
"java",
"networking",
"sockets",
"serialization",
""
] |
Let's assume I'm creating a simple class to work similar to a C-style struct, to just hold data elements. I'm trying to figure out how to search a list of objects for objects with an attribute equaling a certain value. Below is a trivial example to illustrate what I'm trying to do.
For instance:
```
class Data:
pass
myList = []
for i in range(20):
data = Data()
data.n = i
data.n_squared = i * i
myList.append(data)
```
How would I go about searching the myList list to determine if it contains an element with n == 5?
I've been Googling and searching the Python docs, and I think I might be able to do this with a list comprehension, but I'm not sure. I might add that I'm having to use Python 2.4.3 by the way, so any new gee-whiz 2.6 or 3.x features aren't available to me. | You can get a list of *all* matching elements with a list comprehension:
```
[x for x in myList if x.n == 30] # list of all elements with .n==30
```
If you simply want to determine if the list contains *any* element that matches and do it (relatively) efficiently, you can do
```
def contains(list, filter):
for x in list:
if filter(x):
return True
return False
if contains(myList, lambda x: x.n == 3) # True if any element has .n==3
# do stuff
``` | **Simple, Elegant, and Powerful:**
A generator expression in conjuction with a builtin… (python 2.5+)
```
any(x for x in mylist if x.n == 10)
```
Uses the Python [`any()`](http://docs.python.org/2/library/functions.html#any) builtin, which is defined as follows:
> **any(iterable)** `->`
> Return True if any element of the iterable is true. Equivalent to:
```
def any(iterable):
for element in iterable:
if element:
return True
return False
``` | Searching a list of objects in Python | [
"",
"python",
""
] |
I've seen a trend to move business logic out of the data access layer (stored procedures, LINQ, etc.) and into a business logic component layer (like C# objects).
Is this considered the "right" way to do things these days? If so, does this mean that some database developer positions may be eliminated in favor of more middle-tier coding positions? (i.e. more c# code rather than more long stored procedures.) | Data access logic belongs in the data access layer, business logic belongs in the business layer. I don't see how mixing the two could ever be considered a good idea from a design standpoint. | If the applications is small with a short lifetime, then it's not worth putting time into abstracting the concerns in layers. In larger, long lived applications your logic/business rules should not be coupled to the data access. It creates a maintenance nightmare as the application grows.
Moving concerns to a common layer or also known as [Separation of concerns](http://en.wikipedia.org/wiki/Separation_of_concerns), has been around for a while:
*Wikipedia*
> The term separation of concerns was
> probably coined by Edsger W. Dijkstra
> in his 1974 paper "On the role of
> scientific thought"[1](http://en.wikipedia.org/wiki/Separation_of_concerns).
For Application Architecture a great book to start with is [Domain Driven Design](https://rads.stackoverflow.com/amzn/click/com/0321125215). Eric Evans breaks down the different layers of the application in detail. He also discusses the database impedance and what he calls a "Bounded Context"
**Bounded Context**
A blog is a system that displays posts from newest to oldest so that people can comment on. Some would view this as one system, or one "Bounded Context." If you subscribe to DDD, one would say there are two systems or two "Bounded Contexts" in a blog: A commenting system and a publication system. DDD argues that each system is independent (of course there will be interaction between the two) and should be modeled as such. DDD gives concrete guidance on how to separate the concerns into the appropriate layers.
*Other resources that might interest you:*
* [Domain Driven Design Quickly](http://www.infoq.com/minibooks/domain-driven-design-quickly)
* [Applying Domain Driven Design and
Patterns](https://rads.stackoverflow.com/amzn/click/com/0321268202)
* [Clean Code](https://rads.stackoverflow.com/amzn/click/com/0132350882)
* [Working Effectively with Legacy
Code](https://rads.stackoverflow.com/amzn/click/com/0131177052)
* [Refactor](https://rads.stackoverflow.com/amzn/click/com/0201485672)
Until I had a chance to experience [The Big Ball of Mud](http://www.laputan.org/mud/) or [Spaghetti Code](http://en.wikipedia.org/wiki/Spagetti_code) I had a hard time understanding why Application Architecture was so important...
The right way to do things will always to be dependent on the size, availability requirements and lifespan of your application. To use stored procs or not to use stored procs... Tools such as nHibrnate and Linq to SQL are great for small to mid-size projects. To make myself clear, I've never used nHibranate or Linq To Sql on a large application, but my gut feeling is an application will reach a size where optimizations will need to be done on the database server via views, Stored Procedures.. etc to keep the application performant. To do this work Developers with both Development and Database skills will be needed. | Should the data access layer contain business logic? | [
"",
"sql",
"sql-server",
"design-patterns",
"architecture",
""
] |
I was looking at the online help for the Infragistics control library today and saw some VB code that used the **With** keyword to set multiple properties on a tab control. It's been nearly 10 years since I've done any VB programming, and I had all but forgotten that this keyword even existed. Since I'm still relatively new to C#, I quickly went to see if it had a similar construct. Sadly, I haven't been able to find anything.
Does C# have a keyword or similar construct to mimic the functionality provided by the **With** keyword in VB? If not, is there a technical reason why C# does not have this?
**EDIT:** I searched for an existing entry on this before asking my question, but didn't find the one Ray referred to ([here](https://stackoverflow.com/questions/481725/with-block-equivalent-in-c/481746#481746)). To refine the question, then, is there a technical reason why C# does not have this? And Gulzar nailed it - no, there are not a technical reason why C# does not have a **With** keyword. It was a design decision by the language designers. | This is what C# program manager has to say:
[Why doesn't C# have a 'with' statement?](http://msdn.microsoft.com/en-us/vcsharp/aa336816.aspx)
> * **Small or non-existent readability benefits.** We thought the readability benefits were small or non-existent. I won't go as far as to say that the with statement makes code less readable, but some people probably would.
> * **Increased language complexity.** Adding a with statement would make the language more complex. For example, VB had to add new language syntax to address the potential ambiguity between a local variable (Text) and a property on the "with" target (.Text). Other ways of solving this problem also introduce language complexity. Another approach is to push a scope and make the property hide the local variable, but then there's no way to refer to the local without adding some escape syntax.
> * **C++ heritage.** C++ has never had a with statement, and the lack of such a statement is not generally thought to be a problem by C++ developers. Also, we didn't feel that other changes -- changes in the kind of code people are writing, changes in the platform, other changes in the language, etc. -- made with statements more necessary. | In C# 3.0, you can use object initializers to achieve a similar effect when creating objects.
```
var control = new MyControl
{
Title = "title",
SomeEvent += handler,
SomeProperty = foo,
Another = bar
};
```
Rather than:
```
var control = new MyControl();
control.Title = "title";
control.SomeEvent += handler;
control.SomeProperty = foo;
control.Another = bar;
```
Note that, although this syntax was introduced in C# 3.0, you can still use it with the 2.0 framework, it's just syntactic sugar introduced by the compiler. | Missing the 'with' keyword in C# | [
"",
"c#",
".net",
"syntax",
"keyword",
""
] |
### Duplicate
> [What are some good resources for learning about Artificial Neural Networks?](https://stackoverflow.com/questions/478947/what-are-some-good-resources-for-learning-about-neural-networks)
I'm looking for a good (beginner level) reference book (or website) on different types of Neural Nets/their applications/examples. I don't have any particular application in mind, I'm just curious as to how I can make use of them. I'm specifically interested in using them with Python, but any language, or even just theory would do fine. | There is quite a extensive series of courses avaliable at [Heaton Research](http://www.heatonresearch.com/course/intro-neural-nets-cs). The course is for C# (Avaliable also for Java) however it explains the concepts at length, so I suggest you take a look at it even if you will code in python yourself.
The courses are in video format, however most important concepts are also writen down. | See the below three links for Neural Networks using Python:
[An Introduction to Neural Networks](http://www.ibm.com/developerworks/library/l-neural/)
[Weave a Neural Net with Python](http://www-128.ibm.com/developerworks/library/l-neurnet/?ca=dgr-lnxw961NeuralNet)
[Neural Networks in Pyro](http://pyrorobotics.com/?page=PyroModuleNeuralNetworks)
Ron Stephens | Looking for a Good Reference on Neural Networks | [
"",
"python",
"neural-network",
""
] |
I'm using Sqlserver express and I can't do `before updated` trigger. There's a other way to do that? | MSSQL does not support `BEFORE` triggers. The closest you have is `INSTEAD OF` triggers but their behavior is different to that of `BEFORE` triggers in MySQL.
SQL Server offers [DML triggers](https://learn.microsoft.com/en-us/sql/relational-databases/triggers/dml-triggers?view=sql-server-ver16)
> DML triggers is a special type of stored procedure that automatically
> takes effect when a data manipulation language (DML) event takes place
> that affects the table or view defined in the trigger *(Insert, Update, Delete)*.
DML trigger statements use [two special tables](https://learn.microsoft.com/en-us/sql/relational-databases/triggers/use-the-inserted-and-deleted-tables?view=sql-server-ver16): the `deleted` and `inserted` tables.
Note
> INSTEAD OF triggers override the standard actions
> of the triggering statement. Therefore, they can be used to perform
> error or value checking on one or more columns and perform additional
> actions before inserting, updating or deleting the row or rows.
From the now offline documentation
> Specifies that the trigger is executed instead of the triggering SQL
> statement, thus overriding the actions of the triggering statements.
You can learn more about [types of dml triggers here](https://learn.microsoft.com/en-us/sql/relational-databases/triggers/dml-triggers?view=sql-server-ver16#types-of-dml-triggers)
Thus, actions on the update may not take place if the trigger is not properly written/handled. Cascading actions are also affected.
You may instead want to use a different approach to what you are trying to achieve. | It is true that there aren't "before triggers" in MSSQL. However, you could still track the changes that were made on the table, by using the "inserted" and "deleted" tables together. When an update causes the trigger to fire, the "inserted" table stores the new values and the "deleted" table stores the old values. Once having this info, you could relatively easy simulate the "before trigger" behaviour. | How can I do a BEFORE UPDATED trigger with sql server? | [
"",
"sql",
"sql-server",
"database",
"triggers",
"sql-server-express",
""
] |
I'm trying to get a better understanding of what place (if any) Macros have in *modern* C++ and Visual C++, also with reference to Windows programming libraries: What problem (if any) do Macros solve in these situations that cannot be solved without using them?
I remember reading about Google Chrome's use of WTL for Macros (amonst other things) from [this blog post](http://www.hanselman.com/blog/TheWeeklySourceCode33MicrosoftOpenSourceInsideGoogleChrome.aspx), and they are also used in MFC - here is an example of a Macro from that blog post I'd like explained in a superb amount of detail if possible:
```
// CWindowImpl
BEGIN_MSG_MAP(Edit)
MSG_WM_CHAR(OnChar)
MSG_WM_CONTEXTMENU(OnContextMenu)
MSG_WM_COPY(OnCopy)
MSG_WM_CUT(OnCut)
MESSAGE_HANDLER_EX(WM_IME_COMPOSITION, OnImeComposition)
MSG_WM_KEYDOWN(OnKeyDown)
MSG_WM_LBUTTONDBLCLK(OnLButtonDblClk)
MSG_WM_LBUTTONDOWN(OnLButtonDown)
MSG_WM_LBUTTONUP(OnLButtonUp)
MSG_WM_MBUTTONDOWN(OnNonLButtonDown)
MSG_WM_MOUSEMOVE(OnMouseMove)
MSG_WM_MOUSELEAVE(OnMouseLeave)
MSG_WM_NCCALCSIZE(OnNCCalcSize)
MSG_WM_NCPAINT(OnNCPaint)
MSG_WM_RBUTTONDOWN(OnNonLButtonDown)
MSG_WM_PASTE(OnPaste)
MSG_WM_SYSCHAR(OnSysChar) // WM_SYSxxx == WM_xxx with ALT down
MSG_WM_SYSKEYDOWN(OnKeyDown)
END_MSG_MAP()
```
I've read [these](http://msdn.microsoft.com/en-us/library/ttsbh614(VS.80).aspx) [articles](http://msdn.microsoft.com/en-us/library/503x3e3s(VS.80).aspx) to do with Macros on MSDN but am trying to also pick up best practices for writing or avoiding Macros and where/when to use them. | All of those Macros are defined in public sdk header files, so you can go read what they do yourself if you want. Basically what is happening here is you're generating a WndProc function using Macros. Each MSG\_WM\_\* entry is a case statement that handles the given window message by translating its arguments from wParam and lParam into their original types and calling a helper function (which you then get to go implement) that takes those types as arguments (if appropriate—some window messages have 0 or 1 arguments).
In my opinion all this is crap. You're trading off having to write a bunch of boiler-plate up front but in exchange you make it much harder to debug later. Macros don't have much of a place in my modern programming world, other than to check if they are defined or not. Macros that do flow control, or assume specific local variables are always defined, etc, make me quite unhappy. Especially when I have to debug them. | Peter, you might as well ask if vi or EMACS is the better editor. (EMACS, by the way.) There are a lot of people who think the C preprocessor is a horrible idea; Stroustrup and Jim Gosling among them. That's why Java has no preprocessor, and there are innumerable things Stroustrup put into C++, from `const` to templates, to avoid using the preprocessor.
There are other people who find it convenient to be able to add a new language, as in that code.
If you read the original Bourne shell code, you'll find it looks like
```
IF a == b THEN
do_something();
do_more();
ELSE
do_less();
FI
```
Steve Bourne basically used macros to give it an Algol68-like look (that being the Really Cool Language then.) It could be very difficult to work with for anyone but Steve Bourne.
Then have a look at the Obfuscated C contest, where some of the most amazing obfuscations take advantage of the `#define`.
Personally, I don't mind too much, although that example is a little daunting (how do you debug that?) But doing that kind of thing is working without a net; there aren't many Wallendas out there. | Macros and Visual C++ | [
"",
"c++",
"visual-c++",
"macros",
"c-preprocessor",
""
] |
I need to write all my program output to a text file. I believe it's done this way,
```
sOutFile << stdout;
```
where sOutFile is the ofstream object that creates the file like this:
```
sOutFile("CreateAFile.txt" ); // CreateAFile.txt is created.
```
When I insert the stdout into the sOutFile object, I get some code which seems to resemble ~~octal~~ [hexadecimal] code or an address of some kind in the text file that I created.
```
0x77c5fca0
```
But what's confusing to me is that in my program I use cout several times. Mostly just literal statement. If I'm not mistaken that is the program output.
If this code is an address, would it contain all of my output? Could I read it back in to the program and find out that way?
What can I do to get ALL of my program output written to a text file? | This is a duplicate of: [this question](https://stackoverflow.com/questions/573724/how-can-i-redirect-stdout-to-some-visible-display-in-a-windows-application/573733)
You can redirect stdout, stderr and stdin using [`std::freopen`](http://en.cppreference.com/w/cpp/io/c/freopen).
From the above link:
```
/* freopen example: redirecting stdout */
#include <stdio.h>
int main ()
{
freopen ("myfile.txt","w",stdout);
printf ("This sentence is redirected to a file.");
fclose (stdout);
return 0;
}
```
You can also run your program via command prompt like so:
```
a.exe > stdout.txt 2> stderr.txt
``` | If your program already uses cout/printf and you want to send EVERYTHING you currently output to a file, you could simply redirect stdout to point to a file before your existing calls:
<http://support.microsoft.com/kb/58667>
Relevant Code:
```
freopen( "file.txt", "w", stdout );
cout << "hello file world\n"; // goes to file.txt
freopen("CON", "w", stdout);
printf("Hello again, console\n"); // redirected back to the console
```
Alternatively if you just want Some things to be printed to a file, you just want a regular file output stream: <http://www.cplusplus.com/doc/tutorial/files.html>
Relevant Code:
```
ofstream myfile;
myfile.open("file.txt");
myfile << "Hello file world.\n";
printf("Hello console.\n");
myfile.close();
```
EDIT to aggregate answers from John T and Brian Bondy:
Finally, if you're running it from the commandline, you can just redirect the output as everyone else mentioned by using the redirect operator ">" or append ">>":
```
myProg > stdout.txt 2> stderr.txt
``` | Writing ALL program output to a txt file in C++ | [
"",
"c++",
"file-io",
""
] |
I need to use PHP to copy data from one MySQL database to another.
I can build and array of all the values to go into the other database but first I want to make sure the database has the correct fields before inserting.
For example say I am going to be copying data from tableA to tableB.
I can set up tableB to look just like tableA but in the future I may add columns to tableA and forget to add them to tableB, then my PHP script will try to insert data into a column that doesn't exist in tableB and it will fail.
So what I want to do is compare tableA to tableB and any columns that tableA has that tableB doesn't have add them to tableB.
Can anyone tell me how to do this? | Thanks everyone, based on all your help I was able to write a PHP class that copies any columns from table A to table B if they are not already there:
```
class MatchTable
{
var $_table_one_name;
var $_table_two_name;
var $_table_one_db_user;
var $_table_one_db_pass;
var $_table_one_db_host;
var $_table_one_db_name;
var $_table_two_db_user;
var $_table_two_db_pass;
var $_table_two_db_host;
var $_table_two_db_name;
var $_table_one_columns = array();
var $_table_two_columns = array();
var $_table_one_types = array();
var $_table_two_types = array();
var $_table_one_link;
var $_table_two_link;
var $_isTest;
function MatchTable($isLive = true)
{
$this->_isTest = !$isLive;
}
function matchTables($table1, $table2)
{
$this->_table_one_name = $table1;
$this->_table_two_name = $table2;
if(isset($this->_table_one_db_pass))
{
$this->db_connect('ONE');
}
list($this->_table_one_columns,$this->_table_one_types) = $this->getColumns($this->_table_one_name);
if(isset($this->_table_two_db_pass))
{
$this->db_connect('TWO');
}
list($this->_table_two_columns,$this->_table_two_types) = $this->getColumns($this->_table_two_name);
$this->addAdditionalColumns($this->getAdditionalColumns());
}
function setTableOneConnection($host, $user, $pass, $name)
{
$this->_table_one_db_host = $host;
$this->_table_one_db_user = $user;
$this->_table_one_db_pass = $pass;
$this->_table_one_db_name = $name;
}
function setTableTwoConnection($host, $user, $pass, $name)
{
$this->_table_two_db_host = $host;
$this->_table_two_db_user = $user;
$this->_table_two_db_pass = $pass;
$this->_table_two_db_name = $name;
}
function db_connect($table)
{
switch(strtoupper($table))
{
case 'ONE':
$host = $this->_table_one_db_host;
$user = $this->_table_one_db_user;
$pass = $this->_table_one_db_pass;
$name = $this->_table_one_db_name;
$link = $this->_table_one_link = mysql_connect($host, $user, $pass, true);
mysql_select_db($name) or die(mysql_error());
break;
case 'TWO';
$host = $this->_table_two_db_host;
$user = $this->_table_two_db_user;
$pass = $this->_table_two_db_pass;
$name = $this->_table_two_db_name;
$link = $this->_table_two_link = mysql_connect($host, $user, $pass, true);
mysql_select_db($name) or die(mysql_error());
break;
default:
die('Improper parameter in MatchTable->db_connect() expecting "one" or "two".');
break;
}
if (!$link) {
die('Could not connect: ' . mysql_error());
}
}
function getColumns($table_name)
{
$columns = array();
$types = array();
$qry = 'SHOW COLUMNS FROM '.$table_name;
$result = mysql_query($qry) or die(mysql_error());
while($row = mysql_fetch_assoc($result))
{
$field = $row['Field'];
$type = $row['Type'];
/*
$column = array('Field' => $field, 'Type' => $type);
array_push($columns, $column);
*/
$types[$field] = $type;
array_push($columns, $field);
}
$arr = array($columns, $types);
return $arr;
}
function getAdditionalColumns()
{
$additional = array_diff($this->_table_one_columns,$this->_table_two_columns);
return $additional;
}
function addAdditionalColumns($additional)
{
$qry = '';
foreach($additional as $field)
{
$qry = 'ALTER TABLE '.$this->_table_two_name.' ADD '.$field.' '.$this->_table_one_types[$field].'; ';
if($this->_isTest)
{
echo $qry.'<br><br>';
}
else
{
mysql_query($qry) or die(mysql_error());
}
}
}
/**
* End of Class
*/
}
``` | you could look into some phpclasses that do this for you
<http://www.phpclasses.org/search.html?words=mysql+sync&x=0&y=0&go_search=1> | How can i synchronize two database tables with PHP? | [
"",
"php",
"mysql",
"synchronization",
""
] |
```
class logger {
....
};
logger& operator<<(logger& log, const std::string& str)
{
cout << "My Log: " << str << endl;
return log;
}
logger log;
log << "Lexicon Starting";
```
Works fine, but i would like to use a pointer to a class instance instead. i.e.
```
logger * log = new log();
log << "Lexicon Starting";
```
Is this possible? If so what is the syntax? Thanks
Edit: The compiler Error is
```
error: invalid operands of types 'logger*' and 'const char [17]' to binary 'operator<<'
``` | You'd have to dereference the pointer to your logger object and obviously check if it's not 0. Something like this should do the job:
```
log && ((*log) << "Lexicon starting")
```
As a general aside, I would shy away from referencing objects like a logger (which you normally unconditionally expect to be present) via a pointer due to the uncertainty you get with a pointer, AKA is there an object or not? | Here is the way:
```
logger * log = new log();
(*log) << "Lexicon Starting";
``` | Overloading << operator C++ - Pointer to Class | [
"",
"c++",
"pointers",
"operator-overloading",
""
] |
I am trying to parse an html page with BeautifulSoup, but it appears that BeautifulSoup doesn't like the html or that page at all. When I run the code below, the method prettify() returns me only the script block of the page (see below). Does anybody has an idea why it happens?
```
import urllib2
from BeautifulSoup import BeautifulSoup
url = "http://www.futureshop.ca/catalog/subclass.asp?catid=10607&mfr=&logon=&langid=FR&sort=0&page=1"
html = "".join(urllib2.urlopen(url).readlines())
print "-- HTML ------------------------------------------"
print html
print "-- BeautifulSoup ---------------------------------"
print BeautifulSoup(html).prettify()
```
The is the output produced by BeautifulSoup.
```
-- BeautifulSoup ---------------------------------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="JavaScript">
<!--
function highlight(img) {
document[img].src = "/marketing/sony/images/en/" + img + "_on.gif";
}
function unhighlight(img) {
document[img].src = "/marketing/sony/images/en/" + img + "_off.gif";
}
//-->
</script>
```
Thanks!
UPDATE: I am using the following version, which appears to be the latest.
```
__author__ = "Leonard Richardson (leonardr@segfault.org)"
__version__ = "3.1.0.1"
__copyright__ = "Copyright (c) 2004-2009 Leonard Richardson"
__license__ = "New-style BSD"
``` | Try with version 3.0.7a as [Łukasz](https://stackoverflow.com/questions/601166/issues-with-beautifulsoup-parsing/601636#601636) suggested. BeautifulSoup 3.1 was designed to be compatible with Python 3.0 so they had to change the parser from SGMLParser to HTMLParser which seems more vulnerable to bad HTML.
From the [changelog for BeautifulSoup 3.1](http://www.crummy.com/software/BeautifulSoup/CHANGELOG.html):
"Beautiful Soup is now based on HTMLParser rather than SGMLParser, which is gone in Python 3. There's some bad HTML that SGMLParser handled but HTMLParser doesn't" | Try [lxml](http://codespeak.net/lxml/). Despite its name, it is also for parsing and scraping HTML. It's much, much faster than BeautifulSoup, and it even handles "broken" HTML better than BeautifulSoup, so it might work better for you. It has a compatibility API for BeautifulSoup too if you don't want to learn the lxml API.
[Ian Blicking agrees](http://blog.ianbicking.org/2008/12/10/lxml-an-underappreciated-web-scraping-library/).
There's no reason to use BeautifulSoup anymore, unless you're on Google App Engine or something where anything not purely Python isn't allowed. | Issues with BeautifulSoup parsing | [
"",
"python",
"beautifulsoup",
""
] |
Okay, now I've been using drawImage in java for a while, and this has never happened before. Why can't it find `"drawImage(java.awt.image.BufferedImage,<nulltype>,int,int)"` in my code?
```
import java.awt.*;
import javax.swing.*;
import javax.swing.JPanel;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import java.util.Arrays;
import javax.imageio.ImageIO;
public class imgtest extends JFrame{
BufferedImage img;
Graphics g2d;
/**
* Creates a new instance of imgtest.
*/
public imgtest() {
File file = new File("test.png");
img = ImageIO.read(file);
}
/**
* @param args the command line arguments
*/
public void paint(Graphics g)
{
g2d = (Graphics2D)g;
g2d.drawImage(img, null, 0, 0);
}
public static void main(String[] args) {
imgtest i = new imgtest();
i.setSize(640,480);
i.setVisible(true);
i.repaint();
// TODO code application logic here
}
}
``` | You've declared `g2d` as a `Graphics` object, and `Graphics` doesn't have the `drawImage(BufferedImage, BufferedImageOp, int, int)` method. Fix: replace the line
```
Graphics g2d;
```
with
```
Graphics2D g2d;
```
When Java is looking for attributes of an object that's stored in a variable like this, it always uses the declared type of the variable, namely `Graphics`. The fact that you casted `g` to a `Graphics2D` doesn't make a difference unless you actually store it in a variable of type `Graphics2D`. | Along with what other have said about needing to decalre it is a Graphics2D, take it out of the instance variables and make it a local variable. There is no point in having an instance variable that is used in only one method and always has the value overwitten each time that method is called. Instance variables are used to persist state between method calls... you are not doing that here.
```
public void paint(Graphics g)
{
final Graphics2D g2d;
g2d = (Graphics2D)g;
g2d.drawImage(img, null, 0, 0);
}
``` | "cannot find symbol method drawImage(java.awt.image.BufferedImage,<nulltype>,int,int)" | [
"",
"java",
"image",
"swing",
""
] |
I'm trying to run msbuild on a solution that has some C++ code in it.
I have the SDK installed but not Visual Studio.
I get the following error:
error MSB3411: Could not load the Visual C++ component "VCBuild.exe". If the component is not installed, either 1) install the Microsoft Windows SDK for Windows Server 2008 and .NET Framework 3.5, or 2) install Microsoft Visual Studio 2008.
I have vcbuild.exe under
C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\vcpackages
How can make MSBuild find it? | It might be as simple as vcbuild.exe not being in the path. IIRC, at least the visual studio installer doesn't automatically add the command line tools to the system or user path and you have to run vcvars32.bat to set them first before you can kick off the build. | You can download the required windows SDK here: <http://www.microsoft.com/downloads/thankyou.aspx?familyId=e6e1c3df-a74f-4207-8586-711ebe331cdc&displayLang=en> | running msbuild without having VS installed | [
"",
".net",
"c++",
"msbuild",
""
] |
In our application we have style sheets to define common colors etc… I wrote a quick and dirty function where I get a dataset from a stored procedure, lop off the columns that I don’t want to show, cram it into a programmatically generated DataGrid, set that DataGrid’s styles, then export it to Excel. Everyone loves the colors in the Excel output (Gasp! They match the DataGrid colors, blah blah blah…).
My final piece I would like to add to it is that I would like to programmatically access a style and grab color codes and other items from it (.IntranetGridHead) instead of hard coding them, which is what I am doing now.
```
int iHeaderColor = Convert.ToInt32 ("D0D7E8", 16);
DataGrid dg = new DataGrid();
dg.DataSource = dsReturnDataSet.Tables[0].DefaultView;
dg.DataBind();
dg.HeaderStyle.BackColor = System.Drawing.Color.FromArgb(iHeaderColor);
dg.HeaderStyle.Font.Bold = true;
dg.HeaderStyle.Font.Size = 10;
```
Obviously then whenever the company goes through another “rebranding” and the style sheet values change, the excel colors will automatically match and I will get a big (pat on the back||cookie).
Any thoughts from the C# people who know more than I (which would be most of you…)?
Thanks,
Michael | All Web.UI.Control objects have a .Styles property, which can be accessed as Styles["Name"]. Therefore you can do this:
```
DataTable dt = LookupStyles();
dg.Styles.Clear();
foreach (DataRow dr in dt.Rows)
dg.Styles.Add(dr["StyleName"].ToString(), dr["StyleValue"].ToString());
```
I had a similar thought several months ago :) Note for this to work right, your grid must be runat="server".
Edit:
Looks like you want to READ the grid and use that... If you're using a .CssStyle and a Stylesheet (.css), you'll have to do an HTTP GET to that css file and parse it yourself. | I wrote something along these lines a while back. It involved a HttpHandler to deal with the CSS files, a change to the IIS config to get asp.net to receive the requests for the CSS files, and a simple xml file structure which contained my colour definitions. But you've done that with a database, which is fine too.
Then in the CSS I had something like this ...
```
.button
{
background-color: $colours:button-background-colour;
color: $colours:button-text-colour;
}
```
with my xml defining the values for button-background-colour and button-text-colour. I used regular expression text replacement to process the CSS file substituting in the relevant values from the xml file.
I'm sure you could take some of those ideas and combine it with your existing code to get the desired effect. You will of course need to deal with caching and changes to your database/xml file.
Hope that helps.
If you need any pointers on any of that then I'm sure I can dig out some example code. | Accessing styles programmatically to get values | [
"",
"c#",
"asp.net",
"stylesheet",
""
] |
I have a class that manages user preferences for a large software project. Any class in the project that may need to set or retrieve a user preference from a persistent store is to call the static methods on this class. This centralized management allows the preferences to be completely wiped programmatically - which would be impossible if each pref was handled close to its use code, sprinkled throughout the project.
I ran into another implication of the centralization design in the course of this. The software has a public API. That API can be provided by itself in a jar. Classes in that API might refer to the pref management class. So, the pref manager has to go in the API jar.
Each preference might have a default value. Upon software startup, that default might be computed. The algorithm depends on the preference, and thus tends to reside near the use code. So if the pref manager needs to come up with a default, it calls the class in question.
But now that pref manager has become an "octopus class", sucking in all sorts of classes into the API jar that shouldn't be there. If it doesn't, then programs using the API jar quickly run into ClassDef exceptions. If it does, then the API jar is now bloated, as each of those other classes may refer to still others.
In general, do other Java programmers manage their preferences with a centralized class?
Does it make sense to distribute that static pref management class as part of a public API?
Should that pref manager be the keeper of the code for determining defaults? | IMHO, I think that the answer to your first question is "yes" and "no".
Preferences are commonly handled as a centralized class, in the sense that the class is a "sink" for many classes in the project. Trying to do it closer to the calling code means that if the same preference is later useful elsewhere, you are in trouble. In my experience, trying to put the preferences "too close" also results in a very inconsistent handling.
That being said, it is often preferable to use multiple preference classes or "preference set", each supporting a module or submodule. If you look at the main components of your architecture, you will often find that the set of preferences can be logically partitioned. This reduces the mess in each preference class. More importantly, it will allow you to split your program into multiple jars in the future. Now, the "default value" calculators can be placed in the module but still in a global enough area.
I would also suggest not setting preferences directly as static methods, but rather using some getInstance() like operation to obtain a shared instance of the preferences manage, and then operating on it. Depending on your semantics, you may want to lock that object for a while (e.g., while the user is editing preferences in a UI) and this is easier if you have an actual object.
For your other questions, I would say that your public API should have a way of letting users change preferences, but only if you can document well enough what the results of these changes could be.
If you use a single API function to get the "reference manager", you can give users the possibility of providing their own "default values calculator". The preference manager will ask this calculator first before resorting to the one you have provided by default. | Can't you just handle preferences in a really generic way? You'd then just use the preference manager to handle the persistence. So from a class you'd just say to the preference manager PreferenceManager.setPreference(key, value) and it doesn't care what it's saving in terms of the semantics of the data.
Or am I simplifying this too much? | Is a "master preferences" class a good idea? | [
"",
"java",
"design-patterns",
""
] |
I'm in a school project on information security, and one of the assignments is to write some secure pages in PHP. None of the people on my group know PHP, that is not a big problem though, we'll learn enough to create the simple pages needed.
One of the tips the students assistants have given is to use the two functions `strip_tags()` and `mysqli_real_escape_string()`. I assume these are safe, but without indepth knowledge I don't feel certain. Some simple Google-searches reveals at least that there has been vulnerabilities in the past. As part of the assignment is to try to break the other groups systems, it is important both that our own system is safe, and to find possible vulnarabilites in the other group's systems. And most of the groups will use these two functions blindly. So my questions are:
1. Is there any known vulnerabilities in `strip_tags()`?
2. Is there any known vulnerabilities in `mysqli_real_escape_string()`?
3. Is there a natural place to search for such vulnerabilities (other than asking StackOverflow)? | First, I would recommend that you use [Mysqli Prepared Statements](http://devzone.zend.com/node/view/id/686). These are [more secure](http://ilia.ws/archives/103-mysql_real_escape_string-versus-Prepared-Statements.html) than the escape functions as it entirely separates the query structure from the query parameters.
You can use [either](http://shiflett.org/articles/foiling-cross-site-attacks) strip\_tags or htmlentities to make certain that no malicious code is being output to the browser. You'll also probably want to run [all](http://joelonsoftware.com/articles/Wrong.html) dynamic content through some sort of filter function before outputting it to the browser. This is one area where a well-organized and cohesive OO approach can help because you can assign all dynamic content to a single object which is then responsible for rendering the output to the browser so that you can always feel safe knowing that your content is XSS safe without having to search through hundreds of echo statements across multiple pages.
However, these two suggestions really only touch the tip of the iceberg when it comes to PHP security. There are a number of other issues that have to also be dealt with such as:
* [Secure Session Management](http://shiflett.org/articles/the-truth-about-sessions)
* [Session Fixation](http://shiflett.org/articles/session-fixation)
I would recommend that you take a look at the following sites for additional, and more comprehensive treatment on the topic of PHP security:
* [shiflett.org](http://shiflett.org/articles)
* [phpsecurity.org](http://phpsecurity.org/) (This is another Chris Shiflett site, but I'm not certain whether he has additional content here that isn't on his personal site)
* [phpsec.org](http://phpsec.org/) Not as much content there as I would like, but there are some useful things to know such as making certain configuration files that contain sensitive information (like database passwords) are not stored in publicly available directories.
On that final item, if it is possible, you will want to look into using .htaccess files or their IIS equivalent to make certain only the files you intend access to are publicly available. Otherwise, all of your other security measures will be vain.
**Update:** I thought of a couple other issues relating to security in your project. If you remember the unfortunate incident with a Twitter administrator's account being hacked a little bit ago, it was allowed to happen for several reasons that could have all been easily resolved.
1) Password log in attempts where not throttled. In other words if a user attempts to log in and fails then a repeat request from their IP might require 2 seconds to process the second time, then 4 the next and so on. This makes it impractical for a bot to make continuous log in attempts.
2) Secure passwords were not required. As passwords have higher requirements (length and types of characters required such as alphanumeric and special characters), then dictionary attacks become altogether impractical because it is much easier to throw a dictionary at hacking a password than it is to come up with random strings of numbers and letters. Also the amount of time crack a password increases exponentially as more characters are added.
You can see [this post](http://www.codinghorror.com/blog/archives/001206.html) from Jeff Atwood for more information on this particular topic. | For PHP bugs: [bugs.php.net](http://bugs.php.net/) | Security of strip_tags() and mysqli_real_escape_string() | [
"",
"php",
"security",
""
] |
Has anyone had any experience with using the [STEP](http://en.wikipedia.org/wiki/Standard_for_the_Exchange_of_Product_model_data/ "STEP") and [EXPRESS](http://en.wikipedia.org/wiki/EXPRESS_(data_modeling_language)/ "EXPRESS") formats in a .Net environment?
I am looking for a tool that will generate a c# class structure based on an EXPRESS schema. I would also like the tool to create a parser/file generator for importing and exporting to STEP-files.
Does anyone know of a tool that does this? Any tools that will bring me closer to my own implementation would also be useful. | There is a list of tools you might be interested in on the [PDES website](http://www.pdesinc.com/free_STEP.html). Some of these tools allows for example to generate a XML representation of your EXPRESS schema. It might then be easier to implement your tool from there.
It looks like [Open CASCADE](http://www.opencascade.org/) is open source and developed in a .NET environment. | I know this is an old question, but I thought I'd answer for anyone else who stumbles upon it.
If you need to work with `STEP` and `EXPRESS` and don't want CAD libraries, or if you need an uncommon or custom schema, take a look at (**shameless plug!**) [STEPcode](http://github.com/stepcode/stepcode), which uses the BSD license.
It generates `C++`, not `C#` - but IMO it would be far easier to modify SCL than to start from scratch.
Note that this was formerly known as Step Class Library, the same `SCL` that @roch mentions above. A group of people are improving it, and the NIST version is very dated.
**edit:** new name, new URL | STEP/EXPRESS tools for .NET | [
"",
"c#",
".net",
"code-generation",
"step",
""
] |
I've been reading Josh Bloch's 'Effective Java 2nd Edition'. Item 43 states 'Return empty arrays or collections, not nulls'. My question is how can I search for all methods in a project that return an implementation of java.util.Collection interface? IDE that is used is Eclipse, but any way of finding the right result is acceptable, e.g. regex or some other IDE. | Found this in Eclipse Help:
To search for methods with a specific return type, use "\* " as follows:
1. Open the search dialog and click on
the Java Search tab.
2. Type '\*' and
the return type, separated by a
space, in the Search string.
3. Select
the Case sensitive checkbox.
4. Select
Method and Declarations and then
click Search.
It can help finding all methods that return specific types but not implementations of some interface. | Thanks for mentioning SemmleCode. To find all methods in the source that return a subtype of java.util.Collection, you write:
```
import default
class CollectionType extends RefType {
CollectionType() {
this.getASupertype*().hasQualifiedName("java.util","Collection")
}
}
from Method m
where m.getType() instanceof CollectionType
and
m.fromSource()
select m
```
That is, we first define what we mean by a CollectionType: all types that have java.util.Collection as a supertype. There's a star behind getASupertype because we want to apply that operation zero or more times. Next we just select those methods whose return type is such a CollectionType and which occur in the source.
Go on, try it out :-) It's an easy exercise to further refine the query to those methods that are supposed to return a CollectionType but may return null. All this can be done interactively, with auto-completion while you develop the query, and continuous checking to help you get it right. You can view the results in many different ways and navigate between analysis results and code with ease.
-Oege
[disclosure: I'm the CEO of Semmle] | How to search for all methods in a project that return implementation of Collection interface? | [
"",
"java",
"regex",
"search",
"methods",
"return-type",
""
] |
I have an HTML form that submits to a PHP page which initiates a script. The script can take anywhere from 3 seconds to 30 seconds to run - the user doesn't need to be around for this script to complete.
Is it possible to initiate a PHP script, immediately print "Thanks" to the user (or whatever) and let them go on their merry way while your script continues to work?
In my particular case, I am sending form-data to a php script that then posts the data to numerous other locations. Waiting for all of the posts to succeed is not in my interest at the moment. I would just like to let the script run, allow the user to go and do whatever else they like, and that's it. | I ended up with the following.
```
<?php
// Ignore User-Requests to Abort
ignore_user_abort(true);
// Maximum Execution Time In Seconds
set_time_limit(30);
header("Content-Length: 0");
flush();
/*
Loooooooong process
*/
?>
``` | Place your long term work in another php script, for example
background.php:
```
sleep(10);
file_put_contents('foo.txt',mktime());
```
foreground.php
```
$unused_but_required = array();
proc_close(proc_open ("php background.php &", array(), $unused_but_required));
echo("Done);
```
You'll see "Done" immediately, and the file will get written 10 seconds later.
I think proc\_close works because we've giving proc\_open no pipes, and no file descriptors. | Abandon Long Processes in PHP (But let them complete) | [
"",
"php",
"scripting",
""
] |
[This MSDN article](http://msdn.microsoft.com/en-us/library/ms235450.aspx) states that getcwd() has been deprecated and that the ISO C++ compatible \_getcwd should be used instead, which raises the question: what makes getcwd() not ISO-compliant? | Functions not specified in the standard are supposed to be prefixed by an underscore as an indication that they're vendor-specific extensions or adhere to a non-ISO standard. Thus the "compliance" here was for Microsoft to add an underscore to the name of this specific function since it's not part of the ISO standard. | There is a [good discussion](https://groups.google.com/group/comp.os.ms-windows.programmer.misc/msg/e668fa9f36e57c67) about that. [P.J. Plauger](http://en.wikipedia.org/wiki/PJ_Plauger) answers to this
> I'm the guy who insisted back in 1983 that the space of
> names available to a C program be partitioned into:
>
> **a)** those defined by the implementation for the benefit of the programmer (such as printf)
> **b)** those reserved to the programmer (such as foo)
> **c)** those reserved to the implementation (such as \_unlink)
>
> We knew even then that "the implementation" was too monolithic --
> often more than one source supplies bits of the implementation --
> but that was the best we could do at the time. Standard C++
> has introduced namespaces to help, but they have achieved only
> a fraction of their stated goals. (That's what happens when you
> standardize a paper tiger.)
>
> In this particular case, Posix supplies a list of category (a) names
> (such as unlink) that you should get defined when and only when you
> include certain headers. Since the C Standard stole its headers from
> Unix, which is the same source as for Posix, some of those headers
> overlap historically. Nevertheless, compiler warnings should have
> some way of taking into account whether the supported environment
> is "pure" Standard C++ (a Platonic ideal) or a mixed C/C++/Posix
> environment. The current attempt by Microsoft to help us poor
> programmers fails to take that into account. It insists on treating
> unlink as a category (b) name, which is myopic.
Well, GCC will not declare POSIX names in strict C mode, at least (though, it still does in C++ mode):
```
#include <stdio.h>
int main() {
&fdopen;
return 0;
}
```
Output using `-std=c99`
```
test.c: In function 'main':
test.c:4: error: 'fdopen' undeclared (first use in this function)
```
You will have to tell it explicitly that you are operating in a mixed C/Posix by using feature test macros or not passing any specific standard. It will then default to `gnu89` which assumes a mixed environment (`man feature_test_macros`). Apparently, MSVC does not have that possibility. | Why is getcwd() not ISO C++ compliant? | [
"",
"c++",
"iso",
""
] |
I'm a programmer with 2 years experience, I worked in 4 places and I really think of myself as a confident, and fluent developer.
Most of my colleagues have CS degrees, and I don't really feel any difference! However, to keep up my mind on the same stream with these guys, I studied C (read beginning C from novice to professional), DataStructures with C, and also OOP with C++.
I have a reasonable understanding of pointers, memory management, and I also attended a scholarship which C, DataStructures, and C++ were a part of it.
I want to note that my familiarity with C and C++ does not exceed reading some pages, and executing some demos; **I haven't worked on any project using C or C++**.
Lately a friend of mine advised me to learn C, and C++ extensively, and then move to OpenGL and learn about graphics programming. He said that the insights I may gain by learning these topics will really help me throughout my entire life as a programmer.
PS: I work as a full-time developer mostly working on ASP.NET applications using C#.
**Recommendations**? | **For practical advancement:**
From a practical sense, pick a language that suites the domain you want to work in.
There is no need to learn C nor C++ for most programming spaces. You can be a perfectly competent programmer without writing a line of code in those languages.
If however you are not happy working in the exact field you are in now, you can learn C or C++ so that you may find a lower level programming job.
**Helping you be a better programmer:**
You can learn a lot from learning multiple languages though. So it is always good to broaden your horizons that way.
If you want more experience in another language, and have not tried it yet, I would recommend to learn a functional programming language such as Scheme, Lisp, or Haskell. | First, having a degree has nothing to do with knowing C++. I know several people who graduated from CS without ever writing more than 50 lines of C/C++. CS is not *about* programming (in the same sense that surgery is not *about* knives), and it certainly isn't about individual languages. A CS degree requires you to poke your nose into several different languages, on your way to somewhere else. CS teaches the underlying concepts, an understanding of compilers, operating systems, the hardware your code is running on, algorithms and data structures and many other fascinating subjects. But it doesn't teach programming. Whatever programming experience a CS graduate has is almost incidental. It's something he picked up on the fly, or because of a personal interest in programming.
Second, let's be clear that it's very possible to have a successful programming career without knowing C++. In fact, I'd expect that most programmers fall into this category. So you certainly don't *need* to learn C++.
That leaves two possible reasons to learn C++:
1. Self-improvement
2. Changing career track
#2 is simple. If you want to transition to a field where C++ is the dominant language, learning it would obviously be a good idea. You mentioned graphics programming as an example, and if you want to do that for a living, learning C++ will probably be a good idea. (however, I don't think it's a particularly good suggestion for "insights that will help throughout your live as a programmer". There are other fields that are much more generally applicable. Learning graphics programming will teach you graphics programming, and not much else.)
That leaves #1, which is a bit more interesting. Will you become a better programmer simply by knowing C++? Perhaps, but not as much as some may think. There are several useful things that C++ may teach you, but there also seems to be a fair bit of superstition about it: it's low-level and has pointers, so by learning C++, you will achieve enlightenment.
If you want to understand what goes on under the hood, C or C++ will be helpful, sure, but you could cut out the middle man and just go directly into learning about compilers. That'd give you an even better idea. Supplement that with some basic information on how CPU's work, and a bit about operating systems as well, and you've learned all the underlying stuff much better than you would from C++.
However, some things I believe are worth picking up from C++, in no particular order:
(several of them are likely to make you despair at C#, which, despite adopting a lot of brilliant features, is still missing out some that to a C++ programmer seems blindingly obvious)
* Paranoia: Becoming good at C++ implies becoming a bit of a language lawyer. The language leaves a lot of things undefined or unspecified, so a good C++ programmer is paranoid. "The code I just wrote *looks* ok, and it seems to be have ok when I run it - but is it well-defined by the standard? Will it break tomorrow, on his computer, or when I compile with an updated compiler? I have to check the standard". That's less necessary in other languages, but it may still be a healthy experience to carry with you. Sometimes, the compiler doesn't have the final word.
* RAII: C++ has pioneered a pretty clever way to deal with resource management (including the dreaded memory management). Create an object on the stack, which in its constructor acquires the resource in question (database connection, chunk of memory, a file, a network socket or whatever else), and in its destructor ensures that this resource is released. This simple mechanism means that you virtually never write new/delete in your top level code, it is always hidden inside constructors or destructors. And because destructors are guaranteed to execute when the object goes out of scope, even if an exception is thrown, your resource is guaranteed to be released. No memory leaks, no unclosed database connections. C# doesn't directly support this, but being familiar with the technique sometimes lets you see a way to emulate it in C#, in the cases where it's useful. (Obviously memory management isn't a concern, but ensuring that database connections are released quickly might still be)
* Generic programming, templates, the STL and metaprogramming: The C++ standard library (or the part of it commonly known as the STL) is a pretty interesting example of library design. In some ways, it is lightyears ahead of .NET or Java's class libraries, although LINQ has patched up some of the worst shortcomings of .NET. Learning about it might give you some useful insights into clever ways to work with sequences or sets of data. It also has a strong flavor of functional programming, which is always nice to poke around with. It's implemented in terms of templates, which are another remarkable feature of C++, and template metaprogramming may be beneficial to learn about as well. Not because it is directly applicable to many other languages, but because it might give you some ideas for writing more generic code in other languages as well.
* Straightforward mapping to hardware: C++ isn't necessarily a low level language. But most of its abstractions have been modelled so that they *can* be implemented to map directly to common hardware features. That means it might help provide a good understanding of the "magic" that occurs between your managed .net code and the CPU at the other end. How is the CLR implemented, what do the heap and stack actually mean, and so on.
* p/invoke: Let's face it, sometimes, .NET doesn't offer the functionality you need. You have to call some unmanaged code. And then it's useful to actually know the language you might be using. (if you can get around it with just a single pinvoke call, you only need to be able to read C function signatures on MSDN so you know which arguments to pass, but sometimes, it may be preferable to write your own C++ wrapper, and call into that instead.
I don't know if you should learn C++. There are valid reasons why doing so may make you a better programmer, but then again, there are plenty of other things you could spend your time on that would also make you a better programmer. The choice is yours. :) | As a programmer with no CS degree, do I have to learn C++ extensively? | [
"",
"c++",
"c",
""
] |
**BACKGROUND:** I have a custom class written in C# (2005), with code similar to the following:
```
public class Savepoint
{
public int iOffset; /* Starting offset in main journal */
public u32 nOrig; /* Original number of pages in file */
public u32 iSubRec; /* Index of first record in sub-journal */
};
```
After a variable has been declared with **Savepoint sp;** I can test to see if has been instantiated with code similar to:
```
if (sp != null) {...}
```
**QUESTION:** Is it possible to overload the class operator somehow so that I can also use the following syntax as well: **if (sp) {...}** or **if (sp != 0) {...}**
PS: I have no real good reason for wanting to write if (sp) other than force of habit. | I think you can add an implicit cast to bool... something like this should work.
```
public static implicit operator bool(Savepoint sp)
{
return sp != null;
}
```
Example:
```
Savepoint sp1 = new Savepoint();
sp1.iOffset = 4;
Savepoint sp2 = new Savepoint();
Savepoint sp3 = null;
Console.WriteLine("sp1: " + (sp1 ? "true" : "false")); // prints true
Console.WriteLine("sp2: " + (sp2 ? "true" : "false")); // prints true
Console.WriteLine("sp3: " + (sp3 ? "true" : "false")); // prints false
``` | You might be able to do that in C# using the default property decorator, but you shouldn't. Trying to write C# like it was a duck-typed language will lead to all sorts of cognitive dissonance down the line.
As a rule of thumb, it's a good idea to embrace the vernacular of the language you're working in rather than trying to cram it into a more-familiar shape it was never meant to hold. | How can a C# class be written to test against 0 as well as null | [
"",
"c#",
"operator-overloading",
"class-design",
""
] |
I don't get why I get 0 when I use printf and %d to get the size of my vector:
```
vector<long long> sieve;
int size;
...
//add stuff to vector
...
size = sieve.size();
printf("printf sieve size: %d \n", size); //prints "printf sieve size: 0"
std::cout << "cout sieve size: ";
std::cout << size;
std::cout << " \n ";
//prints "cout sieve size: 5 (or whatever the correct sieve size is)"
```
If I iterate through the vector via
```
if(i=0;i<sieve.size();i++)
```
I get the correct number of iterations.
What am I doing wrong or what is up with printf? size() returns an int right??
---
Here's my entire little script:
```
#include <iostream>
#include <vector>
#include <stack>
#include <math.h>
int main (int argc, char * const argv[]) {
unsigned long long answer = 0;
unsigned long long cur = 2;
std::vector<long long> sieve;
unsigned long long limit;
unsigned long long value;
unsigned int i;
int size;
bool isPrime;
std::cout << "Provide a value to find its largest prime factor: ";
std::cin >> value;
limit = ceil(sqrt(value));
sieve.push_back(2);
while(cur++ < limit){
isPrime = true;
sieve.begin();
for(i=0; i<sieve.size();i++){
if(!(cur % sieve[i])){
isPrime = false;
break;
}
}
if(isPrime){
if(!(value % cur)){
std::printf("Is prime factor: %d\n", cur);
sieve.push_back(cur);
answer = sieve[sieve.size() - 1];
size = sieve.size();
std::printf("current last: %d sieve size: %ld\n", answer, size);
for(i=0; i<sieve.size();i++){
std::printf("sieve iter: %d sieve val: %d\n", i, sieve[i]);
std::cout << size;
std::cout << " wtf\n";
}
}
}
}
answer = sieve[sieve.size() - 1];
size = sieve.size();
std::printf("Limit: %d Answer: %d sieve size: %ld\n", limit, answer, size);
return 0;
}
``` | Now, with the complete source, it is clear.
You declared:
```
int size;
```
Then you used:
```
std::printf("current last: %d sieve size: %ld\n", answer, size);
std::printf("Limit: %d Answer: %d sieve size: %ld\n", limit, answer, size);
```
If size is int, you should use "%d", not "%ld". A good compiler would have warned you about this. GCC gives these warnings for your original version:
```
test.cpp: In function ‘int main(int, char* const*)’:
test.cpp:17: warning: converting to ‘long long unsigned int’ from ‘double’
test.cpp:30: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘long long unsigned int’
test.cpp:34: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘long long unsigned int’
test.cpp:34: warning: format ‘%ld’ expects type ‘long int’, but argument 3 has type ‘int’
test.cpp:36: warning: format ‘%d’ expects type ‘int’, but argument 3 has type ‘long long int’
test.cpp:45: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘long long unsigned int’
test.cpp:45: warning: format ‘%d’ expects type ‘int’, but argument 3 has type ‘long long unsigned int’
test.cpp:45: warning: format ‘%ld’ expects type ‘long int’, but argument 4 has type ‘int’
```
This tells a lot.
You should declare size as:
```
std::vector<long long>::size_type size;
```
Then you should use it as:
```
std::printf("current last: %llu sieve size: %llu\n", (unsigned long long) answer, (unsigned long long) size);
std::printf("Limit: %llu Answer: %llu sieve size: %llu\n", (unsigned long long) limit, (unsigned long long) answer, (unsigned long long) size);
```
Of course, using iostream avoids you these problems, specially the ugly casting in printf() to transform size to a type known to printf. | This is screwing up because you've got:
```
unsigned long long answer = 0;
int size;
```
and you call `printf` with:
```
std::printf("current last: %d sieve size: %ld\n", answer, size);
```
Both of your format strings are wrong:
1. You're passing `answer` to `printf` and formatting it `%d`, but it should be `%lld`, since it's declared `unsigned long long`.
2. You're passing size with `%d` instead of `%ld`. Since `size` is and `int`, it should be `%d`.
When those args get passed to printf, it's printing the first 32 bits of `answer` for the first `%d` and the second 32 bits (or more, past the end!) of `answer` for the `%ld`. This is **not** what you want.
If you compile with `-Wall` your compiler should warn you about this kind of thing. Pay very close attention to the warnings! | why does printf show a 0 for vector size when cout shows the correct size? | [
"",
"c++",
"vector",
"printf",
""
] |
I've been programming for a long time now, but I'm not the world's most experienced.Net developer. I recently picked up a project that is using Forms authentication for their website. I first looked at forms authentication in .Net 1.1 and at that time it had some limitations that made me decide not to use it as my primary form of authentication.
This project requires that users have roles (which I understand forms authentication supports) and group memberships. For example "User A" is an "Admin" for "Company A". Does forms authentication now support this sort of user structure?
I've also read that forms authentication sends passwords back as plain text. This client does not use SSL. Is this true?
The current code base uses forms authentication, but does not support groups (it does support roles). So, I need to either modify the forms authentication to support the required groups or rip out the forms authentication and use the Authentication framework I normally use. If forms authentication does support groups and is secure enough, then I should stick with that. If forms authentication has security issues or does not support groups then I need to remove that form of authentication.
I've searched the internet for a pros-and-cons sort of article, but no luck. What do you guys think? | To satisfy you requirements you will use Forms Authentication with [Membership](http://msdn.microsoft.com/en-us/library/yh26yfzy.aspx). If your application is using SQL Server database you can use [SQLMembershipProvider](http://msdn.microsoft.com/en-us/library/system.web.security.sqlmembershipprovider.aspx) as the membership provider to achieve this.
[Examining ASP.NET 2.0's Membership, Roles, and Profile](https://web.archive.org/web/20210513220018/http://aspnet.4guysfromrolla.com/articles/120705-1.aspx) can be a good start reference.
About your concern about sending passwords as a plain text when the connection is not secured.
Actually the passwords that are sent are usually hashed (algorithm will depend on the Membership Provider chosen) and that is as there are eventually stored.
Of course if the connection is not secured that hashed password can be retrieved and used to hack the application but at least you eliminate the possibility that the plain user password is stolen and used e.g. to access another service (as you know many people use the same password across multiple services). So to be secure you really need to use https here.
As a note of warning, I am far from being an expert in that field, but quite recently I was faced with a similar problem that you are describing so I though that you may find some of this useful. | Forms authentication doesn't sends passwords back as plain text. As long as you make sure the login/pwd is protected when receiving it (i.e. using https ... ssl) there is no security risk in there.
If you really need to do authorization that way, you can rely on forms authentication for ... authentication, and do authorization with your own mechanism. | Forms Authentication | [
"",
"c#",
".net",
"asp.net",
"authentication",
""
] |
I noticed that my programs written with wxPython have Win98 button style.
But Boa Constructor (that is written using wxPython too) got pretty buttons.
How to make buttons look like current Windows buttons style? | Are you packaging the app with py2exe?
If so you may need to specify a manifest file to make Python use the WinXP(Vista?) theme/Common Controls:
<http://wiki.wxpython.org/DistributingYourApplication> | Expanding on [John's answer](https://stackoverflow.com/questions/642853/winxp-button-style-with-wxpython/643165#643165), you may also be able to create manifest files for `python.exe` and `pythonw.exe` to see the new styles without first packaging using py2exe. | WinXP button-style with wxPython | [
"",
"python",
"coding-style",
"wxpython",
""
] |
Is there a PHP CMS that works the same way as the .NET CMS Umbraco?
Ie. All data output comes as XML and is transformed with xslt. And you as a developer have more or less total freedom to create any structure and output as you wish.
Reason for asking: Working primarily on OS X / Mac and I'm not very experienced with .NET and the Microsoft web dev. environment. | The XML/XSLT pipeline haven't really been that popular in the PHP world for two reasons: 1) It is perceived as heavyweight, compared to using PHP or some other similar template language and 2) Because of PHPs stateless nature, the performance isn't too good (Or at least hard to get right). | Umbraco really is very good and you don't need to know .net, that's the beauty, just some xslt.
It is even developed on a mac platform (admittedly in Fusion).
But I understand you wanting to stick with your strengths, so try symphony cms
<http://symphony-cms.com/>
Jay | CMS similar to Umbraco but in PHP? | [
"",
".net",
"php",
"umbraco",
""
] |
How would I go about reordering divs without altering the HTML source code?
example, I want divs to appear in order #div2, #div1, #div3, but in the HTML they are:
```
<div id="#div1"></div>
<div id="#div2"></div>
<div id="#div3"></div>
```
Thanks! | There is no catch-all way of reordering elements with css.
You can inverse their order horizontally by floating them all to the right. Or you can position them absolutely relative to the body or some other containing element - but that comes with severe limitations regarding the size of the elements, and positioning relative to other elements on the page.
Short answer: You can only achieve this in a very limited set of circumstances. Reordering elements is best done in markup.
If you have no control over the html, you could use javascript. Here using jQuery:
```
$("#div2").insertAfter("#div3");
$("#div1").prependTo("#div2");
```
I certainly don't recommend that unless your hands are tied. It will be harder to maintain, and for your end users it will make your page "jerk around" while its setting up the page. | Since now [flexbox](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) is widely supported you can also use it to reorder divs using only css:
```
<div id="container">
<div id="div1">1</div>
<div id="div2">2</div>
<div id="div3">3</div>
</div>
```
And css:
```
#container{
display: flex;
flex-direction: column;
}
#div2{
order:2
}
#div3{
order:1
}
```
It would display:
```
1
3
2
```
You can try it on this [fiddle](https://jsfiddle.net/2jse4h44/). | How can I reorder elements with JavaScript? | [
"",
"javascript",
"jquery",
"html",
"css",
""
] |
What is the quickest way to HTTP GET in Python if I know the content will be a string? I am searching the documentation for a quick one-liner like:
```
contents = url.get("http://example.com/foo/bar")
```
But all I can find using Google are `httplib` and `urllib` - and I am unable to find a shortcut in those libraries.
Does standard Python 2.5 have a shortcut in some form as above, or should I write a function `url_get`?
1. I would prefer not to capture the output of shelling out to `wget` or `curl`. | Python 3:
```
import urllib.request
contents = urllib.request.urlopen("http://example.com/foo/bar").read()
```
Python 2:
```
import urllib2
contents = urllib2.urlopen("http://example.com/foo/bar").read()
```
Documentation for [`urllib.request`](https://docs.python.org/library/urllib.request.html) and [`read`](https://docs.python.org/tutorial/inputoutput.html#methods-of-file-objects). | Use the [Requests](https://docs.python-requests.org/en/latest/) library:
```
import requests
r = requests.get("http://example.com/foo/bar")
```
Then you can do stuff like this:
```
>>> print(r.status_code)
>>> print(r.headers)
>>> print(r.content) # bytes
>>> print(r.text) # r.content as str
```
Install Requests by running this command:
```
pip install requests
``` | What is the quickest way to HTTP GET in Python? | [
"",
"python",
"http",
"networking",
""
] |
I am writing a small Java app (on Windows, hence the \_on\_vista appended to my name).
I got 3 buttons, all of which will react to a click event, but do different things.
Is the following code the accepted way or is there a cleaner way I do not know about?
On one half, it works, on the other half, something doesn't seem right...
Thanks
```
cool_button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
coolfunction1();
}
});
cool_button_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
coolfunction2();
}
});
// etc ...
```
The functions that get called will spawn off threads as needed, so on and so forth.
**UPDATE** - Both were good (pretty much the same) answers. I accepted the one with the lower rep to share the wealth. Thanks again guys. | Yes, this is the correct way to do this. It's a bit clumsy (to have to write five long lines of code just to be able to call a method) but that's Java :( | That’s not too bad. I prefer to use [Actions](http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/Action.html) and create [JButtons](http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JButton.html) from them:
```
Action fooAction = new AbstractAction() { ... };
JButton fooButton = new JButton(fooAction);
``` | Java event handlers | [
"",
"java",
"swing",
"event-handling",
""
] |
How can I do a wrapper function which calls another function with exactly same name and parameters as the wrapper function itself in global namespace?
For example I have in A.h foo(int bar); and in A.cpp its implementation, and in B.h foo(int bar); and in B.cpp foo(int bar) { foo(bar) }
I want that the B.cpp's foo(bar) calls A.h's foo(int bar), not recursively itself.
How can I do this? I don't want to rename foo.
**Update:**
A.h is in global namespace and I cannot change it, so I guess using namespaces is not an option?
**Update:**
Namespaces solve the problem. I did not know you can call global namespace function with ::foo() | does B inherit/implement A at all?
If so you can use
```
int B::foo(int bar)
{
::foo(bar);
}
```
to access the foo in the global namespace
or if it does not inherit.. you can use the namespace on B only
```
namespace B
{
int foo(int bar) { ::foo(bar); }
};
``` | use a namespace
```
namespace A
{
int foo(int bar);
};
namespace B
{
int foo(int bar) { A::foo(bar); }
};
```
you can also write using namespace A; in your code but its highly recommended never to write using namespace in a header. | C++ wrapper with same name? | [
"",
"c++",
"wrapper",
""
] |
1. How do I hash files with C#
2. What is available ? (md5, crc, sha1, etc)
3. Is there an interface i should inherit?
I want to checksum multiple files and store it in a db along with using two of my own checksums/hashes. | > 1.) How do i hash files with C#?
You can utilize .NET classes under *[System.Security.Cryptography](http://msdn.microsoft.com/en-us/library/system.security.cryptography.aspx)*
> 2.) What is available?
* [KeyedHashAlgorithm](http://msdn.microsoft.com/en-us/library/system.security.cryptography.keyedhashalgorithm.aspx)
* [MD5](http://msdn.microsoft.com/en-us/library/system.security.cryptography.md5.aspx)
* [RIPEMD160](http://msdn.microsoft.com/en-us/library/system.security.cryptography.ripemd160.aspx)
* [SHA1](http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha1.aspx)
* [SHA256](http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha256.aspx)
* [SHA384](http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha384.aspx)
* [SHA512](http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha512.aspx)
> 3.) Is there an interface i should inherit?
No you don't have to.
Take a look at [HashAlgorithm.Create(...)](http://msdn.microsoft.com/en-us/library/wet69s13.aspx) | Snippet
```
byte[] result;
SHA1 sha = new SHA1CryptoServiceProvider();
using(FileStream fs = File.OpenRead(@"file.txt"))
{
result = sha.ComputeHash(fs);
}
```
See also [SHA1CryptoServiceProvider](http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha1cryptoserviceprovider.aspx) or [MD5CryptoServiceProvider](http://msdn.microsoft.com/en-us/library/system.security.cryptography.md5cryptoserviceprovider.aspx).
CRC is not available -- it's more efficient to create your own. | How to hash files in C# | [
"",
"c#",
"hash",
""
] |
Is it possible to simulate constants in Javascript using closures? If so, can you please furnish me with an example? | Firefox and Chrome both support the [`const`](https://developer.mozilla.org/en/Core%5FJavaScript%5F1.5%5FGuide/Constants) keyword. IE does not. So if you need constants and don't need to support IE, `const` isn't a bad choice. Keep in mind though, neither browser produces a runtime error when a value is assigned to a `const`; the values merely remains unchanged.
Otherwise, you must use functions to define constants that cannot be modified:
```
function PI() { return 3.14159; }
var area = radius*radius * PI();
```
Of course, you could just write code that never modifies certain variables, and maybe establish a naming scheme for such variables such that you recognize that they will never need to be modified...
```
// note to self: never assign values to variables utilizing all-uppercase name
var PI = 3.14159;
```
Another option for "simulating" constants would be to use the [property definition functionality](http://ejohn.org/blog/javascript-getters-and-setters/) available in some browsers to define read-only properties on an object. Of course, since the browsers supporting property definitions don't include IE, that doesn't really help... (note that IE**8** does support property definitions [after a fashion](http://msdn.microsoft.com/en-us/library/dd229916.aspx)... but not on JavaScript objects)
Finally, in *very* contrived scenarios you might use function arguments as constants (perhaps this is what you were thinking of when you suggested closures?). While they behave as variables, they remain scoped to the function in which they are defined and cannot therefore affect the values held by variables with the same name outside of the function in which they are modified:
```
var blah = 3;
var naw = "nope";
(function(blah, naw)
{
blah = 2;
naw = "yeah";
alert(naw + blah); // "yeah2"
})(blah, naw);
alert(naw + blah); // "nope3"
```
Note that something similar to this is [commonly used by jQuery plugins](http://docs.jquery.com/Plugins/Authoring#Custom_Alias), but for the opposite reason: jQuery code is usually written using the `$` shorthand to refer to the jQuery object, but the library is intended to continue working even if some other code redefines that symbol; by wrapping library and plugin code in anonymous functions with a `$` parameter and then passing in `jQuery` as an argument, the code is isolated from changes other libraries might make to the value of `$` later on.
---
### See also: [Are there constants in Javascript?](https://stackoverflow.com/questions/130396/are-there-constants-in-javascript) | You can create read-only, named constants with the [const keyword](https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Constants) ([Implemented in JavaScript 1.5](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/const)). | Is it possible to simulate constants in Javascript using closures? | [
"",
"javascript",
"closures",
"constants",
""
] |
Are the following exactly equivalent? Which idiom do you use and why?
```
$('#form1 .edit-field :input')
$('#form1 .edit-field').find(':input')
$('.edit-field :input', '#form1')
$(':input', '#form1 .edit-field')
``` | I would use either #2 or #4:
```
$('#form1 .edit-field').find(':input')
$(':input', '#form1 .edit-field')
```
Both of the above are essentially the same. Behind the curtain when you specify a context this is what's happening anyway:
```
jQuery( context ).find( selector );
```
The reason I would avoid #1 and #3 is because they're both significantly slower than #2/#4.
---
EDIT: Just did a quick test:
1000 input elements using YOUR selectors:
```
$('#form1 .edit-field :input') // 55ms
$('#form1 .edit-field').find(':input') // 21ms
$('.edit-field :input', '#form1') // 47ms
$(':input', '#form1 .edit-field') // 18ms
``` | The first two are equivalent when comparing element selection. However, the second form, when used in a command chain with a correspoding `end()` call, can be used to select further child elements within "#form1 .edit-field", i.e.:
```
$('#form1 .edit-field').find(':input')
...
.end().find(':hidden')...
.end()...
```
I'm uncertain about the second two forms, actually, I beleive they are not valid. Correct me if I'm wrong, but based on the docs, the correct syntax would look like this:
```
$('.edit-field :input', $('#form1'))
$(':input', $('#form1 .edit-field'))
```
Either way, IMHO these are less consise ways of saying the same.
In summary, generally I'd stick to the first form, unless you exploit the advantage of the second to traverse further children, as explained above. | jQuery equivalent selectors | [
"",
"javascript",
"jquery",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.