Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
How do I find the application's path in a console application?
In [Windows Forms](http://en.wikipedia.org/wiki/Windows_Forms), I can use `Application.StartupPath` to find the current path, but this doesn't seem to be available in a console application. | [`System.Reflection.Assembly.GetExecutingAssembly()`](https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.getexecutingassembly).[`Location`](https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.location)1
Combine that with [`System.IO.Path.GetDirectoryName`](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getdirectoryname) if all you want is the directory.
> 1*As per Mr.Mindor's comment:*
> `System.Reflection.Assembly.GetExecutingAssembly().Location` returns where the executing assembly is currently located, which may or may not be where the assembly is located when not executing. In the case of shadow copying assemblies, you will get a path in a temp directory. [`System.Reflection.Assembly.GetExecutingAssembly().CodeBase`](https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.codebase) will return the 'permanent' path of the assembly. | You can use the following code to get the current application directory.
```
AppDomain.CurrentDomain.BaseDirectory
``` | How can I get the application's path in a .NET console application? | [
"",
"c#",
".net",
"console",
"console-application",
""
] |
I have this string: "123-456-7"
I need to get this string: "1234567"
How I can replace occurrences of "-" with an empty string? | ```
string r = "123-456-7";
r = r.Replace("-", "");
``` | This should do the trick:
```
String st = "123-456-7".Replace("-","");
``` | How to replace occurrences of "-" with an empty string? | [
"",
"c#",
"string",
""
] |
A class can be a "subclass" of itself if its inner class extend the outer class
so the class is somehow extending itself without throwing any Exception. So, does it really mean a class is also a subclass of itself?
Thanks. | A class is not a subclass of itself. An inner class could be a subclass of some other class, but that is a separate class. You can verify this by comparing the Class instances you get when you call getClass(). | ```
public class ParentClass {
int intField = 10;
class InnerClass extends ParentClass {
}
public static void main(String... args) {
ParentClass parentClass = new ParentClass();
InnerClass innerClass = parentClass.new InnerClass();
System.out.println(innerClass.intField);
InnerClass innerClass2 = innerClass.new InnerClass();
}
}
``` | Java: Is a class a subclass of itself? | [
"",
"java",
"class",
"inheritance",
""
] |
I want the given application (Windows Service) to act as a remoting server as well as remoting client. In production I will run the two instances of my application monitoring each other over .NET Remoting and will report the failures accordingly.
I have written a basic pieces, and getting "The channel 'tcp' is already registered" exception..I want to set the channel configuration programmatically. | A channel with a specific port number can only be created by one application instance. You need to use different port numbers and channel names for each instance.
This requires using seperate channel templates (if you are using templates?). | As others have said, if you don't specify the channel name, the code by default uses "tcp" and every channel has to have a unique name: So specify a unique name for each channel you open...
```
int tcpPort = 52131;
// ------------------------------------------------------------
BinaryServerFormatterSinkProvider serverProv =
new BinaryServerFormatterSinkProvider();
serverProv.TypeFilterLevel = TypeFilterLevel.Full;
RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off;
serverProv.TypeFilterLevel = TypeFilterLevel.Full;
IDictionary propBag = new Hashtable();
// -----------------------------------------
bool isSecure = [true/false];
propBag["port"] = tcpPort ;
propBag["typeFilterLevel"] = TypeFilterLevel.Full;
propBag["name"] = "UniqueChannelName"; // here enter unique channel name
if (isSecure) // if you want remoting comm to be secure and encrypted
{
propBag["secure"] = isSecure;
propBag["impersonate"] = false; // change to true to do impersonation
}
// -----------------------------------------
tcpChan = new TcpChannel(
propBag, null, serverProv);
ChannelServices.RegisterChannel(tcpChan, isSecure);
// --------------------------------------------
string uRI = MyUniversalResourceIndicatorName;
// ---------------------------------------------
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(ImportServiceManager), uRI ,
WellKnownObjectMode.SingleCall);
``` | The channel 'tcp' is already registered | [
"",
"c#",
"remoting",
""
] |
I am writing a C++ application and I was wondering what the C++ conventional way of storing a byte array in memory.
Is there something like a string, except specifically made for binary data.
Right now I am using a \*unsigned char\*\* array to store the data, but something more STL/C++ like would be better. | I'd use `std::vector<unsigned char>`. Most operations you need can be done using the STL with iterator ranges. Also, remember that if you really need the raw data `&v[0]` is guaranteed to give a pointer to the underlying array. | You can use `std::string` also for binary data. The length of the data in `std::string` is stored explicitly and not determined by null-termination, so null-bytes don't have special meaning in a `std::string`.
`std::string` is often more convenient than `std::vector<char>` because it provides many methods that are useful to work with binary data but not provided by `vector`. To parse/create binary data it is useful to have things like `substr()`, overloads for `+` and `std::stringstream` at your disposal. On vectors the algorithms from `<algorithm>` can be used to achieve the same effects, but it's more clumsy than the string methods. If you just act on "sequences of characters", `std::string` gives you the methods you usually want, even if these sequences happen to contain "binary" data. | C++ STL's String eqivalent for Binary Data | [
"",
"c++",
"string",
"stl",
"binary",
""
] |
Why is `null` considered an `object` in JavaScript?
Is checking
```
if ( object == null )
Do something
```
the same as
```
if ( !object )
Do something
```
?
And also:
What is the difference between `null` and `undefined`? | ```
(name is undefined)
```
**You:** What is `name`? (\*)
**JavaScript:** `name`? What's a `name`? I don't know what you're talking about. You haven't ever mentioned any `name` before. Are you seeing some other scripting language on the (client-)side?
```
name = null;
```
**You:** What is `name`?
**JavaScript:** I don't know.
In short; `undefined` is where no notion of the thing exists; it has no type, and it's never been referenced before in that scope; `null` is where the thing is known to exist, but it's not known what the value is.
One thing to remember is that `null` is not, conceptually, the same as `false` or `""` or such, even if they equate after type casting, i.e.
```
name = false;
```
**You:** What is `name`?
**JavaScript:** Boolean false.
```
name = '';
```
**You:** What is `name`?
**JavaScript:** Empty string
---
\*: `name` in this context is meant as a variable which has never been defined. It could be any undefined variable, however, name is a property of just about any HTML form element. It goes way, way back and was instituted well before id. It is useful because ids must be unique but names do not have to be. | The difference can be summarized into this snippet:
```
alert(typeof(null)); // object
alert(typeof(undefined)); // undefined
alert(null !== undefined) //true
alert(null == undefined) //true
```
Checking
`object == null` is different to check `if ( !object )`.
The latter is equal to `! Boolean(object)`, because the unary `!` operator automatically cast the right operand into a Boolean.
Since `Boolean(null)` equals false then `!false === true`.
So if your object is **not null**, *but* **false** or **0** or **""**, the check will pass
because:
```
alert(Boolean(null)) //false
alert(Boolean(0)) //false
alert(Boolean("")) //false
``` | Why is null an object and what's the difference between null and undefined? | [
"",
"javascript",
"object",
"null",
"undefined",
"typeof",
""
] |
I've installed VisualSVN on my Windows 2003 server, and have configured it to provide anonymous read-access. From my understanding VisualSVN just uses apache and the official SVN Repository server underneath.
Now, I'd like to extend the SVN web page to provide "download HEAD as ZIP" functionality. Web portals like [SourceForge](http://svn-web-control.svn.sourceforge.net/viewvc/svn-web-control/trunk/ "sourceforge - Download GNU tarball") and [Codeplex](http://downloadsvn.codeplex.com/SourceControl/ListDownloadableCommits.aspx "CodePlex - Download") do provide this functionality.
Is there a plugin for the SVN Repository server for this? Or may be a separate web client (preferably ASP.NET)? | I found a solution, and would want to share it with you, in case someone else would want to achieve the same solution.
After analyzing [WebSvn](http://websvn.tigris.org/), I found out that they use the SVN Export Directory functionality to download the source to a local folder, and then zip the directory, on the fly. The performance is quite well.
My solution in C# below, is using [SharpSVN](http://sharpsvn.open.collab.net/) and [DotNetZip](http://dotnetzip.codeplex.com/). The full source code can be found on [my SVN repository](http://www.activesoft.nl:8080/svn/blog/trunk/SvnExportDirectory/).
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpSvn;
using Ionic.Zip;
using System.IO;
using SharpSvn.Security;
namespace SvnExportDirectory
{
public class SvnToZip
{
public Uri SvnUri { get; set; }
public string Username { get; set; }
public string Password { get; set; }
private bool passwordSupplied;
public SvnToZip() { }
public SvnToZip(Uri svnUri)
{
this.SvnUri = svnUri;
}
public SvnToZip(string svnUri)
: this(new Uri(svnUri)) { }
public void ToFile(string zipPath)
{
if (File.Exists(zipPath))
File.Delete(zipPath);
using (FileStream stream = File.OpenWrite(zipPath))
{
this.Run(stream);
}
}
public MemoryStream ToStream()
{
MemoryStream ms = new MemoryStream();
this.Run(ms);
ms.Seek(0, SeekOrigin.Begin);
return ms;
}
private void Run(Stream stream)
{
string tmpFolder =
Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
try
{
using (SvnClient client = new SvnClient())
{
//client.Authentication.Clear();
client.Authentication.UserNamePasswordHandlers += Authentication_UserNamePasswordHandlers;
SvnUpdateResult res;
bool downloaded = client.Export(SvnTarget.FromUri(SvnUri), tmpFolder, out res);
if (downloaded == false)
throw new Exception("Download Failed");
}
using (ZipFile zipFile = new ZipFile())
{
zipFile.AddDirectory(tmpFolder, GetFolderName());
zipFile.Save(stream);
}
}
finally
{
if (File.Exists(tmpFolder))
File.Delete(tmpFolder);
}
}
private string GetFolderName()
{
foreach (var potential in SvnUri.Segments.Reverse())
{
if (string.Equals(potential, "trunk", StringComparison.InvariantCultureIgnoreCase) == false)
return potential;
}
return null;
}
void Authentication_UserNamePasswordHandlers(object sender, SvnUserNamePasswordEventArgs e)
{
if (passwordSupplied)
{
e.Break = true;
}
else
{
if (this.Username != null)
e.UserName = this.Username;
if (this.Password != null)
e.Password = this.Password;
passwordSupplied = true;
}
}
}
}
``` | I don't know about "built in", but you could try writing a page that uses SharpSVN and #ZipLib to do the job...
If that is too slow, you could presumably use either a commit hook or a scheduled job (every few minutes or something) to keep a pre-prepared zip handy somewhere that you can just return - using the "create as a different name then rename when ready" trick to minimize the amount of time it is locked / unavailable. Or name it with the revision number. | SVN to ZIP on the fly | [
"",
"c#",
"svn",
"zip",
""
] |
I am attempting to extract all instances of a particular format from a string:
> I am wondering if my new Sony [PT# 123456ABC; Sony] has this feature but my friend says the new Toshiba [PT# AD-3232hjk; Toshiba] has this feature.
I would like to extract:
> [PT# 123456ABC; Sony]
>
> [PT# AD-3232hjk; Toshiba]
As you can see here, the only items in the consistent positions are:
* [PT#
* ;
* ]
I was attempting to use various types of strpos() but because of the varying lengths and formats of the part numbers and manufacturer names I was unable to reliably pull out those instances from a much larger string. I have been trying various ways to use regular expressions to solve this however my knowledge with them is fairly limited. After I have these expressions extracted and placed into variables I will then need to separate the part numbers and manufacturer names from the expression. This may also be easier to accomplish using regular expressions.
Any help is appreciated.
Thanks | I think this would do it
```
preg_match_all( "/(\[PT#\s+.*?;\s+.*?\])/", $input, $matches );
print_r( $matches );
```
Altternatively, if you just wanted to capture the unique information
```
preg_match_all( "/\[PT#\s+(.*?);\s+(.*?)\]/", $input, $matches );
``` | ```
$matches = array();
preg_match_all( "/\[PT#([^\];]+);([^\]]+)\]/", $input, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
echo "id=", trim($match[1]), " brand=", trim($match[2]), "\n";
}
``` | Regular expression syntax In PHP to extract all instances of a format | [
"",
"php",
"regex",
"extract",
""
] |
Ok, I didn't really know how to even phrase the question, but let me explain.
Suppose I have a variable:
```
$file = dirname(__FILE__);
```
What happens if I assign `$file` to another variable?
```
$anotherVariable = $file;
```
Does the `dirname` function get executed each time I assign?
Thanks for any help. | No. PHP is imperative, so the right hand side of assignment expressions is *evaluated*, and the result stored "in the" left hand side (in the simple and almost ubiquitous case, the variable named on the left hand side).
```
$a = $b; // Find the value of $b, and copy it into the value of $a
$a = 5 + 2; // Evaulate 5 + 2 to get 7, and store this in $a
$a = funcName(); // Evaluate funcName, which is equivalent to executing the code and obtaining the return value. Copy this value into $a
```
This gets a little more complex when you assign by reference ($a = &$b), but we needn't worry about that for now. | PHP doesn't have closures like that.
> dirname(**FILE**)
this function returns a string.
> $anotherVariable = $file;
gives $anotherVariable that same string value.
so I believe the answer to your question is "no", it does not get executed each time. | How does php execute a function assigned to variable? | [
"",
"php",
""
] |
I have subclassed a control in C# WinForms, and am custom drawing text in my `OnPaint()` handler.
The font is set to Courier New using the following code in my form:
```
FontFamily family = new FontFamily("Courier New");
this.myControl.Font = new Font(family, 10);
```
In the control itself, the string is stored in `realText`, and I use the following code to draw it to the screen:
```
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.DrawString(realText, Font, new SolidBrush(ForeColor), ClientRectangle);
}
```
The result for some random example text looks as follows:
<http://img219.imageshack.us/img219/1778/courier.png>
If you zoom in, you can see for example, that the space between the first 'as' is different than the space between the second 'as' (1 pixels versus 2 pixels). Does anybody have any idea what might be causing this, or how I can prevent it from happening? There is a lot more similar weirdness in spacing as I draw with different fonts, but I assume they're all results of the same problem.
Thanks in advance for any ideas you may have. | I'm going to guess that it's because you're using [`Graphics.DrawString()`](http://msdn.microsoft.com/en-us/library/system.drawing.graphics.drawstring.aspx) instead of [`TextRenderer.DrawText()`](http://msdn.microsoft.com/en-us/library/system.windows.forms.textrenderer.drawtext%28v=vs.110%29.aspx). The former paints text using GDI+ which is sort of crappy and outdated. The latter uses GDI which is more modern (in terms of text rendering). I believe this is the difference noted by the previous answer (WinForms vs. Windows).
You might also try the overload of `Graphics.DrawString()` that takes a [`StringFormat`](http://msdn.microsoft.com/en-us/library/system.drawing.stringformat%28v=vs.110%29.aspx) object and specify `StringFormat.GenericTypographic`. However, this is really a bit of a hack around the problem. If you're using .NET 2.0 or later, you should be using the `TextRenderer` class instead of the crappy `Graphics` class for all of your text rendering needs. `Graphics.MeasureString()` and `Graphics.DrawString()` exist strictly for backwards compatibility with .NET 1.0 and 1.1.
edit: Oh yeah, and your code leaks a GDI object on every paint cycle. Brush objects are managed wrappers around unmanaged resources thus they must be explicitly disposed. | I have to be honest, but this never happened to me before. However, try setting the SmoothingMode to Antialiasing:
```
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
```
Another thing aside, make sure the from your using has DoubleBuffer set to true. Also, try not to create a new SolidBrush in every OnPaint call .. | Why is DrawString exhibiting unexpected behavior in C# Winforms? | [
"",
"c#",
"winforms",
"controls",
"onpaint",
"drawstring",
""
] |
I've got a model like this
> ```
> def upload_location(instance, filename):
> return 'validate/%s/builds/%s' % (get_current_user(), filename)
>
> class MidletPair(models.Model):
> jad_file = models.FileField(upload_to = upload_location)
> jar_file = models.FileField(upload_to = upload_location)
> upload_to=tempfile.gettempdir()
> ```
How can I get the current user in upload\_location()... ?
Side note: Looking up django stuff is confusing as theres a lot of pre-1.0 stuff around on the net. | The current user is stored in the request object, and you can't get that in a model method unless you pass it in from elsewhere - which you can't do in the upload\_to function.
So you'll need to approach this in a different manner - I would suggest doing it at the form level. You can pass the request object into the form's `__init__` method and store it in an instance attribute, where you can get to it in a custom upload handler. For documentation on upload handlers, look [here](http://docs.djangoproject.com/en/dev/topics/http/file-uploads/). | If you added a user field to the model, and have that attribute set before you performed an upload, then you could get the user in to your upload\_location function via the instance attribute. | How to save django FileField to user folder? | [
"",
"python",
"django",
"django-models",
"upload",
""
] |
I am currently using a javascript code to make an entire row in my table clickable. Once the row is clicked a function is ran, I am wondering what I can use to redirect to a PHP page and preferably send a post variable along with it. My guess is AJAX but I am not sure how or if it would work.
> **Javascript**
```
function DoNav(theUrl) {
document.location.href = theUrl;
};
```
> **HTML**
```
<tr onclick="DoNav('myphpscript.php');">
```
I have access to jQuery so that is also an option. Any help is appreciated, Thanks! | If the amount of data is not ridiculously large, use a query string...
<tr onclick="DoNav('myphpscript.php**?key=value**');">
Or if you need a natural HTTP post, you can programmatically submit the form with Javascript...
```
onclick="document.forms[0].submit();"
``` | If you need to POST the data (not use GET), One easy option is to create a form element on the fly, attach input elements with the values you need and submit it. You can do that like so if you use jQuery:
```
$(function() {
$('tr').click(function() {
var mail_id = /* get the mail id of this row... not sure where since I dont' have the HTML */
$('body').append('<form method="post" action="myphpscript.php" id="donavform" style="display:none;"></form>');
$('#donavform').append('<input type="hidden" name="mid" value="'+mail_id+'" />');
$('#donavform').submit();
});
});
```
Hope that makes sense. If not, let me know! It's, okay...
**Explanation:**
The very first line is a jQuery shortcut way of saying "when the document is done loading..." So, when the page is done loading, I'm going to attach an event listener to *all* elements in the document. When one of those elements is clicked, we can then extract the mail id (and whatever else you need) that is in relation to that particular table row. So, if you had HTML like this:
```
<!-- 8435 is the mail ID in this example. -->
<tr id="row3">8435</tr>
```
Then we could extract the mail\_id variable like so:
```
var mail_id = $(this).html();
```
Now, we are going to attach a hidden form element to the end of the body of the HTML (it doesn't really matter where we put it since it is hidden... so, the end is fine). In this form element, we set the method to POST and the action to whatever php file you need to POST to. I also set an ID so it's easily referred to in the next step.
I'm now going to select the newly-created form element using its ID and I'm going to append a new hidden input element to it with the appropriate name value pair.
```
$('#donavform').append('<input type="hidden" name="mid" value="'+mail_id+'" />');
```
Finally, I'm going to use the jQuery JavaScript submit method to trigger the submit event on the form. This is basically equivalent to pressing the 'submit' button on a normal form.
Try it out, it should work flawlessly. | How do I send values between pages using javascript? | [
"",
"javascript",
"jquery",
""
] |
I'm having problems implementing a borg in python. I found an example in an answer to [this question](https://stackoverflow.com/questions/736335/python-superglobal) but it's not working for me, unless I'm missing something. Here's the code:
```
class Config:
"""
Borg singleton config object
"""
__we_are_one = {}
__myvalue = ""
def __init__(self):
#implement the borg pattern (we are one)
self.__dict__ = self.__we_are_one
self.__myvalue = ""
def myvalue(self, value=None):
if value:
self.__myvalue = value
return self.__myvalue
conf = Config()
conf.myvalue("Hello")
conf2 = Config()
print conf2.myvalue()
```
I assume this is meant to print "Hello", but for me it just prints a blank line. Any ideas why this might be? | It looks like it's working rather too well :-)
The issue is that the assignment `self.__myvalue = ""` in `__init__` will always clobber the value of `myvalue` every time a new Borg is, er, created. You can see this if you add some additional print statements to your test:
```
conf = Config()
conf.myvalue("Hello")
print conf.myvalue() # prints Hello
conf2 = Config()
print conf.myvalue() # prints nothing
print conf2.myvalue() # prints nothing
```
Remove the `self.__myvalue` and things will be fine.
Having said that, the implementation of `myvalue()` is a little weird. Better, I'd say, to have explicit getters and setters using properties. You'll also want some code in `__init__` to initialize the value of `myvalue` if it doesn't exist yet, or to at least handle that it might not exist in the getter. Perhaps something like:
```
class Config(object):
"""
Borg singleton config object
"""
_we_are_one = {}
def __init__(self):
#implement the borg pattern (we are one)
self.__dict__ = self._we_are_one
def set_myvalue(self, val):
self._myvalue = val
def get_myvalue(self):
return getattr(self, '_myvalue', None)
myvalue = property(get_myvalue, set_myvalue)
c = Config()
print c.myvalue # prints None
c.myvalue = 5
print c.myvalue # prints 5
c2 = Config()
print c2.myvalue #prints 5
``` | Combining the removal of `self.__myvalue = ""` with the [new-style Borg](http://code.activestate.com/recipes/66531/#c20) and the suggestions to avoid `__` in variable names, we get:
```
class Config(object):
"""
Borg singleton config object
"""
_we_are_one = {}
_myvalue = ""
def __new__(cls, *p, **k):
self = object.__new__(cls, *p, **k)
self.__dict__ = cls._we_are_one
return self
def myvalue(self, value=None):
if value:
self._myvalue = value
return self._myvalue
if __name__ == '__main__':
conf = Config()
conf.myvalue("Hello")
conf2 = Config()
print conf2.myvalue()
``` | Python borg pattern problem | [
"",
"python",
"design-patterns",
""
] |
I'm trying to split an app.config file into multiple files to make it easier to manage the differences needed for different environments. With some sections it was easy...
```
<system.diagnostics>
various stuff
</system.diagnostics>
```
became
```
<system.diagnostics configSource="ConfigFiles\system.diagnostics.dev" />
```
with the "various stuff" moved to the system.diagnostics.dev file.
But for the `system.serviceModel` section this doesn't seem to work.
Now I've read suggestions that it doesn't work for `system.serviceModel` itself, but it works for the sections underneath it: `bindings`, `client`, `diagnostics`, etc. But the same thing happens to me when I try to use configSource with one of them. When I put in
```
<system.serviceModel>
<bindings configSource="ConfigFiles\whateverFile.dev" />
```
I get:
**The 'configSource' attribute is not declared.**
Has anyone else seen this? Do you know a solution? (Perhaps I have an out-of-date schema or something?) | VS.NET's editor moans about the config, but it works.
I have config like this...
```
<system.serviceModel>
<behaviors configSource="config\system.servicemodel.behaviors.config" />
<bindings configSource="config\system.servicemodel.bindings.config" />
<client configSource="config\system.servicemodel.client.config" />
</system.serviceModel>
```
... which works fine. | It will **NOT** work on `<system.serviceModel>` since that's a configuration SectionGroup - not a configuration Section.
It **WILL** work just fine at runtime on anything below `<system.serviceModel>` - we do this all the time. Martin's answer shows it nicely - his sample will work. | configSource doesn't work in system.serviceModel *or* its subsections | [
"",
"c#",
".net",
"winforms",
"wcf",
"configuration",
""
] |
I have panel that is using group layout to organize some label. I want to keep this panel center of the screen when re sized. If i put the panel inside a another panel using flow layout i can keep the labels centered horizontally but not vertically. Which layout manager will allow me to keep the panel centered in the middle of the screen?
I also tried border layout and placed it in the center but it resizes to the window size. | Try using a [`GridBagLayout`](http://java.sun.com/javase/6/docs/api/java/awt/GridBagLayout.html) and adding the panel with an empty [`GridBagConstrants`](http://java.sun.com/javase/6/docs/api/java/awt/GridBagConstraints.html) object.
For example:
```
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setLayout(new GridBagLayout());
JPanel panel = new JPanel();
panel.add(new JLabel("This is a label"));
panel.setBorder(new LineBorder(Color.BLACK)); // make it easy to see
frame.add(panel, new GridBagConstraints());
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
``` | First, I should mention, read my article on layouts: <http://web.archive.org/web/20120420154931/http://java.sun.com/developer/onlineTraining/GUI/AWTLayoutMgr/>. It's old but very helpful (unfortunately that article pre-dates BoxLayout. I have some slides when I gave that talk at JavaOne, which includes BoxLayout at <http://javadude.com/articles/javaone>)
Try BoxLayout:
```
Box verticalBox = Box.createVerticalBox();
verticalBox.add(Box.createVerticalGlue());
verticalBox.add(stuffToCenterVertically);
verticalBox.add(Box.createVerticalGlue());
```
and if you want to center that stuff, use a HorizontalBox as the stuffToCenterVertically:
```
Box horizontalBox = Box.createHorizontalBox();
horizontalBox.add(Box.createHorizontalGlue());
horizontalBox.add(stuffToCenter);
horizontalBox.add(Box.createHorizontalGlue());
```
Way easier to "see" in the code than gridbag | Java layout manager vertical center | [
"",
"java",
"swing",
"layout",
""
] |
I'm writing a Python backup script and I need to find the oldest file in a directory (and its sub-directories). I also need to filter it down to \*.avi files only.
The script will always be running on a Linux machine. Is there some way to do it in Python or would running some shell commands be better?
At the moment I'm running `df` to get the free space on a particular partition, and if there is less than 5 gigabytes free, I want to start deleting the oldest `*.avi` files until that condition is met. | Hm. Nadia's answer is closer to what you *meant* to ask; however, for finding the (single) oldest file in a tree, try this:
```
import os
def oldest_file_in_tree(rootfolder, extension=".avi"):
return min(
(os.path.join(dirname, filename)
for dirname, dirnames, filenames in os.walk(rootfolder)
for filename in filenames
if filename.endswith(extension)),
key=lambda fn: os.stat(fn).st_mtime)
```
With a little modification, you can get the `n` oldest files (similar to Nadia's answer):
```
import os, heapq
def oldest_files_in_tree(rootfolder, count=1, extension=".avi"):
return heapq.nsmallest(count,
(os.path.join(dirname, filename)
for dirname, dirnames, filenames in os.walk(rootfolder)
for filename in filenames
if filename.endswith(extension)),
key=lambda fn: os.stat(fn).st_mtime)
```
Note that using the `.endswith` method allows calls as:
```
oldest_files_in_tree("/home/user", 20, (".avi", ".mov"))
```
to select more than one extension.
Finally, should you want the complete list of files, ordered by modification time, in order to delete as many as required to free space, here's some code:
```
import os
def files_to_delete(rootfolder, extension=".avi"):
return sorted(
(os.path.join(dirname, filename)
for dirname, dirnames, filenames in os.walk(rootfolder)
for filename in filenames
if filename.endswith(extension)),
key=lambda fn: os.stat(fn).st_mtime),
reverse=True)
```
and note that the `reverse=True` brings the oldest files at the end of the list, so that for the next file to delete, you just do a `file_list.pop()`.
By the way, for a complete solution to your issue, since you are running on Linux, where the `os.statvfs` is available, you can do:
```
import os
def free_space_up_to(free_bytes_required, rootfolder, extension=".avi"):
file_list= files_to_delete(rootfolder, extension)
while file_list:
statv= os.statvfs(rootfolder)
if statv.f_bfree*statv.f_bsize >= free_bytes_required:
break
os.remove(file_list.pop())
```
`statvfs.f_bfree` are the device free blocks and `statvfs.f_bsize` is the block size. We take the `rootfolder` statvfs, so mind any symbolic links pointing to other devices, where we could delete many files without actually freeing up space in this device.
UPDATE (copying a comment by Juan):
Depending on the OS and filesystem implementation, you may want to multiply f\_bfree by f\_frsize rather than f\_bsize. In some implementations, the latter is the preferred I/O request size. For example, on a FreeBSD 9 system I just tested, f\_frsize was 4096 and f\_bsize was 16384. POSIX says the block count fields are "in units of f\_frsize" ( see <http://pubs.opengroup.org/onlinepubs/9699919799//basedefs/sys_statvfs.h.html> ) | To do it in Python, you can use [`os.walk(path)`](http://docs.python.org/library/os.html) to iterate recursively over the files, and the `st_size` and `st_mtime` attributes of [`os.stat(filename)`](http://docs.python.org/library/os.html) to get the file sizes and modification times. | Find the oldest file (recursively) in a directory | [
"",
"python",
"linux",
"file-io",
""
] |
Looking to move data from a table A to history table B every X days for data that is Y days old and then remove the data from history table B that is older than Z days.
Just exploring different ways to accomplish this. So any suggestions would be appreciated.
Example for variables
X - 7days
Y - 60days
z - 365days
Thank you | ```
CREATE PROCEDURE prc_clean_tables (Y INT, Z INT)
BEGIN
BEGIN TRANSACTION;
DECLARE _now DATETIME;
SET _now := NOW();
INSERT
INTO b
SELECT *
FROM a
WHERE timestamp < _now - INTERVAL Y DAY;
FOR UPDATE;
DELETE
FROM a
WHERE timestamp < _now - INTERVAL Y DAY;
DELETE
FROM b
WHERE timestamp < _now - INTERVAL Z DAY;
COMMIT;
END
``` | This seems straight forward.
You want a nightly cron job to run a script.
```
#crontab -e
50 11 * * * $HOME/scripts/MyWeeklyArchive.sh
```
The script file itself is pretty simple as well. We'll just use mysqldump and the Now() function;
```
#! /bin/bash
/usr/bin/mysqldump -uUser -pPassword Current_DB Table --where='date < NOW() - INTERVAL 7 DAY' | /usr/bin/mysql -uUser -pPassword archive_DB
```
You could just include that line in the cron file, but for scalability and such I reccomend making it a script file. | What are ways to move data older than 'Y' days to an archive/history table in MySQL? | [
"",
"sql",
"mysql",
"database",
"history",
""
] |
I'm a C# developer and I have to change my display resolution regularly.
There are plenty of examples on how to read the current display resolutions:
[SystemInformation.PrimaryMonitorSize](http://msdn.microsoft.com/en-us/library/system.windows.forms.systeminformation.primarymonitorsize.aspx)
I found the [ChangeDisplaySettingsEx Function](http://msdn.microsoft.com/en-us/library/dd183413(VS.85).aspx)
Is the only way to do this in C# is with [PInvoke](http://www.pinvoke.net/default.aspx/user32/ChangeDisplaySettings.html)???
It seems odd to me that it is very easy to get this information out, but difficult to set it... | You'll have to make a PInvoke call to ChangedisplaySetting.
Here's a link that has some sample code, <http://www.xtremedotnettalk.com/printthread.php?t=73184>. | I also recommend that you check out Jared Parsons PInvoke Toolkit. You can download it here:
<http://www.codeplex.com/clrinterop/Release/ProjectReleases.aspx?ReleaseId=14120>
It makes adding pinvoke signatures to your code a breeze. It doesn't always pick the right interop types, but it's usually pretty close, and even if you have to make some changes its still usually quicker than translating everything by hand. | Setting my Display Resolution | [
"",
"c#",
".net-3.5",
""
] |
Given the following example (using JUnit with Hamcrest matchers):
```
Map<String, Class<? extends Serializable>> expected = null;
Map<String, Class<java.util.Date>> result = null;
assertThat(result, is(expected));
```
This does not compile with the JUnit `assertThat` method signature of:
```
public static <T> void assertThat(T actual, Matcher<T> matcher)
```
The compiler error message is:
```
Error:Error:line (102)cannot find symbol method
assertThat(java.util.Map<java.lang.String,java.lang.Class<java.util.Date>>,
org.hamcrest.Matcher<java.util.Map<java.lang.String,java.lang.Class
<? extends java.io.Serializable>>>)
```
However, if I change the `assertThat` method signature to:
```
public static <T> void assertThat(T result, Matcher<? extends T> matcher)
```
Then the compilation works.
So three questions:
1. Why exactly doesn't the current version compile? Although I vaguely understand the covariance issues here, I certainly couldn't explain it if I had to.
2. Is there any downside in changing the `assertThat` method to `Matcher<? extends T>`? Are there other cases that would break if you did that?
3. Is there any point to the genericizing of the `assertThat` method in JUnit? The `Matcher` class doesn't seem to require it, since JUnit calls the matches method, which is not typed with any generic, and just looks like an attempt to force a type safety which doesn't do anything, as the `Matcher` will just not in fact match, and the test will fail regardless. No unsafe operations involved (or so it seems).
For reference, here is the JUnit implementation of `assertThat`:
```
public static <T> void assertThat(T actual, Matcher<T> matcher) {
assertThat("", actual, matcher);
}
public static <T> void assertThat(String reason, T actual, Matcher<T> matcher) {
if (!matcher.matches(actual)) {
Description description = new StringDescription();
description.appendText(reason);
description.appendText("\nExpected: ");
matcher.describeTo(description);
description
.appendText("\n got: ")
.appendValue(actual)
.appendText("\n");
throw new java.lang.AssertionError(description.toString());
}
}
``` | First - I have to direct you to <http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html> -- she does an amazing job.
The basic idea is that you use
```
<T extends SomeClass>
```
when the actual parameter can be `SomeClass` or any subtype of it.
In your example,
```
Map<String, Class<? extends Serializable>> expected = null;
Map<String, Class<java.util.Date>> result = null;
assertThat(result, is(expected));
```
You're saying that `expected` can contain Class objects that represent any class that implements `Serializable`. Your result map says it can only hold `Date` class objects.
When you pass in result, you're setting `T` to exactly `Map` of `String` to `Date` class objects, which doesn't match `Map` of `String` to anything that's `Serializable`.
One thing to check -- are you sure you want `Class<Date>` and not `Date`? A map of `String` to `Class<Date>` doesn't sound terribly useful in general (all it can hold is `Date.class` as values rather than instances of `Date`)
As for genericizing `assertThat`, the idea is that the method can ensure that a `Matcher` that fits the result type is passed in. | Thanks to everyone who answered the question, it really helped clarify things for me. In the end Scott Stanchfield's answer got the closest to how I ended up understanding it, but since I didn't understand him when he first wrote it, I am trying to restate the problem so that hopefully someone else will benefit.
I'm going to restate the question in terms of List, since it has only one generic parameter and that will make it easier to understand.
The purpose of the parametrized class (such as List`<Date>` or Map`<K, V>` as in the example) is to **force a downcast** and to have the compiler guarantee that this is safe (no runtime exceptions).
Consider the case of List. The essence of my question is why a method that takes a type T and a List won't accept a List of something further down the chain of inheritance than T. Consider this contrived example:
```
List<java.util.Date> dateList = new ArrayList<java.util.Date>();
Serializable s = new String();
addGeneric(s, dateList);
....
private <T> void addGeneric(T element, List<T> list) {
list.add(element);
}
```
This will not compile, because the list parameter is a list of dates, not a list of strings. Generics would not be very useful if this did compile.
The same thing applies to a Map`<String, Class<? extends Serializable>>` It is not the same thing as a Map`<String, Class<java.util.Date>>`. They are not covariant, so if I wanted to take a value from the map containing date classes and put it into the map containing serializable elements, that is fine, but a method signature that says:
```
private <T> void genericAdd(T value, List<T> list)
```
Wants to be able to do both:
```
T x = list.get(0);
```
and
```
list.add(value);
```
In this case, even though the junit method doesn't actually care about these things, the method signature requires the covariance, which it is not getting, therefore it does not compile.
On the second question,
```
Matcher<? extends T>
```
Would have the downside of really accepting anything when T is an Object, which is not the APIs intent. The intent is to statically ensure that the matcher matches the actual object, and there is no way to exclude Object from that calculation.
The answer to the third question is that nothing would be lost, in terms of unchecked functionality (there would be no unsafe typecasting within the JUnit API if this method was not genericized), but they are trying to accomplish something else - statically ensure that the two parameters are likely to match.
EDIT (after further contemplation and experience):
One of the big issues with the assertThat method signature is attempts to equate a variable T with a generic parameter of T. That doesn't work, because they are not covariant. So for example you may have a T which is a `List<String>` but then pass a match that the compiler works out to `Matcher<ArrayList<T>>`. Now if it wasn't a type parameter, things would be fine, because List and ArrayList are covariant, but since Generics, as far as the compiler is concerned require ArrayList, it can't tolerate a List for reasons that I hope are clear from the above. | When do Java generics require <? extends T> instead of <T> and is there any downside of switching? | [
"",
"java",
"generics",
"junit",
""
] |
I have IIS 5.1 on a XP machine, and visual studio 2005. How do I go about attaching my debugger to IIS instance.
BTW: I'm not seeing the IIS process within the running processes or probably I don't know what to look for . | In Visual Studio:
1. Click "Debug" from the menu bar
2. Click "Attach to Process"
3. Check the "**Show processes from all users**" checkbox in the bottom left corner
4. Select **aspnet\_wp.exe**, **w3p.exe**, or **w3wp.exe** from the process list
5. Click "Attach" | Just to clarify Jimmie R. Houts answer…
If you want to debug the web application VS and IIS you can do the following:
1. Host the site inside IIS (virtual directory etc).
2. Then in VS2005 do this:
* Right Click on Web Project → Properties →
Start options → Use Custom Server → Base URL → Enter Site Address as
Hosted in IIS.
* Hit `F5` and you will be able to Debug your code
Same works for VS 2008 also. | Attach Debugger to IIS instance | [
"",
"c#",
"asp.net",
"visual-studio-2005",
"debugging",
""
] |
I've already [found the following question](https://stackoverflow.com/questions/110259/python-memory-profiler), but I was wondering if there was a quicker and dirtier way of grabbing an estimate of how much memory the python interpreter is currently using for my script that doesn't rely on external libraries.
I'm coming from PHP and used to use [memory\_get\_usage()](http://au.php.net/memory_get_usage) and [memory\_get\_peak\_usage()](http://au.php.net/memory_get_peak_usage) a lot for this purpose and I was hoping to find an equivalent. | A simple solution for Linux and other systems with `/proc/self/status` is the following code, which I use in a project of mine:
```
def memory_usage():
"""Memory usage of the current process in kilobytes."""
status = None
result = {'peak': 0, 'rss': 0}
try:
# This will only work on systems with a /proc file system
# (like Linux).
status = open('/proc/self/status')
for line in status:
parts = line.split()
key = parts[0][2:-1].lower()
if key in result:
result[key] = int(parts[1])
finally:
if status is not None:
status.close()
return result
```
It returns the current and peak resident memory size (which is probably what people mean when they talk about how much RAM an application is using). It is easy to extend it to grab other pieces of information from the `/proc/self/status` file.
For the curious: the full output of `cat /proc/self/status` looks like this:
```
% cat /proc/self/status
Name: cat
State: R (running)
Tgid: 4145
Pid: 4145
PPid: 4103
TracerPid: 0
Uid: 1000 1000 1000 1000
Gid: 1000 1000 1000 1000
FDSize: 32
Groups: 20 24 25 29 40 44 46 100 1000
VmPeak: 3580 kB
VmSize: 3580 kB
VmLck: 0 kB
VmHWM: 472 kB
VmRSS: 472 kB
VmData: 160 kB
VmStk: 84 kB
VmExe: 44 kB
VmLib: 1496 kB
VmPTE: 16 kB
Threads: 1
SigQ: 0/16382
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: 0000000000000000
SigIgn: 0000000000000000
SigCgt: 0000000000000000
CapInh: 0000000000000000
CapPrm: 0000000000000000
CapEff: 0000000000000000
CapBnd: ffffffffffffffff
Cpus_allowed: 03
Cpus_allowed_list: 0-1
Mems_allowed: 1
Mems_allowed_list: 0
voluntary_ctxt_switches: 0
nonvoluntary_ctxt_switches: 0
``` | You could also use the `getrusage()` function from the standard library module `resource`. The resulting object has the attribute `ru_maxrss`, which gives total peak memory usage for the calling process:
```
>>> import resource
>>> resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
2656
```
The [Python docs](http://docs.python.org/library/resource.html#resource-usage) aren't clear on what the units are exactly, but the [Mac OS X man page](http://developer.apple.com/library/mac/#documentation/darwin/reference/manpages/man2/getrusage.2.html) for `getrusage(2)` describes the units as kilobytes.
The Linux man page isn't clear, but it seems to be equivalent to the `/proc/self/status` information (i.e. kilobytes) described in the accepted answer. For the same process as above, running on Linux, the function listed in the accepted answer gives:
```
>>> memory_usage()
{'peak': 6392, 'rss': 2656}
```
This may not be quite as easy to use as the `/proc/self/status` solution, but it is standard library, so (provided the units are standard) it should be cross-platform, and usable on systems which lack `/proc/` (eg Mac OS X and other Unixes, maybe Windows).
Also, `getrusage()` function can also be given `resource.RUSAGE_CHILDREN` to get the usage for child processes, and (on some systems) `resource.RUSAGE_BOTH` for total (self and child) process usage.
This will cover the `memory_get_usage()` case, but doesn't include peak usage. I'm unsure if any other functions from the `resource` module can give peak usage. | Python equivalent of PHP's memory_get_usage()? | [
"",
"python",
""
] |
I'm trying to use `usort()` and leverage a global variable inside its function scope, but without success.
I've simplified my code down to bare bones to show what I mean:
```
$testglobal = 1;
function cmp($a, $b) {
global $testglobal;
echo 'hi' . $testglobal;
}
usort($topics, "cmp");
```
Assuming the `usort()` runs twice, my expectations is this will be the output:
```
hi1hi1
```
Instead, my output is:
```
hihi
```
I've read the manual (<http://us.php.net/usort>) and I don't see any limitations on accessing global variables. If I assign the `usort()` to a variable that I echo, it outputs 1, so the `usort()` is definitely running successfully (plus, there are all those "hi's"). | Can't reproduce the "error" and neither can codepad: <http://codepad.org/5kwctnDP>
You could also use object properties instead of global variables
```
<?php
class Foo {
protected $test = 1;
public function bar($a, $b) {
echo 'hi' . $this->test;
return strcmp($a, $b);
}
}
$topics = array(1,2,3);
$foo = new Foo;
usort($topics, array($foo, 'bar'));
``` | The code I put in my question was dropped inside a template on bbPress, which is the forum cousin to Wordpress. A friend told me that "Sometimes PHP will act weird if you don't global a variable before you define it, depending on how nested the code is when it's executed - bbPress does some complex includes by the time the template outputs".
So I tried that and it works:
```
global $hi123;
$hi123 = ' working ';
```
I'm answering my own question in case another idiot like me finds this in a Google search. :-)
I'm going to accept VolkerK's answer, though, because the object workaround is pretty clever. | Can't access global variable inside of a usort() function call | [
"",
"php",
"function",
"scope",
"global-variables",
"usort",
""
] |
I have a DataGrid Control which is bound to a SQL Table.
The XAML Code is:
```
<data:DataGrid x:Name="dg_sql_data"
Grid.Row="1"
Visibility="Collapsed"
Height="auto"
Margin="0,5,5,5"
AutoGenerateColumns="false"
AlternatingRowBackground="Aqua"
Opacity="80"
>
<data:DataGrid.Columns>
<data:DataGridTextColumn Header="Latitude" Binding="{Binding lat}" />
<data:DataGridTextColumn Header="Longitude" Binding="{Binding long}" />
<data:DataGridTextColumn Header="Time" Binding="{Binding time}" />
</data:DataGrid.Columns>
</data:DataGrid>
```
Is it possible increase the single columns sizes to fill out the complete width of the datagrid?
Thanks,
Henrik
**Edit:
Columns with "\*" as width are coming with the Silverlight SDK 4.** | Solution:
```
void dg_sql_data_SizeChanged(object sender, SizeChangedEventArgs e)
{
DataGrid myDataGrid = (DataGrid)sender;
// Do not change column size if Visibility State Changed
if (myDataGrid.RenderSize.Width != 0)
{
double all_columns_sizes = 0.0;
foreach (DataGridColumn dg_c in myDataGrid.Columns)
{
all_columns_sizes += dg_c.ActualWidth;
}
// Space available to fill ( -18 Standard vScrollbar)
double space_available = (myDataGrid.RenderSize.Width - 18) - all_columns_sizes;
foreach (DataGridColumn dg_c in myDataGrid.Columns)
{
dg_c.Width = new DataGridLength(dg_c.ActualWidth + (space_available / myDataGrid.Columns.Count));
}
}
}
``` | ## **Tested only in WPF, not in Silverlight:**
I set up in WPF 3.5 SP1 and it works perfect, no guaranties about Silverlight, but if it works it's indeed charming.
```
<data:DataGridTextColumn Header="Time" Binding="{Binding}" Width="*" />
``` | Increase columns width in Silverlight DataGrid to fill whole DG width | [
"",
"c#",
"silverlight",
"datagrid",
"width",
""
] |
I want to select a token out of a string if it exists in the string, I've got as far the following but I'm unsure why it doesn't compile:
```
IList<string> tokens = _animals.Split(';');
Func<string, bool> f1 = str => str.Contains("Dog");
Func<string, Func<string, bool>, string> f2 = str => Equals(f1, true);
var selected = tokens.Select(f2);
``` | Or in words
```
var selected = from token in tokens where token.Contains("Dog") select token;
``` | I think you just want this.
```
var selected = tokens.Where(str => str.Contains("Dog"));
``` | How do I select tokens from a string using LINQ? | [
"",
"c#",
"linq",
""
] |
When running the following python code:
```
>>> f = open(r"myfile.txt", "a+")
>>> f.seek(-1,2)
>>> f.read()
'a'
>>> f.write('\n')
```
I get the following (helpful) exception:
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 0] Error
```
The same thing happens when openning with "r+".
Is this supposed to fail? Why?
Edit:
1. Obviously, this is just an example, not what I am actually trying to execute. My actual goal was to verify that the files ends with "\n", or add one, before adding the new lines.
2. I am working under Windows XP, and they problem exists in both Python 2.5 and Python 2.6.
3. I managed to bypass the problem by calling seek() again:
> > > f = open(r"myfile.txt", "a+")
> > > f.seek(-1,2)
> > > f.read()
> > > 'a'
> > > f.seek(-10,2)
> > > f.write('\n')
The actual parameters of the 2nd seek call don't seem to matter. | This appears to be a Windows-specific problem - see <http://bugs.python.org/issue1521491> for a similar issue.
Even better, a workaround given and explained at <http://mail.python.org/pipermail/python-bugs-list/2005-August/029886.html>, insert:
```
f.seek(f.tell())
```
between the read() and write() calls. | the a+ mode is for appending, if you want to read & write, you are looking for r+.
try this:
```
>>> f = open("myfile.txt", "r+")
>>> f.write('\n')
```
**Edit:**
you should have specified your platform initially... there are known problems with seek within windows. When trying to seek, UNIX and Win32 have different line endings, LF and CRLF respectively. There is also an issue with reading to the end of a file. I think you are looking for the seek(2) offset for the end of the file, then carry on from there.
these articles may be of interest to you (the second one more specifically):
<http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-08/2512.html>
<http://mail.python.org/pipermail/python-list/2002-June/150556.html> | seek(), then read(), then write() in python | [
"",
"python",
"file-io",
""
] |
I'm using a GET variable and people get to it by the following URL:
```
page?siteID=1
```
and I check to make sure that siteID is an integer, but PHP is saying it is a string.
How can I convert it to a integer? I noticed that `intval()` would convert 0x1A to 26, which I don't want to happen. | If you don't want to convert the variable, but simply check if it represents a number, you can also use the [`is_numeric`](http://www.php.net/is_numeric) function. Either that, or you can use the conversion methods as described in other answers, whichever suits your particular need best.
**EDIT:** based on James Socol's comment, it may also be worth looking at the [`ctype_digit`](http://www.php.net/ctype_digit) function. For your particular application (it looks like you want to check for some page ID number), this might be better suited than the `is_numeric` function. | Just as a side note, so that you know *why* this is happening, here's what's going on.
When a web browser sends a `GET` request, it's all text. The URL `<http://example.com/page?siteID=1>' is actually sent as a single string; in the HTTP request it will be this line:
```
GET /page?siteID=1 HTTP/1.0
```
(The "`http://example.com`" part was used by the web browser to figure out which server to talk to, and what network protocol to use.)
PHP gets hold of that and does a whole bunch of work for you to parse it. It splits it into three pieces based on those spaces (method "`GET`", URI "`/page?siteID=1`" and protocol "`HTTP/1.1`"), and further parses the URI into a path ("`/page`") and query parameters ("siteID=1"), which it further parses into name/value pairs. And even that whole `GET` line quoted above was only part of the full text stream delivered to the HTTP server as a request.
So you're seeing the the result of a whole lot of work to convert a longish sequence of characters into a lot of different pieces.
If you're really curious, you can use tools such as Wireshark or the Firefox [Live HTTP Headers plugin](https://addons.mozilla.org/en-US/firefox/addon/3829) to see the details of what text strings are actually passing over the network. It's worth learning, if you're a web developer. | php 1 is a string not integer | [
"",
"php",
""
] |
I know this might be a long shot, but here it goes. I have several active projects and each has sub project library which gets compiled when the main project compiles. These libraries are dynamic ones, but recently there was an issue that might arise a need for those libraries (most of them are shared between projects) to be static instead of dynamic.
Now, I am quite sure someone has devised a system where I could make a library which could be compiled wither as static into the project or dynamic one with something like a simple preprocessor directive or something. If not, I'll pipe dream away.
edit:
looks like CMake might be it, however, apart from building stuff I would also like to alleviate \_\_declspec(dllimport) and \_\_declspec(dllexport) from my code - so that I can automatically switch between static and dynamic. Although it is fairly easy to do with preprocessor macros, I thought maybe there might be some form of a system already in use by people? | I like to use [CMake](http://cmake.org) to avoid these type of problems. | If you want it to be cross platform, you'll have to use a tool like SCons or Make and setup different compiler/linker arguments based on whatever command variables you pass in. You'll have to do it for each platform and link-type combo you support.
In Visual Studio's Configuration Manager (you're not limited to just Release and Debug) and then you can have ReleaseStatic and ReleaseDynamic and any other configs you can dream up. Then you just set the proper compiler and linker switches for each configuration. | Is there a way to automatically make a library either static or dynamic? | [
"",
"c++",
"visual-studio",
"gcc",
"cross-platform",
""
] |
I need a function that returns the ASCII value of a character, including spaces, tabs, newlines, etc...
On a similar note, what is the function that converts between hexadecimal, decimal, and binary numbers? | ```
char c;
int ascii = (int) c;
s2.data[j]=(char)count;
```
A char **is** an integer, no need for conversion functions.
Maybe you are looking for functions that display integers as a string - using hex, binary or decimal representations? | You don't need a function to get the ASCII value -- just convert to an integer by an (implicit) cast:
```
int x = 'A'; // x = 65
int y = '\t'; // x = 9
```
To convert a number to hexadecimal or decimal, you can use any of the members of the `printf` family:
```
char buffer[32]; // make sure this is big enough!
sprintf(buffer, "%d", 12345); // decimal: buffer is assigned "12345"
sprintf(buffer, "%x", 12345); // hex: buffer is assigned "3039"
```
There is no built-in function to convert to binary; you'll have to roll your own. | Is there a function that returns the ASCII value of a character? (C++) | [
"",
"c++",
"binary",
"ascii",
"character",
"hex",
""
] |
I seem to remember there is a problem with WITH. I don’t miss it; I prefer each line of my code to stand on its own.
I started wondering about this when I learned (at SO) that people consider chaining one of their favorite features of jQuery. JavaScript’s WITH and jQuery’s chaining is, basically, the same feature, right? | With and chaining aren't quite the same. With affects scope, while chaining doesn't. Consider:
```
a.b.c = foo;
```
or:
```
with(a.b) { c = foo; }
```
In the second case, you've got no idea if c exists outside the with block, so if it's possible that you're just clobbering something another part of the program is relying on. | No, they aren't the same thing...
*With* is a shorthand to reference a class's members without the need to fully qualify their names.
```
with o
{
x = y; // where x is a member of o. But how can you tell for sure?
}
```
Read what Douglas Crockford has to say about With. He encourages avoiding it--says its error prone and ambiguous. I agree with him.
jQuery chaining is a way to implement a fluent interface that allows you to pipe the result fro one method directly into another method. That is the output of a given method serves as input into the next. jQuery chaining can indeed look like with if you use lots of whitespace. The example below is from John Resig shows this.
```
jQuery("div").hide("slow", function(){
jQuery(this)
.addClass("done")
.find("span")
.addClass("done")
.end()
.show("slow", function(){
jQuery(this).removeClass("done");
});
});
```
[Read about jQuery chaining here](http://www.aspcode.net/JQuery-and-function-chaining.aspx) and [here](http://blog.pengoworks.com/index.cfm/2007/10/26/jQuery-Understanding-the-chain) | What is wrong with WITH statement in JavaScript? | [
"",
"javascript",
"jquery",
""
] |
I have three tables: videos, videos\_categories, and categories.
The tables look like this:
```
videos: video_id, title, etc...
videos_categories: video_id, category_id
categories: category_id, name, etc...
```
In my app, I allow a user to multiselect categories. When they do so, I need to return all videos that are in **every selected category**.
I ended up with this:
```
SELECT * FROM videos WHERE video_id IN (
SELECT c1.video_id FROM videos_categories AS c1
JOIN c2.videos_categories AS c2
ON c1.video_id = c2.video_id
WHERE c1.category_id = 1 AND c2.category_id = 2
)
```
But for every category I add to the multiselect, I have to add a join to my inner select:
```
SELECT * FROM videos WHERE video_id IN (
SELECT c1.video_id FROM videos_categories AS c1
JOIN videos_categories AS c2
ON c1.video_id = c2.video_id
JOIN videos_categories AS c3
ON c2.video_id = c3.video_id
WHERE c1.category_id = 1 AND c2.category_id = 2 AND c3.category_id = 3
)
```
I can't help but feel this is the *really wrong* way to do this, but I'm blocked trying to see the proper way to go about it. | if this is a primary key:
```
videos_categories: video_id, category_id
```
then a GROUP BY and HAVING should work, try this:
```
SELECT
*
FROM videos
WHERE video_id IN (SELECT
video_id
FROM videos_categories
WHERE category_id IN (1,2,3)
GROUP BY video_id
HAVING COUNT(video_id)=3
)
``` | Here's a FOR XML PATH solution:
```
--Sample data
CREATE TABLE Video
(
VideoID int,
VideoName varchar(50)
)
CREATE TABLE Videos_Categories
(
VideoID int,
CategoryID int
)
INSERT Video(VideoID, VideoName)
SELECT 1, 'Indiana Jones'
UNION ALL
SELECT 2, 'Star Trek'
INSERT Videos_Categories(VideoID, CategoryID)
SELECT 1, 1
UNION ALL
SELECT 1, 2
UNION ALL
SELECT 1, 3
UNION ALL
SELECT 2, 1
GO
--The query
;WITH GroupedVideos
AS
(
SELECT v.*,
SUBSTRING(
(SELECT (', ') + CAST(vc.CategoryID AS varchar(20))
FROM Videos_Categories AS vc
WHERE vc.VideoID = v.VideoID
AND vc.CategoryID IN (1,2)
ORDER BY vc.CategoryID
FOR XML PATH('')), 3, 2000) AS CatList
FROM Video AS v
)
SELECT *
FROM GroupedVideos
WHERE CatList = '1, 2'
```
## (Ignore everything below - I misread the question)
Try
```
WHERE c1.category_id IN (1,2,3)
```
or
```
...
FROM videos v
JOIN Vedeos_categories vc ON v.video_id = vc.video_id
WHERE vc.category_id IN (1,2,3)
```
Multiple joins aren't at all necessary.
Edit: to put the solutions in context (I realize it's not obvious):
```
SELECT *
FROM videos
WHERE video_id IN
( SELECT c1.video_id
FROM videos_categories AS c1
WHERE c1.category_id = IN (1,2,3))
```
or
```
SELECT *
FROM videos v
JOIN Vedeos_categories vc ON v.video_id = vc.video_id
WHERE vc.category_id IN (1,2,3)
``` | SQL Many-to-Many Query Problem | [
"",
"sql",
"mysql",
"many-to-many",
""
] |
When I do something like
```
#include<iostream>
int main()
{
int x;
return 0;
}
```
I get a warning about x being an unreferenced local variable (I assume becuase I created a variable, then did not use it), why does this give me a warning though? | Probably because you're wasting memory for nothing.
Besides, the code becomes dirty and harder to understand, not to mention that programmers don't usually define variables they don't need, so it's sort of a "is this really what you meant?" warning. | Because usually people don't create unreferenced variables intentionally. So if there is an unreferenced variable in a program, usually it is a sign that you have a bug somewhere, and the compiler warns you about it. | Why do I get an "Unreferenced Local Variable" warning? (C++) | [
"",
"c++",
"variables",
"initialization",
""
] |
I have terminal.app set to accept utf-8 and in bash I can type unicode characters, copy and paste them, but if I start the python shell I can't and if I try to decode unicode I get errors:
```
>>> wtf = u'\xe4\xf6\xfc'.decode()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)
>>> wtf = u'\xe4\xf6\xfc'.decode('utf-8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)
```
Anyone know what I'm doing wrong? | I think there is encode/decode confusion all over the place. You start with an unicode object:
```
u'\xe4\xf6\xfc'
```
This is an unicode object, the three characters are the unicode codepoints for "äöü". If you want to turn them into Utf-8, you have to **encode** them:
```
>>> u'\xe4\xf6\xfc'.encode('utf-8')
'\xc3\xa4\xc3\xb6\xc3\xbc'
```
The resulting six characters are the Utf-8 representation of "äöü".
If you call `decode(...)`, you try to interpret the characters as some encoding that still needs to be converted to unicode. Since it already is Unicode, this doesn't work. Your first call tries a Ascii to Unicode conversion, the second call a Utf-8 to Unicode conversion. Since `u'\xe4\xf6\xfc'` is neither valid Ascii nor valid Utf-8 these conversion attempts fail.
Further confusion might come from the fact that `'\xe4\xf6\xfc'` is also the Latin1/ISO-8859-1 encoding of "äöü". If you write a normal python string (without the leading "u" that marks it as unicode), you can convert it to an unicode object with `decode('latin1')`:
```
>>> '\xe4\xf6\xfc'.decode('latin1')
u'\xe4\xf6\xfc'
``` | I think you have encoding and decoding backwards. You encode Unicode into a byte stream, and decode the byte stream into Unicode.
```
Python 2.6.1 (r261:67515, Dec 6 2008, 16:42:21)
[GCC 4.0.1 (Apple Computer, Inc. build 5370)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> wtf = u'\xe4\xf6\xfc'
>>> wtf
u'\xe4\xf6\xfc'
>>> print wtf
äöü
>>> wtf.encode('UTF-8')
'\xc3\xa4\xc3\xb6\xc3\xbc'
>>> print '\xc3\xa4\xc3\xb6\xc3\xbc'.decode('utf-8')
äöü
``` | Can't decode utf-8 string in python on os x terminal.app | [
"",
"python",
"macos",
"unicode",
"terminal",
""
] |
What if I have a class that both extends an abstract class and implements an interface, for example:
```
class Example : AbstractExample, ExampleInterface
{
// class content here
}
```
How can I initialize this class so I can access methods from both the interface and the abstract class?
When I do:
```
AbstractExample example = new Example();
```
I cannot access methods from the interface. | The last example will tie you to a solid instance of either the interface or abstract class which I presume is not your goal.The bad news is you're NOT in a dynamically typed language here, so your stuck with either having a reference to a solid "Example" objects as previously sprcified or casting/uncasting i.e:
```
AbstractExample example = new Example();
((IExampleInterface)example).DoSomeMethodDefinedInInterface();
```
Your other alternitives are to have both AbstractExample and IExampleInterface implement a common interface so you would have i.e.
```
abstract class AbstractExample : ICommonInterface
interface IExampleInterface : ICommonInterface
class Example : AbstractExample, IExampleInterface
```
Now you could work with ICommonInterface and have the functionality of both the abstract class and the implementation of your IExample interface.
If none of these answers are acceptable, you may want to look at some of the DLR languages that run under the .NET framework i.e. IronPython. | You need to
* implement the interface in AbstractExample
* or get a reference to Example
`Example example = new Example();` | Class both extends an abstract class and implements an interface | [
"",
"c#",
".net",
"oop",
"interface",
"abstract-class",
""
] |
I have a small C# function that takes any generic SQLDataReader and converts it to a csv file. However I now need to ignore 1 column from a datareader that gets passed into it.
**How can I remove 1 column from the SQLDataReader?**
This column is needed in the query mainly for ordering but is used in another area on the same pageload, but I do not wish for it to be displayed in the csv file that I will be generating.
EDIT:
I think that I was somewhat missleading, The column that I wish to delete is used in other cases, just not this one, So just removing from the query will work but would cause me to have to run the query twice, instead of only once, and it is a larger query. | Pass an array of integers you wish to hide. The integers correspond to the index of the columns you want to turn off. You could create an overloaded method so you don't have to change the code in your program where you are calling it and printing each column.
(I'm assuming a lot here but the overload is the key bit)
```
public void MakeMyCSV(string MyFileName, SQLDataReader DataToOutput)
{
MakeMyCSV(MyFileName, DataToOutput, null);
}
public void MakeMyCSV(string MyFileName, SQLDataReader DataToOutput, int[] ExcludedColumns) //if this is your current method signature...
{
//iterate through each record
// iterate through each column
// if ExcludedColumns is not null then see if this column is in it
// if it is not in it, output it
}
``` | You don't need to include a column used in the order by clause of a SQL query in the result set. Can you just leave it out of the select statement? | Remove column from datareader | [
"",
"c#",
"asp.net",
"sqldatareader",
""
] |
Duplicate: [Run .NET exe in linux](https://stackoverflow.com/questions/800999/run-net-exe-in-linux)
Hello,
Is it possible to make my existing Windows Forms Application made using Visual Studio 2008 and .Net framework 2.0 run on Linux by recompiling in Linux with less/No code changes?
Thanks | very possible, however, depending on your application your mileage may vary. no-nos include third party libraries/DLLs that depend on COM and Win32 calls, and P/Invokes. you may also have to watch out for code that does file/directory concatenation, as unix uses "/" as directory separator while Windows uses "\". | I suggest you recompile the same code in the Mono IDE, and by making any minor alterations that may be required. I've done this many times. | Making existing C# Windows Application run on linux | [
"",
"c#",
"windows",
"linux",
"mono",
""
] |
Can I create a javascript variable and increment that variable when I press a button (not submit the form).
Thanks! | Yes:
```
<script type="text/javascript">
var counter = 0;
</script>
```
and
```
<button onclick="counter++">Increment</button>
``` | The purist way to do this would be to add event handlers to the button, instead of mixing behavior with the content (LSM, Layered Semantic Markup)
```
<input type="button" value="Increment" id="increment"/>
<script type="text/javascript">
var count = 0;
// JQuery way
$('#increment').click(function (e) {
e.preventDefault();
count++;
});
// YUI way
YAHOO.util.Event.on('increment', 'click', function (e) {
YAHOO.util.Event.preventDefault(e);
count++;
});
// Simple way
document.getElementById('increment').onclick = function (e) {
count++;
if (e.preventDefault) {
e.preventDefault();
}
e.returnValue = false;
};
</script>
``` | How to increment a JavaScript variable using a button press event | [
"",
"javascript",
""
] |
I have a class (foo) that contains a vector.
If i try iterating over the elements in the vector like so:
```
for(vector<random>::iterator it = foo.getVector().begin();
it != foo.getVector().end(); ++it) {
cout << (*it) << endl;
}
```
The first element is always corrupted and returns garbage data.
However, if do something like:
```
vector<random> v = foo.getVector();
for(vector<random>::iterator it = v.begin();
it != v.end(); ++it) {
cout << (*it) << endl;
}
```
Everything appears to be working fine. Is there a "gotcha" that I do not know about?
I've also tried doing cout << foo.getVector()[0] << endl; outside of the loop but that appears to be working ok.
Thanks.
**Edit:**
Here's my header file:
```
#ifndef HITS
#define HITS
#include <vector>
#include "wrappers.h"
class Hits {
public:
Hits();
std::vector<word_idx_value> getVector() {return speech_hits;}
const std::vector<word_idx_value> getVector() const {return speech_hits;}
void add(const word_idx_value&);
Hits &operator+=(const Hits&);
private:
std::vector<word_idx_value> speech_hits;
};
#endif
``` | ```
for(vector<random>::iterator it = foo.getVector().begin();
```
The temporary vector is returned when you do `foo.getVector()` and it gets destroyed the moment `;` is encountered after `foo.getVector().begin();` Hence iterator becomes invalid inside the loop.
If you store the value of `foo.getVector();` in vector v ( `v = foo.getVector();`) and then use the vector v, it works fine. It is because the vector v is valid throughout the loop. | getVector() returns a vector by value. The two invocations of getVector (begin() and end()) return different copies of the vector, so you call begin() on one object and end() on another. What you get is two iterators into two different containers. Comparing those two iterators with != yields an undefined value. | C++: First element of vector "corrupting" | [
"",
"c++",
"stl",
"vector",
"iterator",
"cout",
""
] |
I have signed up(paid) for Google site search. They have me a url of a sort of web service where I can send a query to it, it searches my site, and it returns XML of the search results. Well I am trying to load this XML via Ajax from a page on my site but I cannot. I can load from any of my pages on my domain so I am assuming it is because of the XML being on Google's domain. So there has got to be a way to load it though, I don't think they would have given me the URL if I couldn't do anything with it lol. Does anyone know how to do this?
Thanks!
**UPDATE**:
this is what the page says on google that gave me the XML:
> How to get XML
>
> You can get XML results for your
> search engine by replacing query+terms
> with your search query in this URL:
>
> <http://www.google.com/cse?cx=MY_UNIQUE_KEY&client=google-csbe&output=xml_no_dtd&q=query+terms>
Where MY\_UNIQUE\_KEY = my unique key. | You can't load external files with AJAX. However, you can set up a file on your own server that makes the content available on your server. For instance in PHP, you could write a file `googlexml.php`:
```
<?php
@readfile("http://www.google.com/cse?cx=MY_UNIQUE_KEY&client=googlecsbe&output=xml_no_dtd&q=query+terms");
?>
```
And then you could access that with AJAX. I'm not sure if Google's terms of use will let you do that, but if they do, then this is an option. | Does google not offer the ability to forward a DNS address to the IP of your service, folding it into your domain? This way you can do in AJAX
```
googleAlias.mydomain.com
```
Google should support this, but I don't know for sure. I imagine they would in the same way they do with GMail and external-domain mail.
Removes your cross-domain javascript issues
**edit** I expanded below and another user helpfully pointed out this should work (thanks Stobor)
Well, to get my company mail into GMail, if I recall, I needed to change the MX record on my DNS to point to a google IP. You may be able, if google supports it, to add an A record to your domain so an AJAX request to foo.yourdomain.com is the same as search.google.com or whatever. Google needs to recognize requests from your hostname in the A record and say "Oh yes, that's me, on my client's behalf" | Ajax: Load XML from different domain? | [
"",
"javascript",
"ajax",
"cross-domain",
""
] |
I am using this code to get the background image of a `div`.
```
var bgImage = $('#content').css('backgroundImage');
```
This is returning `url%28http://example.com/images/layout/content-trans.png%29`
I know you can do `element.height()` to get an element's height without `px` appended (`parseInt()` also works), so I was wondering if there was a similiar method for jQuery to get the actual background image minus the `url()` meta data.
I suppose I could use a regular expression, something like `/url\((.*)\)/`, but I'd rather know first if there is an built-in way. | url() is part of the value of background-image, so I guess you need to use regex replace.
```
var bgImage = $('#content').css('background-image').replace(/^url|[\(\)]/g, '');
```
Ref: <http://groups.google.com/group/jquery-en/browse_thread/thread/d866997cb206b35f> | Something like:
```
var imgUrl = 'http://example.com/images/layout/image.png';
var i = imgUrl.lastIndexOf("/");
var filename = imgUrl.substring(i, imgUrl.length - 1);
alert(filename);
```
In pure JS terms | Getting a div's background image with jQuery. Is there an inbuilt method to strip out the url() portion? | [
"",
"javascript",
"jquery",
""
] |
I have 5 tables:
customers
id - name
p\_orders
id - id\_customer - code - date
p\_items
id - id\_order - description - price
and h\_orders and h\_items, that are exactly the copy of p\_orders and p\_items.
When the p\_ tables reach a big amount of rows, i move the oldest to the h\_ tables.. they due as history.
So, my problem is: **how to retrieve the data from both the p\_ tables and h\_ considering them as one unique table**?
For example, i want to retrieve the number of orders for each customer, and the total price (**of all the customer's orders**), and i use that query:
```
SELECT
customer.id,
customer.name,
count(DISTINCT p_orders.id) AS num_orders,
sum(p_items.price) AS total_money
FROM
customer
INNER JOIN p_orders ON p_orders.id_customer = customer.id
INNER JOIN p_items ON p_items.id_order = p_orders.id
GROUP BY
customer.id,
customer.name,
p_orders.id_customer
ORDER BY
customer.id
```
it works just for one 'set' of tables (p\_ or h\_)..but i want them both.
I've tryed to use an UNION:
```
(
SELECT
customer.id,
customer.name,
count(DISTINCT p_orders.id) AS num_orders,
sum(p_items.price) AS total_money
FROM
customer
INNER JOIN p_orders ON p_orders.id_customer = customer.id
INNER JOIN p_items ON p_items.id_order = p_orders.id
GROUP BY
customer.id,
customer.name,
p_orders.id_customer
)
UNION
(
SELECT
customer.id,
customer.name,
count(DISTINCT h_orders.id) AS num_orders,
sum(h_items.price) AS total_money
FROM
customer
INNER JOIN h_orders ON h_orders.id_customer = customer.id
INNER JOIN h_items ON h_items.id_order = h_orders.id
GROUP BY
customer.id,
customer.name,
h_orders.id_customer
)
ORDER BY id ASC
```
This one works, but if a customer have orders both in the p\_ tables and in the h\_ tables, i'll have 2 rows for that customer with 2 different num\_orders and total\_money (respectively coming from p\_ tables and h\_ tables)
I've tryed to add a GROUP BY id outside the union:
```
(
--SELECT 2
)
UNION
(
--SELECT 1
)
GROUP BY id
ORDER BY id ASC
```
but the query fail with *ERROR: syntax error at or near "GROUP" at character 948*, seem like GROUP BY cannot be used in that way.
Any suggestion?
**EDIT:**
For uriDium, yes, all the tables have the id column as primary key, and the referred fields (aka p\_orders.id\_customer) are foreign keys too.
Here the test db structure dump (i added some indexes and foreign keys after the table creation, but i dont think that this mean something):
```
CREATE TABLE customer (
id serial NOT NULL,
name character(50)
);
CREATE TABLE p_orders (
id serial NOT NULL,
id_customer integer NOT NULL,
date date DEFAULT now(),
code character(5)
);
CREATE TABLE p_items (
id serial NOT NULL,
id_order integer NOT NULL,
descr character(250),
price money
);
CREATE TABLE h_orders (
id integer NOT NULL,
id_customer integer NOT NULL,
date date,
code character(5)
);
CREATE TABLE h_items (
id integer NOT NULL,
id_order integer NOT NULL,
descr character(250),
price money
);
CREATE UNIQUE INDEX id_h_orders ON h_orders USING btree (id);
CREATE INDEX id_h_o_c ON h_orders USING btree (id_customer);
CREATE UNIQUE INDEX id_items_h ON h_items USING btree (id);
CREATE INDEX id_ordinr_dsve ON h_items USING btree (id_order);
ALTER TABLE ONLY customer
ADD CONSTRAINT customer_pkey (id);
ALTER TABLE ONLY p_orders
ADD CONSTRAINT p_orders_pkey PRIMARY KEY (id);
ALTER TABLE ONLY p_items
ADD CONSTRAINT p_items_pkey PRIMARY KEY (id);
ALTER TABLE ONLY stats
ADD CONSTRAINT stats_pkey PRIMARY KEY (id);
ALTER TABLE ONLY p_orders
ADD CONSTRAINT "$1" FOREIGN KEY (id_customer) REFERENCES customer(id) ON DELETE CASCADE;
ALTER TABLE ONLY p_items
ADD CONSTRAINT "$1" FOREIGN KEY (id_order) REFERENCES p_orders(id) ON DELETE CASCADE;
ALTER TABLE ONLY h_orders
ADD CONSTRAINT "$1" FOREIGN KEY (id_customer) REFERENCES customer(id) ON DELETE CASCADE;
ALTER TABLE ONLY h_items
ADD CONSTRAINT "$1" FOREIGN KEY (id_order) REFERENCES h_orders(id) ON DELETE CASCADE;
``` | You should probably create views over the two tables:
```
CREATE VIEW All_Orders
AS
SELECT
id,
id_customer,
code,
date,
'H' AS order_type
FROM
h_orders
UNION ALL
SELECT
id,
id_customer,
code,
date,
'P' AS order_type
FROM
p_orders
CREATE VIEW All_Order_Items -- A table name of "items" is pretty bad in my opinion
AS
SELECT
id,
id_order,
description,
price,
'H' AS order_item_type
FROM
h_items
UNION ALL
SELECT
id,
id_order,
description,
price,
'P' AS order_item_type
FROM
p_items
```
Now you can just join to those views. I included the types (P & H) so that you know what the "id" column now refers to. If the ids in your two tables ("h" and "p" can have duplicates then you will have to join the Orders table right in the All\_Order\_Items view. Otherwise you will have a lot of trouble joining between the two views. Hopefully your id columns are intelligently designed and not just auto-incrmenting or identity columns. | You could try this:
```
SELECT tbl.ID,
tbl.Name,
sum(tbl.num_orders) num_orders,
sum(tbl.total_money) total_money
FROM (
SELECT customer.id,
customer.name,
count(DISTINCT p_orders.id) AS num_orders,
sum(p_items.price) AS total_money
FROM customer
INNER JOIN p_orders
ON p_orders.id_customer = customer.id
INNER JOIN p_items
ON p_items.id_order = p_orders.id
GROUP BY customer.id, customer.name, p_orders.id_customer
UNION
SELECT customer.id,
customer.name,
count(DISTINCT h_orders.id) AS num_orders,
sum(h_items.price) AS total_money
FROM customer
INNER JOIN h_orders
ON h_orders.id_customer = customer.id
INNER JOIN h_items
ON h_items.id_order = h_orders.id
GROUP BY customer.id, customer.name, h_orders.id_customer
) tbl
GROUB BY tbl.id, tbl.name
ORDER BY tbl.id ASC
``` | SQL: grouping 2 tables as 1 with join, union, and then? | [
"",
"sql",
"select",
"join",
"union",
""
] |
I have a url string like this:
```
http://www.google.com/cse?cx=017840637368510444960:ny1lmky7r-0&client=google-csbe&output=xml_no_dtd&q=simon+g
```
I need to send this url from ajax to a php script as a single string variable.
I am having trouble though because it keeps getting split into several vars because of the vars in the url string itself. Make sense? How can I send this as a single string??
Thanks!!! | You need to encode it.
In PHP: [`urlencode()`](http://www.php.net/urlencode)
```
$str = urlencode('http://....');
```
In Javascript: encodeURIComponent
```
str = encodeURIComponent('http://...');
``` | You need to [urlencode](https://www.php.net/urlencode) the url. You will then [urldecode](https://www.php.net/manual/en/function.urldecode.php) on the page that receives it.
So the url would become
```
http%3A%2F%2Fwww.google.com%2Fcse%3Fcx%3D017840637368510444960%3Any1lmky7r-0%26client%3Dgoogle-csbe%26output%3Dxml_no_dtd%26q%3Dsimon%2Bg%0D%0A
``` | How to send URL (with vars in it) as a single var? | [
"",
"php",
"ajax",
"urlvariables",
""
] |
Just out of curiosity, how does iostream access the input-output system. (I have a bad habit of constantly reinventing the wheel, and I'm wondering if I can build a custom input-output system to the likes of iostream). | For a detailed guide to IOstreams, see the book [Standard C++ IOStreams and Locales](http://www.angelikalanger.com/iostreams.html). After reading it I suspect you will be content to manage with with the status quo - IOStreams are probably the most complex part of the C++ standard library. | It depends...
It somehow interacts with the native IO system of the operating system. It might internally use the C library, which uses system calls to the kernel, or it might use system calls directly. The exact implementation is highly dependent on the platform.
Many people will say don't reinvent the wheel, but it could be a good learning experience. If you are using Windows, look into the Win32 API calls for file handling. If you use Linux, either use the POSIX/C library, or use the system calls (much harder, I would suggest going with the C library). | How does <iostream> work? (C++) | [
"",
"c++",
"input",
"iostream",
""
] |
I am using OpenCV and saving as a jpeg using the cvSaveImage function, but I am unable to find the Jpeg compression factor used by this.
1. What's cvSaveImage(...)'s Jpeg Compression factor
2. How can I pass the compression factor when using cvSaveImage(...) | Currently cvSaveImage() is declared to take only two parameters:
```
int cvSaveImage( const char* filename, const CvArr* image );
```
However, the "[latest tested snapshot](http://opencvlibrary.svn.sourceforge.net/viewvc/opencvlibrary/tags/latest_tested_snapshot/opencv/)" has:
```
#define CV_IMWRITE_JPEG_QUALITY 1
#define CV_IMWRITE_PNG_COMPRESSION 16
#define CV_IMWRITE_PXM_BINARY 32
/* save image to file */
CVAPI(int) cvSaveImage( const char* filename, const CvArr* image,
const int* params CV_DEFAULT(0) );
```
I've been unable to find any documentation, but my impression from poking through this code is that you would build an array of int values to pass in the third parameter:
```
int p[3];
p[0] = CV_IMWRITE_JPEG_QUALITY;
p[1] = desired_quality_value;
p[2] = 0;
```
I don't know how the quality value is encoded, and I've never tried this, so caveat emptor.
**Edit:**
Being a bit curious about this, I downloaded and built the latest trunk version of OpenCV, and was able to confirm the above via this bit of throwaway code:
```
#include "cv.h"
#include "highgui.h"
int main(int argc, char **argv)
{
int p[3];
IplImage *img = cvLoadImage("test.jpg");
p[0] = CV_IMWRITE_JPEG_QUALITY;
p[1] = 10;
p[2] = 0;
cvSaveImage("out1.jpg", img, p);
p[0] = CV_IMWRITE_JPEG_QUALITY;
p[1] = 100;
p[2] = 0;
cvSaveImage("out2.jpg", img, p);
exit(0);
}
```
My "test.jpg" was 2,054 KB, the created "out1.jpg" was 182 KB and "out2.jpg" was 4,009 KB.
Looks like you should be in good shape assuming you can use the latest code available from the Subversion repository.
BTW, the range for the quality parameter is 0-100, default is 95. | OpenCV now [has a parameter](http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#imwrite) to set jpeg quality. I'm not sure exactly when this was introduced, but presumably sometime after 2.0.
```
const int JPEG_QUALITY = 80;
Mat src;
// put data in src
vector<int> params;
params.push_back(CV_IMWRITE_JPEG_QUALITY);
params.push_back(JPEG_QUALITY);
imwrite("filename.jpg", src, params);
```
If you are using C++0x, you can use this shorter notation:
```
imwrite("filename.jpg", src, vector<int>({CV_IMWRITE_JPEG_QUALITY, JPEG_QUALITY});
``` | OpenCV cvSaveImage Jpeg Compression Factor | [
"",
"c++",
"image",
"opencv",
"jpeg",
""
] |
I'm trying to make a part of my code more fluent.
I have a string extension that makes an HTTP request out of the string and returns the response as a string. So I can do something like...
```
string _html = "http://www.stackoverflow.com".Request();
```
I'm trying to write an extension that will keep trying the request until it succeeds. My signature looks something like...
```
public static T KeepTrying<T>(this Func<T> KeepTryingThis) {
// Code to ignore exceptions and keep trying goes here
// Returns the result of KeepTryingThis if it succeeds
}
```
I intend to call it something like...
```
string _html = "http://www.stackoverflow.com".Request.KeepTrying();
```
Alas, that doesn't seem to work =). I tried making it into a lambda first but that doesn't seem to work either.
```
string _html = (() => "http://www.stackoverflow.com".Request()).KeepTrying();
```
Is there a way to do what I'm trying to do while keeping the syntax fairly fluent?
Suggestions much appreciated.
Thanks. | You can't use a method group for extension methods, or lambda expressions. I [blogged about this a while ago](http://msmvps.com/blogs/jon_skeet/archive/2008/01/08/extension-methods-on-lamdba-expressions-don-t-work-unfortunately.aspx).
I suspect you could cast to `Func<string>`:
```
string _html = ((Func<string>)"http://www.stackoverflow.com".Request)
.KeepTrying();
```
but that's pretty nasty.
One alternative would be to change `Request()` to *return* a Func, and use:
```
string _html = "http://www.stackoverflow.com".Request().KeepTrying();
```
Or if you wanted to keep the `Request` method itself simple, just add a `RequestFunc` method:
```
public static Func<string> RequestFunc(this string url)
{
return () => url.Request();
}
```
and then call:
```
string _html = "http://www.stackoverflow.com".RequestFunc().KeepTrying();
``` | Why not turn this on its head?
```
static T KeepTrying<T>(Func<T> func) {
T val = default(T);
while (true) {
try {
val = func();
break;
} catch { }
}
return val;
}
var html = KeepTrying(() => "http://www.stackoverflow.com".Request());
``` | Getting a parameterless method to act like a Func<ReturnT> | [
"",
"c#",
"lambda",
"extension-methods",
"fluent-interface",
""
] |
How to process dynamic source code in C++? Is it possible to use something like eval("foo")?
I have some functions that need to be called depending on user's choice:
```
void function1 ();
void function2 ();
...
void functionN ();
int main (int argv, char * argv [])
{
char * myString = new char [100];
...
myString = "1" //user input
cout << eval("function"+myString)();
}
```
How is it usually done?
**UPD**: Based on slacy's and clinisbut's answers I think I need to make a function registry. I suppose it should be made as an array of pointers to functions. Here's the question, how do I declare an array of pointers to functions? | C++ is a compiled language, and thus, there is no equivalent to "eval()".
For the specific example you mention, you could make a function registry that maps inputs (strings) to outputs (function pointers) and then call the resultant function.
There are several C++ interpreter libraries that are available, although performance will be very poor, they may accomplish what you want. Google search for "C++ interpreter". I've seen results for "[Ch](http://www.softintegration.com/)", "[CINT](http://root.cern.ch/drupal/content/cint)" and "clipp" | The real answer to your question is this:
```
extern "C" {
void function1 ();
void function2 ();
void function3 ();
}
int main (int argv, char * argv [])
{
char * myString = new char [100];
...
myString = "function1"; //user input
void (*f)() = dlsym(RTLD_NEXT, myString);
f();
}
```
You can obtain the function defined in your binary (by its name, if it was declared with extern "C"), and call it.
On windows, it becomes uglier, but still possible - read on GetProcAddress | Dynamic source code in C++ | [
"",
"c++",
"dynamic",
"evaluation",
""
] |
I am in charge of modeling a 3 floor warehouse, where boxes of documents will be stored. There are rows, columns and shelves in the equation.
in addition:
some floor/row/column/shelf combinations store 2 boxes, some 3.
some rows don't have the normal amount of columns.
They want my application to auto-increment to print labels (20 at a time) telling where the boxes go as a user scans them in.
So box 1 is scanned would print f1r1c1s1b1
box 2 would print f1r1c1s1b2
...
f3r26c26b3
I was thinking of building a MSSql database, filling it with all the possible combos and subtracting out the exception data. (using vb.net2005 for loops to do the filling)
then based on the smalldatetime or perhaps a timestamp column on the table, just grab the next one that doesn't have spotFilled column set.
**would this work? is there a better way?**
(the next step is blocking off the 20 at a time so 2 users could scan boxes without bumping into each other on the same floor/row/column, Most floor/row/column/shelf combos store 21 boxes, 1 bump would probably be ok. also they would like the boxes roughly in the same order received)
MSSQL server and VS2005 are already present in my work environment so those are the tools I am most familiar with. | I'm assuming that there's no trivial schema so you can map the whole location vector to a simple integer index? For instance, if it's always the first column that allows 3 boxes, you can still map the f3r26c26s1b3 vector to an integer.
Otherwise, the best solution is probably not to store each and every combination. Instead, assume that each shelf in fact does store 3 boxes and set the "spotFilled" of the third box to a dummy value (-1 or so; anything but NULL=unfilled). This will you to treat this as a normal rectangular array. It only works because your array is almost regular, but hey - real-world IT is all about recognizing the exceptions to the exceptions | Why not just have a normal table as if it was non-jagged (columns: Floor, Row, Column, Shelf, Box); put appropriate bounds on the data that will minimize how big the thing db needs to be, and then just store fake boxes in the fake spots. | How can I model this Jagged data? | [
"",
"sql",
"jagged-arrays",
""
] |
I am trying to write a function in C++ that solves for X using the quadratic equation. This is what I have written initially, which seems to work as long as there are no complex numbers for an answer:
```
float solution1 = (float)(-1.0 * b) + (sqrt((b * b) - (4 * a * c)));
solution1 = solution1 / (2*a);
cout << "Solution 1: " << solution1 << endl;
float solution2 = (float)(-b) - (sqrt((b*b) - (4 * a * c)));
solution2 = solution2 / (2*a);
cout << "Solution 2: " << solution2;
```
If, for example, I use the equation: x^2 - x - 6, I get the solution 3, -2 correctly.
My question is how would I account for complex numbers....for example, given the equation:
x^2 + 2x + 5
Solving by hand, I would get -1 + 2i, -1 - 2i.
Well, I guess two question, can I write the above better and also make it account for the complex number?
Thanks for any help! | Something like this would work:
```
struct complex { double r,i; }
struct pair<T> { T p1, p2; }
pair<complex> GetResults(double a, double b, double c)
{
pair<complex> result={0};
if(a<0.000001) // ==0
{
if(b>0.000001) // !=0
result.p1.r=result.p2.r=-c/b;
else
if(c>0.00001) throw exception("no solutions");
return result;
}
double delta=b*b-4*a*c;
if(delta>=0)
{
result.p1.r=(-b-sqrt(delta))/2/a;
result.p2.r=(-b+sqrt(delta))/2/a;
}
else
{
result.p1.r=result.p2.r=-b/2/a;
result.p1.i=sqrt(-delta)/2/a;
result.p2.i=-sqrt(-delta)/2/a;
}
return result;
}
```
That way you get the results in a similar way for both real and complex results (the real results just have the imaginary part set to 0). Would look even prettier with boost!
edit: fixed for the delta thing and added a check for degenerate cases like a=0. Sleepless night ftl! | An important note to all of this. The solutions shown in these responses and in the original question are not robust.
The well known solution *(-b +- sqrt(b^2 - 4ac)) / 2a* is known to be non-robust in computation when *ac* is very small compered to *b^2*, because one is subtracting two very similar values. It is better to use the lesser known solution *2c / (-b -+ sqrt(b^2 -4ac))* for the other root.
A robust solution can be calculated as:
```
temp = -0.5 * (b + sign(b) * sqrt(b*b - 4*a*c);
x1 = temp / a;
x2 = c / temp;
```
The use of sign(b) ensures that we are not subtracting two similar values.
For the OP, modify this for complex numbers as shown by other posters. | Solve Quadratic Equation in C++ | [
"",
"c++",
"math",
"equation",
"quadratic",
""
] |
I have a DataContract class that I have to fill by values from the Active Directory of our company.
```
[DataContract(Namespace = Global.Namespace)]
public class UserProfile
{
[DataMember(IsRequired = true, EmitDefaultValue = false)]
public string EmployeeID { get; private set; }
[DataMember(IsRequired = true, EmitDefaultValue = false)]
public string GivenName { get; private set; }
...
public static readonly string[] PropertiesToLoad = new[] { "EmployeeID", "GivenName" };
}
```
I was considering to make a custom attribute to decorate my properties, so that the code that would fill my object from the AD would not need to have the Mapping hardcoded, but much rather I could just decorate the properties to automatically fill the object.
And in the long run, I might also be able to get rid of this "PropertiesToLoad". Do you think that Attributes are a good way of solving this issue? And another question, if I do solve this by Attributes, am I likely to make a huge performance bottle neck or is the use of Attributes not really a performance issue. | I like to use attributes for this kind of concern because it helps make it clear in the code that the property is being used in a certain way. There is a trade-off between having the PropertiesToLoad in one place (as it is in the example above) or at the point of property declaration. I tend to find that using attributes helps code maintenance because I don't have to hunt down changes if the property is removed or modified.
As for performance, yes it will cause a performance hit but not huge. It is measurable but unless this is performance critical code, you probably won't notice. And even at that point, I'm guessing you'll find bigger issues. If the attribute reflection becomes an issue, there are way to mitigate the performance impact by using caching or other methods. | Using reflection and attributes *are* slower than regular C# compiled as IL, but the question is: how much are you doing it? If you aren't doing **lots** of this, you won't notice it.
There are ways of boosting the performance of reflection, but they are quite advanced.
That seems a reasonable way of specifying a mapping (and is comparable to most serialization and persistence frameworks - although often a separate API without attributes is offered too).
For (in)appropriate uses, see [Eric Lippert's blog](http://blogs.msdn.com/ericlippert/archive/2009/02/02/properties-vs-attributes.aspx). | Appropriate use of custom attributes? | [
"",
"c#",
".net",
"performance",
"reflection",
"attributes",
""
] |
What are some alternatives to the Microsoft security enhanced functions such as `strncpy_s` or `_itoa_s`? Although developing in MS environment the goal is to write code that could be ported easily to other platforms. | Rageous is correct, there is no complex logic behind it.
I would just use Microsoft's version for now and if you decide to port to another OS later, THEN implement it yourself for the target platform and use preprocessor commands to specify your implementation on the non-Windows platform(s). | **If you really want to program in C:**
Use the plain old standard `strncpy`.
**If you're programming in C++:**
Use the plain old standard string class `std::string`.
(hint: You probably want the latter. C strings are just bugs waiting to happen, even if you use the "secure" `*_s` functions. C++ added a string class for a reason) | Alternatives to MS strncpy_s | [
"",
"c++",
"visual-c++",
""
] |
I have previously read Spolsky's article on character-encoding, as well as [this from dive into python 3](http://diveintopython3.org/strings.html). I know php is getting Unicode at some point, but I am having trouble understanding why this is such a big deal.
If php-CLI is being used, ok it makes sense. However, in the web server world, isnt it up to the browser to take this integer and turn it into a character (based off character-encoding).
What am I not getting? | Well, for one thing you need to somehow generate the strings the browser displays :-) | PHP does "support" UTF8, look at the mbstring[1](http://uk2.php.net/mbstring) extension. Most of the problem comes from PHP developers who don't use the mb\* functions when dealing with UTF8 data.
UTF8 characters are often more than one character so you need to use functions which appreciate that fact like mb\_strpos[2](http://uk2.php.net/manual/en/function.mb-strpos.php) rather than strpos[3](http://uk2.php.net/manual/en/function.strpos.php).
It works fine if you are getting UTF8 from the browser -> putting in database -> getting it back out -> displaying it to the user. If you are doing something more involved with UTF8 data (or indeed any major text processing) you should probably consider using an alternative language. | unicode in php | [
"",
"php",
"unicode",
"ascii",
""
] |
Is there a best (see below) way to append two byte arrays in C#?
Pretending I have complete control, I can make the first byte array sufficiently large to hold the second byte array at the end and use the [Array.CopyTo](https://msdn.microsoft.com/en-us/library/system.array.copyto%28v=vs.110%29.aspx) function. Or I can loop over individual bytes and make an assignment.
Are there better ways? I can't imagine doing something like converting the byte arrays to string and joining them and converting them back would be better than either method above.
In terms of best/better (in order):
1. Fastest
2. Least RAM consumption
A constraint is that I must work in the .NET 2.0 framework.
The two choices recommended are MemoryStream and BlockCopy. I have run a simple speed test of 10,000,000 loops 3 times and got the following results:
## *Average of 3 runs of 10,000,000 loops in milliseconds:*
* **BlockCopy Time: 1154**, with a range of 13 milliseconds
* MemoryStream GetBuffer Time: 1470, with a range of 14 milliseconds
* MemoryStream ToArray Time: 1895, with a range of 3 milliseconds
* CopyTo Time: 2079, with a range of 19 milliseconds
* Byte-by-byte Time: 2203, with a range of 10 milliseconds
Results of List<byte> [AddRange](https://msdn.microsoft.com/en-us/library/z883w3dc%28v=vs.110%29.aspx) over 10 million loops:
List<byte> Time: 16694
## Relative RAM Consumption (1 is baseline, higher is worse):
* **Byte-by-byte: 1**
* **BlockCopy: 1**
* **Copy To: 1**
* MemoryStream GetBuffer: 2.3
* MemoryStream ToArray: 3.3
* List<byte>: 4.2
The test shows that in general, unless you are doing a lot of byte copies [**which I am**], looking at byte copies is not worth a focus [e.g. 10 million runs yielding a difference of as much as 1.1 seconds]. | You want [BlockCopy](http://msdn.microsoft.com/en-us/library/system.buffer.blockcopy.aspx)
According to [this blog post](https://web.archive.org/web/20140418112901/http://danielvl.blogspot.com/2004/04/use-bufferblockcopy-instead-of.html) it is faster than Array.CopyTo. | You could also use an approach with a MemoryStream. Suppose b1 and b2 are two byte arrays, you can get a new one, b3, by using the MemoryStream in the following fashion:
```
var s = new MemoryStream();
s.Write(b1, 0, b1.Length);
s.Write(b2, 0, b2.Length);
var b3 = s.ToArray();
```
This should work without LINQ and is in fact quite a bit faster. | Append two or more byte arrays in C# | [
"",
"c#",
"arrays",
""
] |
How should i do to create yyyy/mm/dd directory easy?
mysite.com/blog\*\*/2009/01/01/\*\*hello-world.aspx! | ```
String.Format(CultureInfo.InvariantCulture,
"mysite.com/blog**/{0:yyyy/MM/dd}/**hello-world.aspx",
DateTime.Now)
```
Will get you the date. You can add more parameters to it to get it just right. | Use the Uri class to combine the url together and use / to escape the \ character to be explicit rather than the cultural date seperator.
```
Uri oSiteBase = new Uri("http://mysite.com/blog");
Uri oSiteDay = new Uri(oSiteBase, DateTime.Now.ToString("yyyy\/MM\/dd"));
``` | C# create yyyy-mm-dd dir easy | [
"",
"c#",
""
] |
I need a javascript library to convert structured ascii text to html on the fly.
I am especially interested in the following point:
I would like do use anchored links inside pages, see <http://www.w3.org/TR/REC-html40/struct/links.html#h-12.1.1>
Which library for structured text would support this or if it is not supported could be easily extended (i could write an extension)?
Can you make a suggestion for a good and simple syntax for structured ascii text for "in page links"?
```
<a href="#jumpend">jump to the end</a>
...some body text...
<a name="jumpend">this is the end</a>
```
I like the way links are written in "markdown", so how could the name anchor in a to be written extension be expressed in a nice way?
Which libraries do you know or can you recommend? Should be multi browser, good and easy to read and extend clean source code, actively maintained.
I am presently having a look at the JavaScript Markdown library "Showdown": <http://attacklab.net/showdown/> | I think that you should not use markdown if you are looking for anchor references. Try the following Creole Wiki markup parsers:
* A prototype Javascript Creole 0.4 parser can be found at [MeatballSociety](http://www.meatballsociety.org/Creole/0.4/)
* [JavaScript Creole 1.0 Wiki Markup Parser](http://sourceforge.net/projects/jscreole/), based on the above | You might look into [markItUp!](http://markitup.jaysalvat.com/home/) | JavaScript libraries for Markdown, Textile and others; Anchor references | [
"",
"javascript",
"markdown",
"textile",
""
] |
I've found myself evaluating both of these libs. Apart from what the GraphicsMagick comparison says, I see that ImageMagick still got updates and it seems that the two are almost identical.
I'm just looking to do basic image manipulation in C++ (i.e. image load, filters, display); are there any differences I should be aware of when choosing between these libraries? | From what I have read GraphicsMagick is more stable and is faster.
I did a couple of unscientific tests and found gm to be twice as fast as im (doing a resize). | As with many things in life, different people have different ideas about what is best. If you ask a landscape photographer who wanders around in the rain in Scotland's mountains which is the best camera in the world, he's going to tell you a light-weight, weather-sealed camera. Ask a studio photographer, and he'll tell you the highest resolution one with the best flash sync speed. And if you ask a sports photographer he'll tell you the one with the fastest autofocus and highest frame rate. So it is with ImageMagick and GraphicsMagick.
Having answered around 2,000 StackOverflow questions on ImageMagick over the last 5+ years, I make the following observations...
**In terms of popularity...**
* ImageMagick questions on SO outnumber GraphicsMagick questions by a factor of 12:1 (7,375 questions vs 611 at May 2019), and
* ImageMagick followers on SO outnumber GraphicsMagick followers by 15:1 ((387 followers versus 25 at May 2019)
**In terms of performance...**
I am happy to concede that GraphicsMagick may be faster for some, but not all problems. However, if speed is your most important consideration, I think you should probably be using either `libvips`, or parallel code on today's multi-core CPUs or heavily SIMD-optimised (or GPU-optimised) libraries like OpenCV.
**In terms of features and flexibility...**
There is one very clear winner here - ImageMagick. My experience is that there are many features missing from GraphicsMagick which are present in ImageMagick and I list some of these below, in no particular order.
I freely admit I am not as familiar with GraphicsMagick as I am with ImageMagick, but I made my very best effort to find any mention of the features in the most recent GraphicsMagick source code. So, for Canny Edge Detector, I ran the following command on the GM source code:
```
find . -type f -exec grep -i Canny {} \;
```
and found nothing.
---
# Canny Edge detector
This appears to be completely missing in GM. See `-canny radiusxsigma{+lower-percent}{+upper-percent}` in IM.
See example [here](https://imagemagick.org/discourse-server/viewtopic.php?f=4&t=25405) and sample of edge-detection on Lena image:
[](https://i.stack.imgur.com/5tzzs.gif)
---
# Parenthesised processing, sophisticated re-sequencing
This is a killer feature of ImageMagick that I frequently sorely miss when having to use GM. IM can load, or create, or clone a whole series of images and apply different processing selectively to specific images and re-sequence, duplicate and re-order them very simply and conveniently. It is hard to convey the incredible flexibility this affords you in a short answer.
Imagine you want to do something fairly simple like load image A and blur it, load image B and make it greyscale and then place the images side-by-side with Image B on the left. That looks like this with ImageMagick:
```
magick imageA.png -blur x3 \( imageB.png -colorspace gray \) +swap +append result.png
```
[](https://i.stack.imgur.com/Rs6Sl.png)
You can't even get started with GM, it will complain about the parentheses. If you remove them, it will complain about swapping the image order. If you remove that it will apply the greyscale conversion to both images because it doesn't understand parentheses and place imageA on the left.
See the following sequencing commands in IM:
* `-swap`
* `-clone`
* `-duplicate`
* `-delete`
* `-insert`
* `-reverse`
---
# fx DIY Image Processing Operator
IM has the `-fx` operator which allows you to create and experiment with incredibly sophisticated image processing. You can have function evaluated for every single pixel in an image. The function can be as complicated as you like (save it in a file if you want to) and use all mathematical operations, ternary-style `if` statements, references to pixels even in other images and their brightness or saturation and so on.
Here are a couple of examples:
```
magick rose: -channel G -fx 'sin(pi*i/w)' -separate fx_sine_gradient.gif
```
[](https://i.stack.imgur.com/HhVxM.gif)
```
magick -size 80x80 xc: -channel G -fx 'sin((i-w/2)*(j-h/2)/w)/2+.5' -separate fx_2d_gradient.gif
```
[](https://i.stack.imgur.com/hWlUy.gif)
A StackOverflow answer that uses this feature to great effect in processing green-screen (chroma-keyed) images is [here](https://stackoverflow.com/a/25146019/2836621).
---
# Fourier (frequency domain) Analysis
There appears to be no mention of forward or reverse Fourier Analysis in GM, nor the High Dynamic Range support (see later) that is typically required to support it. See `-fft` in IM.
---
# Connected Component Analysis / Labelling/ Blob Analysis
There appears to be no *"Connected Component Analysis"* in GM - also known as *"labelling"* and *"Blob Analysis"*. See `-connected-components connectivity` for 4- and 8-connected blob analysis.
This feature alone has provided 60+ answers - see [here](https://stackoverflow.com/search?q=user%3A2836621%20connected).
---
# Hough Line Detection
There appears to be no Hough Line Detection in GM. See `-hough-lines widthxheight{+threshold}` in IM.
See description of the feature [here](https://imagemagick.org/discourse-server/viewtopic.php?f=4&t=25476) and following example of detected lines:
[](https://i.stack.imgur.com/U1Qhv.png)
---
# Moments and Perceptual Hash (pHash)
There appears to be no support for image moments calculation (centroids and higher orders), nor Perceptual Hashing in GM. See `-moments` in IM.
---
# Morphology
There appears to be no support for Morphological processing in GM. In IM there is sophisticated support for:
* dilation
* erosion
* morphological opening and closing
* skeletonisation
* distance morphology
* top hat and bottom hat morphology
* Hit and Miss morphology - line ends, line junctions, peaks, ridges, Convex Hulls etc
See all the sophisticated processing you can do with [this great tutorial](https://www.imagemagick.org/Usage/morphology/).
---
# Contrast Limited Adaptive Histogram Equalisation - CLAHE
There appears to be no support for Contrast Limited Adaptive Histogram Equalisation in GM. See `-clahe widthxheight{%}{+}number-bins{+}clip-limit{!}` in IM.
---
# HDRI - High Dynamic Range Imaging
There appears to be no support for High Dynamic Range Imaging in GM - just 8, 16, and 32-bit integer types.
---
# Convolution
ImageMagick supports many types of convolution:
* Difference of Gaussians DoG
* Laplacian
* Sobel
* Compass
* Prewitt
* Roberts
* Frei-Chen
None of these are mentioned in the GM source code.
---
# Magick Persistent Register (MPR)
This is an invaluable feature present in ImageMagick that allows you to write intermediate processing results to named chunks of memory during processing without the overhead of writing to disk. For example, you can prepare a texture or pattern and then tile it over an image, or prepare a mask and then alter it and apply it later in the same processing without going to disk.
Here's an example:
```
magick tree.gif -flip -write mpr:tree +delete -size 64x64 tile:mpr:tree mpr_tile.gif
```
[](https://i.stack.imgur.com/EUR9j.gif)
---
# Broader Colourspace Support
IM supports the following colourspaces not found in GM:
* CIELab
* HCL
* HSI
* LMS
* others.
---
# Pango Support
IM supports Pango Text Markup Language which is similar to HTML and allows you to annotate images with text that changes:
* font, colour, size, weight, italics
* subscript, superscript, strike-through
* justification
mid-sentence and much, much more. There is a great example [here](https://www.imagemagick.org/Usage/text/#pango).
[](https://i.stack.imgur.com/AkMuq.png)
---
# Shrink-on-load with JPEG
This invaluable feature allows the library to shrink JPEG images as they are read from disk, so that only the necessary coefficients are read, so the I/O is lessened, and the memory consumption is minimised. It can massively improve performance when down-scaling images.
See example [here](https://stackoverflow.com/a/32169224/2836621).
---
# Defined maximum JPEG size when writing
IM supports the much-requested option to specify a maximum filesize when writing JPEG files, `-define jpeg:extent=400KB` for example.
---
# Polar coordinate transforms
IM supports conversion between cartesian and polar coordinates, see `-distort polar` and `-distort depolar`.
---
# Statistics and operations on customisable areas
With its `-statistic MxN` operator, ImageMagick can generate many useful kinds of statistics and effects. For example, you can set each pixel in an image to the gradient (difference between brightest and darkest) of its 5x3 neighbourhood:
```
magick image.png -statistic gradient 5x3 result.png
```
Or you can set each pixel to the median of its 1x200 neighbourhood:
```
magick image.png -statistic median 1x200 result.png
```
See example of application [here](https://stackoverflow.com/a/42136544/2836621).
[](https://i.stack.imgur.com/kRGDr.png)
---
# Sequences of images
ImageMagick supports sequences of images, so if you have a set of very noisy images shot at high ISO, you can load up the entire sequence of images and, for example, take the median or average of all images to reduce noise. See the `-evaluate-sequence` operator. I do not mean the median in a surrounding neighbourhood in a single image, I mean by finding the median of all images at each pixel position.
---
The above is not an exhaustive list by any means, they are just the first few things that came to mind when I thought about the differences. I didn't even mention support for HEIC (Apple's format for iPhone images), increasingly common High Dynamic Range formats such as EXR, or any others. In fact, if you compare the file formats supported by the two products (`gm convert -list format` and `magick identify -list format`) you will find that IM supports 261 formats and GM supports 192.
As I said, different people have different opinions. Choose the one that you like and enjoy using it.
As always, I am indebted to Anthony Thyssen for his excellent insights and discourse on ImageMagick at <https://www.imagemagick.org/Usage/> Thanks also to Fred Weinhaus for his examples. | What is the difference between ImageMagick and GraphicsMagick? | [
"",
"c++",
"image",
"imagemagick",
"comparison",
"graphicsmagick",
""
] |
Does hibernate provide a method that returns an object's state (transient, persistent, detached)? | see [Javadoc Hibernate Session](https://www.hibernate.org/hib_docs/v3/api/org/hibernate/Session.html) and check the methods
* contains - Check if this instance is associated with this Session.
* getIdentifier - Return the identifier value of the given entity as associated with this session. Beware of the Exception that is thrown if the Entity is not associated, each Exception should be considered fatal and the Session should not be used after it
* get - Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance.
i would use 'get' and furthermore check for changed values, after that its just an "saveOrUpdate" to persist or update (and re-attach) the actual object | [Session.contains](https://www.hibernate.org/hib_docs/v3/api/org/hibernate/Session.html#contains(java.lang.Object)) tells you if an object is associated with the session. If it has no identifier, it's transient, if it has an identifier and associated with the session, persistent. Identifier but not associated with a session, detached.
If that doesn't help, consider rephrasing your question with more context, that is, why do you need to know the state of an object in the first place? | Obtaining an object state | [
"",
"java",
"hibernate",
""
] |
Let's say we have a class `foo` which has a private instance variable `bar`.
Now let us have another class, `baz`, which `extends foo`. Can non-static methods in `baz` access `foo`'s variable `bar` if there is no accessor method defined in `foo`?
I'm working in Java, by the way. | No, not according to the [java language specification, 3rd edition](http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.6.8):
> **6.6.8 Example: private Fields, Methods, and Constructors**
>
> A private
> class member or constructor is
> accessible only within the body of the
> top level class (§7.6) that encloses
> the declaration of the member or
> constructor. It is not inherited by
> subclasses.
But regardless of this language restriction, you *can* [access private fields through reflection](http://tutorials.jenkov.com/java-reflection/private-fields-and-methods.html):
```
Field privateStringField =
MyClass.class.getDeclaredField("privateString");
privateStringField.setAccessible(true);
String fieldValue = (String) privateStringField.get(privateObject);
System.out.println("fieldValue = " + fieldValue);
``` | No, for that you should use `protected.` | Accessing private instance variables of parent from child class? | [
"",
"java",
"oop",
"class",
"inheritance",
"polymorphism",
""
] |
I have a series of urls in a web doc, something like this:
```
<a href="somepage.php?x=some_document.htm">click here</a>
```
What I want to do is replace the bold piece:
<a href="somepage.php?x=**some\_document.htm**">click here</a>
.. with some sort of encrypted variation (lets just say base64\_encoding) .. something like this:
**for each match, turn it into base64\_encode(match)**
**Notes:**
1.the phrase **href="somepage.php?x=** will always precede the phrase.
2.a double-quote (**"**) will always follow the phrase.
I am not a regex guru -- but I know some of you are. Any easy way to do this?
**UPDATE:**
I solved this by using a modified version of what Chris submitted, here it is:
```
function encrypt_param( $in_matches ) {
return 'href="somepage.php?x=' . base64_encode( $in_matches[1] ) . '"';
}
$webdoc = preg_replace_callback( '/href="somepage.php\?x=([^"]+)"/',
'encrypt_param',
$webdoc );
``` | I think you are looking for something like this:
```
function doSomething($matches) {
return base64_encode($matches[1]);
}
preg_replace_callback('/href="somepage.php?x=([^"]+)"/', 'doSomething', $webdoc);
```
The `preg_replace` answer works similarly. If you want to do something more elaborate, the callback would allow you do to that | I would consider using the PHP [DOM](https://www.php.net/dom) parser. Anything less is a hack. (Not that hacks are always bad, just know the difference between a simple regex and a DOM parser.) `getElementsByTagName()` will get your <a> tags, `getAttribute()` will get your href attributes, and `setAttribute()` modifies. | PHP Regex Question | [
"",
"php",
"regex",
""
] |
Let's assume this class in C#:
```
public class LimitedList<T> : List<T>
{
private int _maxitems = 500;
public void Add(T value) /* Adding a new Value to the buffer */
{
base.Add(value);
TrimData(); /* Delete old data if lenght too long */
}
private void TrimData()
{
int num = Math.Max(0, base.Count - _maxitems);
base.RemoveRange(0, num);
}
}
```
The compiler gives me this warning in the line "public void Add(T value)":
> warning CS0108: 'System.LimitedList.Add(T)' hides inherited member 'System.Collections.Generic.List.Add(T)'. Use the new keyword if hiding was intended.
What do I have to do to avoid this warning?
Thx 4 your help | No - **don't** use `new` here; that doesn't give you polymorphism. `List<T>` isn't intended for inheritance in this way; use `Collection<T>` and `override` the ~~`Add`~~ `InsertItem` method.
```
public class LimitedCollection<T> : Collection<T>
{
private int _maxitems = 500;
protected override void InsertItem(int index, T item)
{
base.InsertItem(index, item);
TrimData(); /* Delete old data if lenght too long */
}
private void TrimData()
{
int num = Math.Max(0, base.Count - _maxitems);
while (num > 0)
{
base.RemoveAt(0);
num--;
}
}
}
``` | You can avoid this warning by adding "new" to the declaration.
```
public new void Add(T value) {
...
}
```
However I think you may be approaching this problem a bit wrong by using Inheritance. From my perspective LimitedList is not a List because it expresses very different behavior as it puts a hard constraint on the amount of data in the List. I think it would be much better to not inherit from List but have a List as a member variable.
Another reason why this is a bad idea is that you won't be able to satisfy your class's contract when it is viewed as a List. The following code will use the List`s Add method and not LimitedList.
```
List<int> list = new LimitedList<int>(10);
for ( i = 0; i < 10000; i++ ) {
list.Add(i);
}
``` | C#: Inheritance Problem with List<T> | [
"",
"c#",
".net",
"inheritance",
"list",
""
] |
How do I automate the process of getting an instance created and its function executed dynamically?
Thanks
Edit: Need an option to pass parameters too. Thanks | Do you just want to call a parameterless constructor to create the instance? Is the type specified as a string as well, or can you make it a generic method? For example:
```
// All error checking omitted. In particular, check the results
// of Type.GetType, and make sure you call it with a fully qualified
// type name, including the assembly if it's not in mscorlib or
// the current assembly. The method has to be a public instance
// method with no parameters. (Use BindingFlags with GetMethod
// to change this.)
public void Invoke(string typeName, string methodName)
{
Type type = Type.GetType(typeName);
object instance = Activator.CreateInstance(type);
MethodInfo method = type.GetMethod(methodName);
method.Invoke(instance, null);
}
```
or
```
public void Invoke<T>(string methodName) where T : new()
{
T instance = new T();
MethodInfo method = typeof(T).GetMethod(methodName);
method.Invoke(instance, null);
}
``` | To invoke a constructor, [Activator.CreateInstance](http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx) will do the trick. It has a bunch of overloads to make your life easier.
If your constructor is [parameterless](http://msdn.microsoft.com/en-us/library/wccyzw83.aspx):
```
object instance = Activator.CreateInstance(type)
```
If you need [parameters](http://msdn.microsoft.com/en-us/library/wcxyzt4d.aspx):
```
object instance = Activator.CreateInstance(type, param1, param2)
```
To invoke, a method, once you have the [Type](http://msdn.microsoft.com/en-us/library/system.type.aspx) object you can call [`GetMethod`](http://msdn.microsoft.com/en-us/library/system.type.getmethod.aspx) to get the [method](http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.aspx), and then [`Invoke`](http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.invoke.aspx) (with or without parameters) to invoke it. Should you need it, Invoke will also give you the return value of the function you're calling (or null if its a void method),
For a slightly more detailed sample (paste into a console app and go):
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
namespace Test
{
public static class Invoker
{
public static object CreateAndInvoke(string typeName, object[] constructorArgs, string methodName, object[] methodArgs)
{
Type type = Type.GetType(typeName);
object instance = Activator.CreateInstance(type, constructorArgs);
MethodInfo method = type.GetMethod(methodName);
return method.Invoke(instance, methodArgs);
}
}
class Program
{
static void Main(string[] args)
{
// Default constructor, void method
Invoker.CreateAndInvoke("Test.Tester", null, "TestMethod", null);
// Constructor that takes a parameter
Invoker.CreateAndInvoke("Test.Tester", new[] { "constructorParam" }, "TestMethodUsingValueFromConstructorAndArgs", new object[] { "moo", false });
// Constructor that takes a parameter, invokes a method with a return value
string result = (string)Invoker.CreateAndInvoke("Test.Tester", new object[] { "constructorValue" }, "GetContstructorValue", null);
Console.WriteLine("Expect [constructorValue], got:" + result);
Console.ReadKey(true);
}
}
public class Tester
{
public string _testField;
public Tester()
{
}
public Tester(string arg)
{
_testField = arg;
}
public void TestMethod()
{
Console.WriteLine("Called TestMethod");
}
public void TestMethodWithArg(string arg)
{
Console.WriteLine("Called TestMethodWithArg: " + arg);
}
public void TestMethodUsingValueFromConstructorAndArgs(string arg, bool arg2)
{
Console.WriteLine("Called TestMethodUsingValueFromConstructorAndArg " + arg + " " + arg2 + " " + _testField);
}
public string GetContstructorValue()
{
return _testField;
}
}
}
``` | Dynamically invoking any function by passing function name as string | [
"",
"c#",
"reflection",
"function",
"instance",
""
] |
C# 2008
I am using this code to test for an internet connection. As my application will have to login to a web server. However, if the user internet connection was to fail or cable pulled out. I will have to notify the user.
```
// Ping www.google.com to check if the user has a internet connection.
public bool PingTest()
{
Ping ping = new Ping();
PingReply pingStatus = ping.Send(IPAddress.Parse("208.69.34.231"));
if (pingStatus.Status == IPStatus.Success)
{
return true;
}
else
{
return false;
}
}
```
The only way I think I can test for an Internet connection is to ping www.google.com. So I have a used a server timer which I have set for 500 milliseconds and in the lapsed event it will call this ping function. If the ping returns false. Then my app will take appropriate action.
Do you think using google as a way to test an Internet connect is a good thing. If google was to fail, then my app would not function. Is polling 1/2 second to much or too little? Just wondering about my whole idea if it is good or not?
Many thanks, | Why ping Google? The only server you really care about is the web server you want to talk to, right? So ping that instead. That way, you can notify the user if anything is wrong between them and the web server - that's the only thing that matters.
If something goes wrong with the internet which means that the user can only do anything within their own town, you may not be able to reach Google but if you can still reach the web server you're interested in, why report a problem? On the other hand, if the web server goes down but Google doesn't, why would you *not* want to tell the user that there's a problem?
Likewise, why use a ping? Why not send an HTTP request to a known URL on the web server? After all, if the network is up but the web server process itself is down, surely that's just as bad as the user's network going down.
EDIT: I hadn't noticed in the question that you were repeating this every half second. That's really not pleasant for anyone. Surely once a minute is often enough, isn't it? | Check out this duplicate question which has a good answer that doesn't require ping:
[C# - How do I check for a network connection](https://stackoverflow.com/questions/520347/c-how-do-i-check-for-a-network-connection)
You could subscribe to the System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged event and only then when it indicates that the network is down do a ping/web request to the server to see if it's available. | C# Testing active internet connection. Pinging google.com | [
"",
"c#",
"networking",
""
] |
Is there another way to do this Query ?
```
$query = "SELECT * FROM produto, pt WHERE
produto.refPT = pt.ref AND
produto.refPT IN (SELECT idProduto FROM amb_prod WHERE idAmbiente='1');";
$result_set = mysql_query($query);
```
The problem is my localhost have the MySQL version 5.1.30-community, but my Online server have the 5.0.67-community MySQL version.
And I think is that the reason why I get this error only when I try to run on the online server:
```
mysql_fetch_array(): supplied argument is not a valid MySQL result resource
``` | It makes live easier when you create a nice view of your Query, like:
```
$query = "SELECT *
FROM produto, pt, amb_prod
WHERE produto.refPT = pt.ref
AND produto.refPT = amb_prod.idProduto
WHERE amb_prod.idAmbiente='1';";
$result_set = mysql_query($query);
``` | well, it would make a lot of sense to install a matching version of MySQL on your test systems, so you can debug the error more easily.
You could also try something like this...
```
$query = "SELECT * FROM produto, pt, amb_prod WHERE
produto.refPT = pt.ref AND
produto.refPT = amb_prod.idProduto WHERE amb_prod.idAmbiente='1');";
$result_set = mysql_query($query);
``` | MySQL double query situation | [
"",
"sql",
"mysql",
""
] |
For some reason it looks like constructor delegation doesn't work in the following snippet:
```
function NotImplementedError() {
Error.apply(this, arguments);
}
NotImplementedError.prototype = new Error();
var nie = new NotImplementedError("some message");
console.log("The message is: '"+nie.message+"'")
```
Running this gives `The message is: ''`. Any ideas as to why, or if there is a better way to create a new `Error` subclass? Is there a problem with `apply`ing to the native `Error` constructor that I don't know about? | Update your code to assign your prototype to the Error.prototype and the instanceof and your asserts work.
```
function NotImplementedError(message = "") {
this.name = "NotImplementedError";
this.message = message;
}
NotImplementedError.prototype = Error.prototype;
```
However, I would just throw your own object and just check the name property.
```
throw {name : "NotImplementedError", message : "too lazy to implement"};
```
**Edit based on comments**
After looking at the comments and trying to remember why I would assign prototype to `Error.prototype` instead of `new Error()` like Nicholas Zakas did in his [article](https://www.nczonline.net/blog/2009/03/10/the-art-of-throwing-javascript-errors-part-2/), I created a [jsFiddle](http://jsfiddle.net/MwMEJ/) with the code below:
```
function NotImplementedError(message = "") {
this.name = "NotImplementedError";
this.message = message;
}
NotImplementedError.prototype = Error.prototype;
function NotImplementedError2(message = "") {
this.message = message;
}
NotImplementedError2.prototype = new Error();
try {
var e = new NotImplementedError("NotImplementedError message");
throw e;
} catch (ex1) {
console.log(ex1.stack);
console.log("ex1 instanceof NotImplementedError = " + (ex1 instanceof NotImplementedError));
console.log("ex1 instanceof Error = " + (ex1 instanceof Error));
console.log("ex1.name = " + ex1.name);
console.log("ex1.message = " + ex1.message);
}
try {
var e = new NotImplementedError2("NotImplementedError2 message");
throw e;
} catch (ex1) {
console.log(ex1.stack);
console.log("ex1 instanceof NotImplementedError2 = " + (ex1 instanceof NotImplementedError2));
console.log("ex1 instanceof Error = " + (ex1 instanceof Error));
console.log("ex1.name = " + ex1.name);
console.log("ex1.message = " + ex1.message);
}
```
The console output was this.
```
undefined
ex1 instanceof NotImplementedError = true
ex1 instanceof Error = true
ex1.name = NotImplementedError
ex1.message = NotImplementedError message
Error
at window.onload (http://fiddle.jshell.net/MwMEJ/show/:29:34)
ex1 instanceof NotImplementedError2 = true
ex1 instanceof Error = true
ex1.name = Error
ex1.message = NotImplementedError2 message
```
This confirmes the "problem" I ran into was the stack property of the error was the line number where `new Error()` was created, and not where the `throw e` occurred. However, that may be better that having the side effect of a `NotImplementedError.prototype.name = "NotImplementedError"` line affecting the Error object.
Also, notice with `NotImplementedError2`, when I don't set the `.name` explicitly, it is equal to "Error". However, as mentioned in the comments, because that version sets prototype to `new Error()`, I could set `NotImplementedError2.prototype.name = "NotImplementedError2"` and be OK. | In ES2015, you can use `class` to do this cleanly:
```
class NotImplemented extends Error {
constructor(message = "", ...args) {
super(message, ...args);
this.message = message + " has not yet been implemented.";
}
}
```
This does not modify the global `Error` prototype, allows you to customize `message`, `name`, and other attributes, and properly captures the stack. It's also pretty readable.
Of course, you may need to use a tool like `babel` if your code will be running on older browsers. | How do I create a custom Error in JavaScript? | [
"",
"javascript",
"exception",
""
] |
I have a Java program that runs many small simulations. It runs a genetic algorithm, where each fitness function is a simulation using parameters on each chromosome. Each one takes maybe 10 or so seconds if run by itself, and I want to run a pretty big population size (say 100?). I can't start the next round of simulations until the previous one has finished. I have access to a machine with a whack of processors in it and I'm wondering if I need to do anything to make the simulations run in parallel. I've never written anything explicitly for multicore processors before and I understand it's a daunting task.
So this is what I would like to know: To what extent and how well does the JVM parallel-ize? I have read that it creates low level threads, but how smart is it? How efficient is it? Would my program run faster if I made each simulation a thread? I know this is a huge topic, but could you point me towards some introductory literature concerning parallel processing and Java?
Thanks very much!
**Update:**
Ok, I've implemented an ExecutorService and made my small simulations implement Runnable and have run() methods. Instead of writing this:
```
Simulator sim = new Simulator(args);
sim.play();
return sim.getResults();
```
I write this in my constructor:
```
ExecutorService executor = Executors.newFixedThreadPool(32);
```
And then each time I want to add a new simulation to the pool, I run this:
```
RunnableSimulator rsim = new RunnableSimulator(args);
exectuor.exectue(rsim);
return rsim.getResults();
```
The `RunnableSimulator::run()` method calls the `Simulator::play()` method, neither have arguments.
I think I am getting thread interference, because now the simulations error out. By error out I mean that variables hold values that they really shouldn't. No code from within the simulation was changed, and before the simulation ran perfectly over many many different arguments. The sim works like this: each turn it's given a game-piece and loops through all the location on the game board. It checks to see if the location given is valid, and if so, commits the piece, and measures that board's goodness. Now, obviously invalid locations are being passed to the commit method, resulting in index out of bounds errors all over the place.
Each simulation is its own object right? Based on the code above? I can pass the exact same set of arguments to the `RunnableSimulator` and `Simulator` classes and the runnable version will throw exceptions. What do you think might cause this and what can I do to prevent it? Can I provide some code samples in a new question to help? | [Java Concurrency Tutorial](http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html)
If you're just spawning a bunch of stuff off to different threads, and it isn't going to be talking back and forth between different threads, it isn't too hard; just write each in a [Runnable](http://java.sun.com/javase/6/docs/api/java/lang/Runnable.html) and pass them off to an [ExecutorService](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html).
You should skim the whole tutorial, but for this particular task, [start here](http://java.sun.com/docs/books/tutorial/essential/concurrency/executors.html).
Basically, you do something like this:
```
ExecutorService executorService = Executors.newFixedThreadPool(n);
```
where n is the number of things you want running at once (usually the number of CPUs). Each of your tasks should be an object that implements Runnable, and you then execute it on your ExecutorService:
```
executorService.execute(new SimulationTask(parameters...));
```
`Executors.newFixedThreadPool(n)` will start up `n` threads, and execute will insert the tasks into a queue that feeds to those threads. When a task finishes, the thread it was running on is no longer busy, and the next task in the queue will start running on it. Execute won't block; it will just put the task into the queue and move on to the next one.
The thing to be careful of is that you really AREN'T sharing any mutable state between tasks. Your task classes shouldn't depend on anything mutable that will be shared among them (i.e. static data). There are ways to deal with shared mutable state (locking), but if you can avoid the problem entirely it will be a lot easier.
EDIT: Reading your edits to your question, it looks like you really want something a little different. Instead of implementing `Runnable`, implement [`Callable`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/Callable.html). Your `call()` method should be pretty much the same as your current `run()`, except it should `return getResults();`. Then, `submit()` it to your `ExecutorService`. You will get a [`Future`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/Future.html) in return, which you can use to test if the simulation is done, and, when it is, get your results. | You can also see the [new fork join framework](http://gee.cs.oswego.edu/dl/concurrency-interest/index.html) by [Doug Lea](http://gee.cs.oswego.edu/). One of the best book on the subject is certainly [Java Concurrency in Practice](https://rads.stackoverflow.com/amzn/click/com/0321349601). I would strong recommend you to take a look at the fork join model. | How good is the JVM at parallel processing? When should I create my own Threads and Runnables? Why might threads interfere? | [
"",
"java",
"multithreading",
"multicore",
""
] |
Using Visual Studio 2008, I created a C++ [Win32](http://en.wikipedia.org/wiki/Windows_API) project. To release the program, I made a Visual Studio setup project within the same solution.
The setup.exe prompts my users to install .NET 3.5 SP1, which is often a 15+ minute install and only allowed to administrator level accounts. If they do not there is an error along the lines of "wrong framework". I am confused over what in my project requires .NET 3.5 SP1. I suspect just because that is the framework my PC is on... Is there a way to broaden which frameworks it will run on?
The code is mostly Win32 API calls. Just in case, here are my dependencies and #includes:
```
gdiplus.lib
comctl32.lib
Winmm.lib
d3d9.lib
```
(The setup project automatically added comdlg32.dll, then tells me to exclude it.)
```
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string.h>
#include <commctrl.h>
#include <process.h>
#include <sstream>
#include <math.h>
#include <d3d9.h>
#include <time.h>
#include <gdiplus.h>
```
My guess is that somewhere through windows.h there is a WIN\_VER or similar version setting that is set to .NET 3.5 SP1, and this is where the dependency comes from. If that is the case, and I need to define a different version, I would love to hear everyone's advice on does / don'ts / and how-to and how far back can I go for maximum inclusion. | In VS 2008 the default target framework is .NET 3.5.
For C++ on the Common Properties page there's a "Targeted Framework" drop down, but on the test project I created it's greyed out, so it looks like this can't be changed after the project has been created.
I created a second C++ project and selected the 2.0 Template from the New Project dialog and that had 2.0 in the "Targeted Framework".
So if you want to target a lower version of the framework it looks like you've got to create your project correctly in the first place.
EDIT: As to which version of the framework you should target - it all depends(!)
Do you need to use any of the 3.0 or 3.5 features? If not then go for 2.0. If you do then select that one and take the hit of the download. I can't say how likely it is that any class of user will have a particular version installed. As time goes on it will be increasingly likely that they will have 3.5 installed as other apps will require it. | Have you checked the prerequisites on the installer project? (Right click -> *Properties*; Prerequesites button).
On the test project I created, the .NET framework is selected by default (I assume it doesn't actually analyse the projects being installed, as it doesn't include the C++ runtime libraries by default, either.) | Why does my Visual Studio Win32 project require .NET 3.5 SP1 to install? | [
"",
"c++",
"visual-studio",
"winapi",
"installation",
""
] |
Assuming the webserver is configured to handle ***.exe***, Can i compile a python CGI file into an exe for speed. What would some pros and cons be to such a desession? | There is [py2exe](http://www.py2exe.org/) ([and a tutorial on how to use it](http://www.ehow.com/how_2091641_compile-python-code.html)), but there is no guarentee that it will make your script any faster. Really its more of an executable interpreter that wraps the bytecode. There are other exe compilers that do varying degrees of things to the python code, so you might want to do a general Google search.
However, you can always use [psyco](http://psyco.sourceforge.net/doc.html) to boost speed of many of the most intensive operations that a python script can perform, namely looping. | You probably don't want to run Python as a CGI if you want it fast. Look at proxies, mod\_python, WSGI or FastCGI, as those techinques avoid re-loading python runtime and your app on each request. | Compiled Python CGI | [
"",
"python",
""
] |
How do I get the absolute x,y coordinates for an HTML element on a page that may exist within a iFrame. The page is sometimes called on its own and sometimes is called from within an iFrame.
This is the function that I wrote to figure out the x,y position based on the offsetLeft and offsetTop of the element and the offseParent.
```
function getXY(obj)
{
var curObj = obj;
var curLeft = curTop = 0;
curLeft += curObj.offsetLeft
curTop += curObj.offsetTop;
while (curObj.offsetParent != null)
{
curObj = curObj.offsetParent;
curLeft += curObj.offsetLeft
curTop += curObj.offsetTop;
}
obj.x = curLeft;
obj.y = curTop;
}
```
This works great if the page is the top, but the problem is that if the page is run from within an iFrame I do not know the offset of the iFrame on the page.
Is there a way to get the exact, absolutes coordinates regardless of whether the page is in an iFrame or not?
Thank you. | well, I would suggest the jquery dimensions suggested if that works for you. For getting to the parent iframe, you will need to lookup against window.parent. You could then get your offset recursively through parents.
```
if (window.parent && window.parent.frames && window.parent.document && window.parent.document.getElementsByTagName) {
var iframes = window.parent.document.getElementsByTagName("IFRAME");
for (var i = 0; i < iframes.length; i++) {
var id = iframes[i].id || iframes[i].name || i;
if (window.parent.frames[id] == window) {
//iframes[i] is your iframe in your parent.
}
}
}
```
I'm using this technique for identifying the frame in my [FrameDialog](http://plugins.jquery.com/project/jquery-framedialog) plugin for jQueryUI. | I use [JQuery Dimensions](http://plugins.jquery.com/project/dimensions) to do this. It does a good job of walking up the DOM and adding up all the offsets for you. | Exact coordinate of html element within an iFrame | [
"",
"javascript",
"html",
""
] |
I am attempting to be cheap and execute a local system command (`uname -a`) in Java. I am looking to grab the output from `uname` and store it in a String. What is the best way of doing this? Current code:
```
public class lame {
public static void main(String args[]) {
try {
Process p = Runtime.getRuntime().exec("uname -a");
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
}
catch(IOException e1) {}
catch(InterruptedException e2) {}
System.out.println("finished.");
}
}
``` | Your way isn't far off from what I'd probably do:
```
Runtime r = Runtime.getRuntime();
Process p = r.exec("uname -a");
p.waitFor();
BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = b.readLine()) != null) {
System.out.println(line);
}
b.close();
```
Handle whichever exceptions you care to, of course. | That is the best way to do it.
Also you can use the [ProcessBuilder](http://java.sun.com/javase/6/docs/api/java/lang/ProcessBuilder.html) which has a variable argument constructor, so you could save a line or two of code | How to execute system commands (linux/bsd) using Java | [
"",
"java",
"output-redirect",
""
] |
I come from a C++ background and I've been working with C# for about a year. Like many others I'm flummoxed as to why deterministic resource management is not built-in to the language. Instead of deterministic destructors we have the dispose pattern. [People start to wonder](https://stackoverflow.com/questions/752344) whether spreading the IDisposable cancer through their code is worth the effort.
In my C++-biased brain it seems like using reference-counted smart pointers with deterministic destructors is a major step up from a garbage collector that requires you to implement IDisposable and call dispose to clean up your non-memory resources. Admittedly, I'm not very smart... so I'm asking this purely from a desire to better understand why things are the way they are.
What if C# were modified such that:
Objects are reference counted. When an object's reference count goes to zero, a resource cleanup method is called deterministically on the object, then the object is marked for garbage collection. Garbage collection occurs at some non-deterministic time in the future at which point memory is reclaimed. In this scenario you don't have to implement IDisposable or remember to call Dispose. You just implement the resource cleanup function if you have non-memory resources to release.
* Why is that a bad idea?
* Would that defeat the purpose of the garbage collector?
* Would it be feasible to implement such a thing?
EDIT:
From the comments so far, this is a bad idea because
1. GC is faster without reference counting
2. problem of dealing with cycles in the object graph
I think number one is valid, but number two is easy to deal with using weak references.
So does the speed optimization outweigh the cons that you:
1. may not free a non-memory resource in a timely manner
2. might free a non-memory resource too soon
If your resource cleanup mechanism is deterministic and built-in to the language you can eliminate those possibilities. | Brad Abrams posted [an e-mail from Brian Harry](https://learn.microsoft.com/en-gb/archive/blogs/brada/resource-management) written during development of the .Net framework. It details many of the reasons reference counting was not used, even when one of the early priorities was to keep semantic equivalence with VB6, which uses reference counting. It looks into possibilities such as having some types ref counted and not others (`IRefCounted`!), or having specific instances ref counted, and why none of these solutions were deemed acceptable.
> Because [the issue of resource
> management and deterministic
> finalization] is such a
> sensitive topic I am going to try to
> be as precise and complete in my
> explanation as I can. I apologize for
> the length of the mail. The first 90%
> of this mail is trying to convince you
> that the problem really is hard. In
> that last part, I'll talk about things
> we are trying to do but you need the
> first part to understand why we are
> looking at these options.
>
> ...
>
> We initially started with the
> assumption that **the solution would
> take the form of automatic ref
> counting** (so the programmer couldn't
> forget) plus some other stuff to
> detect and handle cycles
> automatically. ...we **ultimately concluded that
> this was not going to work in the
> general case.**
>
> ...
>
> In summary:
>
> * We feel that it is very important to **solve the cycle problem**
> without forcing programmers to
> understand, track down and design
> around these complex data structure
> problems.
> * We want to make sure we have a high performance (both speed and
> working set) system and our analysis
> shows that using **reference counting
> for every single object in the system
> will not allow us to achieve this
> goal**.
> * For a variety of reasons, including composition and casting
> issues, there is **no simple transparent
> solution to having just those objects
> that need it be ref counted**.
> * We chose not to select a solution that provides **deterministic
> finalization for a single
> language/context because it inhibits
> interop** with other languages and
> causes bifurcation of class libraries
> by creating language specific
> versions. | The garbage collector does not require you to write a Dispose method for **every** class/type that you define. You only define one when you need to explicitly do something to cleanup ; when you have explicitly allocated native resources. Most of the time, the GC just reclaims memory even if you only do something like new() up an object.
The GC does reference counting - however it does it in a different way by finding which objects are 'reachable' (`Ref Count > 0`) **every time it does a collection**... it just doesn't do it in a integer counter way. . Unreachable objects are collected (`Ref Count = 0`). This way the runtime doesn't have to do housekeeping/updating tables everytime an object is assigned or released... should be faster.
The only major difference between C++ (deterministic) and C# (non-deterministic) is when the object would be cleaned up. You can't predict the exact moment an object would be collected in C#.
*Umpteenth plug: I'd recommend reading Jeffrey Richter's standup chapter on the GC in [CLR via C#](https://rads.stackoverflow.com/amzn/click/com/0735621632) in case you're really interested in how the GC works.* | Why no Reference Counting + Garbage Collection in C#? | [
"",
"c#",
"garbage-collection",
"reference-counting",
""
] |
I need to support Chinese in one of my application on Windows, the problem is that I need to support for **Chinese Mandarin** and I did not find any locale code for it, can you clarify whether Windows support Mandarin chinese or is there any alternate?? | Since the question is tagged C# and .NET 3.5 I'm assuming the following .NET-specifics apply.
There's a hint on this page [zh-Hans, zh-Hant and the "old" zh-CHS, zh-CHT](http://blogs.msdn.com/shawnste/archive/2007/12/13/zh-hans-zh-hant-and-the-old-zh-chs-zh-cht.aspx)
> use the IETF standard "zh-Hans", and "zh-Hant" names for Chinese simplified and traditional ... in .Net 2.0/3.x we still recognize zh-CHS & zh-CHT for backwards compatibility ... **LCID (0x0004 or 0x7C04)**
And from [W3 I18N FAQ](http://www.w3.org/International/questions/qa-css-lang)
> "zh-Hant" and "zh-Hans". These language codes do not represent specific languages. "zh-Hant" would indicate Chinese written in Traditional Chinese *script*. Similarly "zh-Hans" represents Chinese written in Simplified Chinese *script*. This could refer to Mandarin or many other Chinese languages.
I guess the key point is that **Chinese Mandarin** that you mentioned is a spoken dialect (for want of a better term), and **Chinese (Simplified)** is the 'character set' that is used to represent that spoken language 'on paper'. LocaleId [0x0004](http://www.microsoft.com/resources/msdn/goglobal/default.mspx?submitted=0004&OS=Windows%20Vista) according to coobird's link.
Other **spoken** languages (**Cantonese**?) are represented by different 'character sets' like **Chinese (Traditional)**. If your application was going to Taiwan or Hong Kong you might use LocaleId [0x7C04](http://msdn.microsoft.com/en-us/goglobal/bb896001.aspx).
* NOTE: I'm not meaning 'character set' in the computerese/ASCII sense above ~ just distinguishing between the spoken and written representations. There's a whole other discussion on character sets/codepages/unicode (although generally .NET seems to cope with that stuff as long as your fonts are sorted out and you stick to UTF-8). | [Mandarin Chinese](http://en.wikipedia.org/wiki/Mandarin_Chinese) refers to a family of dialects of the spoken Chinese language.
Perhaps you're looking for [Simplified Chinese](http://en.wikipedia.org/wiki/Simplified_Chinese_characters), which is the written Chinese character set used in the [People's Republic of China](http://en.wikipedia.org/wiki/People%27s_Republic_of_China) and other countries?
**Edit** I was able to find the [Natural Language Support (NLS) API Reference](http://msdn.microsoft.com/en-us/goglobal/bb896001.aspx) from Microsoft, which provides the Culture Name used for internationalization, I believe. (I'm not sure how internationalization works in .NET.)
According to the table, there are seven Culture Names/Identifiers available for Chinese. (The Culture Names for Chinese starts with `zh`.)
Without more information about which specific Chinese language the internationalization should be targeted at, I think it's going to be a little bit difficult to narrow down. (Perhaps someone else has had some experience in this topic?) | Localization support for Chinese | [
"",
"c#",
"wpf",
"windows",
".net-3.5",
"localization",
""
] |
How would you normalize all new-line sequences in a string to one type?
I'm looking to make them all CRLF for the purpose of email (MIME documents). Ideally this would be wrapped in a static method, executing very quickly, and not using regular expressions (since the variances of line breaks, carriage returns, etc. are limited). Perhaps there's even a BCL method I've overlooked?
ASSUMPTION: After giving this a bit more thought, I think it's a safe assumption to say that CR's are either stand-alone or part of the CRLF sequence. That is, if you see CRLF then you know all CR's can be removed. Otherwise it's difficult to tell how many lines should come out of something like "\r\n\n\r". | ```
input.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", "\r\n")
```
This will work if the input contains only one type of line breaks - either CR, or LF, or CR+LF. | It depends on *exactly* what the requirements are. In particular, how do you want to handle "\r" on its own? Should that count as a line break or not? As an example, how should "a\n\rb" be treated? Is that one very odd line break, one "\n" break and then a rogue "\r", or two separate linebreaks? If "\r" and "\n" can both be linebreaks on their own, why should "\r\n" not be treated as two linebreaks?
Here's some code which I suspect is *reasonably* efficient.
```
using System;
using System.Text;
class LineBreaks
{
static void Main()
{
Test("a\nb");
Test("a\nb\r\nc");
Test("a\r\nb\r\nc");
Test("a\rb\nc");
Test("a\r");
Test("a\n");
Test("a\r\n");
}
static void Test(string input)
{
string normalized = NormalizeLineBreaks(input);
string debug = normalized.Replace("\r", "\\r")
.Replace("\n", "\\n");
Console.WriteLine(debug);
}
static string NormalizeLineBreaks(string input)
{
// Allow 10% as a rough guess of how much the string may grow.
// If we're wrong we'll either waste space or have extra copies -
// it will still work
StringBuilder builder = new StringBuilder((int) (input.Length * 1.1));
bool lastWasCR = false;
foreach (char c in input)
{
if (lastWasCR)
{
lastWasCR = false;
if (c == '\n')
{
continue; // Already written \r\n
}
}
switch (c)
{
case '\r':
builder.Append("\r\n");
lastWasCR = true;
break;
case '\n':
builder.Append("\r\n");
break;
default:
builder.Append(c);
break;
}
}
return builder.ToString();
}
}
``` | What is a quick way to force CRLF in C# / .NET? | [
"",
"c#",
".net",
"string",
"newline",
""
] |
My `CMDIFrameWndEx` derived main frame window uses a `CMFCRibbonStatusBar` to which I add a `CMFCRibbonLabel`.
I'd like to change the text of this label at runtime:
```
m_pLabel->SetText(description);
m_pLabel->Redraw();
```
It only updates the text but not the rectangle in which to draw it. So if the original text was too short, the new string won't be visible completely.
How do I get it to resize correctly? | Answering my own question again...
I worked around the issue by adding and removing the label instead of trying to change the text.
### Code for adding the label:
```
CMFCRibbonLabel* pLabel = new CMFCRibbonLabel(description);
pLabel->SetID(ID_MYLABEL); // ID is 0 by default
m_wndStatusBar.AddDynamicElement(pLabel);
m_wndStatusBar.RecalcLayout();
m_wndStatusBar.RedrawWindow();
```
Note that I'm setting an ID so I can later call `CMFCRibbonStatusBar::RemoveElement()` with that ID.
The calls to `RecalcLayout()` and `RedrawWindow()` are needed to make the changes visible.
### Code for removing the label:
```
if(m_wndStatusBar.RemoveElement(ID_MYLABEL))
{
m_wndStatusBar.RecalcLayout();
m_wndStatusBar.RedrawWindow();
}
``` | You don't need to remove and re-add. Just call this:
```
m_wndStatusBar.ForceRecalcLayout();
``` | How do I dynamically change the text of a CMFCRibbonLabel | [
"",
"c++",
"label",
"ribbon",
"statusbar",
"mfc-feature-pack",
""
] |
This is similar to (but different from) [this question](https://stackoverflow.com/questions/117293/use-of-const-for-function-parameters "tangent from this question").
Here is some simple test code to illustrate some weirdness I have discovered with Sun CC:
```
//---------------main.cpp
#include "wtc.hpp"
int main(int, char**)
{
testy t;
t.lame(99);
return 0;
}
//--------------wtc.hpp
#ifndef WTC_HPP_INCLUDED
#define WTC_HPP_INCLUDED
class testy
{
public:
void lame(int );
};
#endif
//---------------wtc.cpp
#include <iostream>
#include "wtc.hpp"
void testy::lame(const int a)
{
std::cout << "I was passed " << a << "\n";
}
//---------------makefile
#CXX=CC
CXX =g++
#CXXFLAGS= -g
CXXFLAGS= -g3 -Wall -Werror
OBJECTS=$(patsubst %.cpp,%.o,$(wildcard *.cpp))
all : $(OBJECTS)
$(CXX) $(CXXFLAGS) -o $@ $^
.PHONY: clean
clean :
rm *.o
```
When this was compiled using g++ it compiles, links and does what you would expect when run.
You can also add a ++a; in testy::lame() and the compiler will complain about changing a read-only variable (as it should).
However when I compile using CC, I get the following linker error:
```
CC -g -c -o main.o main.cpp
CC -g -c -o wtc.o wtc.cpp
CC -g -o all main.o wtc.o
Undefined first referenced
symbol in file
void testy::lame(int) main.o
ld: fatal: Symbol referencing errors. No output written to all
make: *** [all] Error 1
```
checking the object code with nm and C++filt, I find that the g++ version creates a
testy::lame(int) symbol, whereas CC creates testy::lame(const int) , hence the linker error.
I looked it up in Stroustrup's book, but can't find this technique mentioned (doesn't mean it's not there!); so is this really a compiler bug, or just a hack that works everywhere else but Solaris? | This looks like a compiler problem in `CC`. The C++ standard says (in 13.1 Overloadable declarations):
> Parameter declarations that differ only in the presence or absence of const and/or volatile are equivalent. That is, the const and volatile type-specifiers for each parameter type are ignored when determining which function is being declared, defined, or called.
But there are `const`/`volatile` modifiers that can participate in overloading, as the standard mentions shortly afterwards:
> Only the const and volatile type-specifiers at the outermost level of the parameter type specification are ignored in this fashion; const and volatile type-specifiers buried within a parameter type specification are significant and can be used to distinguish overloaded function declarations. | The 'const' in the 'const int' parameter should be ignored by the compiler. However, the difference between the declaration and the definition is bad style, to say the least. | Is the const value parameter in definition but not declaration really C++? | [
"",
"c++",
"solaris",
"language-features",
""
] |
I know this sounds like a homework assignment, but it isn't. Lately I've been interested in algorithms used to perform certain mathematical operations, such as sine, square root, etc. At the moment, I'm trying to write the [Babylonian method](http://en.wikipedia.org/wiki/Babylonian_method#Babylonian_method) of computing square roots in C#.
So far, I have this:
```
public static double SquareRoot(double x) {
if (x == 0) return 0;
double r = x / 2; // this is inefficient, but I can't find a better way
// to get a close estimate for the starting value of r
double last = 0;
int maxIters = 100;
for (int i = 0; i < maxIters; i++) {
r = (r + x / r) / 2;
if (r == last)
break;
last = r;
}
return r;
}
```
It works just fine and produces the exact same answer as the .NET Framework's Math.Sqrt() method every time. As you can probably guess, though, it's slower than the native method (by around 800 ticks). I know this particular method will never be faster than the native method, but I'm just wondering if there are any optimizations I can make.
The only optimization I saw immediately was the fact that the calculation would run 100 times, even after the answer had already been determined (at which point, r would always be the same value). So, I added a quick check to see if the newly calculated value is the same as the previously calculated value and break out of the loop. Unfortunately, it didn't make much of a difference in speed, but just seemed like the right thing to do.
And before you say "Why not just use Math.Sqrt() instead?"... I'm doing this as a learning exercise and do not intend to actually use this method in any production code. | First, instead of checking for equality (r == last), you should be checking for convergence, wherein r is close to last, where close is defined by an arbitrary epsilon:
```
eps = 1e-10 // pick any small number
if (Math.Abs(r-last) < eps) break;
```
As the wikipedia article you linked to mentions - you don't efficiently calculate square roots with Newton's method - instead, you use logarithms. | ```
float InvSqrt (float x){
float xhalf = 0.5f*x;
int i = *(int*)&x;
i = 0x5f3759df - (i>>1);
x = *(float*)&i;
x = x*(1.5f - xhalf*x*x);
return x;}
```
This is my favorite fast square root. Actually it's the inverse of the square root, but you can invert it after if you want....I can't say if it's faster if you want the square root and not the inverse square root, but it's freaken cool just the same.
<http://www.beyond3d.com/content/articles/8/> | How can I improve this square root method? | [
"",
"c#",
"algorithm",
"optimization",
"math",
"performance",
""
] |
```
function t1()
{
echo 1;
}
function t2()
{
echo 2;
}
$funcs = array(t1,t2);
$length = count($funcs);
for($i=0;$i<$length;$i++)
{
$funcs[$i]();
}
```
when I execute this tiny php file:
PHP Notice: Use of undefined constant t1 - assumed 't1' in D:\jobirn\test\str.php on line 11
PHP Notice: Use of undefined constant t2 - assumed 't2' in D:\jobirn\test\str.php on line 11
How can I get rid of those Notices?
12 | You get a notice because PHP doesn't treat functions as first class objects.
When you do this
```
$functions = array(t1, t2);
```
The PHP engine sees t1, and t2, and tries to resolve it as a constant, but because it cannot find a constant named t1/t2, it "assumes" that you wanted to type array('t1', 't2');
If you do a var\_dump($functions), you can see that the items in the array are strings.
When you try to call a string as a function, like
```
$functions[0]()
```
PHP will look for a function with the same name as the string. I wouldn't call this as using a string as a function pointer, this is more like using reflection. PHP calls it "variable functions", see:
<http://hu2.php.net/manual/en/functions.variable-functions.php>
So, the correct way to get rid of the notices is:
```
$functions = array('t1', 't2');
```
About why does
```
't1'();
```
not work? Unfortunately there is no answer. It's PHP, there are a good number of these annoying as hell quirks. It's the same quirk as:
```
explode(':', 'one:two:three')[0];
Parse error: syntax error, unexpected '[' in php shell code on line 1
```
Edit:
The above mentioned array referencing syntax is available in PHP5.4, it's called array dereferencing. | ```
$funcs = array('t1','t2');
```
Unintuitive, but that's how it works | how to get rid of PHP notice here? | [
"",
"php",
"notice",
""
] |
I have found numerous examples on uploading a file to a web server via C++ on Windows.
However I am struggling after a *lot* of searching (and I thought I was good with Google!) to find any examples to help me achieve the same on a Mac.
Can anyone point me towards some help on how to upload a file to a web server on a Mac OS using either C++ or objective C?
It can be via either HTTP/HTTPS *or* FTP/FTPS (or both).
Thanks! | [connection Kit](http://opensource.utr-software.com/connection/) might be what your looking for | You could use 'libcurl', see [this article](http://en.wikipedia.org/wiki/CURL) on Wikipedia. | Uploading a file over HTTP/HTTPS and/or FTP/FTPS on a Mac | [
"",
"c++",
"objective-c",
"macos",
"file",
"upload",
""
] |
I want to give the user the ability to import a csv file into my php/mysql system, but ran into some problems with encoding when the language is russian which excel only can store in UTF-16 tab-coded tab files.
Right now my database is in latin1, but I will change that to utf-8 as described in question "a-script-to-change-all-tables-and-fields-to-the-utf-8-bin-collation-in-mysql"
But how should I import the file? and store the strings?
Should I for example translate it to html\_entitites?
I am using the `fgetcsv` command to get the data out of the csv file.
My code looks something like this right now.
```
file_put_contents($tmpfile, str_replace("\t", ";", file_get_contents($tmpfile)));
$filehandle = fopen($tmpfile,'r');
while (($data = fgetcsv($filehandle, 1000, ";")) !== FALSE) {
$values[] = array(
'id' => $data[0],
'type' => $data[1],
'text' => $data[4],
'desc' => $data[5],
'pdf' => $data[7]);
}
```
As note, if I store the xls file as csv in excel, i special chars are replaced by '\_', so the only way I can get the russian chars out of the file, is to store the file in excel as tabbed seperated file in UTF16 format. | Okay, the solution was to export the file from excel to UTF16 unicode text and add the ';' instaid of '\t' and convert from utf16 to utf8.
```` ```
file_put_contents($tmpfile, str_replace("\t", ";", iconv('UTF-16', 'UTF-8', file_get_contents($tmpfile))));
``` ````
The table in mysql has to be changed from latin1 to utf8
```
ALTER TABLE `translation`
CHANGE `text` `text` VARCHAR( 100 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
CHANGE `desc` `desc` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL
```
And then the file could be imported as before.
When I want to export the data from the database to a excel file, the csv-version is **not** an option. It has to be done in excel's html mode. Where data is corrected by eg. `urlencode()` or `htmlentities()`
Here some example code.
```
<?php
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="export.xls"');
print ('<html xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns="http://www.w3.org/TR/REC-html40">
<div id="Classeur1_16681" align=center x:publishsource="Excel">
<table x:str border=0 cellpadding=0 cellspacing=0 width=100% style="border-collapse: collapse">');
for($i = 0 ; $i < count($lines) ; $i++) {
print ('<tr><td>');
print implode("</td><td>",$lines[$i]);
print ('</td></tr>');
}
?>
</div>
</body>
</html>
``` | I would not import it using PHP. Instead consider creating a temporary table to store your data using [READ DATA INFILE](http://dev.mysql.com/doc/refman/5.1/en/load-data.html).
```
$file_handle = fopen($file_name, 'r');
$first_row = fgetcsv($file_handle, 0, ',', '"');
fclose($file_handle);
# Your usual error checking
if (!is_array($first_row)) {
...
}
$columns = 'column'.implode(' TEXT, column', array_keys($first_row)).' TEXT';
query("CREATE TABLE $table ($columns) Engine=MyISAM DEFAULT CHARSET=ucs2");
query("LOAD DATA LOCAL INFILE '$file_name' INTO TABLE $table ...
```
Then you can do whatever you want with the data in that table. | Howto import xls/csv file with unicode charset into php/mysql? | [
"",
"php",
"mysql",
"excel",
"unicode",
""
] |
I have a program that only allows one instance of itself to run. I use this code
```
bool createdNew = true;
using(Mutex mutex = new Mutex(true, "MobilePOSServer", out createdNew))
{
if(createdNew)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
else
{
Process current = Process.GetCurrentProcess();
foreach(Process proc in Process.GetProcessesByName(current.ProcessName))
{
if(proc.Id != current.Id)
{
SetForegroundWindow(proc.MainWindowHandle);
}
}
}
}
```
What I want to do is handle commandline arguments to call some start and stop methods on my MainForm winform. I can get the start just fine. But running the app from a new commandline window and trying to call a method is not working. I can get the window to come to the front. Is there a way I can get my form from the handle?
Or a better way to do this? | Is this what you're looking for:
[Single Instance Application, Passing Command Line Arguments](http://www.codeproject.com/KB/threads/SingletonApp.aspx) | You won't be able to get a reference to the form itself, no - that object exists in a different process.
If you want to be able to control the other process, it will need to expose some sort of "remote access" (where "remote" in this case means "out-of-process", not "on a different machine"). That could be via .NET remoting, WCF or your own simple protocol based on sockets, named pipes etc. However, it's likely to be a bit of a pain to do - so weigh up how much you *really* want this feature before you start putting too much work into it. | How to get a form from MainWindowHandle? | [
"",
"c#",
"winforms",
"command-line",
"process",
""
] |
I'd like to get at the variable name of class.
```
var Poop = new Class({
getClassName: function() {
return arguments.callee._owner.name;
}
});
var a = new Poop();
a.getClassName(); //want 'Poop'
```
I'm making that will be implemented into other classes, and I'd like to build a SQL query that uses the class name (pluralized) for the table.
I've tried various combinations of the above example to try to get the name, and can't figure it out (if it's even possible considering MooTools class system). | Found a solution. [Hash has a keyOf function](http://mootools.net/docs/core/Native/Hash#Hash:keyOf), which will give me the variable name that holds a value. So I made a Hash of window, and then asked for the key of the class constructor.
```
var Poop = new Class({
name: function() {
var w = $H(window);
return w.keyOf(this.constructor);
}
});
var a = new Poop();
a.name(); // returns 'Poop'
```
This of course works only because I create classes in the global window namespace (as is common with MooTools). If you made classes inside some namespace, then you'd just need to Hash that namespace instead.
Edit: [I wrote up](http://mcarthurgfx.com/blog/article/get-class-of-an-instance) about how to use this solution and how to make it work in namespaces automatically, for any MooToolers interested. | I ran into a problem with Extends, but found a way around it:
```
var getClassNameFromKeys = function (obj, instance) {
var i = 0, keys = Object.keys(obj);
for (i; i < keys.length; i++) {
if ('Ext' !== keys[i] && typeOf(obj[keys[i]]) === 'class' && instance instanceof obj[keys[i]]) {
return keys[i];
}
}
},
Ext = new Class(),
WhatsMyName = new Class({
Extends: Ext
}),
whatsMyNameInstance = new WhatsMyName(),
cName = getClassNameFromKeys(this, whatsMyNameInstance);
console.log(cName);
```
You can avoid the check on the extends name if you follow a pattern something like this:
```
var O = {},
whatsMyNameInstance;
(function () {
var SUBCLASS_KEYS;
O.Ext = new Class({
_className: null,
getClassName: function () {
var i = 0;
SUBCLASS_KEYS = SUBCLASS_KEYS || Object.keys(O.subclasses);
for (i; i < SUBCLASS_KEYS.length; i++) {
if (this instanceof O.subclasses[SUBCLASS_KEYS[i]]) {
return SUBCLASS_KEYS[i];
}
}
}
});
})();
O.subclasses = {};
O.subclasses.WhatsMyName = new Class({
Extends: O.Ext
});
whatsMyNameInstance = new O.subclasses.WhatsMyName();
whatsMyNameInstance.getClassName();
``` | How to get the name of a Mootools class from within | [
"",
"javascript",
"mootools",
""
] |
I have an interface that defines the ability to persist an entity to a data store. I'm having trouble thinking of a name for it. Any ideas?
```
public interface IInterfaceForDefiningADataPersistenceOperation<T>
{
void Store(T entity);
}
``` | `IRepository` ? | How about `IFooRepository`, where `Foo` is some base-entity or describes the product. If it truly is generic, then perhaps just `IRepository<T>` | What's the best name for this interface? | [
"",
"c#",
".net",
""
] |
Let's say that you have a project which is using a 3rd party library, such as [Google's Analytics Data API (gdata)](http://code.google.com/apis/gdata/), which does not appear to be currently deployed into any well-known or popular Maven public repositories/indexes. This isn't much of a problem, as I can just deploy the artifact into my local hosted Nexus repository.
But, are there any best practices in the Maven community for how I should name this library's "coordinates" in my POM, since a standard is not already set in public repositories for it?
For example, should I refer to it in my POM as
```
<dependency>
<groupId>com.google</groupId>
<artifactId>gdata-analytics</artifactId>
<version>1.0</version>
</dependency>
```
or is there some better / more standard way for me to come up with the `artifactId`?
(And, why the heck wouldn't a provider of a few dozen libraries such as Google take some effort to get them hosted into the mainstream public Maven repositories/indexes? Wouldn't this make it easier for people to use them and thus drive up adoption?) | What you've done is pretty reasonable. A few extra points:
* When Maven obtains an artifact from Nexus, the artifact is named as artifactId-version. GroupId is annoyingly omitted. So, when the artifact is moved around (say, copied into WEB-INF/lib in a web app), your jar file will read "**gdata-analytics-1.0**". That's usually not a problem. However, if the artifact name is very common, like "util", you may want to include group information inside the artifactId, such as using groupId of "**com.google**" and an artifactId of "**com.google.gdata-analytics**". Yes, the repitition is annoying, but it yields maximum clarity on the file system and in searches. I've actually had a problem where two different groupIds both had a "**core-1.0**" jar, and one overwrote the other when being copied into the lib directory at build time.
* I second MattK's suggestion of aligning your Maven versionId with whatever version the artifact is commonly known by.
* If you follow Dominic's advice of prefixing the groupId with your own company name (eg acme), it may make it easier to take advantage of Nexus' routing feature. It will ensure that requests for internal artifacts aren't propagated out to Maven Central and end up in their logs (which may be important if your groupId is "**acme.secret.project**"! | I've been using Maven for about a year and have never run across a "standard" naming convention. I usually do exactly what you're doing, although I try to make the version number as close to the "real" version number as possible, just to avoid confusion in case I deploy multiple versions. | Best practices for installing 3rd party libraries into your hosted Maven repository? | [
"",
"java",
"maven-2",
""
] |
I realize I'm going to get flamed for not simply writing a test myself... but I'm curious about people's opinions, not just the functionality, so... here goes...
I have a class that has a private list. I want to add to that private list through the public getMyList() method.
so... will this work?
```
public class ObA{
private List<String> foo;
public List<String> getFoo(){return foo;}
}
public class ObB{
public void dealWithObAFoo(ObA obA){
obA.getFoo().add("hello");
}
}
``` | Yes, that will absolutely work - which is usually a bad thing. (This is because you're really returning a *reference* to the collection object, not a copy of the collection itself.)
Very often you want to provide genuinely read-only access to a collection, which usually means returning a read-only wrapper around the collection. Making the return type a read-only interface implemented by the collection and returning the actual collection reference doesn't provide much protection: the caller can easily cast to the "real" collection type and then add without any problems. | Indeed, not a good idea. Do not publish your mutable members outside, make a copy if you cannot provide a read-only version on the fly...
```
public class ObA{
private List<String> foo;
public List<String> getFoo(){return Collections.unmodifiableList(foo);}
public void addString(String value) { foo.add(value); }
}
``` | can I add to a private list directly through the getter? | [
"",
"java",
""
] |
I know I can set a CultureInfo object with an specified culture in the Application\_BeginRequest event as is described [here](https://stackoverflow.com/questions/300841/how-do-you-globally-set-the-date-format-in-asp-net/300853#300853), but I don't want to do it for each request but in the application startup.
All I can imagine is that I can use the Application\_Start event, but I don't know how to set the global culture. | Set it in your web.config:
```
<globalization uiCulture="es" culture="es-MX" />
```
More info here: [<http://msdn.microsoft.com/en-us/library/bz9tc508.aspx>](http://msdn.microsoft.com/en-us/library/bz9tc508.aspx) | Thread.CurrentThread.CurrentUICulture
Keep in mind, this is overriding the settings that the WinForm app will have gotten from the computer. For example, if the user has a custom date format defined, this will replace that. | How to configure localization for an entire application? | [
"",
"c#",
"asp.net",
"localization",
""
] |
I have WPF application.
After testing my app on Windows7 and realized that opening help does not work.
Basically to open chm help file I call:
```
Process.Start("help.chm");
```
And nothing happens. I have also tried my app on Vista SP1, same result.
I'm admin in both OS'es
I have googled this problem, but have not found solution to it.
Is there way to solve this problem?
Have you experienced this types of incompatibilities.
Thank You! | have you tried ShellExecute ?
using System.Runtime.InteropServices;
[DllImport("shell32.dll", CharSet = CharSet.Auto)]
static extern bool ShellExecuteEx(ref SHELLEXECUTEINFO lpExecInfo);
```
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct SHELLEXECUTEINFO
{
public int cbSize;
public uint fMask;
public IntPtr hwnd;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpVerb;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpFile;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpParameters;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpDirectory;
public int nShow;
public IntPtr hInstApp;
public IntPtr lpIDList;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpClass;
public IntPtr hkeyClass;
public uint dwHotKey;
public IntPtr hIcon;
public IntPtr hProcess;
}
```
and you can try to start process with :
```
SHELLEXECUTEINFO info = new SHELLEXECUTEINFO();
info.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(info);
info.lpVerb = "open";
info.lpFile = "help.chm";
info.nShow = 5;
info.fMask = 12;
ShellExecuteEx(ref info);
```
(<http://www.pinvoke.net/default.aspx/shell32.ShellExecuteEx>) | This [SO thread](https://stackoverflow.com/questions/133379/elevating-process-privilege-programatically) should help you. Also, here's a [pretty detailed article](http://codefromthe70s.org/vistatutorial.aspx) on UAC and how to elevate. | .NET WPF Process.Start() not working on Vista and Windows 7 | [
"",
"c#",
".net",
"wpf",
"windows-7",
"windows-vista",
""
] |
I'm very much new to programming and have been doing fairly well so far. But progress bars still confuse me. The web unfortunately has to many differing examples for me to get anything out of them. Some say to use background worker some don't, etc. Below I have what I THINK should work but doesn't. Its just supposed to she a progress bar when copying file from one folder to another. Any help is appreciated.
Thanks.
```
private void btnCopyFiles_Click(object sender, EventArgs e)
{
string folder1 = @"c:\folder1\";
string folder2 = @"c:\folder2\";
DirectoryInfo di = new DirectoryInfo(folder1);
FileInfo[] filelist = di.GetFiles("*.*");
int count = di.GetFiles("*.*").Length;
this.progressBar1 = new System.Windows.Forms.ProgressBar();
progressBar1.Maximum = count;
progressBar1.Minimum = 0;
progressBar1.Step = 1;
foreach (FileInfo file in filelist)
{
try
{
this.Cursor = Cursors.WaitCursor;
File.Copy(folder1 + @"\" + file.Name, folder2 + @"\" + file.Name, true);
progressBar1.PerformStep();
this.Cursor = Cursors.Default;
}
catch (Exception error)
{
MessageBox.Show("Error: " + error);
}
}
}
``` | I'm assuming that you are using Visual Studio and have added the ProgressBar control by dragging it to the form. If this is correct, then following line, may be the problem:
```
this.progressBar1 = new System.Windows.Forms.ProgressBar();
```
By recreating the control, you are loosing its link to the form. Just remove or comment that line and try it again. | Overall the issue is that your code continues to execute not allowing the form to re-draw itself as it needs to. Your best, and fastest route is to use a BackgroundWorker to actually perform your operation, using its events to update the progress. Doing this, the update to the progress bar is done on the UI thread, and the UI updates, your file operations go on behind the scenes. | Progress Bar help | [
"",
"c#",
".net",
"winforms",
""
] |
I have heard that in C++, using an accessor ( `get...()` ) in a member function of the same class where the accessor was defined is good programming practice? Is it true and should it be done?
For example, is this preferred:
```
void display() {
cout << getData();
}
```
over something like this:
```
void display() {
cout << data;
}
```
`data` is a data member of the same class where the accessor was defined... same with the `display()` method.
I'm thinking of the overhead for doing that especially if you need to invoke the accessor lots of times inside the same class rather than just using the data member directly. | The reason for this is that if you change the implementation of `getData()`, you won't have to change the rest of the code that directly accesses `data`.
And also, a smart compiler will inline it anyways (it would always know the implementation inside the class), so there is no performance penalty. | It depends. Using an accessor function provides a layer of abstraction, which could make future changes to 'data' less painful. For example, if you wanted to lazily compute the value of 'data', you could hide that computation in the accessor function.
As for the overhead - If you are referring to performance overhead, it will likely be insignificant - your accessors will almost certainly be inlined. If you are referring to coding overhead, then yes, it is a tradeoff, and you'll have to decide whether it is worth the extra effort to provide accessors.
Personally, I don't think the accessors are worth it in most cases. | using accessors in same class | [
"",
"c++",
"accessor",
""
] |
I need to save some classes and data structures to a file. My first reflex was to use XML or Binary serialization but this is turning into a nightmare. I have a set of classes that were not meant to be serialize (private setters, no parameterless constructors, no Serialization attribute, dictionaries, etc.). Considering that I cannot change those classes, what should I do? Is there any workaround this and still use serialization?
Am I going to have to write all the code to write the properties, collections, etc? | Use the JavaScriptSerializer. It's in the System.Web.Script.Serialization namespace and is implemented in the 3.5 framework in the System.Web.Extensions.dll assembly.
With this class, you can serialize any POCO whether it's marked as [Serializable] or not. Your program does not have to be a web application to use JSON serialization. Here's an example:
```
public class Unserializable
{
public int Age { get; set; }
public int ID { get; set; }
public string Name { get; set; }
}
public class Program
{
static void Main()
{
var u = new Unserializable
{
Age = 40,
ID = 2,
Name = "Betty"
};
var jser = new JavaScriptSerializer();
var jsonText = jser.Serialize( u );
// next line outputs {"Age":40,"ID":2,"Name":"Betty"}
Console.WriteLine( jsonText );
}
}
``` | Sounds like a job for... serialization surrogates!
Go to <http://msdn.microsoft.com/en-us/magazine/cc188950.aspx>
for an overview. | How to serialize classes that were not designed to be serialized? | [
"",
"c#",
"xml-serialization",
""
] |
We are developing a Visual Studio.NET 2008 application with Oracle 9i as backend. Is it true that the usage of Stored procedures would be faster than Inline SQL ? This is a debate with my co-programmers.
We are using ODP.NET (Oracle Data Provider for .NET) from Oracle.
Thanks. | While I am tempted to answer "no" or "I don't think so", the only real way to know the answer to this question is to **go and measure it yourself**. Use a profiler like JetBrains dotTrace, and TOAD's own profiler, to find out.
All other answers are speculative. | It should be. When you send inline SQL to database, the engine must parse it and execute. Stored procedures are being parsed (and compiled) at creation time. So at least you are gaining parsing time. | Are Oracle stored procedures faster than in line SQL for a Microsoft.NET application? | [
"",
"sql",
"oracle",
"stored-procedures",
"odp.net",
""
] |
Trying to parse an HTML document and extract some elements (any links to text files).
The current strategy is to load an HTML document into a string. Then find all instances of links to text files. It could be any file type, but for this question, it's a text file.
The end goal is to have an `IEnumerable` list of string objects. That part is easy, but parsing the data is the question.
```
<html>
<head><title>Blah</title>
</head>
<body>
<br/>
<div>Here is your first text file: <a href="http://myServer.com/blah.txt"></div>
<span>Here is your second text file: <a href="http://myServer.com/blarg2.txt"></span>
<div>Here is your third text file: <a href="http://myServer.com/bat.txt"></div>
<div>Here is your fourth text file: <a href="http://myServer.com/somefile.txt"></div>
<div>Thanks for visiting!</div>
</body>
</html>
```
The initial approaches are:
* load the string into an XML document, and attack it in a Linq-To-Xml fashion.
* create a regex, to look for a string starting with `href=`, and ending with `.txt`
The question being:
* what would that regex look like? I am a regex newbie, and this is part of my regex learning.
* which method would you use to extract a list of tags?
* which would be the most performant way?
* which method would be the most readable/maintainable?
---
**Update:**
Kudos to [Matthew](https://stackoverflow.com/questions/907563/parsing-html-document-regular-expression-or-linq/907571#907571) on the HTML Agility Pack suggestion. It worked just fine! The XPath suggestion works as well. I wish I could mark both answers as 'The Answer', but I obviously cannot. They are both valid solutions to the problem.
Here's a C# console app using the regex suggested by [Jeff](https://stackoverflow.com/questions/907563/parsing-html-document-regular-expression-or-linq/907639#907639). It reads the string fine, and will not include any href that is not ended with .txt. With the given sample, it correctly does NOT include the `.txt.snarg` file in the results (as provided in the HTML string function).
```
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
namespace ParsePageLinks
{
class Program
{
static void Main(string[] args)
{
GetAllLinksFromStringByRegex();
}
static List<string> GetAllLinksFromStringByRegex()
{
string myHtmlString = BuildHtmlString();
string txtFileExp = "href=\"([^\\\"]*\\.txt)\"";
List<string> foundTextFiles = new List<string>();
MatchCollection textFileLinkMatches = Regex.Matches(myHtmlString, txtFileExp, RegexOptions.IgnoreCase);
foreach (Match m in textFileLinkMatches)
{
foundTextFiles.Add( m.Groups[1].ToString()); // this is your captured group
}
return files;
}
static string BuildHtmlString()
{
return new StringReader(@"<html><head><title>Blah</title></head><body><br/>
<div>Here is your first text file: <a href=""http://myServer.com/blah.txt""></div>
<span>Here is your second text file: <a href=""http://myServer.com/blarg2.txt""></span>
<div>Here is your third text file: <a href=""http://myServer.com/bat.txt.snarg""></div>
<div>Here is your fourth text file: <a href=""http://myServer.com/somefile.txt""></div>
<div>Thanks for visiting!</div></body></html>").ReadToEnd();
}
}
}
``` | I would recommend regex. Why?
* Flexible (case-insensitivity, easy to
add new file extensions, elements to
check, etc.)
* Fast to write
* Fast to run
Regex expressions will not be hard to read, as long as you can WRITE regexes.
using this as the regular expression:
> `href="([^"]*\.txt)"`
Explanation:
* It has parentheses around the
filename, which will result in a
"captured group" which you can access
after each match has been found.
* It has to escape the "." by using the
regex escape character, a backslash.
* It has to match any character EXCEPT
double-quotes: [^"] until it finds
the ".txt"
it translates into an escaped string like this:
```
string txtExp = "href=\"([^\\\"]*\\.txt)\"
```
Then you can iterate over your Matches:
```
Matches txtMatches = Regex.Matches(input, exp, RegexOptions.IgnoreCase);
foreach(Match m in txtMatches) {
string filename = m.Groups[1]; // this is your captured group
}
``` | Neither. Load it into an (X/HT)MLDocument and use XPath, which is a standard method of manipulating XML and very powerful. The functions to look at are [SelectNodes](http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.selectnodes.aspx) and [SelectSingleNode](http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.selectsinglenode.aspx).
Since you are apparently using HTML (not XHTML), you should use [HTML Agility Pack](http://www.codeplex.com/htmlagilitypack). Most of the methods and properties match the related XML classes.
Sample implementation using XPath:
```
HtmlDocument doc = new HtmlDocument();
doc.Load(new StringReader(@"<html>
<head><title>Blah</title>
</head>
<body>
<br/>
<div>Here is your first text file: <a href=""http://myServer.com/blah.txt""></div>
<span>Here is your second text file: <a href=""http://myServer.com/blarg2.txt""></span>
<div>Here is your third text file: <a href=""http://myServer.com/bat.txt""></div>
<div>Here is your fourth text file: <a href=""http://myServer.com/somefile.txt""></div>
<div>Thanks for visiting!</div>
</body>
</html>"));
HtmlNode root = doc.DocumentNode;
// 3 = ".txt".Length - 1. See http://stackoverflow.com/questions/402211/how-to-use-xpath-function-in-a-xpathexpression-instance-programatically
HtmlNodeCollection links = root.SelectNodes("//a[@href['.txt' = substring(., string-length(.)- 3)]]");
IList<string> fileStrings;
if(links != null)
{
fileStrings = new List<string>(links.Count);
foreach(HtmlNode link in links)
fileStrings.Add(link.GetAttributeValue("href", null));
}
else
fileStrings = new List<string>(0);
``` | Parsing HTML document: Regular expression or LINQ? | [
"",
"c#",
"regex",
"linq",
"parsing",
"linq-to-xml",
""
] |
In python, is there a way I can use instance variables as optional arguments in a class method? ie:
```
def function(self, arg1=val1, arg2=val2, arg3=self.instance_var):
# do stuff....
```
Any help would be appreciated. | Try this:
```
def foo(self, blah=None):
if blah is None: # faster than blah == None - thanks to kcwu
blah = self.instance_var
``` | All the responses suggesting `None` are correct; if you want to make sure a caller can pass None as a regular argument, use a special `sentinel` and test with `is`:
```
class Foo(object):
__default = object()
def foo(self, blah=Foo.__default):
if blah is Foo.__default: blah = self.instavar
```
Each call to `object()` makes a unique object, such that `is` will never succeed between it and any other value. The two underscores in `__default` mean "strongly private", meaning that callers know they shouldn't try to mess with it (and would need quite some work to do so, explicitly imitating the name mangling that the compiler is doing).
The reason you can't just use the code you posted, btw, is that default values evaluate when the `def` statement evaluates, not later at call time; and at the time `def` evaluates, there is as yet no `self` from which to take the instance variable. | python instance variables as optional arguments | [
"",
"python",
"function",
"class",
""
] |
I would like to assign a static list of items in a `SelectList()` to a `Html.DropDownList()` in ASP.NET MVC, what is the best practice?
I was about to try to find a way to use `new SelectList(new {key = "value"}...` but one, that didn't work, and two, would I be breaking a law here, should my static list be declared in `ViewData` anyway and passed as `IList/IENumerable`? | OK I decided to take my own advice, and this should be defined in the controller:
FYI, I just returned:
```
PageData data = new PageData()
{
Formats = new[]
{
new { ID = "string", Name = "Text" },
new { ID = "int", Name = "Numeric" },
new { ID = "decimal", Name = "Decimal" },
new { ID = "datetime", Name = "Date/Time" },
new { ID = "timespan", Name = "Stopwatch" }
},
.............
};
return View(data);
```
... (ignore context) and in the View ASPX side:
```
<%= Html.DropDownList("type.field", new SelectList(ViewData.Model.Formats, "ID", "Name"...
```
If anyone has a more optimal way of doing this I'll be happy to accept their answer. | It is a best practice not to create the SelectList in the view. You should create it in the controller and pass it using the ViewData.
Example:
```
var list = new SelectList(new []
{
new {ID="1",Name="name1"},
new{ID="2",Name="name2"},
new{ID="3",Name="name3"},
},
"ID","Name",1);
ViewData["list"]=list;
return View();
```
you pass to the constructor: the IEnumerable object, the value field the text field and the selected value.
in the View:
```
<%=Html.DropDownList("list",ViewData["list"] as SelectList) %>
``` | How to add static list of items in MVC Html.DropDownList() | [
"",
"c#",
".net",
"asp.net",
"asp.net-mvc",
"html-helper",
""
] |
### Duplicate:
> [SQL - how to store and navigate hierarchies](https://stackoverflow.com/questions/38801/sql-how-to-store-and-navigate-hierarchies)
---
If I have a database where the client requires categories, sub-categories, sub-sub-categories and so on, what's the best way to do that? If they only needed three, and always knew they'd need three I could just create three tables cat, subcat, subsubcat, or the like. But what if they want further depth? I don't like the three tables but it's the only way I know how to do it.
I have seen the "[sql adjacency list](http://www.sqlsummit.com/AdjacencyList.htm)" but didn't know if that was the only way possible. I was hoping for input so that the client can have any level of categories and subcategories. I believe this means hierarchical data.
EDIT: Was hoping for the sql to get the list back out if possible
Thank you. | ```
table categories: id, title, parent_category_id
id | title | parent_category_id
----+-------+-------------------
1 | food | NULL
2 | pizza | 1
3 | wines | NULL
4 | red | 3
5 | white | 3
6 | bread | 1
```
I usually do a `select *` and assemble the tree algorithmically in the application layer. | You might have a look at Joe Celko's book, or [this previous question](https://stackoverflow.com/questions/38801/sql-how-to-store-and-navigate-hierarchies). | What the best way to handle categories, sub-categories - hierachical data? | [
"",
"sql",
"tree",
"rdbms",
"hierarchical-data",
""
] |
I have VBScript code which launches QuickTest Professional, executes a series of QTP tests, and emails the results. This works well, but I would prefer to use a language with better tools support (a good IDE for example). I am currently calling .Net libraries from the launch script, so I was wondering if it was possible to use a language like C# to accomplish the same task. If so, are there any good resources which address this? I could find very little on this topic via Google and there do not seem to be any other questions on SO about this topic.
For clarity, I have included the code for the routine that does the bulk of the work. This does not include the .Net declarations, but `failedTestsList` and `allTestsList` are instances of `System.ArrayList`.
**EDIT**: All the QTP documentation examples use VBScript, but as you can see, the code is just creating the QTP objects. I would assume these would be callable from another language which supported creation of these objects. It just seems from my Google failures that no one is doing it.
```
Sub ExecuteQTPTest(name)
Dim App, resultsPath
Dim testPath, testResults
testPath = name
allTestsList.Add(name)
Set App = CreateObject("QuickTest.Application")
App.Launch
App.Visible = False
App.Open testPath
SetQTPTestOptions(App)
SetQTPRunOptions(App)
SetQTPWebOptions(App)
App.Folders.RemoveAll
Dim qtpTest, qtpResultsOpt
Set qtpTest = App.Test
Set qtpResultsOpt = CreateObject("QuickTest.RunResultsOptions")
resultsPath = testPath & "\RES1"
qtpResultsOpt.ResultsLocation = resultsPath
qtpTest.Run qtpResultsOpt ''// Run the test
testResults = "Test Status: " & qtpTest.LastRunResults.Status & vbCrLf & _
"Last Error: " & qtpTest.LastRunResults.LastError & vbCrLf & _
"Detailed Results located at " & qtpTest.LastRunResults.Path & _
" can be viewed with the QTP Results Viewer Tool " & vbCrLf
If qtpTest.LastRunResults.Status <> "Passed" Then
g_testRunPassed = False
failureCount = failureCount + 1
failedTestsList.Add(name)
LogResults testResults, name
End If
qtpTest.Close
Set qtpResultsOpt = Nothing
Set qtpTest = Nothing
App.Quit
Set App = Nothing
End Sub
``` | Apologies, but I don't have time to convert your full sample over to C#. I've thrown together a simple demo that should get you going. This just uses C# to open a QTP instance:
```
using System;
using QTObjectModelLib;
namespace QtpDemo
{
class QtpDriver
{
[STAThread]
static void Main(string[] args)
{
Application app = new Application();
app.Launch();
app.Visible = true;
}
}
}
```
You'll need to compile it linking to C:\Program Files\Mercury Interactive\QuickTest Professional\bin\QTObjectModelLib.dll (which is the .NET interop library for QTObjectModel.dll) and have that and QTObjectModel.dll in your app directory when you run it.
It shouldn't be that hard from here for you to convert any object declarations and function calls from VBScript to C#. Please ask if anything's unclear.
To your other point about samples on the internet - there are plenty of people out there doing more advanced stuff with QTP and QC, but I think any really clever solutions aren't shared. I, for example, would probably be prohibited from sharing such things by my employment contract, but I agree with you - there is a dearth of good QTP API samples out there, at least on Google. Having said that, I heartily recommend the [SQA Forums](http://www.sqaforums.com) for your QTP and QC needs.
Rich | YES, you can use anything that can "do" COM, and that includes C#.
Also VB.NET of course.
and Perl, Python, Javascript, and others.
With no help from google, you will have to follow your nose, on how to deal with the interface, but it's not that difficult when you have the existing example. Also your vendor, ideally, will have documented the COM interface for you. | Can I use a language other than VBScript to programmatically execute QTP Tests? | [
"",
"c#",
"vbscript",
"automation",
"qtp",
""
] |
I'm trying to display a panel to the user when an asynchronous call is made, but only if that happend from a specific call.
using the normal "get control" script I have mine like:
```
function pageLoad() {
try {
var manager = Sys.WebForms.PageRequestManager.getInstance();
manager.add_endRequest(OnEndRequest);
manager.add_beginRequest(OnBeginRequest);
}
catch (err) { }
}
function OnBeginRequest(sender, args) {
//alert('Start\n\n' + sender + '\n\n' + args);
var p = document.getElementById('ajaxLoadingPanel');
p.style.visibility = 'visible';
p.style.display = 'inline';
}
function OnEndRequest(sender, args) {
//alert('End\n\n' + sender + '\n\n' + args);
var p = document.getElementById('ajaxLoadingPanel');
p.style.visibility = 'hidden';
p.style.display = 'none';
}
```
but my question is **How do I know the methods of sender and args?**
I went [through the MSDN](http://msdn.microsoft.com/en-us/library/bb383809.aspx) and they talk nothing about the methods we can use, and there is no intellisence in VS2008 for this part...
any ideas? I want to get a list of methods and properties for both sender and args that I can use of this javascript API. | This documentation is helpful:
<http://msdn.microsoft.com/en-us/library/bb398976.aspx>
It has a table of all the events on PageRequestManager and what their event args are. Then the event args documents their properties, etc. The sender is always the PageRequestManager. | Debug in ScriptDebugger and find out the contents of sender and args
you can identify that which control has caused the postback | Assyncronous interaction using Sys WebForms PageRequestManager | [
"",
"asp.net",
"javascript",
"asynchronous",
"webforms",
"pagerequestmanager",
""
] |
I have a class that is mapped in fluent nhibernate but I want one of the classes properties to be ignored by the mapping.
With class and mapping below I get this error:
***The following types may not be used as proxies:
iMasterengine.Data.Model.Calendar: method get\_HasEvents should be virtual***
```
//my class
public class Calendar : IEntity {
public virtual int Id { get; private set; }
public virtual string Name { get; set; }
public virtual string SiteId { get; set; }
public virtual IList<CalendarEvent> Events { get; set; }
//ignore this property
public bool HasEvents { get { return Events.Count > 0; } }
}
//my mapping
public class CalendarMap : ClassMap<Calendar> {
public CalendarMap() {
Id(x => x.Id);
Map(x => x.Name);
Map(x => x.SiteId);
HasMany(x => x.Events).Inverse();
//what do I put here to tell nhibernate
//to ignore my HasEvents property?
}
}
``` | ```
map.IgnoreProperty(p => p.What);
``` | You can just make `HasEvents` *virtual* in the class:
```
public virtual bool HasEvents { get { return Events.Count > 0; } }
```
You don't need to add anything to the mappings.
You only need to tell fluent to ingore a property if you are using Auto Mapping, which I don't think you are. | How to tell Fluent NHibernate not to map a class property | [
"",
"c#",
"nhibernate",
"fluent-nhibernate",
""
] |
My hosting provider says my python script must be made to be executable(chmod755). What does this mean & how do I do it?
Cheers! | If you have ssh access to your web space, connect and issue
```
chmod 755 nameofyourscript.py
```
If you do not have ssh access but rather connect by FTP, check your FTP application to see whether it supports setting the permissions.
As to the meaning of 755:
* first digit is user settings (yourself)
* second digit is group settings
* third digit is the rest of the system
The digits are constructed by adding the permision values. 1 = executable, 2 = writable and 4 = readable. I.e. 755 means that you yourself can read, write and execute the file and everybody else can read and execute it. | Unix-like systems have "file modes" that say who can read/write/execute a file. The mode 755 means owner can read/write/execute, and everyone else can read/execute but not write. To make your Python script have this mode, you type
```
chmod 0755 script.py
```
You also need a shebang like
```
#!/usr/bin/python
```
on the very first line of the file to tell the operating system what kind of script it is. | Making a Python script executable chmod755? | [
"",
"python",
"hosting",
""
] |
In C++, I believe, a better way of dealing with reallocation is to use a STL vectors, as it guarantees the contiguous storage locations.
I have couple question to understand the difference:
1. Is there any scenario in which I need to prefer [realloc](http://en.cppreference.com/w/cpp/memory/c/realloc) over vector ?
2. Is there anything else ( apart from vector ) which is equivalent to [realloc](http://en.cppreference.com/w/cpp/memory/c/realloc) in C++? | It is only `vector`, which is guaranteed to have contiguous memory. Not the others.
`realloc` is a C memory management function. It's use is not encouraged in C++ code. Here's Stroustrup telling you why: [Why doesn't C++ have an equivalent to realloc()?](http://www.stroustrup.com/bs_faq2.html#renew)
> However, realloc() is only guaranteed to work on arrays allocated by malloc() (and similar functions) containing objects without user-defined copy constructors. Also, please remember that contrary to naive expectations, realloc() occasionally does copy its argument array. | The set of C functions (malloc, calloc, realloc, free) are raw memory operations. They will create/modify/release a given buffer in memory, but the memory will have no type and no constructors will be called.
C++ does not have an equivalent of *realloc*, but only typesafe equivalents to malloc/free through the use of *new/new[]* and *delete/delete[]*. The C++ versions will both acquire the memory from the system *and* initialize it by calling the appropriate constructors. Using *delete* will call the destructors of the objects and then release the memory. C and C++ versions are not compatible, if you acquire memory with *malloc* (even if you call the inplace constructor on the received memory) you cannot release it with *delete/delete[]* as it is undefined behavior.
Using *realloc* in C++ might be unsafe, as it will bitwise copy the objects from one memory area to the next. Sometimes your objects will not deal properly with memory moves (say that your object has both an attribute and a reference to it, after bitwise moving it the reference will be pointing to the old position rather than the real attribute). Inside *vector*, whenever the memory needs to grow, a new memory area is acquired with *new[]* and then all objects are copied to (or copy constructed in) the new positions using the appropriate C++ operations before deleting the old elements.
Whenever *vector* grows in size (reserved size, not used size) it will create a complete new memory area and *move* all the objects. On the other hand, realloc will only move the memory block to another position if there is not enough contiguous space after the pointer to just *grow* it. *Vectors* do not decrease size. Never. When you clear the elements, the reserved memory is still held.
Finally, there is a higher level of abstraction in *vector* than in realloc even for POD types (that are safe to be moved with C-like constructs). The equivalent to *vector* would be a structure that holds the pointer to the memory buffer, a used elements count and a reserved (buffer size) and the set of functions that deal with acquiring more memory as needed and updating the indexes with each operation. | Is STL vector a better version of realloc? | [
"",
"c++",
"stl",
"vector",
"realloc",
""
] |
Consider this scenario. I have an object, lets call it.... Foo. Foo raises a simple event named "Loaded". As part of the information for the event, consumers will need to know which foo object raised the event. Our team has adopted the following pattern.
1) Create a new class that inherits from EventArgs - for example,
FooEventArgs : System.EventArgs.
2) Add a property of type Foo to the FooEventArgs, which is set by being passed in via the constructor.
3) Declare the event using the generic version of EventHandler, so
```
public event EventHandler<FooEventArgs> Loaded;
```
4) Raise the event from the Foo class with the following signature:
```
Loaded(this, new FooEventArgs(this));
```
Essentially what this does is makes the "sender" the foo object, but it *also* puts the foo object reference into the event argument as a strongly typed property.
One advantage for doing this is that no one has to bother with casting "sender" when they handle the event, which lowers the coupling between the event consumer and the event raiser. Another "advantage" is that if the type of the event raiser ever has to change, and hence the strongly typed property (which hopefully never happens), then instead of simply having code start to fail on the cast when it comes out as null, the API actually breaks so it can be fixed at compile time.
To me, this pattern seems like it might be overkill. Should they be trusting the "sender" parameter more, and ditching the custom event arguments? My team argues that no one really uses the sender parameter. What's the best practice for passing out a reference to the event-raising object?
**EDIT: Great feedback so far, I'll leave this open for another day or so before I accept one.** | The common pattern is to use sender and not add the sender separately to the EventArgs. The custom EventArgs is used for other state like a tree node for a tree event, a (settable) boolean for a cancelable event etc.
We use the common pattern since it is used by the BCL classes also, and making a difference for "self-made events" is potentially confusing. Also, we have a global IoC publisher-subscriber pattern but this one only works with the normal EventHandler delegate signature, since the types are not known in advance. In this case, a cast (for instance to a custom EventArgs) is necessary anyways, so we might just as well cast the sender. | I don't think this is overkill. I agree with the advantages you state for having a separate FooEventArgs class. One other advantage to doing it that way is that if you need to add more information to the event in the future you can just add more properties to the FooEventArgs and you don't need to change the delegate. | C# simple Event Raising - using "sender" vs. custom EventArgs | [
"",
"c#",
"events",
""
] |
I googled,I checked wikipedia.None of them helped me to find an official java compiler by Sun.
By "official" I mean for example "C# Express" by Microsoft.I want that type of compiler by Sun.
My question is: Where do I get it?
I'm very sorry for my stupid question,I just get lost when I open java dot com.
Thanks in advance for your answers. | C# Express is an IDE (Integrated Development Environment), not just a compiler.
The JDK ships with `javac` which is the equivalent of `csc` - they're the compilers.
The nearest equivalent to C# Express is probably [Netbeans](http://www.netbeans.org/), although there are other IDEs available for Java, such as [Eclipse](http://eclipse.org) (free) and [IntelliJ IDEA](http://www.jetbrains.com/idea/) (not free). | Official java compiler is bin/javac that comes with Sun's JDK.
<http://java.sun.com/javase/downloads/index.jsp> (see Java SE Development Kit).
It contains the compiler in question. | Official Java compiler | [
"",
"java",
"compiler-construction",
""
] |
I'm new to Qt so please excuse my ignorance.
I am attempting to create a an 'svg image button' with QSizePolicy::Preferred for both horizontal and vertical.
That part works. When the window is resized, the button grows and shrinks exactly how I want... But the image within the button stays the same size.
I would like the image to scale with the button. I tried to overload resizeEvent, and call setImageSize, but that infinitely recurses.
```
#ifndef SVGPUSHBUTTON_H
#define SVGPUSHBUTTON_H
#include <QtGui>
class SVGPushButton : public QPushButton
{
public:
SVGPushButton(QString path, QString name = "");
~SVGPushButton();
void resizeEvent(QResizeEvent * event);
private:
};
#endif // SVGPUSHBUTTON_H
#include "SVGPushButton.h"
SVGPushButton::SVGPushButton(QString svgPath, QString name)
: QPushButton(name)
{
QIcon icon(svgPath);
setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Preferred );
setFlat(true);
setIcon(icon);
}
SVGPushButton::~SVGPushButton()
{}
void SVGPushButton::resizeEvent(QResizeEvent * event)
{
setIconSize( event->size() );
}
``` | This is how I eventually solved it:
```
SVGPushButton::SVGPushButton(QString svgPath, QString name)
: QPushButton()
{
setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Preferred );
QSvgWidget *icon = new QSvgWidget(svgPath,this);
setLayout( new QHBoxLayout(this) );
layout()->addWidget( icon );
}
``` | From looking over the docs, it looks like what you want to do is have a `QLabel` in the button. Then call `setPixmap()` on the label, and then set the property `scaledContents()` to `true`.
Now I'm not sure if just adding a label to the button will work, because the button has an icon and text property already.
I'll mark this as a community wiki so you can change it if you want.
Also, from my experience, messing with `resizeEvent()` is rarely a good idea :-) | Qt: creating an "svg image button" | [
"",
"c++",
"qt",
""
] |
I have been investigating transactions and it appears that they take care of themselves in EF as long as I pass `false` to `SaveChanges()` and then call `AcceptAllChanges()` if there are no errors:
```
SaveChanges(false);
// ...
AcceptAllChanges();
```
What if something goes bad? don't I have to rollback or, as soon as my method goes out of scope, is the transaction ended?
What happens to any indentiy columns that were assigned half way through the transaction? I presume if somebody else added a record after mine before mine went bad then this means there will be a missing Identity value.
Is there any reason to use the standard `TransactionScope` class in my code? | With the Entity Framework most of the time `SaveChanges()` is sufficient. This creates a transaction, or enlists in any ambient transaction, and does all the necessary work in that transaction.
Sometimes though the `SaveChanges(false) + AcceptAllChanges()` pairing is useful.
The most useful place for this is in situations where you want to do a distributed transaction across two different Contexts.
I.e. something like this (bad):
```
using (TransactionScope scope = new TransactionScope())
{
//Do something with context1
//Do something with context2
//Save and discard changes
context1.SaveChanges();
//Save and discard changes
context2.SaveChanges();
//if we get here things are looking good.
scope.Complete();
}
```
If `context1.SaveChanges()` succeeds but `context2.SaveChanges()` fails the whole distributed transaction is aborted. But unfortunately the Entity Framework has already discarded the changes on `context1`, so you can't replay or effectively log the failure.
But if you change your code to look like this:
```
using (TransactionScope scope = new TransactionScope())
{
//Do something with context1
//Do something with context2
//Save Changes but don't discard yet
context1.SaveChanges(false);
//Save Changes but don't discard yet
context2.SaveChanges(false);
//if we get here things are looking good.
scope.Complete();
context1.AcceptAllChanges();
context2.AcceptAllChanges();
}
```
While the call to `SaveChanges(false)` sends the necessary commands to the database, the context itself is not changed, so you can do it again if necessary, or you can interrogate the `ObjectStateManager` if you want.
This means if the transaction actually throws an exception you can compensate, by either re-trying or logging state of each contexts `ObjectStateManager` somewhere.
See [my](https://twitter.com/adjames) [blog post](https://learn.microsoft.com/en-gb/archive/blogs/alexj/savechangesfalse) for more. | If you are using EF6 (Entity Framework 6+), this has changed for database calls to SQL.
See: <https://learn.microsoft.com/en-us/ef/ef6/saving/transactions>
Use `context.Database.BeginTransaction`.
## From MSDN:
> ```
> using (var context = new BloggingContext())
> {
> using (var dbContextTransaction = context.Database.BeginTransaction())
> {
> try
> {
> context.Database.ExecuteSqlCommand(
> @"UPDATE Blogs SET Rating = 5" +
> " WHERE Name LIKE '%Entity Framework%'"
> );
>
> var query = context.Posts.Where(p => p.Blog.Rating >= 5);
> foreach (var post in query)
> {
> post.Title += "[Cool Blog]";
> }
>
> context.SaveChanges();
>
> dbContextTransaction.Commit();
> }
> catch (Exception)
> {
> dbContextTransaction.Rollback(); //Required according to MSDN article
> throw; //Not in MSDN article, but recommended so the exception still bubbles up
> }
> }
> }
> ``` | Using Transactions or SaveChanges(false) and AcceptAllChanges()? | [
"",
"c#",
"entity-framework",
"transactions",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.